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:
1 parent
b4dfbd7540
commit
b8773b8fc2
4 files changed
+1543
No files matched your search
@@ -0,0 +1,44 @@
|
||||
# Patched reclip — source of truth
|
||||
|
||||
Our transcription + history additions to [averygan/reclip](https://github.com/averygan/reclip),
|
||||
kept here so container updates and new machines can't lose them.
|
||||
|
||||
- `app.py`, `index.html` — the full patched files (deployed via bind-mounts
|
||||
from `documents/reclip/` on the Unraid share; see that dir's DEPLOY.md)
|
||||
- `reclip-transcript.patch` — the same delta as a diff against upstream,
|
||||
for rebasing onto future upstream versions
|
||||
|
||||
Patch base: upstream `1d161d1` (cloned 2026-10-25).
|
||||
|
||||
## What the patch adds
|
||||
|
||||
1. `fetch_transcript()` — after each download, pull yt-dlp captions
|
||||
(YouTube subs; X auto-captions) → `<stem>.txt` sidecar, never fails the job
|
||||
2. `/api/transcript/<job_id>` + Transcript button + auto-save in the UI
|
||||
3. Persisted download history (`history.json` in the downloads volume) +
|
||||
`/api/history` + History section with a live transcript-available flag
|
||||
(manual `yt-transcribe` sidecars are detected at read time)
|
||||
4. `/api/file` + `/api/transcript` fall back to history, so old links
|
||||
survive restarts
|
||||
|
||||
## Updating reclip (when upstream changes)
|
||||
|
||||
git clone --depth 1 https://github.com/averygan/reclip.git /tmp/reclip-new
|
||||
cd /tmp/reclip-new
|
||||
git apply --3way ~/Documents/dotfiles/patches/reclip/reclip-transcript.patch
|
||||
|
||||
Resolve any conflicts (the additions are mostly self-contained: one new
|
||||
function, two routes, one status field, UI button + History section), then
|
||||
copy the updated `app.py` + `templates/index.html`:
|
||||
|
||||
- into this directory (commit — new source of truth)
|
||||
- to the share: `/Volumes/data/documents/reclip/{app.py,index.html}`
|
||||
- restart the reclip container (gunicorn reloads at start; the entrypoint
|
||||
also pip-updates yt-dlp at every container start)
|
||||
|
||||
If `git apply` fails on a drifted file, the fastest path is re-porting by
|
||||
hand from the conflict markers — the four additions are small and greppable
|
||||
(`fetch_transcript`, `history.json`, `resolve_download`, `saveTranscript`).
|
||||
|
||||
If an image update happens WITHOUT re-porting: the old patched files keep
|
||||
working (bind-mounts win), you just may miss upstream improvements.
|
||||
@@ -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)
|
||||
@@ -0,0 +1,784 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ReClip — Free Media Downloader</title>
|
||||
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f4f1eb;
|
||||
--fg: #3a3a38;
|
||||
--accent: #e85d2a;
|
||||
--accent-hover: #d04e1f;
|
||||
--muted: #9c9889;
|
||||
--card: #fff;
|
||||
--card-border: #e2ded6;
|
||||
--success: #2d8a4e;
|
||||
--error: #c43d3d;
|
||||
--radius: 14px;
|
||||
--shimmer: linear-gradient(90deg, #ebe8e2 25%, #f0ede7 50%, #ebe8e2 75%);
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: 'DM Mono', monospace;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: '';
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
opacity: 0.03;
|
||||
pointer-events: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
|
||||
background-size: 128px;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 620px;
|
||||
margin: 0 auto;
|
||||
padding: 60px 24px 80px;
|
||||
}
|
||||
|
||||
.brand { margin-bottom: 48px; }
|
||||
.brand h1 {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 4.2rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 1;
|
||||
color: var(--fg);
|
||||
}
|
||||
.brand h1 em { font-style: italic; color: var(--accent); }
|
||||
.brand p {
|
||||
margin-top: 10px;
|
||||
font-size: 0.78rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 18px 20px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
color: var(--fg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.88rem;
|
||||
outline: none;
|
||||
resize: none;
|
||||
min-height: 56px;
|
||||
transition: border-color 0.25s, box-shadow 0.25s;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
textarea:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(232, 93, 42, 0.08);
|
||||
}
|
||||
textarea::placeholder { color: var(--muted); }
|
||||
|
||||
.hint {
|
||||
font-size: 0.7rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 20px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.pill-group {
|
||||
display: flex;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--card);
|
||||
}
|
||||
.pill {
|
||||
padding: 9px 18px;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.76rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.pill.active { background: var(--fg); color: var(--bg); }
|
||||
.pill:not(.active):hover { color: var(--fg); }
|
||||
|
||||
.fetch-btn {
|
||||
flex: 1;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, transform 0.1s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.fetch-btn:hover { background: var(--accent-hover); }
|
||||
.fetch-btn:active { transform: scale(0.98); }
|
||||
.fetch-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
|
||||
|
||||
/* Cards */
|
||||
.cards { margin-top: 24px; }
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--card);
|
||||
padding: 14px;
|
||||
margin-bottom: 10px;
|
||||
animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.card-thumb {
|
||||
width: 120px;
|
||||
min-width: 120px;
|
||||
height: 80px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--card-border);
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
}
|
||||
.card-thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
/* No-thumbnail icon */
|
||||
.card-thumb .no-thumb {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-thumb .no-thumb svg {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* Shimmer skeleton for loading state */
|
||||
.card-thumb.loading {
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
}
|
||||
.skeleton-line {
|
||||
height: 12px;
|
||||
border-radius: 4px;
|
||||
background: var(--shimmer);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s infinite;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.skeleton-line.short { width: 40%; height: 10px; }
|
||||
.skeleton-line.medium { width: 75%; }
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.card-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
.card-title {
|
||||
font-family: 'Instrument Serif', serif;
|
||||
font-size: 1rem;
|
||||
line-height: 1.3;
|
||||
color: var(--fg);
|
||||
margin-bottom: 2px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.card-meta {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-dl-btn {
|
||||
padding: 6px 14px;
|
||||
border: none;
|
||||
border-radius: 7px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.card-dl-btn:hover { background: #2d2d2a; }
|
||||
.card-dl-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.card-dl-btn.done { background: var(--success); color: #fff; }
|
||||
.card-dl-btn.error { background: var(--error); color: #fff; }
|
||||
|
||||
.card-status {
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
.card-status.downloading { color: var(--accent); }
|
||||
.card-status.done { color: var(--success); }
|
||||
.card-status.error { color: var(--error); }
|
||||
|
||||
.q-chip {
|
||||
padding: 4px 10px;
|
||||
border: 1.5px solid var(--card-border);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.65rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.q-chip.active {
|
||||
border-color: var(--fg);
|
||||
color: var(--fg);
|
||||
background: rgba(26,26,24,0.04);
|
||||
}
|
||||
.q-chip:hover:not(.active) { border-color: var(--muted); }
|
||||
|
||||
/* Error card */
|
||||
.card.card-error {
|
||||
border-color: rgba(196, 61, 61, 0.2);
|
||||
background: rgba(196, 61, 61, 0.03);
|
||||
}
|
||||
.card-error-icon {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(196, 61, 61, 0.08);
|
||||
color: var(--error);
|
||||
}
|
||||
.card-error-icon svg {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
.card-error-msg {
|
||||
font-size: 0.72rem;
|
||||
color: var(--error);
|
||||
margin-top: 2px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.card-error-url {
|
||||
font-size: 0.65rem;
|
||||
color: var(--muted);
|
||||
word-break: break-all;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Download all bar */
|
||||
.dl-all-bar {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.dl-all-btn {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: var(--fg);
|
||||
color: var(--bg);
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.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;
|
||||
border: 2px solid currentColor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
vertical-align: middle;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.footer {
|
||||
margin-top: 48px;
|
||||
text-align: center;
|
||||
font-size: 0.68rem;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* Mobile */
|
||||
@media (max-width: 500px) {
|
||||
.brand h1 { font-size: 3rem; }
|
||||
.page { padding: 40px 16px 60px; }
|
||||
.card { flex-direction: column; gap: 10px; }
|
||||
.card-thumb {
|
||||
width: 100%;
|
||||
min-width: unset;
|
||||
height: 160px;
|
||||
}
|
||||
.card-title { white-space: normal; }
|
||||
.controls { flex-wrap: wrap; }
|
||||
.fetch-btn { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="brand">
|
||||
<h1>Re<em>Clip</em></h1>
|
||||
<p>Free media downloader</p>
|
||||
</div>
|
||||
|
||||
<textarea id="urls" placeholder="Paste one or more URLs..." rows="2"></textarea>
|
||||
<p class="hint">Multiple links? Separate with spaces, commas, or newlines.</p>
|
||||
|
||||
<div class="controls">
|
||||
<div class="pill-group">
|
||||
<button class="pill active" data-format="video" onclick="setFormat(this)">MP4</button>
|
||||
<button class="pill" data-format="audio" onclick="setFormat(this)">MP3</button>
|
||||
</div>
|
||||
<button class="fetch-btn" id="goBtn" onclick="go()">Fetch</button>
|
||||
</div>
|
||||
|
||||
<div id="cards" class="cards"></div>
|
||||
<div id="history"></div>
|
||||
|
||||
<div class="footer">
|
||||
YouTube · TikTok · Instagram · Twitter/X · Reddit · Facebook<br>
|
||||
Vimeo · Twitch · Dailymotion · SoundCloud · Loom · Streamable<br>
|
||||
Pinterest · Tumblr · Threads · LinkedIn · 1000+ more
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentFormat = 'video';
|
||||
let cardData = [];
|
||||
|
||||
function setFormat(btn) {
|
||||
document.querySelectorAll('.pill').forEach(b => b.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
currentFormat = btn.dataset.format;
|
||||
}
|
||||
|
||||
function parseUrls(text) {
|
||||
return [...new Set(text.split(/[\s,]+/).map(u => u.trim()).filter(u => u.startsWith('http')))];
|
||||
}
|
||||
|
||||
function fmtDur(s) {
|
||||
if (!s) return '';
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = Math.floor(s % 60);
|
||||
return `${m}:${sec.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
function friendlyError(err) {
|
||||
if (err.includes('Unsupported URL')) return 'This URL is not supported';
|
||||
if (err.includes('Video unavailable')) return 'Video is unavailable or private';
|
||||
if (err.includes('Private video')) return 'This video is private';
|
||||
if (err.includes('HTTP Error 403')) return 'Access denied by the platform';
|
||||
if (err.includes('HTTP Error 404')) return 'Video not found';
|
||||
if (err.includes('copyright')) return 'Video blocked due to copyright';
|
||||
if (err.includes('geo')) return 'Video not available in your region';
|
||||
if (err.includes('timed out') || err.includes('Timed out')) return 'Request timed out — try again';
|
||||
if (err.includes('network') || err.includes('Network')) return 'Network error — check your connection';
|
||||
return err.length > 80 ? err.slice(0, 80) + '...' : err;
|
||||
}
|
||||
|
||||
document.getElementById('urls').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); go(); }
|
||||
});
|
||||
|
||||
async function go() {
|
||||
const urls = parseUrls(document.getElementById('urls').value);
|
||||
if (!urls.length) return;
|
||||
|
||||
const btn = document.getElementById('goBtn');
|
||||
const container = document.getElementById('cards');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Loading...';
|
||||
container.innerHTML = '';
|
||||
cardData = [];
|
||||
|
||||
// Check if youtube playlist URL
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
if (urls[i].includes('list=')) {
|
||||
const res = await fetch('/api/playlist', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: urls[i] }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.urls) {
|
||||
// replace playlist URL with individual video URLs
|
||||
urls.splice(i, 1, ...data.urls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const url = urls[i];
|
||||
const idx = cardData.length;
|
||||
cardData.push({ url, status: 'loading' });
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/info', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: data.error };
|
||||
} else {
|
||||
cardData[idx] = {
|
||||
...cardData[idx],
|
||||
status: 'ready',
|
||||
title: data.title || '',
|
||||
thumbnail: data.thumbnail || '',
|
||||
duration: data.duration,
|
||||
uploader: data.uploader || '',
|
||||
formats: data.formats || [],
|
||||
selectedFormatId: data.formats?.[0]?.id || null,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
cardData[idx] = { ...cardData[idx], status: 'info-error', error: err.message };
|
||||
}
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
if (cardData.filter(c => c.status === 'ready').length > 1) {
|
||||
renderDownloadAll();
|
||||
}
|
||||
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Fetch';
|
||||
}
|
||||
|
||||
function renderCard(idx) {
|
||||
const c = cardData[idx];
|
||||
let el = document.getElementById(`card-${idx}`);
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = `card-${idx}`;
|
||||
el.className = 'card';
|
||||
document.getElementById('cards').appendChild(el);
|
||||
}
|
||||
|
||||
// Loading skeleton
|
||||
if (c.status === 'loading') {
|
||||
el.className = 'card';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb loading"></div>
|
||||
<div class="card-body">
|
||||
<div class="skeleton-line medium"></div>
|
||||
<div class="skeleton-line short"></div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (c.status === 'info-error') {
|
||||
el.className = 'card card-error';
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">
|
||||
<div class="card-error-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title" style="color:var(--error)">Could not fetch video</div>
|
||||
<div class="card-error-msg">${esc(friendlyError(c.error || ''))}</div>
|
||||
<div class="card-error-url">${esc(c.url)}</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Ready / downloading / done / error states
|
||||
el.className = 'card';
|
||||
const isAudio = currentFormat === 'audio';
|
||||
|
||||
let thumbHtml;
|
||||
if (isAudio) {
|
||||
thumbHtml = `<div class="no-thumb" style="color:var(--accent)"><svg viewBox="0 0 24 24" fill="currentColor" stroke="none"><polygon points="5 3 19 12 5 21 5 3"/></svg></div>`;
|
||||
} else if (c.thumbnail) {
|
||||
thumbHtml = `<img src="${c.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>`;
|
||||
}
|
||||
|
||||
let qualityChips = '';
|
||||
if (!isAudio && c.formats && c.formats.length > 1) {
|
||||
qualityChips = c.formats.map(f =>
|
||||
`<button class="q-chip${f.id === c.selectedFormatId ? ' active' : ''}" onclick="pickFormat(${idx}, '${f.id}')">${f.label}</button>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
let actionHtml = '';
|
||||
if (c.status === 'ready') {
|
||||
actionHtml = `<button class="card-dl-btn" onclick="dlCard(${idx})">Download</button>${qualityChips}`;
|
||||
} 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>` +
|
||||
(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>`;
|
||||
}
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="card-thumb">${thumbHtml}</div>
|
||||
<div class="card-body">
|
||||
<div class="card-title">${esc(c.title || 'Untitled')}</div>
|
||||
<div class="card-meta">${esc(c.uploader)}${c.duration ? ' · ' + fmtDur(c.duration) : ''}</div>
|
||||
<div class="card-actions">${actionHtml}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderDownloadAll() {
|
||||
const existing = document.getElementById('dl-all-bar');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const bar = document.createElement('div');
|
||||
bar.id = 'dl-all-bar';
|
||||
bar.className = 'dl-all-bar';
|
||||
bar.innerHTML = `<button class="dl-all-btn" onclick="dlAll()">Download All</button>`;
|
||||
document.getElementById('cards').appendChild(bar);
|
||||
}
|
||||
|
||||
function pickFormat(idx, formatId) {
|
||||
cardData[idx].selectedFormatId = formatId;
|
||||
renderCard(idx);
|
||||
}
|
||||
|
||||
async function dlCard(idx) {
|
||||
const c = cardData[idx];
|
||||
c.status = 'downloading';
|
||||
c.error = null;
|
||||
renderCard(idx);
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/download', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: c.url,
|
||||
format: currentFormat,
|
||||
format_id: c.selectedFormatId,
|
||||
title: c.title || '',
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
c.status = 'error';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
return;
|
||||
}
|
||||
c.jobId = data.job_id;
|
||||
pollCard(idx);
|
||||
} catch (err) {
|
||||
c.status = 'error';
|
||||
c.error = err.message;
|
||||
renderCard(idx);
|
||||
}
|
||||
}
|
||||
|
||||
function pollCard(idx) {
|
||||
const c = cardData[idx];
|
||||
const iv = setInterval(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/status/${c.jobId}`);
|
||||
const data = await res.json();
|
||||
if (data.status === 'done') {
|
||||
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';
|
||||
c.error = data.error;
|
||||
renderCard(idx);
|
||||
}
|
||||
} catch {
|
||||
clearInterval(iv);
|
||||
c.status = 'error';
|
||||
c.error = 'Lost connection to server';
|
||||
renderCard(idx);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function saveCard(idx) {
|
||||
const c = cardData[idx];
|
||||
if (!c.jobId) return;
|
||||
const a = document.createElement('a');
|
||||
a.href = `/api/file/${c.jobId}`;
|
||||
a.download = c.filename || '';
|
||||
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...'; }
|
||||
|
||||
for (let i = 0; i < cardData.length; i++) {
|
||||
if (cardData[i].status === 'ready') {
|
||||
await dlCard(i);
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -0,0 +1,353 @@
|
||||
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>
|
||||
Reference in new issue
Block a user