Given an input audio/video file, generate subtitles in the specified language and format.
519704
def generate_subtitles( # pylint: disable=too-many-locals,too-many-arguments
        source_path,
        output=None,
        concurrency=DEFAULT_CONCURRENCY,
        src_language=DEFAULT_SRC_LANGUAGE,
        dst_language=DEFAULT_DST_LANGUAGE,
        subtitle_file_format=DEFAULT_SUBTITLE_FORMAT,
        api_key=None,
    ):
    
    audio_filename, audio_rate = extract_audio(source_path)

    regions = find_speech_regions(audio_filename)

    pool = multiprocessing.Pool(concurrency)
    converter = FLACConverter(source_path=audio_filename)
    recognizer = SpeechRecognizer(language=src_language, rate=audio_rate,
                                  api_key=GOOGLE_SPEECH_API_KEY)

    transcripts = []
    if regions:
        try:
            widgets = ["Converting speech regions to FLAC files: ", Percentage(), ' ', Bar(), ' ',
                       ETA()]
            pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()
            extracted_regions = []
            for i, extracted_region in enumerate(pool.imap(converter, regions)):
                extracted_regions.append(extracted_region)
                pbar.update(i)
            pbar.finish()

            widgets = ["Performing speech recognition: ", Percentage(), ' ', Bar(), ' ', ETA()]
            pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()

            for i, transcript in enumerate(pool.imap(recognizer, extracted_regions)):
                transcripts.append(transcript)
                pbar.update(i)
            pbar.finish()

            if src_language.split("-")[0] != dst_language.split("-")[0]:
                if api_key:
                    google_translate_api_key = api_key
                    translator = Translator(dst_language, google_translate_api_key,
                                            dst=dst_language,
                                            src=src_language)
                    prompt = "Translating from {0} to {1}: ".format(src_language, dst_language)
                    widgets = [prompt, Percentage(), ' ', Bar(), ' ', ETA()]
                    pbar = ProgressBar(widgets=widgets, maxval=len(regions)).start()
                    translated_transcripts = []
                    for i, transcript in enumerate(pool.imap(translator, transcripts)):
                        translated_transcripts.append(transcript)
                        pbar.update(i)
                    pbar.finish()
                    transcripts = translated_transcripts
                else:
                    print(
                        "Error: Subtitle translation requires specified Google Translate API key. "
                        "See --help for further information."
                    )
                    return 1

        except KeyboardInterrupt:
            pbar.finish()
            pool.terminate()
            pool.join()
            print("Cancelling transcription")
            raise

    timed_subtitles = [(r, t) for r, t in zip(regions, transcripts) if t]
    formatter = FORMATTERS.get(subtitle_file_format)
    formatted_subtitles = formatter(timed_subtitles)

    dest = output

    if not dest:
        base = os.path.splitext(source_path)[0]
        dest = "{base}.{format}".format(base=base, format=subtitle_file_format)

    with open(dest, 'wb') as output_file:
        output_file.write(formatted_subtitles.encode("utf-8"))

    os.remove(audio_filename)

    return dest
887148
def play(self, filename, translate=False):  # pragma: no cover
        '''
        
        '''
        # FIXME: Use platform-independent and async audio-output here
        # PyAudio looks most promising, too bad about:
        #  --allow-external PyAudio --allow-unverified PyAudio
        if translate:
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                fname = f.name
            with audioread.audio_open(filename) as f:
                with contextlib.closing(wave.open(fname, 'w')) as of:
                    of.setnchannels(f.channels)
                    of.setframerate(f.samplerate)
                    of.setsampwidth(2)
                    for buf in f:
                        of.writeframes(buf)
            filename = fname

        if winsound:
            winsound.PlaySound(str(filename), winsound.SND_FILENAME)
        else:
            cmd = ['aplay', str(filename)]
            self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd]))
            subprocess.call(cmd)

        if translate:
            os.remove(fname)
