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
initial
Nika Siradze78e2d940266f
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..a408daf--- /dev/null+++ b/.env.example@@ -0,0 +1,21 @@+# podcli Configuration++# Whisper model size: tiny, base, small, medium, large+WHISPER_MODEL=base++# Device for Whisper: cpu, cuda, auto+WHISPER_DEVICE=auto++# FFmpeg paths (leave blank to use system defaults)+FFMPEG_PATH=+FFPROBE_PATH=++# Python path (leave blank to auto-detect venv)+PYTHON_PATH=++# Working directory (defaults to ~/.podcli)+PODCLI_HOME=++# Logging+LOG_LEVEL=info+DEBUG=falsediff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..29b67db--- /dev/null+++ b/.gitignore@@ -0,0 +1,32 @@+# Dependencies+node_modules/+venv/++# Build output+dist/++# Data directory+data/++# Environment+.env++# OS+.DS_Store+Thumbs.db++# Python+__pycache__/+*.pyc+*.pyo+*.egg-info/+.pytest_cache/++# Media & temp files+*.mp4+*.mp3+*.wav+*.ass+*.srt+uploads/+output/diff --git a/README.md b/README.mdnew file mode 100644index 0000000..623e4d1--- /dev/null+++ b/README.md@@ -0,0 +1,265 @@+# podcli++AI-powered podcast clip generator. Takes a long-form podcast video, identifies viral moments, and exports upload-ready TikTok / YouTube Shorts (1080×1920, 9:16, burned captions, normalized audio).++## Features++- **Auto clip suggestion** — text heuristics + audio energy analysis for smarter scoring+- **Hardware-accelerated encoding** — auto-detects VideoToolbox (Mac), NVENC (NVIDIA), VAAPI, or falls back to CPU+- **Burned-in captions** — word-level timestamps with branded, hormozi, karaoke, or subtle styles+- **Smooth gradient overlay** — alpha-blended PNG overlay (no banding)+- **Smart cropping** — center crop or face detection+- **Transcript import** — paste `Speaker (MM:SS)` format, JSON, or drag-and-drop `.txt` files+- **Whisper transcription** — auto-transcribe with OpenAI Whisper (tiny → large)+- **CLI mode** — one-command processing: `./podcli process video.mp4 --top 5`+- **Preset system** — save and load named configurations per show+- **MCP server** — use as a Claude Desktop / Claude Code tool+- **Web UI** — single-page flow: input → suggest → review → export++---++## Prerequisites++| Tool | Install |+|------|---------|+| **Node.js** ≥ 18 | [nodejs.org](https://nodejs.org) |+| **Python** ≥ 3.10 | [python.org](https://python.org) |+| **FFmpeg** | `brew install ffmpeg` / `sudo apt install ffmpeg` |++---++## Quick Start++```bash+cd podcli+chmod +x setup.sh podcli+./setup.sh+```++This will:++1. Check system dependencies (Node, Python, FFmpeg)+2. Create a Python virtual environment and install packages+3. Install Node packages and build TypeScript+4. Launch the web UI at **http://localhost:3847**++### Setup options++```bash+./setup.sh # full install + launch UI+./setup.sh --install # install only+./setup.sh --ui # launch UI only (skip install)+./setup.sh --mcp # print MCP config+```++---++## Usage (CLI)++Process a video in one command — no UI needed:++```bash+# Basic: auto-transcribe + suggest top 5 clips + export+./podcli process video.mp4++# With existing transcript+./podcli process video.mp4 --transcript transcript.txt --top 5++# With a saved preset+./podcli process video.mp4 -t transcript.txt --preset myshow++# Full options+./podcli process video.mp4 \+ --transcript transcript.txt \+ --top 8 \+ --output ./clips \+ --caption-style branded \+ --crop center \+ --logo ~/logo.png \+ --time-adjust -1+```++### Presets++Save your settings so you don't reconfigure each time:++```bash+# Save a preset+./podcli presets save myshow --caption-style branded --logo ~/logo.png --top 5++# List presets+./podcli presets list++# Show preset details+./podcli presets show myshow++# Use a preset+./podcli process video.mp4 --preset myshow++# Delete a preset+./podcli presets delete myshow+```++Presets are stored in `~/.podcli/presets/`.++### System info++```bash+./podcli info+```++Shows detected encoder (VideoToolbox, NVENC, CPU), platform, and FFmpeg flags.++---++## Usage (Web UI)++1. **Set video** — drag-and-drop a video file or enter a local path+2. **Add transcript** — drag a `.txt` file, paste `Speaker (MM:SS)` text, or use Whisper auto-transcription+3. **Click "Generate Clips"** — podcli analyzes audio energy, parses transcript, and suggests clips+4. **Review** — toggle clips on/off, adjust settings (caption style, crop, logo)+5. **Export** — batch-renders all selected clips with hardware acceleration+6. **Preview / Retry / Download** — watch results inline, re-export individual clips++The encoder badge in the header shows which encoder is active (e.g., VIDEOTOOLBOX, NVENC, or CPU).++### Transcript format++```+Speaker Name (00:00)+What they said goes here as plain text.++Another Speaker (00:45)+Their response text here.+```++The time offset field (default: -1s) shifts all timestamps to sync with audio.++---++## Usage (MCP Server)++podcli is also a [Model Context Protocol](https://modelcontextprotocol.io) server — Claude can use it as a tool to create clips programmatically.++### Claude Desktop++Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:++```json+{+ "mcpServers": {+ "podcli": {+ "command": "node",+ "args": ["/absolute/path/to/podcli/dist/index.js"],+ "env": {+ "PYTHON_PATH": "/absolute/path/to/podcli/venv/bin/python3"+ }+ }+ }+}+```++### Claude Code++```bash+claude mcp add podcli -- node /absolute/path/to/podcli/dist/index.js+```++Or run `./setup.sh --mcp` to get the exact config with your paths filled in.++### Available MCP tools++| Tool | Description |+|------|-------------|+| `transcribe_podcast` | Transcribe audio with Whisper |+| `suggest_clips` | Get AI-suggested clip timestamps |+| `create_clip` | Render a single short clip |+| `batch_clips` | Render multiple clips in one go |++---++## Project Structure++```+podcli/+├── podcli # CLI entry point (shell wrapper)+├── setup.sh # one-command install & launch+├── package.json+├── tsconfig.json+├── .env.example+│+├── src/ # TypeScript source+│ ├── index.ts # MCP server entry (stdio)+│ ├── server.ts # MCP tool definitions+│ ├── config/paths.ts # path resolution+│ ├── models/index.ts # shared types+│ ├── handlers/ # MCP tool handlers+│ │ ├── transcribe.handler.ts+│ │ ├── suggest-clips.handler.ts+│ │ ├── create-clip.handler.ts+│ │ └── batch-clips.handler.ts+│ ├── services/+│ │ ├── python-executor.ts # spawns Python backend+│ │ └── file-manager.ts+│ └── ui/+│ ├── web-server.ts # Express server + SSE + REST API+│ └── public/index.html # React single-page UI+│+├── backend/ # Python backend+│ ├── main.py # stdin/stdout JSON dispatcher+│ ├── cli.py # CLI entry point (argparse)+│ ├── presets.py # preset save/load system+│ ├── requirements.txt+│ ├── services/+│ │ ├── transcription.py # Whisper wrapper+│ │ ├── video_processor.py # FFmpeg clip rendering (hw-accel)+│ │ ├── audio_analyzer.py # RMS energy analysis for scoring+│ │ ├── encoder.py # hardware encoder detection+│ │ ├── clip_generator.py # full pipeline orchestration+│ │ ├── caption_renderer.py # ASS subtitle generation+│ │ └── transcript_parser.py # Speaker (MM:SS) parser+│ └── config/+│ └── caption_styles.py # ASS subtitle style presets+│+└── data/ # runtime data (gitignored)+ ├── cache/transcripts/+ ├── working/uploads/+ ├── output/+ └── logs/+```++---++## Configuration++Copy `.env.example` to `.env` (setup.sh does this automatically):++```bash+cp .env.example .env+```++| Variable | Default | Description |+|----------|---------|-------------|+| `WHISPER_MODEL` | `base` | Whisper model size |+| `WHISPER_DEVICE` | `auto` | `cpu`, `cuda`, or `auto` |+| `PYTHON_PATH` | (venv) | Path to Python binary |+| `PODCLI_HOME` | `~/.podcli` | Data directory |+| `FFMPEG_PATH` | `ffmpeg` | Custom FFmpeg path |+| `LOG_LEVEL` | `info` | Logging verbosity |++---++## Caption Styles++| Style | Look |+|-------|------|+| **branded** | Gradient overlay + boxed word highlight + optional logo |+| **hormozi** | Bold pop-on text (Alex Hormozi style) |+| **karaoke** | Word-by-word highlight |+| **subtle** | Clean, minimal white text |++---++## License++MITdiff --git a/backend/cli.py b/backend/cli.pynew file mode 100644index 0000000..4e5b70a--- /dev/null+++ b/backend/cli.py@@ -0,0 +1,396 @@+#!/usr/bin/env python3+"""+podcli — CLI entry point.++One-command processing:+ python cli.py process video.mp4 --top 5 --transcript transcript.txt+ python cli.py process video.mp4 --preset myshow+ python cli.py presets list+ python cli.py presets save myshow --caption-style branded --logo ~/logo.png+ python cli.py info (show encoder, system info)+"""++import argparse+import json+import os+import sys+import time++# Add parent dir to path+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+++def cmd_process(args):+ """Full auto pipeline: transcribe → suggest → export."""+ from services.clip_generator import generate_clip+ from services.transcript_parser import parse_speaker_transcript+ from services.audio_analyzer import get_energy_profile+ from services.encoder import get_encoder_info+ from presets import get_preset, DEFAULT_PRESET++ video_path = args.video+ if not os.path.exists(video_path):+ print(f"Error: Video not found: {video_path}", file=sys.stderr)+ sys.exit(1)++ # Load preset or defaults+ if args.preset:+ try:+ config = get_preset(args.preset)+ print(f" Using preset: {args.preset}")+ except FileNotFoundError:+ print(f"Error: Preset '{args.preset}' not found", file=sys.stderr)+ sys.exit(1)+ else:+ config = {**DEFAULT_PRESET}++ # CLI overrides+ if args.caption_style:+ config["caption_style"] = args.caption_style+ if args.crop:+ config["crop_strategy"] = args.crop+ if args.top:+ config["top_clips"] = args.top+ if args.logo:+ config["logo_path"] = args.logo+ if args.time_adjust is not None:+ config["time_adjust"] = args.time_adjust+ if args.no_energy:+ config["energy_boost"] = False++ # Output directory+ output_dir = args.output or os.path.join(os.path.dirname(video_path), "clips")+ os.makedirs(output_dir, exist_ok=True)++ enc_info = get_encoder_info()+ print(f"\n podcli — processing")+ print(f" Encoder: {enc_info['best']} ({enc_info['system']})")+ print(f" Video: {os.path.basename(video_path)}")+ print()++ # ── Step 1: Get transcript ──+ transcript = None+ words = []+ segments = []++ if args.transcript:+ print(" [1/4] Loading transcript...")+ with open(args.transcript, "r") as f:+ raw_text = f.read()++ # Detect format+ if raw_text.strip().startswith("{") or raw_text.strip().startswith("["):+ data = json.loads(raw_text)+ if isinstance(data, list):+ words = data+ else:+ words = data.get("words", [])+ segments = data.get("segments", [])+ print(f" JSON transcript: {len(words)} words")+ else:+ parsed = parse_speaker_transcript(+ raw_text,+ time_adjust=config.get("time_adjust", 0),+ )+ if "error" in parsed:+ print(f" Error: {parsed['error']}", file=sys.stderr)+ sys.exit(1)+ words = parsed["words"]+ segments = parsed["segments"]+ print(f" Parsed: {len(segments)} segments, {len(words)} words")+ else:+ print(" [1/4] Transcribing with Whisper...")+ from services.transcription import transcribe_file+ result = transcribe_file(+ file_path=video_path,+ model_size=config.get("whisper_model", "base"),+ progress_callback=lambda pct, msg: print(f" {pct}% {msg}") if pct % 20 == 0 else None,+ )+ words = result["words"]+ segments = result["segments"]+ print(f" Done: {len(segments)} segments, {len(words)} words")++ if not segments:+ print(" Error: No transcript segments found.", file=sys.stderr)+ sys.exit(1)++ # ── Step 2: Analyze audio energy ──+ energy_scores = None+ if config.get("energy_boost", True):+ print(" [2/4] Analyzing audio energy...")+ try:+ profile = get_energy_profile(video_path, segments)+ energy_scores = profile["segment_scores"]+ print(f" {len(profile['peak_times'])} peak moments found")+ except Exception as e:+ print(f" Skipped (error: {e})")+ else:+ print(" [2/4] Audio analysis skipped (--no-energy)")++ # ── Step 3: Score and select clips ──+ print(" [3/4] Scoring clips...")+ clips = _suggest_clips(+ segments=segments,+ energy_scores=energy_scores,+ top_n=config.get("top_clips", 5),+ min_dur=config.get("min_clip_duration", 20),+ max_dur=config.get("max_clip_duration", 90),+ )++ if not clips:+ print(" No clips found. Try a longer transcript or lower --min-duration.", file=sys.stderr)+ sys.exit(1)++ print(f" Selected {len(clips)} clips:")+ for i, c in enumerate(clips):+ m_s = int(c["start_second"]) // 60+ s_s = int(c["start_second"]) % 60+ print(f" {i+1}. [{m_s}:{s_s:02d} → +{c['duration']}s] {c['title'][:55]}")++ # ── Step 4: Export ──+ print(f"\n [4/4] Exporting {len(clips)} clips to {output_dir}/")+ results = []+ t0 = time.time()++ for i, clip in enumerate(clips):+ print(f" Clip {i+1}/{len(clips)}: {clip['title'][:40]}...", end="", flush=True)+ try:+ result = generate_clip(+ video_path=video_path,+ start_second=clip["start_second"],+ end_second=clip["end_second"],+ caption_style=config.get("caption_style", "branded"),+ crop_strategy=config.get("crop_strategy", "center"),+ transcript_words=words,+ title=clip.get("title", f"clip_{i+1}"),+ output_dir=output_dir,+ logo_path=config.get("logo_path") or None,+ )+ results.append(result)+ print(f" ✓ {result['file_size_mb']}MB")+ except Exception as e:+ print(f" ✗ {e}")+ results.append({"status": "error", "error": str(e)})++ elapsed = time.time() - t0+ success = sum(1 for r in results if "output_path" in r)+ print(f"\n Done! {success}/{len(clips)} clips exported in {elapsed:.1f}s")+ print(f" Output: {output_dir}/\n")+++def _suggest_clips(+ segments: list,+ energy_scores: list | None = None,+ top_n: int = 5,+ min_dur: float = 20,+ max_dur: float = 90,+) -> list:+ """+ Score and rank transcript segments into clip suggestions.++ Combines text heuristics + audio energy for scoring.+ """+ KEYWORDS = [+ "secret", "mistake", "important", "never", "always", "best",+ "how to", "why", "story", "amazing", "changed", "money",+ "learn", "truth", "actually", "problem", "solution", "believe",+ "crazy", "number one", "biggest", "first thing", "listen",+ "here's the thing", "let me tell you", "the key", "game changer",+ "nobody talks about", "most people", "don't realize",+ ]++ clips = []+ win_sizes = [6, 8, 10, 12] # try multiple window sizes++ for win_size in win_sizes:+ step = max(1, int(win_size * 0.6))+ for i in range(0, len(segments) - win_size, step):+ win = segments[i : i + win_size]+ text = " ".join(s.get("text", "") for s in win)+ start = win[0].get("start", 0)+ end = win[-1].get("end", 0)+ dur = end - start++ if dur < min_dur or dur > max_dur:+ continue++ # Text heuristics+ score = 0+ text_lower = text.lower()+ if "?" in text:+ score += 3+ if "!" in text:+ score += 2+ if len(text) > 200:+ score += 1++ for kw in KEYWORDS:+ if kw in text_lower:+ score += 2++ # Sentence-start bonus (if window starts at a natural boundary)+ first_text = win[0].get("text", "").strip()+ if first_text and first_text[0].isupper():+ score += 1++ # Audio energy boost+ if energy_scores:+ seg_energies = energy_scores[i : i + win_size]+ if seg_energies:+ avg_energy = sum(seg_energies) / len(seg_energies)+ max_energy = max(seg_energies)+ score += avg_energy * 0.5 + max_energy * 0.3++ if score >= 3:+ clips.append({+ "title": text[:55].strip() + "...",+ "start_second": round(start),+ "end_second": round(end),+ "duration": round(dur),+ "score": round(score, 2),+ "preview": text[:100].strip(),+ })++ # Deduplicate overlapping clips (keep highest score)+ clips.sort(key=lambda c: c["score"], reverse=True)+ selected = []+ for clip in clips:+ overlap = False+ for sel in selected:+ if (clip["start_second"] < sel["end_second"] and+ clip["end_second"] > sel["start_second"]):+ # More than 50% overlap → skip+ overlap_amt = (min(clip["end_second"], sel["end_second"]) -+ max(clip["start_second"], sel["start_second"]))+ if overlap_amt > clip["duration"] * 0.5:+ overlap = True+ break+ if not overlap:+ selected.append(clip)+ if len(selected) >= top_n:+ break++ # Sort by time for natural ordering+ selected.sort(key=lambda c: c["start_second"])+ return selected+++def cmd_presets(args):+ """Manage presets."""+ from presets import list_presets, get_preset, save_preset, delete_preset++ if args.presets_action == "list":+ presets = list_presets()+ if not presets:+ print(" No saved presets. Create one with: podcli presets save <name>")+ return+ print(f"\n Saved presets ({len(presets)}):\n")+ for p in presets:+ print(f" {p['name']}")+ print(f" caption: {p.get('caption_style', '?')} | crop: {p.get('crop_strategy', '?')} | top: {p.get('top_clips', '?')}")+ print()++ elif args.presets_action == "save":+ config = {}+ if args.caption_style:+ config["caption_style"] = args.caption_style+ if args.crop:+ config["crop_strategy"] = args.crop+ if args.logo:+ config["logo_path"] = args.logo+ if args.top:+ config["top_clips"] = args.top+ if args.time_adjust is not None:+ config["time_adjust"] = args.time_adjust++ path = save_preset(args.name, config)+ print(f" Preset '{args.name}' saved to {path}")++ elif args.presets_action == "delete":+ if delete_preset(args.name):+ print(f" Preset '{args.name}' deleted")+ else:+ print(f" Preset '{args.name}' not found")++ elif args.presets_action == "show":+ try:+ p = get_preset(args.name)+ print(f"\n Preset: {args.name}\n")+ for k, v in p.items():+ if k != "name":+ print(f" {k}: {v}")+ print()+ except FileNotFoundError:+ print(f" Preset '{args.name}' not found")+++def cmd_info(args):+ """Show system info."""+ from services.encoder import get_encoder_info++ info = get_encoder_info()+ print(f"\n podcli system info\n")+ print(f" Platform: {info['system']}")+ print(f" Encoder: {info['best']}")+ print(f" Available: {', '.join(info['available'])}")+ print(f" Flags: {' '.join(info['best_flags'])}")+ print()+++def main():+ parser = argparse.ArgumentParser(+ prog="podcli",+ description="AI-powered podcast clip generator",+ )+ sub = parser.add_subparsers(dest="command")++ # ── process ──+ proc = sub.add_parser("process", help="Process a video into clips")+ proc.add_argument("video", help="Path to podcast video file")+ proc.add_argument("-t", "--transcript", help="Path to transcript file (.txt or .json)")+ proc.add_argument("-n", "--top", type=int, help="Number of top clips to export (default: 5)")+ proc.add_argument("-o", "--output", help="Output directory (default: ./clips)")+ proc.add_argument("-p", "--preset", help="Load a saved preset")+ proc.add_argument("--caption-style", choices=["branded", "hormozi", "karaoke", "subtle"])+ proc.add_argument("--crop", choices=["center", "face"])+ proc.add_argument("--logo", help="Path to logo image")+ proc.add_argument("--time-adjust", type=float, help="Timestamp offset in seconds")+ proc.add_argument("--no-energy", action="store_true", help="Skip audio energy analysis")++ # ── presets ──+ pre = sub.add_parser("presets", help="Manage presets")+ pre_sub = pre.add_subparsers(dest="presets_action")++ pre_list = pre_sub.add_parser("list", help="List all presets")++ pre_save = pre_sub.add_parser("save", help="Save a preset")+ pre_save.add_argument("name", help="Preset name")+ pre_save.add_argument("--caption-style", choices=["branded", "hormozi", "karaoke", "subtle"])+ pre_save.add_argument("--crop", choices=["center", "face"])+ pre_save.add_argument("--logo", help="Logo path")+ pre_save.add_argument("--top", type=int, help="Default top clips count")+ pre_save.add_argument("--time-adjust", type=float)++ pre_show = pre_sub.add_parser("show", help="Show a preset")+ pre_show.add_argument("name")++ pre_del = pre_sub.add_parser("delete", help="Delete a preset")+ pre_del.add_argument("name")++ # ── info ──+ sub.add_parser("info", help="Show system info (encoder, etc.)")++ args = parser.parse_args()++ if args.command == "process":+ cmd_process(args)+ elif args.command == "presets":+ cmd_presets(args)+ elif args.command == "info":+ cmd_info(args)+ else:+ parser.print_help()+++if __name__ == "__main__":+ main()diff --git a/backend/config/__init__.py b/backend/config/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/backend/config/caption_styles.py b/backend/config/caption_styles.pynew file mode 100644index 0000000..441a6dc--- /dev/null+++ b/backend/config/caption_styles.py@@ -0,0 +1,97 @@+"""+Caption style definitions for ASS subtitle rendering.++Each style defines fonts, colors, sizes, and behavior for the+supported caption types.+"""++# ASS color format: &HAABBGGRR (hex, alpha-blue-green-red)+# Note: ASS uses BGR order, NOT RGB!++STYLES = {+ "hormozi": {+ "description": "Bold, centered, 2-3 words at a time, active word gets color pop",+ "font_name": "Arial",+ "font_size": 80,+ "primary_color": "&H00FFFFFF", # White (inactive words)+ "active_color": "&H0000FFFF", # Yellow (active word) — BGR for yellow+ "outline_color": "&H00000000", # Black outline+ "back_color": "&H80000000", # Semi-transparent black shadow+ "bold": True,+ "outline_width": 4,+ "shadow_depth": 2,+ "alignment": 2, # Bottom-center+ "margin_v": 180, # Vertical margin from bottom+ "words_per_chunk": 3, # Show 3 words at a time+ "uppercase": True,+ "gradient_overlay": False,+ "logo_support": False,+ },+ "karaoke": {+ "description": "Full sentence visible, words highlight progressively",+ "font_name": "Arial",+ "font_size": 60,+ "primary_color": "&H00808080", # Gray (unspoken words)+ "active_color": "&H00FFFFFF", # White (spoken words)+ "outline_color": "&H00000000",+ "back_color": "&H80000000",+ "bold": False,+ "outline_width": 3,+ "shadow_depth": 1,+ "alignment": 2,+ "margin_v": 160,+ "words_per_chunk": None, # Full sentence+ "uppercase": False,+ "gradient_overlay": False,+ "logo_support": False,+ },+ "subtle": {+ "description": "Clean white text at bottom with shadow, professional look",+ "font_name": "Arial",+ "font_size": 52,+ "primary_color": "&H00FFFFFF", # White+ "active_color": None, # No active word highlighting+ "outline_color": "&H00000000",+ "back_color": "&H80000000",+ "bold": False,+ "outline_width": 2,+ "shadow_depth": 2,+ "alignment": 2,+ "margin_v": 100,+ "words_per_chunk": None, # Full sentence/segment+ "uppercase": False,+ "gradient_overlay": False,+ "logo_support": False,+ },+ "branded": {+ "description": "Large bold text, ~7 words wrapping across 2-3 lines, dark box on active word. TikTok/Reels style.",+ "font_name": "Arial",+ "font_size": 90,+ "primary_color": "&H00FFFFFF", # White (all words)+ "active_color": "&H00FFFFFF", # White text on box+ "active_box_color": "&H00181818", # Dark box (near-black)+ "outline_color": "&H00000000", # Black outline+ "back_color": "&H00000000", # No shadow+ "bold": True,+ "outline_width": 0, # No outline — gradient provides contrast+ "shadow_depth": 0,+ "alignment": 2, # Bottom-center+ "margin_v": 360, # Lower-third area+ "words_per_chunk": 7, # Show ~7 words, wraps across 2-3 lines+ "uppercase": False, # Mixed case+ "gradient_overlay": True, # Enable bottom 50% dark gradient+ "gradient_opacity": 0.7, # 70% black at bottom edge+ "logo_support": True, # Enable top-left logo+ "logo_margin_x": 30, # Logo X offset from left+ "logo_margin_y": 40, # Logo Y offset from top+ "logo_height": 80, # Logo render height in px+ },+}+++def get_style(name: str) -> dict:+ """Get a caption style config by name."""+ style = STYLES.get(name)+ if not style:+ raise ValueError(f"Unknown caption style: {name}. Available: {list(STYLES.keys())}")+ return stylediff --git a/backend/main.py b/backend/main.pynew file mode 100644index 0000000..2e31c30--- /dev/null+++ b/backend/main.py@@ -0,0 +1,239 @@+#!/usr/bin/env python3+"""+podcli — Python Backend Entry Point++Reads a JSON task request from stdin, dispatches to the appropriate service,+and writes a JSON result to stdout. Progress events go to stderr.+"""++import json+import sys+import traceback++def emit_progress(task_id: str, stage: str, percent: int, message: str):+ """Write a progress event to stderr (picked up by TypeScript executor)."""+ event = {+ "task_id": task_id,+ "stage": stage,+ "percent": percent,+ "message": message,+ }+ print(json.dumps(event), file=sys.stderr, flush=True)+++def emit_result(task_id: str, status: str, data=None, error=None):+ """Write the final result to stdout."""+ result = {+ "task_id": task_id,+ "status": status,+ }+ if data is not None:+ result["data"] = data+ if error is not None:+ result["error"] = error+ print(json.dumps(result), flush=True)+++def handle_ping(task_id: str, params: dict):+ """Simple health check."""+ emit_result(task_id, "success", data={"message": "pong", "version": "1.0.0"})+++def handle_transcribe(task_id: str, params: dict):+ """Transcribe a podcast video/audio file with speaker detection."""+ from services.transcription import transcribe_file++ emit_progress(task_id, "transcribing", 0, "Starting transcription...")+ result = transcribe_file(+ file_path=params["file_path"],+ model_size=params.get("model_size", "base"),+ language=params.get("language"),+ enable_diarization=params.get("enable_diarization", True),+ num_speakers=params.get("num_speakers"),+ progress_callback=lambda pct, msg: emit_progress(task_id, "transcribing", pct, msg),+ )+ emit_result(task_id, "success", data=result)+++def handle_create_clip(task_id: str, params: dict):+ """Create a single finished short-form clip."""+ from services.clip_generator import generate_clip++ emit_progress(task_id, "starting", 0, "Preparing clip...")+ result = generate_clip(+ video_path=params["video_path"],+ start_second=params["start_second"],+ end_second=params["end_second"],+ caption_style=params.get("caption_style", "hormozi"),+ crop_strategy=params.get("crop_strategy", "center"),+ transcript_words=params.get("transcript_words", []),+ title=params.get("title", "clip"),+ output_dir=params.get("output_dir"),+ logo_path=params.get("logo_path"),+ progress_callback=lambda pct, msg: emit_progress(task_id, "processing", pct, msg),+ )+ emit_result(task_id, "success", data=result)+++def handle_batch_clips(task_id: str, params: dict):+ """Create multiple clips in sequence."""+ from services.clip_generator import generate_clip++ clips = params["clips"]+ results = []+ total = len(clips)++ for i, clip in enumerate(clips):+ emit_progress(+ task_id,+ "batch",+ int((i / total) * 100),+ f"Processing clip {i + 1}/{total}...",+ )+ try:+ result = generate_clip(+ video_path=params["video_path"],+ start_second=clip["start_second"],+ end_second=clip["end_second"],+ caption_style=clip.get("caption_style", "hormozi"),+ crop_strategy=clip.get("crop_strategy", "center"),+ transcript_words=params.get("transcript_words", []),+ title=clip.get("title", f"clip_{i + 1}"),+ output_dir=params.get("output_dir"),+ logo_path=clip.get("logo_path") or params.get("logo_path"),+ progress_callback=lambda pct, msg: emit_progress(+ task_id, "batch", int((i / total) * 100 + pct / total), msg+ ),+ )+ results.append({"clip_index": i, "status": "success", **result})+ except Exception as e:+ results.append({"clip_index": i, "status": "error", "error": str(e)})++ emit_result(+ task_id,+ "success",+ data={+ "results": results,+ "total_clips": total,+ "successful_clips": sum(1 for r in results if r["status"] == "success"),+ },+ )+++def handle_parse_transcript(task_id: str, params: dict):+ """Parse a speaker-labeled transcript into word-level timestamps."""+ from services.transcript_parser import parse_speaker_transcript++ raw_text = params.get("raw_text", "")+ total_duration = params.get("total_duration")+ time_adjust = params.get("time_adjust", 0.0)++ if not raw_text:+ emit_result(task_id, "error", error="raw_text is required")+ return++ emit_progress(task_id, "parsing", 50, "Parsing transcript...")+ result = parse_speaker_transcript(raw_text, total_duration=total_duration, time_adjust=time_adjust)++ if "error" in result:+ emit_result(task_id, "error", error=result["error"])+ return++ emit_progress(task_id, "parsing", 100, "Transcript parsed!")+ emit_result(task_id, "success", data=result)+++def handle_analyze_energy(task_id: str, params: dict):+ """Analyze audio energy of a video to improve clip scoring."""+ from services.audio_analyzer import get_energy_profile++ video_path = params.get("video_path", "")+ segments = params.get("segments", [])++ if not video_path:+ emit_result(task_id, "error", error="video_path is required")+ return++ result = get_energy_profile(+ video_path=video_path,+ segments=segments,+ progress_callback=lambda pct, msg: emit_progress(task_id, "analyzing", pct, msg),+ )+ emit_result(task_id, "success", data=result)+++def handle_detect_encoder(task_id: str, params: dict):+ """Detect available hardware encoders."""+ from services.encoder import get_encoder_info+ emit_result(task_id, "success", data=get_encoder_info())+++def handle_presets(task_id: str, params: dict):+ """Manage presets (list, get, save, delete)."""+ from presets import list_presets, get_preset, save_preset, delete_preset++ action = params.get("action", "list")+ name = params.get("name", "default")++ if action == "list":+ emit_result(task_id, "success", data={"presets": list_presets()})+ elif action == "get":+ try:+ preset = get_preset(name)+ emit_result(task_id, "success", data=preset)+ except FileNotFoundError as e:+ emit_result(task_id, "error", error=str(e))+ elif action == "save":+ config = params.get("config", {})+ path = save_preset(name, config)+ emit_result(task_id, "success", data={"path": path, "name": name})+ elif action == "delete":+ ok = delete_preset(name)+ emit_result(task_id, "success", data={"deleted": ok})+ else:+ emit_result(task_id, "error", error=f"Unknown presets action: {action}")+++TASK_HANDLERS = {+ "ping": handle_ping,+ "transcribe": handle_transcribe,+ "parse_transcript": handle_parse_transcript,+ "create_clip": handle_create_clip,+ "batch_clips": handle_batch_clips,+ "analyze_energy": handle_analyze_energy,+ "detect_encoder": handle_detect_encoder,+ "presets": handle_presets,+}+++def main():+ try:+ raw = sys.stdin.readline().strip()+ if not raw:+ emit_result("unknown", "error", error="Empty input")+ sys.exit(1)++ request = json.loads(raw)+ task_id = request.get("task_id", "unknown")+ task_type = request.get("task_type", "")+ params = request.get("params", {})++ handler = TASK_HANDLERS.get(task_type)+ if not handler:+ emit_result(task_id, "error", error=f"Unknown task type: {task_type}")+ sys.exit(1)++ handler(task_id, params)++ except Exception as e:+ task_id = "unknown"+ try:+ task_id = json.loads(raw).get("task_id", "unknown")+ except Exception:+ pass+ emit_result(task_id, "error", error=f"{type(e).__name__}: {e}\n{traceback.format_exc()}")+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/backend/presets.py b/backend/presets.pynew file mode 100644index 0000000..147d938--- /dev/null+++ b/backend/presets.py@@ -0,0 +1,89 @@+"""+Preset/template system for podcli.++Save and load named configurations so you don't reconfigure settings+for every episode. Stored as JSON in ~/.podcli/presets/+"""++import os+import json+from typing import Optional++PRESETS_DIR = os.path.join(+ os.environ.get("PODCLI_HOME", os.path.expanduser("~/.podcli")),+ "presets",+)++DEFAULT_PRESET = {+ "caption_style": "branded",+ "crop_strategy": "center",+ "time_adjust": -1.0,+ "logo_path": "",+ "whisper_model": "base",+ "top_clips": 5,+ "max_clip_duration": 90,+ "min_clip_duration": 20,+ "target_lufs": -14.0,+ "energy_boost": True,+}+++def list_presets() -> list[dict]:+ """List all saved presets."""+ if not os.path.exists(PRESETS_DIR):+ return []++ presets = []+ for f in sorted(os.listdir(PRESETS_DIR)):+ if f.endswith(".json"):+ name = f[:-5]+ path = os.path.join(PRESETS_DIR, f)+ try:+ with open(path, "r") as fh:+ data = json.load(fh)+ presets.append({"name": name, **data})+ except (json.JSONDecodeError, IOError):+ pass+ return presets+++def get_preset(name: str) -> dict:+ """Load a preset by name, falling back to defaults for missing keys."""+ path = os.path.join(PRESETS_DIR, f"{name}.json")+ if not os.path.exists(path):+ if name == "default":+ return {**DEFAULT_PRESET}+ raise FileNotFoundError(f"Preset not found: {name}")++ with open(path, "r") as f:+ saved = json.load(f)++ # Merge with defaults so new keys are always present+ merged = {**DEFAULT_PRESET, **saved, "name": name}+ return merged+++def save_preset(name: str, config: dict) -> str:+ """Save a preset to disk."""+ os.makedirs(PRESETS_DIR, exist_ok=True)+ path = os.path.join(PRESETS_DIR, f"{name}.json")++ # Only save keys that differ from or match the default schema+ to_save = {}+ for key in DEFAULT_PRESET:+ if key in config:+ to_save[key] = config[key]++ with open(path, "w") as f:+ json.dump(to_save, f, indent=2)++ return path+++def delete_preset(name: str) -> bool:+ """Delete a preset file."""+ path = os.path.join(PRESETS_DIR, f"{name}.json")+ if os.path.exists(path):+ os.remove(path)+ return True+ return Falsediff --git a/backend/requirements.txt b/backend/requirements.txtnew file mode 100644index 0000000..55727a8--- /dev/null+++ b/backend/requirements.txt@@ -0,0 +1,23 @@+# Transcription+openai-whisper>=20231117++# Speaker diarization (optional — only needed if you enable local speaker detection)+# Most users don't need this: Claude handles speaker identification via MCP,+# and the "Paste Transcript" flow supports Speaker (MM:SS) labels natively.+# To enable: pip install pyannote.audio speechbrain && set HF_TOKEN in .env+# pyannote.audio>=3.1.0+# speechbrain>=1.0.0++# Video/audio processing+ffmpeg-python>=0.2.0+pydub>=0.25.1++# Face detection (optional, for smart cropping)+opencv-python-headless>=4.8.0+numpy>=1.24.0++# Data models+pydantic>=2.0.0++# Utilities+python-dotenv>=1.0.0diff --git a/backend/services/__init__.py b/backend/services/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/backend/services/audio_analyzer.py b/backend/services/audio_analyzer.pynew file mode 100644index 0000000..ae2afea--- /dev/null+++ b/backend/services/audio_analyzer.py@@ -0,0 +1,196 @@+"""+Audio energy analysis for smarter clip scoring.++Extracts volume/RMS data per second from a video file using FFmpeg,+then identifies energy peaks (loud moments, laughs, emphasis).+Used by the clip suggestor to boost scores for high-energy segments.+"""++import subprocess+import json+import re+from typing import Optional, Callable+++def extract_audio_energy(+ video_path: str,+ window_sec: float = 1.0,+) -> list[dict]:+ """+ Extract per-second RMS energy levels from a video's audio track.++ Returns list of {time, rms, peak} dicts, one per window.+ """+ # Use ffmpeg astats filter to get per-frame audio stats+ cmd = [+ "ffmpeg",+ "-i", video_path,+ "-af", f"astats=metadata=1:reset={int(1/window_sec)},"+ f"ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-",+ "-f", "null", "-",+ ]++ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)++ # Parse the ametadata output from stdout+ # Format: "frame:N pts:N pts_time:N.N\nlavfi.astats.Overall.RMS_level=N.N"+ energy_data = []+ lines = (result.stdout or "").split("\n")++ current_time = None+ for line in lines:+ line = line.strip()+ pts_match = re.search(r'pts_time:(\d+\.?\d*)', line)+ if pts_match:+ current_time = float(pts_match.group(1))++ rms_match = re.search(r'RMS_level=(-?\d+\.?\d*)', line)+ if rms_match and current_time is not None:+ rms_db = float(rms_match.group(1))+ energy_data.append({+ "time": round(current_time, 2),+ "rms_db": round(rms_db, 2),+ })+ current_time = None++ if not energy_data:+ # Fallback: use volumedetect for a simpler analysis+ return _fallback_energy(video_path)++ return energy_data+++def _fallback_energy(video_path: str) -> list[dict]:+ """+ Simpler fallback: extract volume per second using ffprobe + loudness.+ Returns a basic energy profile.+ """+ # Get duration first+ probe_cmd = [+ "ffprobe", "-v", "quiet", "-print_format", "json",+ "-show_format", video_path,+ ]+ probe = subprocess.run(probe_cmd, capture_output=True, text=True)+ try:+ duration = float(json.loads(probe.stdout)["format"]["duration"])+ except (json.JSONDecodeError, KeyError):+ return []++ # Use ebur128 filter which reliably outputs loudness per second+ cmd = [+ "ffmpeg",+ "-i", video_path,+ "-af", "ebur128=peak=true",+ "-f", "null", "-",+ ]+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)++ energy_data = []+ # Parse ebur128 output from stderr: "t: N.N M: -N.N S: -N.N"+ for line in (result.stderr or "").split("\n"):+ m = re.search(r't:\s*(\d+\.?\d*)\s+M:\s*(-?\d+\.?\d*)', line)+ if m:+ energy_data.append({+ "time": round(float(m.group(1)), 2),+ "rms_db": round(float(m.group(2)), 2),+ })++ return energy_data+++def compute_energy_scores(+ energy_data: list[dict],+ segments: list[dict],+) -> list[float]:+ """+ For each segment, compute an energy score (0-10) based on audio loudness.++ Higher scores = louder/more energetic moments.+ Uses z-score normalization so it adapts to each podcast's baseline.+ """+ if not energy_data:+ return [0.0] * len(segments)++ # Build time→rms lookup+ rms_values = [e["rms_db"] for e in energy_data]+ if not rms_values:+ return [0.0] * len(segments)++ # Filter out silence (-inf or very low values)+ valid_rms = [r for r in rms_values if r > -60]+ if not valid_rms:+ return [0.0] * len(segments)++ mean_rms = sum(valid_rms) / len(valid_rms)+ std_rms = max((sum((r - mean_rms) ** 2 for r in valid_rms) / len(valid_rms)) ** 0.5, 0.1)++ scores = []+ for seg in segments:+ seg_start = seg.get("start", 0)+ seg_end = seg.get("end", 0)++ # Get energy values within this segment's time range+ seg_rms = [+ e["rms_db"] for e in energy_data+ if seg_start <= e["time"] <= seg_end and e["rms_db"] > -60+ ]++ if not seg_rms:+ scores.append(0.0)+ continue++ # Average RMS for segment+ avg_rms = sum(seg_rms) / len(seg_rms)+ # Peak RMS (most energetic moment)+ peak_rms = max(seg_rms)++ # Z-score: how many std devs above mean+ z_avg = (avg_rms - mean_rms) / std_rms+ z_peak = (peak_rms - mean_rms) / std_rms++ # Combine: weight peak more (catches laughs, emphasis)+ raw_score = z_avg * 0.4 + z_peak * 0.6++ # Normalize to 0-10 range (clamp)+ score = max(0, min(10, (raw_score + 1) * 3))+ scores.append(round(score, 2))++ return scores+++def get_energy_profile(+ video_path: str,+ segments: list[dict],+ progress_callback: Optional[Callable] = None,+) -> dict:+ """+ Full pipeline: extract energy data and score all segments.++ Returns {energy_data, segment_scores, mean_rms, peak_times}+ """+ if progress_callback:+ progress_callback(0, "Analyzing audio energy...")++ energy_data = extract_audio_energy(video_path)++ if progress_callback:+ progress_callback(70, "Scoring segments by energy...")++ segment_scores = compute_energy_scores(energy_data, segments)++ # Find peak moments (top 10% loudest)+ if energy_data:+ sorted_by_rms = sorted(energy_data, key=lambda e: e["rms_db"], reverse=True)+ top_count = max(1, len(sorted_by_rms) // 10)+ peak_times = [e["time"] for e in sorted_by_rms[:top_count]]+ else:+ peak_times = []++ if progress_callback:+ progress_callback(100, "Audio analysis complete")++ return {+ "energy_data": energy_data,+ "segment_scores": segment_scores,+ "peak_times": peak_times,+ }diff --git a/backend/services/caption_renderer.py b/backend/services/caption_renderer.pynew file mode 100644index 0000000..6ab72ef--- /dev/null+++ b/backend/services/caption_renderer.py@@ -0,0 +1,257 @@+"""+ASS (Advanced SubStation Alpha) subtitle generator.++Generates styled caption files that FFmpeg can burn into video.+Supports styles: Hormozi, Karaoke, Subtle, and Branded.+"""++import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from config.caption_styles import get_style+from utils.timing_utils import seconds_to_ass+++def generate_ass_header(style: dict, play_res_x: int = 1080, play_res_y: int = 1920) -> str:+ """Generate the ASS file header with style definitions."""+ bold_val = -1 if style["bold"] else 0++ return f"""[Script Info]+Title: Podcast Clip Captions+ScriptType: v4.00++PlayResX: {play_res_x}+PlayResY: {play_res_y}+WrapStyle: 0+ScaledBorderAndShadow: yes++[V4+ Styles]+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding+Style: Default,{style["font_name"]},{style["font_size"]},{style["primary_color"]},{style["primary_color"]},{style["outline_color"]},{style["back_color"]},{bold_val},0,0,0,100,100,0,0,1,{style["outline_width"]},{style["shadow_depth"]},{style["alignment"]},40,40,{style["margin_v"]},1++[Events]+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text+"""+++def generate_branded_header(style: dict, play_res_x: int = 1080, play_res_y: int = 1920) -> str:+ """+ Generate ASS header for branded style.+ Uses BrandedNormal style: bold white text with inline box overrides on active word.+ """+ return f"""[Script Info]+Title: Podcast Clip Captions (Branded)+ScriptType: v4.00++PlayResX: {play_res_x}+PlayResY: {play_res_y}+WrapStyle: 0+ScaledBorderAndShadow: yes++[V4+ Styles]+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding+Style: BrandedNormal,{style["font_name"]},{style["font_size"]},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,{style["alignment"]},80,80,{style["margin_v"]},1++[Events]+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text+"""+++def render_captions(+ words: list[dict],+ caption_style: str,+ output_path: str,+ time_offset: float = 0.0,+) -> str:+ """+ Generate an ASS subtitle file from word-level timestamps.++ Args:+ words: List of {word, start, end, confidence} dicts+ caption_style: "hormozi", "karaoke", "subtle", or "branded"+ output_path: Where to write the .ass file+ time_offset: Subtract this from all timestamps (for clip segments)++ Returns:+ Path to the generated .ass file+ """+ style = get_style(caption_style)++ if caption_style == "hormozi":+ content = _render_hormozi(words, style, time_offset)+ elif caption_style == "karaoke":+ content = _render_karaoke(words, style, time_offset)+ elif caption_style == "subtle":+ content = _render_subtle(words, style, time_offset)+ elif caption_style == "branded":+ content = _render_branded(words, style, time_offset)+ else:+ raise ValueError(f"Unknown style: {caption_style}")++ with open(output_path, "w", encoding="utf-8") as f:+ f.write(content)++ return output_path+++def _render_hormozi(words: list[dict], style: dict, offset: float) -> str:+ """+ Hormozi style: Show 2-3 words at a time, highlight active word.+ """+ header = generate_ass_header(style)+ events = []+ chunk_size = style["words_per_chunk"]+ uppercase = style["uppercase"]++ chunks = []+ for i in range(0, len(words), chunk_size):+ chunk = words[i : i + chunk_size]+ chunks.append(chunk)++ for chunk in chunks:+ if not chunk:+ continue++ for word_idx, active_word in enumerate(chunk):+ w_start = max(0, active_word["start"] - offset)+ w_end = max(0, active_word["end"] - offset)++ parts = []+ for j, w in enumerate(chunk):+ text = w["word"].upper() if uppercase else w["word"]+ if j == word_idx:+ active_c = style["active_color"]+ parts.append(f"{{\\c{active_c}}}{text}{{\\c{style['primary_color']}}}")+ else:+ parts.append(text)++ line_text = " ".join(parts)+ start_ts = seconds_to_ass(w_start)+ end_ts = seconds_to_ass(w_end)++ events.append(+ f"Dialogue: 0,{start_ts},{end_ts},Default,,0,0,0,,{line_text}"+ )++ return header + "\n".join(events) + "\n"+++def _render_karaoke(words: list[dict], style: dict, offset: float) -> str:+ """+ Karaoke style: Full sentence visible, words highlight as spoken.+ """+ header = generate_ass_header(style)+ events = []++ sentence_size = 10+ sentences = []+ for i in range(0, len(words), sentence_size):+ sentences.append(words[i : i + sentence_size])++ for sentence in sentences:+ if not sentence:+ continue++ sent_start = max(0, sentence[0]["start"] - offset)+ sent_end = max(0, sentence[-1]["end"] - offset)++ parts = []+ for w in sentence:+ duration_cs = int((w["end"] - w["start"]) * 100)+ text = w["word"]+ parts.append(f"{{\\kf{duration_cs}}}{text}")++ line_text = " ".join(parts)+ line_text = (+ f"{{\\c{style['active_color']}}}{{\\2c{style['primary_color']}}}" + line_text+ )++ start_ts = seconds_to_ass(sent_start)+ end_ts = seconds_to_ass(sent_end)++ events.append(f"Dialogue: 0,{start_ts},{end_ts},Default,,0,0,0,,{line_text}")++ return header + "\n".join(events) + "\n"+++def _render_subtle(words: list[dict], style: dict, offset: float) -> str:+ """+ Subtle style: Clean white subtitles at bottom, sentence-level timing.+ """+ header = generate_ass_header(style)+ events = []++ line_size = 7+ lines = []+ for i in range(0, len(words), line_size):+ lines.append(words[i : i + line_size])++ for line_words in lines:+ if not line_words:+ continue++ line_start = max(0, line_words[0]["start"] - offset)+ line_end = max(0, line_words[-1]["end"] - offset)++ line_text = " ".join(w["word"] for w in line_words)++ start_ts = seconds_to_ass(line_start)+ end_ts = seconds_to_ass(line_end)++ events.append(f"Dialogue: 0,{start_ts},{end_ts},Default,,0,0,0,,{line_text}")++ return header + "\n".join(events) + "\n"+++def _render_branded(words: list[dict], style: dict, offset: float) -> str:+ """+ Branded style — large bold text wrapping across 2-3 lines.+ Active word gets a dark rounded-box background.+ All text stays white. Designed for TikTok/Reels vertical video.++ Shows ~7 words at a time (wrapping naturally via ASS WrapStyle: 0),+ cycling through each word as active with a dark box highlight.+ """+ header = generate_branded_header(style)+ events = []+ chunk_size = style.get("words_per_chunk", 7)+ box_color = style.get("active_box_color", "&H00181818")++ # Group words into chunks+ chunks = []+ for i in range(0, len(words), chunk_size):+ chunk = words[i : i + chunk_size]+ chunks.append(chunk)++ for chunk in chunks:+ if not chunk:+ continue++ for word_idx, active_word in enumerate(chunk):+ w_start = max(0, active_word["start"] - offset)+ w_end = max(0, active_word["end"] - offset)++ parts = []+ for j, w in enumerate(chunk):+ text = w["word"]+ if j == word_idx:+ # Dark box via thick border: \3c sets border color as box fill+ # \xbord\ybord control horizontal/vertical padding+ parts.append(+ f"{{\\bord10\\xbord14\\ybord8\\3c{box_color}\\shad0}}"+ f"{text}"+ f"{{\\bord0\\3c&H00000000&}}"+ )+ else:+ parts.append(text)++ line_text = " ".join(parts)++ start_ts = seconds_to_ass(w_start)+ end_ts = seconds_to_ass(w_end)++ events.append(+ f"Dialogue: 0,{start_ts},{end_ts},BrandedNormal,,0,0,0,,{line_text}"+ )++ return header + "\n".join(events) + "\n"diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.pynew file mode 100644index 0000000..ddc0f8e--- /dev/null+++ b/backend/services/clip_generator.py@@ -0,0 +1,181 @@+"""+Clip generator — orchestrates the full pipeline for creating a short-form clip.++Pipeline: cut segment → crop to 9:16 → render captions → burn captions+ (+ optional gradient overlay + logo) → normalize audio+"""++import os+import sys+import tempfile+import shutil+from typing import Optional, Callable++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from services.caption_renderer import render_captions+from services.video_processor import (+ cut_segment,+ crop_to_vertical,+ burn_captions,+ normalize_audio,+)+from config.caption_styles import get_style+++def generate_clip(+ video_path: str,+ start_second: float,+ end_second: float,+ caption_style: str = "hormozi",+ crop_strategy: str = "center",+ transcript_words: list[dict] = None,+ title: str = "clip",+ output_dir: Optional[str] = None,+ logo_path: Optional[str] = None,+ progress_callback: Optional[Callable[[int, str], None]] = None,+) -> dict:+ """+ Generate a complete short-form video clip.++ Args:+ video_path: Path to source podcast video+ start_second: Clip start time+ end_second: Clip end time+ caption_style: "hormozi", "karaoke", "subtle", or "branded"+ crop_strategy: "center" or "face"+ transcript_words: Word-level timestamps from transcription+ title: Clip title (used in filename)+ output_dir: Where to save the final clip (defaults to temp)+ logo_path: Path to logo image (PNG). Used with "branded" style.+ progress_callback: Optional (percent, message) callback++ Returns:+ {+ "output_path": str,+ "duration": float,+ "file_size_mb": float,+ "title": str,+ }+ """+ if not os.path.exists(video_path):+ raise FileNotFoundError(f"Video not found: {video_path}")++ if end_second <= start_second:+ raise ValueError("end_second must be greater than start_second")++ duration = end_second - start_second+ if duration > 180:+ raise ValueError(f"Clip too long ({duration:.0f}s). Max 180 seconds for shorts.")++ # Load style config for branded-specific settings+ style_config = get_style(caption_style)++ # Create temp working directory+ work_dir = tempfile.mkdtemp(prefix="podcast_clip_")++ try:+ # Step 1: Cut the segment from the source video+ if progress_callback:+ progress_callback(10, "Cutting video segment...")++ segment_path = os.path.join(work_dir, "segment.mp4")+ cut_segment(video_path, segment_path, start_second, end_second)++ # Step 2: Crop to vertical 9:16+ if progress_callback:+ progress_callback(30, "Cropping to 9:16 vertical...")++ cropped_path = os.path.join(work_dir, "cropped.mp4")+ crop_to_vertical(segment_path, cropped_path, strategy=crop_strategy)++ # Step 3: Generate captions + burn (with optional gradient & logo)+ if transcript_words:+ if progress_callback:+ progress_callback(50, f"Rendering {caption_style} captions...")++ # Filter words that fall within our clip's time range+ clip_words = [+ w for w in transcript_words+ if w["start"] >= start_second and w["end"] <= end_second+ ]++ if clip_words:+ # Generate ASS subtitle file+ ass_path = os.path.join(work_dir, "captions.ass")+ render_captions(+ words=clip_words,+ caption_style=caption_style,+ output_path=ass_path,+ time_offset=start_second,+ )++ # Burn captions into video+ if progress_callback:+ progress_callback(65, "Burning captions into video...")++ captioned_path = os.path.join(work_dir, "captioned.mp4")++ # Branded style: add gradient overlay + logo+ use_gradient = style_config.get("gradient_overlay", False)+ gradient_opacity = style_config.get("gradient_opacity", 0.6)+ use_logo = style_config.get("logo_support", False) and logo_path++ burn_captions(+ input_path=cropped_path,+ ass_path=ass_path,+ output_path=captioned_path,+ gradient_overlay=use_gradient,+ gradient_opacity=gradient_opacity,+ logo_path=logo_path if use_logo else None,+ logo_height=style_config.get("logo_height", 80),+ logo_margin_x=style_config.get("logo_margin_x", 30),+ logo_margin_y=style_config.get("logo_margin_y", 40),+ )+ else:+ captioned_path = cropped_path+ else:+ captioned_path = cropped_path++ # Step 4: Normalize audio+ if progress_callback:+ progress_callback(80, "Normalizing audio to -14 LUFS...")++ normalized_path = os.path.join(work_dir, "normalized.mp4")+ normalize_audio(captioned_path, normalized_path)++ # Step 5: Move to output+ if progress_callback:+ progress_callback(95, "Finalizing output...")++ # Clean filename+ safe_title = "".join(c if c.isalnum() or c in "-_ " else "" for c in title)+ safe_title = safe_title.strip().replace(" ", "_")[:50]+ output_filename = f"{safe_title}_short.mp4"++ if output_dir:+ os.makedirs(output_dir, exist_ok=True)+ final_path = os.path.join(output_dir, output_filename)+ else:+ final_path = os.path.join(work_dir, output_filename)++ shutil.copy2(normalized_path, final_path)++ # Get file size+ file_size = os.path.getsize(final_path)+ file_size_mb = round(file_size / (1024 * 1024), 2)++ if progress_callback:+ progress_callback(100, "Clip complete!")++ return {+ "output_path": final_path,+ "duration": round(duration, 2),+ "file_size_mb": file_size_mb,+ "title": title,+ }++ finally:+ # Clean up temp files (but not if output is in work_dir)+ if output_dir and os.path.exists(work_dir):+ shutil.rmtree(work_dir, ignore_errors=True)diff --git a/backend/services/encoder.py b/backend/services/encoder.pynew file mode 100644index 0000000..44d0e85--- /dev/null+++ b/backend/services/encoder.py@@ -0,0 +1,157 @@+"""+Hardware-accelerated encoder detection and configuration.++Probes system for available encoders:+- macOS: h264_videotoolbox (M-series / Intel GPU)+- NVIDIA: h264_nvenc+- AMD: h264_amf (Windows) / h264_vaapi (Linux)+- Fallback: libx264 (CPU, always available)++Returns optimal FFmpeg encoder flags for the current system.+"""++import subprocess+import platform+import tempfile+import os+import functools+import sys++[email protected]_cache(maxsize=1)+def detect_encoders() -> dict:+ """+ Detect available hardware encoders.+ """+ system = platform.system()+ available = ["libx264"]++ candidates = []+ if system == "Darwin":+ candidates = ["h264_videotoolbox"]+ elif system == "Linux":+ candidates = ["h264_nvenc", "h264_vaapi"]+ elif system == "Windows":+ candidates = ["h264_nvenc", "h264_amf", "h264_qsv"]++ for enc in candidates:+ if _test_encoder(enc):+ available.append(enc)++ priority = [+ "h264_videotoolbox",+ "h264_nvenc",+ "h264_amf",+ "h264_vaapi",+ "h264_qsv",+ "libx264",+ ]++ best = "libx264"+ for enc in priority:+ if enc in available:+ best = enc+ break++ return {+ "available": available,+ "best": best,+ "best_flags": _get_encoder_flags(best),+ "system": system,+ }+++def _test_encoder(encoder: str) -> bool:+ """+ Test if an FFmpeg encoder works by encoding a small real video to a temp file.+ Writing to /dev/null or -f null fails for some HW encoders.+ """+ tmp_out = None+ try:+ tmp_out = tempfile.mktemp(suffix=".mp4")+ flags = _get_encoder_flags(encoder)+ cmd = [+ "ffmpeg", "-y",+ "-f", "lavfi", "-i", "color=black:s=320x240:d=0.5:r=24",+ "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono",+ "-t", "0.5",+ *flags,+ "-c:a", "aac",+ "-shortest",+ tmp_out,+ ]+ result = subprocess.run(+ cmd, capture_output=True, text=True, timeout=15,+ )+ # Check both return code AND that the file was actually created+ return result.returncode == 0 and os.path.exists(tmp_out) and os.path.getsize(tmp_out) > 100+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):+ return False+ finally:+ if tmp_out and os.path.exists(tmp_out):+ try:+ os.remove(tmp_out)+ except OSError:+ pass+++def _get_encoder_flags(encoder: str) -> list[str]:+ """+ Get optimal FFmpeg flags for a given encoder.+ Kept minimal to avoid conflicts with filter_complex.+ """+ flags = {+ "h264_videotoolbox": [+ "-c:v", "h264_videotoolbox",+ "-b:v", "6M", # Bitrate mode (more reliable than -q:v)+ "-allow_sw", "1", # Allow software fallback+ ],+ "h264_nvenc": [+ "-c:v", "h264_nvenc",+ "-preset", "p4",+ "-cq", "23",+ "-profile:v", "high",+ ],+ "h264_amf": [+ "-c:v", "h264_amf",+ "-quality", "balanced",+ "-rc", "cqp",+ "-qp_i", "23", "-qp_p", "23",+ ],+ "h264_vaapi": [+ "-c:v", "h264_vaapi",+ "-qp", "23",+ ],+ "h264_qsv": [+ "-c:v", "h264_qsv",+ "-preset", "medium",+ "-global_quality", "23",+ ],+ "libx264": [+ "-c:v", "libx264",+ "-crf", "23",+ "-preset", "medium",+ ],+ }+ return flags.get(encoder, flags["libx264"])+++def get_video_encode_flags() -> list[str]:+ """Get the best available encoder flags. Main entry point."""+ try:+ info = detect_encoders()+ return info["best_flags"]+ except Exception:+ # Absolute fallback — never let encoder detection break the pipeline+ print("Warning: encoder detection failed, using libx264", file=sys.stderr)+ return ["-c:v", "libx264", "-crf", "23", "-preset", "medium"]+++def get_encoder_info() -> dict:+ """Get full encoder detection info (for UI/logging)."""+ try:+ return detect_encoders()+ except Exception:+ return {"available": ["libx264"], "best": "libx264",+ "best_flags": ["-c:v", "libx264", "-crf", "23", "-preset", "medium"],+ "system": platform.system()}diff --git a/backend/services/speaker_detection.py b/backend/services/speaker_detection.pynew file mode 100644index 0000000..e389fa0--- /dev/null+++ b/backend/services/speaker_detection.py@@ -0,0 +1,235 @@+"""+Speaker diarization service.++Detects who is speaking when in a podcast using pyannote.audio.+Merges speaker labels with Whisper transcription segments for+per-word and per-segment speaker attribution.++Supports 2-person and 3+ person podcasts automatically.+"""++import os+import subprocess+import tempfile+from typing import Optional, Callable+++def extract_audio_wav(video_path: str, output_path: str) -> str:+ """Extract audio as 16kHz mono WAV (required by pyannote)."""+ cmd = [+ "ffmpeg", "-y",+ "-i", video_path,+ "-vn", # No video+ "-acodec", "pcm_s16le", # 16-bit PCM+ "-ar", "16000", # 16kHz+ "-ac", "1", # Mono+ output_path,+ ]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"Audio extraction failed: {result.stderr[-300:]}")+ return output_path+++def run_diarization(+ audio_path: str,+ num_speakers: Optional[int] = None,+ min_speakers: int = 2,+ max_speakers: int = 5,+ hf_token: Optional[str] = None,+ progress_callback: Optional[Callable[[int, str], None]] = None,+) -> list[dict]:+ """+ Run speaker diarization on an audio file.++ Returns list of speaker segments:+ [{"speaker": "SPEAKER_00", "start": 0.5, "end": 3.2}, ...]++ Args:+ audio_path: Path to WAV audio file+ num_speakers: Exact number of speakers (if known)+ min_speakers: Minimum speakers to detect+ max_speakers: Maximum speakers to detect+ hf_token: HuggingFace token for pyannote model access+ """+ token = hf_token or os.environ.get("HF_TOKEN", "")++ try:+ from pyannote.audio import Pipeline+ except ImportError:+ msg = "pyannote.audio not installed — run: pip install pyannote.audio"+ if progress_callback:+ progress_callback(0, msg)+ raise ImportError(msg)++ if not token:+ msg = (+ "HF_TOKEN not set — speaker detection requires a HuggingFace token. "+ "Get one at https://huggingface.co/settings/tokens and set HF_TOKEN in your .env file. "+ "You must also accept terms at https://huggingface.co/pyannote/speaker-diarization-3.1"+ )+ if progress_callback:+ progress_callback(0, msg)+ raise PermissionError(msg)++ if progress_callback:+ progress_callback(10, "Loading speaker diarization model...")++ try:+ pipeline = Pipeline.from_pretrained(+ "pyannote/speaker-diarization-3.1",+ use_auth_token=token,+ )+ except Exception as e:+ err_str = str(e).lower()+ if "token" in err_str or "auth" in err_str or "403" in err_str or "401" in err_str:+ msg = (+ f"HuggingFace auth failed: {e}. "+ "Make sure your HF_TOKEN is valid and you accepted the model terms at "+ "https://huggingface.co/pyannote/speaker-diarization-3.1"+ )+ if progress_callback:+ progress_callback(0, msg)+ raise PermissionError(msg) from e+ raise++ if progress_callback:+ progress_callback(30, "Running speaker diarization...")++ # Run diarization+ diarization_params = {}+ if num_speakers:+ diarization_params["num_speakers"] = num_speakers+ else:+ diarization_params["min_speakers"] = min_speakers+ diarization_params["max_speakers"] = max_speakers++ diarization = pipeline(audio_path, **diarization_params)++ if progress_callback:+ progress_callback(90, "Processing speaker segments...")++ # Convert to simple list format+ speaker_segments = []+ for turn, _, speaker in diarization.itertracks(yield_label=True):+ speaker_segments.append({+ "speaker": speaker,+ "start": round(turn.start, 3),+ "end": round(turn.end, 3),+ })++ if progress_callback:+ progress_callback(100, f"Detected {len(set(s['speaker'] for s in speaker_segments))} speakers")++ return speaker_segments+++def assign_speakers_to_segments(+ segments: list[dict],+ speaker_segments: list[dict],+) -> list[dict]:+ """+ Assign speaker labels to transcription segments.++ For each transcription segment, find the speaker who talks the most+ during that segment's time range (majority vote).+ """+ if not speaker_segments:+ # No diarization data — return segments unchanged+ for seg in segments:+ seg["speaker"] = None+ return segments++ for seg in segments:+ seg_start = seg["start"]+ seg_end = seg["end"]++ # Find overlapping speaker segments+ speaker_overlap = {}+ for sp in speaker_segments:+ overlap_start = max(seg_start, sp["start"])+ overlap_end = min(seg_end, sp["end"])+ overlap = max(0, overlap_end - overlap_start)++ if overlap > 0:+ speaker_overlap[sp["speaker"]] = speaker_overlap.get(sp["speaker"], 0) + overlap++ if speaker_overlap:+ # Assign speaker with most overlap+ seg["speaker"] = max(speaker_overlap, key=speaker_overlap.get)+ else:+ seg["speaker"] = None++ return segments+++def assign_speakers_to_words(+ words: list[dict],+ speaker_segments: list[dict],+) -> list[dict]:+ """+ Assign speaker labels to individual words.++ Uses the midpoint of each word's timestamp to determine+ which speaker segment it falls within.+ """+ if not speaker_segments:+ for w in words:+ w["speaker"] = None+ return words++ for w in words:+ midpoint = (w["start"] + w["end"]) / 2++ # Find which speaker segment contains this midpoint+ assigned = None+ for sp in speaker_segments:+ if sp["start"] <= midpoint <= sp["end"]:+ assigned = sp["speaker"]+ break++ w["speaker"] = assigned++ return words+++def create_speaker_summary(speaker_segments: list[dict]) -> dict:+ """+ Create a summary of speaker activity.++ Returns:+ {+ "num_speakers": int,+ "speakers": {+ "SPEAKER_00": {"total_time": float, "segments": int, "label": "Speaker 1"},+ ...+ }+ }+ """+ if not speaker_segments:+ return {"num_speakers": 0, "speakers": {}}++ speaker_stats = {}+ for sp in speaker_segments:+ name = sp["speaker"]+ if name not in speaker_stats:+ speaker_stats[name] = {"total_time": 0, "segments": 0}+ speaker_stats[name]["total_time"] += sp["end"] - sp["start"]+ speaker_stats[name]["segments"] += 1++ # Sort by total speaking time (most talkative first)+ sorted_speakers = sorted(speaker_stats.items(), key=lambda x: -x[1]["total_time"])++ # Assign friendly labels+ result = {}+ for i, (name, stats) in enumerate(sorted_speakers):+ result[name] = {+ "total_time": round(stats["total_time"], 1),+ "segments": stats["segments"],+ "label": f"Speaker {i + 1}",+ }++ return {+ "num_speakers": len(result),+ "speakers": result,+ }diff --git a/backend/services/transcript_parser.py b/backend/services/transcript_parser.pynew file mode 100644index 0000000..986d684--- /dev/null+++ b/backend/services/transcript_parser.py@@ -0,0 +1,169 @@+"""+Parse speaker-labeled transcript formats into word-level timestamps.++Supported format:+ Speaker (MM:SS)+ Text of what they said...++ Speaker2 (MM:SS)+ More text...+"""++import re+from typing import List, Dict, Any, Optional+++def parse_timestamp(ts: str) -> float:+ """Convert MM:SS or HH:MM:SS to seconds."""+ parts = ts.strip().split(":")+ if len(parts) == 2:+ return int(parts[0]) * 60 + int(parts[1])+ elif len(parts) == 3:+ return int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])+ return 0.0+++def parse_speaker_transcript(raw_text: str, total_duration: Optional[float] = None, time_adjust: float = 0.0) -> Dict[str, Any]:+ """+ Parse a speaker-labeled transcript into structured data with word-level timestamps.++ Words between two known timestamps are distributed evenly across that time window.++ Args:+ raw_text: The raw transcript text+ total_duration: Total duration of the podcast in seconds+ time_adjust: Seconds to add/subtract from all timestamps (e.g., -1.0 to shift 1s earlier)+ """+ lines = raw_text.strip().split("\n")++ # Pattern: "Speaker Name (MM:SS)" or "Speaker (HH:MM:SS)"+ header_pattern = re.compile(r'^(.+?)\s*\((\d{1,2}:\d{2}(?::\d{2})?)\)\s*$')++ # First pass: extract blocks (speaker, start_time, text)+ blocks = []+ current_speaker = None+ current_time = 0.0+ current_text_lines = []++ for line in lines:+ match = header_pattern.match(line.strip())+ if match:+ # Save previous block+ if current_speaker is not None:+ text = " ".join(current_text_lines).strip()+ # Clean up special chars+ text = text.replace("⁓", "").strip()+ text = re.sub(r'\s+', ' ', text)+ if text:+ blocks.append({+ "speaker": current_speaker,+ "start": current_time,+ "text": text,+ })++ current_speaker = match.group(1).strip()+ current_time = parse_timestamp(match.group(2))+ current_text_lines = []+ else:+ stripped = line.strip()+ if stripped:+ current_text_lines.append(stripped)++ # Don't forget the last block+ if current_speaker is not None:+ text = " ".join(current_text_lines).strip()+ text = text.replace("⁓", "").strip()+ text = re.sub(r'\s+', ' ', text)+ if text:+ blocks.append({+ "speaker": current_speaker,+ "start": current_time,+ "text": text,+ })++ if not blocks:+ return {"error": "No speaker blocks found in transcript"}++ # Second pass: compute end times for each block+ for i, block in enumerate(blocks):+ if i + 1 < len(blocks):+ block["end"] = blocks[i + 1]["start"]+ else:+ # Last block: use total_duration or estimate from text length+ if total_duration:+ block["end"] = total_duration+ else:+ # Rough estimate: ~3 words per second+ word_count = len(block["text"].split())+ block["end"] = block["start"] + max(word_count / 3.0, 2.0)++ # Third pass: generate word-level timestamps+ all_words = []+ segments = []+ speakers_set = set()+ speaker_times = {}++ for block in blocks:+ speaker = block["speaker"]+ speakers_set.add(speaker)+ words_in_block = block["text"].split()++ if not words_in_block:+ continue++ block_duration = block["end"] - block["start"]+ # Leave a small gap at the end of each block+ usable_duration = block_duration * 0.95+ word_duration = usable_duration / len(words_in_block) if words_in_block else 0++ block_words = []+ for j, w in enumerate(words_in_block):+ word_start = block["start"] + j * word_duration + time_adjust+ word_end = word_start + word_duration * 0.9 # small gap between words+ word_obj = {+ "word": w,+ "start": round(max(0, word_start), 3),+ "end": round(max(0, word_end), 3),+ "speaker": speaker,+ }+ all_words.append(word_obj)+ block_words.append(word_obj)++ # Track speaker time+ if speaker not in speaker_times:+ speaker_times[speaker] = 0.0+ speaker_times[speaker] += block_duration++ segments.append({+ "text": block["text"],+ "start": round(max(0, block["start"] + time_adjust), 3),+ "end": round(max(0, block["end"] + time_adjust), 3),+ "speaker": speaker,+ })++ # Build speaker summary+ speakers_list = []+ for i, speaker in enumerate(sorted(speakers_set)):+ speakers_list.append({+ "id": f"SPEAKER_{i}",+ "label": speaker,+ "total_time": round(speaker_times.get(speaker, 0), 2),+ })++ full_text = " ".join(w["word"] for w in all_words)+ duration = total_duration or (blocks[-1]["end"] if blocks else 0)++ return {+ "transcript": full_text,+ "words": all_words,+ "segments": segments,+ "duration": round(duration, 2),+ "language": "en",+ "speakers": speakers_list,+ "speaker_segments": [+ {"speaker": b["speaker"], "start": b["start"], "end": b["end"]}+ for b in blocks+ ],+ "imported": True,+ "format": "speaker_timestamp",+ }diff --git a/backend/services/transcription.py b/backend/services/transcription.pynew file mode 100644index 0000000..f81332b--- /dev/null+++ b/backend/services/transcription.py@@ -0,0 +1,211 @@+"""+Transcription service using OpenAI Whisper + speaker diarization.++Produces word-level timestamps with speaker labels by:+1. Running Whisper for speech-to-text with word timing+2. Running pyannote speaker diarization (if available)+3. Merging speaker labels onto each word and segment+"""++import os+import subprocess+import tempfile+from typing import Optional, Callable+++def transcribe_file(+ file_path: str,+ model_size: str = "base",+ language: Optional[str] = None,+ enable_diarization: bool = True,+ num_speakers: Optional[int] = None,+ progress_callback: Optional[Callable[[int, str], None]] = None,+) -> dict:+ """+ Transcribe a video/audio file with word-level timestamps and speaker detection.++ Returns:+ {+ "transcript": str,+ "segments": [{id, start, end, text, speaker}, ...],+ "words": [{word, start, end, confidence, speaker}, ...],+ "duration": float,+ "language": str,+ "speakers": {num_speakers, speakers: {SPEAKER_00: {total_time, segments, label}, ...}},+ "speaker_segments": [{speaker, start, end}, ...]+ }+ """+ if not os.path.exists(file_path):+ raise FileNotFoundError(f"File not found: {file_path}")++ # ================================================================+ # Step 1: Whisper transcription+ # ================================================================+ if progress_callback:+ progress_callback(5, "Loading Whisper model...")++ import whisper++ model = whisper.load_model(model_size)++ if progress_callback:+ progress_callback(10, f"Transcribing with Whisper ({model_size})...")++ result = model.transcribe(+ file_path,+ language=language,+ word_timestamps=True,+ verbose=False,+ )++ if progress_callback:+ progress_callback(50, "Processing timestamps...")++ segments = []+ words = []++ for seg in result.get("segments", []):+ segments.append(+ {+ "id": seg["id"],+ "start": round(seg["start"], 3),+ "end": round(seg["end"], 3),+ "text": seg["text"].strip(),+ "speaker": None, # Will be filled by diarization+ }+ )++ seg_words = seg.get("words", [])+ if seg_words:+ for w in seg_words:+ words.append(+ {+ "word": w.get("word", "").strip(),+ "start": round(w.get("start", 0), 3),+ "end": round(w.get("end", 0), 3),+ "confidence": round(w.get("probability", 0), 3),+ "speaker": None,+ }+ )+ else:+ text = seg["text"].strip()+ if not text:+ continue+ seg_words_list = text.split()+ seg_start = seg["start"]+ seg_end = seg["end"]+ seg_duration = seg_end - seg_start++ if len(seg_words_list) == 0:+ continue++ word_duration = seg_duration / len(seg_words_list)++ for i, word_text in enumerate(seg_words_list):+ w_start = seg_start + i * word_duration+ w_end = w_start + word_duration+ words.append(+ {+ "word": word_text,+ "start": round(w_start, 3),+ "end": round(w_end, 3),+ "confidence": 0.5,+ "speaker": None,+ }+ )++ duration = result.get("duration", 0)+ if not duration and segments:+ duration = segments[-1]["end"]++ detected_lang = result.get("language", language or "en")++ # ================================================================+ # Step 2: Speaker diarization (if enabled)+ # ================================================================+ speaker_segments = []+ speaker_summary = {"num_speakers": 0, "speakers": {}}+ diarization_warning = None++ if enable_diarization:+ try:+ from services.speaker_detection import (+ extract_audio_wav,+ run_diarization,+ assign_speakers_to_segments,+ assign_speakers_to_words,+ create_speaker_summary,+ )++ if progress_callback:+ progress_callback(55, "Extracting audio for speaker detection...")++ # Extract audio as WAV for pyannote+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:+ wav_path = tmp.name++ try:+ extract_audio_wav(file_path, wav_path)++ if progress_callback:+ progress_callback(60, "Running speaker diarization...")++ speaker_segments = run_diarization(+ wav_path,+ num_speakers=num_speakers,+ progress_callback=lambda pct, msg: (+ progress_callback(60 + int(pct * 0.3), msg) if progress_callback else None+ ),+ )++ if speaker_segments:+ if progress_callback:+ progress_callback(92, "Assigning speakers to transcript...")++ # Merge speaker labels into segments and words+ segments = assign_speakers_to_segments(segments, speaker_segments)+ words = assign_speakers_to_words(words, speaker_segments)+ speaker_summary = create_speaker_summary(speaker_segments)++ if progress_callback:+ progress_callback(+ 95,+ f"Found {speaker_summary['num_speakers']} speakers",+ )++ finally:+ if os.path.exists(wav_path):+ os.unlink(wav_path)++ except ImportError as e:+ diarization_warning = f"Speaker detection unavailable: {e}"+ if progress_callback:+ progress_callback(90, diarization_warning)+ except PermissionError as e:+ diarization_warning = str(e)+ if progress_callback:+ progress_callback(90, diarization_warning)+ except Exception as e:+ diarization_warning = f"Speaker detection failed: {e}"+ if progress_callback:+ progress_callback(90, diarization_warning)+ else:+ diarization_warning = "Speaker detection disabled"++ if progress_callback:+ progress_callback(100, "Transcription complete")++ result_data = {+ "transcript": result.get("text", "").strip(),+ "segments": segments,+ "words": words,+ "duration": round(duration, 3),+ "language": detected_lang,+ "speakers": speaker_summary,+ "speaker_segments": speaker_segments,+ }++ if diarization_warning:+ result_data["diarization_warning"] = diarization_warning++ return result_datadiff --git a/backend/services/video_processor.py b/backend/services/video_processor.pynew file mode 100644index 0000000..fa69c9d--- /dev/null+++ b/backend/services/video_processor.py@@ -0,0 +1,412 @@+"""+Video processing service using FFmpeg.++Handles: cutting segments, cropping to 9:16, burning captions,+audio normalization, and final encoding.+"""++import os+import subprocess+import json+from typing import Optional++from services.encoder import get_video_encode_flags+import sys++CPU_FLAGS = ["-c:v", "libx264", "-crf", "23", "-preset", "medium"]+++def _run_ffmpeg_with_fallback(cmd_parts_before_enc: list, cmd_parts_after_enc: list, output_path: str, label: str = "encode") -> str:+ """+ Run an FFmpeg command with the best encoder. If it fails, retry with libx264.+ cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path]+ """+ enc_flags = get_video_encode_flags()+ cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path]++ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode == 0:+ return output_path++ # If not already CPU, retry with libx264+ if enc_flags != CPU_FLAGS:+ print(f"Warning: HW encoder failed for {label}, falling back to libx264", file=sys.stderr)+ cmd_fallback = cmd_parts_before_enc + CPU_FLAGS + cmd_parts_after_enc + [output_path]+ result2 = subprocess.run(cmd_fallback, capture_output=True, text=True)+ if result2.returncode == 0:+ return output_path+ raise RuntimeError(f"FFmpeg {label} failed (both HW and CPU): {result2.stderr[-500:]}")++ raise RuntimeError(f"FFmpeg {label} failed: {result.stderr[-500:]}")+++def get_video_info(video_path: str) -> dict:+ """Get video metadata via ffprobe."""+ cmd = [+ "ffprobe",+ "-v", "quiet",+ "-print_format", "json",+ "-show_format",+ "-show_streams",+ video_path,+ ]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"ffprobe failed: {result.stderr}")+ return json.loads(result.stdout)+++def get_dimensions(video_path: str) -> tuple[int, int]:+ """Get video width and height."""+ info = get_video_info(video_path)+ for stream in info.get("streams", []):+ if stream.get("codec_type") == "video":+ return int(stream["width"]), int(stream["height"])+ raise ValueError(f"No video stream found in {video_path}")+++def cut_segment(+ input_path: str,+ output_path: str,+ start_second: float,+ end_second: float,+) -> str:+ """+ Extract a time segment from a video file.+ Uses -ss before -i for fast seeking.+ """+ duration = end_second - start_second++ cmd = [+ "ffmpeg", "-y",+ "-ss", str(start_second),+ "-i", input_path,+ "-t", str(duration),+ "-c", "copy", # No re-encoding for speed+ "-avoid_negative_ts", "make_zero",+ output_path,+ ]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"FFmpeg cut failed: {result.stderr[-500:]}")+ return output_path+++def crop_to_vertical(+ input_path: str,+ output_path: str,+ strategy: str = "center",+) -> str:+ """+ Crop/scale video to 1080x1920 (9:16 vertical).++ Strategies:+ - center: Take center column of the frame, scale to fit+ - face: Detect face position, center crop on face (falls back to center)+ """+ width, height = get_dimensions(input_path)+ target_w, target_h = 1080, 1920+ target_ratio = target_w / target_h # 0.5625++ source_ratio = width / height++ if strategy == "face":+ crop_x = _detect_face_offset(input_path, width, height, target_ratio)+ if crop_x is not None:+ crop_h = height+ crop_w = int(crop_h * target_ratio)+ vf = f"crop={crop_w}:{crop_h}:{crop_x}:0,scale={target_w}:{target_h}"+ else:+ # Fallback to center+ strategy = "center"++ if strategy == "center":+ if source_ratio > target_ratio:+ # Source is wider than target — crop sides+ crop_h = height+ crop_w = int(crop_h * target_ratio)+ crop_x = (width - crop_w) // 2+ vf = f"crop={crop_w}:{crop_h}:{crop_x}:0,scale={target_w}:{target_h}"+ else:+ # Source is taller or same — crop top/bottom or pad+ crop_w = width+ crop_h = int(crop_w / target_ratio)+ if crop_h > height:+ # Need to pad (letterbox)+ vf = f"scale={target_w}:-2,pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:black"+ else:+ crop_y = (height - crop_h) // 2+ vf = f"crop={crop_w}:{crop_h}:0:{crop_y},scale={target_w}:{target_h}"++ return _run_ffmpeg_with_fallback(+ cmd_parts_before_enc=[+ "ffmpeg", "-y",+ "-i", input_path,+ "-vf", vf,+ ],+ cmd_parts_after_enc=[+ "-c:a", "aac",+ "-b:a", "128k",+ "-ar", "44100",+ "-movflags", "+faststart",+ ],+ output_path=output_path,+ label="crop",+ )+++def _create_gradient_png(output_path: str, width: int = 1080, height: int = 1920, opacity: float = 0.7) -> str:+ """+ Create a transparent-to-black gradient PNG for the bottom 50% of the frame.+ Uses Python to generate the image — no external deps needed (uses raw PPM → FFmpeg).+ """+ # Generate a 1-pixel wide gradient strip, then FFmpeg scales it+ # Build gradient with FFmpeg: black fading from 0% to opacity% over bottom half+ # We create a gradient using lavfi color + geq+ max_alpha = int(opacity * 255)++ cmd = [+ "ffmpeg", "-y",+ "-f", "lavfi",+ "-i", f"[email protected]:size={width}x{height}:duration=1,format=rgba,"+ f"geq="+ f"r=0:"+ f"g=0:"+ f"b=0:"+ f"a='if(lt(Y,H/2),0,min({max_alpha},{max_alpha}*(Y-H/2)/(H/2)))'",+ "-frames:v", "1",+ output_path,+ ]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"Gradient creation failed: {result.stderr[-300:]}")+ return output_path+++def burn_captions(+ input_path: str,+ ass_path: str,+ output_path: str,+ gradient_overlay: bool = False,+ gradient_opacity: float = 0.7,+ logo_path: Optional[str] = None,+ logo_height: int = 80,+ logo_margin_x: int = 30,+ logo_margin_y: int = 40,+) -> str:+ """+ Burn ASS subtitles into the video.++ Optionally adds:+ - Bottom 50% smooth gradient overlay (transparent → black)+ - Logo image in top-left corner+ """+ safe_ass = ass_path.replace("\\", "/").replace(":", "\\:")++ # Get video dimensions for gradient+ if gradient_overlay:+ width, height = get_dimensions(input_path)+ gradient_path = output_path + ".gradient.png"+ _create_gradient_png(gradient_path, width, height, gradient_opacity)++ # Build filter_complex for all overlay inputs+ inputs = ["-i", input_path]+ input_idx = 1 # next input index++ filter_parts = []++ if gradient_overlay:+ inputs.extend(["-i", gradient_path])+ grad_idx = input_idx+ input_idx += 1+ # Overlay gradient on video+ filter_parts.append(+ f"[0:v][{grad_idx}:v]overlay=0:0:format=auto[grad]"+ )+ current_label = "grad"+ else:+ current_label = "0:v"++ if logo_path and os.path.exists(logo_path):+ inputs.extend(["-i", logo_path])+ logo_idx = input_idx+ input_idx += 1+ # Scale logo + overlay+ filter_parts.append(+ f"[{logo_idx}:v]scale=-1:{logo_height}[logo]"+ )+ filter_parts.append(+ f"[{current_label}][logo]overlay={logo_margin_x}:{logo_margin_y}[withlogo]"+ )+ current_label = "withlogo"++ # Burn ASS subtitles+ filter_parts.append(+ f"[{current_label}]ass='{safe_ass}'[out]"+ )++ filter_complex = ";".join(filter_parts)++ # Run with HW encoder, fallback to CPU if it fails+ enc_flags = get_video_encode_flags()+ cmd = [+ "ffmpeg", "-y",+ *inputs,+ "-filter_complex", filter_complex,+ "-map", "[out]",+ "-map", "0:a",+ *enc_flags,+ "-c:a", "copy",+ "-movflags", "+faststart",+ output_path,+ ]++ result = subprocess.run(cmd, capture_output=True, text=True)++ # Fallback to CPU if HW encoder failed+ if result.returncode != 0 and enc_flags != CPU_FLAGS:+ print(f"Warning: HW encoder failed for caption burn, falling back to libx264", file=sys.stderr)+ cmd_fallback = [+ "ffmpeg", "-y",+ *inputs,+ "-filter_complex", filter_complex,+ "-map", "[out]",+ "-map", "0:a",+ *CPU_FLAGS,+ "-c:a", "copy",+ "-movflags", "+faststart",+ output_path,+ ]+ result = subprocess.run(cmd_fallback, capture_output=True, text=True)++ # Clean up gradient file+ if gradient_overlay and os.path.exists(gradient_path):+ os.remove(gradient_path)++ if result.returncode != 0:+ raise RuntimeError(f"FFmpeg caption burn failed: {result.stderr[-500:]}")+ return output_path+++def normalize_audio(+ input_path: str,+ output_path: str,+ target_lufs: float = -14.0,+) -> str:+ """+ Normalize audio to target LUFS (loudness units).+ TikTok/YouTube Shorts standard is around -14 LUFS.+ """+ # First pass: measure current loudness+ measure_cmd = [+ "ffmpeg", "-y",+ "-i", input_path,+ "-af", f"loudnorm=I={target_lufs}:TP=-1.5:LRA=11:print_format=json",+ "-f", "null", "-",+ ]+ result = subprocess.run(measure_cmd, capture_output=True, text=True)++ # Try to parse loudnorm output from stderr+ stderr = result.stderr+ try:+ # Find the JSON block in stderr+ json_start = stderr.rfind("{")+ json_end = stderr.rfind("}") + 1+ if json_start >= 0 and json_end > json_start:+ loudnorm_data = json.loads(stderr[json_start:json_end])+ else:+ # Fallback: simple normalization without two-pass+ loudnorm_data = None+ except (json.JSONDecodeError, ValueError):+ loudnorm_data = None++ if loudnorm_data:+ # Second pass: apply measured correction+ af_filter = (+ f"loudnorm=I={target_lufs}:TP=-1.5:LRA=11:"+ f"measured_I={loudnorm_data.get('input_i', '-24')}:"+ f"measured_TP={loudnorm_data.get('input_tp', '-1')}:"+ f"measured_LRA={loudnorm_data.get('input_lra', '7')}:"+ f"measured_thresh={loudnorm_data.get('input_thresh', '-34')}:"+ f"offset={loudnorm_data.get('target_offset', '0')}:"+ f"linear=true"+ )+ else:+ # Single-pass fallback+ af_filter = f"loudnorm=I={target_lufs}:TP=-1.5:LRA=11"++ cmd = [+ "ffmpeg", "-y",+ "-i", input_path,+ "-af", af_filter,+ "-c:v", "copy",+ "-c:a", "aac",+ "-b:a", "128k",+ "-ar", "44100",+ "-movflags", "+faststart",+ output_path,+ ]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"FFmpeg normalize failed: {result.stderr[-500:]}")+ return output_path+++def _detect_face_offset(+ video_path: str,+ width: int,+ height: int,+ target_ratio: float,+) -> Optional[int]:+ """+ Detect face position in first few seconds and return crop x-offset.+ Returns None if no face detected (caller should fall back to center).+ """+ try:+ import cv2+ import numpy as np++ face_cascade = cv2.CascadeClassifier(+ cv2.data.haarcascades + "haarcascade_frontalface_default.xml"+ )++ cap = cv2.VideoCapture(video_path)+ face_positions = []++ # Sample ~30 frames from first 5 seconds+ for _ in range(30):+ ret, frame = cap.read()+ if not ret:+ break++ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)+ faces = face_cascade.detectMultiScale(gray, 1.3, 5, minSize=(50, 50))++ if len(faces) > 0:+ # Get largest face+ largest = max(faces, key=lambda f: f[2] * f[3])+ face_center_x = largest[0] + largest[2] // 2+ face_positions.append(face_center_x)++ cap.release()++ if not face_positions:+ return None++ # Average face center x position+ avg_face_x = int(np.mean(face_positions))++ # Calculate crop window centered on face+ crop_w = int(height * target_ratio)+ crop_x = avg_face_x - crop_w // 2++ # Clamp to valid range+ crop_x = max(0, min(crop_x, width - crop_w))++ return crop_x++ except ImportError:+ # OpenCV not installed, fall back to center+ return None+ except Exception:+ return Nonediff --git a/backend/utils/__init__.py b/backend/utils/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/backend/utils/timing_utils.py b/backend/utils/timing_utils.pynew file mode 100644index 0000000..abd58fe--- /dev/null+++ b/backend/utils/timing_utils.py@@ -0,0 +1,26 @@+"""Timestamp formatting utilities for ASS subtitles and FFmpeg."""+++def seconds_to_ass(seconds: float) -> str:+ """Convert seconds to ASS timestamp format: H:MM:SS.cc"""+ h = int(seconds // 3600)+ m = int((seconds % 3600) // 60)+ s = seconds % 60+ return f"{h}:{m:02d}:{s:05.2f}"+++def seconds_to_ffmpeg(seconds: float) -> str:+ """Convert seconds to FFmpeg timestamp: HH:MM:SS.mmm"""+ h = int(seconds // 3600)+ m = int((seconds % 3600) // 60)+ s = seconds % 60+ return f"{h:02d}:{m:02d}:{s:06.3f}"+++def seconds_to_srt(seconds: float) -> str:+ """Convert seconds to SRT timestamp: HH:MM:SS,mmm"""+ h = int(seconds // 3600)+ m = int((seconds % 3600) // 60)+ s = int(seconds % 60)+ ms = int((seconds % 1) * 1000)+ return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"diff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..cd41aa2--- /dev/null+++ b/package-lock.json@@ -0,0 +1,2614 @@+{+ "name": "podcli",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "podcli",+ "version": "1.0.0",+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.12.1",+ "dotenv": "^16.4.7",+ "express": "^4.21.0",+ "multer": "^1.4.5-lts.1",+ "uuid": "^11.1.0",+ "winston": "^3.17.0",+ "zod": "^3.24.2"+ },+ "devDependencies": {+ "@types/express": "^5.0.0",+ "@types/multer": "^1.4.12",+ "@types/node": "^22.12.0",+ "@types/uuid": "^10.0.0",+ "tsx": "^4.19.0",+ "typescript": "^5.7.0"+ }+ },+ "node_modules/@colors/colors": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",+ "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.1.90"+ }+ },+ "node_modules/@dabh/diagnostics": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.8.tgz",+ "integrity": "sha512-R4MSXTVnuMzGD7bzHdW2ZhhdPC/igELENcq5IjEverBvq5hn1SXCWcsi6eSsdWP0/Ur+SItRRjAktmdoX/8R/Q==",+ "license": "MIT",+ "dependencies": {+ "@so-ric/colorspace": "^1.1.6",+ "enabled": "2.0.x",+ "kuler": "^2.0.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.9",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz",+ "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.27.1",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz",+ "integrity": "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/content-disposition": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",+ "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/type-is": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^1.0.5",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/@so-ric/colorspace": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/@so-ric/colorspace/-/colorspace-1.1.6.tgz",+ "integrity": "sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==",+ "license": "MIT",+ "dependencies": {+ "color": "^5.0.2",+ "text-hex": "1.0.x"+ }+ },+ "node_modules/@types/body-parser": {+ "version": "1.19.6",+ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",+ "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/connect": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/express": {+ "version": "5.0.6",+ "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",+ "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/body-parser": "*",+ "@types/express-serve-static-core": "^5.0.0",+ "@types/serve-static": "^2"+ }+ },+ "node_modules/@types/express-serve-static-core": {+ "version": "5.1.1",+ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",+ "integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "@types/qs": "*",+ "@types/range-parser": "*",+ "@types/send": "*"+ }+ },+ "node_modules/@types/http-errors": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz",+ "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/multer": {+ "version": "1.4.13",+ "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz",+ "integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/express": "*"+ }+ },+ "node_modules/@types/node": {+ "version": "22.19.12",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.12.tgz",+ "integrity": "sha512-0QEp0aPJYSyf6RrTjDB7HlKgNMTY+V2C7ESTaVt6G9gQ0rPLzTGz7OF2NXTLR5vcy7HJEtIUsyWLsfX0kTqJBA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/qs": {+ "version": "6.14.0",+ "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz",+ "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/range-parser": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz",+ "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz",+ "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/serve-static": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz",+ "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/http-errors": "*",+ "@types/node": "*"+ }+ },+ "node_modules/@types/triple-beam": {+ "version": "1.3.5",+ "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",+ "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",+ "license": "MIT"+ },+ "node_modules/@types/uuid": {+ "version": "10.0.0",+ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz",+ "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/accepts": {+ "version": "1.3.8",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",+ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "~2.1.34",+ "negotiator": "0.6.3"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/ajv": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",+ "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/append-field": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",+ "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",+ "license": "MIT"+ },+ "node_modules/array-flatten": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",+ "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",+ "license": "MIT"+ },+ "node_modules/async": {+ "version": "3.2.6",+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",+ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",+ "license": "MIT"+ },+ "node_modules/body-parser": {+ "version": "1.20.4",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz",+ "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "content-type": "~1.0.5",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "destroy": "~1.2.0",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.4.24",+ "on-finished": "~2.4.1",+ "qs": "~6.14.0",+ "raw-body": "~2.5.3",+ "type-is": "~1.6.18",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8",+ "npm": "1.2.8000 || >= 1.4.16"+ }+ },+ "node_modules/body-parser/node_modules/iconv-lite": {+ "version": "0.4.24",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",+ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/body-parser/node_modules/raw-body": {+ "version": "2.5.3",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",+ "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.4.24",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/buffer-from": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",+ "license": "MIT"+ },+ "node_modules/busboy": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",+ "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",+ "dependencies": {+ "streamsearch": "^1.1.0"+ },+ "engines": {+ "node": ">=10.16.0"+ }+ },+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/color": {+ "version": "5.0.3",+ "resolved": "https://registry.npmjs.org/color/-/color-5.0.3.tgz",+ "integrity": "sha512-ezmVcLR3xAVp8kYOm4GS45ZLLgIE6SPAFoduLr6hTDajwb3KZ2F46gulK3XpcwRFb5KKGCSezCBAY4Dw4HsyXA==",+ "license": "MIT",+ "dependencies": {+ "color-convert": "^3.1.3",+ "color-string": "^2.1.3"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/color-convert": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-3.1.3.tgz",+ "integrity": "sha512-fasDH2ont2GqF5HpyO4w0+BcewlhHEZOFn9c1ckZdHpJ56Qb7MHhH/IcJZbBGgvdtwdwNbLvxiBEdg336iA9Sg==",+ "license": "MIT",+ "dependencies": {+ "color-name": "^2.0.0"+ },+ "engines": {+ "node": ">=14.6"+ }+ },+ "node_modules/color-name": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-2.1.0.tgz",+ "integrity": "sha512-1bPaDNFm0axzE4MEAzKPuqKWeRaT43U/hyxKPBdqTfmPF+d6n7FSoTFxLVULUJOmiLp01KjhIPPH+HrXZJN4Rg==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20"+ }+ },+ "node_modules/color-string": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/color-string/-/color-string-2.1.4.tgz",+ "integrity": "sha512-Bb6Cq8oq0IjDOe8wJmi4JeNn763Xs9cfrBcaylK1tPypWzyoy2G3l90v9k64kjphl/ZJjPIShFztenRomi8WTg==",+ "license": "MIT",+ "dependencies": {+ "color-name": "^2.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/concat-stream": {+ "version": "1.6.2",+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",+ "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",+ "engines": [+ "node >= 0.8"+ ],+ "license": "MIT",+ "dependencies": {+ "buffer-from": "^1.0.0",+ "inherits": "^2.0.3",+ "readable-stream": "^2.2.2",+ "typedarray": "^0.0.6"+ }+ },+ "node_modules/concat-stream/node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },+ "node_modules/concat-stream/node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "license": "MIT"+ },+ "node_modules/concat-stream/node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },+ "node_modules/content-disposition": {+ "version": "0.5.4",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",+ "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "5.2.1"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",+ "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",+ "license": "MIT"+ },+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "license": "MIT"+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/debug/node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/destroy": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",+ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8",+ "npm": "1.2.8000 || >= 1.4.16"+ }+ },+ "node_modules/dotenv": {+ "version": "16.6.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",+ "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },+ "node_modules/enabled": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",+ "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==",+ "license": "MIT"+ },+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.3",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.3",+ "@esbuild/android-arm": "0.27.3",+ "@esbuild/android-arm64": "0.27.3",+ "@esbuild/android-x64": "0.27.3",+ "@esbuild/darwin-arm64": "0.27.3",+ "@esbuild/darwin-x64": "0.27.3",+ "@esbuild/freebsd-arm64": "0.27.3",+ "@esbuild/freebsd-x64": "0.27.3",+ "@esbuild/linux-arm": "0.27.3",+ "@esbuild/linux-arm64": "0.27.3",+ "@esbuild/linux-ia32": "0.27.3",+ "@esbuild/linux-loong64": "0.27.3",+ "@esbuild/linux-mips64el": "0.27.3",+ "@esbuild/linux-ppc64": "0.27.3",+ "@esbuild/linux-riscv64": "0.27.3",+ "@esbuild/linux-s390x": "0.27.3",+ "@esbuild/linux-x64": "0.27.3",+ "@esbuild/netbsd-arm64": "0.27.3",+ "@esbuild/netbsd-x64": "0.27.3",+ "@esbuild/openbsd-arm64": "0.27.3",+ "@esbuild/openbsd-x64": "0.27.3",+ "@esbuild/openharmony-arm64": "0.27.3",+ "@esbuild/sunos-x64": "0.27.3",+ "@esbuild/win32-arm64": "0.27.3",+ "@esbuild/win32-ia32": "0.27.3",+ "@esbuild/win32-x64": "0.27.3"+ }+ },+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/express": {+ "version": "4.22.1",+ "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",+ "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "accepts": "~1.3.8",+ "array-flatten": "1.1.1",+ "body-parser": "~1.20.3",+ "content-disposition": "~0.5.4",+ "content-type": "~1.0.4",+ "cookie": "~0.7.1",+ "cookie-signature": "~1.0.6",+ "debug": "2.6.9",+ "depd": "2.0.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "finalhandler": "~1.3.1",+ "fresh": "~0.5.2",+ "http-errors": "~2.0.0",+ "merge-descriptors": "1.0.3",+ "methods": "~1.1.2",+ "on-finished": "~2.4.1",+ "parseurl": "~1.3.3",+ "path-to-regexp": "~0.1.12",+ "proxy-addr": "~2.0.7",+ "qs": "~6.14.0",+ "range-parser": "~1.2.1",+ "safe-buffer": "5.2.1",+ "send": "~0.19.0",+ "serve-static": "~1.16.2",+ "setprototypeof": "1.2.0",+ "statuses": "~2.0.1",+ "type-is": "~1.6.18",+ "utils-merge": "1.0.1",+ "vary": "~1.1.2"+ },+ "engines": {+ "node": ">= 0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.2.1",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz",+ "integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "10.0.1"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fecha": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",+ "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==",+ "license": "MIT"+ },+ "node_modules/finalhandler": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",+ "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",+ "license": "MIT",+ "dependencies": {+ "debug": "2.6.9",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "on-finished": "~2.4.1",+ "parseurl": "~1.3.3",+ "statuses": "~2.0.2",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/fn.name": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",+ "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",+ "license": "MIT"+ },+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",+ "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/get-tsconfig": {+ "version": "4.13.6",+ "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",+ "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "resolve-pkg-maps": "^1.0.0"+ },+ "funding": {+ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.2",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.2.tgz",+ "integrity": "sha512-gJnaDHXKDayjt8ue0n8Gs0A007yKXj4Xzb8+cNjZeYsSzzwKc0Lr+OZgYwVfB0pHfUs17EPoLvrOsEaJ9mj+Tg==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },+ "node_modules/ip-address": {+ "version": "10.0.1",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz",+ "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "license": "MIT"+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "6.1.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.3.tgz",+ "integrity": "sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },+ "node_modules/kuler": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",+ "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==",+ "license": "MIT"+ },+ "node_modules/logform": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",+ "integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",+ "license": "MIT",+ "dependencies": {+ "@colors/colors": "1.6.0",+ "@types/triple-beam": "^1.3.2",+ "fecha": "^4.2.0",+ "ms": "^2.1.1",+ "safe-stable-stringify": "^2.3.1",+ "triple-beam": "^1.3.0"+ },+ "engines": {+ "node": ">= 12.0.0"+ }+ },+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",+ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",+ "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/methods": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",+ "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/mkdirp": {+ "version": "0.5.6",+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",+ "license": "MIT",+ "dependencies": {+ "minimist": "^1.2.6"+ },+ "bin": {+ "mkdirp": "bin/cmd.js"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/multer": {+ "version": "1.4.5-lts.2",+ "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz",+ "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==",+ "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.",+ "license": "MIT",+ "dependencies": {+ "append-field": "^1.0.0",+ "busboy": "^1.0.0",+ "concat-stream": "^1.5.2",+ "mkdirp": "^0.5.4",+ "object-assign": "^4.1.1",+ "type-is": "^1.6.4",+ "xtend": "^4.0.0"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/negotiator": {+ "version": "0.6.3",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",+ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },+ "node_modules/one-time": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",+ "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",+ "license": "MIT",+ "dependencies": {+ "fn.name": "1.x.x"+ }+ },+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",+ "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",+ "license": "MIT"+ },+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "license": "MIT"+ },+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/qs": {+ "version": "6.14.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",+ "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "license": "MIT",+ "dependencies": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/resolve-pkg-maps": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",+ "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"+ }+ },+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/router/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/router/node_modules/path-to-regexp": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",+ "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/safe-stable-stringify": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/safer-buffer": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",+ "license": "MIT"+ },+ "node_modules/send": {+ "version": "0.19.2",+ "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",+ "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",+ "license": "MIT",+ "dependencies": {+ "debug": "2.6.9",+ "depd": "2.0.0",+ "destroy": "1.2.0",+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "etag": "~1.8.1",+ "fresh": "~0.5.2",+ "http-errors": "~2.0.1",+ "mime": "1.6.0",+ "ms": "2.1.3",+ "on-finished": "~2.4.1",+ "range-parser": "~1.2.1",+ "statuses": "~2.0.2"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/serve-static": {+ "version": "1.16.3",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",+ "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "~2.0.0",+ "escape-html": "~1.0.3",+ "parseurl": "~1.3.3",+ "send": "~0.19.1"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/stack-trace": {+ "version": "0.0.10",+ "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",+ "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/streamsearch": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",+ "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",+ "engines": {+ "node": ">=10.0.0"+ }+ },+ "node_modules/string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.2.0"+ }+ },+ "node_modules/text-hex": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",+ "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==",+ "license": "MIT"+ },+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },+ "node_modules/triple-beam": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",+ "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",+ "license": "MIT",+ "engines": {+ "node": ">= 14.0.0"+ }+ },+ "node_modules/tsx": {+ "version": "4.21.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",+ "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.27.0",+ "get-tsconfig": "^4.7.5"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/type-is": {+ "version": "1.6.18",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",+ "license": "MIT",+ "dependencies": {+ "media-typer": "0.3.0",+ "mime-types": "~2.1.24"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/typedarray": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",+ "license": "MIT"+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/utils-merge": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",+ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4.0"+ }+ },+ "node_modules/uuid": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist/esm/bin/uuid"+ }+ },+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/winston": {+ "version": "3.19.0",+ "resolved": "https://registry.npmjs.org/winston/-/winston-3.19.0.tgz",+ "integrity": "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA==",+ "license": "MIT",+ "dependencies": {+ "@colors/colors": "^1.6.0",+ "@dabh/diagnostics": "^2.0.8",+ "async": "^3.2.3",+ "is-stream": "^2.0.0",+ "logform": "^2.7.0",+ "one-time": "^1.0.0",+ "readable-stream": "^3.4.0",+ "safe-stable-stringify": "^2.3.1",+ "stack-trace": "0.0.x",+ "triple-beam": "^1.3.0",+ "winston-transport": "^4.9.0"+ },+ "engines": {+ "node": ">= 12.0.0"+ }+ },+ "node_modules/winston-transport": {+ "version": "4.9.0",+ "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",+ "integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",+ "license": "MIT",+ "dependencies": {+ "logform": "^2.7.0",+ "readable-stream": "^3.6.2",+ "triple-beam": "^1.3.0"+ },+ "engines": {+ "node": ">= 12.0.0"+ }+ },+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },+ "node_modules/xtend": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "peer": true,+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.1",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz",+ "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25 || ^4"+ }+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..4dd81a1--- /dev/null+++ b/package.json@@ -0,0 +1,31 @@+{+ "name": "podcli",+ "version": "1.0.0",+ "description": "podcli — AI-powered podcast clip generator for TikTok/YouTube Shorts",+ "type": "module",+ "main": "dist/index.js",+ "scripts": {+ "build": "tsc",+ "start": "node dist/index.js",+ "dev": "tsx src/index.ts",+ "ui": "tsx src/ui/web-server.ts",+ "ui:prod": "node dist/ui/web-server.js"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.12.1",+ "dotenv": "^16.4.7",+ "express": "^4.21.0",+ "multer": "^1.4.5-lts.1",+ "uuid": "^11.1.0",+ "winston": "^3.17.0",+ "zod": "^3.24.2"+ },+ "devDependencies": {+ "@types/express": "^5.0.0",+ "@types/multer": "^1.4.12",+ "@types/node": "^22.12.0",+ "@types/uuid": "^10.0.0",+ "tsx": "^4.19.0",+ "typescript": "^5.7.0"+ }+}diff --git a/podcli b/podclinew file mode 100755index 0000000..ffe0d58--- /dev/null+++ b/podcli@@ -0,0 +1,17 @@+#!/bin/bash+# podcli — CLI wrapper+# Usage: ./podcli process video.mp4 --top 5 --transcript file.txt++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"++# Use venv python if available+if [ -f "$SCRIPT_DIR/venv/bin/python3" ]; then+ PYTHON="$SCRIPT_DIR/venv/bin/python3"+elif [ -f "$SCRIPT_DIR/.env" ]; then+ PYTHON=$(grep '^PYTHON_PATH=' "$SCRIPT_DIR/.env" | cut -d'=' -f2-)+ [ -z "$PYTHON" ] && PYTHON="python3"+else+ PYTHON="python3"+fi++exec "$PYTHON" "$SCRIPT_DIR/backend/cli.py" "$@"diff --git a/setup.sh b/setup.shnew file mode 100755index 0000000..52a7ecc--- /dev/null+++ b/setup.sh@@ -0,0 +1,184 @@+#!/bin/bash+set -e++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$SCRIPT_DIR"++# ============================================================+# podcli — Install & Launch+# Usage:+# ./setup.sh # Install everything + open UI+# ./setup.sh --install # Install only (no launch)+# ./setup.sh --ui # Launch UI only (skip install)+# ./setup.sh --mcp # Show MCP config (for Claude Desktop/Code)+# ============================================================++MODE="${1:-full}"++echo ""+echo " ╔══════════════════════════════════════╗"+echo " ║ 🎬 podcli v1.0 ║"+echo " ╚══════════════════════════════════════╝"+echo ""++# ---- Install ----+install() {+ echo "━━━ [1/6] Checking system dependencies ━━━"++ local MISSING=0++ if ! command -v ffmpeg &>/dev/null; then+ echo " ✗ FFmpeg not found"+ echo " → macOS: brew install ffmpeg"+ echo " → Ubuntu: sudo apt install ffmpeg"+ echo " → Windows: choco install ffmpeg"+ MISSING=1+ else+ echo " ✓ FFmpeg"+ fi++ if ! command -v python3 &>/dev/null; then+ echo " ✗ Python 3 not found"+ MISSING=1+ else+ echo " ✓ Python $(python3 --version 2>&1 | awk '{print $2}')"+ fi++ if ! command -v node &>/dev/null; then+ echo " ✗ Node.js not found"+ MISSING=1+ else+ echo " ✓ Node $(node --version)"+ fi++ if [ "$MISSING" -eq 1 ]; then+ echo ""+ echo " Please install the missing dependencies above and re-run."+ exit 1+ fi++ echo ""+ echo "━━━ [2/6] Creating directories ━━━"+ CLIPPER_HOME="${PODCLI_HOME:-$HOME/.podcli}"+ mkdir -p "$CLIPPER_HOME"/{cache/transcripts,working,working/uploads,output,logs}+ echo " ✓ $CLIPPER_HOME"++ echo ""+ echo "━━━ [3/6] Python virtual environment ━━━"+ if [ ! -d "venv" ]; then+ python3 -m venv venv+ echo " ✓ Created venv"+ else+ echo " ✓ venv exists"+ fi++ source venv/bin/activate+ echo ""+ echo "━━━ [4/6] Installing Python packages ━━━"+ pip install -q --upgrade pip+ pip install -q -r backend/requirements.txt 2>&1 | tail -3+ echo " ✓ Python packages ready"++ echo ""+ echo "━━━ [5/6] Installing Node packages ━━━"+ npm install --silent 2>&1 | tail -1+ echo " ✓ Node packages ready"++ echo ""+ echo "━━━ [6/6] Building TypeScript ━━━"+ npx tsc+ echo " ✓ Build complete"++ # Create .env+ VENV_PYTHON="$(pwd)/venv/bin/python3"+ if [ ! -f .env ]; then+ cp .env.example .env+ fi+ # Always update PYTHON_PATH to point at venv (handles re-runs)+ if [[ "$OSTYPE" == "darwin"* ]]; then+ sed -i '' "s|^PYTHON_PATH=.*|PYTHON_PATH=$VENV_PYTHON|" .env+ else+ sed -i "s|^PYTHON_PATH=.*|PYTHON_PATH=$VENV_PYTHON|" .env+ fi+ echo " ✓ .env configured (python: $VENV_PYTHON)"++ # Copy public assets to dist+ mkdir -p dist/ui/public+ cp -r src/ui/public/* dist/ui/public/++ echo ""+ echo " ✅ Installation complete!"+ echo ""+}++# ---- Launch UI ----+launch_ui() {+ echo " Starting web UI..."+ echo ""++ # Ensure public files are in dist+ mkdir -p dist/ui/public+ cp -r src/ui/public/* dist/ui/public/ 2>/dev/null || true++ # Always use venv python (absolute path, no spaces issue)+ if [ -f "venv/bin/python3" ]; then+ export PYTHON_PATH="$(cd "$(pwd)" && pwd)/venv/bin/python3"+ echo " Using Python: $PYTHON_PATH"+ fi++ # Load .env (line-by-line to handle spaces in values)+ if [ -f .env ]; then+ while IFS='=' read -r key value; do+ # Skip comments and empty lines+ [[ "$key" =~ ^#.*$ || -z "$key" ]] && continue+ # PYTHON_PATH from venv takes priority over .env+ [[ "$key" == "PYTHON_PATH" ]] && continue+ export "$key=$value"+ done < .env+ fi++ exec npx tsx src/ui/web-server.ts+}++# ---- Show MCP config ----+show_mcp() {+ VENV_PYTHON="$(pwd)/venv/bin/python3"+ echo " ── Claude Desktop config ──"+ echo " Add to ~/Library/Application Support/Claude/claude_desktop_config.json:"+ echo ""+ echo " {"+ echo " \"mcpServers\": {"+ echo " \"podcli\": {"+ echo " \"command\": \"node\","+ echo " \"args\": [\"$(pwd)/dist/index.js\"],"+ echo " \"env\": {"+ echo " \"PYTHON_PATH\": \"$VENV_PYTHON\""+ echo " }"+ echo " }"+ echo " }"+ echo " }"+ echo ""+ echo " ── Claude Code ──"+ echo " claude mcp add podcli -- node $(pwd)/dist/index.js"+ echo ""+}++# ---- Route ----+case "$MODE" in+ --install)+ install+ ;;+ --ui)+ launch_ui+ ;;+ --mcp)+ show_mcp+ ;;+ full|*)+ install+ echo ""+ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo ""+ launch_ui+ ;;+esacdiff --git a/src/config/paths.ts b/src/config/paths.tsnew file mode 100644index 0000000..4a85ae1--- /dev/null+++ b/src/config/paths.ts@@ -0,0 +1,21 @@+import { homedir } from "os";+import { join, dirname } from "path";+import { fileURLToPath } from "url";++const __dirname = dirname(fileURLToPath(import.meta.url));++const home =+ process.env.PODCLI_HOME || join(homedir(), ".podcli");++export const paths = {+ home,+ cache: join(home, "cache"),+ transcripts: join(home, "cache", "transcripts"),+ working: join(home, "working"),+ output: join(home, "output"),+ logs: join(home, "logs"),+ pythonBackend: join(__dirname, "..", "..", "backend", "main.py"),+ pythonPath: process.env.PYTHON_PATH || "python3",+ ffmpegPath: process.env.FFMPEG_PATH || "ffmpeg",+ ffprobePath: process.env.FFPROBE_PATH || "ffprobe",+};diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.tsnew file mode 100644index 0000000..ccb000f--- /dev/null+++ b/src/handlers/batch-clips.handler.ts@@ -0,0 +1,80 @@+import { PythonExecutor } from "../services/python-executor.js";+import { FileManager } from "../services/file-manager.js";+import { paths } from "../config/paths.js";++const executor = new PythonExecutor();+const fileManager = new FileManager();++export const batchClipsToolDef = {+ name: "batch_create_clips",+ description:+ "Create multiple short-form clips from a podcast in one batch. " ++ "Each clip is independently cropped, captioned, and exported. " ++ "Returns status for each clip (success/error).",+ inputSchema: {+ type: "object" as const,+ properties: {+ video_path: {+ type: "string",+ description: "Path to the original podcast video",+ },+ clips: {+ type: "array",+ description: "Array of clips to create",+ items: {+ type: "object",+ properties: {+ start_second: { type: "number" },+ end_second: { type: "number" },+ title: { type: "string" },+ caption_style: {+ type: "string",+ enum: ["hormozi", "karaoke", "subtle", "branded"],+ },+ crop_strategy: {+ type: "string",+ enum: ["center", "face"],+ },+ },+ required: ["start_second", "end_second"],+ },+ },+ transcript_words: {+ type: "array",+ description: "Word-level timestamps from transcribe_podcast",+ items: {+ type: "object",+ properties: {+ word: { type: "string" },+ start: { type: "number" },+ end: { type: "number" },+ confidence: { type: "number" },+ },+ },+ },+ },+ required: ["video_path", "clips", "transcript_words"],+ },+};++export async function handleBatchClips(+ input: Record<string, unknown>+): Promise<string> {+ await fileManager.ensureDirectories();++ const result = await executor.execute("batch_clips", {+ video_path: input.video_path,+ clips: input.clips,+ transcript_words: input.transcript_words || [],+ output_dir: paths.output,+ });++ const data = result.data as Record<string, unknown>;++ return JSON.stringify({+ total_clips: data.total_clips,+ successful_clips: data.successful_clips,+ results: data.results,+ message: `Batch complete: ${data.successful_clips}/${data.total_clips} clips created successfully.`,+ });+}diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.tsnew file mode 100644index 0000000..dbbd30b--- /dev/null+++ b/src/handlers/create-clip.handler.ts@@ -0,0 +1,109 @@+import { PythonExecutor } from "../services/python-executor.js";+import { FileManager } from "../services/file-manager.js";+import { paths } from "../config/paths.js";+import type { ClipResult } from "../models/index.js";++const executor = new PythonExecutor();+const fileManager = new FileManager();++export const createClipToolDef = {+ name: "create_clip",+ description:+ "Create a finished short-form video clip ready for TikTok/YouTube Shorts. " ++ "Takes a segment from the podcast, crops to 9:16 vertical (1080x1920), " ++ "burns styled captions, normalizes audio to -14 LUFS, and exports as H.264 MP4. " ++ "Requires transcript_words from transcribe_podcast for caption timing.",+ inputSchema: {+ type: "object" as const,+ properties: {+ video_path: {+ type: "string",+ description: "Path to the original podcast video file",+ },+ start_second: {+ type: "number",+ description: "Clip start time in seconds",+ },+ end_second: {+ type: "number",+ description: "Clip end time in seconds (max 180s clip length)",+ },+ caption_style: {+ type: "string",+ enum: ["hormozi", "karaoke", "subtle", "branded"],+ description:+ "Caption style: hormozi (bold word-by-word), karaoke (progressive highlight), subtle (clean bottom text). Default: hormozi",+ default: "hormozi",+ },+ crop_strategy: {+ type: "string",+ enum: ["center", "face"],+ description:+ "How to crop to vertical: center (fast, default) or face (detect speaker face). Default: center",+ default: "center",+ },+ transcript_words: {+ type: "array",+ description: "Word-level timestamps from transcribe_podcast",+ items: {+ type: "object",+ properties: {+ word: { type: "string" },+ start: { type: "number" },+ end: { type: "number" },+ confidence: { type: "number" },+ },+ },+ },+ title: {+ type: "string",+ description: "Short title for the clip (used in filename)",+ },+ logo_path: {+ type: "string",+ description: "Path to a PNG logo image. Shown in top-left corner (used with 'branded' style).",+ },+ // === EXTENSIBILITY: Future pipeline steps ===+ outro_video_path: {+ type: "string",+ description: "[Future] Path to an outro video to append at the end",+ },+ generate_thumbnail: {+ type: "boolean",+ description: "[Future] Whether to auto-generate a thumbnail image",+ default: false,+ },+ },+ required: ["video_path", "start_second", "end_second", "transcript_words"],+ },+};++export async function handleCreateClip(+ input: Record<string, unknown>+): Promise<string> {+ await fileManager.ensureDirectories();++ const result = await executor.execute("create_clip", {+ video_path: input.video_path,+ start_second: input.start_second,+ end_second: input.end_second,+ caption_style: input.caption_style || "hormozi",+ crop_strategy: input.crop_strategy || "center",+ transcript_words: input.transcript_words || [],+ title: input.title || "clip",+ output_dir: paths.output,+ logo_path: input.logo_path || null,+ // Pass through future extensibility params+ outro_video_path: input.outro_video_path || null,+ generate_thumbnail: input.generate_thumbnail || false,+ });++ const data = result.data as unknown as ClipResult;++ return JSON.stringify({+ output_path: data.output_path,+ duration: data.duration,+ file_size_mb: data.file_size_mb,+ message: `Clip created successfully! ${data.duration}s, ${data.file_size_mb}MB`,+ });+}diff --git a/src/handlers/suggest-clips.handler.ts b/src/handlers/suggest-clips.handler.tsnew file mode 100644index 0000000..e227893--- /dev/null+++ b/src/handlers/suggest-clips.handler.ts@@ -0,0 +1,94 @@+/**+ * suggest_clips tool — helps Claude structure its clip suggestions.+ *+ * This tool doesn't do heavy processing. Claude analyzes the transcript+ * in conversation, then calls this tool to store/format the suggestions.+ */++export const suggestClipsToolDef = {+ name: "suggest_clips",+ description:+ "Store and structure clip suggestions from transcript analysis. " ++ "Use after analyzing a transcript to format suggested viral moments " ++ "with timestamps, titles, and reasoning. Claude should analyze the " ++ "transcript first, then call this tool to present suggestions to the user.",+ inputSchema: {+ type: "object" as const,+ properties: {+ suggestions: {+ type: "array",+ description: "Array of suggested clip moments",+ items: {+ type: "object",+ properties: {+ title: {+ type: "string",+ description: "Short catchy title for the clip",+ },+ start_second: {+ type: "number",+ description: "Start timestamp in seconds",+ },+ end_second: {+ type: "number",+ description: "End timestamp in seconds",+ },+ reasoning: {+ type: "string",+ description: "Why this moment is viral-worthy",+ },+ preview_text: {+ type: "string",+ description: "Brief text preview of what's said",+ },+ suggested_caption_style: {+ type: "string",+ enum: ["hormozi", "karaoke", "subtle", "branded"],+ description: "Recommended caption style for this clip",+ },+ },+ required: ["title", "start_second", "end_second", "reasoning"],+ },+ },+ },+ required: ["suggestions"],+ },+};++export async function handleSuggestClips(+ input: Record<string, unknown>+): Promise<string> {+ const suggestions = input.suggestions as Array<{+ title: string;+ start_second: number;+ end_second: number;+ reasoning: string;+ preview_text?: string;+ suggested_caption_style?: string;+ }>;++ // Validate and enrich suggestions+ const enriched = suggestions.map((s, i) => ({+ clip_id: `clip_${i + 1}`,+ title: s.title,+ start_second: s.start_second,+ end_second: s.end_second,+ duration: Math.round((s.end_second - s.start_second) * 10) / 10,+ reasoning: s.reasoning,+ preview_text: s.preview_text || "",+ suggested_caption_style: s.suggested_caption_style || "hormozi",+ timestamp_display: `${formatTime(s.start_second)} → ${formatTime(s.end_second)}`,+ }));++ return JSON.stringify({+ clip_count: enriched.length,+ total_content_seconds: enriched.reduce((sum, c) => sum + c.duration, 0),+ clips: enriched,+ });+}++function formatTime(seconds: number): string {+ const m = Math.floor(seconds / 60);+ const s = Math.floor(seconds % 60);+ return `${m}:${s.toString().padStart(2, "0")}`;+}diff --git a/src/handlers/transcribe.handler.ts b/src/handlers/transcribe.handler.tsnew file mode 100644index 0000000..72026f6--- /dev/null+++ b/src/handlers/transcribe.handler.ts@@ -0,0 +1,104 @@+import { PythonExecutor } from "../services/python-executor.js";+import { TranscriptCache } from "../services/transcript-cache.js";+import type { TranscriptResult } from "../models/index.js";++const executor = new PythonExecutor();+const cache = new TranscriptCache();++export const transcribeToolDef = {+ name: "transcribe_podcast",+ description:+ "Transcribe a podcast video/audio file with word-level timestamps and automatic " ++ "speaker detection. Identifies who is speaking when (supports 2-5 speakers). " ++ "Returns structured transcript with word timing and speaker labels. " ++ "Supports MP4, MOV, WebM, MKV, MP3, WAV.",+ inputSchema: {+ type: "object" as const,+ properties: {+ file_path: {+ type: "string",+ description: "Absolute path to the podcast file",+ },+ model_size: {+ type: "string",+ enum: ["tiny", "base", "small", "medium", "large"],+ description:+ "Whisper model size. tiny=fastest, large=most accurate. Default: base",+ default: "base",+ },+ language: {+ type: "string",+ description: "ISO language code (e.g. 'en'). Leave empty for auto-detect.",+ },+ enable_diarization: {+ type: "boolean",+ description:+ "Enable speaker detection (who is speaking). Requires pyannote.audio. Default: true",+ default: true,+ },+ num_speakers: {+ type: "number",+ description:+ "Exact number of speakers if known (e.g. 2 for a two-person podcast). " ++ "Leave empty to auto-detect (2-5 speakers).",+ },+ },+ required: ["file_path"],+ },+};++export async function handleTranscribe(+ input: Record<string, unknown>+): Promise<string> {+ const filePath = input.file_path as string;+ const modelSize = (input.model_size as string) || "base";+ const language = input.language as string | undefined;+ const enableDiarization = input.enable_diarization !== false; // default true+ const numSpeakers = input.num_speakers as number | undefined;++ // Check cache first+ const cached = await cache.get(filePath);+ if (cached) {+ return JSON.stringify({+ cached: true,+ ...formatResult(cached as unknown as Record<string, unknown>),+ });+ }++ // Execute transcription + diarization+ const result = await executor.execute("transcribe", {+ file_path: filePath,+ model_size: modelSize,+ language,+ enable_diarization: enableDiarization,+ num_speakers: numSpeakers,+ });++ const data = result.data as Record<string, unknown>;++ // Cache the result+ await cache.set(filePath, data as unknown as TranscriptResult);++ return JSON.stringify({+ cached: false,+ ...formatResult(data),+ });+}++function formatResult(data: Record<string, unknown>) {+ const words = (data.words as Array<Record<string, unknown>>) || [];+ const segments = (data.segments as Array<Record<string, unknown>>) || [];+ const speakers = data.speakers as Record<string, unknown> | undefined;++ return {+ transcript: data.transcript,+ segments,+ words,+ duration: data.duration,+ language: data.language,+ word_count: words.length,+ segment_count: segments.length,+ speakers: speakers || { num_speakers: 0, speakers: {} },+ speaker_segments: data.speaker_segments || [],+ };+}diff --git a/src/index.ts b/src/index.tsnew file mode 100644index 0000000..aefd0f4--- /dev/null+++ b/src/index.ts@@ -0,0 +1,31 @@+#!/usr/bin/env node+/**+ * podcli — MCP Server+ *+ * Entry point — starts the MCP server over stdio transport.+ * Connect this to Claude Desktop, Claude Code, or any MCP client.+ */++import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import { createServer } from "./server.js";+import { FileManager } from "./services/file-manager.js";++async function main() {+ // Ensure working directories exist+ const fileManager = new FileManager();+ await fileManager.ensureDirectories();++ // Create MCP server with all tools+ const server = createServer();++ // Start stdio transport (for Claude Desktop / Claude Code integration)+ const transport = new StdioServerTransport();+ await server.connect(transport);++ console.error("podcli MCP server running on stdio");+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/src/models/index.ts b/src/models/index.tsnew file mode 100644index 0000000..cb9c150--- /dev/null+++ b/src/models/index.ts@@ -0,0 +1,97 @@+// === Task Communication Models ===++export interface TaskRequest {+ task_id: string;+ task_type: "transcribe" | "parse_transcript" | "create_clip" | "batch_clips" | "analyze_energy" | "detect_encoder" | "presets" | "ping";+ params: Record<string, unknown>;+}++export interface TaskResult {+ task_id: string;+ status: "success" | "error";+ data?: Record<string, unknown>;+ error?: string;+}++export interface ProgressEvent {+ task_id: string;+ stage: string;+ percent: number;+ message: string;+}++// === Transcript Models ===++export interface WordTimestamp {+ word: string;+ start: number;+ end: number;+ confidence: number;+ speaker?: string | null;+}++export interface TranscriptSegment {+ id: number;+ start: number;+ end: number;+ text: string;+ speaker?: string | null;+}++export interface SpeakerInfo {+ total_time: number;+ segments: number;+ label: string;+}++export interface SpeakerSummary {+ num_speakers: number;+ speakers: Record<string, SpeakerInfo>;+}++export interface SpeakerSegment {+ speaker: string;+ start: number;+ end: number;+}++export interface TranscriptResult {+ transcript: string;+ segments: TranscriptSegment[];+ words: WordTimestamp[];+ duration: number;+ language: string;+ speakers: SpeakerSummary;+ speaker_segments: SpeakerSegment[];+}++// === Clip Models ===++export type CaptionStyle = "hormozi" | "karaoke" | "subtle";+export type CropStrategy = "center" | "face";++export interface ClipRequest {+ video_path: string;+ start_second: number;+ end_second: number;+ caption_style: CaptionStyle;+ crop_strategy: CropStrategy;+ title?: string;+ transcript_words: WordTimestamp[];+}++export interface ClipResult {+ output_path: string;+ duration: number;+ file_size_mb: number;+}++export interface SuggestedClip {+ clip_id: string;+ title: string;+ start_second: number;+ end_second: number;+ duration: number;+ reasoning: string;+ preview_text: string;+}diff --git a/src/server.ts b/src/server.tsnew file mode 100644index 0000000..569adf1--- /dev/null+++ b/src/server.ts@@ -0,0 +1,195 @@+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { z } from "zod";++import { transcribeToolDef, handleTranscribe } from "./handlers/transcribe.handler.js";+import { suggestClipsToolDef, handleSuggestClips } from "./handlers/suggest-clips.handler.js";+import { createClipToolDef, handleCreateClip } from "./handlers/create-clip.handler.js";+import { batchClipsToolDef, handleBatchClips } from "./handlers/batch-clips.handler.js";+import { FileManager } from "./services/file-manager.js";+import { paths } from "./config/paths.js";++export function createServer(): McpServer {+ const server = new McpServer({+ name: "podcli",+ version: "1.0.0",+ });++ // =============================================+ // Tool: transcribe_podcast+ // =============================================+ server.tool(+ transcribeToolDef.name,+ transcribeToolDef.description,+ {+ file_path: z.string().describe("Absolute path to the podcast file"),+ model_size: z+ .enum(["tiny", "base", "small", "medium", "large"])+ .optional()+ .default("base")+ .describe("Whisper model size"),+ language: z.string().optional().describe("ISO language code"),+ enable_diarization: z+ .boolean()+ .optional()+ .default(true)+ .describe("Enable speaker detection (who is speaking). Default: true"),+ num_speakers: z+ .number()+ .optional()+ .describe("Exact number of speakers if known (e.g. 2). Auto-detects if omitted."),+ },+ async ({ file_path, model_size, language, enable_diarization, num_speakers }) => {+ try {+ const result = await handleTranscribe({ file_path, model_size, language, enable_diarization, num_speakers });+ return { content: [{ type: "text" as const, text: result }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return {+ content: [{ type: "text" as const, text: `Error: ${msg}` }],+ isError: true,+ };+ }+ }+ );++ // =============================================+ // Tool: suggest_clips+ // =============================================+ server.tool(+ suggestClipsToolDef.name,+ suggestClipsToolDef.description,+ {+ suggestions: z+ .array(+ z.object({+ title: z.string(),+ start_second: z.number(),+ end_second: z.number(),+ reasoning: z.string(),+ preview_text: z.string().optional(),+ suggested_caption_style: z+ .enum(["hormozi", "karaoke", "subtle", "branded"])+ .optional(),+ })+ )+ .describe("Array of suggested clip moments"),+ },+ async ({ suggestions }) => {+ try {+ const result = await handleSuggestClips({ suggestions });+ return { content: [{ type: "text" as const, text: result }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return {+ content: [{ type: "text" as const, text: `Error: ${msg}` }],+ isError: true,+ };+ }+ }+ );++ // =============================================+ // Tool: create_clip+ // =============================================+ server.tool(+ createClipToolDef.name,+ createClipToolDef.description,+ {+ video_path: z.string().describe("Path to the original podcast video"),+ start_second: z.number().describe("Clip start time in seconds"),+ end_second: z.number().describe("Clip end time in seconds"),+ caption_style: z+ .enum(["hormozi", "karaoke", "subtle", "branded"])+ .optional()+ .default("hormozi")+ .describe("Caption style"),+ crop_strategy: z+ .enum(["center", "face"])+ .optional()+ .default("center")+ .describe("Cropping strategy"),+ transcript_words: z+ .array(+ z.object({+ word: z.string(),+ start: z.number(),+ end: z.number(),+ confidence: z.number().optional().default(0),+ })+ )+ .describe("Word-level timestamps"),+ title: z.string().optional().default("clip").describe("Clip title"),+ logo_path: z+ .string()+ .optional()+ .describe("Path to PNG logo image. Shown in top-left (used with 'branded' style)."),+ outro_video_path: z+ .string()+ .optional()+ .describe("[Future] Path to outro video to append"),+ generate_thumbnail: z+ .boolean()+ .optional()+ .default(false)+ .describe("[Future] Auto-generate thumbnail"),+ },+ async (params) => {+ try {+ const result = await handleCreateClip(params);+ return { content: [{ type: "text" as const, text: result }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return {+ content: [{ type: "text" as const, text: `Error: ${msg}` }],+ isError: true,+ };+ }+ }+ );++ // =============================================+ // Tool: batch_create_clips+ // =============================================+ server.tool(+ batchClipsToolDef.name,+ batchClipsToolDef.description,+ {+ video_path: z.string().describe("Path to the original podcast video"),+ clips: z+ .array(+ z.object({+ start_second: z.number(),+ end_second: z.number(),+ title: z.string().optional(),+ caption_style: z.enum(["hormozi", "karaoke", "subtle", "branded"]).optional(),+ crop_strategy: z.enum(["center", "face"]).optional(),+ })+ )+ .describe("Array of clips to create"),+ transcript_words: z+ .array(+ z.object({+ word: z.string(),+ start: z.number(),+ end: z.number(),+ confidence: z.number().optional().default(0),+ })+ )+ .describe("Word-level timestamps"),+ },+ async (params) => {+ try {+ const result = await handleBatchClips(params);+ return { content: [{ type: "text" as const, text: result }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return {+ content: [{ type: "text" as const, text: `Error: ${msg}` }],+ isError: true,+ };+ }+ }+ );++ return server;+}diff --git a/src/services/file-manager.ts b/src/services/file-manager.tsnew file mode 100644index 0000000..eac2f0a--- /dev/null+++ b/src/services/file-manager.ts@@ -0,0 +1,80 @@+import { mkdir, rm, readdir, stat, rename } from "fs/promises";+import { existsSync } from "fs";+import { join } from "path";+import { v4 as uuidv4 } from "uuid";+import { paths } from "../config/paths.js";++/**+ * Manages working directories and output files.+ */+export class FileManager {+ async ensureDirectories() {+ const dirs = [+ paths.home,+ paths.cache,+ paths.transcripts,+ paths.working,+ paths.output,+ paths.logs,+ ];+ for (const dir of dirs) {+ if (!existsSync(dir)) {+ await mkdir(dir, { recursive: true });+ }+ }+ }++ createTaskDir(): { taskId: string; taskDir: string } {+ const taskId = uuidv4();+ const taskDir = join(paths.working, taskId);+ return { taskId, taskDir };+ }++ async ensureTaskDir(taskId: string): Promise<string> {+ const taskDir = join(paths.working, taskId);+ if (!existsSync(taskDir)) {+ await mkdir(taskDir, { recursive: true });+ }+ return taskDir;+ }++ async moveToOutput(sourcePath: string, filename: string): Promise<string> {+ const destPath = join(paths.output, filename);+ await rename(sourcePath, destPath);+ return destPath;+ }++ async cleanupTask(taskId: string): Promise<void> {+ const taskDir = join(paths.working, taskId);+ if (existsSync(taskDir)) {+ await rm(taskDir, { recursive: true, force: true });+ }+ }++ /**+ * Remove working directories older than maxAgeHours.+ */+ async cleanupOldTasks(maxAgeHours = 48): Promise<number> {+ if (!existsSync(paths.working)) return 0;++ const entries = await readdir(paths.working);+ const now = Date.now();+ let cleaned = 0;++ for (const entry of entries) {+ const fullPath = join(paths.working, entry);+ try {+ const s = await stat(fullPath);+ const ageHours = (now - s.mtimeMs) / (1000 * 60 * 60);+ if (ageHours > maxAgeHours) {+ await rm(fullPath, { recursive: true, force: true });+ cleaned++;+ }+ } catch {+ // Skip entries we can't stat+ }+ }++ return cleaned;+ }+}diff --git a/src/services/python-executor.ts b/src/services/python-executor.tsnew file mode 100644index 0000000..a21581b--- /dev/null+++ b/src/services/python-executor.ts@@ -0,0 +1,116 @@+import { spawn } from "child_process";+import { v4 as uuidv4 } from "uuid";+import { paths } from "../config/paths.js";+import type { TaskRequest, TaskResult, ProgressEvent } from "../models/index.js";++type ProgressCallback = (event: ProgressEvent) => void;++/**+ * Executes Python backend tasks via subprocess.+ * Communication: JSON over stdin (request) → stdout (result), stderr (progress logs).+ */+export class PythonExecutor {+ private timeoutMs: number;++ constructor(timeoutMs = 3600_000) {+ // Default 1 hour for long podcasts+ this.timeoutMs = timeoutMs;+ }++ async execute(+ taskType: TaskRequest["task_type"],+ params: Record<string, unknown>,+ onProgress?: ProgressCallback+ ): Promise<TaskResult> {+ const taskId = uuidv4();++ const request: TaskRequest = {+ task_id: taskId,+ task_type: taskType,+ params,+ };++ return new Promise<TaskResult>((resolve, reject) => {+ const proc = spawn(paths.pythonPath, [paths.pythonBackend], {+ stdio: ["pipe", "pipe", "pipe"],+ env: {+ ...process.env,+ PYTHONUNBUFFERED: "1",+ },+ });++ let stdout = "";+ let stderr = "";++ proc.stdout.on("data", (chunk: Buffer) => {+ stdout += chunk.toString();+ });++ proc.stderr.on("data", (chunk: Buffer) => {+ const raw = chunk.toString();+ stderr += raw;++ // Try to parse progress events (one per line)+ for (const line of raw.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed || !trimmed.startsWith("{")) continue;+ try {+ const event = JSON.parse(trimmed) as ProgressEvent;+ if (event.task_id === taskId && onProgress) {+ onProgress(event);+ }+ } catch {+ // Regular log line, ignore+ }+ }+ });++ proc.on("error", (err) => {+ reject(new Error(`Failed to spawn Python process: ${err.message}`));+ });++ proc.on("close", (code) => {+ try {+ // Find the last complete JSON object in stdout+ const jsonMatch = stdout.trim().split("\n").filter(Boolean).pop();+ if (!jsonMatch) {+ reject(+ new Error(+ `No output from Python task. Exit code: ${code}. Stderr: ${stderr.slice(-500)}`+ )+ );+ return;+ }++ const result = JSON.parse(jsonMatch) as TaskResult;++ if (result.status === "error") {+ reject(new Error(result.error || "Unknown Python error"));+ return;+ }++ resolve(result);+ } catch (parseErr) {+ reject(+ new Error(+ `Failed to parse Python output. Exit code: ${code}. ` ++ `Stdout: ${stdout.slice(-300)}. Stderr: ${stderr.slice(-300)}`+ )+ );+ }+ });++ // Send request and close stdin+ proc.stdin.write(JSON.stringify(request) + "\n");+ proc.stdin.end();++ // Timeout guard+ const timer = setTimeout(() => {+ proc.kill("SIGKILL");+ reject(new Error(`Task timed out after ${this.timeoutMs / 1000}s`));+ }, this.timeoutMs);++ proc.on("close", () => clearTimeout(timer));+ });+ }+}diff --git a/src/services/transcript-cache.ts b/src/services/transcript-cache.tsnew file mode 100644index 0000000..432c6f9--- /dev/null+++ b/src/services/transcript-cache.ts@@ -0,0 +1,81 @@+import { createHash } from "crypto";+import { readFile, writeFile, mkdir } from "fs/promises";+import { existsSync } from "fs";+import { join } from "path";+import { paths } from "../config/paths.js";+import type { TranscriptResult } from "../models/index.js";++/**+ * Caches transcripts by file hash so we don't re-transcribe+ * the same podcast when creating multiple clips.+ */+export class TranscriptCache {+ private cacheDir: string;++ constructor() {+ this.cacheDir = paths.transcripts;+ }++ private async ensureDir() {+ if (!existsSync(this.cacheDir)) {+ await mkdir(this.cacheDir, { recursive: true });+ }+ }++ /**+ * Hash the first 10MB of the file + file size for a fast unique key.+ */+ async getFileHash(filePath: string): Promise<string> {+ const { createReadStream, statSync } = await import("fs");+ const stat = statSync(filePath);+ const hash = createHash("sha256");++ return new Promise((resolve, reject) => {+ let bytesRead = 0;+ const maxBytes = 10 * 1024 * 1024; // 10MB sample++ const stream = createReadStream(filePath);+ stream.on("data", (chunk) => {+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);+ if (bytesRead < maxBytes) {+ const remaining = maxBytes - bytesRead;+ hash.update(buf.subarray(0, Math.min(buf.length, remaining)));+ bytesRead += buf.length;+ }+ if (bytesRead >= maxBytes) {+ stream.destroy();+ }+ });+ stream.on("end", () => {+ hash.update(`size:${stat.size}`);+ resolve(hash.digest("hex").slice(0, 16));+ });+ stream.on("close", () => {+ hash.update(`size:${stat.size}`);+ resolve(hash.digest("hex").slice(0, 16));+ });+ stream.on("error", reject);+ });+ }++ async get(filePath: string): Promise<TranscriptResult | null> {+ try {+ const hash = await this.getFileHash(filePath);+ const cachePath = join(this.cacheDir, `${hash}.json`);++ if (!existsSync(cachePath)) return null;++ const data = await readFile(cachePath, "utf-8");+ return JSON.parse(data) as TranscriptResult;+ } catch {+ return null;+ }+ }++ async set(filePath: string, transcript: TranscriptResult): Promise<void> {+ await this.ensureDir();+ const hash = await this.getFileHash(filePath);+ const cachePath = join(this.cacheDir, `${hash}.json`);+ await writeFile(cachePath, JSON.stringify(transcript), "utf-8");+ }+}diff --git a/src/ui/public/index.html b/src/ui/public/index.htmlnew file mode 100644index 0000000..36f064b--- /dev/null+++ b/src/ui/public/index.html@@ -0,0 +1,1019 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>podcli</title>+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet">+ <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.9/babel.min.js"></script>+ <style>+ :root {+ --bg: #0b0b0d;+ --surface: #131316;+ --surface2: #1b1b20;+ --border: #252530;+ --border-hover: #35354a;+ --text: #e8e8e2;+ --text2: #77776f;+ --text3: #4e4e48;+ --accent: #d4874a;+ --accent-hover: #e09860;+ --accent-subtle: rgba(212, 135, 74, 0.10);+ --accent-glow: rgba(212, 135, 74, 0.25);+ --green: #4ade80;+ --green-subtle: rgba(74, 222, 128, 0.07);+ --green-border: rgba(74, 222, 128, 0.18);+ --red: #f87171;+ --red-subtle: rgba(248, 113, 113, 0.07);+ --red-border: rgba(248, 113, 113, 0.18);+ --radius: 12px;+ --radius-sm: 8px;+ --ease: cubic-bezier(0.4, 0, 0.2, 1);+ }++ * { margin: 0; padding: 0; box-sizing: border-box; }++ body {+ font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;+ background: var(--bg); color: var(--text); min-height: 100vh;+ -webkit-font-smoothing: antialiased;+ }++ /* ─── Layout ─── */+ .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; }+ .logo span { color: var(--accent); }+ h1 { font-size: 28px; font-weight: 700; letter-spacing: -0.5px; line-height: 1.15; }+ .layout { display: grid; grid-template-columns: 1fr 340px; gap: 40px; align-items: start; }+ .main-col { min-width: 0; }+ .preview-col { position: relative; }++ /* ─── Preview Panel ─── */+ .preview-panel { position: sticky; top: 32px; }+ .preview-player {+ background: #000; border: 1px solid var(--border);+ border-radius: var(--radius); overflow: hidden; position: relative;+ }+ .preview-player video {+ width: 100%; display: block; background: #000;+ }+ .preview-player video.vertical {+ max-height: 480px; width: auto; margin: 0 auto;+ }+ .preview-empty {+ aspect-ratio: 16/9; display: flex; flex-direction: column;+ align-items: center; justify-content: center; gap: 8px;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); color: var(--text3); font-size: 13px;+ }+ .preview-empty .pe-icon { font-size: 28px; opacity: 0.3; }++ /* ─── Style Preview (vertical phone mockup) ─── */+ .style-preview {+ aspect-ratio: 9/16; width: 100%;+ background: #111114; border: 1px solid var(--border);+ border-radius: var(--radius); overflow: hidden;+ position: relative; user-select: none;+ }+ .style-preview .sp-bg {+ position: absolute; inset: 0;+ background:+ radial-gradient(ellipse at 35% 30%, rgba(80,60,40,0.18) 0%, transparent 60%),+ radial-gradient(ellipse at 65% 55%, rgba(50,50,70,0.12) 0%, transparent 50%),+ linear-gradient(180deg, #16161a 0%, #111114 100%);+ }+ .style-preview .sp-person {+ position: absolute; top: 18%; left: 50%; transform: translateX(-50%);+ width: 55%; aspect-ratio: 3/4;+ background: radial-gradient(ellipse at 50% 35%, rgba(140,120,100,0.15) 0%, rgba(80,70,60,0.06) 60%, transparent 80%);+ border-radius: 50% 50% 44% 44%;+ }+ .style-preview .sp-gradient {+ position: absolute; bottom: 0; left: 0; right: 0; height: 55%;+ background: linear-gradient(to top, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0.4) 40%, transparent 100%);+ pointer-events: none;+ }+ .style-preview .sp-captions {+ position: absolute; left: 0; right: 0;+ display: flex; flex-direction: column; align-items: center;+ padding: 0 20px; text-align: center;+ font-family: Arial, Helvetica, sans-serif;+ line-height: 1.35; transition: all 0.3s var(--ease);+ }+ .style-preview .sp-word {+ display: inline; transition: all 0.25s var(--ease);+ }+ .style-preview .sp-logo {+ position: absolute; top: 14px; left: 14px;+ width: 32px; height: 32px; border-radius: 7px;+ overflow: hidden;+ }+ .preview-clip-range {+ padding: 8px 12px; background: var(--surface);+ border-top: 1px solid var(--border);+ font-size: 12px; color: var(--text2);+ display: flex; align-items: center; justify-content: space-between;+ }+ .preview-clip-range .clip-name {+ font-weight: 600; color: var(--text);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ max-width: 200px;+ }+ .preview-back {+ padding: 0; background: none; border: none; color: var(--accent);+ font-family: inherit; font-size: 12px; font-weight: 600;+ cursor: pointer; transition: opacity 0.15s;+ }+ .preview-back:hover { opacity: 0.7; }+ .preview-settings {+ margin-top: 12px; display: flex; flex-wrap: wrap; gap: 6px;+ }+ .preview-tag {+ display: inline-flex; align-items: center; gap: 5px;+ padding: 5px 10px; background: var(--surface);+ border: 1px solid var(--border); border-radius: 8px;+ font-size: 11px; color: var(--text2); font-weight: 500;+ transition: all 0.2s var(--ease);+ }+ .preview-tag strong { color: var(--text); font-weight: 600; text-transform: capitalize; }+ .preview-tag.changed { border-color: var(--accent); background: var(--accent-subtle); }++ /* ─── Sections ─── */+ .section { margin-bottom: 24px; }+ .section-label { font-size: 11px; font-weight: 700; letter-spacing: 0.8px; color: var(--text2); margin-bottom: 10px; text-transform: uppercase; }++ /* ─── Form Elements ─── */+ input[type="text"], input[type="number"], select, textarea {+ width: 100%; background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); padding: 11px 14px;+ color: var(--text); font-family: inherit; font-size: 14px;+ outline: none; transition: border-color 0.2s var(--ease), box-shadow 0.2s var(--ease);+ }+ input[type="text"]:focus, input[type="number"]:focus, select:focus, textarea:focus {+ border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-subtle);+ }+ textarea {+ font-family: 'SF Mono', 'Fira Code', 'JetBrains Mono', monospace;+ font-size: 12px; resize: vertical; min-height: 120px; line-height: 1.7;+ }+ select {+ appearance: none; cursor: pointer; padding-right: 34px;+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='none'%3E%3Cpath d='M1 1L5 5L9 1' stroke='%2377776f' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");+ background-repeat: no-repeat; background-position: right 14px center;+ }++ /* ─── Buttons ─── */+ .btn {+ padding: 10px 18px; border-radius: var(--radius); font-family: inherit;+ font-size: 13px; font-weight: 600; cursor: pointer; border: none;+ transition: all 0.15s var(--ease); display: inline-flex;+ align-items: center; justify-content: center; gap: 6px; text-decoration: none;+ }+ .btn:active:not(:disabled) { transform: scale(0.97); }+ .btn-primary { background: var(--accent); color: #fff; }+ .btn-primary:hover:not(:disabled) { background: var(--accent-hover); }+ .btn-primary:disabled { opacity: 0.25; cursor: not-allowed; }+ .btn-ghost { background: transparent; color: var(--text2); border: 1px solid var(--border); }+ .btn-ghost:hover { border-color: var(--border-hover); color: var(--text); }+ .btn-sm { padding: 6px 12px; font-size: 12px; border-radius: var(--radius-sm); }+ .btn-go {+ width: 100%; padding: 14px; font-size: 15px; justify-content: center;+ background: var(--accent); color: #fff; border-radius: var(--radius);+ }+ .btn-go:hover:not(:disabled) { background: var(--accent-hover); box-shadow: 0 4px 24px var(--accent-glow); }+ .btn-go:disabled { opacity: 0.25; cursor: not-allowed; }+ .pill { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }+ .pill-blue { background: var(--accent-subtle); color: var(--accent); }++ /* ─── Drop Zone ─── */+ .drop-zone {+ border: 1.5px dashed var(--border); border-radius: var(--radius);+ padding: 32px 20px; text-align: center; cursor: pointer;+ transition: all 0.2s var(--ease); position: relative; overflow: hidden;+ }+ .drop-zone:hover { border-color: var(--border-hover); background: rgba(255,255,255,0.012); }+ .drop-zone.drag-over { border-color: var(--accent); background: var(--accent-subtle); box-shadow: 0 0 0 4px var(--accent-subtle); }+ .drop-zone.uploading { border-color: var(--accent); border-style: solid; pointer-events: none; }+ .drop-zone .icon { font-size: 28px; margin-bottom: 8px; opacity: 0.35; line-height: 1; }+ .drop-zone .label { font-size: 13px; color: var(--text2); line-height: 1.5; }+ .drop-zone .label strong { color: var(--accent); font-weight: 600; }+ .drop-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }+ .upload-bar { position: absolute; bottom: 0; left: 0; height: 3px; background: var(--accent); border-radius: 0 2px 2px 0; transition: width 0.25s var(--ease); }++ /* ─── File Badge ─── */+ .file-badge {+ display: flex; align-items: center; gap: 10px;+ padding: 10px 14px; background: var(--green-subtle);+ border: 1px solid var(--green-border); border-radius: var(--radius);+ }+ .file-badge .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--green); flex-shrink: 0; }+ .file-badge .name { font-size: 13px; color: var(--green); font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .file-badge .meta { font-size: 11px; color: var(--text2); flex-shrink: 0; }++ /* ─── Tabs ─── */+ .tabs { display: flex; gap: 2px; background: var(--surface); border-radius: var(--radius); padding: 3px; margin-bottom: 14px; }+ .tab {+ flex: 1; text-align: center; padding: 8px 12px;+ border-radius: calc(var(--radius) - 3px); font-size: 13px;+ font-weight: 600; color: var(--text2); cursor: pointer;+ transition: all 0.2s var(--ease); user-select: none;+ }+ .tab:hover:not(.active) { color: var(--text); }+ .tab.active { background: var(--accent); color: #fff; }++ /* ─── Settings ─── */+ .settings-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 14px; }+ .field-label { font-size: 11px; color: var(--text2); font-weight: 600; display: block; margin-bottom: 6px; }+ .row { display: flex; gap: 10px; align-items: flex-end; }+ .row > * { flex: 1; }++ /* ─── Progress ─── */+ .progress-track { background: var(--surface2); border-radius: 4px; height: 4px; overflow: hidden; margin: 8px 0; }+ .progress-fill { height: 100%; background: var(--accent); border-radius: 4px; transition: width 0.5s var(--ease); }+ .progress-fill.indeterminate { width: 35% !important; animation: shimmer 1.4s ease-in-out infinite; }+ .status-line { font-size: 13px; color: var(--text2); display: flex; justify-content: space-between; }+ .spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.6s linear infinite; flex-shrink: 0; }+ .spinner.sm { width: 14px; height: 14px; border-width: 1.5px; }++ /* ─── Clip List ─── */+ .clip-item {+ display: flex; align-items: center; gap: 12px;+ padding: 12px 14px; margin-bottom: 4px;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); transition: all 0.15s var(--ease);+ cursor: pointer;+ }+ .clip-item:hover { border-color: var(--border-hover); }+ .clip-item.dimmed { opacity: 0.35; }+ .clip-item.active-clip { border-color: rgba(212, 135, 74, 0.3); background: rgba(212, 135, 74, 0.03); }+ .clip-item.selected { border-color: var(--accent); background: rgba(212, 135, 74, 0.04); }+ .checkbox {+ width: 20px; height: 20px; border-radius: 6px;+ border: 1.5px solid var(--border); display: flex;+ align-items: center; justify-content: center;+ cursor: pointer; transition: all 0.15s var(--ease); flex-shrink: 0;+ }+ .checkbox:hover { border-color: var(--accent); }+ .checkbox.checked { background: var(--accent); border-color: var(--accent); }+ .clip-info { flex: 1; min-width: 0; }+ .clip-title { font-size: 13px; font-weight: 600; line-height: 1.4; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .clip-meta { font-size: 12px; color: var(--text2); margin-top: 2px; }+ .clip-meta .err { color: var(--red); }+ .clip-actions { display: flex; gap: 4px; flex-shrink: 0; }+ .clip-status { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 11px; font-weight: 700; }+ .clip-status.pending { border: 1.5px dashed var(--border); }+ .clip-status.rendering { border: 2px solid var(--border); border-top-color: var(--accent); animation: spin 0.6s linear infinite; }+ .clip-status.exported { background: var(--green-subtle); color: var(--green); }+ .status-dot { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 12px; }+ .status-dot.ok { background: var(--green-subtle); color: var(--green); }+ .status-dot.fail { background: var(--red-subtle); color: var(--red); }++ /* ─── Error ─── */+ .error-bar { padding: 12px 16px; background: var(--red-subtle); border: 1px solid var(--red-border); border-radius: var(--radius); margin-bottom: 20px; font-size: 13px; color: var(--red); display: flex; align-items: center; gap: 10px; }+ .error-bar span { flex: 1; }+ .spacer { height: 1px; background: var(--border); margin: 28px 0; opacity: 0.4; }++ /* ─── Modal ─── */+ .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.88); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); z-index: 1000; display: flex; align-items: center; justify-content: center; cursor: pointer; animation: fadeIn 0.15s var(--ease); }+ .modal-body { max-width: 380px; width: 92%; cursor: default; animation: scaleIn 0.2s var(--ease); }+ .modal-body video { width: 100%; border-radius: 16px; box-shadow: 0 24px 64px rgba(0,0,0,0.5); }++ /* ─── Animations ─── */+ .fade-in { animation: fadeIn 0.3s var(--ease); }+ @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }+ @keyframes scaleIn { from { opacity: 0; transform: scale(0.96) translateY(4px); } to { opacity: 1; transform: none; } }+ @keyframes spin { to { transform: rotate(360deg); } }+ @keyframes shimmer { 0% { transform: translateX(-120%); } 100% { transform: translateX(350%); } }+ @keyframes clipReveal { from { opacity: 0; transform: translateY(10px) scale(0.98); } to { opacity: 1; transform: none; } }+ .clip-reveal { animation: clipReveal 0.35s var(--ease) both; }+ @keyframes tagFlash { 0% { border-color: var(--accent); background: var(--accent-subtle); } 100% { border-color: var(--border); background: var(--surface); } }++ /* ─── Responsive ─── */+ @media (max-width: 920px) {+ .app { padding: 36px 20px 80px; }+ .layout { grid-template-columns: 1fr; gap: 0; }+ .preview-col { display: none; }+ }+ </style>+</head>+<body>+ <div id="root"></div>++ <script type="text/babel">+ const { useState, useEffect, useRef, useCallback } = React;++ const fmt = (s) => `${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,'0')}`;+ const api = async (path, opts={}) => (await fetch(`/api${path}`, { headers:{'Content-Type':'application/json',...opts.headers}, ...opts })).json();++ function uploadFile(file, onProgress) {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ const fd = new FormData();+ fd.append('file', file);+ xhr.upload.onprogress = (e) => { if (e.lengthComputable && onProgress) onProgress(Math.round((e.loaded / e.total) * 100)); };+ xhr.onload = () => { try { resolve(JSON.parse(xhr.responseText)); } catch(e) { reject(e); } };+ xhr.onerror = () => reject(new Error('Upload failed'));+ xhr.open('POST', '/api/upload');+ xhr.send(fd);+ });+ }++ function useJob(jobId) {+ const [state, setState] = useState(null);+ useEffect(() => {+ if (!jobId) { setState(null); return; }+ const es = new EventSource(`/api/job/${jobId}/stream`);+ es.onmessage = e => { const d=JSON.parse(e.data); setState(d); if(d.status==='done'||d.status==='error') es.close(); };+ es.onerror = () => es.close();+ return () => es.close();+ }, [jobId]);+ return state;+ }++ function suggestClips(segments, energyScores) {+ if (!segments?.length) return [];+ const clips = [];+ const kw = ['secret','mistake','important','never','always','best','how to','why','story','amazing','changed','money','learn','truth','actually','problem','solution','believe','crazy','number one','biggest','first thing','listen','here\'s the thing','let me tell you','the key','game changer','nobody talks about','most people','don\'t realize'];+ const winSizes = [6, 8, 10, 12];+ for (const winSize of winSizes) {+ const step = Math.max(1, Math.floor(winSize * 0.6));+ for (let i = 0; i < segments.length - winSize; i += step) {+ const win = segments.slice(i, i+winSize);+ const text = win.map(s=>s.text).join(' ');+ const start = win[0].start, end = win[win.length-1].end, dur = end-start;+ if (dur < 20 || dur > 90) continue;+ let score = 0;+ const lower = text.toLowerCase();+ if (text.includes('?')) score+=3;+ if (text.includes('!')) score+=2;+ if (text.length>200) score+=1;+ const firstText = (win[0].text||'').trim();+ if (firstText && firstText[0] === firstText[0].toUpperCase()) score+=1;+ kw.forEach(k=>{ if(lower.includes(k)) score+=2; });+ if (energyScores?.length) {+ const segE = energyScores.slice(i, i+winSize).filter(e => e > 0);+ if (segE.length) { const avg = segE.reduce((a,b)=>a+b,0)/segE.length; const peak = Math.max(...segE); score += avg*0.5 + peak*0.3; }+ }+ if (score >= 3) clips.push({ title: text.slice(0,55).trim()+'...', start_second: Math.floor(start), end_second: Math.ceil(end), duration: Math.round(dur), preview: text.slice(0,100).trim(), score });+ }+ }+ clips.sort((a,b)=>b.score-a.score);+ const selected = [];+ for (const clip of clips) {+ const overlap = selected.some(sel => { const o = Math.min(clip.end_second, sel.end_second) - Math.max(clip.start_second, sel.start_second); return o > clip.duration * 0.5; });+ if (!overlap) selected.push(clip);+ if (selected.length >= 8) break;+ }+ selected.sort((a,b)=>a.start_second-b.start_second);+ return selected;+ }++ 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>);++ /* ── Style Preview Component ── */+ const STYLE_CONFIGS = {+ branded: {+ words: ['Did you ever,', 'felt', 'like I\u2019m in the', 'wrong place'],+ fontSize: 19, fontWeight: 800, bottom: '30%',+ lineHeight: 1.3, textShadow: 'none',+ activeStyle: { background:'#1a1a1a', borderRadius:5, padding:'2px 6px', color:'#fff' },+ normalStyle: { background:'transparent', borderRadius:5, padding:'2px 6px', color:'#fff' },+ gradient: true,+ },+ hormozi: {+ words: ['LOOKING', 'FOR', 'HIGH ENERGY'],+ fontSize: 22, fontWeight: 900, bottom: '22%',+ lineHeight: 1.25, textShadow: '0 2px 8px rgba(0,0,0,0.7)',+ activeStyle: { color:'#ffff00' },+ normalStyle: { color:'#fff' },+ gradient: false,+ },+ karaoke: {+ words: ['the secret to', 'building', 'something', 'people', 'actually want'],+ fontSize: 15, fontWeight: 600, bottom: '22%',+ lineHeight: 1.4, textShadow: '0 1px 6px rgba(0,0,0,0.6)',+ activeStyle: { color:'#fff' },+ normalStyle: { color:'rgba(255,255,255,0.35)' },+ gradient: false,+ },+ subtle: {+ words: ['the secret to building something people actually want'],+ fontSize: 13, fontWeight: 400, bottom: '12%',+ lineHeight: 1.5, textShadow: '0 1px 4px rgba(0,0,0,0.8)',+ activeStyle: { color:'rgba(255,255,255,0.9)' },+ normalStyle: { color:'rgba(255,255,255,0.9)' },+ gradient: false,+ },+ };++ function StylePreview({ style, logoPath }) {+ const [activeIdx, setActiveIdx] = useState(0);+ const cfg = STYLE_CONFIGS[style] || STYLE_CONFIGS.branded;++ useEffect(() => {+ if (cfg.words.length <= 1) return;+ const iv = setInterval(() => setActiveIdx(i => (i + 1) % cfg.words.length), 800);+ return () => clearInterval(iv);+ }, [style]);++ useEffect(() => setActiveIdx(0), [style]);++ const showLogo = style === 'branded' && logoPath;++ return (+ <div className="style-preview fade-in" key={style}>+ <div className="sp-bg" />+ <div className="sp-person" />+ {cfg.gradient && <div className="sp-gradient" />}+ {showLogo && (+ <div className="sp-logo">+ <img src={`/api/stream-source?path=${encodeURIComponent(logoPath)}`} style={{ width:'100%', height:'100%', objectFit:'contain', borderRadius:6 }} />+ </div>+ )}+ <div className="sp-captions" style={{ bottom: cfg.bottom, fontSize: cfg.fontSize, fontWeight: cfg.fontWeight, lineHeight: cfg.lineHeight, textShadow: cfg.textShadow }}>+ <div style={{ display:'flex', flexWrap:'wrap', justifyContent:'center', gap:'4px 6px' }}>+ {cfg.words.map((w, i) => (+ <span key={w} className="sp-word" style={i === activeIdx ? cfg.activeStyle : cfg.normalStyle}>{w}</span>+ ))}+ </div>+ </div>+ </div>+ );+ }++ function App() {+ const [videoPath, setVideoPath] = useState('');+ const [transcriptMode, setTranscriptMode] = useState('import');+ const [transcriptText, setTranscriptText] = useState('');+ const [timeAdjust, setTimeAdjust] = useState(-1);+ const [whisperModel, setWhisperModel] = useState('base');+ const [captionStyle, setCaptionStyle] = useState('branded');+ const [cropStrategy, setCropStrategy] = useState('center');+ const [logoPath, setLogoPath] = useState('');+ const logoRef = useRef();+ const [videoDragOver, setVideoDragOver] = useState(false);+ const [transcriptDragOver, setTranscriptDragOver] = useState(false);+ const [transcriptFileName, setTranscriptFileName] = useState('');++ const [phase, setPhase] = useState('idle');+ const [file, setFile] = useState(null);+ const [transcript, setTranscript] = useState(null);+ const [suggestions, setSuggestions] = useState([]);+ const [deselected, setDeselected] = useState(new Set());+ const [batchJobId, setBatchJobId] = useState(null);+ const batchStream = useJob(batchJobId);+ const [results, setResults] = useState([]);+ const [error, setError] = useState(null);+ const [previewFile, setPreviewFile] = useState(null);++ const [whisperJobId, setWhisperJobId] = useState(null);+ const whisperStream = useJob(whisperJobId);+ const [retryIdx, setRetryIdx] = useState(null);+ const [retryJobId, setRetryJobId] = useState(null);+ const retryStream = useJob(retryJobId);++ const [videoUploading, setVideoUploading] = useState(false);+ const [uploadProgress, setUploadProgress] = useState(0);+ const [logoUploading, setLogoUploading] = useState(false);+ const [uploadingFileName, setUploadingFileName] = useState('');++ const [encoderInfo, setEncoderInfo] = useState(null);+ useEffect(() => { api('/encoder-info').then(d => { if(d.best) setEncoderInfo(d); }).catch(()=>{}); }, []);++ // Preview panel state+ const videoRef = useRef();+ const [activeClipIdx, setActiveClipIdx] = useState(null);+ const [previewSrc, setPreviewSrc] = useState(null); // null=source, string=rendered clip filename+ const [settingsFlash, setSettingsFlash] = useState(null);++ // Video source URL+ const videoUrl = previewSrc+ ? `/api/preview/${previewSrc}`+ : videoPath+ ? `/api/stream-source?path=${encodeURIComponent(videoPath)}`+ : null;++ // Seek to clip when active clip changes (and showing source)+ useEffect(() => {+ if (activeClipIdx === null || previewSrc) return;+ const clip = suggestions[activeClipIdx];+ if (!clip || !videoRef.current) return;+ const seek = () => {+ videoRef.current.currentTime = clip.start_second;+ videoRef.current.play().catch(() => {});+ };+ if (videoRef.current.readyState >= 1) seek();+ else videoRef.current.addEventListener('loadedmetadata', seek, { once: true });+ }, [activeClipIdx, previewSrc]);++ // Flash settings when they change+ const flashSetting = (key) => {+ setSettingsFlash(key);+ setTimeout(() => setSettingsFlash(null), 600);+ };++ const onCaptionChange = (v) => { setCaptionStyle(v); flashSetting('caption'); };+ const onCropChange = (v) => { setCropStrategy(v); flashSetting('crop'); };++ // Click clip row → seek source video+ const onClipClick = (idx) => {+ setActiveClipIdx(idx);+ if (previewSrc) setPreviewSrc(null);+ };++ // Play rendered clip in preview panel+ const onPlayRendered = (filename) => {+ setPreviewSrc(filename);+ setActiveClipIdx(null);+ };++ // Upload+ const doVideoUpload = useCallback(async (f) => {+ setVideoUploading(true); setUploadProgress(0); setUploadingFileName(f.name);+ try {+ const d = await uploadFile(f, (pct) => setUploadProgress(pct));+ if (d.file_path) setVideoPath(d.file_path);+ } catch(e) { setError('Upload failed: ' + e.message); }+ finally { setVideoUploading(false); setUploadProgress(0); setUploadingFileName(''); }+ }, []);++ // Pipeline+ const startPipeline = async () => {+ setError(null); setResults([]); setSuggestions([]); setDeselected(new Set());+ setBatchJobId(null); setActiveClipIdx(null); setPreviewSrc(null);+ setPhase('parsing');+ const fileData = await api('/select-file', { method:'POST', body: JSON.stringify({ file_path: videoPath.trim() }) });+ if (fileData.error) { setError(fileData.error); setPhase('idle'); return; }+ setFile(fileData);+ let t = null;+ if (transcriptMode === 'import') {+ const text = transcriptText.trim();+ if (!text) { setError('Paste your transcript'); setPhase('idle'); return; }+ const isJson = text.startsWith('{') || text.startsWith('[');+ if (isJson) {+ const parsed = JSON.parse(text);+ const tr = Array.isArray(parsed) ? { words: parsed } : parsed;+ const data = await api('/import-transcript', { method:'POST', body: JSON.stringify({ file_path: videoPath.trim(), transcript: tr }) });+ if (data.error) { setError(data.error); setPhase('idle'); return; }+ t = data.data;+ } else {+ const data = await api('/parse-transcript', { method:'POST', body: JSON.stringify({ file_path: videoPath.trim(), raw_text: text, time_adjust: timeAdjust }) });+ if (data.error) { setError(data.error); setPhase('idle'); return; }+ t = data.data;+ }+ } else {+ const data = await api('/transcribe', { method:'POST', body: JSON.stringify({ file_path: videoPath.trim(), model_size: whisperModel }) });+ if (data.cached) { t = data.data; }+ else { setWhisperJobId(data.job_id); return; }+ }+ continueWithTranscript(t, fileData);+ };++ const continueWithTranscript = async (t, f) => {+ setTranscript(t); setPhase('suggesting'); setSuggestions([]);+ let energyScores = null;+ const vp = f?.file_path || videoPath.trim();+ if (vp && t?.segments?.length) {+ try {+ const eData = await api('/analyze-energy', { method:'POST', body: JSON.stringify({ video_path: vp, segments: t.segments }) });+ if (eData.segment_scores) energyScores = eData.segment_scores;+ } catch(e) {}+ }+ const allClips = suggestClips(t?.segments || [], energyScores);+ if (allClips.length === 0) { setError('No clip suggestions found.'); setPhase('idle'); return; }+ for (let i = 0; i < allClips.length; i++) {+ await new Promise(r => setTimeout(r, i === 0 ? 150 : 250));+ setSuggestions(prev => [...prev, allClips[i]]);+ }+ await new Promise(r => setTimeout(r, 300));+ setPhase('review');+ };++ useEffect(() => {+ if (whisperStream?.status === 'done' && whisperStream.result) { setWhisperJobId(null); continueWithTranscript(whisperStream.result, file); }+ if (whisperStream?.status === 'error') { setError('Transcription failed: ' + whisperStream.error); setPhase('idle'); }+ }, [whisperStream?.status]);++ const startExport = async () => {+ setPhase('exporting'); setResults([]);+ const sc = suggestions.filter((_,i) => !deselected.has(i));+ const data = await api('/batch-clips', { method:'POST', body: JSON.stringify({+ video_path: file.file_path,+ clips: sc.map(c => ({ start_second: c.start_second, end_second: c.end_second, title: c.title.slice(0,40), caption_style: captionStyle, crop_strategy: cropStrategy })),+ transcript_words: transcript?.words || [], logo_path: logoPath || undefined,+ })});+ setBatchJobId(data.job_id);+ };++ useEffect(() => {+ if (batchStream?.status === 'done') { setPhase('done'); setResults(batchStream.result?.results || []); }+ if (batchStream?.status === 'error') { setError('Export failed: ' + batchStream.error); setPhase('review'); }+ }, [batchStream?.status]);++ const retryClip = async (idx) => {+ const sc = suggestions.filter((_,i) => !deselected.has(i));+ const c = sc[idx]; setRetryIdx(idx); setRetryJobId(null);+ const data = await api('/create-clip', { method:'POST', body: JSON.stringify({+ video_path: file.file_path, start_second: c.start_second, end_second: c.end_second,+ title: c.title.slice(0,40), caption_style: captionStyle, crop_strategy: cropStrategy,+ transcript_words: transcript?.words || [], logo_path: logoPath || undefined,+ })});+ setRetryJobId(data.job_id);+ };++ useEffect(() => {+ if (retryStream?.status === 'done') {+ setResults(prev => { const n = [...prev]; n[retryIdx] = { ...retryStream.result, status: 'success' }; return n; });+ setRetryIdx(null); setRetryJobId(null);+ }+ }, [retryStream?.status]);++ const toggleClip = (i) => setDeselected(prev => { const n=new Set(prev); n.has(i)?n.delete(i):n.add(i); return n; });+ const selectedCount = suggestions.length - deselected.size;+ const handleLogoUpload = async (f) => {+ setLogoUploading(true);+ try { const d = await uploadFile(f, ()=>{}); if(d.file_path) setLogoPath(d.file_path); }+ catch(e) { setError('Logo upload failed'); }+ finally { setLogoUploading(false); }+ };+ const isProcessing = phase === 'parsing' || phase === 'suggesting' || phase === 'exporting' || whisperJobId;+ const selectedClips = suggestions.filter((_,i) => !deselected.has(i));++ const getExportStatus = (resultIdx) => {+ if (phase !== 'exporting' || !batchStream) return null;+ const total = selectedClips.length; if (!total) return null;+ const pct = batchStream.progress || 0;+ const done = Math.floor(pct / (100 / total));+ if (resultIdx < done) return 'exported';+ if (resultIdx === done && pct < 100) return 'rendering';+ return 'pending';+ };++ const handleVideoDrop = async (e) => { e.preventDefault(); setVideoDragOver(false); const files = e.dataTransfer?.files; if(files?.length) doVideoUpload(files[0]); };+ const handleVideoFileSelect = async (e) => { const f = e.target.files?.[0]; if(f) doVideoUpload(f); };+ const handleTranscriptDrop = (e) => { e.preventDefault(); setTranscriptDragOver(false); const files = e.dataTransfer?.files; if(!files?.length) return; const f=files[0]; setTranscriptFileName(f.name); const reader=new FileReader(); reader.onload=(ev)=>setTranscriptText(ev.target.result); reader.readAsText(f); };+ const handleTranscriptFileSelect = (e) => { const f=e.target.files?.[0]; if(!f) return; setTranscriptFileName(f.name); const reader=new FileReader(); reader.onload=(ev)=>setTranscriptText(ev.target.result); reader.readAsText(f); };+ const preventDef = (e) => e.preventDefault();++ const activeClip = activeClipIdx !== null ? suggestions[activeClipIdx] : null;++ return (+ <div className="app">+ <div className="header">+ <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>+ <div className="logo">pod<span>cli</span></div>+ <div style={{ display:'flex', alignItems:'center', gap: 8 }}>+ {encoderInfo && (+ <span className="pill pill-blue" style={{ fontSize:10, letterSpacing:'0.5px' }}>+ {encoderInfo.best === 'libx264' ? 'CPU' : encoderInfo.best.replace('h264_','').toUpperCase()}+ </span>+ )}+ <a href="/integration.html" style={{ fontSize:12, fontWeight:600, color:'var(--text2)', textDecoration:'none', padding:'5px 12px', border:'1px solid var(--border)', borderRadius:'var(--radius-sm)', transition:'all 0.15s' }}>MCP Setup</a>+ </div>+ </div>+ <h1>Create short-form clips</h1>+ </div>++ <div className="layout">+ {/* ═══════════ LEFT COLUMN ═══════════ */}+ <div className="main-col">++ {/* Video */}+ <div className="section">+ <div className="section-label">Video</div>+ {videoUploading && (+ <div className="drop-zone uploading fade-in">+ <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap: 10 }}>+ <div className="spinner sm" />+ <div>+ <div style={{ fontSize: 13, fontWeight: 600 }}>Uploading{'\u2026'} {uploadProgress}%</div>+ <div style={{ fontSize: 11, color: 'var(--text2)', marginTop: 2 }}>{uploadingFileName}</div>+ </div>+ </div>+ <div className="upload-bar" style={{ width: `${uploadProgress}%` }} />+ </div>+ )}+ {!videoUploading && !videoPath && (+ <div className={`drop-zone ${videoDragOver?'drag-over':''}`}+ onDragOver={e=>{preventDef(e);setVideoDragOver(true);}} onDragLeave={()=>setVideoDragOver(false)} onDrop={handleVideoDrop}>+ <div className="icon">{'\uD83C\uDFAC'}</div>+ <div className="label">Drop your video here or <strong>browse</strong></div>+ <input type="file" accept="video/*" onChange={handleVideoFileSelect} disabled={isProcessing} />+ </div>+ )}+ {!videoUploading && videoPath && (+ <div className="file-badge fade-in">+ <div className="dot" />+ <div className="name">{videoPath.split('/').pop()}</div>+ <button className="btn btn-ghost btn-sm" onClick={()=>setVideoPath('')} style={{padding:'4px 10px',fontSize:11}}>Clear</button>+ </div>+ )}+ <input type="text" placeholder="Or paste a local path: /Users/you/episode.mp4"+ value={videoPath} onChange={e=>setVideoPath(e.target.value)}+ disabled={isProcessing||videoUploading}+ style={{ marginTop:8, fontSize:12, padding:'9px 13px', background:'var(--bg)', borderColor: videoPath?'var(--green-border)':'var(--border)' }} />+ </div>++ {/* Transcript */}+ <div className="section">+ <div className="section-label">Transcript</div>+ <div className="tabs">+ <div className={`tab ${transcriptMode==='import'?'active':''}`} onClick={()=>setTranscriptMode('import')}>Paste Transcript</div>+ <div className={`tab ${transcriptMode==='whisper'?'active':''}`} onClick={()=>setTranscriptMode('whisper')}>Auto (Whisper)</div>+ </div>+ {transcriptMode === 'import' && (+ <div className="fade-in">+ {!transcriptText && (+ <div className={`drop-zone ${transcriptDragOver?'drag-over':''}`}+ onDragOver={e=>{preventDef(e);setTranscriptDragOver(true);}} onDragLeave={()=>setTranscriptDragOver(false)}+ onDrop={handleTranscriptDrop} style={{marginBottom:10,padding:'22px 20px'}}>+ <div className="icon">{'\uD83D\uDCC4'}</div>+ <div className="label">Drop a transcript file or <strong>browse</strong></div>+ <input type="file" accept=".txt,.json,.srt,.vtt" onChange={handleTranscriptFileSelect} disabled={isProcessing} />+ </div>+ )}+ {transcriptText && transcriptFileName && (+ <div className="file-badge fade-in" style={{marginBottom:10}}>+ <div className="dot"/><div className="name">{transcriptFileName}</div>+ <div className="meta">{transcriptText.split('\n').length} lines</div>+ <button className="btn btn-ghost btn-sm" onClick={()=>{setTranscriptText('');setTranscriptFileName('');}} style={{padding:'4px 10px',fontSize:11}}>Clear</button>+ </div>+ )}+ <textarea placeholder={'Speaker (00:00)\nText of what they said...\n\nSpeaker2 (00:15)\nMore text...\n\n— or paste JSON / drag a .txt file above —'}+ value={transcriptText} onChange={e=>{setTranscriptText(e.target.value);setTranscriptFileName('');}}+ disabled={isProcessing} style={{minHeight:transcriptText?80:120}}+ onDragOver={e=>{preventDef(e);setTranscriptDragOver(true);}} onDrop={handleTranscriptDrop} />+ <div style={{display:'flex',gap:8,alignItems:'center',marginTop:10}}>+ <span style={{fontSize:12,color:'var(--text2)',whiteSpace:'nowrap'}}>Time offset</span>+ <input type="number" step="0.5" value={timeAdjust} onChange={e=>setTimeAdjust(parseFloat(e.target.value)||0)}+ style={{width:72,padding:'7px 10px',fontSize:12}} disabled={isProcessing} />+ <span style={{fontSize:11,color:'var(--text3)'}}>sec</span>+ </div>+ </div>+ )}+ {transcriptMode === 'whisper' && (+ <div className="fade-in"><div className="row"><div>+ <label className="field-label">Model</label>+ <select value={whisperModel} onChange={e=>setWhisperModel(e.target.value)} disabled={isProcessing}>+ <option value="tiny">Tiny (fastest)</option><option value="base">Base</option>+ <option value="small">Small</option><option value="medium">Medium</option>+ <option value="large">Large (best)</option>+ </select>+ </div></div></div>+ )}+ </div>++ {/* Settings */}+ <div className="section">+ <div className="section-label">Settings</div>+ <div className="settings-grid">+ <div>+ <label className="field-label">Caption Style</label>+ <select value={captionStyle} onChange={e=>onCaptionChange(e.target.value)} disabled={isProcessing}>+ <option value="branded">Branded</option><option value="hormozi">Hormozi</option>+ <option value="karaoke">Karaoke</option><option value="subtle">Subtle</option>+ </select>+ </div>+ <div>+ <label className="field-label">Crop</label>+ <select value={cropStrategy} onChange={e=>onCropChange(e.target.value)} disabled={isProcessing}>+ <option value="center">Center</option><option value="face">Face Detection</option>+ </select>+ </div>+ </div>+ {captionStyle === 'branded' && (+ <div className="fade-in" style={{display:'flex',gap:8,alignItems:'center'}}>+ <input type="text" placeholder="Logo image path (optional)" value={logoPath} onChange={e=>setLogoPath(e.target.value)}+ style={{flex:1}} disabled={isProcessing||logoUploading} />+ <button className="btn btn-ghost btn-sm" onClick={()=>logoRef.current?.click()} disabled={isProcessing||logoUploading} style={{minWidth:72}}>+ {logoUploading ? <><div className="spinner sm"/><span style={{fontSize:11}}>wait</span></> : 'Upload'}+ </button>+ <input ref={logoRef} type="file" accept=".png,.jpg,.jpeg,.svg" style={{display:'none'}}+ onChange={e=>e.target.files[0]&&handleLogoUpload(e.target.files[0])} />+ </div>+ )}+ </div>++ {/* Error */}+ {error && (+ <div className="error-bar fade-in">+ <span>{error}</span>+ <button className="btn btn-ghost btn-sm" onClick={()=>setError(null)} style={{flexShrink:0,color:'var(--red)',borderColor:'var(--red-border)'}}>Dismiss</button>+ </div>+ )}++ {/* Generate */}+ {phase === 'idle' && (+ <button className="btn btn-go" disabled={!videoPath.trim()||(transcriptMode==='import'&&!transcriptText.trim())||videoUploading} onClick={startPipeline}>+ Generate Clips+ </button>+ )}++ {/* Whisper progress */}+ {whisperJobId && whisperStream && (+ <div className="fade-in" style={{marginTop:20}}>+ <div className="status-line">+ <span style={{display:'flex',alignItems:'center',gap:8}}><div className="spinner sm"/>Transcribing{'\u2026'}</span>+ <span style={{fontWeight:600,fontVariantNumeric:'tabular-nums'}}>{whisperStream.progress||0}%</span>+ </div>+ <div className="progress-track"><div className="progress-fill" style={{width:`${whisperStream.progress||0}%`}}/></div>+ <div style={{fontSize:12,color:'var(--text3)',marginTop:4}}>{whisperStream.message}</div>+ </div>+ )}++ {/* Parsing */}+ {phase === 'parsing' && !whisperJobId && (+ <div className="fade-in" style={{marginTop:20}}>+ <div className="status-line"><span style={{display:'flex',alignItems:'center',gap:8}}><div className="spinner sm"/>Processing transcript{'\u2026'}</span></div>+ <div className="progress-track"><div className="progress-fill indeterminate"/></div>+ </div>+ )}++ {/* Suggesting (no clips yet) */}+ {phase === 'suggesting' && suggestions.length === 0 && (+ <div className="fade-in" style={{marginTop:20}}>+ <div className="status-line"><span style={{display:'flex',alignItems:'center',gap:8}}><div className="spinner sm"/>Analyzing transcript{'\u2026'}</span></div>+ <div className="progress-track"><div className="progress-fill indeterminate"/></div>+ </div>+ )}++ {/* Clip list */}+ {(phase==='suggesting'||phase==='review'||phase==='exporting'||phase==='done') && suggestions.length > 0 && (+ <div>+ <div className="spacer" />+ <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>+ <div className="section-label" style={{margin:0,display:'flex',alignItems:'center',gap:8}}>+ {phase === 'suggesting' && <div className="spinner sm"/>}+ {phase==='suggesting' ? `Found ${suggestions.length} clip${suggestions.length!==1?'s':''}`+ : phase==='review' ? `Clips \u00B7 ${selectedCount} selected` : 'Clips'}+ </div>+ {phase === 'review' && (+ <button className="btn btn-primary btn-sm" disabled={selectedCount===0} onClick={startExport}>+ Export {selectedCount} clip{selectedCount!==1?'s':''}+ </button>+ )}+ </div>++ {suggestions.map((clip, i) => {+ const off = deselected.has(i);+ const resultIdx = [...suggestions.keys()].filter(k=>!deselected.has(k)).indexOf(i);+ const r = results[resultIdx];+ const outputFile = r?.output_path?.split('/').pop();+ const failed = r?.status === 'error';+ const isRetryingThis = retryIdx === resultIdx;+ const exportStatus = !off ? getExportStatus(resultIdx) : null;+ const isSelected = activeClipIdx === i && !previewSrc;++ return (+ <div key={i}+ className={`clip-item ${off&&phase==='review'?'dimmed':''} ${exportStatus==='rendering'?'active-clip':''} ${phase==='suggesting'?'clip-reveal':''} ${isSelected?'selected':''}`}+ onClick={() => onClipClick(i)}>++ {phase === 'review' && (+ <div className={`checkbox ${!off?'checked':''}`} onClick={(e)=>{e.stopPropagation();toggleClip(i);}}>+ {!off && <CheckIcon/>}+ </div>+ )}++ {phase === 'exporting' && !off && exportStatus && (+ <div className={`clip-status ${exportStatus}`}>{exportStatus==='exported'&&<CheckSmall/>}</div>+ )}++ {phase === 'done' && !off && r && (+ <div className={`status-dot ${failed?'fail':'ok'}`}>{failed?'\u00D7':'\u2713'}</div>+ )}++ <div className="clip-info">+ <div className="clip-title">{clip.title}</div>+ <div className="clip-meta">+ {fmt(clip.start_second)} {'\u2192'} {fmt(clip.end_second)} {'\u00B7'} {clip.duration}s+ {r&&!failed&&<span> {'\u00B7'} {r.file_size_mb}MB</span>}+ {failed&&<span className="err"> {'\u00B7'} {r.error?.slice(0,60)}</span>}+ {exportStatus==='rendering'&&<span style={{color:'var(--accent)'}}> {'\u00B7'} rendering{'\u2026'}</span>}+ </div>+ </div>++ {phase === 'done' && !off && r && !failed && outputFile && (+ <div className="clip-actions" onClick={e=>e.stopPropagation()}>+ <button className="btn btn-ghost btn-sm" onClick={()=>onPlayRendered(outputFile)} title="Preview">{'\u25B6'}</button>+ <a href={`/api/download/${outputFile}`} className="btn btn-primary btn-sm" download title="Download">{'\u2193'}</a>+ <button className="btn btn-ghost btn-sm" disabled={isRetryingThis} onClick={()=>retryClip(resultIdx)} title="Retry">{'\u21BB'}</button>+ </div>+ )}+ {phase === 'done' && !off && r && failed && (+ <button className="btn btn-ghost btn-sm" onClick={e=>{e.stopPropagation();retryClip(resultIdx);}} disabled={isRetryingThis}>+ {isRetryingThis?'\u2026':'Retry'}+ </button>+ )}+ </div>+ );+ })}++ {phase === 'exporting' && batchStream && (+ <div style={{marginTop:14}}>+ <div className="status-line">+ <span>{batchStream.message}</span>+ <span style={{fontWeight:600,fontVariantNumeric:'tabular-nums'}}>{batchStream.progress||0}%</span>+ </div>+ <div className="progress-track"><div className="progress-fill" style={{width:`${batchStream.progress||0}%`}}/></div>+ </div>+ )}++ {retryIdx !== null && retryStream?.status === 'running' && (+ <div style={{marginTop:10,padding:12,background:'var(--surface)',borderRadius:'var(--radius-sm)'}}>+ <div className="status-line" style={{fontSize:12}}>+ <span style={{display:'flex',alignItems:'center',gap:6}}><div className="spinner sm"/>Retrying{'\u2026'}</span>+ <span style={{fontWeight:600}}>{retryStream.progress||0}%</span>+ </div>+ <div className="progress-track"><div className="progress-fill" style={{width:`${retryStream.progress||0}%`}}/></div>+ </div>+ )}++ {phase === 'done' && (+ <div style={{display:'flex',gap:10,justifyContent:'center',marginTop:24}}>+ <button className="btn btn-ghost" onClick={()=>{setPhase('idle');setResults([]);setSuggestions([]);setBatchJobId(null);setFile(null);setTranscript(null);setActiveClipIdx(null);setPreviewSrc(null);}}>Start Over</button>+ <button className="btn btn-ghost" onClick={()=>{setPhase('review');setResults([]);setBatchJobId(null);}}>Re-export</button>+ </div>+ )}+ </div>+ )}+ </div>++ {/* ═══════════ RIGHT COLUMN — PREVIEW ═══════════ */}+ <div className="preview-col">+ <div className="preview-panel">++ {/* Video player (when video loaded) */}+ {videoUrl && (+ <div className="preview-player fade-in" style={{ marginBottom: 12 }}>+ <video+ key={videoUrl}+ ref={videoRef}+ src={videoUrl}+ controls+ preload="auto"+ className={previewSrc ? 'vertical' : ''}+ />+ {activeClip && !previewSrc && (+ <div className="preview-clip-range">+ <span className="clip-name">{activeClip.title}</span>+ <span>{fmt(activeClip.start_second)} {'\u2192'} {fmt(activeClip.end_second)}</span>+ </div>+ )}+ {previewSrc && (+ <div className="preview-clip-range">+ <span className="clip-name">Rendered clip</span>+ <button className="preview-back" onClick={()=>setPreviewSrc(null)}>Back to source</button>+ </div>+ )}+ </div>+ )}++ {/* Style preview mockup — always visible */}+ <StylePreview style={captionStyle} logoPath={logoPath} />++ {/* Settings tags */}+ <div className="preview-settings">+ <div className={`preview-tag ${settingsFlash==='caption'?'changed':''}`}+ style={settingsFlash==='caption'?{animation:'tagFlash 0.6s var(--ease)'}:{}}>+ Caption {'\u00B7'} <strong>{captionStyle}</strong>+ </div>+ <div className={`preview-tag ${settingsFlash==='crop'?'changed':''}`}+ style={settingsFlash==='crop'?{animation:'tagFlash 0.6s var(--ease)'}:{}}>+ Crop {'\u00B7'} <strong>{cropStrategy}</strong>+ </div>+ {logoPath && (+ <div className="preview-tag">+ Logo {'\u00B7'} <strong>{logoPath.split('/').pop()}</strong>+ </div>+ )}+ </div>+ </div>+ </div>+ </div>++ {/* Modal (mobile fallback) */}+ {previewFile && (+ <div className="modal-overlay" onClick={()=>setPreviewFile(null)}>+ <div className="modal-body" onClick={e=>e.stopPropagation()}>+ <video src={`/api/preview/${previewFile}`} controls autoPlay />+ <div style={{textAlign:'center',marginTop:12}}>+ <button className="btn btn-ghost btn-sm" onClick={()=>setPreviewFile(null)}>Close</button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+ }++ ReactDOM.createRoot(document.getElementById('root')).render(<App />);+ </script>+</body>+</html>diff --git a/src/ui/public/integration.html b/src/ui/public/integration.htmlnew file mode 100644index 0000000..8c856db--- /dev/null+++ b/src/ui/public/integration.html@@ -0,0 +1,359 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>podcli — Integration</title>+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">+ <style>+ :root {+ --bg: #0b0b0d;+ --surface: #131316;+ --surface2: #1b1b20;+ --border: #252530;+ --border-hover: #35354a;+ --text: #e8e8e2;+ --text2: #77776f;+ --text3: #4e4e48;+ --accent: #d4874a;+ --accent-hover: #e09860;+ --accent-subtle: rgba(212, 135, 74, 0.10);+ --accent-glow: rgba(212, 135, 74, 0.25);+ --green: #4ade80;+ --green-subtle: rgba(74, 222, 128, 0.07);+ --green-border: rgba(74, 222, 128, 0.18);+ --red: #f87171;+ --red-subtle: rgba(248, 113, 113, 0.07);+ --red-border: rgba(248, 113, 113, 0.18);+ --blue: #60a5fa;+ --blue-subtle: rgba(96, 165, 250, 0.08);+ --blue-border: rgba(96, 165, 250, 0.18);+ --radius: 12px;+ --radius-sm: 8px;+ --ease: cubic-bezier(0.4, 0, 0.2, 1);+ }++ * { margin: 0; padding: 0; box-sizing: border-box; }++ body {+ font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;+ background: var(--bg); color: var(--text); min-height: 100vh;+ -webkit-font-smoothing: antialiased;+ }++ .app { max-width: 780px; margin: 0 auto; padding: 48px 32px 96px; }++ /* ─── Header ─── */+ .header { margin-bottom: 40px; }+ .nav { display: flex; align-items: center; justify-content: space-between; margin-bottom: 28px; }+ .logo { font-size: 13px; font-weight: 700; letter-spacing: 1.2px; color: var(--text3); text-transform: uppercase; text-decoration: none; }+ .logo span { color: var(--accent); }+ .nav-link {+ font-size: 13px; font-weight: 600; color: var(--text2);+ text-decoration: none; padding: 6px 14px;+ border-radius: var(--radius-sm); border: 1px solid var(--border);+ transition: all 0.15s var(--ease);+ }+ .nav-link:hover { border-color: var(--border-hover); color: var(--text); }+ h1 { font-size: 28px; font-weight: 700; letter-spacing: -0.5px; line-height: 1.15; }+ .subtitle { font-size: 14px; color: var(--text2); margin-top: 8px; line-height: 1.6; }++ /* ─── Status Bar ─── */+ .status-bar {+ display: flex; align-items: center; gap: 10px;+ padding: 12px 16px; border-radius: var(--radius);+ font-size: 13px; font-weight: 500; margin-bottom: 32px;+ }+ .status-bar.ok { background: var(--green-subtle); border: 1px solid var(--green-border); color: var(--green); }+ .status-bar.err { background: var(--red-subtle); border: 1px solid var(--red-border); color: var(--red); }+ .status-bar.warn { background: var(--blue-subtle); border: 1px solid var(--blue-border); color: var(--blue); }+ .status-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }+ .status-bar.ok .status-dot { background: var(--green); }+ .status-bar.err .status-dot { background: var(--red); }+ .status-bar.warn .status-dot { background: var(--blue); }++ /* ─── Card ─── */+ .card {+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); padding: 24px; margin-bottom: 20px;+ transition: border-color 0.2s var(--ease);+ }+ .card:hover { border-color: var(--border-hover); }+ .card-label {+ font-size: 11px; font-weight: 700; letter-spacing: 0.8px;+ color: var(--text2); text-transform: uppercase; margin-bottom: 16px;+ }+ .card-title {+ font-size: 16px; font-weight: 700; margin-bottom: 6px; display: flex;+ align-items: center; gap: 8px;+ }+ .card-desc { font-size: 13px; color: var(--text2); line-height: 1.6; margin-bottom: 16px; }++ /* ─── Code Block ─── */+ .code-block {+ position: relative; background: #0a0a0c; border: 1px solid var(--border);+ border-radius: var(--radius-sm); overflow: hidden;+ }+ .code-header {+ display: flex; align-items: center; justify-content: space-between;+ padding: 8px 14px; background: var(--surface2);+ border-bottom: 1px solid var(--border);+ }+ .code-filename { font-size: 11px; font-weight: 600; color: var(--text2); font-family: 'JetBrains Mono', monospace; }+ .copy-btn {+ padding: 4px 10px; font-size: 11px; font-weight: 600;+ font-family: inherit; color: var(--text2); background: transparent;+ border: 1px solid var(--border); border-radius: 6px; cursor: pointer;+ transition: all 0.15s var(--ease);+ }+ .copy-btn:hover { border-color: var(--accent); color: var(--accent); }+ .copy-btn.copied { border-color: var(--green); color: var(--green); }+ pre {+ padding: 16px; overflow-x: auto; font-family: 'JetBrains Mono', monospace;+ font-size: 12.5px; line-height: 1.7; color: var(--text); tab-size: 2;+ }+ pre .key { color: #60a5fa; }+ pre .str { color: #4ade80; }+ pre .comment { color: var(--text3); font-style: italic; }+ pre .punct { color: var(--text2); }++ /* ─── Steps ─── */+ .steps { counter-reset: step; }+ .step {+ position: relative; padding-left: 40px; margin-bottom: 24px;+ counter-increment: step;+ }+ .step::before {+ content: counter(step);+ position: absolute; left: 0; top: 1px;+ width: 26px; height: 26px; border-radius: 50%;+ background: var(--surface2); border: 1px solid var(--border);+ display: flex; align-items: center; justify-content: center;+ font-size: 12px; font-weight: 700; color: var(--text2);+ }+ .step-title { font-size: 14px; font-weight: 700; margin-bottom: 6px; }+ .step-desc { font-size: 13px; color: var(--text2); line-height: 1.6; }+ .step-desc code {+ background: var(--surface2); padding: 2px 7px; border-radius: 5px;+ font-family: 'JetBrains Mono', monospace; font-size: 11.5px;+ color: var(--accent); border: 1px solid var(--border);+ }++ /* ─── Tool List ─── */+ .tool-grid { display: grid; gap: 8px; }+ .tool-item {+ display: flex; align-items: flex-start; gap: 12px;+ padding: 14px 16px; background: var(--surface2);+ border-radius: var(--radius-sm); border: 1px solid transparent;+ transition: border-color 0.15s var(--ease);+ }+ .tool-item:hover { border-color: var(--border); }+ .tool-name {+ font-family: 'JetBrains Mono', monospace; font-size: 12.5px;+ font-weight: 600; color: var(--accent); white-space: nowrap;+ }+ .tool-desc { font-size: 12.5px; color: var(--text2); line-height: 1.5; }++ /* ─── Divider ─── */+ .divider { height: 1px; background: var(--border); margin: 32px 0; opacity: 0.4; }++ /* ─── Animations ─── */+ .fade-in { animation: fadeIn 0.3s var(--ease); }+ @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }++ /* ─── Responsive ─── */+ @media (max-width: 640px) {+ .app { padding: 28px 16px 64px; }+ }+ </style>+</head>+<body>+ <div class="app fade-in">++ <!-- Nav -->+ <div class="nav">+ <a href="/" class="logo">pod<span>cli</span></a>+ <a href="/" class="nav-link">Back to app</a>+ </div>++ <!-- Header -->+ <div class="header">+ <h1>MCP Integration</h1>+ <p class="subtitle">Connect podcli to Claude Desktop, Claude Code, or any MCP-compatible client to generate clips through conversation.</p>+ </div>++ <!-- Connection Status -->+ <div id="status-bar" class="status-bar warn">+ <div class="status-dot"></div>+ <span id="status-text">Checking connection...</span>+ </div>++ <!-- Setup: Claude Desktop -->+ <div class="card">+ <div class="card-label">Setup</div>+ <div class="card-title">Claude Desktop</div>+ <div class="card-desc">+ Add podcli as an MCP server in your Claude Desktop configuration file. Claude will gain access to transcription, clip suggestion, and rendering tools.+ </div>++ <div class="steps">+ <div class="step">+ <div class="step-title">Open your config file</div>+ <div class="step-desc">+ macOS: <code>~/Library/Application Support/Claude/claude_desktop_config.json</code><br>+ Windows: <code>%APPDATA%\Claude\claude_desktop_config.json</code>+ </div>+ </div>+ <div class="step">+ <div class="step-title">Add the podcli server entry</div>+ <div class="step-desc">Paste this into the <code>mcpServers</code> object:</div>+ </div>+ </div>++ <div class="code-block" style="margin-bottom:16px">+ <div class="code-header">+ <span class="code-filename">claude_desktop_config.json</span>+ <button class="copy-btn" onclick="copyBlock(this, 'desktop-config')">Copy</button>+ </div>+ <pre id="desktop-config"><span class="punct">{</span>+ <span class="key">"mcpServers"</span><span class="punct">:</span> <span class="punct">{</span>+ <span class="key">"podcli"</span><span class="punct">:</span> <span class="punct">{</span>+ <span class="key">"command"</span><span class="punct">:</span> <span class="str">"node"</span><span class="punct">,</span>+ <span class="key">"args"</span><span class="punct">:</span> <span class="punct">[</span><span class="str" id="desktop-dist-path">"<span class="comment">loading...</span>"</span><span class="punct">]</span>+ <span class="punct">}</span>+ <span class="punct">}</span>+<span class="punct">}</span></pre>+ </div>++ <div class="step" style="padding-left:40px; counter-increment: step;">+ <div class="step-title">Restart Claude Desktop</div>+ <div class="step-desc">After saving, restart the app. You should see podcli listed in the MCP tools panel.</div>+ </div>+ </div>++ <!-- Setup: Claude Code -->+ <div class="card">+ <div class="card-title">Claude Code (CLI)</div>+ <div class="card-desc">+ Add podcli as an MCP server in your Claude Code project or global settings.+ </div>++ <div class="steps">+ <div class="step">+ <div class="step-title">Run this command in your terminal</div>+ <div class="step-desc">This registers podcli as an MCP server for the current project scope:</div>+ </div>+ </div>++ <div class="code-block">+ <div class="code-header">+ <span class="code-filename">terminal</span>+ <button class="copy-btn" onclick="copyBlock(this, 'code-config')">Copy</button>+ </div>+ <pre id="code-config"><span id="code-cmd-text"><span class="comment"># loading path...</span></span></pre>+ </div>+ </div>++ <div class="divider"></div>++ <!-- Available Tools -->+ <div class="card">+ <div class="card-label">Reference</div>+ <div class="card-title">Available MCP Tools</div>+ <div class="card-desc">These tools become available to Claude after connecting.</div>++ <div class="tool-grid">+ <div class="tool-item">+ <span class="tool-name">transcribe_podcast</span>+ <span class="tool-desc">Transcribe audio/video with Whisper. Supports model size selection, language detection, and speaker diarization.</span>+ </div>+ <div class="tool-item">+ <span class="tool-name">suggest_clips</span>+ <span class="tool-desc">Submit an array of viral moment suggestions with title, time range, and reasoning. Used by Claude to pass clip ideas.</span>+ </div>+ <div class="tool-item">+ <span class="tool-name">create_clip</span>+ <span class="tool-desc">Render a single short-form clip with caption style, crop strategy, and optional logo overlay.</span>+ </div>+ <div class="tool-item">+ <span class="tool-name">batch_create_clips</span>+ <span class="tool-desc">Render multiple clips in one call. Each clip can have its own caption style and crop settings.</span>+ </div>+ </div>+ </div>++ <!-- Example Prompts -->+ <div class="card">+ <div class="card-title">Example Prompts</div>+ <div class="card-desc">Try these with Claude after connecting:</div>++ <div class="tool-grid">+ <div class="tool-item" style="cursor:default;">+ <span class="tool-desc" style="color:var(--text);"><em>"Transcribe /path/to/episode.mp4 and find the 5 most viral moments, then export them with hormozi captions"</em></span>+ </div>+ <div class="tool-item" style="cursor:default;">+ <span class="tool-desc" style="color:var(--text);"><em>"Create a 30-second clip from 12:45 to 13:15 with branded captions and face-tracking crop"</em></span>+ </div>+ <div class="tool-item" style="cursor:default;">+ <span class="tool-desc" style="color:var(--text);"><em>"Batch export all suggested clips with karaoke-style captions"</em></span>+ </div>+ </div>+ </div>++ </div>++ <script>+ // Resolve the dist path and populate config blocks+ async function init() {+ try {+ const resp = await fetch('/api/integration-info');+ const data = await resp.json();++ // Desktop config+ const distEl = document.getElementById('desktop-dist-path');+ if (distEl) distEl.textContent = `"${data.dist_path}"`;++ // Claude Code command+ const codeEl = document.getElementById('code-cmd-text');+ if (codeEl) {+ codeEl.innerHTML = `claude mcp add podcli node ${escapeHtml(data.dist_path)}`;+ }++ // Status+ const bar = document.getElementById('status-bar');+ const txt = document.getElementById('status-text');+ if (data.server_ok) {+ bar.className = 'status-bar ok';+ txt.textContent = `Server running — ${data.tools_count} tools available`;+ } else {+ bar.className = 'status-bar err';+ txt.textContent = 'Server not built. Run: npm run build';+ }+ } catch (e) {+ const bar = document.getElementById('status-bar');+ const txt = document.getElementById('status-text');+ bar.className = 'status-bar err';+ txt.textContent = 'Could not reach server';+ }+ }++ function escapeHtml(str) {+ return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');+ }++ function copyBlock(btn, id) {+ const el = document.getElementById(id);+ const text = el.innerText;+ navigator.clipboard.writeText(text).then(() => {+ btn.textContent = 'Copied';+ btn.classList.add('copied');+ setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 1500);+ });+ }++ init();+ </script>+</body>+</html>diff --git a/src/ui/web-server.ts b/src/ui/web-server.tsnew file mode 100644index 0000000..4becd93--- /dev/null+++ b/src/ui/web-server.ts@@ -0,0 +1,626 @@+#!/usr/bin/env node+/**+ * podcli — Web UI Server+ *+ * Express server that provides:+ * - File upload endpoint for podcast videos+ * - Transcription with SSE progress streaming+ * - Clip creation with real-time progress+ * - Static file serving for the frontend+ */++import express from "express";+import multer from "multer";+import { createReadStream, existsSync, statSync } from "fs";+import { mkdir, readdir, unlink } from "fs/promises";+import { join, dirname, basename, extname } from "path";+import { fileURLToPath } from "url";+import { v4 as uuidv4 } from "uuid";++import { PythonExecutor } from "../services/python-executor.js";+import { TranscriptCache } from "../services/transcript-cache.js";+import { FileManager } from "../services/file-manager.js";+import { paths } from "../config/paths.js";++const __dirname = dirname(fileURLToPath(import.meta.url));+const app = express();+const PORT = parseInt(process.env.PORT || "3847");++// --- Services ---+const executor = new PythonExecutor();+const cache = new TranscriptCache();+const fileManager = new FileManager();++// --- State ---+// Track active jobs so the UI can poll progress+interface JobState {+ id: string;+ type: "transcribe" | "create_clip" | "batch_clips";+ status: "pending" | "running" | "done" | "error";+ progress: number;+ message: string;+ result?: Record<string, unknown>;+ error?: string;+ createdAt: number;+}++const jobs = new Map<string, JobState>();+// Store the latest transcript per uploaded file for the session+const sessionTranscripts = new Map<string, Record<string, unknown>>();++// --- Middleware ---+app.use(express.json({ limit: "50mb" }));++// Serve static frontend+app.use(express.static(join(__dirname, "public")));++// File upload config+const uploadDir = join(paths.working, "uploads");+const upload = multer({+ storage: multer.diskStorage({+ destination: async (_req, _file, cb) => {+ await mkdir(uploadDir, { recursive: true });+ cb(null, uploadDir);+ },+ filename: (_req, file, cb) => {+ const ext = extname(file.originalname);+ cb(null, `${uuidv4()}${ext}`);+ },+ }),+ limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB+ fileFilter: (_req, file, cb) => {+ const allowed = [".mp4", ".mov", ".mkv", ".webm", ".mp3", ".wav", ".m4a", ".png", ".jpg", ".jpeg", ".svg"];+ const ext = extname(file.originalname).toLowerCase();+ if (allowed.includes(ext)) {+ cb(null, true);+ } else {+ cb(new Error(`Unsupported format: ${ext}. Use MP4, MOV, MKV, WebM, MP3, WAV, M4A.`));+ }+ },+});++// --- API Routes ---++/**+ * POST /api/upload — Upload a podcast file+ */+app.post("/api/upload", upload.single("file"), (req, res) => {+ if (!req.file) {+ res.status(400).json({ error: "No file uploaded" });+ return;+ }+ res.json({+ file_path: req.file.path,+ filename: req.file.originalname,+ size_mb: Math.round((req.file.size / (1024 * 1024)) * 100) / 100,+ });+});++/**+ * POST /api/select-file — Use an existing local file (no upload needed)+ */+app.post("/api/select-file", (req, res) => {+ const { file_path } = req.body;+ if (!file_path || !existsSync(file_path)) {+ res.status(400).json({ error: "File not found" });+ return;+ }+ const stat = statSync(file_path);+ res.json({+ file_path,+ filename: basename(file_path),+ size_mb: Math.round((stat.size / (1024 * 1024)) * 100) / 100,+ });+});++/**+ * POST /api/import-transcript — Import an existing transcript (skip Whisper)+ * Accepts: { file_path, transcript } where transcript is an object with:+ * - text: string (full transcript text)+ * - words: Array<{ word, start, end, speaker? }>+ * - segments?: Array<{ text, start, end, speaker? }>+ * - duration?: number+ */+app.post("/api/import-transcript", (req, res) => {+ const { file_path, transcript } = req.body;++ if (!file_path) {+ res.status(400).json({ error: "file_path is required" });+ return;+ }+ if (!transcript || !transcript.words || !Array.isArray(transcript.words)) {+ res.status(400).json({+ error: "transcript must include a 'words' array with { word, start, end } objects",+ });+ return;+ }++ // Build a full transcript result from the imported data+ const result: Record<string, unknown> = {+ transcript: transcript.text || transcript.words.map((w: any) => w.word).join(" "),+ words: transcript.words,+ segments: transcript.segments || [],+ duration: transcript.duration || (transcript.words.length > 0+ ? transcript.words[transcript.words.length - 1].end+ : 0),+ language: transcript.language || "en",+ speakers: transcript.speakers || null,+ speaker_segments: transcript.speaker_segments || null,+ imported: true,+ };++ sessionTranscripts.set(file_path, result);++ res.json({+ status: "done",+ cached: false,+ imported: true,+ data: result,+ });+});++/**+ * POST /api/parse-transcript — Parse a speaker-labeled plain text transcript+ * Format: "Speaker (MM:SS)\ntext...\n\nSpeaker2 (MM:SS)\ntext..."+ * Uses Python backend to generate word-level timestamps.+ */+app.post("/api/parse-transcript", async (req, res) => {+ const { file_path, raw_text, total_duration, time_adjust = 0 } = req.body;++ if (!file_path) {+ res.status(400).json({ error: "file_path is required" });+ return;+ }+ if (!raw_text) {+ res.status(400).json({ error: "raw_text is required" });+ return;+ }++ try {+ const result = await executor.execute("parse_transcript", {+ raw_text,+ total_duration: total_duration || null,+ time_adjust: time_adjust || 0,+ });++ if (result.data) {+ sessionTranscripts.set(file_path, result.data as Record<string, unknown>);+ }++ res.json({+ status: "done",+ imported: true,+ data: result.data,+ });+ } catch (err: any) {+ res.status(500).json({ error: err.message || "Failed to parse transcript" });+ }+});++/**+ * POST /api/transcribe — Start transcription job+ */+app.post("/api/transcribe", async (req, res) => {+ const { file_path, model_size = "base", language, enable_diarization = false, num_speakers } = req.body;++ if (!file_path || !existsSync(file_path)) {+ res.status(400).json({ error: "File not found" });+ return;+ }++ // Check cache first+ const cached = await cache.get(file_path);+ if (cached) {+ const jobId = uuidv4();+ sessionTranscripts.set(file_path, cached as unknown as Record<string, unknown>);+ res.json({+ job_id: jobId,+ status: "done",+ cached: true,+ data: cached,+ });+ return;+ }++ const jobId = uuidv4();+ const job: JobState = {+ id: jobId,+ type: "transcribe",+ status: "running",+ progress: 0,+ message: "Starting transcription...",+ createdAt: Date.now(),+ };+ jobs.set(jobId, job);++ res.json({ job_id: jobId, status: "running" });++ // Run async+ executor+ .execute(+ "transcribe",+ { file_path, model_size, language, enable_diarization, num_speakers },+ (event) => {+ job.progress = event.percent;+ job.message = event.message;+ }+ )+ .then(async (result) => {+ job.status = "done";+ job.progress = 100;+ job.message = "Transcription complete";+ job.result = result.data;+ sessionTranscripts.set(file_path, result.data as Record<string, unknown>);+ // Cache it+ try {+ await cache.set(file_path, result.data as any);+ } catch {}+ })+ .catch((err) => {+ job.status = "error";+ job.error = err.message;+ job.message = `Error: ${err.message}`;+ });+});++/**+ * POST /api/create-clip — Start clip creation job+ */+app.post("/api/create-clip", async (req, res) => {+ const {+ video_path,+ start_second,+ end_second,+ caption_style = "hormozi",+ crop_strategy = "center",+ transcript_words = [],+ title = "clip",+ logo_path = null,+ } = req.body;++ if (!video_path || !existsSync(video_path)) {+ res.status(400).json({ error: "Video file not found" });+ return;+ }++ await fileManager.ensureDirectories();++ const jobId = uuidv4();+ const job: JobState = {+ id: jobId,+ type: "create_clip",+ status: "running",+ progress: 0,+ message: "Preparing clip...",+ createdAt: Date.now(),+ };+ jobs.set(jobId, job);++ res.json({ job_id: jobId, status: "running" });++ executor+ .execute(+ "create_clip",+ {+ video_path,+ start_second,+ end_second,+ caption_style,+ crop_strategy,+ transcript_words,+ title,+ output_dir: paths.output,+ logo_path,+ },+ (event) => {+ job.progress = event.percent;+ job.message = event.message;+ }+ )+ .then((result) => {+ job.status = "done";+ job.progress = 100;+ job.message = "Clip created!";+ job.result = result.data;+ })+ .catch((err) => {+ job.status = "error";+ job.error = err.message;+ job.message = `Error: ${err.message}`;+ });+});++/**+ * POST /api/batch-clips — Create multiple clips+ */+app.post("/api/batch-clips", async (req, res) => {+ const { video_path, clips, transcript_words = [], logo_path = null } = req.body;++ if (!video_path || !existsSync(video_path)) {+ res.status(400).json({ error: "Video file not found" });+ return;+ }++ await fileManager.ensureDirectories();++ const jobId = uuidv4();+ const job: JobState = {+ id: jobId,+ type: "batch_clips",+ status: "running",+ progress: 0,+ message: "Starting batch...",+ createdAt: Date.now(),+ };+ jobs.set(jobId, job);++ res.json({ job_id: jobId, status: "running" });++ executor+ .execute(+ "batch_clips",+ { video_path, clips, transcript_words, output_dir: paths.output, logo_path },+ (event) => {+ job.progress = event.percent;+ job.message = event.message;+ }+ )+ .then((result) => {+ job.status = "done";+ job.progress = 100;+ job.message = "Batch complete!";+ job.result = result.data;+ })+ .catch((err) => {+ job.status = "error";+ job.error = err.message;+ job.message = `Error: ${err.message}`;+ });+});++/**+ * GET /api/job/:id — Poll job status + progress+ */+app.get("/api/job/:id", (req, res) => {+ const job = jobs.get(req.params.id);+ if (!job) {+ res.status(404).json({ error: "Job not found" });+ return;+ }+ res.json(job);+});++/**+ * GET /api/job/:id/stream — SSE progress stream+ */+app.get("/api/job/:id/stream", (req, res) => {+ const jobId = req.params.id;+ const job = jobs.get(jobId);+ if (!job) {+ res.status(404).json({ error: "Job not found" });+ return;+ }++ res.writeHead(200, {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ });++ const interval = setInterval(() => {+ const current = jobs.get(jobId);+ if (!current) {+ clearInterval(interval);+ res.end();+ return;+ }++ res.write(+ `data: ${JSON.stringify({+ status: current.status,+ progress: current.progress,+ message: current.message,+ result: current.result,+ error: current.error,+ })}\n\n`+ );++ if (current.status === "done" || current.status === "error") {+ clearInterval(interval);+ setTimeout(() => res.end(), 500);+ }+ }, 500);++ req.on("close", () => clearInterval(interval));+});++/**+ * GET /api/outputs — List finished clips+ */+app.get("/api/outputs", async (_req, res) => {+ try {+ await mkdir(paths.output, { recursive: true });+ const files = await readdir(paths.output);+ const clips = files+ .filter((f) => f.endsWith(".mp4"))+ .map((f) => {+ const fullPath = join(paths.output, f);+ const stat = statSync(fullPath);+ return {+ filename: f,+ path: fullPath,+ size_mb: Math.round((stat.size / (1024 * 1024)) * 100) / 100,+ created: stat.mtime.toISOString(),+ };+ })+ .sort((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime());+ res.json(clips);+ } catch {+ res.json([]);+ }+});++/**+ * GET /api/download/:filename — Download a finished clip+ */+app.get("/api/download/:filename", (req, res) => {+ const filePath = join(paths.output, req.params.filename);+ if (!existsSync(filePath)) {+ res.status(404).json({ error: "File not found" });+ return;+ }+ res.download(filePath);+});++/**+ * GET /api/preview/:filename — Stream a video clip for in-browser playback+ */+app.get("/api/preview/:filename", (req, res) => {+ const filePath = join(paths.output, req.params.filename);+ if (!existsSync(filePath)) {+ res.status(404).json({ error: "File not found" });+ return;+ }++ const stat = statSync(filePath);+ const fileSize = stat.size;+ const range = req.headers.range;++ if (range) {+ const parts = range.replace(/bytes=/, "").split("-");+ const start = parseInt(parts[0], 10);+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;+ const chunkSize = end - start + 1;++ const stream = createReadStream(filePath, { start, end });+ res.writeHead(206, {+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,+ "Accept-Ranges": "bytes",+ "Content-Length": chunkSize,+ "Content-Type": "video/mp4",+ });+ stream.pipe(res);+ } else {+ res.writeHead(200, {+ "Content-Length": fileSize,+ "Content-Type": "video/mp4",+ });+ createReadStream(filePath).pipe(res);+ }+});++/**+ * GET /api/stream-source — Stream the source video for in-browser preview+ * Accepts ?path= query param (must be a file previously validated via /select-file or /upload)+ */+app.get("/api/stream-source", (req, res) => {+ const filePath = req.query.path as string;+ if (!filePath || !existsSync(filePath)) {+ res.status(404).json({ error: "File not found" });+ return;+ }++ const stat = statSync(filePath);+ const fileSize = stat.size;+ const range = req.headers.range;+ const ext = extname(filePath).toLowerCase();+ const mimeTypes: Record<string, string> = {+ ".mp4": "video/mp4",+ ".webm": "video/webm",+ ".mov": "video/quicktime",+ ".avi": "video/x-msvideo",+ ".mkv": "video/x-matroska",+ ".m4v": "video/mp4",+ };+ const contentType = mimeTypes[ext] || "video/mp4";++ if (range) {+ const parts = range.replace(/bytes=/, "").split("-");+ const start = parseInt(parts[0], 10);+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;+ const chunkSize = end - start + 1;+ const stream = createReadStream(filePath, { start, end });+ res.writeHead(206, {+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,+ "Accept-Ranges": "bytes",+ "Content-Length": chunkSize,+ "Content-Type": contentType,+ });+ stream.pipe(res);+ } else {+ res.writeHead(200, {+ "Content-Length": fileSize,+ "Content-Type": contentType,+ });+ createReadStream(filePath).pipe(res);+ }+});++// --- Integration info ---+app.get("/api/integration-info", (_req, res) => {+ const projectRoot = join(__dirname, "..", "..");+ const distPath = join(projectRoot, "dist", "index.js");+ const serverOk = existsSync(distPath);++ res.json({+ dist_path: distPath,+ project_root: projectRoot,+ server_ok: serverOk,+ tools_count: 4,+ });+});++// --- Analyze audio energy ---+app.post("/api/analyze-energy", async (req, res) => {+ const { video_path, segments } = req.body;+ if (!video_path) return res.json({ error: "video_path required" });+ try {+ const result = await executor.execute("analyze_energy", { video_path, segments: segments || [] });+ res.json(result.data || {});+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++// --- Encoder info ---+app.get("/api/encoder-info", async (_req, res) => {+ try {+ const result = await executor.execute("detect_encoder", {});+ res.json(result.data || {});+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++// --- Presets ---+app.get("/api/presets", async (_req, res) => {+ try {+ const result = await executor.execute("presets", { action: "list" });+ res.json(result.data || { presets: [] });+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++app.post("/api/presets", async (req, res) => {+ const { action, name, config } = req.body;+ try {+ const result = await executor.execute("presets", { action, name, config });+ res.json(result.data || {});+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++// --- Start ---+async function main() {+ await fileManager.ensureDirectories();+ await mkdir(uploadDir, { recursive: true });++ app.listen(PORT, () => {+ console.log(`\n 🎬 podcli running at:`);+ console.log(` ➜ http://localhost:${PORT}\n`);+ });+}++main().catch(console.error);diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 0000000..9778a7c--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}