Skip to content

Commit 0dbcaaa

Browse files
committed
Set TEMP/TMP env vars before importing pgsrip
Back to Python API - set TEMP/TMP environment variables to video directory before importing pgsrip. This forces tempfile module to use video directory for temp folders. Restore env vars after. Avoids sys.executable issue where PyInstaller exe would launch another FastFlix window when trying to run pgsrip as subprocess.
1 parent 6539e4c commit 0dbcaaa

File tree

1 file changed

+84
-55
lines changed

1 file changed

+84
-55
lines changed

fastflix/widgets/background_tasks.py

Lines changed: 84 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def _convert_sup_to_srt(self, sup_filepath: str) -> bool:
232232
video_path = Path(self.main.input_video)
233233
video_dir = str(video_path.parent)
234234

235-
# Set environment variables for pgsrip CLI to find tesseract and mkvextract
235+
# Set environment variables for pgsrip to find tesseract and mkvextract
236236
if self.app.fastflix.config.tesseract_path:
237237
tesseract_dir = str(Path(self.app.fastflix.config.tesseract_path).parent)
238238
os.environ["PATH"] = f"{tesseract_dir}{os.pathsep}{os.environ.get('PATH', '')}"
@@ -242,62 +242,91 @@ def _convert_sup_to_srt(self, sup_filepath: str) -> bool:
242242
mkvtoolnix_dir = str(Path(self.app.fastflix.config.mkvmerge_path).parent)
243243
os.environ["PATH"] = f"{mkvtoolnix_dir}{os.pathsep}{os.environ.get('PATH', '')}"
244244

245-
# Use pgsrip CLI instead of Python API to avoid PyInstaller temp folder issues
246-
# Build pgsrip command
247-
import sys
248-
import subprocess
245+
# CRITICAL FIX: Set TEMP/TMP to video directory before importing pgsrip
246+
# This forces Python's tempfile module to use the video directory
247+
original_temp = os.environ.get("TEMP")
248+
original_tmp = os.environ.get("TMP")
249+
os.environ["TEMP"] = video_dir
250+
os.environ["TMP"] = video_dir
249251

250-
# Get list of existing .srt files before conversion
251-
existing_srts = set(video_path.parent.glob("*.srt"))
252-
253-
# Call pgsrip as subprocess
254-
pgsrip_cmd = [
255-
sys.executable,
256-
"-m",
257-
"pgsrip",
258-
"--languages",
259-
self.language,
260-
"--overwrite",
261-
str(video_path),
262-
]
263-
264-
self.main.thread_logging_signal.emit(f"DEBUG:Running: {' '.join(pgsrip_cmd)}")
265-
266-
result = subprocess.run(pgsrip_cmd, capture_output=True, text=True, cwd=video_dir, env=os.environ.copy())
267-
268-
if result.returncode != 0:
269-
raise Exception(f"pgsrip CLI failed: {result.stderr or result.stdout}")
270-
271-
# Find newly created .srt files
272-
current_srts = set(video_path.parent.glob("*.srt"))
273-
new_srts = current_srts - existing_srts
274-
275-
if not new_srts:
276-
raise Exception(f"pgsrip completed but no .srt file found in {video_path.parent}")
277-
278-
# Get the first new .srt file
279-
srt_files = list(new_srts)
280-
281-
# Move the .srt file to the expected location (same dir as .sup was)
282-
created_srt = srt_files[0]
283-
expected_srt = sup_path.with_suffix(".srt")
284-
285-
if created_srt != expected_srt:
286-
# Move/rename to expected location
287-
import shutil
288-
289-
shutil.move(str(created_srt), str(expected_srt))
290-
291-
self.main.thread_logging_signal.emit(f"INFO:{t('OCR conversion successful')}: {expected_srt.name}")
292-
293-
# Optionally delete the .sup file since we have .srt now
294252
try:
295-
sup_path.unlink()
296-
self.main.thread_logging_signal.emit(f"INFO:{t('Removed .sup file, kept .srt')}")
297-
except Exception:
298-
pass
299-
300-
return True
253+
# Import pgsrip AFTER setting TEMP/TMP
254+
from pgsrip import pgsrip, Mkv, Options
255+
from babelfish import Language as BabelLanguage
256+
257+
media = Mkv(str(video_path))
258+
259+
# Configure options for pgsrip
260+
try:
261+
# Detect if language code is 2-letter or 3-letter
262+
if len(self.language) == 2:
263+
babel_lang = BabelLanguage.fromalpha2(self.language)
264+
elif len(self.language) == 3:
265+
babel_lang = BabelLanguage(self.language)
266+
else:
267+
babel_lang = BabelLanguage.fromname(self.language)
268+
269+
options = Options(
270+
languages={babel_lang},
271+
overwrite=True,
272+
one_per_lang=True,
273+
)
274+
except Exception:
275+
# Fallback to English if language code is invalid
276+
options = Options(
277+
languages={BabelLanguage("eng")},
278+
overwrite=True,
279+
one_per_lang=True,
280+
)
281+
282+
# Get list of existing .srt files before conversion
283+
existing_srts = set(video_path.parent.glob("*.srt"))
284+
285+
# Run pgsrip conversion using Python API
286+
pgsrip.rip(media, options)
287+
288+
# Find newly created .srt files
289+
current_srts = set(video_path.parent.glob("*.srt"))
290+
new_srts = current_srts - existing_srts
291+
292+
if not new_srts:
293+
raise Exception(f"pgsrip completed but no .srt file found in {video_path.parent}")
294+
295+
# Get the first new .srt file
296+
srt_files = list(new_srts)
297+
298+
# Move the .srt file to the expected location (same dir as .sup was)
299+
created_srt = srt_files[0]
300+
expected_srt = sup_path.with_suffix(".srt")
301+
302+
if created_srt != expected_srt:
303+
# Move/rename to expected location
304+
import shutil
305+
306+
shutil.move(str(created_srt), str(expected_srt))
307+
308+
self.main.thread_logging_signal.emit(f"INFO:{t('OCR conversion successful')}: {expected_srt.name}")
309+
310+
# Optionally delete the .sup file since we have .srt now
311+
try:
312+
sup_path.unlink()
313+
self.main.thread_logging_signal.emit(f"INFO:{t('Removed .sup file, kept .srt')}")
314+
except Exception:
315+
pass
316+
317+
return True
318+
319+
finally:
320+
# Restore original TEMP/TMP
321+
if original_temp is not None:
322+
os.environ["TEMP"] = original_temp
323+
elif "TEMP" in os.environ:
324+
del os.environ["TEMP"]
325+
326+
if original_tmp is not None:
327+
os.environ["TMP"] = original_tmp
328+
elif "TMP" in os.environ:
329+
del os.environ["TMP"]
301330

302331
except Exception as err:
303332
self.main.thread_logging_signal.emit(f"ERROR:{t('OCR conversion failed')}: {err}")

0 commit comments

Comments
 (0)