import os import uuid import glob import json import re import hashlib 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", ""), "thumbnail": job.get("thumbnail", ""), "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]) MEDIA_EXTS = (".mp4", ".mkv", ".webm", ".m4a", ".mp3", ".flac", ".mov", ".avi", ".wav", ".ts") def backfill_history(): """Add on-disk downloads that predate history.json (or were dropped into the downloads dir manually) so the whole library shows up on the page. The transcript flag is resolved live at read time, so backfilled entries pick up manual yt-transcribe sidecars automatically.""" for name in sorted(os.listdir(DOWNLOAD_DIR)): path = os.path.join(DOWNLOAD_DIR, name) if not os.path.isfile(path) or not name.lower().endswith(MEDIA_EXTS): continue with _history_lock: history = load_history() if any(h.get("file") == path for h in history): continue stem = os.path.splitext(name)[0] # a 10-hex stem is a reclip job id — the real title wasn't kept title = "" if re.fullmatch(r"[0-9a-f]{10}", stem) else stem history.insert(0, { "job_id": hashlib.sha1(path.encode()).hexdigest()[:10], "url": "", "title": title, "filename": name, "file": path, "transcript": "", "transcript_name": "", "has_transcript": False, "size": os.path.getsize(path), "date": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(path))), }) save_history(history[:200]) backfill_history() 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