Spaces:
Running

File size: 6,155 Bytes
bcd173d
 
dd3ea72
 
 
 
 
 
 
 
 
bcd173d
 
 
 
 
 
 
 
 
dd3ea72
 
 
 
 
 
bcd173d
dd3ea72
bcd173d
 
dd3ea72
 
 
 
bcd173d
 
dd3ea72
 
 
 
 
 
8b7cb4a
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
f231003
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd3ea72
 
 
 
 
 
 
 
f231003
dd3ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f231003
 
 
dd3ea72
f231003
 
 
 
 
dd3ea72
 
 
 
 
 
 
 
bcd173d
dd3ea72
 
 
 
 
bcd173d
dd3ea72
 
 
 
 
 
 
 
 
 
 
bcd173d
dd3ea72
 
bcd173d
 
 
dd3ea72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3
"""
runner.py β€” NEXUS DAEMON v17 (autonomous, make-and-forget).

APScheduler-free simple loop (robust on HF Space):
  - boot: warmup if vault empty β†’ 1 instant short
  - quota reset daily 00:05 UTC
  - next_run from scheduler brain (1-3 shorts/day, 1-2 longs/week)
  - heartbeat every 15s β†’ state/live_status.json
  - kill switch / force burst every 30s
  - memory + disk watchdogs
"""
from __future__ import annotations

import os
import signal
import sys
import time
from pathlib import Path

from nexus.config import load_settings
from nexus.scheduler import (daily_plan, next_run_plan, override_requests,
                             today_counts)
from nexus.utils import (cleanup_temp, disk_guard, get_live_status, get_system_stats,
                         live_status, log, memory_guard, purge_older_than,
                         setup_logging)

RUNNING = True


def _signal_handler(signum, frame):
    global RUNNING
    log.warning("Signal %s received β€” graceful shutdown after current job", signum)
    RUNNING = False


def warmup_if_empty() -> None:
    cfg = load_settings()
    mp4s = list(cfg.paths.vault.glob("*.mp4"))
    if not mp4s:
        log.info("Vault empty β€” warmup render (1 short)")
        from main import render_one
        try:
            render_one("short")
        except Exception as e:  # noqa: BLE001
            log.exception("Warmup render failed: %s", e)


def daily_maintenance() -> None:
    cfg = load_settings()
    purge_older_than(cfg.paths.artifacts, cfg.artifact_purge_hours)
    disk_guard()
    cleanup_temp()


def boot_maintenance() -> None:
    """Boot hygiene BEFORE heavy work (fixes 'launch timed out' crashes):
    1) free stale render workdirs + temp junk (ephemeral disk protection)
    2) trim huge log files
    3) wait for the UI to pass the HF health check (max ~5 min) so the
       container is 'healthy' before whisper/ffmpeg load their RAM."""
    import urllib.request
    cfg = load_settings()
    log.info("Boot maintenance: disk + log hygiene")
    try:
        purge_older_than(cfg.paths.artifacts, cfg.artifact_purge_hours)
        cleanup_temp()
        disk_guard()
    except Exception as e:  # noqa: BLE001
        log.warning("Boot cleanup partial failure: %s", str(e)[:120])
    logf = cfg.paths.logs / "nexus.log"
    try:
        if logf.exists() and logf.stat().st_size > 5 * 1024 * 1024:
            tail = logf.read_text(encoding="utf-8", errors="ignore").splitlines()[-500:]
            logf.write_text("\n".join(tail), encoding="utf-8")
            log.info("Boot maintenance: nexus.log trimmed to 500 lines")
    except OSError:
        pass
    port = os.getenv("PORT", "7860")
    for _ in range(60):
        try:
            with urllib.request.urlopen(
                    "http://127.0.0.1:%s/healthz" % port, timeout=3) as r:
                if r.status == 200:
                    log.info("Boot maintenance: UI healthy β€” safe to proceed")
                    return
        except Exception:  # noqa: BLE001
            time.sleep(5)
    log.warning("Boot maintenance: UI not healthy after 5 min β€” proceeding anyway")


def main_loop() -> int:
    cfg = load_settings()
    setup_logging(log_dir=cfg.paths.logs)
    signal.signal(signal.SIGTERM, _signal_handler)
    signal.signal(signal.SIGINT, _signal_handler)

    log.info("═══ NEXUS DAEMON v17 starting (pid=%d) ═══", os.getpid())
    live_status("daemon", "online", {"pid": os.getpid(), "stage": "BOOT"})
    boot_maintenance()

    last_heartbeat = 0.0
    last_check = 0.0
    last_day = time.strftime("%Y-%m-%d", time.gmtime())
    warmed = False

    while RUNNING:
        now = time.time()

        # heartbeats
        if now - last_heartbeat >= 15:
            st = get_system_stats()
            live_status("system", st)
            live_status("daemon_heartbeat", time.strftime("%H:%M:%S", time.gmtime()))
            last_heartbeat = now

        # overrides every 30s
        if now - last_check >= 30:
            ov = override_requests()
            if ov["kill"]:
                log.warning("KILL_SWITCH β€” stopping daemon")
                live_status("daemon", "killed")
                break
            last_check = now

        # memory + disk watchdogs
        memory_guard()
        disk_guard()

        # quota reset (00:05 UTC)
        today = time.strftime("%Y-%m-%d", time.gmtime())
        if today != last_day:
            last_day = today
            daily_maintenance()
            log.info("New UTC day β€” quotas reset, plan=%s", daily_plan())

        # warmup once β€” but NEVER under memory pressure (defer, retry next
        # loop): a heavy render at boot was the top suspect for the
        # "workload was not healthy after 30 min" launch failures.
        if not warmed:
            if memory_guard():
                log.warning("Warmup deferred: memory pressure β€” retry next loop")
            else:
                warmup_if_empty()
                warmed = True

        # plan next action
        plan = next_run_plan()
        live_status("next_plan", plan)
        if plan.get("action") == "render":
            kind = plan["kind"]
            log.info("NEXT: render %s (longs_left=%s shorts_left=%s reason=%s)",
                     kind, plan["longs_left"], plan["shorts_left"], plan["reason"])
            try:
                from main import render_one
                render_one(kind)
            except Exception as e:  # noqa: BLE001
                log.exception("Render crashed: %s", e)
            continue

        # sleep until next time (bounded to keep loop responsive)
        nxt = plan.get("next_time", "")
        sleep_s = 60
        if nxt:
            try:
                from datetime import datetime
                t = datetime.fromisoformat(nxt.replace("Z", "+00:00"))
                sleep_s = max(15, min(3600, (t - datetime.now(tz=t.tzinfo)).total_seconds()))
            except Exception:  # noqa: BLE001
                sleep_s = 300
        time.sleep(sleep_s)

    live_status("daemon", "offline")
    return 0


if __name__ == "__main__":
    sys.exit(main_loop())