utils.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. from typing import Iterator, TextIO
  3. def str2bool(string):
  4. str2val = {"True": True, "False": False}
  5. if string in str2val:
  6. return str2val[string]
  7. else:
  8. raise ValueError(
  9. f"Expected one of {set(str2val.keys())}, got {string}")
  10. def format_timestamp(seconds: float, always_include_hours: bool = False):
  11. assert seconds >= 0, "non-negative timestamp expected"
  12. milliseconds = round(seconds * 1000.0)
  13. hours = milliseconds // 3_600_000
  14. milliseconds -= hours * 3_600_000
  15. minutes = milliseconds // 60_000
  16. milliseconds -= minutes * 60_000
  17. seconds = milliseconds // 1_000
  18. milliseconds -= seconds * 1_000
  19. hours_marker = f"{hours}:" if always_include_hours or hours > 0 else ""
  20. return f"{hours_marker}{minutes:02d}:{seconds:02d}.{milliseconds:03d}"
  21. def write_srt(transcript: Iterator[dict], file: TextIO):
  22. for i, segment in enumerate(transcript, start=1):
  23. print(
  24. f"{i}\n"
  25. f"{format_timestamp(segment['start'], always_include_hours=True)} --> "
  26. f"{format_timestamp(segment['end'], always_include_hours=True)}\n"
  27. f"{segment['text'].strip().replace('-->', '->')}\n",
  28. file=file,
  29. flush=True,
  30. )
  31. def filename(path):
  32. return os.path.splitext(os.path.basename(path))[0]