diff --git a/app.py b/app.py index 2b5eaa5..1dfbbd0 100644 --- a/app.py +++ b/app.py @@ -2,8 +2,11 @@ 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__) @@ -12,6 +15,97 @@ 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. @@ -29,6 +123,53 @@ def parse_ytdlp_json(stdout): 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