#!/usr/bin/env python3 """ main.py — NEXUS PIPELINE v17 orchestrator (CLI + library). Usage: python main.py --dry-run --no-delay --test-fast --short-count 1 python main.py --kind long --topic "The lost city of Atlantis" python main.py --demo # mini 10-15s demo short → Telegram """ from __future__ import annotations import argparse import json import random import shutil import sys import time from pathlib import Path from typing import Optional from nexus.config import load_settings from nexus.utils import (atomic_write_json, cleanup_temp, disk_guard, live_status, log, memory_guard, purge_older_than, read_json, sanitize_filename, setup_logging) __version__ = "17.0.0-nexus" # ─────────────────────────── pipeline ───────────────────────────── def render_one(kind: str, topic: Optional[str] = None, force_topic: bool = False, voice: Optional[str] = None, model: Optional[str] = None) -> dict: """ Full render: topic → script → tts → whisper → subs → visuals → compose → thumbnails → QC → deliver (telegram) → (yt if enabled) → analytics. Returns a result dict. Never raises (all phases guarded). """ cfg = load_settings() result = {"kind": kind, "ok": False, "stage": "started"} live_status("stage", "topic", {"current_kind": kind}) ts = int(time.time()) # fail fast — no silent 3× regen loop when tooling is broken from nexus.utils import ffmpeg_available if not ffmpeg_available(): result["error"] = "ffmpeg not installed — cannot render" live_status("stage", "failed", result) return result # 1) topic from nexus.topics import choose_topic, keyword_extract, mark_used if topic and not force_topic: pass # treat as manual override chosen = choose_topic(kind, force_topic=topic if force_topic else None) topic = topic or chosen["title"] kws = keyword_extract(topic) slug = sanitize_filename(topic) live_status("stage", "script", {"current_topic": topic}) log.info("── RENDER %s: %s ──", kind.upper(), topic) # 2) script from nexus.script_engine import (build_description, generate_script, humanize, title_variants, validate_script) script = generate_script(topic, kind) script["text"] = humanize(script["text"]) valid = validate_script(script["text"], kind) if not valid["pass"] and script["model"] != "local-template": log.warning("Script validation warnings: %s", valid) result["script"] = {"model": script["model"], "words": script["words"]} live_status("stage", "tts") # 3) TTS with duration enforcement + NEVER-SILENT guard from nexus.tts_orchestra import make_tts from nexus.utils import ffprobe_duration work = cfg.paths.artifacts / "tmp" / ("render_%s_%d" % (kind, ts)) work.mkdir(parents=True, exist_ok=True) voice_path = work / ("voice_%s.mp3" % slug) vdur = 0.0 tts_engine = "none" for attempt in range(3): voice_path, tts_engine = make_tts(script["text"], voice_path, voice=voice, seed=ts + attempt) voice_norm = work / ("voice_norm_%s.mp3" % slug) from nexus.composer import normalize_voice vpath = normalize_voice(voice_path, voice_norm) or voice_path vdur = ffprobe_duration(vpath) or 0.0 voice_path = vpath if tts_engine == "tone": log.error("TTS produced TONE fallback — aborting render (never ship silent)") result["error"] = "TTS failed — all engines down" live_status("stage", "failed", result) return result if kind in ("short", "nano") and not (20 <= vdur <= 55): hint = int(45 * 155 / 60) # ≈116 words log.warning("Voice %.1fs outside 20-55s — regenerating script (hint ≤%d words, try %d)", vdur, hint, attempt + 1) script = generate_script(topic, kind, word_hint=hint) continue break if vdur < 12.0: log.error("Voice too short (%.1fs) after 3 attempts — aborting render", vdur) result["error"] = "TTS voice too short — refusing silent render" live_status("stage", "failed", result) return result result["voice_duration_s"] = round(vdur, 1) result["tts_engine"] = tts_engine live_status("stage", "whisper") # 4) whisper timecodes (audio = source of truth) — text passed for # silence-aligned fallback so subs ALWAYS match the voice from nexus.whisper_timecode import transcribe (voice_path.with_suffix(".txt")).write_text(script["text"], encoding="utf-8") tcs = transcribe(voice_path, kind, script_text=script["text"]) words = tcs["words"] if not words and script["text"]: from nexus.whisper_timecode import _estimate_words words = _estimate_words(script["text"], vdur) if not words: result["error"] = "no timecodes" live_status("stage", "failed", result) return result live_status("stage", "subtitles") # 5) subtitles from nexus.subtitles import build_ass, build_srt, build_vtt ass_path = build_ass(words, work / "subtitles.ass", kind) build_srt(words, work / "subtitles.srt", kind) build_vtt(words, work / "subtitles.vtt") # 6) visuals from nexus.visuals import collect_visual_clips live_status("stage", "visuals", {"progress_pct": 15}) clip_count = cfg.long_clip_target if kind == "long" else ( 6 if cfg.test_fast else cfg.short_clip_target) clips = collect_visual_clips(topic, kind, count=clip_count, work_dir=work / "clips", target_total_s=vdur + 1.0) if not clips: result["error"] = "no visual clips" live_status("stage", "failed", result) return result live_status("stage", "compose", {"progress_pct": 30}) # 7) music from nexus.music import get_music music = get_music(vdur, work, seed=ts) # 8) compose (with brain-storming hook line for the opening card) from nexus.composer import assemble from nexus.script_engine import extract_hook_line hook_line = extract_hook_line(script["text"]) final_name = "%s_%s_%d.mp4" % (kind, slug[:40], ts) final = work / final_name out = assemble(kind, clips, voice_path, ass_path, music, work, final, topic, hook_line=hook_line) if not out or not out.exists(): result["error"] = "assembly failed" live_status("stage", "failed", result) return result live_status("stage", "thumbnails", {"progress_pct": 55}) # 9) thumbnails from nexus.thumbnails import generate_thumbnails, insert_designed_frame titles = title_variants(topic, kind) title = random.choice(titles) thumb_meta = generate_thumbnails(topic, work / "thumbs", kind, title=title) if kind == "short" and thumb_meta.get("designed_frame"): framed = work / ("framed_" + final_name) fixed = insert_designed_frame(out, thumb_meta["designed_frame"], framed) if fixed: out = fixed # 10) QC gate from nexus.qc_gate import auto_repair, quality_control, quarantine live_status("stage", "qc", {"progress_pct": 75}) qc = quality_control(out, voice_path, thumb_meta, kind, ass_path) if not qc["pass"]: repaired = auto_repair(out, work / ("repaired_" + final_name), " ".join(qc["issues"])) if repaired: out = repaired qc = quality_control(out, voice_path, thumb_meta, kind, ass_path) result["qc"] = {"score": qc["score"], "pass": qc["pass"], "issues": qc["issues"]} if not qc["pass"]: log.error("QC FAIL: %s", "; ".join(qc["issues"])) quarantine(out) result["error"] = "QC failed: %s" % "; ".join(qc["issues"][:3]) live_status("stage", "failed", result) return result live_status("stage", "deliver", {"progress_pct": 90}) # 11) vault + deliver vault_dest = cfg.paths.vault / final_name shutil.copy2(out, vault_dest) size_mb = round(vault_dest.stat().st_size / 1e6, 2) result.update(vault=vault_dest.name, size_mb=size_mb, duration_s=qc["detail"].get("duration_s", 0), title=title, topic=topic) # 12) YouTube upload FIRST (never blocked by Telegram connectivity) from nexus.youtube_uploader import enabled as yt_enabled, upload_video if yt_enabled(): desc = build_description(topic, kind, kws, title, int(result["duration_s"])) yt_res = upload_video(vault_dest, { "title": title, "description": desc, "tags": kws + ["history", "mystery"], "kind": kind, "thumbnail": thumb_meta["variants"][thumb_meta["primary"]]["path"], }) result["youtube"] = yt_res if yt_res.get("status") == "uploaded": result["ok"] = True else: result["youtube"] = {"status": "disabled", "reason": "awaiting owner confirmation"} live_status("stage", "done", {"progress_pct": 100}) # 13) Telegram delivery — best-effort, NON-BLOCKING (HF can't always # reach api.telegram.org; a TG outage must never stall the pipeline) from nexus.telegram_sender import build_caption, configured, send_video from nexus.scheduler import next_run_plan nxt = next_run_plan() caption = build_caption({**result, "next_time": nxt.get("next_time", "—")}) tg_ok = False if configured(): thumb_primary = thumb_meta["variants"][thumb_meta["primary"]]["path"] import threading as _th def _deliver(): try: send_video(vault_dest, caption, work_dir=work, thumbnail=thumb_primary) except Exception as e: # noqa: BLE001 log.warning("Telegram deliver thread failed: %s", str(e)[:120]) _th.Thread(target=_deliver, daemon=True).start() tg_ok = "queued" # non-blocking — doesn't gate ok=True else: log.warning("Telegram not configured — video saved to vault only") # 13) records + analytics + notify from nexus.scheduler import record_upload from nexus.analytics import ingest_local_render from nexus.notify import notify if tg_ok or True: # count every rendered video record_upload(kind, {"title": title, "topic": topic, "kind": kind, "size_mb": size_mb, "qc_score": qc["score"], "vault": vault_dest.name, "telegram": tg_ok}) ingest_local_render(topic, kind, qc["score"], size_mb, True) notify("INFO", "Render complete: %s" % title, "kind=%s size=%.1fMB qc=%d/100 telegram=%s vault=%s" % (kind, size_mb, qc["score"], tg_ok, vault_dest.name)) result["ok"] = True live_status("last_render", {k: v for k, v in result.items() if k != "script"}) cleanup_temp() return result def run_pipeline(kind: Optional[str] = None, long_count: int = 0, short_count: int = 0, topic: Optional[str] = None, demo: bool = False) -> dict: """Orchestrator honoring counts; schedules auto-plan when no args.""" cfg = load_settings() from nexus.scheduler import daily_plan, today_counts, override_requests, clear_burst_flag results = [] if demo: return render_one("nano", topic="The mystery of the silent wings in radar history", force_topic=True) if kind == "long": plans = [("long", long_count or 1)] elif kind == "short": plans = [("short", short_count or 1)] else: plan = daily_plan() done = today_counts() longs = max(0, plan["longs"] - done["longs_done"]) shorts = max(0, plan["shorts"] - done["shorts_done"]) plans = ([("long", longs)] if longs else []) + ([("short", shorts)] if shorts else []) log.info("Daily plan: %s", plan) # override deck (bursts / kill) checked before each job for k, cnt in plans: ov = override_requests() if ov["kill"]: log.warning("KILL_SWITCH active — aborting before %s", k) break if ov["burst"]: k, topic = ov["burst"] cnt = 1 clear_burst_flag() for i in range(cnt): if not cfg.no_delay and not cfg.test_fast: d = random.randint(cfg.min_between_jobs_seconds, cfg.max_between_jobs_seconds) log.info("Human-like delay %ds before next job…", d) time.sleep(min(d, 5 if cfg.test_fast else d)) r = render_one(k, topic=topic, force_topic=bool(topic)) results.append(r) if not r.get("ok"): break return {"results": results, "ok": all(r.get("ok") for r in results)} # ─────────────────────────── CLI ────────────────────────────────── def build_arg_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser(prog="main.py", description="YT HISTRY NEXUS v17 pipeline") p.add_argument("--dry-run", action="store_true", help="never upload / send (safe)") p.add_argument("--no-delay", action="store_true", help="skip human-like delays") p.add_argument("--test-fast", action="store_true", help="minimal fast test render") p.add_argument("--kind", choices=["long", "short"], default=None) p.add_argument("--long-count", type=int, default=0) p.add_argument("--short-count", type=int, default=0) p.add_argument("--topic", type=str, default=None) p.add_argument("--single", action="store_true", help="single short render") p.add_argument("--demo", action="store_true", help="mini demo short → Telegram") p.add_argument("--version", action="version", version=__version__) return p def main(argv=None) -> int: args = build_arg_parser().parse_args(argv) cfg = load_settings() setup_logging(log_dir=cfg.paths.logs) log.info("═══ %s (%s) ═══", cfg.__class__.__module__ and "YT HISTRY NEXUS v17", __version__) if args.dry_run: log.info("DRY RUN: uploads disabled, telegram preview only") if args.single: args.kind = "short" args.short_count = 1 try: res = run_pipeline(kind=args.kind, long_count=args.long_count, short_count=args.short_count, topic=args.topic, demo=args.demo) ok = res.get("ok", False) log.info("Pipeline finished: ok=%s (%d renders)", ok, len(res.get("results", []))) return 0 if ok else 2 except KeyboardInterrupt: log.warning("Interrupted by user") return 130 except Exception as e: # noqa: BLE001 log.exception("FATAL: %s", e) return 1 if __name__ == "__main__": sys.exit(main())