def cmd_search(args): repo = get_repo_or_exit() keyword, pagenum, pagelen = args.keyword, args.pagenum, args.pagelen respage = repo.search_subtitle(keyword, pagenum, pagelen) if not respage: msg = 'Nothong Found.' print_and_log(msg) return msg = 'page {}/{}, result {} - {} of total {}.' \ .format(respage.pagenum, respage.pagecount, respage.offset + 1, respage.offset + respage.pagelen, respage.total) print_and_log(msg) for item in respage: subtitle_object_id = item['object_id'] start, end, content = item['start'], item['end'], item['content'] movie = get_movie_by_subtitle_object_id(repo.db.connect(), subtitle_object_id) print_and_log('{} {}-->{} {}'.format(content.replace('\n', ' '), start, end, movie.name)) clip_cmd = 'CMD: enchant clip --start {} --end {} --video_object_id {}'\ .format(start, end, movie.video_object_id) print_and_log(clip_cmd) print_and_log('') if args.auto_clip_all: print_and_log('automatically make clips for search result:') for item in respage: movie = get_movie_by_subtitle_object_id(repo.db.connect(), item['object_id']) start = srt.srt_timestamp_to_timedelta(item['start']) end = srt.srt_timestamp_to_timedelta(item['end']) repo.clip_video_and_subtitle(movie.video_object_id, start, end, timedelta(seconds=args.pre_reserved_secs), timedelta(seconds=args.post_reserved_secs))
def start_element(self, name, attrs): if name == 'p': subLine = {'start': srt.srt_timestamp_to_timedelta(dict(attrs)['begin'].replace('.', ',')), 'end': srt.srt_timestamp_to_timedelta(dict(attrs)['end'].replace('.', ',')), 'content': ''} self._subs.append(subLine) self._subIdx += 1
def set_args(): examples = { "Paste subtitles from :05 - :08 at :10": "srt paste -i example.srt --t1 00:00:5,00 --t2 00:00:8,00 -p 00:00:10,00", "Paste subtitles from :05 - :08 at :10 with :01 space beforehand": "srt paste -i example.srt --t1 00:00:5,00 --t2 00:00:8,00 -p 00:00:10,00 -s 00:00:01,00", "Paste subtitles from :05 - :08 at :10 and adjust all subsequent subtitles": "srt paste -i example.srt --t1 00:00:5,00 --t2 00:00:8,00 -p 00:00:10,00 -b", } parser = _cli.basic_parser(description=__doc__, examples=examples) parser.add_argument( "--t1", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to start copying from.", ) parser.add_argument( "--t2", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to stop copying at.", ) parser.add_argument( "--paste", "-p", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to paste at.", ) parser.add_argument( "--space", "-s", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), help="The amount of space to place before copied subtitles.", ) parser.add_argument( "--block", "-b", action="store_true", help= "Paste copied subtitles as a block and adjust subsequent subtitles' timestamps.", ) parser.add_argument( "--zero", "-z", action="store_true", help="Start the copied subtitle block from 00:00.", ) return parser.parse_args()
def po_to_srt_converter(src_fp, dest_fp): po = polib.pofile(src_fp.read().decode("utf-8-sig")) for unit in po: translated_content = unit.msgstr or unit.msgid lines = translated_content.split(NEW_LINE_TAG) content = "\n".join(lines) index, timecodes = unit.comment.split("\n", maxsplit=1) start, end = timecodes.split(" --> ") start = srt.srt_timestamp_to_timedelta(start) end = srt.srt_timestamp_to_timedelta(end) cue = srt.Subtitle(index=index, start=start, end=end, content=content) dest_fp.write(cue.to_srt().encode("utf-8"))
def _srt_timestamp_to_milliseconds(parser, arg): try: delta = srt.srt_timestamp_to_timedelta(arg) except ValueError: parser.error("not a valid SRT timestamp: %s" % arg) else: return _timedelta_to_milliseconds(delta)
def write_srt_file(transcriptions, id): v_transcriptions = [] for trans in transcriptions: index = trans['index'] start = srt.srt_timestamp_to_timedelta(trans['start']) end = srt.srt_timestamp_to_timedelta(trans['end']) content = trans['content'] v_transcriptions.append(srt.Subtitle(index, start, end, content)) new_filename = f'subtitles_{id}.srt' subtitles = srt.compose(v_transcriptions) with open(f'data/subtitles/{new_filename}', "w") as f: f.write(subtitles) f.close() return new_filename
def break_sentences(args, subs, alternative): firstword = True charcount = 0 idx = len(subs) + 1 content = "" for w in alternative.words: if firstword: # first word in sentence, record start time start_hhmmss = time.strftime('%H:%M:%S', time.gmtime(w.start_time.seconds)) print("start_hhmmss: " + start_hhmmss) start_ms = int(w.start_time.nanos / 1000000) #print("start_ms: " + start_ms) start = start_hhmmss + "," + str(start_ms) print("start: " + start) charcount += len(w.word) content += " " + w.word.strip() if ("." in w.word or "!" in w.word or "?" in w.word or charcount > args.max_chars or ("," in w.word and not firstword)): # break sentence at: . ! ? or line length exceeded # also break if , and not first word end_hhmmss = time.strftime('%H:%M:%S', time.gmtime(w.end_time.seconds)) print("end_hhmmss: " + end_hhmmss) end_ms = int(w.end_time.nanos / 1000000) end = end_hhmmss + "," + str(end_ms) subs.append( srt.Subtitle(index=idx, start=srt.srt_timestamp_to_timedelta(start), end=srt.srt_timestamp_to_timedelta(end), content=srt.make_legal_content(content))) firstword = True idx += 1 content = "" charcount = 0 else: firstword = False return subs
def set_args(): examples = { "Find subtitles from :05 - :08": "srt find -i example.srt -s 00:00:5,00 -e 00:00:8,00", "Find subtitles from :00 - :05 and :08 onwards": "srt find -i example.srt -s 00:00:8,00 -e 00:00:5,00", "Find subtitles from :00 - :16 and adjust the timestamps of found subtitles": "srt find -i example.srt -e 00:00:16,00", "Find subtitles from :16 onwards and zero the block.": "srt find -i example.srt -s 00:00:16,00 -a", "Find every subtitle": "srt find -i example.srt", } parser = _cli.basic_parser(description=__doc__, examples=examples) parser.add_argument( "--start", "-s", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to start removing from.", ) parser.add_argument( "--end", "-e", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to stop removing at.", ) parser.add_argument( "--adjust", "-a", action="store_true", help= "Adjust the timestamps of subtitles by placing the first found subtitle at 00:00.", ) return parser.parse_args()
def edit_file(filename, edit_data, id): with open(f'data/subtitles/{filename}', 'w') as f: transcriptions = [] return_data = [] for sub in edit_data: new_sub = srt.Subtitle( sub['index'], srt.srt_timestamp_to_timedelta(sub['start']), srt.srt_timestamp_to_timedelta(sub['end']), sub['content']) transcriptions.append(new_sub) return_data.append({ 'index': sub['index'], 'start': sub['start'], 'end': sub['end'], 'content': sub['content'] }) new_subtitles = srt.compose(transcriptions) f.write(new_subtitles) f.close() return get_json_response(return_data, id)
def set_args(): examples = { "Add a subtitle": 'srt add -i example.srt -s 00:00:5,00 -e 00:00:5,00 -c "srt3 is awesome."', "Add a subtitle and adjust subsequent ones": 'srt add -i example.srt -s 00:00:5,00 -e 00:00:5,00 --c "srt3 is awesome." -a', } parser = _cli.basic_parser(description=__doc__, examples=examples) parser.add_argument( "--start", "-s", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to start the subtitle at.", ) parser.add_argument( "--end", "-e", metavar=("TIMESTAMP"), type=lambda arg: srt.srt_timestamp_to_timedelta(arg), default=datetime.timedelta(0), nargs="?", help="The timestamp to stop the subtitle at.", ) parser.add_argument("-c", "--content", required=True, help="The content of the subtitle.") parser.add_argument( "--adjust", "-a", action="store_true", help="Adjust the timestamps of subsequent subtitles.", ) return parser.parse_args()
def convert(file_path): file_name = os.path.basename(file_path) file_dir = os.path.dirname(file_path) if not '.vtt' in file_name: return file_path = file_dir + '/' + file_name content = [] i = 1 for caption in webvtt.read(file_path): content.append(srt.Subtitle(index=i, start=srt.srt_timestamp_to_timedelta(caption.start), end=srt.srt_timestamp_to_timedelta(caption.end), content=caption.text, proprietary='')) i+=1 file_create(file_path.replace(".vtt", ".srt"), srt.compose(content))
def test_bad_timestamp_format_raises(ts): ts = srt.timedelta_to_srt_timestamp(ts) ts = ts.replace(":", "t", 1) with pytest.raises(srt.TimestampParseError): srt.srt_timestamp_to_timedelta(ts)
def test_equal_timestamps_despite_different_fields_parsed_as_equal(timestamps): ts1, ts2 = timestamps assert srt.srt_timestamp_to_timedelta( ts1) == srt.srt_timestamp_to_timedelta(ts2)
def test_srt_timestamp_to_timedelta_too_short_raises(ts): srt_ts = srt.timedelta_to_srt_timestamp(ts)[:-1] with assert_raises(ValueError): srt.srt_timestamp_to_timedelta(srt_ts)