Spaces:
Running
Running
feat: YouTube preflight check (/api/ytcheck β pure auth test, no upload) + youtube_ready flag
4617600 verified Download app.py from MDHojayfa213/YT-AI-based: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/MDHojayfa213/YT-AI-based/resolve/main/app.py
- Command line
-
hf download hf://spaces/MDHojayfa213/YT-AI-based/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MDHojayfa213/YT-AI-based/resolve/main/app.py
12.9 kB
| #!/usr/bin/env python3 | |
| """ | |
| app.py β NEXUS GOD-EYE UI (Gradio 5 + API endpoints). | |
| Tabs: DASHBOARD / VAULT / STUDIO / SCHEDULER / ANALYTICS / TOPICS / LOGS / SETTINGS | |
| API: /api/status, /api/vault, /api/logs, /api/trigger, /api/kill, /healthz | |
| If Gradio is missing β Flask fallback page (HF Space safe). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import threading | |
| import time | |
| from pathlib import Path | |
| from nexus.config import load_settings | |
| from nexus.utils import get_live_status, get_system_stats, live_status, read_json | |
| cfg = load_settings() | |
| cfg.paths.ensure() | |
| STATE = cfg.paths.state | |
| VAULT = cfg.paths.vault | |
| def _vault_listing(): | |
| out = [] | |
| for f in sorted(VAULT.glob("*.mp4"), key=lambda p: p.stat().st_mtime, reverse=True)[:200]: | |
| out.append({"name": f.name, "size_mb": round(f.stat().st_size / 1e6, 2), | |
| "mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(f.stat().st_mtime))}) | |
| return out | |
| def _log_tail(n: int = 200): | |
| try: | |
| lines = (cfg.paths.logs / "nexus.log").read_text(encoding="utf-8", errors="ignore").splitlines() | |
| return "\n".join(lines[-n:]) | |
| except OSError: | |
| return "(no log yet)" | |
| def _trigger_render(kind: str, topic: str): | |
| def _run(): | |
| try: | |
| from main import render_one | |
| render_one(kind, topic=topic or None, force_topic=bool(topic)) | |
| except Exception as e: # noqa: BLE001 | |
| live_status("last_error", str(e)[:500]) | |
| live_status("manual_trigger", {"kind": kind, "topic": topic, "at": time.time()}) | |
| threading.Thread(target=_run, daemon=True).start() | |
| return "Render started: %s %s" % (kind, topic or "(auto topic)") | |
| # βββββββββββββββββββββββββββ Flask fallback βββββββββββββββββββββββ | |
| def make_flask(): | |
| from flask import Flask, jsonify, request, send_from_directory, abort | |
| app = Flask(__name__) | |
| def index(): | |
| st = get_live_status() | |
| sys_st = get_system_stats() | |
| return """<!doctype html><html><head><title>YT HISTRY NEXUS v17</title> | |
| <style>body{font-family:monospace;background:#05070c;color:#d4d4d4;padding:2rem} | |
| h1{color:#00e5ff}.ok{color:#00ff88}</style></head><body> | |
| <h1>π¬ YT HISTRY NEXUS v17 (Flask fallback)</h1> | |
| <p>stage: <b class="ok">%s</b> | kind: %s | topic: %s</p> | |
| <p>cpu: %s%% ram: %s%% disk: %s%% | vault: %s</p> | |
| <pre>%s</pre></body></html>""" % ( | |
| st.get("stage", "?"), st.get("current_kind", ""), st.get("current_topic", ""), | |
| sys_st.get("cpu_pct", "?"), sys_st.get("ram_pct", "?"), sys_st.get("disk_pct", "?"), | |
| len(_vault_listing()), _log_tail(60).replace("<", "<")) | |
| def api_status(): | |
| st = get_live_status() | |
| st["system"] = get_system_stats() | |
| st["vault_count"] = len(_vault_listing()) | |
| return jsonify(st) | |
| def api_vault(): | |
| return jsonify({"files": _vault_listing()}) | |
| def api_logs(): | |
| n = int(request.args.get("n", 200)) | |
| return jsonify({"log": _log_tail(n)}) | |
| def api_trigger(): | |
| d = request.get_json(silent=True) or {} | |
| return jsonify({"ok": True, "msg": _trigger_render(d.get("kind", "short"), d.get("topic", ""))}) | |
| def api_kill(): | |
| (STATE / "KILL_SWITCH").write_text("1", encoding="utf-8") | |
| return jsonify({"ok": True}) | |
| def api_ytcheck(): | |
| try: | |
| from nexus.youtube_uploader import check_connection | |
| return jsonify(check_connection()) | |
| except Exception as e: # noqa: BLE001 | |
| return jsonify({"ok": False, "error": str(e)[:200]}) | |
| def vault_file(name: str): | |
| p = VAULT / name | |
| if not p.exists() or p.suffix.lower() not in (".mp4", ".mp3", ".jpg", ".png"): | |
| abort(404) | |
| return send_from_directory(VAULT, name) | |
| def healthz(): | |
| return "OK" | |
| return app | |
| # βββββββββββββββββββββββββββ Gradio UI ββββββββββββββββββββββββββββ | |
| def make_gradio(): | |
| import gradio as gr | |
| def status_view(): | |
| st = get_live_status() | |
| sys_st = get_system_stats() | |
| plan = st.get("next_plan", {}) | |
| rows = [ | |
| ["Stage", st.get("stage", "β")], | |
| ["Kind / Topic", "%s / %s" % (st.get("current_kind", "β"), st.get("current_topic", "β"))], | |
| ["Progress", "%s%%" % st.get("progress_pct", 0)], | |
| ["CPU / RAM", "%s%% / %s%%" % (sys_st.get("cpu_pct", 0), sys_st.get("ram_pct", 0))], | |
| ["Disk", "%s%% free %s GB" % (sys_st.get("disk_pct", 0), sys_st.get("disk_free_gb", 0))], | |
| ["Next action", plan.get("action", "β")], | |
| ["Next time", plan.get("next_time", "β")], | |
| ["Reason", plan.get("reason", "β")], | |
| ["Daemon", st.get("daemon", "β")], | |
| ["TG configured", "yes" if cfg.tg_bot_token and cfg.tg_channel_id else "no"], | |
| ["YouTube uploads", "ENABLED" if cfg.yt_upload_enabled else "DISABLED (owner-confirm)"], | |
| ] | |
| return "\n".join("β’ %s: %s" % (k, v) for k, v in rows) | |
| def vault_view(): | |
| rows = _vault_listing() | |
| if not rows: | |
| return "Vault empty β renders will appear here." | |
| return "\n".join("%s | %.1f MB | %s" % (r["name"], r["size_mb"], r["mtime"]) for r in rows[:50]) | |
| def logs_view(n): | |
| return _log_tail(int(n)) | |
| def trigger(kind, topic): | |
| return _trigger_render(kind, topic) | |
| def topics_view(): | |
| from nexus.topics import all_topics, load_used | |
| used = set(load_used()) | |
| lines = [] | |
| for t in all_topics(): | |
| mark = "β USED" if t["title"] in used else "Β· fresh" | |
| lines.append("[%s] %s (%s)" % (mark, t["title"], t["category"])) | |
| return "\n".join(lines) | |
| def scheduler_view(): | |
| from nexus.scheduler import daily_plan, simulate, today_counts | |
| d = today_counts() | |
| plan = daily_plan() | |
| sim = simulate(30) | |
| return ("TODAY plan: %s\nDone: %d longs / %d shorts\n\n" | |
| "30-DAY SIMULATION: shorts=%d longs=%d (weekend=%d weekday=%d off-day-longs=%d)" | |
| % (plan, d["longs_done"], d["shorts_done"], sim["total_shorts"], | |
| sim["total_longs"], sim["weekend_shorts"], sim["weekday_shorts"], | |
| sim["off_day_longs"])) | |
| def analytics_view(): | |
| scores = read_json(STATE / "topic_scores.json", {}) | |
| if not scores: | |
| return "No analytics yet." | |
| top = sorted(scores.items(), key=lambda kv: kv[1].get("score", 0), reverse=True)[:20] | |
| return "\n".join("%.1f | %s (picks=%s)" % (v.get("score", 0), k[:60], v.get("picks", 0)) | |
| for k, v in top) | |
| def settings_view(): | |
| return json.dumps(cfg.secrets_status(), indent=2) | |
| with gr.Blocks(title="YT HISTRY NEXUS v17", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# π¬ YT HISTRY NEXUS v17 β GOD-EYE") | |
| with gr.Tabs(): | |
| with gr.Tab("β DASHBOARD"): | |
| gr.Markdown("## Live telemetry (auto-refresh)") | |
| out_status = gr.Textbox(label="Status", lines=12) | |
| t_status = gr.Timer(value=5) | |
| t_status.tick(status_view, outputs=out_status) | |
| with gr.Tab("β‘ VAULT"): | |
| out_vault = gr.Textbox(label="Vault gallery", lines=20) | |
| btn_vault = gr.Button("Refresh vault") | |
| btn_vault.click(vault_view, outputs=out_vault) | |
| t_vault = gr.Timer(value=20) | |
| t_vault.tick(vault_view, outputs=out_vault) | |
| with gr.Tab("β’ STUDIO"): | |
| kind_in = gr.Dropdown(["short", "long", "nano"], value="short", label="Kind") | |
| topic_in = gr.Textbox(label="Topic (empty = auto-pick)") | |
| btn_render = gr.Button("π RENDER NOW") | |
| out_render = gr.Textbox(label="Result") | |
| btn_render.click(trigger, [kind_in, topic_in], out_render) | |
| gr.Markdown("_Renders stream to LOGS tab._") | |
| with gr.Tab("β£ SCHEDULER"): | |
| out_sched = gr.Textbox(label="Schedule", lines=14) | |
| btn_sched = gr.Button("Refresh") | |
| btn_sched.click(scheduler_view, outputs=out_sched) | |
| with gr.Tab("β€ ANALYTICS"): | |
| out_an = gr.Textbox(label="Topic leaderboard", lines=16) | |
| btn_an = gr.Button("Refresh") | |
| btn_an.click(analytics_view, outputs=out_an) | |
| with gr.Tab("β₯ TOPICS"): | |
| out_top = gr.Textbox(label="150 topics", lines=24) | |
| btn_top = gr.Button("Refresh") | |
| btn_top.click(topics_view, outputs=out_top) | |
| with gr.Tab("β¦ LOGS"): | |
| n_in = gr.Number(value=200, label="Lines") | |
| out_log = gr.Textbox(label="Live log", lines=24) | |
| btn_log = gr.Button("Refresh") | |
| btn_log.click(logs_view, n_in, out_log) | |
| t_log = gr.Timer(value=5) | |
| t_log.tick(logs_view, n_in, out_log) | |
| with gr.Tab("β§ SETTINGS"): | |
| out_set = gr.Textbox(label="Secrets status (masked)", lines=14) | |
| btn_set = gr.Button("Refresh") | |
| btn_set.click(settings_view, outputs=out_set) | |
| gr.Markdown("_Secrets are read from HF Space env β never shown in full._") | |
| return demo | |
| def _mount_api(demo) -> None: | |
| """Add FastAPI /api routes DIRECTLY onto the Gradio app (same port, reliable).""" | |
| from fastapi import Request | |
| from fastapi.responses import JSONResponse, FileResponse | |
| app = demo.app | |
| def status(): | |
| st = get_live_status() | |
| st["system"] = get_system_stats() | |
| st["vault_count"] = len(_vault_listing()) | |
| return st | |
| def vault(): | |
| return {"files": _vault_listing()} | |
| def logs(n: int = 200): | |
| return {"log": _log_tail(n)} | |
| async def trigger(request: Request): | |
| try: | |
| d = await request.json() | |
| except Exception: # noqa: BLE001 | |
| d = {} | |
| return {"ok": True, "msg": _trigger_render(d.get("kind", "short"), d.get("topic", ""))} | |
| def kill(): | |
| (STATE / "KILL_SWITCH").write_text("1", encoding="utf-8") | |
| return {"ok": True} | |
| def vault_file(name: str): | |
| p = VAULT / name | |
| if not p.exists() or p.suffix.lower() not in (".mp4", ".mp3", ".jpg", ".png"): | |
| return JSONResponse({"error": "not found"}, status_code=404) | |
| return FileResponse(p) | |
| def healthz(): | |
| return "OK" | |
| def ytcheck(): | |
| try: | |
| from nexus.youtube_uploader import check_connection | |
| return check_connection() | |
| except Exception as e: # noqa: BLE001 | |
| return {"ok": False, "error": str(e)[:200]} | |
| routes = [ | |
| ("/api/status", status, ["GET"]), | |
| ("/api/vault", vault, ["GET"]), | |
| ("/api/logs", logs, ["GET"]), | |
| ("/api/trigger", trigger, ["POST"]), | |
| ("/api/kill", kill, ["POST"]), | |
| ("/api/ytcheck", ytcheck, ["GET"]), | |
| ("/api/vault/{name}", vault_file, ["GET"]), | |
| ("/healthz", healthz, ["GET"]), | |
| ] | |
| for path, fn, methods in routes: | |
| try: | |
| app.add_api_route(path, fn, methods=methods) | |
| except Exception as e: # noqa: BLE001 | |
| print("[NEXUS] route %s failed: %s" % (path, str(e)[:120])) | |
| def main() -> None: | |
| port = int(os.getenv("PORT", "7860")) | |
| try: | |
| demo = make_gradio() | |
| demo.launch(server_name="0.0.0.0", server_port=port, | |
| prevent_thread_lock=True, show_error=True) | |
| # API routes MUST be registered after launch β Gradio rebuilds its | |
| # FastAPI app during launch and wipes pre-launch routes. | |
| _mount_api(demo) | |
| print("[NEXUS] Gradio UI live on :%d β YT HISTRY NEXUS v17 ONLINE" % port) | |
| while True: | |
| time.sleep(3600) | |
| except ImportError: | |
| print("[NEXUS] Gradio missing β Flask fallback UI") | |
| make_flask().run(host="0.0.0.0", port=port, debug=False) | |
| except Exception as e: # noqa: BLE001 | |
| print("[NEXUS] Gradio launch failed (%s) β Flask fallback UI" % str(e)[:150]) | |
| try: | |
| make_flask().run(host="0.0.0.0", port=port, debug=False) | |
| except Exception as e2: # noqa: BLE001 | |
| print("[NEXUS] FATAL UI failure:", e2) | |
| if __name__ == "__main__": | |
| main() | |