Spaces:
Running

MDHojayfa213 commited on
Commit
8d10400
·
verified ·
1 Parent(s): bd7eadb

Add missing deployment files (app.py, runner.py, Dockerfile, etc.)

Browse files
Files changed (6) hide show
  1. .gitignore +47 -0
  2. Dockerfile +53 -0
  3. app.py +954 -0
  4. requirements.txt +9 -0
  5. runner.py +355 -0
  6. start.sh +36 -0
.gitignore ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ *.egg-info/
8
+ .eggs/
9
+ build/
10
+ dist/
11
+ .venv/
12
+ venv/
13
+
14
+ # State & runtime artifacts
15
+ state/
16
+ artifacts/
17
+ vault/
18
+ tmp_run/
19
+ logs/
20
+ *.log
21
+
22
+ # Sensitive
23
+ .env
24
+ .env.local
25
+ client_secrets.json
26
+ token.json
27
+ *.token
28
+ *.key
29
+ *credentials*.json
30
+
31
+ # OS
32
+ .DS_Store
33
+ Thumbs.db
34
+
35
+ # Editors
36
+ .vscode/
37
+ .idea/
38
+ *.swp
39
+
40
+ # Test artifacts
41
+ .pytest_cache/
42
+ .coverage
43
+ htmlcov/
44
+
45
+ # Hugging Face cache
46
+ .cache/
47
+ hf_cache/
Dockerfile ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # System deps
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ ffmpeg \
6
+ wget \
7
+ xz-utils \
8
+ fonts-dejavu \
9
+ fonts-liberation \
10
+ ca-certificates \
11
+ libsm6 \
12
+ libxext6 \
13
+ libxrender1 \
14
+ curl \
15
+ git \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ # Static FFmpeg 7.x (in case the apt version is older - optional safety net)
19
+ # You can comment this out if your host has FFmpeg 7.x already.
20
+ # RUN wget -q https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz \
21
+ # && tar -xf ffmpeg-master-latest-linux64-gpl.tar.xz \
22
+ # && cp ffmpeg-master-latest-linux64-gpl/bin/ffmpeg /usr/local/bin/ \
23
+ # && cp ffmpeg-master-latest-linux64-gpl/bin/ffprobe /usr/local/bin/ \
24
+ # && rm -rf ffmpeg-master-latest-linux64-gpl*
25
+
26
+ # Working directory
27
+ WORKDIR /app
28
+
29
+ # Python deps first (better layer caching)
30
+ COPY requirements.txt .
31
+ RUN pip install --no-cache-dir -r requirements.txt
32
+
33
+ # App code
34
+ COPY . /app/
35
+
36
+ # Make sure dirs exist
37
+ RUN mkdir -p /app/state /app/artifacts /app/logs /app/vault /app/tmp_run
38
+
39
+ # Default port (HF Spaces uses 7860 by default)
40
+ ENV PORT=7860
41
+ ENV PYTHONUNBUFFERED=1
42
+ ENV DRY_RUN=true
43
+
44
+ # Expose port
45
+ EXPOSE 7860
46
+
47
+ # Health check
48
+ HEALTHCHECK --interval=60s --timeout=10s --start-period=30s --retries=3 \
49
+ CMD curl -f http://localhost:${PORT}/health || exit 1
50
+
51
+ # Start script
52
+ RUN chmod +x /app/start.sh
53
+ CMD ["/app/start.sh"]
app.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ YT HISTRY APEX v9.0 - GOD-EYE Dashboard
4
+ ========================================
5
+
6
+ Mobile-first Flask dashboard for the YT HISTRY pipeline.
7
+
8
+ Features:
9
+ - Real-time telemetry (CPU, RAM, Disk)
10
+ - Stage tracker (IDLE → SCRIPT_GEN → RENDER → UPLOAD → DONE)
11
+ - "The Vault" - video previews with time-ago
12
+ - "Neural Link" - color-coded live log feed
13
+ - Error banner with copy button
14
+ - KILL_SWITCH + FORCE_BURST buttons
15
+ - Mobile-responsive, dark theme with gold accents
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ import os
23
+ import platform
24
+ import shutil
25
+ import subprocess
26
+ import time
27
+ from datetime import datetime, timezone
28
+ from pathlib import Path
29
+ from typing import Any, Dict, List
30
+
31
+ try:
32
+ from flask import Flask, jsonify, render_template_string, request, Response
33
+ FLASK_AVAILABLE = True
34
+ except Exception:
35
+ FLASK_AVAILABLE = False
36
+
37
+
38
+ # Paths
39
+ ROOT = Path.cwd()
40
+ STATE_DIR = ROOT / "state"
41
+ LOG_DIR = ROOT / "logs"
42
+ ARTIFACTS_DIR = ROOT / "artifacts"
43
+ VAULT_DIR = ROOT / "vault"
44
+ LOG_FILE = LOG_DIR / "automation.log"
45
+ ERROR_LOG_FILE = LOG_DIR / "error.log"
46
+ LAST_RUN_FILE = STATE_DIR / "last_run.json"
47
+ RUN_REPORT_FILE = ARTIFACTS_DIR / "run_report.json"
48
+ KILL_SWITCH_FILE = STATE_DIR / "KILL_SWITCH"
49
+ FORCE_BURST_FILE = STATE_DIR / "FORCE_BURST"
50
+
51
+
52
+ def setup_logging() -> logging.Logger:
53
+ log = logging.getLogger("god-eye")
54
+ log.setLevel(logging.INFO)
55
+ if not log.handlers:
56
+ h = logging.StreamHandler()
57
+ h.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
58
+ log.addHandler(h)
59
+ return log
60
+
61
+
62
+ log = setup_logging()
63
+
64
+
65
+ # ============================================================================
66
+ # TELEMETRY
67
+ # ============================================================================
68
+
69
+ def get_disk_usage() -> Dict[str, Any]:
70
+ try:
71
+ total, used, free = shutil.disk_usage(ROOT)
72
+ return {
73
+ "total_gb": round(total / (1024 ** 3), 2),
74
+ "used_gb": round(used / (1024 ** 3), 2),
75
+ "free_gb": round(free / (1024 ** 3), 2),
76
+ "percent": round((used / total) * 100, 1),
77
+ }
78
+ except Exception as exc:
79
+ return {"total_gb": 0, "used_gb": 0, "free_gb": 0, "percent": 0, "error": str(exc)}
80
+
81
+
82
+ def get_cpu_usage() -> Dict[str, Any]:
83
+ try:
84
+ if platform.system() == "Linux":
85
+ # Sample twice over 100ms
86
+ with open("/proc/stat", "r") as f:
87
+ line1 = f.readline()
88
+ time.sleep(0.1)
89
+ with open("/proc/stat", "r") as f:
90
+ line2 = f.readline()
91
+ def parse(s):
92
+ parts = s.split()[1:]
93
+ return sum(int(x) for x in parts[:7]), int(parts[3]) # total, idle
94
+ t1, i1 = parse(line1)
95
+ t2, i2 = parse(line2)
96
+ dt = t2 - t1
97
+ di = i2 - i1
98
+ pct = round(100 * (1 - di / dt) if dt > 0 else 0, 1)
99
+ return {"percent": pct, "load_avg": _load_avg()}
100
+ return {"percent": 0, "load_avg": _load_avg()}
101
+ except Exception as exc:
102
+ return {"percent": 0, "load_avg": [0, 0, 0], "error": str(exc)}
103
+
104
+
105
+ def _load_avg() -> List[float]:
106
+ try:
107
+ if hasattr(os, "getloadavg"):
108
+ return [round(x, 2) for x in os.getloadavg()]
109
+ return [0, 0, 0]
110
+ except Exception:
111
+ return [0, 0, 0]
112
+
113
+
114
+ def get_memory_usage() -> Dict[str, Any]:
115
+ try:
116
+ if platform.system() == "Linux":
117
+ with open("/proc/meminfo", "r") as f:
118
+ lines = f.readlines()
119
+ info = {}
120
+ for line in lines:
121
+ parts = line.split(":")
122
+ if len(parts) == 2:
123
+ info[parts[0].strip()] = int(parts[1].strip().split()[0])
124
+ total = info.get("MemTotal", 0)
125
+ available = info.get("MemAvailable", 0)
126
+ used = total - available
127
+ return {
128
+ "total_mb": round(total / 1024, 1),
129
+ "used_mb": round(used / 1024, 1),
130
+ "available_mb": round(available / 1024, 1),
131
+ "percent": round((used / total) * 100, 1) if total > 0 else 0,
132
+ }
133
+ return {"total_mb": 0, "used_mb": 0, "available_mb": 0, "percent": 0}
134
+ except Exception as exc:
135
+ return {"total_mb": 0, "used_mb": 0, "available_mb": 0, "percent": 0, "error": str(exc)}
136
+
137
+
138
+ def get_telemetry() -> Dict[str, Any]:
139
+ return {
140
+ "disk": get_disk_usage(),
141
+ "cpu": get_cpu_usage(),
142
+ "memory": get_memory_usage(),
143
+ "timestamp": datetime.now(timezone.utc).isoformat() + "Z",
144
+ }
145
+
146
+
147
+ # ============================================================================
148
+ # LOG TAIL
149
+ # ============================================================================
150
+
151
+ def tail_log(path: Path, max_bytes: int = 8192, max_lines: int = 80) -> List[str]:
152
+ if not path.exists():
153
+ return []
154
+ try:
155
+ size = path.stat().st_size
156
+ if size > max_bytes:
157
+ with path.open("rb") as f:
158
+ f.seek(-max_bytes, 2)
159
+ data = f.read().decode("utf-8", errors="ignore")
160
+ else:
161
+ data = path.read_text(encoding="utf-8", errors="ignore")
162
+ lines = data.splitlines()[-max_lines:]
163
+ return [line for line in lines if line.strip()]
164
+ except Exception as exc:
165
+ log.warning("tail_log failed: %s", exc)
166
+ return []
167
+
168
+
169
+ def classify_log_line(line: str) -> Dict[str, Any]:
170
+ """Color-code log lines based on level + tags."""
171
+ color = "#88c0d0" # default light blue
172
+ icon = "•"
173
+ if "[FATAL]" in line or "ERROR" in line or "Traceback" in line:
174
+ color = "#bf616a"
175
+ icon = "❌"
176
+ elif "WARNING" in line:
177
+ color = "#ebcb8b"
178
+ icon = "⚠️"
179
+ elif "[UPLOAD]" in line or "uploaded" in line.lower():
180
+ color = "#a3be8c"
181
+ icon = "📤"
182
+ elif "[OK]" in line or "✅" in line:
183
+ color = "#a3be8c"
184
+ icon = "✅"
185
+ elif "[RENDER" in line or "Rendering" in line:
186
+ color = "#b48ead"
187
+ icon = "🎬"
188
+ return {"text": line, "color": color, "icon": icon}
189
+
190
+
191
+ # ============================================================================
192
+ # VAULT
193
+ # ============================================================================
194
+
195
+ def list_vault() -> List[Dict[str, Any]]:
196
+ if not VAULT_DIR.exists():
197
+ return []
198
+ items: List[Dict[str, Any]] = []
199
+ for path in sorted(VAULT_DIR.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):
200
+ try:
201
+ if not path.is_file():
202
+ continue
203
+ stat = path.stat()
204
+ size_mb = round(stat.st_size / (1024 * 1024), 2)
205
+ mtime = datetime.fromtimestamp(stat.st_mtime)
206
+ ago = (datetime.now(timezone.utc) - mtime.replace(tzinfo=None)).total_seconds()
207
+ items.append({
208
+ "name": path.name,
209
+ "path": str(path),
210
+ "size_mb": size_mb,
211
+ "mtime": mtime.isoformat() + "Z",
212
+ "ago_seconds": int(ago),
213
+ "ago_human": _humanize_ago(ago),
214
+ })
215
+ if len(items) >= 20:
216
+ break
217
+ except Exception:
218
+ continue
219
+ return items
220
+
221
+
222
+ def _humanize_ago(seconds: float) -> str:
223
+ if seconds < 60:
224
+ return f"{int(seconds)}s ago"
225
+ if seconds < 3600:
226
+ return f"{int(seconds // 60)}m ago"
227
+ if seconds < 86400:
228
+ return f"{int(seconds // 3600)}h ago"
229
+ return f"{int(seconds // 86400)}d ago"
230
+
231
+
232
+ def list_run_report() -> Dict[str, Any]:
233
+ if not RUN_REPORT_FILE.exists():
234
+ return {"summary": {"success_count": 0, "failure_count": 0}, "results": [], "failures": []}
235
+ try:
236
+ return json.loads(RUN_REPORT_FILE.read_text(encoding="utf-8"))
237
+ except Exception:
238
+ return {"summary": {"success_count": 0, "failure_count": 0}, "results": [], "failures": []}
239
+
240
+
241
+ def get_last_run() -> Dict[str, Any]:
242
+ if not LAST_RUN_FILE.exists():
243
+ return {"results": [], "failures": [], "success_count": 0, "failure_count": 0}
244
+ try:
245
+ return json.loads(LAST_RUN_FILE.read_text(encoding="utf-8"))
246
+ except Exception:
247
+ return {"results": [], "failures": [], "success_count": 0, "failure_count": 0}
248
+
249
+
250
+ # ============================================================================
251
+ # COMMANDS
252
+ # ============================================================================
253
+
254
+ def trigger_kill_switch() -> bool:
255
+ try:
256
+ KILL_SWITCH_FILE.parent.mkdir(parents=True, exist_ok=True)
257
+ KILL_SWITCH_FILE.write_text("KILL\n", encoding="utf-8")
258
+ log.info("KILL_SWITCH activated")
259
+ return True
260
+ except Exception as exc:
261
+ log.error("Failed to activate KILL_SWITCH: %s", exc)
262
+ return False
263
+
264
+
265
+ def trigger_force_burst() -> bool:
266
+ try:
267
+ FORCE_BURST_FILE.parent.mkdir(parents=True, exist_ok=True)
268
+ FORCE_BURST_FILE.write_text("BURST\n", encoding="utf-8")
269
+ log.info("FORCE_BURST activated")
270
+ return True
271
+ except Exception as exc:
272
+ log.error("Failed to activate FORCE_BURST: %s", exc)
273
+ return False
274
+
275
+
276
+ def is_kill_active() -> bool:
277
+ return KILL_SWITCH_FILE.exists()
278
+
279
+
280
+ def is_burst_active() -> bool:
281
+ return FORCE_BURST_FILE.exists()
282
+
283
+
284
+ def clear_burst() -> bool:
285
+ try:
286
+ if FORCE_BURST_FILE.exists():
287
+ FORCE_BURST_FILE.unlink()
288
+ return True
289
+ except Exception:
290
+ return False
291
+
292
+
293
+ # ============================================================================
294
+ # HTML TEMPLATE (mobile-first, dark theme, gold accents)
295
+ # ============================================================================
296
+
297
+ HTML_TEMPLATE = r"""<!DOCTYPE html>
298
+ <html lang="en">
299
+ <head>
300
+ <meta charset="UTF-8">
301
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
302
+ <title>YT HISTRY · GOD-EYE</title>
303
+ <style>
304
+ * { box-sizing: border-box; margin: 0; padding: 0; }
305
+ :root {
306
+ --bg: #0a0c14;
307
+ --card: #11141f;
308
+ --card-2: #161a28;
309
+ --border: #1f2433;
310
+ --text: #e4e8f0;
311
+ --muted: #6c7488;
312
+ --accent: #d4af37;
313
+ --accent-2: #ffd700;
314
+ --success: #4ade80;
315
+ --warn: #fbbf24;
316
+ --danger: #f87171;
317
+ --info: #60a5fa;
318
+ }
319
+ body {
320
+ background: var(--bg);
321
+ color: var(--text);
322
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
323
+ min-height: 100vh;
324
+ font-size: 14px;
325
+ -webkit-font-smoothing: antialiased;
326
+ }
327
+ .header {
328
+ background: linear-gradient(135deg, #0a0c14 0%, #1a1426 100%);
329
+ padding: 16px 18px;
330
+ border-bottom: 2px solid var(--accent);
331
+ display: flex;
332
+ align-items: center;
333
+ justify-content: space-between;
334
+ position: sticky;
335
+ top: 0;
336
+ z-index: 100;
337
+ backdrop-filter: blur(10px);
338
+ }
339
+ .header h1 {
340
+ font-size: 16px;
341
+ font-weight: 800;
342
+ letter-spacing: 1px;
343
+ background: linear-gradient(90deg, var(--accent-2), var(--accent));
344
+ -webkit-background-clip: text;
345
+ -webkit-text-fill-color: transparent;
346
+ }
347
+ .header .ver { font-size: 10px; color: var(--muted); }
348
+ .status-dot {
349
+ width: 10px;
350
+ height: 10px;
351
+ border-radius: 50%;
352
+ background: var(--success);
353
+ animation: pulse 2s infinite;
354
+ }
355
+ @keyframes pulse {
356
+ 0%, 100% { opacity: 1; transform: scale(1); }
357
+ 50% { opacity: 0.6; transform: scale(1.15); }
358
+ }
359
+ .container { padding: 16px; max-width: 1200px; margin: 0 auto; }
360
+ .card {
361
+ background: var(--card);
362
+ border: 1px solid var(--border);
363
+ border-radius: 12px;
364
+ padding: 14px;
365
+ margin-bottom: 12px;
366
+ }
367
+ .card h2 {
368
+ font-size: 11px;
369
+ font-weight: 700;
370
+ text-transform: uppercase;
371
+ letter-spacing: 1.5px;
372
+ color: var(--accent);
373
+ margin-bottom: 10px;
374
+ display: flex;
375
+ align-items: center;
376
+ gap: 8px;
377
+ }
378
+ .telemetry-grid {
379
+ display: grid;
380
+ grid-template-columns: 1fr 1fr;
381
+ gap: 10px;
382
+ }
383
+ .tel {
384
+ background: var(--card-2);
385
+ border-radius: 8px;
386
+ padding: 10px 12px;
387
+ border: 1px solid var(--border);
388
+ }
389
+ .tel .label { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }
390
+ .tel .value { font-size: 18px; font-weight: 700; color: var(--text); margin-top: 2px; }
391
+ .tel .unit { font-size: 11px; color: var(--muted); font-weight: 400; }
392
+ .progress-bar {
393
+ width: 100%;
394
+ height: 6px;
395
+ background: var(--card-2);
396
+ border-radius: 3px;
397
+ overflow: hidden;
398
+ margin-top: 6px;
399
+ }
400
+ .progress-fill {
401
+ height: 100%;
402
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
403
+ border-radius: 3px;
404
+ transition: width 0.5s ease;
405
+ }
406
+ .stage-tracker {
407
+ display: flex;
408
+ align-items: center;
409
+ justify-content: space-between;
410
+ padding: 10px 4px;
411
+ overflow-x: auto;
412
+ }
413
+ .stage {
414
+ flex-shrink: 0;
415
+ text-align: center;
416
+ font-size: 10px;
417
+ color: var(--muted);
418
+ transition: all 0.3s;
419
+ }
420
+ .stage .dot {
421
+ width: 12px;
422
+ height: 12px;
423
+ border-radius: 50%;
424
+ background: var(--border);
425
+ margin: 0 auto 4px;
426
+ transition: all 0.3s;
427
+ }
428
+ .stage.active .dot {
429
+ background: var(--accent-2);
430
+ box-shadow: 0 0 10px var(--accent-2);
431
+ animation: pulse 1.5s infinite;
432
+ }
433
+ .stage.done .dot { background: var(--success); }
434
+ .stage-arrow { color: var(--muted); margin: 0 4px; font-size: 10px; }
435
+ .btn {
436
+ display: inline-flex;
437
+ align-items: center;
438
+ justify-content: center;
439
+ gap: 6px;
440
+ padding: 10px 14px;
441
+ border-radius: 8px;
442
+ font-size: 12px;
443
+ font-weight: 700;
444
+ text-transform: uppercase;
445
+ letter-spacing: 1px;
446
+ border: none;
447
+ cursor: pointer;
448
+ transition: all 0.2s;
449
+ flex: 1;
450
+ }
451
+ .btn-danger { background: var(--danger); color: #fff; }
452
+ .btn-danger:hover { background: #ef4444; transform: translateY(-1px); }
453
+ .btn-success { background: var(--success); color: #062012; }
454
+ .btn-success:hover { background: #22c55e; transform: translateY(-1px); }
455
+ .btn-warning { background: var(--warn); color: #422006; }
456
+ .btn-warning:hover { background: #f59e0b; transform: translateY(-1px); }
457
+ .btn-secondary { background: var(--card-2); color: var(--text); border: 1px solid var(--border); }
458
+ .btn-secondary:hover { background: var(--border); }
459
+ .btn-row { display: flex; gap: 8px; margin-top: 12px; }
460
+ .log-feed {
461
+ background: #06080d;
462
+ border: 1px solid var(--border);
463
+ border-radius: 8px;
464
+ padding: 10px;
465
+ max-height: 280px;
466
+ overflow-y: auto;
467
+ font-family: "SF Mono", "Monaco", "Courier New", monospace;
468
+ font-size: 11px;
469
+ line-height: 1.5;
470
+ scrollbar-width: thin;
471
+ }
472
+ .log-feed::-webkit-scrollbar { width: 6px; }
473
+ .log-feed::-webkit-scrollbar-track { background: transparent; }
474
+ .log-feed::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
475
+ .log-line { display: flex; gap: 6px; padding: 2px 0; }
476
+ .log-icon { flex-shrink: 0; }
477
+ .vault-grid {
478
+ display: grid;
479
+ grid-template-columns: 1fr;
480
+ gap: 8px;
481
+ max-height: 400px;
482
+ overflow-y: auto;
483
+ }
484
+ .vault-item {
485
+ background: var(--card-2);
486
+ border: 1px solid var(--border);
487
+ border-radius: 8px;
488
+ padding: 10px 12px;
489
+ display: flex;
490
+ align-items: center;
491
+ gap: 10px;
492
+ transition: all 0.2s;
493
+ }
494
+ .vault-item:hover { border-color: var(--accent); }
495
+ .vault-thumb {
496
+ width: 60px;
497
+ height: 40px;
498
+ background: var(--bg);
499
+ border-radius: 4px;
500
+ display: flex;
501
+ align-items: center;
502
+ justify-content: center;
503
+ font-size: 18px;
504
+ flex-shrink: 0;
505
+ background: linear-gradient(135deg, var(--card-2), var(--border));
506
+ }
507
+ .vault-info { flex: 1; min-width: 0; }
508
+ .vault-name { font-size: 12px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
509
+ .vault-meta { font-size: 10px; color: var(--muted); margin-top: 2px; }
510
+ .stat-row { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 8px; }
511
+ .stat {
512
+ background: var(--card-2);
513
+ border-radius: 8px;
514
+ padding: 10px;
515
+ text-align: center;
516
+ border: 1px solid var(--border);
517
+ }
518
+ .stat .num { font-size: 20px; font-weight: 800; color: var(--accent-2); }
519
+ .stat .lbl { font-size: 9px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }
520
+ .error-banner {
521
+ background: linear-gradient(90deg, rgba(248,113,113,0.15), rgba(248,113,113,0.05));
522
+ border: 1px solid var(--danger);
523
+ border-radius: 8px;
524
+ padding: 12px;
525
+ margin-bottom: 12px;
526
+ display: none;
527
+ }
528
+ .error-banner.active { display: block; }
529
+ .error-banner pre {
530
+ font-size: 10px;
531
+ color: #fca5a5;
532
+ white-space: pre-wrap;
533
+ word-break: break-word;
534
+ max-height: 100px;
535
+ overflow-y: auto;
536
+ font-family: "SF Mono", monospace;
537
+ margin-top: 6px;
538
+ }
539
+ .copy-btn {
540
+ background: var(--card-2);
541
+ color: var(--danger);
542
+ border: 1px solid var(--danger);
543
+ border-radius: 4px;
544
+ padding: 3px 8px;
545
+ font-size: 9px;
546
+ cursor: pointer;
547
+ text-transform: uppercase;
548
+ letter-spacing: 1px;
549
+ font-weight: 700;
550
+ }
551
+ .copy-btn:hover { background: var(--danger); color: #fff; }
552
+ .refresh-info { font-size: 10px; color: var(--muted); text-align: center; margin-top: 10px; }
553
+ @media (min-width: 600px) {
554
+ .telemetry-grid { grid-template-columns: 1fr 1fr 1fr; }
555
+ .vault-grid { grid-template-columns: 1fr 1fr; }
556
+ }
557
+ @media (min-width: 900px) {
558
+ .container { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
559
+ .container .full { grid-column: 1 / -1; }
560
+ }
561
+ </style>
562
+ </head>
563
+ <body>
564
+ <div class="header">
565
+ <div>
566
+ <h1>⬡ YT HISTRY · GOD-EYE</h1>
567
+ <div class="ver">APEX v9.0 · 100% Truthful Telemetry</div>
568
+ </div>
569
+ <div class="status-dot" id="statusDot"></div>
570
+ </div>
571
+
572
+ <div class="container">
573
+ <div class="error-banner" id="errorBanner">
574
+ <div style="display:flex; justify-content:space-between; align-items:center;">
575
+ <strong style="color:var(--danger);">❌ LAST ERROR</strong>
576
+ <button class="copy-btn" onclick="copyError()">COPY</button>
577
+ </div>
578
+ <pre id="errorText"></pre>
579
+ </div>
580
+
581
+ <div class="card">
582
+ <h2>📊 TELEMETRY</h2>
583
+ <div class="telemetry-grid">
584
+ <div class="tel">
585
+ <div class="label">DISK</div>
586
+ <div class="value"><span id="diskPercent">0</span><span class="unit">%</span></div>
587
+ <div class="progress-bar"><div class="progress-fill" id="diskBar" style="width:0%"></div></div>
588
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
589
+ <span id="diskUsed">0</span> / <span id="diskTotal">0</span> GB
590
+ </div>
591
+ </div>
592
+ <div class="tel">
593
+ <div class="label">CPU</div>
594
+ <div class="value"><span id="cpuPercent">0</span><span class="unit">%</span></div>
595
+ <div class="progress-bar"><div class="progress-fill" id="cpuBar" style="width:0%"></div></div>
596
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
597
+ Load: <span id="cpuLoad">0, 0, 0</span>
598
+ </div>
599
+ </div>
600
+ <div class="tel">
601
+ <div class="label">RAM</div>
602
+ <div class="value"><span id="memPercent">0</span><span class="unit">%</span></div>
603
+ <div class="progress-bar"><div class="progress-fill" id="memBar" style="width:0%"></div></div>
604
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
605
+ <span id="memUsed">0</span> / <span id="memTotal">0</span> MB
606
+ </div>
607
+ </div>
608
+ <div class="tel">
609
+ <div class="label">NEXT RUN</div>
610
+ <div class="value" id="nextRun" style="font-size:14px;">—</div>
611
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;" id="lastRunAgo">—</div>
612
+ </div>
613
+ </div>
614
+ </div>
615
+
616
+ <div class="card">
617
+ <h2>⚡ PIPELINE STAGE</h2>
618
+ <div class="stage-tracker" id="stageTracker">
619
+ <div class="stage active" data-stage="IDLE"><div class="dot"></div>IDLE</div>
620
+ <div class="stage-arrow">→</div>
621
+ <div class="stage" data-stage="TOPIC"><div class="dot"></div>TOPIC</div>
622
+ <div class="stage-arrow">→</div>
623
+ <div class="stage" data-stage="SCRIPT"><div class="dot"></div>SCRIPT</div>
624
+ <div class="stage-arrow">→</div>
625
+ <div class="stage" data-stage="TTS"><div class="dot"></div>TTS</div>
626
+ <div class="stage-arrow">→</div>
627
+ <div class="stage" data-stage="VISUAL"><div class="dot"></div>VISUAL</div>
628
+ <div class="stage-arrow">→</div>
629
+ <div class="stage" data-stage="RENDER"><div class="dot"></div>RENDER</div>
630
+ <div class="stage-arrow">→</div>
631
+ <div class="stage" data-stage="UPLOAD"><div class="dot"></div>UPLOAD</div>
632
+ <div class="stage-arrow">→</div>
633
+ <div class="stage" data-stage="DONE"><div class="dot"></div>DONE</div>
634
+ </div>
635
+ <div class="stat-row" style="margin-top:14px;">
636
+ <div class="stat"><div class="num" id="statLongs">0</div><div class="lbl">Longs Today</div></div>
637
+ <div class="stat"><div class="num" id="statShorts">0</div><div class="lbl">Shorts Today</div></div>
638
+ <div class="stat"><div class="num" id="statFails">0</div><div class="lbl">Failures</div></div>
639
+ <div class="stat"><div class="num" id="statVault">0</div><div class="lbl">In Vault</div></div>
640
+ </div>
641
+ <div class="btn-row">
642
+ <button class="btn btn-success" id="forceBtn" onclick="forceBurst()">🚀 FORCE_BURST</button>
643
+ <button class="btn btn-danger" id="killBtn" onclick="killSwitch()">🛑 KILL_SWITCH</button>
644
+ </div>
645
+ </div>
646
+
647
+ <div class="card full">
648
+ <h2>🔮 NEURAL LINK · LIVE LOG</h2>
649
+ <div class="log-feed" id="logFeed"></div>
650
+ </div>
651
+
652
+ <div class="card full">
653
+ <h2>🏛️ THE VAULT</h2>
654
+ <div class="vault-grid" id="vaultGrid"></div>
655
+ </div>
656
+
657
+ <div class="refresh-info">
658
+ Auto-refresh every 2s · Last: <span id="lastRefresh">—</span>
659
+ </div>
660
+ </div>
661
+
662
+ <script>
663
+ async function fetchJson(url) {
664
+ try {
665
+ const res = await fetch(url);
666
+ return await res.json();
667
+ } catch (err) {
668
+ return null;
669
+ }
670
+ }
671
+
672
+ function classifyLogLine(line) {
673
+ let color = "#88c0d0", icon = "•";
674
+ if (line.includes("[FATAL]") || line.includes("ERROR") || line.includes("Traceback")) {
675
+ color = "#bf616a"; icon = "❌";
676
+ } else if (line.includes("WARNING")) {
677
+ color = "#ebcb8b"; icon = "⚠️";
678
+ } else if (line.includes("[UPLOAD]") || line.toLowerCase().includes("uploaded")) {
679
+ color = "#a3be8c"; icon = "📤";
680
+ } else if (line.includes("[OK]") || line.includes("✅")) {
681
+ color = "#a3be8c"; icon = "✅";
682
+ } else if (line.includes("[RENDER") || line.includes("Rendering")) {
683
+ color = "#b48ead"; icon = "🎬";
684
+ }
685
+ return {color, icon};
686
+ }
687
+
688
+ function humanizeAgo(seconds) {
689
+ if (seconds < 60) return seconds + "s ago";
690
+ if (seconds < 3600) return Math.floor(seconds/60) + "m ago";
691
+ if (seconds < 86400) return Math.floor(seconds/3600) + "h ago";
692
+ return Math.floor(seconds/86400) + "d ago";
693
+ }
694
+
695
+ function setStages(currentStage) {
696
+ const stages = ["IDLE","TOPIC","SCRIPT","TTS","VISUAL","RENDER","UPLOAD","DONE"];
697
+ const curIdx = stages.indexOf(currentStage);
698
+ document.querySelectorAll(".stage").forEach(el => {
699
+ el.classList.remove("active", "done");
700
+ const s = el.getAttribute("data-stage");
701
+ const idx = stages.indexOf(s);
702
+ if (idx < curIdx) el.classList.add("done");
703
+ else if (idx === curIdx) el.classList.add("active");
704
+ });
705
+ }
706
+
707
+ async function refresh() {
708
+ const telem = await fetchJson("/api/telemetry");
709
+ if (telem) {
710
+ document.getElementById("diskPercent").textContent = telem.disk.percent || 0;
711
+ document.getElementById("diskBar").style.width = (telem.disk.percent || 0) + "%";
712
+ document.getElementById("diskUsed").textContent = telem.disk.used_gb || 0;
713
+ document.getElementById("diskTotal").textContent = telem.disk.total_gb || 0;
714
+ document.getElementById("cpuPercent").textContent = telem.cpu.percent || 0;
715
+ document.getElementById("cpuBar").style.width = (telem.cpu.percent || 0) + "%";
716
+ document.getElementById("cpuLoad").textContent = (telem.cpu.load_avg || [0,0,0]).join(", ");
717
+ document.getElementById("memPercent").textContent = telem.memory.percent || 0;
718
+ document.getElementById("memBar").style.width = (telem.memory.percent || 0) + "%";
719
+ document.getElementById("memUsed").textContent = telem.memory.used_mb || 0;
720
+ document.getElementById("memTotal").textContent = telem.memory.total_mb || 0;
721
+ }
722
+
723
+ const status = await fetchJson("/api/status");
724
+ if (status) {
725
+ setStages(status.stage || "IDLE");
726
+ document.getElementById("statLongs").textContent = status.longs || 0;
727
+ document.getElementById("statShorts").textContent = status.shorts || 0;
728
+ document.getElementById("statFails").textContent = status.failures || 0;
729
+ document.getElementById("statVault").textContent = status.vault_count || 0;
730
+ document.getElementById("nextRun").textContent = status.next_run || "—";
731
+ document.getElementById("lastRunAgo").textContent = status.last_run_ago || "—";
732
+
733
+ if (status.kill_active) {
734
+ document.getElementById("killBtn").innerHTML = "✅ KILLED";
735
+ document.getElementById("killBtn").classList.add("btn-secondary");
736
+ } else {
737
+ document.getElementById("killBtn").innerHTML = "🛑 KILL_SWITCH";
738
+ document.getElementById("killBtn").classList.remove("btn-secondary");
739
+ }
740
+ if (status.burst_active) {
741
+ document.getElementById("forceBtn").innerHTML = "⏳ BURSTING...";
742
+ document.getElementById("forceBtn").classList.add("btn-warning");
743
+ } else {
744
+ document.getElementById("forceBtn").innerHTML = "🚀 FORCE_BURST";
745
+ document.getElementById("forceBtn").classList.remove("btn-warning");
746
+ }
747
+ }
748
+
749
+ const logs = await fetchJson("/api/logs");
750
+ if (logs && logs.lines) {
751
+ const feed = document.getElementById("logFeed");
752
+ feed.innerHTML = logs.lines.map(line => {
753
+ const c = classifyLogLine(line);
754
+ return `<div class="log-line" style="color:${c.color}"><span class="log-icon">${c.icon}</span><span>${escapeHtml(line)}</span></div>`;
755
+ }).join("");
756
+ feed.scrollTop = feed.scrollHeight;
757
+ }
758
+
759
+ const err = await fetchJson("/api/errors");
760
+ if (err && err.last_error) {
761
+ document.getElementById("errorBanner").classList.add("active");
762
+ document.getElementById("errorText").textContent = err.last_error;
763
+ } else {
764
+ document.getElementById("errorBanner").classList.remove("active");
765
+ }
766
+
767
+ const vault = await fetchJson("/api/vault");
768
+ if (vault && vault.items) {
769
+ const grid = document.getElementById("vaultGrid");
770
+ if (vault.items.length === 0) {
771
+ grid.innerHTML = '<div style="color:var(--muted); text-align:center; padding:20px; font-size:12px;">Vault is empty. Run a job to fill it.</div>';
772
+ } else {
773
+ grid.innerHTML = vault.items.map(it => `
774
+ <div class="vault-item">
775
+ <div class="vault-thumb">🎬</div>
776
+ <div class="vault-info">
777
+ <div class="vault-name">${escapeHtml(it.name)}</div>
778
+ <div class="vault-meta">${it.size_mb} MB · ${it.ago_human}</div>
779
+ </div>
780
+ </div>
781
+ `).join("");
782
+ }
783
+ }
784
+
785
+ document.getElementById("lastRefresh").textContent = new Date().toLocaleTimeString();
786
+ }
787
+
788
+ function escapeHtml(text) {
789
+ return String(text).replace(/[&<>"']/g, m => ({
790
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
791
+ }[m]));
792
+ }
793
+
794
+ async function forceBurst() {
795
+ await fetch("/api/force_burst", {method: "POST"});
796
+ refresh();
797
+ }
798
+
799
+ async function killSwitch() {
800
+ if (confirm("Activate KILL_SWITCH? This will stop the current run.")) {
801
+ await fetch("/api/kill", {method: "POST"});
802
+ refresh();
803
+ }
804
+ }
805
+
806
+ async function copyError() {
807
+ const text = document.getElementById("errorText").textContent;
808
+ try {
809
+ await navigator.clipboard.writeText(text);
810
+ alert("Error copied to clipboard");
811
+ } catch (err) {
812
+ alert("Copy failed: " + err);
813
+ }
814
+ }
815
+
816
+ refresh();
817
+ setInterval(refresh, 2000);
818
+ </script>
819
+ </body>
820
+ </html>"""
821
+
822
+
823
+ # ============================================================================
824
+ # FLASK APP
825
+ # ============================================================================
826
+
827
+ def create_app() -> "Flask":
828
+ if not FLASK_AVAILABLE:
829
+ raise RuntimeError("Flask not installed. Run: pip install flask")
830
+
831
+ app = Flask(__name__)
832
+
833
+ @app.route("/")
834
+ def index():
835
+ return render_template_string(HTML_TEMPLATE)
836
+
837
+ @app.route("/api/telemetry")
838
+ def api_telemetry():
839
+ return jsonify(get_telemetry())
840
+
841
+ @app.route("/api/logs")
842
+ def api_logs():
843
+ log_lines = tail_log(LOG_FILE, max_bytes=8192, max_lines=80)
844
+ error_lines = tail_log(ERROR_LOG_FILE, max_bytes=4096, max_lines=20)
845
+ # Combine, errors last (most recent at top of errors)
846
+ return jsonify({"lines": error_lines + log_lines[-60:]})
847
+
848
+ @app.route("/api/vault")
849
+ def api_vault():
850
+ return jsonify({"items": list_vault()})
851
+
852
+ @app.route("/api/errors")
853
+ def api_errors():
854
+ errs = tail_log(ERROR_LOG_FILE, max_bytes=8192, max_lines=50)
855
+ last_err = "\n".join(errs) if errs else ""
856
+ return jsonify({"last_error": last_err})
857
+
858
+ @app.route("/api/status")
859
+ def api_status():
860
+ report = list_run_report()
861
+ last_run = get_last_run()
862
+ vault = list_vault()
863
+ longs = sum(1 for r in report.get("results", []) if r.get("kind") == "long")
864
+ shorts = sum(1 for r in report.get("results", []) if r.get("kind") == "short")
865
+ # Determine stage from log content
866
+ log_lines = tail_log(LOG_FILE, max_bytes=4096, max_lines=15)
867
+ stage = "IDLE"
868
+ joined = " ".join(log_lines).lower()
869
+ if "pipeline start" in joined or "rendering long" in joined or "rendering short" in joined:
870
+ if "uploading" in joined or "upload progress" in joined:
871
+ stage = "UPLOAD"
872
+ elif "rendering" in joined or "assembling" in joined:
873
+ stage = "RENDER"
874
+ elif "voice" in joined or "tts" in joined:
875
+ stage = "TTS"
876
+ elif "script" in joined:
877
+ stage = "SCRIPT"
878
+ elif "topic" in joined:
879
+ stage = "TOPIC"
880
+ else:
881
+ stage = "RENDER"
882
+ # last_run timestamp
883
+ last_run_ts = last_run.get("timestamp", "")
884
+ last_run_ago = "—"
885
+ if last_run_ts:
886
+ try:
887
+ dt = datetime.fromisoformat(last_run_ts.replace("Z", ""))
888
+ ago = (datetime.now(timezone.utc) - dt.replace(tzinfo=None)).total_seconds()
889
+ last_run_ago = humanize_ago(ago)
890
+ except Exception:
891
+ pass
892
+ return jsonify({
893
+ "stage": stage,
894
+ "longs": longs,
895
+ "shorts": shorts,
896
+ "failures": report["summary"].get("failure_count", 0),
897
+ "vault_count": len(vault),
898
+ "next_run": "randomized",
899
+ "last_run_ago": last_run_ago,
900
+ "kill_active": is_kill_active(),
901
+ "burst_active": is_burst_active(),
902
+ })
903
+
904
+ @app.route("/api/kill", methods=["POST"])
905
+ def api_kill():
906
+ ok = trigger_kill_switch()
907
+ return jsonify({"success": ok})
908
+
909
+ @app.route("/api/force_burst", methods=["POST"])
910
+ def api_force_burst():
911
+ ok = trigger_force_burst()
912
+ return jsonify({"success": ok})
913
+
914
+ @app.route("/api/clear_burst", methods=["POST"])
915
+ def api_clear_burst():
916
+ ok = clear_burst()
917
+ return jsonify({"success": ok})
918
+
919
+ @app.route("/api/report")
920
+ def api_report():
921
+ return jsonify(list_run_report())
922
+
923
+ @app.route("/health")
924
+ def health():
925
+ return jsonify({"status": "ok", "version": "9.0.0"})
926
+
927
+ return app
928
+
929
+
930
+ def humanize_ago(seconds: float) -> str:
931
+ if seconds < 60:
932
+ return f"{int(seconds)}s ago"
933
+ if seconds < 3600:
934
+ return f"{int(seconds // 60)}m ago"
935
+ if seconds < 86400:
936
+ return f"{int(seconds // 3600)}h ago"
937
+ return f"{int(seconds // 86400)}d ago"
938
+
939
+
940
+ # ============================================================================
941
+ # MAIN
942
+ # ============================================================================
943
+
944
+ def main() -> int:
945
+ log.info("GOD-EYE Dashboard starting on port %s", os.getenv("PORT", "7860"))
946
+ app = create_app()
947
+ port = int(os.getenv("PORT", "7860"))
948
+ host = os.getenv("HOST", "0.0.0.0")
949
+ app.run(host=host, port=port, debug=False, use_reloader=False, threaded=True)
950
+ return 0
951
+
952
+
953
+ if __name__ == "__main__":
954
+ raise SystemExit(main())
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ requests>=2.31.0
2
+ Pillow>=10.0.0
3
+ gTTS>=2.5.0
4
+ edge-tts>=6.1.10
5
+ google-auth>=2.28.0
6
+ google-auth-oauthlib>=1.2.0
7
+ google-api-python-client>=2.120.0
8
+ Flask>=3.0.0
9
+ gunicorn>=21.2.0
runner.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ YT HISTRY APEX v9.0 - Autonomous Runner
4
+ =======================================
5
+
6
+ Schedules and runs the production pipeline with:
7
+ - Randomized viral timing (1-3 shorts/day, 1-2 longs/week + off-day bonus)
8
+ - FORCE_BURST support (manual trigger via dashboard)
9
+ - KILL_SWITCH support (emergency stop)
10
+ - 48-hour garbage collector (runs periodically)
11
+ - Health check + last-run tracking
12
+ - Cron-compatible loop (uses sleep, not exact cron precision)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import datetime as dt
19
+ from datetime import timezone
20
+ import json
21
+ import logging
22
+ import os
23
+ import random
24
+ import shutil
25
+ import signal
26
+ import subprocess
27
+ import sys
28
+ import time
29
+ from pathlib import Path
30
+ from typing import Any, Dict, Optional
31
+
32
+ ROOT = Path.cwd()
33
+ STATE_DIR = ROOT / "state"
34
+ LOG_DIR = ROOT / "logs"
35
+ ARTIFACTS_DIR = ROOT / "artifacts"
36
+ VAULT_DIR = ROOT / "vault"
37
+ LOG_FILE = LOG_DIR / "runner.log"
38
+ KILL_SWITCH_FILE = STATE_DIR / "KILL_SWITCH"
39
+ FORCE_BURST_FILE = STATE_DIR / "FORCE_BURST"
40
+ LAST_RUN_FILE = STATE_DIR / "last_run.json"
41
+ SCHEDULE_FILE = STATE_DIR / "schedule.json"
42
+
43
+
44
+ def setup_logging() -> logging.Logger:
45
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
46
+ log = logging.getLogger("runner")
47
+ log.setLevel(logging.INFO)
48
+ log.handlers.clear()
49
+ fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
50
+ sh = logging.StreamHandler(sys.stdout)
51
+ sh.setFormatter(fmt)
52
+ log.addHandler(sh)
53
+ try:
54
+ fh = logging.FileHandler(LOG_FILE, encoding="utf-8")
55
+ fh.setFormatter(fmt)
56
+ log.addHandler(fh)
57
+ except Exception:
58
+ pass
59
+ return log
60
+
61
+
62
+ log = setup_logging()
63
+
64
+
65
+ # ============================================================================
66
+ # SCHEDULING LOGIC
67
+ # ============================================================================
68
+
69
+ def compute_next_run() -> dt.datetime:
70
+ """Compute the next run time based on randomized viral timing.
71
+ - Mon-Thu: every 4-8h (favor shorts)
72
+ - Fri: every 3-6h (off-day bonus)
73
+ - Sat-Sun: every 2-5h (heavy shorts)
74
+ """
75
+ now = dt.datetime.now(timezone.utc)
76
+ weekday = now.weekday()
77
+ # Random delays in seconds
78
+ if weekday in (5, 6): # Sat-Sun: shorts-heavy
79
+ delay_sec = random.randint(2 * 3600, 5 * 3600)
80
+ elif weekday == 4: # Fri: off-day bonus
81
+ delay_sec = random.randint(3 * 3600, 6 * 3600)
82
+ else: # Mon-Thu
83
+ delay_sec = random.randint(4 * 3600, 8 * 3600)
84
+ return now + dt.timedelta(seconds=delay_sec)
85
+
86
+
87
+ def plan_jobs(now: Optional[dt.datetime] = None) -> Dict[str, int]:
88
+ """Decide how many longs + shorts to make in this run."""
89
+ current = now or dt.datetime.now(timezone.utc)
90
+ weekday = current.weekday()
91
+ # Mon-Thu: 0-1 long, 1-2 shorts
92
+ # Fri: 1-2 longs (off-day bonus), 1-2 shorts
93
+ # Sat-Sun: 0 longs, 1-3 shorts (user priority)
94
+ if weekday in (0, 1, 2, 3):
95
+ longs = random.randint(0, 1)
96
+ shorts = random.randint(1, 2)
97
+ elif weekday == 4:
98
+ longs = random.randint(1, 2)
99
+ shorts = random.randint(1, 2)
100
+ else:
101
+ longs = 0
102
+ shorts = random.randint(1, 3)
103
+ return {"longs": longs, "shorts": shorts}
104
+
105
+
106
+ # ============================================================================
107
+ # HEALTH & STATE
108
+ # ============================================================================
109
+
110
+ def write_health(state: Dict[str, Any]) -> None:
111
+ """Persist current runner state."""
112
+ try:
113
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
114
+ SCHEDULE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
115
+ except Exception as exc:
116
+ log.warning("Could not write health: %s", exc)
117
+
118
+
119
+ def read_health() -> Dict[str, Any]:
120
+ if not SCHEDULE_FILE.exists():
121
+ return {}
122
+ try:
123
+ return json.loads(SCHEDULE_FILE.read_text(encoding="utf-8"))
124
+ except Exception:
125
+ return {}
126
+
127
+
128
+ def is_kill_active() -> bool:
129
+ return KILL_SWITCH_FILE.exists()
130
+
131
+
132
+ def is_burst_active() -> bool:
133
+ return FORCE_BURST_FILE.exists()
134
+
135
+
136
+ def clear_burst() -> None:
137
+ try:
138
+ if FORCE_BURST_FILE.exists():
139
+ FORCE_BURST_FILE.unlink()
140
+ log.info("Cleared FORCE_BURST flag.")
141
+ except Exception as exc:
142
+ log.warning("Failed to clear FORCE_BURST: %s", exc)
143
+
144
+
145
+ def clear_kill() -> None:
146
+ try:
147
+ if KILL_SWITCH_FILE.exists():
148
+ KILL_SWITCH_FILE.unlink()
149
+ log.info("Cleared KILL_SWITCH flag (post-run reset).")
150
+ except Exception as exc:
151
+ log.warning("Failed to clear KILL_SWITCH: %s", exc)
152
+
153
+
154
+ # ============================================================================
155
+ # PIPELINE EXECUTION
156
+ # ============================================================================
157
+
158
+ def run_main(args: list, timeout: int = 7200) -> int:
159
+ """Run main.py as subprocess. Returns exit code."""
160
+ cmd = [sys.executable, "main.py", *args]
161
+ log.info("Executing: %s", " ".join(cmd))
162
+ try:
163
+ result = subprocess.run(
164
+ cmd,
165
+ cwd=str(ROOT),
166
+ timeout=timeout,
167
+ )
168
+ log.info("main.py exit code: %d", result.returncode)
169
+ return result.returncode
170
+ except subprocess.TimeoutExpired:
171
+ log.error("main.py timed out after %ds", timeout)
172
+ return 124
173
+ except Exception as exc:
174
+ log.error("main.py failed to launch: %s", exc)
175
+ return 1
176
+
177
+
178
+ def cleanup_old(max_age_hours: int = 48) -> int:
179
+ """Garbage collector: remove artifacts older than max_age_hours."""
180
+ cleaned = 0
181
+ cutoff = time.time() - (max_age_hours * 3600)
182
+ for base in (ARTIFACTS_DIR, VAULT_DIR):
183
+ if not base.exists():
184
+ continue
185
+ for path in list(base.iterdir()):
186
+ try:
187
+ if path.stat().st_mtime < cutoff:
188
+ if path.is_dir():
189
+ shutil.rmtree(path, ignore_errors=True)
190
+ else:
191
+ path.unlink()
192
+ cleaned += 1
193
+ except Exception:
194
+ continue
195
+ if cleaned > 0:
196
+ log.info("Cleaned %d old artifacts (>%dh).", cleaned, max_age_hours)
197
+ return cleaned
198
+
199
+
200
+ # ============================================================================
201
+ # MAIN LOOP
202
+ # ============================================================================
203
+
204
+ def handle_signal(signum, frame):
205
+ log.warning("Received signal %s; setting kill flag.", signum)
206
+ try:
207
+ KILL_SWITCH_FILE.write_text("KILL\n", encoding="utf-8")
208
+ except Exception:
209
+ pass
210
+ sys.exit(130)
211
+
212
+
213
+ def run_loop(
214
+ max_runs: Optional[int] = None,
215
+ once: bool = False,
216
+ cleanup_interval_minutes: int = 360,
217
+ ) -> int:
218
+ """Main scheduler loop.
219
+
220
+ Args:
221
+ max_runs: stop after N runs (None = forever)
222
+ once: run pipeline once and exit
223
+ cleanup_interval_minutes: how often to run GC
224
+ """
225
+ log.info("=" * 70)
226
+ log.info("YT HISTRY APEX v9.0 - AUTONOMOUS RUNNER STARTED")
227
+ log.info("=" * 70)
228
+ log.info("Time: %s UTC", dt.datetime.now(timezone.utc).isoformat())
229
+ log.info("Once=%s, Max runs=%s, GC interval=%dmin",
230
+ once, max_runs, cleanup_interval_minutes)
231
+
232
+ # Signal handlers
233
+ signal.signal(signal.SIGINT, handle_signal)
234
+ signal.signal(signal.SIGTERM, handle_signal)
235
+
236
+ runs_completed = 0
237
+ last_cleanup = time.time()
238
+
239
+ while True:
240
+ try:
241
+ # 1. Check kill switch (always reset after run completes)
242
+ if is_kill_active():
243
+ log.warning("KILL_SWITCH active. Exiting.")
244
+ return 130
245
+
246
+ # 2. Check force burst
247
+ force_burst = is_burst_active()
248
+
249
+ # 3. Plan jobs
250
+ if force_burst:
251
+ log.info("FORCE_BURST detected - running burst pipeline.")
252
+ plan = {"longs": 1, "shorts": 2}
253
+ next_run = dt.datetime.now(timezone.utc)
254
+ else:
255
+ plan = plan_jobs()
256
+ next_run = compute_next_run()
257
+
258
+ # Persist health
259
+ write_health({
260
+ "next_run": next_run.isoformat() + "Z",
261
+ "plan": plan,
262
+ "force_burst": force_burst,
263
+ "last_update": dt.datetime.now(timezone.utc).isoformat() + "Z",
264
+ "runs_completed": runs_completed,
265
+ })
266
+
267
+ # 4. Sleep until next run (unless FORCE_BURST)
268
+ now = dt.datetime.now(timezone.utc)
269
+ sleep_sec = (next_run - now).total_seconds()
270
+ if not force_burst and sleep_sec > 0:
271
+ log.info(
272
+ "Next run scheduled in %.0fs (%s UTC). Plan: %d long, %d short.",
273
+ sleep_sec, next_run.isoformat(),
274
+ plan["longs"], plan["shorts"],
275
+ )
276
+ # Sleep in small chunks so we can react to kill/burst quickly
277
+ chunk = 30
278
+ slept = 0
279
+ while slept < sleep_sec:
280
+ if is_kill_active():
281
+ log.warning("KILL_SWITCH during sleep. Exiting.")
282
+ return 130
283
+ if is_burst_active():
284
+ log.info("FORCE_BURST detected mid-sleep. Waking up.")
285
+ break
286
+ time.sleep(min(chunk, sleep_sec - slept))
287
+ slept += chunk
288
+
289
+ # 5. Run pipeline
290
+ args = []
291
+ if not force_burst:
292
+ if plan["longs"] > 0:
293
+ args.extend(["--long-count", str(plan["longs"])])
294
+ if plan["shorts"] > 0:
295
+ args.extend(["--short-count", str(plan["shorts"])])
296
+ else:
297
+ args.extend(["--force-burst"])
298
+ clear_burst()
299
+
300
+ log.info("Starting pipeline run #%d with args: %s",
301
+ runs_completed + 1, " ".join(args))
302
+ exit_code = run_main(args, timeout=7200)
303
+ runs_completed += 1
304
+ log.info("Run #%d completed with exit code %d", runs_completed, exit_code)
305
+
306
+ # 6. Periodic cleanup
307
+ if time.time() - last_cleanup > cleanup_interval_minutes * 60:
308
+ cleanup_old(max_age_hours=48)
309
+ last_cleanup = time.time()
310
+
311
+ # 7. Stop conditions
312
+ if once:
313
+ log.info("--once mode: exiting.")
314
+ return exit_code
315
+ if max_runs is not None and runs_completed >= max_runs:
316
+ log.info("Max runs reached (%d). Exiting.", max_runs)
317
+ return exit_code
318
+
319
+ # Loop again
320
+ time.sleep(5) # brief pause between iterations
321
+
322
+ except KeyboardInterrupt:
323
+ log.warning("Interrupted. Exiting.")
324
+ return 130
325
+ except Exception as exc:
326
+ log.exception("Loop error: %s", exc)
327
+ time.sleep(60) # back off on error
328
+
329
+
330
+ def main() -> int:
331
+ parser = argparse.ArgumentParser(description="YT HISTRY Autonomous Runner")
332
+ parser.add_argument("--once", action="store_true",
333
+ help="Run pipeline once and exit.")
334
+ parser.add_argument("--max-runs", type=int, default=None,
335
+ help="Stop after N runs (default: forever).")
336
+ parser.add_argument("--cleanup-interval", type=int, default=360,
337
+ help="Garbage collection interval in minutes.")
338
+ parser.add_argument("--cleanup-only", action="store_true",
339
+ help="Run GC and exit.")
340
+ args = parser.parse_args()
341
+
342
+ if args.cleanup_only:
343
+ cleaned = cleanup_old(max_age_hours=48)
344
+ log.info("Cleanup complete: %d items removed.", cleaned)
345
+ return 0
346
+
347
+ return run_loop(
348
+ max_runs=args.max_runs,
349
+ once=args.once,
350
+ cleanup_interval_minutes=args.cleanup_interval,
351
+ )
352
+
353
+
354
+ if __name__ == "__main__":
355
+ raise SystemExit(main())
start.sh ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # YT HISTRY APEX v9.0 - Startup Script
3
+ # Boots the autonomous runner (background) + the GOD-EYE dashboard (foreground)
4
+
5
+ set -e
6
+
7
+ cd /app
8
+
9
+ echo "============================================================"
10
+ echo " YT HISTRY APEX v9.0 - BOOT SEQUENCE"
11
+ echo "============================================================"
12
+ echo " Time: $(date -u)"
13
+ echo " Port: ${PORT:-7860}"
14
+ echo " DRY_RUN: ${DRY_RUN:-true}"
15
+ echo "============================================================"
16
+
17
+ # Ensure dirs exist
18
+ mkdir -p /app/state /app/artifacts /app/logs /app/vault /app/tmp_run
19
+
20
+ # Clean any stale kill/force flags from previous container
21
+ rm -f /app/state/KILL_SWITCH /app/state/FORCE_BURST
22
+
23
+ # Start the autonomous runner in background
24
+ echo "[1/2] Starting autonomous runner in background..."
25
+ nohup python3 runner.py >> /app/logs/runner_stdout.log 2>&1 &
26
+ RUNNER_PID=$!
27
+ echo " Runner PID: $RUNNER_PID"
28
+
29
+ # Give runner a moment to write its health file
30
+ sleep 3
31
+
32
+ # Start the GOD-EYE dashboard (foreground)
33
+ echo "[2/2] Starting GOD-EYE dashboard (port ${PORT:-7860})..."
34
+ echo " Open http://localhost:${PORT:-7860} in your browser."
35
+ echo "============================================================"
36
+ exec python3 app.py