Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
Content studio + standalone Thumbnail studio pages (#34)
Nika Siradzecb5bfda8d157
diff --git a/backend/main.py b/backend/main.pyindex b8d2a85..d07e803 100644--- a/backend/main.py+++ b/backend/main.py@@ -430,6 +430,10 @@ def handle_generate_content(task_id: str, params: dict):clip=clip,transcript_segments=transcript_segments,progress_callback=lambda pct, msg: emit_progress(task_id, "generating", pct, msg),+ mode=params.get("mode", "shorts"),+ partial_callback=lambda partial: emit_progress(+ task_id, "generating", 60, "Writing content...", partial=partial+ ),)if result is None:diff --git a/backend/services/content_generator.py b/backend/services/content_generator.pyindex e1d3ba5..6359998 100644--- a/backend/services/content_generator.py+++ b/backend/services/content_generator.py@@ -8,23 +8,27 @@ import jsonimport osimport subprocessimport tempfile+import threadingfrom typing import Optional, Callablefrom config.paths import pathsfrom services.claude_suggest import _engine_label, _find_ai_cli_candidates, _run_ai_command-def _load_kb_context() -> str:- """Load PodStack knowledge base files for content generation."""+CONTENT_KB_FILES = [+ ("05-title-formulas.md", 3000),+ ("06-descriptions-template.md", 2000),+ ("02-voice-and-tone.md", 2000),+ ("01-brand-identity.md", 1000),+ ("12-quick-reference.md", 1500),+]+++def load_kb_context(files: Optional[list[tuple[str, int]]] = None) -> str:+ """Load PodStack knowledge base files as inline prompt context."""kb_dir = paths["knowledge"]kb_context = ""- for fname, max_chars in [- ("05-title-formulas.md", 3000),- ("06-descriptions-template.md", 2000),- ("02-voice-and-tone.md", 2000),- ("01-brand-identity.md", 1000),- ("12-quick-reference.md", 1500),- ]:+ for fname, max_chars in files if files is not None else CONTENT_KB_FILES:fpath = os.path.join(kb_dir, fname)if os.path.exists(fpath):try:@@ -39,10 +43,152 @@ def _load_kb_context() -> str:return kb_context+def _sample_lines(lines: list[str], max_lines: int = 30) -> list[str]:+ """Pick evenly spaced lines so long episodes are represented end to end."""+ if len(lines) <= max_lines:+ return lines+ last = len(lines) - 1+ picked = sorted({round(i * last / (max_lines - 1)) for i in range(max_lines)})+ return [lines[i] for i in picked]+++def _parse_content(raw_text: str) -> dict:+ result = {+ "raw_text": raw_text,+ "titles": [],+ "top_pick": "",+ "description": "",+ "tags": "",+ "hashtags": "",+ }+ section = ""+ for line in raw_text.split("\n"):+ stripped = line.strip()+ if not stripped:+ # Keep paragraph breaks in multi-paragraph episode descriptions.+ if section == "description" and result["description"]:+ result["description"] += "\n"+ continue+ upper = stripped.upper()+ if upper.startswith("TITLES"):+ section = "titles"+ continue+ elif upper.startswith("TOP PICK"):+ result["top_pick"] = stripped+ section = ""+ continue+ elif upper.startswith("DESCRIPTION"):+ section = "description"+ continue+ elif upper.startswith("TAGS"):+ section = "tags"+ continue+ elif upper.startswith("HASHTAGS"):+ section = "hashtags"+ continue++ if section == "titles" and stripped[0:1].isdigit() and ". " in stripped[:4]:+ result["titles"].append(stripped)+ elif section == "description":+ result["description"] += stripped + "\n"+ elif section == "tags":+ result["tags"] = stripped+ elif section == "hashtags":+ result["hashtags"] = stripped++ result["description"] = result["description"].strip()+ return result+++def _stream_claude_content(+ cli_path: str,+ prompt_file: str,+ project_dir: str,+ timeout: int,+ on_partial: Callable[[dict], None],+) -> Optional[str]:+ """Stream one claude --print run, emitting a parsed partial package as each+ output line completes. Returns the full response text, or None when+ streaming is unavailable so the caller can fall back to the blocking runner.+ """+ args = [+ cli_path, "--print", "--verbose",+ "--output-format", "stream-json", "--include-partial-messages",+ "-p", "-",+ ]+ try:+ prompt_fh = open(prompt_file, encoding="utf-8")+ except Exception:+ return None+ try:+ proc = subprocess.Popen(+ args,+ stdin=prompt_fh,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ encoding="utf-8",+ errors="replace",+ cwd=project_dir,+ )+ except Exception:+ prompt_fh.close()+ return None++ # readline blocks between deltas, so the timeout is enforced by a watchdog+ # kill rather than an in-loop deadline check.+ watchdog = threading.Timer(timeout, proc.kill)+ watchdog.start()+ text = ""+ final_text = None+ emitted = None+ try:+ for line in proc.stdout:+ line = line.strip()+ if not line.startswith("{"):+ continue+ try:+ event = json.loads(line)+ except Exception:+ continue+ etype = event.get("type")+ if etype == "stream_event":+ delta = (event.get("event") or {}).get("delta") or {}+ if delta.get("type") == "text_delta":+ chunk = delta.get("text", "")+ text += chunk+ if "\n" in chunk:+ parsed = _parse_content(text)+ snapshot = json.dumps(parsed, sort_keys=True)+ if snapshot != emitted:+ emitted = snapshot+ on_partial(parsed)+ elif etype == "result":+ final_text = event.get("result") or None+ rc = proc.wait()+ except Exception:+ try:+ proc.kill()+ proc.wait()+ except Exception:+ pass+ return None+ finally:+ watchdog.cancel()+ prompt_fh.close()++ out = (final_text or text).strip()+ if rc != 0 or not out:+ return None+ return out++def generate_clip_content(clip: dict,transcript_segments: list[dict],progress_callback: Optional[Callable[[int, str], None]] = None,+ mode: str = "shorts",+ partial_callback: Optional[Callable[[dict], None]] = None,) -> Optional[dict]:"""Generate titles, description, tags, and hashtags for a single clip.@@ -51,6 +197,7 @@ def generate_clip_content(clip: dict with title, start_second, end_second, content_typetranscript_segments: full transcript segments listprogress_callback: optional (percent, message) callback+ mode: "shorts" (per-clip package) or "episode" (long-form episode package)Returns:dict with raw_text, titles, description, tags, hashtags, or None if AI unavailable@@ -63,7 +210,7 @@ def generate_clip_content(if progress_callback:progress_callback(0, f"Generating content via {label}...")- kb_context = _load_kb_context()+ kb_context = load_kb_context()# Extract transcript text for this clip's time rangeclip_start = clip.get("start_second", 0)@@ -76,7 +223,42 @@ def generate_clip_content(sp_label = f"[{sp}] " if sp else ""clip_transcript.append(f"{sp_label}{seg.get('text', '').strip()}")- prompt = f"""Generate a YouTube Shorts content package for this clip. Return ONLY the content below, no preamble.+ if mode == "episode":+ prompt = f"""Generate a YouTube content package for this full podcast episode. Return ONLY the content below, no preamble.++KNOWLEDGE BASE:+{kb_context}++EPISODE: "{clip.get('title', '')}"++TRANSCRIPT EXCERPT:+{chr(10).join(_sample_lines(clip_transcript))}++Generate exactly this (no other text):++TITLES (8 options, 50-70 chars, keyword-first, follow title spec):+1. [title]+2. [title]+3. [title]+4. [title]+5. [title]+6. [title]+7. [title]+8. [title]+TOP PICK: [number] — [why]++DESCRIPTION:+[hook line under 100 chars]+[2-3 short paragraphs: what the episode covers and why it matters]+[guest attribution line]++TAGS:+[comma-separated, 10-15 tags for YouTube]++HASHTAGS:+[3-5 hashtags for description]"""+ else:+ prompt = f"""Generate a YouTube Shorts content package for this clip. Return ONLY the content below, no preamble.KNOWLEDGE BASE:{kb_context}@@ -124,72 +306,40 @@ HASHTAGS:progress_callback(0, f"Retrying content generation with {label}...")progress_callback(30, f"Asking {label} for titles & descriptions...")- try:- cr = _run_ai_command(+ raw_text = None+ if engine == "claude" and partial_callback is not None:+ raw_text = _stream_claude_content(cli_path=cli_path,- engine=engine,- prompt=prompt[:4000] if engine == "codex" else prompt,prompt_file=prompt_file,project_dir=project_dir,timeout=120,+ on_partial=partial_callback,)- except subprocess.TimeoutExpired:- continue- except Exception:- continue-- if cr.returncode != 0 or not cr.stdout.strip():- continue-- raw_text = cr.stdout.strip()-- if progress_callback:- progress_callback(90, "Parsing content...")- result = {- "raw_text": raw_text,- "titles": [],- "top_pick": "",- "description": "",- "tags": "",- "hashtags": "",- "engine": engine,- }-- lines = raw_text.split("\n")- section = ""- for line in lines:- stripped = line.strip()- if not stripped:- continue- upper = stripped.upper()- if upper.startswith("TITLES"):- section = "titles"- continue- elif upper.startswith("TOP PICK"):- result["top_pick"] = stripped- section = ""+ if raw_text is None:+ try:+ cr = _run_ai_command(+ cli_path=cli_path,+ engine=engine,+ prompt=prompt[:4000] if engine == "codex" else prompt,+ prompt_file=prompt_file,+ project_dir=project_dir,+ timeout=120,+ )+ except subprocess.TimeoutExpired:continue- elif upper.startswith("DESCRIPTION"):- section = "description"+ except Exception:continue- elif upper.startswith("TAGS"):- section = "tags"- continue- elif upper.startswith("HASHTAGS"):- section = "hashtags"++ if cr.returncode != 0 or not cr.stdout.strip():continue+ raw_text = cr.stdout.strip()- if section == "titles" and stripped[0:1].isdigit() and ". " in stripped[:4]:- result["titles"].append(stripped)- elif section == "description":- result["description"] += stripped + "\n"- elif section == "tags":- result["tags"] = stripped- elif section == "hashtags":- result["hashtags"] = stripped+ if progress_callback:+ progress_callback(90, "Parsing content...")- result["description"] = result["description"].strip()+ result = _parse_content(raw_text)+ result["engine"] = engineif not result["titles"] and not result["description"]:continuediff --git a/backend/services/thumbnail_ai.py b/backend/services/thumbnail_ai.pyindex 8eeef18..daf1394 100644--- a/backend/services/thumbnail_ai.py+++ b/backend/services/thumbnail_ai.py@@ -469,6 +469,19 @@ def _ask_ai_for_json(prompt: str, timeout: int = 30):return None+def _thumbnail_kb_context() -> str:+ from services.content_generator import load_kb_context++ kb = load_kb_context([+ ("07-thumbnail-guide.md", 2500),+ ("02-voice-and-tone.md", 1500),+ ("01-brand-identity.md", 800),+ ])+ if not kb:+ return ""+ return f"\nBRAND KNOWLEDGE BASE (follow its thumbnail text rules, voice, and banned words):\n{kb}\n"++def ask_claude_for_layout(title: str,frame_path: str,@@ -496,7 +509,7 @@ def ask_claude_for_layout(prompt = f"""You are a thumbnail layout engine. Given a title and face position, return CSS values for a YouTube Shorts thumbnail (1080x1920).TITLE: "{title}"-+{_thumbnail_kb_context()}PHOTO INFO:{face_ctx}@@ -537,7 +550,7 @@ def generate_headline_variations(title: str, n: int, config: Optional[dict] = Noprompt = f"""You are a thumbnail copywriter. Write {n} DISTINCT headline options for a YouTube Shorts thumbnail.TITLE: "{title}"-+{_thumbnail_kb_context()}Return ONLY a JSON array of exactly {n} objects, each with "line1" and "line2":[{{"line1": "FIRST LINE", "line2": "SECOND LINE"}}, ...]diff --git a/package-lock.json b/package-lock.jsonindex 1930b9c..b68bfc8 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "podcli",- "version": "1.1.0",+ "version": "2.0.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "podcli",- "version": "1.1.0",+ "version": "2.0.0","license": "AGPL-3.0-only","dependencies": {"@fontsource/dm-sans": "^5.2.8",@@ -16,6 +16,7 @@"@remotion/renderer": "^4.0.441","dotenv": "^16.4.7","express": "^4.21.0",+ "lucide-react": "^1.23.0","multer": "^1.4.5-lts.1","react": "^18.3.1","react-dom": "^18.3.1",@@ -6656,6 +6657,15 @@"node": ">=10"}},+ "node_modules/lucide-react": {+ "version": "1.23.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.23.0.tgz",+ "integrity": "sha512-38BpJcD0JhFosxHApP/BYsBetLpQFRoTRzEzstM/XCc3jsAG7wqaY1lgVwxiUe3xqYE+lNxo2PkCmYwXWrwwIw==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/magic-string": {"version": "0.30.21","resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",diff --git a/package.json b/package.jsonindex 9164b4e..bf7c8f9 100644--- a/package.json+++ b/package.json@@ -44,6 +44,7 @@"@remotion/renderer": "^4.0.441","dotenv": "^16.4.7","express": "^4.21.0",+ "lucide-react": "^1.23.0","multer": "^1.4.5-lts.1","react": "^18.3.1","react-dom": "^18.3.1",diff --git a/src/models/index.ts b/src/models/index.tsindex ce95d90..79831c1 100644--- a/src/models/index.ts+++ b/src/models/index.ts@@ -19,6 +19,7 @@ export interface ProgressEvent {percent: number;message: string;clip_result?: BatchClipsResult["results"][number];+ partial?: Record<string, unknown>;}// === Transcript Models ===diff --git a/src/ui/client/ContentStudio.tsx b/src/ui/client/ContentStudio.tsxnew file mode 100644index 0000000..98e1f05--- /dev/null+++ b/src/ui/client/ContentStudio.tsx@@ -0,0 +1,198 @@+import React, { useEffect, useState } from "react";+import { api, basename, labelStyle } from "./lib";+import CopyButton from "./CopyButton";++interface ContentResult {+ titles?: string[];+ top_pick?: string;+ description?: string;+ tags?: string;+ hashtags?: string;+ engine?: string;+}++const STORE = "podcli.content-studio";++export default function ContentStudio() {+ const [title, setTitle] = useState("");+ const [transcript, setTranscript] = useState("");+ const [mode, setMode] = useState<"episode" | "shorts">("shorts");+ const [busy, setBusy] = useState(false);+ const [stage, setStage] = useState<string | null>(null);+ const [msg, setMsg] = useState<string | null>(null);+ const [result, setResult] = useState<ContentResult | null>(null);+ const [sessionText, setSessionText] = useState("");+ const [sessionName, setSessionName] = useState("");+ const [copied, setCopied] = useState<string | null>(null);++ useEffect(() => {+ try {+ const saved = JSON.parse(localStorage.getItem(STORE) || "null");+ if (saved?.result) {+ setResult(saved.result);+ setTitle(saved.title || "");+ setMode(saved.mode === "episode" ? "episode" : "shorts");+ }+ } catch {}+ api("/ui-state")+ .then((s) => {+ setSessionText(s?.transcript?.transcript || s?.rawTranscriptText || "");+ setSessionName(basename(s?.filePath || s?.videoPath || ""));+ })+ .catch(() => {});+ }, []);++ const copy = (text: string) => {+ navigator.clipboard?.writeText(text).then(() => {+ setCopied(text);+ setTimeout(() => setCopied(null), 1500);+ });+ };++ const generate = async () => {+ if (!transcript.trim()) {+ setMsg("Paste a transcript first");+ return;+ }+ setBusy(true);+ setMsg(null);+ setResult(null);+ setStage("Starting generation...");+ const streamId = Math.random().toString(36).slice(2);+ const es = new EventSource("/api/events");+ es.addEventListener("content-partial", (e) => {+ try {+ const d = JSON.parse((e as MessageEvent).data);+ if (d.stream_id === streamId && d.partial) setResult(d.partial);+ } catch {}+ });+ es.addEventListener("job-update", (e) => {+ try {+ const d = JSON.parse((e as MessageEvent).data);+ if (d.message) setStage(d.message);+ } catch {}+ });+ try {+ const r = await api<ContentResult>("/content-studio/generate", {+ method: "POST",+ body: JSON.stringify({ title: title || undefined, transcript_text: transcript, mode, stream_id: streamId }),+ });+ if (!r.titles?.length && !r.description) throw new Error("AI CLI returned nothing. Is claude or codex installed?");+ setResult(r);+ try { localStorage.setItem(STORE, JSON.stringify({ title, mode, result: r })); } catch {}+ } catch (e: any) {+ setMsg(`Generation failed: ${e.message}`);+ } finally {+ es.close();+ setBusy(false);+ setStage(null);+ }+ };++ return (+ <div className="app">+ <div className="header">+ <h1>Content studio</h1>+ </div>++ <div style={{ display: "flex", gap: 24, alignItems: "flex-start", flexWrap: "wrap" }}>+ <div style={{ flex: "1 1 380px", minWidth: 320 }}>+ <div className="section">+ <label style={labelStyle}>Episode / clip title (optional)</label>+ <input+ type="text"+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ placeholder="Working title or topic"+ style={{ width: "100%", fontSize: 14, padding: "10px 13px" }}+ />++ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "18px 0 0" }}>+ <label style={{ ...labelStyle, marginBottom: 0 }}>Transcript</label>+ {sessionText && (+ <button className="btn btn-ghost btn-sm" onClick={() => setTranscript(sessionText)} disabled={busy} title={sessionName}>+ Use current episode{sessionName ? ` · ${sessionName}` : ""}+ </button>+ )}+ </div>+ <textarea+ value={transcript}+ onChange={(e) => setTranscript(e.target.value)}+ placeholder="Paste the transcript here"+ style={{ width: "100%", minHeight: 260, fontSize: 13, lineHeight: 1.6, padding: "10px 13px", marginTop: 8, resize: "vertical" }}+ />++ <div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center" }}>+ <select value={mode} onChange={(e) => setMode(e.target.value as "episode" | "shorts")} style={{ flex: 1 }}>+ <option value="episode">Full episode (long-form)</option>+ <option value="shorts">Short / clip</option>+ </select>+ <button className="btn btn-primary btn-sm" onClick={generate} disabled={busy || !transcript.trim()}>+ {busy ? <><div className="spinner sm" /> Generating…</> : "Generate"}+ </button>+ </div>+ {busy && stage && <div style={{ fontSize: 11, color: "var(--text3)", marginTop: 10 }}>{stage}</div>}+ {msg && <div className="set-note ok" style={{ marginTop: 10, wordBreak: "break-word" }}>{msg}</div>}+ </div>+ </div>++ <div style={{ flex: "1 1 420px", minWidth: 320 }}>+ {!result ? (+ <div className="section" style={{ color: "var(--text3)", fontSize: 12, display: "flex", alignItems: "center", gap: 8 }}>+ {busy ? <><div className="spinner sm" /> Waiting for the first lines</> : "Titles, description, tags, and hashtags appear here."}+ </div>+ ) : (+ <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>+ {result.titles?.length ? (+ <div className="section">+ <div style={{ fontSize: 11, color: "var(--text3)", marginBottom: 6 }}>Title options · click to copy</div>+ <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>+ {result.titles.map((t, i) => {+ const clean = t.replace(/^\d+\.\s*/, "");+ return (+ <button key={i} className={`title-option stream-in ${copied === clean ? "selected" : ""}`} onClick={() => copy(clean)}>+ {t}{copied === clean ? " · copied" : ""}+ </button>+ );+ })}+ </div>+ {result.top_pick && <div className="stream-in" style={{ fontSize: 12, color: "var(--accent)", marginTop: 10 }}>{result.top_pick}</div>}+ </div>+ ) : null}++ {result.description ? (+ <div className="section stream-in">+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>+ <span style={{ fontSize: 11, color: "var(--text3)" }}>Description</span>+ <CopyButton text={result.description} />+ </div>+ <div style={{ fontSize: 13, color: "var(--text2)", lineHeight: 1.6, whiteSpace: "pre-wrap" }}>{result.description}</div>+ </div>+ ) : null}++ {result.tags ? (+ <div className="section stream-in">+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>+ <span style={{ fontSize: 11, color: "var(--text3)" }}>Tags</span>+ <CopyButton text={result.tags} />+ </div>+ <div style={{ fontSize: 12, color: "var(--text2)", lineHeight: 1.6 }}>{result.tags}</div>+ </div>+ ) : null}++ {result.hashtags ? (+ <div className="section stream-in">+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>+ <span style={{ fontSize: 11, color: "var(--text3)" }}>Hashtags</span>+ <CopyButton text={result.hashtags} />+ </div>+ <div style={{ fontSize: 12, color: "var(--accent)", lineHeight: 1.6 }}>{result.hashtags}</div>+ </div>+ ) : null}+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/src/ui/client/CopyButton.tsx b/src/ui/client/CopyButton.tsxindex 825e505..4bb7e12 100644--- a/src/ui/client/CopyButton.tsx+++ b/src/ui/client/CopyButton.tsx@@ -1,4 +1,5 @@import React, { useEffect, useRef, useState } from "react";+import { Copy, Check } from "lucide-react";type CopyButtonProps = {text?: string;@@ -15,23 +16,6 @@ type CopyButtonProps = {onCopied?: () => void;};-function CopyIcon() {- return (- <svg className="copy-button-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">- <path d="M8 8h10v12H8z" />- <path d="M6 16H4V4h12v2" />- </svg>- );-}--function CheckIcon() {- return (- <svg className="copy-button-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">- <path d="M5 13l4 4L19 7" />- </svg>- );-}-export default function CopyButton({text,getText,@@ -84,11 +68,11 @@ export default function CopyButton({style={style}><span className="copy-button-layer copy-button-idle">- <CopyIcon />+ <Copy className="copy-button-icon" aria-hidden="true" />{!iconOnly && <span>{label}</span>}</span><span className="copy-button-layer copy-button-success">- <CheckIcon />+ <Check className="copy-button-icon" aria-hidden="true" />{!iconOnly && <span>{copiedLabel}</span>}</span></button>diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsxindex e905bb0..8e26116 100644--- a/src/ui/client/EpisodeWorkspace.jsx+++ b/src/ui/client/EpisodeWorkspace.jsx@@ -1,4 +1,17 @@import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';+import {+ Check,+ Heart as HeartGlyph,+ MessageCircle,+ Bookmark as BookmarkGlyph,+ Forward,+ Music,+ User as UserGlyph,+ Search as SearchGlyph,+ Home as HomeGlyph,+ Users as UsersGlyph,+ Inbox,+} from 'lucide-react';import CopyButton from './CopyButton';const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;@@ -56,8 +69,8 @@ const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(return { lastEvent, connected };}- const CheckIcon = () => (<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2.5 6L5 8.5L9.5 3.5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>);- const CheckSmall = ({ color = 'var(--green)' }) => (<svg width="10" height="10" viewBox="0 0 12 12" fill="none"><path d="M2.5 6L5 8.5L9.5 3.5" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" /></svg>);+ const CheckIcon = () => <Check size={12} color="#fff" strokeWidth={2.5} />;+ const CheckSmall = ({ color = 'var(--green)' }) => <Check size={10} color={color} strokeWidth={3} />;const PREVIEW_SCALE = 0.27;const px = (n) => Math.round(n * PREVIEW_SCALE);@@ -126,53 +139,17 @@ const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(function TikTokWireframe({ activeClip, captionStyle }) {- const Heart = () => (- <svg width="28" height="28" viewBox="0 0 24 24" fill="#fff">- <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>- </svg>- );- const Comment = () => (- <svg width="28" height="28" viewBox="0 0 24 24" fill="#fff">- <path d="M20 2H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3l5 4 5-4h3a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z"/>- </svg>- );- const Bookmark = () => (- <svg width="24" height="28" viewBox="0 0 24 24" fill="#fff">- <path d="M17 3H7a2 2 0 0 0-2 2v17l7-3.5L19 22V5a2 2 0 0 0-2-2z"/>- </svg>- );- const Share = () => (- <svg width="28" height="28" viewBox="0 0 24 24" fill="#fff">- <path d="M22 12L12 4v5c-7 0-10 4-10 11 2-4 5-6 10-6v5l10-7z"/>- </svg>- );- const MusicNote = () => (- <svg width="11" height="11" viewBox="0 0 24 24" fill="#fff">- <path d="M9 17V5l12-2v12a4 4 0 1 1-2-3.46V6.18L11 7.82V19a4 4 0 1 1-2-3.46z"/>- </svg>- );- const Person = () => (- <svg viewBox="0 0 24 24" fill="#fff">- <path d="M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zm0 2c-4 0-8 2-8 6v2h16v-2c0-4-4-6-8-6z"/>- </svg>- );- const Search = () => (- <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ width: '100%', height: '100%' }}>- <circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.5" y2="16.5"/>- </svg>- );- const NavHome = () => (- <svg viewBox="0 0 24 24" fill="#fff" className="tt-nav-icon"><path d="M3 11l9-8 9 8v10h-6v-6h-6v6H3z"/></svg>- );- const NavFriends = () => (- <svg viewBox="0 0 24 24" fill="#fff" className="tt-nav-icon"><circle cx="9" cy="8" r="4"/><circle cx="17" cy="9" r="3"/><path d="M2 20c0-4 4-6 7-6s7 2 7 6v1H2v-1zm14-5c2 0 6 1 6 5v1h-6"/></svg>- );- const NavInbox = () => (- <svg viewBox="0 0 24 24" fill="#fff" className="tt-nav-icon"><path d="M3 6h18l-2 8h-7l-2 3-2-3H5z"/></svg>- );- const NavProfile = () => (- <svg viewBox="0 0 24 24" fill="#fff" className="tt-nav-icon"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-5 4-7 8-7s8 2 8 7"/></svg>- );+ const Heart = () => <HeartGlyph size={28} fill="#fff" strokeWidth={0} />;+ const Comment = () => <MessageCircle size={28} fill="#fff" strokeWidth={0} />;+ const Bookmark = () => <BookmarkGlyph size={26} fill="#fff" strokeWidth={0} />;+ const Share = () => <Forward size={28} color="#fff" fill="#fff" strokeWidth={1.5} />;+ const MusicNote = () => <Music size={11} color="#fff" strokeWidth={2.5} />;+ const Person = () => <UserGlyph fill="#fff" strokeWidth={0} style={{ width: '100%', height: '100%' }} />;+ const Search = () => <SearchGlyph color="#fff" strokeWidth={2.2} style={{ width: '100%', height: '100%' }} />;+ const NavHome = () => <HomeGlyph className="tt-nav-icon" fill="#fff" color="#fff" strokeWidth={1.5} />;+ const NavFriends = () => <UsersGlyph className="tt-nav-icon" fill="#fff" color="#fff" strokeWidth={1.5} />;+ const NavInbox = () => <Inbox className="tt-nav-icon" color="#fff" strokeWidth={2.2} />;+ const NavProfile = () => <UserGlyph className="tt-nav-icon" fill="#fff" color="#fff" strokeWidth={1.5} />;const fmtCount = (n) => {if (n >= 100000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'K';if (n >= 1000) return (n / 1000).toFixed(1).replace(/\.0$/, '') + 'K';diff --git a/src/ui/client/Layout.tsx b/src/ui/client/Layout.tsxindex 1bb8d41..be9c231 100644--- a/src/ui/client/Layout.tsx+++ b/src/ui/client/Layout.tsx@@ -1,22 +1,32 @@import React from "react";import { NavLink, Link, Outlet } from "react-router-dom";+import {+ LayoutGrid,+ Play,+ FileText,+ Image,+ BookOpen,+ Settings,+ Plug,+ Terminal,+ BarChart3,+} from "lucide-react";-const icons: Record<string, React.ReactNode> = {- library: <path d="M3 5h7v14H3zM14 5h7v9h-7z" />,- episode: <path d="M5 3l14 9-14 9z" />,- thumbnail: <path d="M3 4h18v16H3z M3 15l5-4 4 3 4-4 5 4" />,- knowledge: <path d="M4 5a2 2 0 0 1 2-2h12v18H6a2 2 0 0 1-2-2z M9 3v18" />,- config: <path d="M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z M19 12a7 7 0 0 0-.1-1l2-1.6-2-3.4-2.4 1a7 7 0 0 0-1.7-1L14.5 2h-5l-.3 2.9a7 7 0 0 0-1.7 1l-2.4-1-2 3.4L2.1 11a7 7 0 0 0 0 2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 1.7 1l.3 2.9h5l.3-2.9a7 7 0 0 0 1.7-1l2.4 1 2-3.4-2-1.6a7 7 0 0 0 .1-1z" />,- integrations: <path d="M10 3v6M14 3v6M7 9h10v3a5 5 0 0 1-10 0z M11 17v4" />,- analytics: <path d="M4 20V10M10 20V4M16 20v-7M22 20H2" />,+const icons: Record<string, typeof LayoutGrid> = {+ library: LayoutGrid,+ episode: Play,+ content: FileText,+ thumbnail: Image,+ knowledge: BookOpen,+ config: Settings,+ integrations: Plug,+ mcp: Terminal,+ analytics: BarChart3,};function Icon({ name }: { name: string }) {- return (- <svg className="ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">- {icons[name]}- </svg>- );+ const Glyph = icons[name];+ return <Glyph className="ico" strokeWidth={1.8} />;}export default function Layout() {@@ -30,13 +40,14 @@ export default function Layout() {<div className="sidebar-section">Studio</div><NavLink to="/" end className="sidebar-link"><Icon name="library" /> Library</NavLink><NavLink to="/episode" className="sidebar-link"><Icon name="episode" /> New episode</NavLink>- <NavLink to="/thumbnail" className="sidebar-link"><Icon name="thumbnail" /> Thumbnail</NavLink>+ <NavLink to="/content" className="sidebar-link"><Icon name="content" /> Content</NavLink>+ <NavLink to="/thumbnails" className="sidebar-link"><Icon name="thumbnail" /> Thumbnails</NavLink><div className="sidebar-section">Workspace</div><NavLink to="/knowledge" className="sidebar-link"><Icon name="knowledge" /> Knowledge</NavLink><NavLink to="/config" className="sidebar-link"><Icon name="config" /> Config</NavLink><NavLink to="/integrations" className="sidebar-link"><Icon name="integrations" /> Integrations</NavLink>- <NavLink to="/mcp" className="sidebar-link"><Icon name="config" /> MCP setup</NavLink>+ <NavLink to="/mcp" className="sidebar-link"><Icon name="mcp" /> MCP setup</NavLink><div className="sidebar-section">Insights</div><NavLink to="/analytics" className="sidebar-link"><Icon name="analytics" /> Analytics</NavLink>diff --git a/src/ui/client/ThumbnailStudio.tsx b/src/ui/client/ThumbnailStudio.tsxnew file mode 100644index 0000000..720c8f3--- /dev/null+++ b/src/ui/client/ThumbnailStudio.tsx@@ -0,0 +1,202 @@+import React, { useRef, useState } from "react";+import { api, upload, basename, labelStyle } from "./lib";+import ThumbnailTemplate from "./ThumbnailTemplate";++const img = (p: string, bust: number) => `/api/image?path=${encodeURIComponent(p)}&t=${bust}`;+const isImage = (name: string) => /\.(png|jpe?g|webp)$/i.test(name);++export default function ThumbnailStudio() {+ const fileRef = useRef<HTMLInputElement>(null);+ const [title, setTitle] = useState("");+ const [video, setVideo] = useState<{ path: string; name: string } | null>(null);+ const [startS, setStartS] = useState("");+ const [endS, setEndS] = useState("");+ const [line1, setLine1] = useState("");+ const [line2, setLine2] = useState("");+ const [textOpts, setTextOpts] = useState<[string, string][]>([]);+ const [frameOpts, setFrameOpts] = useState<any[]>([]);+ const [selFrame, setSelFrame] = useState<{ path: string; info?: any } | null>(null);+ const [preview, setPreview] = useState<string | null>(null);+ const [busy, setBusy] = useState<string | null>(null);+ const [msg, setMsg] = useState<string | null>(null);+ const [bust, setBust] = useState(1);+ const [editingTemplate, setEditingTemplate] = useState(false);++ if (editingTemplate) {+ return <ThumbnailTemplate onBack={() => { setEditingTemplate(false); setBust(Date.now()); }} />;+ }++ const browse = async () => {+ setBusy("browse"); setMsg(null);+ try {+ const r = await api("/browse-file");+ if (r.file_path) setVideo({ path: r.file_path, name: r.filename || basename(r.file_path) });+ } catch (e: any) {+ if (e.message !== "cancelled") setMsg(`Browse failed: ${e.message}`);+ } finally { setBusy(null); }+ };++ const uploadFile = async (f: File) => {+ setBusy("upload"); setMsg(null);+ try {+ const fd = new FormData();+ fd.append("file", f);+ const r = await upload<any>("/upload", fd);+ if (!r.file_path) throw new Error("upload failed");+ if (isImage(f.name)) {+ setSelFrame({ path: r.file_path });+ setPreview(null);+ setMsg("Image set as the thumbnail background");+ } else {+ setVideo({ path: r.file_path, name: f.name });+ }+ } catch (e: any) { setMsg(`Upload failed: ${e.message}`); } finally { setBusy(null); }+ };++ const loadOptions = async () => {+ if (!title.trim()) { setMsg("Enter a title first, headlines are written from it"); return; }+ setBusy("options"); setMsg(null);+ try {+ const r = await api("/thumbnail-studio/options", {+ method: "POST",+ body: JSON.stringify({+ title,+ video_path: video?.path,+ start: startS !== "" ? Number(startS) : undefined,+ end: endS !== "" ? Number(endS) : undefined,+ }),+ });+ setTextOpts(r.texts || []);+ setFrameOpts(r.frames || []);+ setBust(Date.now());+ if ((r.frames || []).length) setSelFrame({ path: r.frames[0].path, info: r.frames[0] });+ if (!(r.texts || []).length && !(r.frames || []).length) setMsg("No options. Is the AI CLI installed? Pick a video for frame options.");+ } catch (e: any) { setMsg(`Options failed: ${e.message}`); } finally { setBusy(null); }+ };++ const render = async () => {+ if (!selFrame) { setMsg("Select a frame or upload an image first"); return; }+ setBusy("render"); setMsg(null);+ try {+ const r = await api("/thumbnail-studio/render", {+ method: "POST",+ body: JSON.stringify({+ title,+ line1: line1 || undefined,+ line2: line2 || undefined,+ frame_path: selFrame.path,+ frame_info: selFrame.info,+ }),+ });+ if (!r.path) throw new Error("no thumbnail produced");+ setPreview(r.path);+ setBust(Date.now());+ setMsg("Thumbnail generated");+ } catch (e: any) { setMsg(`Generate failed: ${e.message}`); } finally { setBusy(null); }+ };++ return (+ <div className="app">+ <div className="header">+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>+ <h1 style={{ margin: 0 }}>Thumbnail studio</h1>+ <button className="btn btn-ghost btn-sm" onClick={() => setEditingTemplate(true)}>Edit template</button>+ </div>+ </div>++ <div className="section">+ <label style={labelStyle}>Source</label>+ <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>+ <button className="btn btn-ghost btn-sm" onClick={browse} disabled={busy !== null}>+ {busy === "browse" ? <div className="spinner sm" /> : "Browse video…"}+ </button>+ <button className="btn btn-ghost btn-sm" onClick={() => fileRef.current?.click()} disabled={busy !== null}>+ {busy === "upload" ? <div className="spinner sm" /> : "Upload video or image"}+ </button>+ <input+ ref={fileRef}+ type="file"+ accept=".mp4,.mov,.mkv,.webm,.png,.jpg,.jpeg"+ style={{ display: "none" }}+ onChange={(e) => e.target.files?.[0] && uploadFile(e.target.files[0])}+ />+ {video && <span style={{ fontSize: 12, color: "var(--text2)" }}>{video.name}</span>}+ </div>+ <div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center", flexWrap: "wrap" }}>+ <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title to write headlines from" style={{ flex: "1 1 280px", fontSize: 14, padding: "10px 13px" }} />+ <input type="number" min={0} value={startS} onChange={(e) => setStartS(e.target.value)} placeholder="Start (s)" style={{ width: 90, fontSize: 13, padding: "9px 10px" }} />+ <input type="number" min={0} value={endS} onChange={(e) => setEndS(e.target.value)} placeholder="End (s)" style={{ width: 90, fontSize: 13, padding: "9px 10px" }} />+ <button className="btn btn-primary btn-sm" onClick={loadOptions} disabled={busy !== null}>+ {busy === "options" ? <><div className="spinner sm" /> Finding options…</> : (textOpts.length || frameOpts.length ? "Refresh options" : "Get options")}+ </button>+ </div>+ </div>++ {msg && <div className="set-note ok" style={{ wordBreak: "break-word" }}>{msg}</div>}++ <div className="section">+ <label style={labelStyle}>Thumbnail</label>+ <div className="thumb-edit">+ <div className="thumb-edit-preview">+ <div className="thumb-stage">+ {busy === "render" ? (+ <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", gap: 8, color: "var(--text2)", fontSize: 11 }}>+ <div className="spinner sm" /> Rendering…+ </div>+ ) : preview ? (+ <img key={`gen-${bust}`} src={img(preview, bust)} alt="thumbnail" />+ ) : selFrame ? (+ <img src={img(selFrame.path, bust)} alt="selected frame" />+ ) : (+ <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: "var(--text3)", fontSize: 11, textAlign: "center", padding: 12 }}>+ Pick a source and get options, or upload an image+ </div>+ )}+ </div>+ </div>+ <div className="thumb-edit-controls">+ <input type="text" value={line1} onChange={(e) => setLine1(e.target.value)} placeholder="Line 1" style={{ width: "100%", fontSize: 14, padding: "9px 12px" }} />+ <input type="text" value={line2} onChange={(e) => setLine2(e.target.value)} placeholder="Line 2 (highlighted)" style={{ width: "100%", fontSize: 14, padding: "9px 12px", marginTop: 8 }} />+ <div className="set-actions" style={{ marginTop: 10 }}>+ <button className="btn btn-primary btn-sm" onClick={render} disabled={busy !== null || !selFrame}>+ {busy === "render" ? <div className="spinner sm" /> : (preview ? "Regenerate" : "Generate")}+ </button>+ {preview && (+ <a className="btn btn-ghost btn-sm" href={img(preview, bust)} download="thumbnail.png" style={{ textDecoration: "none" }}>+ Download+ </a>+ )}+ </div>+ <div style={{ fontSize: 11, color: "var(--text3)", marginTop: 8 }}>Leave line 1 and line 2 empty to auto-write the text.</div>+ </div>+ </div>++ {textOpts.length > 0 && (+ <div style={{ marginTop: 16 }}>+ <div style={{ fontSize: 11, color: "var(--text3)", marginBottom: 6 }}>Text options · click to use</div>+ <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>+ {textOpts.map(([l1, l2], i) => (+ <button key={i} className={`title-option stream-in ${line1 === l1 && line2 === l2 ? "selected" : ""}`} style={{ animationDelay: `${i * 40}ms` }} onClick={() => { setLine1(l1); setLine2(l2); }}>+ <strong>{l1}</strong>{l2 ? ` · ${l2}` : ""}+ </button>+ ))}+ </div>+ </div>+ )}++ {frameOpts.length > 0 && (+ <div style={{ marginTop: 16 }}>+ <div style={{ fontSize: 11, color: "var(--text3)", marginBottom: 6 }}>Frame options · click to select</div>+ <div className="thumb-variations">+ {frameOpts.map((f, i) => (+ <button key={i} className={`thumb-variation stream-in ${selFrame?.path === f.path ? "selected" : ""}`} style={{ animationDelay: `${i * 40}ms` }} onClick={() => setSelFrame({ path: f.path, info: f })} disabled={busy !== null}>+ <img src={img(f.path, bust)} alt="" />+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/src/ui/client/ThumbnailTemplate.tsx b/src/ui/client/ThumbnailTemplate.tsxindex 6938fd7..63accc5 100644--- a/src/ui/client/ThumbnailTemplate.tsx+++ b/src/ui/client/ThumbnailTemplate.tsx@@ -56,7 +56,7 @@ function padToPreview(pad: any): string {return parts.join(" ") || "8px 12px";}-export default function ThumbnailTemplate() {+export default function ThumbnailTemplate({ onBack }: { onBack?: () => void }) {const [cfg, setCfg] = useState<Cfg | null>(null);const [busy, setBusy] = useState<string | null>(null);const [msg, setMsg] = useState<string | null>(null);@@ -145,7 +145,12 @@ export default function ThumbnailTemplate() {return (<div className="app">- <div className="header"><h1>Thumbnail template</h1></div>+ <div className="header">+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>+ <h1 style={{ margin: 0 }}>Edit template</h1>+ {onBack && <button className="btn btn-ghost btn-sm" onClick={onBack}>← Back to generator</button>}+ </div>+ </div><div className="tmpl-layout"><div className="tmpl-preview">diff --git a/src/ui/client/icons.tsx b/src/ui/client/icons.tsxindex 678ef12..273ce82 100644--- a/src/ui/client/icons.tsx+++ b/src/ui/client/icons.tsx@@ -1,19 +1,13 @@import React from "react";+import { Play, Pause, ChevronLeft, ChevronRight, SkipBack, SkipForward, X, Trash2 } from "lucide-react";-function Svg({ children, size = 15 }: { children: React.ReactNode; size?: number }) {- return (- <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"- strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: "block" }}>- {children}- </svg>- );-}+const block = { display: "block" } as const;-export const PlayIcon = () => <Svg><path d="M7 4.5v15l12-7.5z" fill="currentColor" stroke="none" /></Svg>;-export const PauseIcon = () => <Svg><path d="M8 4v16M16 4v16" /></Svg>;-export const FrameBackIcon = () => <Svg><path d="M15 6l-6 6 6 6" /></Svg>;-export const FrameForwardIcon = () => <Svg><path d="M9 6l6 6-6 6" /></Svg>;-export const CutBackIcon = () => <Svg><path d="M18 5v14l-9-7z" fill="currentColor" stroke="none" /><path d="M6 5v14" /></Svg>;-export const CutForwardIcon = () => <Svg><path d="M6 5v14l9-7z" fill="currentColor" stroke="none" /><path d="M18 5v14" /></Svg>;-export const CloseIcon = () => <Svg><path d="M6 6l12 12M18 6L6 18" /></Svg>;-export const TrashIcon = ({ size = 14 }: { size?: number }) => <Svg size={size}><path d="M4 7h16M10 11v6M14 11v6M5 7l1 13h12l1-13M9 7V4h6v3" /></Svg>;+export const PlayIcon = () => <Play size={15} style={block} fill="currentColor" strokeWidth={0} />;+export const PauseIcon = () => <Pause size={15} style={block} />;+export const FrameBackIcon = () => <ChevronLeft size={15} style={block} />;+export const FrameForwardIcon = () => <ChevronRight size={15} style={block} />;+export const CutBackIcon = () => <SkipBack size={15} style={block} fill="currentColor" />;+export const CutForwardIcon = () => <SkipForward size={15} style={block} fill="currentColor" />;+export const CloseIcon = () => <X size={15} style={block} />;+export const TrashIcon = ({ size = 14 }: { size?: number }) => <Trash2 size={size} style={block} />;diff --git a/src/ui/client/index.html b/src/ui/client/index.htmlindex 163016a..b7f909b 100644--- a/src/ui/client/index.html+++ b/src/ui/client/index.html@@ -6,7 +6,7 @@<meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Podcli - AI podcast clip studio</title><meta name="robots" content="noindex,nofollow">- <meta name="theme-color" content="#08080a" media="(prefers-color-scheme: dark)">+ <meta name="theme-color" content="#141210" media="(prefers-color-scheme: dark)"><meta name="color-scheme" content="dark light"><link rel="icon" type="image/png" href="/podcli-icon.png"><link rel="apple-touch-icon" href="/podcli-icon.png">diff --git a/src/ui/client/main.tsx b/src/ui/client/main.tsxindex 77e2f62..bc1ce28 100644--- a/src/ui/client/main.tsx+++ b/src/ui/client/main.tsx@@ -1,11 +1,12 @@import React from "react";import { createRoot } from "react-dom/client";-import { BrowserRouter, Routes, Route } from "react-router-dom";+import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";import Layout from "./Layout";import StudioHome from "./StudioHome";import ClipDetail from "./ClipDetail";import EpisodeWorkspace from "./EpisodeWorkspace";-import ThumbnailTemplate from "./ThumbnailTemplate";+import ThumbnailStudio from "./ThumbnailStudio";+import ContentStudio from "./ContentStudio";import AnalyticsPage from "./AnalyticsPage";import KnowledgePage from "./KnowledgePage";import ConfigPage from "./ConfigPage";@@ -19,7 +20,9 @@ createRoot(document.getElementById("root")!).render(<Route element={<Layout />}><Route path="/" element={<StudioHome />} /><Route path="/episode" element={<EpisodeWorkspace />} />- <Route path="/thumbnail" element={<ThumbnailTemplate />} />+ <Route path="/content" element={<ContentStudio />} />+ <Route path="/thumbnails" element={<ThumbnailStudio />} />+ <Route path="/thumbnail" element={<Navigate to="/thumbnails" replace />} /><Route path="/clip/:id" element={<ClipDetail />} /><Route path="/knowledge" element={<KnowledgePage />} /><Route path="/config" element={<ConfigPage />} />diff --git a/src/ui/public/css/styles.css b/src/ui/public/css/styles.cssindex ed13785..045c988 100644--- a/src/ui/public/css/styles.css+++ b/src/ui/public/css/styles.css@@ -1,14 +1,14 @@/* ─── podcli — Shared Styles ─── */:root {- --bg: #08080a;- --bg2: #0e0e11;- --surface: #131316;- --surface2: #1a1a1f;- --surface3: #222228;- --border: #1b1b22;- --border-hover: #2b2833;- --border-h: #2b2833;+ --bg: #141210;+ --bg2: #191613;+ --surface: #1e1b17;+ --surface2: #26221d;+ --surface3: #2f2a24;+ --border: #2b2620;+ --border-hover: #3d362d;+ --border-h: #3d362d;--text: #e8e6df;--text2: #9a9388;--text3: #8b8579;@@ -29,7 +29,7 @@--blue-subtle: rgba(96, 165, 250, 0.08);--blue-border: rgba(96, 165, 250, 0.18);--yellow: #facc15;- --glass-bg: rgba(22, 20, 24, 0.55);+ --glass-bg: rgba(26, 23, 20, 0.55);--glass-border: rgba(255, 255, 255, 0.055);--glass-hi: rgba(255, 255, 255, 0.05);--radius: 12px;@@ -78,7 +78,7 @@ body {.img-outline { box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.07); }/* ─── Layout ─── */-.app { max-width: 1080px; margin: 0 auto; padding: 48px 32px 96px; background: #0D0B0D; }+.app { max-width: 1080px; margin: 0 auto; padding: 48px 32px 96px; }.header { margin-bottom: 36px; }.logo { font-size: 13px; font-weight: 700; letter-spacing: 1.2px; color: var(--text3); margin-bottom: 10px; text-transform: uppercase; text-decoration: none; }.logo span { color: var(--accent); }@@ -453,7 +453,7 @@ select {box-shadow: 0 5px #1a1a1f, 0 11px 18px -5px #000000d9,0 0 0 1px #ffffff14, inset 0 1px #ffffff24;}-.btn-ghost:hover:not(:disabled) { background: #2c2c34; }+.btn-ghost:hover:not(:disabled) { background: var(--surface3); }.btn-ghost:active:not(:disabled) { transform: translateY(4px); box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.09), inset 0 1px 0 rgba(255, 255, 255, 0.10); }.btn-ghost:disabled { opacity: 0.4; cursor: not-allowed; }.btn-danger {@@ -833,7 +833,7 @@ select {}.card-desc { font-size: 13px; color: var(--text2); line-height: 1.6; margin-bottom: 16px; }.code-block {- position: relative; background: #0a0a0c; border: 1px solid var(--border);+ position: relative; background: var(--bg); border: 1px solid var(--border);border-radius: var(--radius-sm); overflow: hidden;}.code-header {@@ -1314,3 +1314,13 @@ p, li, figcaption, blockquote, .subtitle, .file-preview, .card-desc, .int-row .d/* ── Reframe: camera-switch (cut) markers ── */.rf-cut { position: absolute; top: 0; bottom: 0; width: 2px; background: #facc15; opacity: 0.75; transform: translateX(-1px); pointer-events: none; }++/* ── Streamed content reveal ── */+.stream-in { animation: stream-in 0.24s var(--ease-out) both; }+@keyframes stream-in {+ from { opacity: 0; transform: translateY(4px); filter: blur(6px); }+ to { opacity: 1; transform: none; filter: none; }+}+@media (prefers-reduced-motion: reduce) {+ .stream-in { animation: none; }+}diff --git a/src/ui/web-server.ts b/src/ui/web-server.tsindex 540d3e5..0c97c70 100644--- a/src/ui/web-server.ts+++ b/src/ui/web-server.ts@@ -1513,10 +1513,8 @@ app.post("/api/clips/:id/thumbnail/render", async (req, res) => {if (!frame_path) { res.status(400).json({ error: "select a frame first" }); return; }// Only allow frames podcli itself produced (candidate frames) or the user uploaded —// never an arbitrary server path passed through to the renderer.- const resolvedFrame = resolve(String(frame_path));- const frameRoots = [resolve(join(paths.output, "thumbnails", String(clip.id))), resolve(uploadDir)];- const inAllowedRoot = frameRoots.some((root) => resolvedFrame === root || resolvedFrame.startsWith(root + path.sep));- if (!inAllowedRoot || !existsSync(resolvedFrame)) { res.status(400).json({ error: "invalid frame" }); return; }+ const resolvedFrame = resolveFrameInRoots(frame_path, [join(paths.output, "thumbnails", String(clip.id)), uploadDir]);+ if (!resolvedFrame) { res.status(400).json({ error: "invalid frame" }); return; }const outDir = join(paths.output, "thumbnails", String(clip.id));await mkdir(outDir, { recursive: true });const out = join(outDir, `thumb_${uuidv4().slice(0, 8)}.png`);@@ -1540,6 +1538,73 @@ app.post("/api/clips/:id/thumbnail/render", async (req, res) => {res.json({ ok: true, preview_path: outPath });});+// --- Thumbnail studio (standalone thumbnails, no clip required) ---++const thumbStudioDir = join(paths.output, "thumbnails", "studio");++// realpath both sides so a symlink planted inside an allowed root can't point+// the renderer at a file outside it.+function resolveFrameInRoots(framePath: unknown, roots: string[]): string | null {+ let real: string;+ try {+ real = realpathSync(path.resolve(String(framePath)));+ } catch {+ return null;+ }+ const realRoot = (p: string) => {+ try { return realpathSync(p); } catch { return resolve(p); }+ };+ const ok = roots.map(realRoot).some((root) => real === root || real.startsWith(root + path.sep));+ return ok ? real : null;+}++app.post("/api/thumbnail-studio/options", async (req, res) => {+ const { title, video_path, start, end, texts, frames } = req.body || {};+ if (!title || !String(title).trim()) { res.status(400).json({ error: "title is required" }); return; }+ const clamp = (v: any, d: number) => Math.min(Math.max(parseInt(String(v)) || d, 1), 8);+ const args = [+ "thumbnail-options", String(title),+ "--output", join(thumbStudioDir, "frames"),+ "--texts", String(clamp(texts, 6)),+ "--frames", String(clamp(frames, 6)),+ ];+ if (video_path) {+ // Frames come only from files the user explicitly uploaded/selected this+ // session — never an arbitrary server path passed to the extractor.+ let video: string;+ try { video = realpathSync(path.resolve(String(video_path))); } catch { res.status(400).json({ error: "video not found" }); return; }+ if (!allowedSourcePaths.has(video)) { res.status(400).json({ error: "unknown video, upload or select it first" }); return; }+ args.push("--video", video);+ if (start != null && start !== "") args.push("--start", String(Math.max(0, Number(start) || 0)));+ if (end != null && end !== "") args.push("--end", String(Math.max(0, Number(end) || 0)));+ }+ const r = await runCli(args);+ if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "options failed" }); return; }+ const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));+ try { res.json(JSON.parse(jsonLine || "{}")); } catch { res.status(500).json({ error: "bad options output" }); }+});++app.post("/api/thumbnail-studio/render", async (req, res) => {+ const { title, line1, line2, frame_path, frame_info } = req.body || {};+ if (!title || !String(title).trim()) { res.status(400).json({ error: "title is required" }); return; }+ if (!frame_path) { res.status(400).json({ error: "select a frame first" }); return; }+ const resolvedFrame = resolveFrameInRoots(frame_path, [thumbStudioDir, uploadDir]);+ if (!resolvedFrame) { res.status(400).json({ error: "invalid frame" }); return; }+ await mkdir(thumbStudioDir, { recursive: true });+ const out = join(thumbStudioDir, `thumb_${uuidv4().slice(0, 8)}.png`);+ const args = ["thumbnail-render", String(title), "--frame", resolvedFrame, "--output", out];+ if (line1) args.push("--line1", String(line1));+ if (line2) args.push("--line2", String(line2));+ if (frame_info) args.push("--frame-info", JSON.stringify(frame_info));+ const r = await runCli(args);+ if (r.code !== 0) { res.status(400).json({ error: stripAnsi(r.stderr || r.stdout) || "render failed" }); return; }+ const jsonLine = r.stdout.trim().split("\n").reverse().find((l) => l.trim().startsWith("{"));+ let outPath = "";+ try { outPath = JSON.parse(jsonLine || "{}").path || ""; } catch { /* no path */ }+ if (!outPath || !existsSync(outPath)) { res.status(500).json({ error: "no thumbnail produced" }); return; }+ res.json({ ok: true, path: outPath });+});+// --- Secrets/settings stored in the global .env (e.g. HF_TOKEN) ---app.get("/api/settings", async (_req, res) => {@@ -2351,11 +2416,16 @@ app.post("/api/generate-content", async (req, res) => {const result = await executor.execute("generate_content",{ clip, transcript_segments: segs },- (event) =>+ (event) => {+ if (event.partial) {+ broadcastSSE("content-partial", { stream_id: clip?.id ? String(clip.id) : null, partial: event.partial });+ return;+ }broadcastSSE("job-update", {progress: event.percent,message: event.message,- }),+ });+ },);const data: any = result.data || {};@@ -2379,6 +2449,80 @@ app.post("/api/generate-content", async (req, res) => {}});+// --- Content studio (transcript-first generation, no clip required) ---++const CONTENT_MAX_SEGMENTS = 30;++// Long transcripts get sampled evenly so titles reflect the whole episode,+// not just the opening minutes (the generator reads at most 30 segments).+function packTranscriptText(text: string): Array<{ start: number; text: string }> {+ const clean = text.replace(/\r/g, "").trim();+ const segChars = 1000;+ const stride = Math.max(segChars, Math.floor(clean.length / CONTENT_MAX_SEGMENTS));+ const segs: Array<{ start: number; text: string }> = [];+ for (let off = 0; off < clean.length && segs.length < CONTENT_MAX_SEGMENTS; off += stride) {+ const chunk = clean.slice(off, off + segChars).trim();+ if (chunk) segs.push({ start: segs.length, text: chunk });+ }+ return segs;+}++function condenseSegments(segments: Array<{ start?: number; text?: string }>): Array<{ start: number; text: string }> {+ const clean = segments+ .map((s) => ({ start: Number(s.start) || 0, text: String(s.text || "").trim() }))+ .filter((s) => s.text);+ if (clean.length <= CONTENT_MAX_SEGMENTS) return clean;+ const per = Math.ceil(clean.length / CONTENT_MAX_SEGMENTS);+ const out: Array<{ start: number; text: string }> = [];+ for (let i = 0; i < clean.length; i += per) {+ const group = clean.slice(i, i + per);+ out.push({ start: group[0].start, text: group.map((s) => s.text).join(" ").slice(0, 1200) });+ }+ return out;+}++app.post("/api/content-studio/generate", async (req, res) => {+ const { title, transcript_text, mode, stream_id } = req.body || {};+ let segs: Array<{ start: number; text: string }>;+ if (typeof transcript_text === "string" && transcript_text.trim()) {+ segs = packTranscriptText(transcript_text);+ } else if (uiState.transcript?.segments?.length) {+ segs = condenseSegments(uiState.transcript.segments);+ } else {+ res.status(400).json({ error: "paste a transcript or load an episode first" });+ return;+ }+ const episode = mode === "episode";+ const lastStart = segs.length ? segs[segs.length - 1].start : 0;+ const clip = {+ title: String(title || "").trim() || "Untitled episode",+ start_second: 0,+ end_second: lastStart + 60,+ content_type: episode ? "full episode" : "highlight",+ };+ try {+ const result = await executor.execute(+ "generate_content",+ { clip, transcript_segments: segs, mode: episode ? "episode" : "shorts" },+ (event) => {+ if (event.partial) {+ broadcastSSE("content-partial", { stream_id: stream_id || null, partial: event.partial });+ return;+ }+ broadcastSSE("job-update", {+ progress: event.percent,+ message: event.message,+ });+ },+ );+ res.json(result.data || {});+ } catch (err: any) {+ res.status(500).json({+ error: `Content generation failed: ${err.message?.substring(0, 200)}`,+ });+ }+});+// --- MCP ↔ UI Bridge Endpoints ---/**