import os import uuid import glob import json import re import subprocess import threading import time from flask import Flask, request, jsonify, send_file, render_template app = Flask(__name__) DOWNLOAD_DIR = os.path.join(os.path.dirname(__file__), "downloads") os.makedirs(DOWNLOAD_DIR, exist_ok=True) jobs = {} HISTORY_FILE = os.path.join(DOWNLOAD_DIR, "history.json") _history_lock = threading.Lock() def load_history(): try: with open(HISTORY_FILE, encoding="utf-8") as fh: data = json.load(fh) return data if isinstance(data, list) else [] except Exception: return [] def save_history(history): try: tmp = HISTORY_FILE + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(history, fh, indent=2) os.replace(tmp, HISTORY_FILE) except OSError: pass def sidecar_transcript(file_path): """Manual-fallback transcripts (yt-transcribe ) live beside the media as .txt — recognize them at read time so history stays truthful without re-downloading anything.""" if not file_path: return None stem = os.path.splitext(file_path)[0] + ".txt" return stem if os.path.exists(stem) else None def record_history(job): """Persist the completed job so history + file/transcript downloads survive process restarts (downloads dir is the mapped volume).""" with _history_lock: history = [h for h in load_history() if h.get("job_id") != job.get("job_id")] history.insert(0, { "job_id": job.get("job_id"), "url": job.get("url", ""), "title": job.get("title", ""), "filename": job.get("filename", ""), "file": job.get("file", ""), "transcript": job.get("transcript") or "", "transcript_name": job.get("transcript_name", ""), "has_transcript": bool(job.get("transcript")), "size": os.path.getsize(job["file"]) if job.get("file") and os.path.exists(job["file"]) else 0, "date": time.strftime("%Y-%m-%d %H:%M:%S"), }) save_history(history[:200]) def parse_ytdlp_json(stdout): """Parse yt-dlp JSON output. With ``-j`` yt-dlp prints one JSON object per line. Some extractors emit multiple videos even with ``--no-playlist``, so stdout contains several objects and a plain ``json.loads`` raises "Extra data". Return the first valid object. """ for line in stdout.splitlines(): line = line.strip() if not line: continue return json.loads(line) raise ValueError("yt-dlp returned no data") def fetch_transcript(url, chosen_path): """Best-effort transcript via yt-dlp captions (manual or auto-generated; includes X's auto-captions). Writes