feat(patches): vendor reclip transcript+history patch (base 1d161d1)

Full patched app.py/index.html plus rebaseable diff. Deployed via
bind-mounts from the share (documents/reclip/); this repo is the
versioned source of truth so container/image updates and new machines
cannot lose the patch. Rebase instructions in patches/reclip/README.md.
This commit is contained in:
Lap Tran committed 2026-10-25 16:02:44 -04:00
1 parent b4dfbd7540
commit b8773b8fc2
4 files changed
+1543

No files matched your search

+362
View File
@@ -0,0 +1,362 @@
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 <file>) live beside the
media as <stem>.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 <video stem>.txt beside the download.
Returns the .txt path, or None when the video has no captions. Never
raises — a transcript is a bonus, not a download requirement."""
stem = os.path.splitext(chosen_path)[0]
try:
cmd = ["yt-dlp", "--no-playlist", "--skip-download", "--no-warnings",
"--write-subs", "--write-auto-subs",
"--sub-langs", "en,en-orig",
"--sub-format", "vtt",
"-o", stem + ".%(ext)s", url]
subprocess.run(cmd, capture_output=True, text=True, timeout=180)
vtts = glob.glob(stem + ".*.vtt")
if not vtts:
return None
vtts.sort(key=lambda p: (0 if p.endswith(".en.vtt") else 1, p))
lines, prev = [], None
with open(vtts[0], encoding="utf-8", errors="replace") as fh:
for raw in fh:
line = raw.strip()
if (not line or "-->" in line
or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
or re.match(r"^\d+$", line)):
continue
line = re.sub(r"<[^>]+>", "", line)
if line and line != prev:
lines.append(line)
prev = line
txt = stem + ".txt"
with open(txt, "w", encoding="utf-8") as out:
out.write(" ".join(lines) + "\n")
for f in vtts:
try:
os.remove(f)
except OSError:
pass
return txt if lines else None
except Exception:
return None
def run_download(job_id, url, format_choice, format_id):
job = jobs[job_id]
out_template = os.path.join(DOWNLOAD_DIR, f"{job_id}.%(ext)s")
cmd = ["yt-dlp", "--no-playlist", "-o", out_template]
if format_choice == "audio":
cmd += ["-x", "--audio-format", "mp3"]
elif format_id:
cmd += ["-f", f"{format_id}+bestaudio/best", "--merge-output-format", "mp4"]
else:
cmd += ["-f", "bestvideo+bestaudio/best", "--merge-output-format", "mp4"]
cmd.append(url)
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
job["status"] = "error"
job["error"] = result.stderr.strip().split("\n")[-1]
return
files = glob.glob(os.path.join(DOWNLOAD_DIR, f"{job_id}.*"))
if not files:
job["status"] = "error"
job["error"] = "Download completed but no file was found"
return
if format_choice == "audio":
target = [f for f in files if f.endswith(".mp3")]
chosen = target[0] if target else files[0]
else:
target = [f for f in files if f.endswith(".mp4")]
chosen = target[0] if target else files[0]
for f in files:
if f != chosen:
try:
os.remove(f)
except OSError:
pass
job["status"] = "done"
job["file"] = chosen
ext = os.path.splitext(chosen)[1]
title = job.get("title", "").strip()
# Sanitize title for filename
if title:
safe_title = "".join(c for c in title if c not in r'\/:*?"<>|').strip()[:100].strip()
job["filename"] = f"{safe_title}{ext}" if safe_title else os.path.basename(chosen)
else:
job["filename"] = os.path.basename(chosen)
# Best-effort transcript sidecar: yt-dlp captions (X auto-captions
# included) -> plain .txt next to the chosen file. Never fails the job.
job["transcript"] = fetch_transcript(url, chosen)
job["transcript_name"] = os.path.splitext(job["filename"])[0] + ".txt"
record_history(job)
except subprocess.TimeoutExpired:
job["status"] = "error"
job["error"] = "Download timed out (5 min limit)"
except Exception as e:
job["status"] = "error"
job["error"] = str(e)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/info", methods=["POST"])
def get_info():
data = request.json
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
cmd = ["yt-dlp", "--no-playlist", "-j", url]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
info = parse_ytdlp_json(result.stdout)
# Build quality options — keep best format per resolution
best_by_height = {}
for f in info.get("formats", []):
height = f.get("height")
if height and f.get("vcodec", "none") != "none":
tbr = f.get("tbr") or 0
if height not in best_by_height or tbr > (best_by_height[height].get("tbr") or 0):
best_by_height[height] = f
formats = []
for height, f in best_by_height.items():
formats.append({
"id": f["format_id"],
"label": f"{height}p",
"height": height,
})
formats.sort(key=lambda x: x["height"], reverse=True)
return jsonify({
"title": info.get("title", ""),
"thumbnail": info.get("thumbnail", ""),
"duration": info.get("duration"),
"uploader": info.get("uploader", ""),
"formats": formats,
})
except subprocess.TimeoutExpired:
return jsonify({"error": "Timed out fetching video info"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/api/playlist", methods=["POST"])
def get_playlist_info():
data = request.json
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
cmd = ["yt-dlp", "--flat-playlist", "-J", url]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return jsonify({"error": result.stderr.strip().split("\n")[-1]}), 400
info = json.loads(result.stdout)
entries = info.get("entries", [])
urls = [entry.get("url") for entry in entries if entry.get("url")]
return jsonify({"urls": urls})
except subprocess.TimeoutExpired:
return jsonify({"error": "Timed out fetching playlist info"}), 400
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/api/download", methods=["POST"])
def start_download():
data = request.json
url = data.get("url", "").strip()
format_choice = data.get("format", "video")
format_id = data.get("format_id")
title = data.get("title", "")
if not url:
return jsonify({"error": "No URL provided"}), 400
job_id = uuid.uuid4().hex[:10]
jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title}
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
thread.daemon = True
thread.start()
return jsonify({"job_id": job_id})
def resolve_download(job_id, key):
"""Find a completed job in memory, falling back to the on-disk history
(paths point into DOWNLOAD_DIR, so they survive restarts)."""
job = jobs.get(job_id)
if job and job.get("status") == "done" and job.get(key):
return job
for entry in load_history():
if entry.get("job_id") == job_id and entry.get(key):
return entry
return None
@app.route("/api/status/<job_id>")
def check_status(job_id):
job = jobs.get(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
return jsonify({
"status": job["status"],
"error": job.get("error"),
"filename": job.get("filename"),
"transcript": bool(job.get("transcript")),
})
@app.route("/api/history")
def get_history():
rows = load_history()[:50]
for r in rows:
# Truth at read time: a recorded caption-transcript may have been
# deleted, and a manual yt-transcribe sidecar may have appeared since.
path = r.get("transcript") or sidecar_transcript(r.get("file"))
if path and os.path.exists(path):
r["transcript"] = path
r["has_transcript"] = True
if not r.get("transcript_name"):
r["transcript_name"] = os.path.splitext(os.path.basename(path))[0] + ".txt"
else:
r["transcript"] = ""
r["has_transcript"] = False
return jsonify(rows)
@app.route("/api/transcript/<job_id>")
def download_transcript(job_id):
rec = resolve_download(job_id, "file") or resolve_download(job_id, "transcript")
path = (rec.get("transcript") if rec else None) \
or (sidecar_transcript(rec.get("file")) if rec else None)
if not rec or not path or not os.path.exists(path):
return jsonify({"error": "Transcript not found"}), 404
default_name = os.path.splitext(os.path.basename(path))[0] + ".txt"
return send_file(path, as_attachment=True,
download_name=rec.get("transcript_name") or default_name)
@app.route("/api/file/<job_id>")
def download_file(job_id):
rec = resolve_download(job_id, "file")
path = rec.get("file") if rec else None
if not rec or not path or not os.path.exists(path):
return jsonify({"error": "File not found"}), 404
return send_file(path, as_attachment=True,
download_name=rec.get("filename") or os.path.basename(path))
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8899))
host = os.environ.get("HOST", "127.0.0.1")
app.run(host=host, port=port)