Files
dotfiles/patches/reclip/reclip-transcript.patch
Lap Tran 10f5811d7f feat(patches): reclip history cards match UI design; thumbnails persisted
History section now renders reclip's own card components (thumbnail,
serif title, meta line with date/size, Save/Transcript pill buttons).
Frontend passes the video thumbnail to /api/download so history cards
show real artwork; pre-thumbnail entries keep the placeholder icon.
2026-10-25 20:41:31 -04:00

390 lines
15 KiB
Diff

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 <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", ""),
+ "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 <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")
@@ -81,6 +222,12 @@ def run_download(job_id, url, format_choice, format_id):
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)"
@@ -175,7 +322,8 @@ def start_download():
return jsonify({"error": "No URL provided"}), 400
job_id = uuid.uuid4().hex[:10]
- jobs[job_id] = {"status": "downloading", "url": url, "title": title}
+ jobs[job_id] = {"job_id": job_id, "status": "downloading", "url": url, "title": title,
+ "thumbnail": (data.get("thumbnail") or "")[:500]}
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
thread.daemon = True
@@ -184,6 +332,18 @@ def start_download():
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)
@@ -193,15 +353,48 @@ def check_status(job_id):
"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):
- job = jobs.get(job_id)
- if not job or job["status"] != "done":
- return jsonify({"error": "File not ready"}), 404
- return send_file(job["file"], as_attachment=True, download_name=job["filename"])
+ 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__":
diff --git a/templates/index.html b/templates/index.html
index 1f566d1..4807aa1 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -343,6 +343,18 @@
.dl-all-btn:hover { background: #2d2d2a; }
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
+ /* History — same card language as the fetch results */
+ .hist-h {
+ font-family: 'Instrument Serif', serif;
+ font-size: 1.9rem;
+ font-weight: 400;
+ letter-spacing: -0.02em;
+ margin: 44px 0 14px;
+ color: var(--fg);
+ }
+ #history .card { animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1); }
+ a.card-dl-btn { text-decoration: none; display: inline-block; }
+
.spin {
display: inline-block;
width: 10px; height: 10px;
@@ -399,6 +411,7 @@
</div>
<div id="cards" class="cards"></div>
+ <div id="history"></div>
<div class="footer">
YouTube &middot; TikTok &middot; Instagram &middot; Twitter/X &middot; Reddit &middot; Facebook<br>
@@ -586,8 +599,9 @@
} else if (c.status === 'downloading') {
actionHtml = `<span class="card-status downloading"><span class="spin"></span> Downloading...</span>`;
} else if (c.status === 'done') {
- actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>
- <span class="card-status done">${esc(c.filename || '')}</span>`;
+ actionHtml = `<button class="card-dl-btn done" onclick="saveCard(${idx})">Save</button>` +
+ (c.hasTranscript ? `<button class="card-dl-btn" onclick="saveTranscript(${idx})">Transcript</button>` : '') +
+ `<span class="card-status done">${esc(c.filename || '')}</span>`;
} else if (c.status === 'error') {
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Retry</button>
<span class="card-status error">${esc(friendlyError(c.error || 'Download failed'))}</span>`;
@@ -634,6 +648,7 @@
format: currentFormat,
format_id: c.selectedFormatId,
title: c.title || '',
+ thumbnail: c.thumbnail || '',
}),
});
const data = await res.json();
@@ -662,8 +677,10 @@
clearInterval(iv);
c.status = 'done';
c.filename = data.filename;
+ c.hasTranscript = !!data.transcript;
renderCard(idx);
saveCard(idx);
+ if (c.hasTranscript) saveTranscript(idx);
} else if (data.status === 'error') {
clearInterval(iv);
c.status = 'error';
@@ -688,6 +705,15 @@
a.click();
}
+ function saveTranscript(idx) {
+ const c = cardData[idx];
+ if (!c.jobId || !c.hasTranscript) return;
+ const a = document.createElement('a');
+ a.href = `/api/transcript/${c.jobId}`;
+ a.download = (c.filename || 'transcript').replace(/\.[^.]+$/, '') + '.txt';
+ a.click();
+ }
+
async function dlAll() {
const btn = document.querySelector('.dl-all-btn');
if (btn) { btn.disabled = true; btn.textContent = 'Downloading...'; }
@@ -700,6 +726,47 @@
if (btn) { btn.disabled = false; btn.textContent = 'Download All'; }
}
+
+ function fmtSize(bytes) {
+ if (!bytes) return '';
+ const mb = bytes / 1048576;
+ return mb >= 1024 ? (mb / 1024).toFixed(2) + ' GB' : mb.toFixed(1) + ' MB';
+ }
+
+ async function loadHistory() {
+ try {
+ const res = await fetch('/api/history');
+ const rows = await res.json();
+ const box = document.getElementById('history');
+ if (!Array.isArray(rows) || !rows.length) return;
+ const items = rows.map(r => {
+ let thumbHtml;
+ if (r.thumbnail) {
+ thumbHtml = `<img src="${r.thumbnail}" alt="">`;
+ } else {
+ thumbHtml = `<div class="no-thumb"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/></svg></div>`;
+ }
+ const flag = r.has_transcript
+ ? `<span class="card-status done">transcript ✓</span>`
+ : `<span class="card-status">no transcript</span>`;
+ return `
+ <div class="card">
+ <div class="card-thumb">${thumbHtml}</div>
+ <div class="card-body">
+ <div class="card-title">${esc(r.title || r.filename || r.url || 'Untitled')}</div>
+ <div class="card-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · <span class="${r.has_transcript ? 'card-status done' : ''}">${r.has_transcript ? 'transcript ✓' : 'no transcript'}</span></div>
+ <div class="card-actions">
+ <a class="card-dl-btn" href="/api/file/${r.job_id}" download>Save</a>
+ ${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
+ </div>
+ </div>
+ </div>`;
+ }).join('');
+ box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
+ } catch { /* history unavailable */ }
+ }
+
+ loadHistory();
</script>
</body>
</html>