refactor: migrate project from Flask to Next.js with TypeScript, Prisma, and Edge TTS integration

This commit is contained in:
2026-09-03 00:16:04 -07:00
parent 84f79dc5f9
commit f033a6045c
60 changed files with 5340 additions and 2179 deletions
+468
View File
@@ -0,0 +1,468 @@
"use client";
import React, { useEffect, useState } from "react";
import {
Radio,
PlusCircle,
Headphones,
Trash2,
FileText,
Sparkles,
Loader2,
Clock,
ExternalLink,
Volume2,
} from "lucide-react";
import { AudioPlayer } from "@/components/AudioPlayer";
import { TranscriptViewer } from "@/components/TranscriptViewer";
import { TimingCue, VoiceOption } from "@/lib/tts/types";
interface Episode {
id: string;
title: string;
originalContent: string;
mode: string;
status: string;
durationSeconds?: number | null;
audioUrl?: string | null;
timingsJson?: string | null;
createdAt: string;
}
export default function Home() {
const [episodes, setEpisodes] = useState<Episode[]>([]);
const [activeEpisode, setActiveEpisode] = useState<Episode | null>(null);
const [activeTimings, setActiveTimings] = useState<TimingCue[]>([]);
const [currentTime, setCurrentTime] = useState<number>(0);
const [seekTime, setSeekTime] = useState<number | null>(null);
// Form state
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [voice, setVoice] = useState("zh-CN-XiaoxiaoNeural");
const [voices, setVoices] = useState<VoiceOption[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formError, setFormError] = useState("");
const [showCreateForm, setShowCreateForm] = useState(false);
const handleContentChange = (val: string) => {
setContent(val);
if (/[\u4e00-\u9fa5]/.test(val) && voice.startsWith("en-")) {
setVoice("zh-CN-XiaoxiaoNeural");
}
};
// Fetch episodes on mount
const fetchEpisodes = async () => {
try {
const res = await fetch("/api/episodes");
const data = await res.json();
if (data.success && data.episodes) {
setEpisodes(data.episodes);
// Default to first episode if none selected
if (!activeEpisode && data.episodes.length > 0) {
selectEpisode(data.episodes[0]);
}
}
} catch (err) {
console.error("Failed to load episodes:", err);
}
};
// Fetch voices on mount
const fetchVoices = async () => {
try {
const res = await fetch("/api/voices");
const data = await res.json();
if (data.success && data.voices) {
setVoices(data.voices);
}
} catch (err) {
console.error("Failed to load voices:", err);
}
};
useEffect(() => {
fetchEpisodes();
fetchVoices();
}, []);
const selectEpisode = (ep: Episode) => {
setActiveEpisode(ep);
if (ep.timingsJson) {
try {
setActiveTimings(JSON.parse(ep.timingsJson));
} catch {
setActiveTimings([]);
}
} else {
setActiveTimings([]);
}
setCurrentTime(0);
};
const handleCreateEpisode = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim() || !content.trim()) {
setFormError("Please provide both a title and article content.");
return;
}
setIsSubmitting(true);
setFormError("");
try {
const res = await fetch("/api/episodes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
content,
mode: "VERBATIM",
provider: "edge",
voice,
}),
});
const data = await res.json();
if (!res.ok || !data.success) {
throw new Error(data.error || "Synthesis failed");
}
// Reset form
setTitle("");
setContent("");
setShowCreateForm(false);
// Refresh list & select newly created episode
await fetchEpisodes();
if (data.episode) {
selectEpisode(data.episode);
}
} catch (err: any) {
setFormError(err.message || "Failed to generate audio.");
} finally {
setIsSubmitting(false);
}
};
const handleDeleteEpisode = async (id: string, e: React.MouseEvent) => {
e.stopPropagation();
if (!confirm("Are you sure you want to delete this episode?")) return;
try {
await fetch(`/api/episodes/${id}`, { method: "DELETE" });
if (activeEpisode?.id === id) {
setActiveEpisode(null);
setActiveTimings([]);
}
await fetchEpisodes();
} catch (err) {
console.error("Failed to delete episode:", err);
}
};
const formatDuration = (secs?: number | null) => {
if (!secs) return "0:00";
const m = Math.floor(secs / 60);
const s = Math.floor(secs % 60);
return `${m}:${s.toString().padStart(2, "0")}`;
};
return (
<div className="flex-1 flex flex-col pb-32">
{/* Top Navbar */}
<header className="border-b border-slate-800 bg-slate-900/60 backdrop-blur-md sticky top-0 z-40">
<div className="max-w-7xl mx-auto px-4 sm:px-6 h-16 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-gradient-to-tr from-blue-600 to-indigo-500 flex items-center justify-center text-white shadow-md shadow-blue-500/20">
<Radio className="w-5 h-5" />
</div>
<div>
<span className="font-bold text-lg text-slate-100 tracking-tight">
Be My Anchor
</span>
<span className="ml-2 text-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20 font-mono">
v2.0 M1
</span>
</div>
</div>
<button
onClick={() => setShowCreateForm(!showCreateForm)}
className="flex items-center gap-2 px-3.5 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium transition shadow-sm shadow-blue-600/20"
>
<PlusCircle className="w-4 h-4" />
<span>New Episode</span>
</button>
</div>
</header>
{/* Main Content Area */}
<main className="max-w-7xl mx-auto px-4 sm:px-6 py-6 w-full flex-1">
{/* Ingest Form (Collapsible) */}
{showCreateForm && (
<div className="mb-8 p-6 bg-slate-900 border border-slate-800 rounded-2xl shadow-xl animate-in fade-in slide-in-from-top-4 duration-200">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<Sparkles className="w-5 h-5 text-blue-400" />
<h2 className="text-lg font-semibold text-slate-100">
Convert Content to Podcast Episode
</h2>
</div>
<button
onClick={() => setShowCreateForm(false)}
className="text-xs text-slate-400 hover:text-slate-200"
>
Close
</button>
</div>
{formError && (
<div className="mb-4 p-3 bg-red-950/40 border border-red-800 text-red-300 text-sm rounded-lg">
{formError}
</div>
)}
<form onSubmit={handleCreateEpisode} className="space-y-4">
<div>
<label className="block text-xs font-medium text-slate-400 mb-1">
Article or Episode Title
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g., Understanding Kubernetes Ingress and Service Meshes"
className="w-full px-3.5 py-2.5 bg-slate-800/80 border border-slate-700 rounded-lg text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-blue-500"
required
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-medium text-slate-400 mb-1">
TTS Voice Engine (Edge Neural)
</label>
<select
value={voice}
onChange={(e) => setVoice(e.target.value)}
className="w-full px-3.5 py-2.5 bg-slate-800/80 border border-slate-700 rounded-lg text-sm text-slate-100 focus:outline-none focus:border-blue-500"
>
<optgroup label="🇨🇳 中文 / Chinese (支持中英双语混合)">
{voices
.filter((v) => v.locale.startsWith("zh"))
.map((v) => (
<option key={v.id} value={v.id}>
{v.name}
</option>
))}
</optgroup>
<optgroup label="🇺🇸 English (US & UK)">
{voices
.filter((v) => !v.locale.startsWith("zh"))
.map((v) => (
<option key={v.id} value={v.id}>
{v.name}
</option>
))}
</optgroup>
</select>
</div>
<div>
<label className="block text-xs font-medium text-slate-400 mb-1">
Narration Mode
</label>
<select
disabled
className="w-full px-3.5 py-2.5 bg-slate-850 border border-slate-700/50 rounded-lg text-sm text-slate-400 cursor-not-allowed"
>
<option value="VERBATIM">Verbatim Reader (M1 Active)</option>
<option value="FEYNMAN" disabled>Feynman Tutor (M2 Preview)</option>
<option value="DUAL_HOST" disabled>Dual-Host Dialogue (M2 Preview)</option>
</select>
</div>
</div>
<div>
<label className="block text-xs font-medium text-slate-400 mb-1">
Article Text or Markdown
</label>
<textarea
value={content}
onChange={(e) => handleContentChange(e.target.value)}
placeholder="Paste your technical article, newsletter, blog post, or notes here..."
rows={6}
className="w-full px-3.5 py-2.5 bg-slate-800/80 border border-slate-700 rounded-lg text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:border-blue-500 font-mono text-xs leading-relaxed"
required
/>
</div>
<div className="flex justify-end gap-3 pt-2">
<button
type="button"
onClick={() => setShowCreateForm(false)}
className="px-4 py-2 text-sm text-slate-400 hover:text-slate-200"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="flex items-center gap-2 px-5 py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-blue-800 text-white text-sm font-medium rounded-lg shadow-md shadow-blue-600/30 transition"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
<span>Synthesizing Audio...</span>
</>
) : (
<>
<Headphones className="w-4 h-4" />
<span>Synthesize Episode</span>
</>
)}
</button>
</div>
</form>
</div>
)}
{/* Dashboard Columns */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
{/* Left: Episode Library (5 cols) */}
<section className="lg:col-span-5 flex flex-col gap-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-slate-400 uppercase tracking-wider flex items-center gap-2">
<FileText className="w-4 h-4" />
<span>Episodes ({episodes.length})</span>
</h2>
</div>
{episodes.length === 0 ? (
<div className="p-8 text-center bg-slate-900/50 border border-dashed border-slate-800 rounded-2xl">
<Headphones className="w-10 h-10 text-slate-600 mx-auto mb-3" />
<h3 className="text-slate-200 font-medium text-sm mb-1">No episodes generated yet</h3>
<p className="text-xs text-slate-500 mb-4">
Paste a blog post or article to generate your first podcast episode!
</p>
<button
onClick={() => setShowCreateForm(true)}
className="inline-flex items-center gap-2 px-3 py-1.5 text-xs bg-blue-600 text-white rounded-lg hover:bg-blue-500"
>
<PlusCircle className="w-3.5 h-3.5" />
<span>Generate Episode</span>
</button>
</div>
) : (
<div className="space-y-2.5">
{episodes.map((ep) => {
const isSelected = activeEpisode?.id === ep.id;
return (
<div
key={ep.id}
onClick={() => selectEpisode(ep)}
className={`p-4 rounded-xl cursor-pointer transition-all border ${
isSelected
? "bg-slate-850 border-blue-500/60 shadow-md shadow-blue-500/5"
: "bg-slate-900/70 border-slate-800 hover:border-slate-700 hover:bg-slate-850/60"
}`}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<h3 className={`text-sm font-medium truncate ${isSelected ? "text-blue-200" : "text-slate-200"}`}>
{ep.title}
</h3>
<div className="flex items-center gap-3 mt-1.5 text-xs text-slate-500">
<span className="flex items-center gap-1 font-mono">
<Clock className="w-3 h-3" />
{formatDuration(ep.durationSeconds)}
</span>
<span>•</span>
<span className="capitalize">{ep.mode.toLowerCase()}</span>
<span>•</span>
<span
className={`px-1.5 py-0.2 rounded text-[10px] font-medium uppercase ${
ep.status === "READY"
? "bg-emerald-500/10 text-emerald-400"
: ep.status === "PROCESSING"
? "bg-amber-500/10 text-amber-400"
: "bg-red-500/10 text-red-400"
}`}
>
{ep.status}
</span>
</div>
</div>
<button
onClick={(e) => handleDeleteEpisode(ep.id, e)}
className="p-1.5 text-slate-500 hover:text-red-400 hover:bg-red-950/30 rounded-lg transition"
title="Delete episode"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
);
})}
</div>
)}
</section>
{/* Right: Active Episode & Transcript (7 cols) */}
<section className="lg:col-span-7 bg-slate-900/80 border border-slate-800 rounded-2xl p-6 min-h-[480px] flex flex-col">
{activeEpisode ? (
<div className="flex flex-col flex-1">
{/* Header */}
<div className="border-b border-slate-800 pb-4 mb-4">
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase tracking-wider text-blue-400 bg-blue-950/60 px-2.5 py-1 rounded border border-blue-900">
Now Playing
</span>
<span className="text-xs text-slate-500">
Created {new Date(activeEpisode.createdAt).toLocaleDateString()}
</span>
</div>
<h1 className="text-xl font-bold text-slate-100 mt-2">
{activeEpisode.title}
</h1>
</div>
{/* Synchronized Transcript */}
<div className="flex-1 flex flex-col">
<h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wider mb-3 flex items-center gap-1.5">
<Volume2 className="w-3.5 h-3.5 text-blue-400" />
<span>Synchronized Transcript</span>
</h3>
<TranscriptViewer
timings={activeTimings}
currentTime={currentTime}
onSeek={(t) => setSeekTime(t)}
/>
</div>
</div>
) : (
<div className="flex-1 flex flex-col items-center justify-center text-center text-slate-500 py-16">
<Radio className="w-12 h-12 mb-3 opacity-30 text-blue-400" />
<p className="text-sm">Select an episode from the library to listen and follow along.</p>
</div>
)}
</section>
</div>
</main>
{/* Persistent Bottom Audio Player */}
{activeEpisode && activeEpisode.audioUrl && (
<AudioPlayer
title={activeEpisode.title}
audioUrl={activeEpisode.audioUrl}
durationSeconds={activeEpisode.durationSeconds}
onTimeUpdate={(t) => setCurrentTime(t)}
seekTime={seekTime}
/>
)}
</div>
);
}