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.
354 lines
13 KiB
Diff
354 lines
13 KiB
Diff
diff --git a/app.py b/app.py
|
|
index 2b5eaa5..3c3c9c8 100644
|
|
--- a/app.py
|
|
+++ b/app.py
|
|
@@ -2,8 +2,10 @@ 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__)
|
|
@@ -12,6 +14,58 @@ 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.
|
|
@@ -29,6 +83,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 +182,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 +282,7 @@ 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}
|
|
|
|
thread = threading.Thread(target=run_download, args=(job_id, url, format_choice, format_id))
|
|
thread.daemon = True
|
|
@@ -184,6 +291,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 +312,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..9017db6 100644
|
|
--- a/templates/index.html
|
|
+++ b/templates/index.html
|
|
@@ -343,6 +343,43 @@
|
|
.dl-all-btn:hover { background: #2d2d2a; }
|
|
.dl-all-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
|
|
|
+ /* History */
|
|
+ .hist-h {
|
|
+ font-family: 'Instrument Serif', serif;
|
|
+ font-size: 1.4rem;
|
|
+ font-weight: 400;
|
|
+ margin: 32px 0 10px;
|
|
+ color: var(--fg);
|
|
+ }
|
|
+ .hist-row {
|
|
+ display: flex;
|
|
+ gap: 10px;
|
|
+ align-items: center;
|
|
+ border: 1.5px solid var(--card-border);
|
|
+ border-radius: 10px;
|
|
+ background: var(--card);
|
|
+ padding: 10px 12px;
|
|
+ margin-bottom: 6px;
|
|
+ }
|
|
+ .hist-main { flex: 1; min-width: 0; }
|
|
+ .hist-title {
|
|
+ font-size: 0.8rem;
|
|
+ color: var(--fg);
|
|
+ overflow: hidden;
|
|
+ text-overflow: ellipsis;
|
|
+ white-space: nowrap;
|
|
+ }
|
|
+ .hist-meta {
|
|
+ font-size: 0.65rem;
|
|
+ color: var(--muted);
|
|
+ text-transform: uppercase;
|
|
+ letter-spacing: 0.03em;
|
|
+ margin-top: 2px;
|
|
+ }
|
|
+ .hist-meta .t-flag { color: var(--success); }
|
|
+ .hist-actions { display: flex; gap: 6px; }
|
|
+ a.card-dl-btn { text-decoration: none; display: inline-block; }
|
|
+
|
|
.spin {
|
|
display: inline-block;
|
|
width: 10px; height: 10px;
|
|
@@ -399,6 +436,7 @@
|
|
</div>
|
|
|
|
<div id="cards" class="cards"></div>
|
|
+ <div id="history"></div>
|
|
|
|
<div class="footer">
|
|
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
|
@@ -586,8 +624,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>`;
|
|
@@ -662,8 +701,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 +729,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 +750,35 @@
|
|
|
|
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 => `
|
|
+ <div class="hist-row">
|
|
+ <div class="hist-main">
|
|
+ <div class="hist-title">${esc(r.title || r.filename || r.url || '')}</div>
|
|
+ <div class="hist-meta">${esc(r.date || '')}${r.size ? ' · ' + fmtSize(r.size) : ''} · ${r.has_transcript ? '<span class="t-flag">transcript ✓</span>' : 'no transcript'}</div>
|
|
+ </div>
|
|
+ <div class="hist-actions">
|
|
+ <a class="card-dl-btn" href="/api/file/${r.job_id}" download>${esc(r.filename || 'Save').replace(/\.[^.]+$/, '')}</a>
|
|
+ ${r.has_transcript ? `<a class="card-dl-btn" href="/api/transcript/${r.job_id}" download>Transcript</a>` : ''}
|
|
+ </div>
|
|
+ </div>`).join('');
|
|
+ box.innerHTML = `<h2 class="hist-h">History</h2>${items}`;
|
|
+ } catch { /* history unavailable */ }
|
|
+ }
|
|
+
|
|
+ loadHistory();
|
|
</script>
|
|
</body>
|
|
</html>
|