Skip to content

Commit

Permalink
adds gui that is executed with no args
Browse files Browse the repository at this point in the history
  • Loading branch information
zackees committed May 10, 2023
1 parent 6fd67e2 commit 1298c9b
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 6 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies = [
"srtranslator",
"gTTS",
"playaudio",
"PyQt6==6.3.1"
]

dynamic = ["version"]
Expand Down
18 changes: 13 additions & 5 deletions src/video_subtitles/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import argparse
import os
import sys
import warnings

from video_subtitles import __version__
Expand Down Expand Up @@ -104,17 +105,24 @@ def validate_api_key() -> str:

def main() -> int:
"""Main entry point for the template_python_cmd package."""
print(f"videosubtitles version: {__version__}")
cuda_cards = ensure_dependencies()
print("Found the following Nvidia/CUDA video cards:")
for card in cuda_cards:
print(f" [{card.idx}]: {card.name}, {card.memory_gb} GB")
if len(sys.argv) == 1:
from video_subtitles.gui import ( # pylint: disable=import-outside-toplevel
run_gui,
)

run_gui()
return 0
try:
args = parse_args()
file = args.file
if not os.path.exists(file):
print(f"Error - file does not exist: {file}")
return 1
print(f"videosubtitles version: {__version__}")
cuda_cards = ensure_dependencies()
print("Found the following Nvidia/CUDA video cards:")
for card in cuda_cards:
print(f" [{card.idx}]: {card.name}, {card.memory_gb} GB")
api_key: None | str = None
if args.api_key:
api_key = args.api_key
Expand Down
94 changes: 94 additions & 0 deletions src/video_subtitles/gui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""
Gui for the video_subtitles package
"""

# pylint: disable=no-name-in-module,c-extension-no-member,invalid-name

import os
import platform
import subprocess
import sys
from threading import Thread

from PyQt6 import QtCore # type: ignore
from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow # type: ignore

from video_subtitles.run import run
from video_subtitles.say import say


def open_folder(path):
"""Opens a folder in the OS."""
if platform.system() == "Windows":
os.startfile(path)
elif platform.system() == "Darwin":
subprocess.Popen(["open", path]) # pylint: disable=consider-using-with
else:
subprocess.Popen(["xdg-open", path]) # pylint: disable=consider-using-with


class MainWidget(QMainWindow):
"""Main widget."""

def __init__(self, on_drop_callback):
super().__init__()
self.setWindowTitle("Video Subtitle Generator")
self.resize(720, 480)
self.setAcceptDrops(True)
# Add a label to the window on top of everythign elese
self.label = QLabel(self)
# Adjust label so it is centered
self.label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
self.label.setText(" Drag and Drop Video File Here")
self.label.adjustSize()
self.on_drop_callback = on_drop_callback

def dragEnterEvent(self, event):
"""Drag and drop handler."""
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()

def dropEvent(self, event):
"""Drag and drop handler."""
files = [u.toLocalFile() for u in event.mimeData().urls()]
for f in files:
self.on_drop_callback(f)


def run_gui() -> None:
"""Runs the gui."""
app = QApplication(sys.argv)

def callback(videofile):
# path, _ = os.path.splitext(videofile)
# os.makedirs(path, exist_ok=True)
# open_folder(path)

# Open folder in the OS
def _generate_subtitles(videofile):
# perform the actual work here
os.chdir(os.path.dirname(videofile))
videofile = os.path.basename(videofile)
try:
out = run(
file=videofile,
deepl_api_key=None,
out_languages=["en", "zh", "it", "es", "fr"],
model="large",
)
except Exception as e: # pylint: disable=broad-except
print(e)
say("Error: " + str(e))
return
open_folder(out)
print("Generating subtitles for", videofile)
voicename = os.path.basename(videofile).split(".")[0].replace("_", " ")
say(f"Attention: {voicename} has completed subtitle generation")

Thread(target=_generate_subtitles, args=(videofile,), daemon=True).start()

gui = MainWidget(callback)
gui.show()
sys.exit(app.exec())
5 changes: 4 additions & 1 deletion src/video_subtitles/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,16 @@ def run( # pylint: disable=too-many-locals,too-many-branches,too-many-statement
deepl_api_key: str | None,
out_languages: list[str],
model: str,
) -> None:
) -> str:
"""Run the program."""
print("Running transcription")
out_languages = out_languages.copy()
print(f"Output languages: {out_languages}")
print(f"Model: {model}")
print(f"File: {file}")
print("Done running transcription")
if deepl_api_key == "free":
deepl_api_key = None
device = "cuda" if not IS_GITHUB else "cpu"
out_en_dir = transcribe(url_or_file=file, device=device, model=model, language="en")
print(f"Output directory: {out_en_dir}")
Expand Down Expand Up @@ -84,3 +86,4 @@ def run( # pylint: disable=too-many-locals,too-many-branches,too-many-statement
shutil.move(srt_file, out_file)
shutil.rmtree(os.path.dirname(srt_file))
print("Done translating")
return outdir

0 comments on commit 1298c9b

Please sign in to comment.