utils.py 1.3 KB

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