Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

14.4 KB
Raw Blame
import React, { useEffect, useState } from "react";
import { PageHeader } from "./Page";
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";

type ContentMode = "episode" | "shorts";

const CONTENT_MODES: readonly ContentMode[] = ["episode", "shorts"];

export default function ContentStudio() {
  const [title, setTitle] = useState("");
  const [transcript, setTranscript] = useState("");
  const [mode, setMode] = useState<ContentMode>("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);
  const [customReq, setCustomReq] = useState("");
  const [customBusy, setCustomBusy] = useState(false);
  const [customOut, setCustomOut] = useState<string | null>(null);
  const [regenField, setRegenField] = useState<string | null>(null);
  const [regenNote, setRegenNote] = useState("");
  const [regenBusy, setRegenBusy] = useState(false);
  const isBusy = busy || customBusy || regenBusy;

  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 persist = (r: ContentResult) => {
    try {
      localStorage.setItem(STORE, JSON.stringify({ title, mode, result: r }));
    } catch {}
  };

  const copy = (text: string) => {
    navigator.clipboard?.writeText(text).then(() => {
      setCopied(text);
      setTimeout(() => setCopied(null), 1500);
    });
  };

  const generate = async () => {
    if (isBusy) return;

    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) => {
      if (!(e instanceof MessageEvent)) return;

      try {
        const d = JSON.parse(e.data);

        if (d.stream_id === streamId && d.partial) setResult(d.partial);
      } catch {}
    });
    es.addEventListener("job-update", (e) => {
      if (!(e instanceof MessageEvent)) return;

      try {
        const d = JSON.parse(e.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);
      persist(r);
    } catch (e: any) {
      setMsg(`Generation failed: ${e.message}`);
    } finally {
      es.close();
      setBusy(false);
      setStage(null);
    }
  };

  const runCustom = async (instruction: string): Promise<string | null> => {
    const r = await api<{ text?: string; error?: string }>("/content-studio/custom", {
      method: "POST",
      body: JSON.stringify({ instruction, transcript_text: transcript || undefined, mode }),
    });

    if (r.error) throw new Error(r.error);

    return r.text?.trim() || null;
  };

  const askCustom = async () => {
    if (!customReq.trim() || isBusy) return;
    setCustomBusy(true);
    setCustomOut(null);
    setMsg(null);

    try {
      setCustomOut((await runCustom(customReq.trim())) || "No output.");
    } catch (e: any) {
      setMsg(`Custom request failed: ${e.message}`);
    } finally {
      setCustomBusy(false);
    }
  };

  const REGEN = new Map([
    ["titles", "Give me 8 fresh YouTube title options for this content, one per line, numbered 1-8. Return only the titles."],
    ["description", "Rewrite the YouTube description for this content. Return only the description text, no labels."],
    ["tags", "Give a comma-separated list of 10-15 YouTube tags for this content. Return only the tags."],
    ["hashtags", "Give 5 relevant hashtags for this content. Return only the hashtags, space-separated."],
  ]);

  const regenerate = async (field: string) => {
    if (isBusy) return;
    setRegenBusy(true);
    setMsg(null);

    try {
      const instruction = `${REGEN.get(field)}${regenNote.trim() ? ` Extra guidance: ${regenNote.trim()}` : ""}`;
      const text = await runCustom(instruction);

      if (!text) throw new Error("empty response");
      const next: ContentResult = { ...result };

      if (field === "titles") {
        next.titles = text
          .split(/\r?\n/)
          .map((l) => l.replace(/^\s*\d+[.)]\s*/, "").trim())
          .filter(Boolean)
          .slice(0, 8);
      } else if (field === "description") next.description = text;
      else if (field === "tags") next.tags = text;
      else if (field === "hashtags") next.hashtags = text;
      setResult(next);
      persist(next);
      setRegenField(null);
      setRegenNote("");
    } catch (e: any) {
      setMsg(`Regenerate failed: ${e.message}`);
    } finally {
      setRegenBusy(false);
    }
  };

  const regenBtn = (field: string) => (
    <button
      className="btn btn-ghost btn-sm"
      style={{ padding: "3px 9px", fontSize: 11 }}
      onClick={() => { setRegenField(regenField === field ? null : field); setRegenNote(""); }}
      disabled={regenBusy}
    >
      Regenerate
    </button>
  );

  const regenInput = (field: string) =>
    regenField === field ? (
      <div style={{ display: "flex", gap: 6, margin: "0 0 10px" }}>
        <input
          value={regenNote}
          onChange={(e) => setRegenNote(e.target.value)}
          placeholder="Optional: how to change it"
          style={{ flex: 1, fontSize: 12 }}
          onKeyDown={(e) => { if (e.key === "Enter") regenerate(field); }}
          autoFocus
        />
        <button className="btn btn-primary btn-sm" onClick={() => regenerate(field)} disabled={regenBusy}>
          {regenBusy ? <div className="spinner sm" /> : "Go"}
        </button>
      </div>
    ) : null;

  const hasTitle = !!(result?.titles?.length || title.trim());

  const previewTitle =
    result?.titles?.[0]?.replace(/^\d+\.\s*/, "").replace(/^["']|["']$/g, "") ||
    title.trim() ||
    "Your title appears here";

  const vertical = mode === "shorts";

  return (
    <div className="app">
      <PageHeader title="Content studio" />

      <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%" }}
            />

            <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={isBusy} title={sessionName ? `Use transcript from ${sessionName}` : "Use the current episode transcript"}>
                  Use current episode
                </button>
              )}
            </div>
            <textarea
              value={transcript}
              onChange={(e) => setTranscript(e.target.value)}
              placeholder="Paste the transcript here"
              style={{ width: "100%", minHeight: 260, lineHeight: 1.6, marginTop: 8, resize: "vertical" }}
            />

            <div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center" }}>
              <select value={mode} onChange={(e) => setMode(CONTENT_MODES.find((m) => m === e.target.value) ?? mode)} 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={isBusy || !transcript.trim()}>
                {busy ? <><div className="spinner sm" /> Generating…</> : "Generate"}
              </button>
            </div>
            {busy && stage && <div className="hint" style={{ marginTop: 10 }}>{stage}</div>}
            {msg && <div className="set-note ok" style={{ marginTop: 10, wordBreak: "break-word" }}>{msg}</div>}
          </div>

          <div className="yt-card">
            <div className="hint" style={{ marginBottom: -2 }}>Thumbnail preview</div>
            <div className={`yt-thumb${vertical ? " vertical" : ""}`}>
              <div className={`yt-thumb-title${hasTitle ? "" : " placeholder"}`}>{previewTitle}</div>
            </div>
          </div>

          <div className="section" style={{ marginTop: 18 }}>
            <label style={labelStyle}>Ask for anything else</label>
            <textarea
              value={customReq}
              onChange={(e) => setCustomReq(e.target.value)}
              placeholder="e.g. Write a LinkedIn post, a Twitter thread, 10 punchier hooks…"
              style={{ width: "100%", minHeight: 78, marginTop: 8, resize: "vertical" }}
            />
            <button
              className="btn btn-primary btn-sm"
              style={{ marginTop: 10 }}
              onClick={askCustom}
              disabled={isBusy || !customReq.trim()}
            >
              {customBusy ? <><div className="spinner sm" /> Generating…</> : "Generate"}
            </button>
            {customOut && (
              <div className="stream-in" style={{ marginTop: 12, borderTop: "1px solid var(--border)", paddingTop: 12 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                  <span className="hint">Result</span>
                  <CopyButton text={customOut} />
                </div>
                <div style={{ fontSize: 13, color: "var(--text2)", lineHeight: 1.6, whiteSpace: "pre-wrap" }}>{customOut}</div>
              </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={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                    <span className="hint">Title options · click to copy</span>
                    {regenBtn("titles")}
                  </div>
                  {regenInput("titles")}
                  <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 className="hint">Description</span>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>{regenBtn("description")}<CopyButton text={result.description} /></div>
                  </div>
                  {regenInput("description")}
                  <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 className="hint">Tags</span>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>{regenBtn("tags")}<CopyButton text={result.tags} /></div>
                  </div>
                  {regenInput("tags")}
                  <div className="meta" style={{ 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 className="hint">Hashtags</span>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>{regenBtn("hashtags")}<CopyButton text={result.hashtags} /></div>
                  </div>
                  {regenInput("hashtags")}
                  <div style={{ fontSize: 12, color: "var(--accent)", lineHeight: 1.6 }}>{result.hashtags}</div>
                </div>
              ) : null}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}