main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import warnings
  3. import tempfile
  4. from .utils.files import filename, write_srt
  5. from .utils.ffmpeg import get_audio, overlay_subtitles
  6. from .utils.whisper import WhisperAI
  7. def process(args: dict):
  8. model_name: str = args.pop("model")
  9. output_dir: str = args.pop("output_dir")
  10. output_srt: bool = args.pop("output_srt")
  11. srt_only: bool = args.pop("srt_only")
  12. language: str = args.pop("language")
  13. sample_interval: str = args.pop("sample_interval")
  14. os.makedirs(output_dir, exist_ok=True)
  15. if model_name.endswith(".en"):
  16. warnings.warn(
  17. f"{model_name} is an English-only model, forcing English detection.")
  18. args["language"] = "en"
  19. # if translate task used and language argument is set, then use it
  20. elif language != "auto":
  21. args["language"] = language
  22. audios = get_audio(args.pop("video"), args.pop('audio_channel'), sample_interval)
  23. subtitles = get_subtitles(
  24. audios, output_srt or srt_only, output_dir, model_name, args
  25. )
  26. if srt_only:
  27. return
  28. overlay_subtitles(subtitles, output_dir, sample_interval)
  29. def get_subtitles(audio_paths: list, output_srt: bool, output_dir: str, model_name: str, model_args: dict):
  30. model = WhisperAI(model_name, model_args)
  31. subtitles_path = {}
  32. for path, audio_path in audio_paths.items():
  33. print(
  34. f"Generating subtitles for {filename(path)}... This might take a while."
  35. )
  36. srt_path = output_dir if output_srt else tempfile.gettempdir()
  37. srt_path = os.path.join(srt_path, f"{filename(path)}.srt")
  38. segments = model.transcribe(audio_path)
  39. with open(srt_path, "w", encoding="utf-8") as srt:
  40. write_srt(segments, file=srt)
  41. subtitles_path[path] = srt_path
  42. return subtitles_path