258646
def main(input_filename, format):
    

    # open the file & convert to wav
    song_data = AudioSegment.from_file(input_filename, format=format)
    song_data = song_data.set_channels(1)  # convert to mono
    wav_tmp = song_data.export(format="wav")  # write to a tmp file buffer
    wav_tmp.seek(0)
    rate, wav_data = wavfile.read(wav_tmp)

    rows_per_second = (1 + (rate - WIDTH)) // FRAME_STRIDE

    # Calculate a coarser window for matching
    window_size = (rows_per_second // TIME_STRIDE, (WIDTH // 2) // FREQ_STRIDE)
    peaks = resound.get_peaks(np.array(wav_data), window_size=window_size)

    # half width (nyquist freq) & half size (window is +/- around the middle)
    f_width = WIDTH // (2 * FREQ_STRIDE) * 2
    t_gap = 1 * rows_per_second
    t_width = 2 * rows_per_second
    fingerprints = resound.hashes(peaks, f_width=f_width, t_gap=t_gap, t_width=t_width)  # hash, offset pairs

    return fingerprints
399387
def _create_html_file_content(translations):
    
    content = []
    for i1, t in enumerate(translations):
        if i1 > 0:
            content.append("<br>")
        content.append('<div class="translation">')
        content.append('<div class="word">')
        for w in t.word:
            content.append("<h2>{word}</h2>".format(word=w))
        content.append("</div>")  # end `word`
        for i2, t2 in enumerate(t.parts_of_speech):
            if i2 > 0:
                content.append("<br>")
            content.append('<div class="part-of-speech">')
            if t2.part is not None:
                content.append('<p class="part-name">[{part}]</p>'.format(part=t2.part))
            content.append("<ol>")
            for m in t2.meanings:
                content.append('<div class="meaning">')
                mng = ["<strong><li>"]
                for i3, mn in enumerate(m.meaning):
                    if i3 > 0:
                        mng.append(", ")
                    mng.append("<span>{meaning}</span>".format(meaning=mn))
                mng.append("</li></strong>")
                content.append("".join(mng))
                content.append('<div class="examples">')
                for e in m.examples:
                    exmpl = "<p><span>{ex}</span>".format(ex=e[0])
                    if e[1]:
                        exmpl += "<br><span>{tr}</span>".format(tr=e[1])
                    exmpl += "</p>"
                    content.append(exmpl)
                content.append("</div>")  # end `examples`
                content.append("</div>")  # end `meaning`
            content.append("</ol>")
            content.append("</div>")  # end `part-of-speech`
        content.append("</div>")  # end `translation`
    return "\n".join(content)
440399
def main():
    """"""
    options = docopt(__doc__, version=__version__)
    if options['segment']:
        segment(
            options['<file>'],
            options['--output'],
            options['--target-duration'],
            options['--mpegts'],
        )
1344648
def _gen_subname(videofile, language, ext):
        
        root, basename = os.path.split(videofile)
        name, _ = os.path.splitext(basename)
        subname = '{basename}.{language}.{ext}'.format(
            basename=name,
            language=language,
            ext=ext)
        return subname
1214404
def generate_prepare_subparser(subparsers):
    """"""
    parser = subparsers.add_parser(
        'prepare', description=constants.PREPARE_DESCRIPTION,
        epilog=constants.PREPARE_EPILOG, formatter_class=ParagraphFormatter,
        help=constants.PREPARE_HELP)
    parser.set_defaults(func=prepare_xml)
    utils.add_common_arguments(parser)
    parser.add_argument('-s', '--source', dest='source',
                        choices=constants.TEI_SOURCE_CHOICES,
                        default=constants.TEI_SOURCE_CBETA_GITHUB,
                        help=constants.PREPARE_SOURCE_HELP,
                        metavar='SOURCE')
    parser.add_argument('input', help=constants.PREPARE_INPUT_HELP,
                        metavar='INPUT')
    parser.add_argument('output', help=constants.PREPARE_OUTPUT_HELP,
                        metavar='OUTPUT')
570701
def parse(args):
    """"""

    import argparse

    parser = argparse.ArgumentParser(
        add_help=False,
        description="Remove spam and advertising from subtitle files.",
        usage="%(prog)s [OPTION]... TARGET...")
    parser.add_argument(
        "-a", "--aeidon",
        action="store_true",
        dest="aeidon",
        help="use python3-aeidon to process subtitles")
    parser.add_argument(
        "-f", "--file",
        action="append",
        dest="pattern_files",
        help="obtain matches from FILE")
    parser.add_argument(
        "--fix",
        action="store_true",
        dest="fix",
        help="repair potentially damaged subtitle files with aeidon")
    parser.add_argument(
        "-g", "--gui",
        action="store_true",
        dest="gui",
        help="indicate use from a GUI")
    parser.add_argument(
        "-h", "--help",
        action="help",
        help=argparse.SUPPRESS)
    parser.add_argument(
        "-r", "--regex",
        action="store_true",
        dest="regex",
        help="perform regex matching")
    parser.add_argument(
        "-s", "--case-sensitive",
        action="store_true",
        default=False,
        dest="case_sensitive",
        help="match case-sensitively")
    parser.add_argument(
        "-y", "--yes",
        action="store_true",
        dest="autoyes",
        help="automatic yes to prompts")
    parser.add_argument(
        "--version",
        action="version",
        version='%(prog)s ' + __version__)
    parser.add_argument(
        dest="targets",
        help=argparse.SUPPRESS,
        nargs="*")

    options = parser.parse_args(args)
    arguments = options.targets

    return options, arguments
189323
def __parseFormat(self, fmt, content, fps = 25):
        ''''''

        headerFound = False
        subSection = ''
        for lineNo, line in enumerate(content):
            line = self._initialLinePrepare(line, lineNo)
            if not fmt.WITH_HEADER and not self._formatFound and lineNo > self._maxFmtSearch:
                return

            subSection = ''.join([subSection, line])
            if fmt.WITH_HEADER and not headerFound:
                if lineNo > self._maxHeaderLen:
                    return
                headerFound = fmt.addHeaderInfo(subSection, self._subtitles.header())
                if headerFound:
                    self._formatFound = True
                    subSection = ''
            elif fmt.subtitleEnds(line) or (lineNo + 1) == len(content):
                subtitle = fmt.createSubtitle(fps, subSection)
                if subtitle is None:
                    if subSection in ('\n', '\r\n', '\r'):
                        subSection = ''
                        continue
                    elif self._subtitles.size() > 0:
                        raise SubParsingError(_("Parsing error"), lineNo)
                    else:
                        return

                # store parsing result if new end marker occurred, then clear results
                if subtitle.start and subtitle.text:
                    self._formatFound = True
                    try:
                        self._subtitles.append(subtitle)
                    except SubException as msg:
                        raise SubParsingError(msg, lineNo)
                elif subtitle.start and not subtitle.text:
                    pass
                else:
                    return
                subSection = ''
1130353
def get_subtitle_files(inputfile):
    """"""
    srts = []

    for f in inputfile:
        filename = f.split('.')
        filename[-1] = 'srt'
        srt = '.'.join(filename)
        if os.path.isfile(srt):
            srts.append(srt)

    if len(srts) == 0:
        print("[!] No subtitle files were found.")
        return False

    return srts
297511
protected function generateTranslation()
    {
        $name = $this->qualifyClass($this->getNameInput());
        $path = $this->getTranslationPath($name);

        $this->makeDirectory($path);
        $this->files->put($path, $this->buildTranslation($name));

        $this->info('Translation also generated successfully.');
        $this->warn($path);
    }
229723
def _frame_generator(self, frame_duration_ms, audio, sample_rate):
        
        n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
        offset = 0
        timestamp = 0.0
        duration = (float(n) / sample_rate) / 2.0
        while offset + n < len(audio):
            yield self.Frame(audio[offset:offset + n], timestamp, duration)
            timestamp += duration
            offset += n
24383
def title_translations(self, key, value):
    """"""
    return {
        'language': langdetect.detect(value.get('a')),
        'source': value.get('9'),
        'subtitle': value.get('b'),
        'title': value.get('a'),
    }
1293071
def createSubtitle(self, fps, section):
        """"""
        matched = self._pattern.search(section)
        if matched is not None:
            matchedDict = matched.groupdict()
            return Subtitle(
                self.frametime(fps, matchedDict.get("time_from")),
                self.frametime(fps, matchedDict.get("time_to")),
                self.formatSub(matchedDict.get("text"))
            )
        return None
302644
def _read_subtitles(self, lines):
        
        self.log(u"Parsing fragments from subtitles text format")
        id_format = self._get_id_format()
        lines = [line.strip() for line in lines]
        pairs = []
        i = 1
        current = 0
        while current < len(lines):
            line_text = lines[current]
            if len(line_text) > 0:
                fragment_lines = [line_text]
                following = current + 1
                while (following < len(lines)) and (len(lines[following]) > 0):
                    fragment_lines.append(lines[following])
                    following += 1
                identifier = id_format % i
                pairs.append((identifier, fragment_lines))
                current = following
                i += 1
            current += 1
        self._create_text_fragments(pairs)
383722
def cc(filename: 'input source file',
       output:
       'output file name. default to be replacing input file\'s suffix with ".py"' = None,
       name: 'name of language' = 'unname'):
    

    lang = Language(name)

    with Path(filename).open('r') as fr:
        build_language(fr.read(), lang, filename)

    if not output:
        base, _ = os.path.splitext(filename)

        output = base + '.py'
    lang.dump(output)
581844
def fill_subparser(subparser):
    
    subparser.add_argument(
        '--youtube-id', type=str, required=True,
        help=("The YouTube ID of the video from which to extract audio, "
              "usually an 11-character string.")
    )
    return download