Spaces:
Running

MDHojayfa213 commited on
Commit
c770ef1
·
verified ·
1 Parent(s): 7c3ad68

v10.3: Add missing deployment files

Browse files
Files changed (7) hide show
  1. .gitignore +47 -0
  2. Dockerfile +54 -0
  3. README.md +295 -0
  4. app.py +1089 -0
  5. requirements.txt +9 -0
  6. runner.py +380 -0
  7. start.sh +37 -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,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # v10.2: NO DRY_RUN default - auto-detect from secrets instead
43
+ # User can still override with DRY_RUN=true/false in Space Variables
44
+
45
+ # Expose port
46
+ EXPOSE 7860
47
+
48
+ # Health check
49
+ HEALTHCHECK --interval=60s --timeout=10s --start-period=30s --retries=3 \
50
+ CMD curl -f http://localhost:${PORT}/health || exit 1
51
+
52
+ # Start script
53
+ RUN chmod +x /app/start.sh
54
+ CMD ["/app/start.sh"]
README.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: YT HISTRY APEX
3
+ emoji: 🎬
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_file: app.py
8
+ pinned: false
9
+ license: mit
10
+ ---
11
+
12
+ # 🚨 YT HISTRY APEX v10.0 — Ultimate YouTube History & Mystery Automation
13
+
14
+ > The most cinematic, viral-grade, autonomous YouTube production engine ever built.
15
+ > Built with the "Apex Directive" philosophy: **no stage directions reach TTS, every clip has Ken Burns, atmospheric drones, WORD-BY-WORD karaoke subtitles, 4 thumbnail variants.**
16
+
17
+ [![Version](https://img.shields.io/badge/version-10.0.0-d4af37)]()
18
+ [![Python](https://img.shields.io/badge/python-3.11-blue)]()
19
+ [![License](https://img.shields.io/badge/license-MIT-green)]()
20
+
21
+ ---
22
+
23
+ ## 🎬 What This Does
24
+
25
+ Fully automated "make and forget" YouTube channel for **History & Mystery** documentaries.
26
+
27
+ - **Long videos** (1920×1080, 6-10 min) — independently produced, never assembled from a single clip
28
+ - **Shorts** (1080×1920, ≤58s) — independently produced vertical videos, NEVER cropped from longs
29
+ - **4 thumbnail variants** per video (A/B/C/D) — for A/B testing
30
+ - **Autonomous scheduler** — runs the pipeline 24/7 with random viral timing
31
+ - **GOD-EYE dashboard** — mobile-first live monitoring with KILL_SWITCH & FORCE_BURST
32
+
33
+ ---
34
+
35
+ ## ✨ Apex Features
36
+
37
+ ### Phase 1: Script & Audio Sanitization
38
+ - ✅ Strips ALL brackets `[00:00:00]`, parentheses `(ominous voice)`, AI meta-tags
39
+ - ✅ Nukes structural tags `Hook:`, `Setup:`, `Evidence:`, timestamps
40
+ - ✅ Emotional shift detection (suspenseful keywords trigger audio ducking + bass drop SFX)
41
+ - ✅ 181 curated topics (3× more than v6)
42
+
43
+ ### Phase 2: Visual Kinetic Engine (v10.0 UPGRADED)
44
+ - ✅ **12-16 clips per long**, **8-12 clips per short**
45
+ - ✅ **Ken Burns on EVERY clip** — cinematic drone-like zoom
46
+ - ✅ **Weighted random durations**: shorts favor 2-3s, longs favor 4-5s (natural variety)
47
+ - ✅ **Curves filter** (`preset=vintage`) for proper film color science
48
+ - ✅ Cinematic filter chain: film grain + vignette + contrast EQ + curves
49
+ - ✅ Multi-source fallback: **Pexels → Pixabay → AI image → Ken Burns**
50
+ - ✅ Light leak overlays for cinematic vibe
51
+ - ✅ Reddit r/UnresolvedMysteries trending topics as backup (30% chance)
52
+
53
+ ### Phase 3: Viral Subtitle Engine (v10.0 WORD-BY-WORD)
54
+ - ✅ **Word-by-word karaoke highlighting** — each word gets its own ASS event with active style
55
+ - ✅ Active word: gold + 1.15x scale via `\fad` animation
56
+ - ✅ Inactive words: white at base scale
57
+ - ✅ Smaller, less obtrusive: **32px longs, 44px shorts** (was 42-56px)
58
+ - ✅ Lower-third position (75% Y axis) via calculated MarginV
59
+ - ✅ Color psychology per emotion: gold (mystery), red (danger), cyan (mystery/cool)
60
+ - ✅ Black outline 3px + 70% black background bar
61
+ - ✅ **Emoji injection** based on keywords (😱 shocking, 💀 death, 🔥 fire, 👻 ghost)
62
+ - ✅ 2 layered events per "tick" — baseline (inactive) + overlay (active word)
63
+
64
+ ### Phase 4: Atmospheric Audio
65
+ - ✅ Multi-layer procedural drone (4 oscillators at 55/82/110/164 Hz)
66
+ - ✅ Low-pass filter for dark mystery vibe
67
+ - ✅ Fade-in/3s + fade-out/4s envelopes
68
+ - ✅ **Whoosh SFX** at clip transitions
69
+ - ✅ **Bass drop SFX** at emotional keywords (delayed to 30% of duration)
70
+ - ✅ **Bell ring SFX** at CTA (delayed to 90% of duration)
71
+ - ✅ Audio ducking (-20%) at emotional peaks
72
+
73
+ ### Phase 5: Hook / Outro Enhancement
74
+ - ✅ 3-second dramatic hook with topic title reveal + aggressive zoom (1.0 → 1.30)
75
+ - ✅ Pattern interrupts baked into script
76
+ - ✅ 5-second pulsing SUBSCRIBE outro with bell icon 🔔
77
+ - ✅ Animated SUBSCRIBE button with rounded corners + drop shadow
78
+
79
+ ### Phase 6: 6-Pass Robust Assembly
80
+ ```
81
+ Pass 1: Scale/grade all clips to uniform resolution + cinematic grain
82
+ Pass 2: Crossfade (xfade) assemble OR fade fallback OR concat fallback
83
+ Pass 3: Prepend hook + append outro
84
+ Pass 4: Burn ASS subtitles with karaoke-style animations
85
+ Pass 5: Add cinematic top/bottom bars (black@60%)
86
+ Pass 6: Mix voice + atmospheric drone + SFX (with ducking)
87
+ ```
88
+
89
+ ### Phase 7: Smart YouTube Upload
90
+ - ✅ Explicit token refresh (fixes the "not posting" bug)
91
+ - ✅ `cache_discovery=False` for HF compatibility
92
+ - ✅ Detailed error logging with full traceback
93
+ - ✅ Thumbnail upload alongside video
94
+ - ✅ Auto-chapters embedded in description
95
+ - ✅ Retry with exponential backoff on 5xx errors
96
+
97
+ ### Phase 8: Random Schedule (NEW per user spec)
98
+ | Day | Longs | Shorts | Cron (UTC) |
99
+ |-----------|-------|--------|------------|
100
+ | Mon-Thu | 0-1 | 1-2 | random 4-8h |
101
+ | Friday | 1-2 | 1-2 | random 3-6h (off-day bonus) |
102
+ | Sat-Sun | 0 | 1-3 | random 2-5h (heavy shorts) |
103
+
104
+ **Total: ~14-20 uploads/week** (varies due to randomness, matches user's "1-3 shorts/day, 1-2 longs/week" spec)
105
+
106
+ ---
107
+
108
+ ## 📦 Files
109
+
110
+ ```
111
+ yt_histry_project/
112
+ ├── main.py # Production engine (2,300+ lines, 98+ functions)
113
+ ├── app.py # GOD-EYE dashboard (Flask, mobile-first)
114
+ ├── runner.py # Autonomous scheduler
115
+ ├── Dockerfile # Python 3.11 + FFmpeg 7.x
116
+ ├── start.sh # Boots runner + dashboard
117
+ ├── requirements.txt # 9 dependencies
118
+ ├── README.md # This file
119
+ ├── .gitignore # Excludes secrets, state, logs
120
+ ├── PROJECT_RESUME.txt # Full project history
121
+ └── TODO.md # Master upgrade checklist
122
+ ```
123
+
124
+ ---
125
+
126
+ ## 🚀 Setup (5 minutes)
127
+
128
+ ### Step 1: Get API Keys
129
+
130
+ | Secret | Where |
131
+ |--------|-------|
132
+ | `GROQ_API_KEY` | https://console.groq.com/keys (free) |
133
+ | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) |
134
+ | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) |
135
+ | `YOUTUBE_CLIENT_ID` | Google Cloud Console → OAuth 2.0 Client |
136
+ | `YOUTUBE_CLIENT_SECRET` | Same |
137
+ | `YOUTUBE_REFRESH_TOKEN` | OAuth Playground method (see below) |
138
+ | `GMAIL_USER` | Your Gmail |
139
+ | `GMAIL_APP_PASSWORD` | https://myaccount.google.com/apppasswords |
140
+
141
+ ### Step 2: Get YouTube Refresh Token (Browser Method)
142
+
143
+ 1. Go to https://developers.google.com/oauthplayground
144
+ 2. ⚙️ gear icon → "Use your own OAuth credentials"
145
+ 3. Enter Client ID + Client Secret
146
+ 4. Left panel → YouTube Data API v3 → check `https://www.googleapis.com/auth/youtube.upload`
147
+ 5. "Authorize APIs" → sign in with your YouTube channel → Allow
148
+ 6. "Exchange authorization code for tokens"
149
+ 7. Copy the `refresh_token` value (starts with `1//`)
150
+
151
+ ### Step 3: Deploy to Hugging Face Space
152
+
153
+ **Already deployed**: https://huggingface.co/spaces/MDHojayfa213/YT-AI-based
154
+
155
+ To deploy fresh:
156
+ 1. Create Space at https://huggingface.co/new-space (SDK: Docker)
157
+ 2. Push these files to the Space repo
158
+ 3. Add the 8 secrets above in Space Settings → Variables
159
+ 4. Space auto-builds and boots
160
+
161
+ To push via command line:
162
+ ```bash
163
+ git clone https://oauth2:hf_YOUR_TOKEN@huggingface.co/spaces/MDHojayfa213/YT-AI-based
164
+ cp main.py app.py runner.py Dockerfile start.sh requirements.txt README.md .gitignore <space-dir>/
165
+ cd <space-dir>
166
+ git add . && git commit -m "YT HISTRY APEX v9.0"
167
+ git push origin main
168
+ ```
169
+
170
+ ### Step 4: Monitor
171
+
172
+ Open: **https://huggingface.co/spaces/MDHojayfa213/YT-AI-based**
173
+
174
+ The GOD-EYE dashboard shows:
175
+ - Real-time CPU, RAM, Disk telemetry
176
+ - Pipeline stage tracker (IDLE → TOPIC → SCRIPT → TTS → VISUAL → RENDER → UPLOAD → DONE)
177
+ - The Vault (recently produced videos with time-ago)
178
+ - Neural Link (live log feed, color-coded)
179
+ - 🚀 FORCE_BURST button (manual trigger)
180
+ - 🛑 KILL_SWITCH button (emergency stop)
181
+ - Last error with COPY button
182
+
183
+ ---
184
+
185
+ ## 🧪 Testing
186
+
187
+ ### Local Dry-Run Test
188
+ ```bash
189
+ python3 main.py --test-fast --dry-run --single
190
+ ```
191
+
192
+ This generates tiny local outputs in `artifacts/` without uploading.
193
+
194
+ ### View the Dashboard Locally
195
+ ```bash
196
+ # Terminal 1
197
+ python3 runner.py --once
198
+
199
+ # Terminal 2
200
+ python3 app.py
201
+ # Open http://localhost:7860
202
+ ```
203
+
204
+ ### Run a Single Production Cycle
205
+ ```bash
206
+ python3 main.py --live --long-count 1 --short-count 1 --no-delay
207
+ ```
208
+
209
+ ---
210
+
211
+ ## 🛡️ Failure Handling
212
+
213
+ | Failure | Response |
214
+ |---------|----------|
215
+ | Groq API down | Uses fallback script (181 topics, never runs out) |
216
+ | Edge TTS fails | Switches to gTTS, then synthetic sine wave |
217
+ | Pexels down | Tries Pixabay → AI image → Ken Burns |
218
+ | YouTube token expired | Clear error in dashboard with copy button |
219
+ | FFmpeg filter missing | Uses compatible alternative (xfade → fade → concat) |
220
+ | Music/SFX fails | Video proceeds with voice only |
221
+ | Any crash | Sends failure email, cleans temp, logs to `error.log` |
222
+
223
+ ---
224
+
225
+ ## 🧠 Why APEX v9.0?
226
+
227
+ Previous versions (Qwen v1-v6, Kimi v6, Jules v7-v8) all had:
228
+ - ❌ Static subtitles or huge blocking text
229
+ - ❌ Single looping backgrounds (flagged by YouTube as "low effort")
230
+ - ❌ No atmospheric audio (felt flat)
231
+ - ❌ Limited to 2 thumbnail variants
232
+ - ❌ Shorts cropped from longs (lazy, bad quality)
233
+ - ❌ xfade crashes on some FFmpeg versions
234
+
235
+ **APEX v9.0 fixes ALL of these:**
236
+ - ✅ ASS karaoke subtitles with animations + emoji
237
+ - ✅ 12-16 unique clips per long with Ken Burns + film grain
238
+ - ✅ Multi-layer procedural drone + 3 SFX layers
239
+ - ✅ 4 thumbnail variants (A/B/C/D) for testing
240
+ - ✅ Shorts independently produced from scratch
241
+ - ✅ Triple fallback chain: xfade → fade → concat
242
+ - ✅ Cinematic filter chain (vignette + grain + EQ + curve)
243
+
244
+ ---
245
+
246
+ ## 📊 Expected Output
247
+
248
+ **Monthly (assuming consistent runs):**
249
+ - ~80-120 long videos
250
+ - ~150-200 shorts
251
+ - Total: ~250 videos/month
252
+ - Cost: $0 (all free tier APIs)
253
+
254
+ ---
255
+
256
+ ## 🐛 Troubleshooting
257
+
258
+ ### "Module not found"
259
+ ```bash
260
+ pip install -r requirements.txt
261
+ ```
262
+
263
+ ### "FFmpeg not available"
264
+ ```bash
265
+ # Ubuntu/Debian
266
+ sudo apt-get install ffmpeg
267
+
268
+ # macOS
269
+ brew install ffmpeg
270
+ ```
271
+
272
+ ### "YouTube upload failed: invalid_grant"
273
+ Your refresh token expired. Regenerate via OAuth Playground (see Step 2).
274
+
275
+ ### "Dashboard shows IDLE but no runs happening"
276
+ Check `state/schedule.json` for next run time. Check logs at `logs/runner.log`.
277
+
278
+ ---
279
+
280
+ ## 📜 License
281
+
282
+ MIT — go wild. 🚀
283
+
284
+ ---
285
+
286
+ ## 🙏 Credits
287
+
288
+ - **Qwen AI** — initial blueprint
289
+ - **Kimi AI** — Kimi v6.0 base
290
+ - **Jules (Gemini)** — Apex Directive v7-v8 (karaoke subtitles, cinematic grade)
291
+ - **You (mdhojayfa213)** — for the relentless "go deeper" feedback that pushed us to v9.0
292
+
293
+ ---
294
+
295
+ **The pipeline is designed for "set and forget" — but the dashboard gives you full control when you want it.** 🎯
app.py ADDED
@@ -0,0 +1,1089 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ LIVE_STATUS_FILE = STATE_DIR / "live_status.json" # v10.1
51
+ SCHEDULE_FILE = STATE_DIR / "schedule.json" # v10.1
52
+
53
+
54
+ def setup_logging() -> logging.Logger:
55
+ log = logging.getLogger("god-eye")
56
+ log.setLevel(logging.INFO)
57
+ if not log.handlers:
58
+ h = logging.StreamHandler()
59
+ h.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
60
+ log.addHandler(h)
61
+ return log
62
+
63
+
64
+ log = setup_logging()
65
+
66
+
67
+ # ============================================================================
68
+ # TELEMETRY
69
+ # ============================================================================
70
+
71
+ def get_disk_usage() -> Dict[str, Any]:
72
+ try:
73
+ total, used, free = shutil.disk_usage(ROOT)
74
+ return {
75
+ "total_gb": round(total / (1024 ** 3), 2),
76
+ "used_gb": round(used / (1024 ** 3), 2),
77
+ "free_gb": round(free / (1024 ** 3), 2),
78
+ "percent": round((used / total) * 100, 1),
79
+ }
80
+ except Exception as exc:
81
+ return {"total_gb": 0, "used_gb": 0, "free_gb": 0, "percent": 0, "error": str(exc)}
82
+
83
+
84
+ def get_cpu_usage() -> Dict[str, Any]:
85
+ try:
86
+ if platform.system() == "Linux":
87
+ # Sample twice over 100ms
88
+ with open("/proc/stat", "r") as f:
89
+ line1 = f.readline()
90
+ time.sleep(0.1)
91
+ with open("/proc/stat", "r") as f:
92
+ line2 = f.readline()
93
+ def parse(s):
94
+ parts = s.split()[1:]
95
+ return sum(int(x) for x in parts[:7]), int(parts[3]) # total, idle
96
+ t1, i1 = parse(line1)
97
+ t2, i2 = parse(line2)
98
+ dt = t2 - t1
99
+ di = i2 - i1
100
+ pct = round(100 * (1 - di / dt) if dt > 0 else 0, 1)
101
+ return {"percent": pct, "load_avg": _load_avg()}
102
+ return {"percent": 0, "load_avg": _load_avg()}
103
+ except Exception as exc:
104
+ return {"percent": 0, "load_avg": [0, 0, 0], "error": str(exc)}
105
+
106
+
107
+ def _load_avg() -> List[float]:
108
+ try:
109
+ if hasattr(os, "getloadavg"):
110
+ return [round(x, 2) for x in os.getloadavg()]
111
+ return [0, 0, 0]
112
+ except Exception:
113
+ return [0, 0, 0]
114
+
115
+
116
+ def get_memory_usage() -> Dict[str, Any]:
117
+ try:
118
+ if platform.system() == "Linux":
119
+ with open("/proc/meminfo", "r") as f:
120
+ lines = f.readlines()
121
+ info = {}
122
+ for line in lines:
123
+ parts = line.split(":")
124
+ if len(parts) == 2:
125
+ info[parts[0].strip()] = int(parts[1].strip().split()[0])
126
+ total = info.get("MemTotal", 0)
127
+ available = info.get("MemAvailable", 0)
128
+ used = total - available
129
+ return {
130
+ "total_mb": round(total / 1024, 1),
131
+ "used_mb": round(used / 1024, 1),
132
+ "available_mb": round(available / 1024, 1),
133
+ "percent": round((used / total) * 100, 1) if total > 0 else 0,
134
+ }
135
+ return {"total_mb": 0, "used_mb": 0, "available_mb": 0, "percent": 0}
136
+ except Exception as exc:
137
+ return {"total_mb": 0, "used_mb": 0, "available_mb": 0, "percent": 0, "error": str(exc)}
138
+
139
+
140
+ def get_telemetry() -> Dict[str, Any]:
141
+ return {
142
+ "disk": get_disk_usage(),
143
+ "cpu": get_cpu_usage(),
144
+ "memory": get_memory_usage(),
145
+ "timestamp": datetime.now(timezone.utc).isoformat() + "Z",
146
+ }
147
+
148
+
149
+ # ============================================================================
150
+ # LOG TAIL
151
+ # ============================================================================
152
+
153
+ def tail_log(path: Path, max_bytes: int = 8192, max_lines: int = 80) -> List[str]:
154
+ if not path.exists():
155
+ return []
156
+ try:
157
+ size = path.stat().st_size
158
+ if size > max_bytes:
159
+ with path.open("rb") as f:
160
+ f.seek(-max_bytes, 2)
161
+ data = f.read().decode("utf-8", errors="ignore")
162
+ else:
163
+ data = path.read_text(encoding="utf-8", errors="ignore")
164
+ lines = data.splitlines()[-max_lines:]
165
+ return [line for line in lines if line.strip()]
166
+ except Exception as exc:
167
+ log.warning("tail_log failed: %s", exc)
168
+ return []
169
+
170
+
171
+ def classify_log_line(line: str) -> Dict[str, Any]:
172
+ """Color-code log lines based on level + tags."""
173
+ color = "#88c0d0" # default light blue
174
+ icon = "•"
175
+ if "[FATAL]" in line or "ERROR" in line or "Traceback" in line:
176
+ color = "#bf616a"
177
+ icon = "❌"
178
+ elif "WARNING" in line:
179
+ color = "#ebcb8b"
180
+ icon = "⚠️"
181
+ elif "[UPLOAD]" in line or "uploaded" in line.lower():
182
+ color = "#a3be8c"
183
+ icon = "📤"
184
+ elif "[OK]" in line or "✅" in line:
185
+ color = "#a3be8c"
186
+ icon = "✅"
187
+ elif "[RENDER" in line or "Rendering" in line:
188
+ color = "#b48ead"
189
+ icon = "🎬"
190
+ return {"text": line, "color": color, "icon": icon}
191
+
192
+
193
+ # ============================================================================
194
+ # VAULT
195
+ # ============================================================================
196
+
197
+ def list_vault() -> List[Dict[str, Any]]:
198
+ if not VAULT_DIR.exists():
199
+ return []
200
+ items: List[Dict[str, Any]] = []
201
+ for path in sorted(VAULT_DIR.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):
202
+ try:
203
+ if not path.is_file():
204
+ continue
205
+ stat = path.stat()
206
+ size_mb = round(stat.st_size / (1024 * 1024), 2)
207
+ mtime = datetime.fromtimestamp(stat.st_mtime)
208
+ ago = (datetime.now(timezone.utc) - mtime.replace(tzinfo=None)).total_seconds()
209
+ items.append({
210
+ "name": path.name,
211
+ "path": str(path),
212
+ "size_mb": size_mb,
213
+ "mtime": mtime.isoformat() + "Z",
214
+ "ago_seconds": int(ago),
215
+ "ago_human": _humanize_ago(ago),
216
+ })
217
+ if len(items) >= 20:
218
+ break
219
+ except Exception:
220
+ continue
221
+ return items
222
+
223
+
224
+ def _humanize_ago(seconds: float) -> str:
225
+ if seconds < 60:
226
+ return f"{int(seconds)}s ago"
227
+ if seconds < 3600:
228
+ return f"{int(seconds // 60)}m ago"
229
+ if seconds < 86400:
230
+ return f"{int(seconds // 3600)}h ago"
231
+ return f"{int(seconds // 86400)}d ago"
232
+
233
+
234
+ def list_run_report() -> Dict[str, Any]:
235
+ if not RUN_REPORT_FILE.exists():
236
+ return {"summary": {"success_count": 0, "failure_count": 0}, "results": [], "failures": []}
237
+ try:
238
+ return json.loads(RUN_REPORT_FILE.read_text(encoding="utf-8"))
239
+ except Exception:
240
+ return {"summary": {"success_count": 0, "failure_count": 0}, "results": [], "failures": []}
241
+
242
+
243
+ def get_last_run() -> Dict[str, Any]:
244
+ if not LAST_RUN_FILE.exists():
245
+ return {"results": [], "failures": [], "success_count": 0, "failure_count": 0}
246
+ try:
247
+ return json.loads(LAST_RUN_FILE.read_text(encoding="utf-8"))
248
+ except Exception:
249
+ return {"results": [], "failures": [], "success_count": 0, "failure_count": 0}
250
+
251
+
252
+ def read_live_status() -> Dict[str, Any]:
253
+ """v10.1: Read live status from main.py's writes."""
254
+ if not LIVE_STATUS_FILE.exists():
255
+ return {"stage": "IDLE", "message": "", "progress_pct": 0,
256
+ "current_topic": "", "current_kind": "", "next_run": "",
257
+ "pid": None, "timestamp": ""}
258
+ try:
259
+ return json.loads(LIVE_STATUS_FILE.read_text(encoding="utf-8"))
260
+ except Exception:
261
+ return {"stage": "IDLE", "message": "", "progress_pct": 0,
262
+ "current_topic": "", "current_kind": "", "next_run": "",
263
+ "pid": None, "timestamp": ""}
264
+
265
+
266
+ def read_schedule() -> Dict[str, Any]:
267
+ """v10.1: Read schedule from runner.py's writes."""
268
+ if not SCHEDULE_FILE.exists():
269
+ return {}
270
+ try:
271
+ return json.loads(SCHEDULE_FILE.read_text(encoding="utf-8"))
272
+ except Exception:
273
+ return {}
274
+
275
+
276
+ # ============================================================================
277
+ # COMMANDS
278
+ # ============================================================================
279
+
280
+ def trigger_kill_switch() -> bool:
281
+ try:
282
+ KILL_SWITCH_FILE.parent.mkdir(parents=True, exist_ok=True)
283
+ KILL_SWITCH_FILE.write_text("KILL\n", encoding="utf-8")
284
+ log.info("KILL_SWITCH activated")
285
+ return True
286
+ except Exception as exc:
287
+ log.error("Failed to activate KILL_SWITCH: %s", exc)
288
+ return False
289
+
290
+
291
+ def trigger_force_burst() -> bool:
292
+ try:
293
+ FORCE_BURST_FILE.parent.mkdir(parents=True, exist_ok=True)
294
+ FORCE_BURST_FILE.write_text("BURST\n", encoding="utf-8")
295
+ log.info("FORCE_BURST activated")
296
+ return True
297
+ except Exception as exc:
298
+ log.error("Failed to activate FORCE_BURST: %s", exc)
299
+ return False
300
+
301
+
302
+ def is_kill_active() -> bool:
303
+ return KILL_SWITCH_FILE.exists()
304
+
305
+
306
+ def is_burst_active() -> bool:
307
+ return FORCE_BURST_FILE.exists()
308
+
309
+
310
+ def clear_burst() -> bool:
311
+ try:
312
+ if FORCE_BURST_FILE.exists():
313
+ FORCE_BURST_FILE.unlink()
314
+ return True
315
+ except Exception:
316
+ return False
317
+
318
+
319
+ # ============================================================================
320
+ # HTML TEMPLATE (mobile-first, dark theme, gold accents)
321
+ # ============================================================================
322
+
323
+ HTML_TEMPLATE = r"""<!DOCTYPE html>
324
+ <html lang="en">
325
+ <head>
326
+ <meta charset="UTF-8">
327
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
328
+ <title>YT HISTRY · GOD-EYE</title>
329
+ <style>
330
+ * { box-sizing: border-box; margin: 0; padding: 0; }
331
+ :root {
332
+ --bg: #0a0c14;
333
+ --card: #11141f;
334
+ --card-2: #161a28;
335
+ --border: #1f2433;
336
+ --text: #e4e8f0;
337
+ --muted: #6c7488;
338
+ --accent: #d4af37;
339
+ --accent-2: #ffd700;
340
+ --success: #4ade80;
341
+ --warn: #fbbf24;
342
+ --danger: #f87171;
343
+ --info: #60a5fa;
344
+ }
345
+ body {
346
+ background: var(--bg);
347
+ color: var(--text);
348
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
349
+ min-height: 100vh;
350
+ font-size: 14px;
351
+ -webkit-font-smoothing: antialiased;
352
+ }
353
+ .header {
354
+ background: linear-gradient(135deg, #0a0c14 0%, #1a1426 100%);
355
+ padding: 16px 18px;
356
+ border-bottom: 2px solid var(--accent);
357
+ display: flex;
358
+ align-items: center;
359
+ justify-content: space-between;
360
+ position: sticky;
361
+ top: 0;
362
+ z-index: 100;
363
+ backdrop-filter: blur(10px);
364
+ }
365
+ .header h1 {
366
+ font-size: 16px;
367
+ font-weight: 800;
368
+ letter-spacing: 1px;
369
+ background: linear-gradient(90deg, var(--accent-2), var(--accent));
370
+ -webkit-background-clip: text;
371
+ -webkit-text-fill-color: transparent;
372
+ }
373
+ .header .ver { font-size: 10px; color: var(--muted); }
374
+ .status-dot {
375
+ width: 10px;
376
+ height: 10px;
377
+ border-radius: 50%;
378
+ background: var(--success);
379
+ animation: pulse 2s infinite;
380
+ }
381
+ @keyframes pulse {
382
+ 0%, 100% { opacity: 1; transform: scale(1); }
383
+ 50% { opacity: 0.6; transform: scale(1.15); }
384
+ }
385
+ .container { padding: 16px; max-width: 1200px; margin: 0 auto; }
386
+ .card {
387
+ background: var(--card);
388
+ border: 1px solid var(--border);
389
+ border-radius: 12px;
390
+ padding: 14px;
391
+ margin-bottom: 12px;
392
+ }
393
+ .card h2 {
394
+ font-size: 11px;
395
+ font-weight: 700;
396
+ text-transform: uppercase;
397
+ letter-spacing: 1.5px;
398
+ color: var(--accent);
399
+ margin-bottom: 10px;
400
+ display: flex;
401
+ align-items: center;
402
+ gap: 8px;
403
+ }
404
+ .telemetry-grid {
405
+ display: grid;
406
+ grid-template-columns: 1fr 1fr;
407
+ gap: 10px;
408
+ }
409
+ .tel {
410
+ background: var(--card-2);
411
+ border-radius: 8px;
412
+ padding: 10px 12px;
413
+ border: 1px solid var(--border);
414
+ }
415
+ .tel .label { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }
416
+ .tel .value { font-size: 18px; font-weight: 700; color: var(--text); margin-top: 2px; }
417
+ .tel .unit { font-size: 11px; color: var(--muted); font-weight: 400; }
418
+ .progress-bar {
419
+ width: 100%;
420
+ height: 6px;
421
+ background: var(--card-2);
422
+ border-radius: 3px;
423
+ overflow: hidden;
424
+ margin-top: 6px;
425
+ }
426
+ .progress-fill {
427
+ height: 100%;
428
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
429
+ border-radius: 3px;
430
+ transition: width 0.5s ease;
431
+ }
432
+ .stage-tracker {
433
+ display: flex;
434
+ align-items: center;
435
+ justify-content: space-between;
436
+ padding: 10px 4px;
437
+ overflow-x: auto;
438
+ }
439
+ .stage {
440
+ flex-shrink: 0;
441
+ text-align: center;
442
+ font-size: 10px;
443
+ color: var(--muted);
444
+ transition: all 0.3s;
445
+ }
446
+ .stage .dot {
447
+ width: 12px;
448
+ height: 12px;
449
+ border-radius: 50%;
450
+ background: var(--border);
451
+ margin: 0 auto 4px;
452
+ transition: all 0.3s;
453
+ }
454
+ .stage.active .dot {
455
+ background: var(--accent-2);
456
+ box-shadow: 0 0 10px var(--accent-2);
457
+ animation: pulse 1.5s infinite;
458
+ }
459
+ .stage.done .dot { background: var(--success); }
460
+ .stage-arrow { color: var(--muted); margin: 0 4px; font-size: 10px; }
461
+ .btn {
462
+ display: inline-flex;
463
+ align-items: center;
464
+ justify-content: center;
465
+ gap: 6px;
466
+ padding: 10px 14px;
467
+ border-radius: 8px;
468
+ font-size: 12px;
469
+ font-weight: 700;
470
+ text-transform: uppercase;
471
+ letter-spacing: 1px;
472
+ border: none;
473
+ cursor: pointer;
474
+ transition: all 0.2s;
475
+ flex: 1;
476
+ }
477
+ .btn-danger { background: var(--danger); color: #fff; }
478
+ .btn-danger:hover { background: #ef4444; transform: translateY(-1px); }
479
+ .btn-success { background: var(--success); color: #062012; }
480
+ .btn-success:hover { background: #22c55e; transform: translateY(-1px); }
481
+ .btn-warning { background: var(--warn); color: #422006; }
482
+ .btn-warning:hover { background: #f59e0b; transform: translateY(-1px); }
483
+ .btn-secondary { background: var(--card-2); color: var(--text); border: 1px solid var(--border); }
484
+ .btn-secondary:hover { background: var(--border); }
485
+ .btn-row { display: flex; gap: 8px; margin-top: 12px; }
486
+ .log-feed {
487
+ background: #06080d;
488
+ border: 1px solid var(--border);
489
+ border-radius: 8px;
490
+ padding: 10px;
491
+ max-height: 280px;
492
+ overflow-y: auto;
493
+ font-family: "SF Mono", "Monaco", "Courier New", monospace;
494
+ font-size: 11px;
495
+ line-height: 1.5;
496
+ scrollbar-width: thin;
497
+ }
498
+ .log-feed::-webkit-scrollbar { width: 6px; }
499
+ .log-feed::-webkit-scrollbar-track { background: transparent; }
500
+ .log-feed::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
501
+ .log-line { display: flex; gap: 6px; padding: 2px 0; }
502
+ .log-icon { flex-shrink: 0; }
503
+ .vault-grid {
504
+ display: grid;
505
+ grid-template-columns: 1fr;
506
+ gap: 8px;
507
+ max-height: 400px;
508
+ overflow-y: auto;
509
+ }
510
+ .vault-item {
511
+ background: var(--card-2);
512
+ border: 1px solid var(--border);
513
+ border-radius: 8px;
514
+ padding: 10px 12px;
515
+ display: flex;
516
+ align-items: center;
517
+ gap: 10px;
518
+ transition: all 0.2s;
519
+ }
520
+ .vault-item:hover { border-color: var(--accent); }
521
+ .vault-thumb {
522
+ width: 60px;
523
+ height: 40px;
524
+ background: var(--bg);
525
+ border-radius: 4px;
526
+ display: flex;
527
+ align-items: center;
528
+ justify-content: center;
529
+ font-size: 18px;
530
+ flex-shrink: 0;
531
+ background: linear-gradient(135deg, var(--card-2), var(--border));
532
+ }
533
+ .vault-info { flex: 1; min-width: 0; }
534
+ .vault-name { font-size: 12px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
535
+ .vault-meta { font-size: 10px; color: var(--muted); margin-top: 2px; }
536
+ .stat-row { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 8px; }
537
+ .stat {
538
+ background: var(--card-2);
539
+ border-radius: 8px;
540
+ padding: 10px;
541
+ text-align: center;
542
+ border: 1px solid var(--border);
543
+ }
544
+ .stat .num { font-size: 20px; font-weight: 800; color: var(--accent-2); }
545
+ .stat .lbl { font-size: 9px; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; }
546
+ .error-banner {
547
+ background: linear-gradient(90deg, rgba(248,113,113,0.15), rgba(248,113,113,0.05));
548
+ border: 1px solid var(--danger);
549
+ border-radius: 8px;
550
+ padding: 12px;
551
+ margin-bottom: 12px;
552
+ display: none;
553
+ }
554
+ .error-banner.active { display: block; }
555
+ .error-banner pre {
556
+ font-size: 10px;
557
+ color: #fca5a5;
558
+ white-space: pre-wrap;
559
+ word-break: break-word;
560
+ max-height: 100px;
561
+ overflow-y: auto;
562
+ font-family: "SF Mono", monospace;
563
+ margin-top: 6px;
564
+ }
565
+ .copy-btn {
566
+ background: var(--card-2);
567
+ color: var(--danger);
568
+ border: 1px solid var(--danger);
569
+ border-radius: 4px;
570
+ padding: 3px 8px;
571
+ font-size: 9px;
572
+ cursor: pointer;
573
+ text-transform: uppercase;
574
+ letter-spacing: 1px;
575
+ font-weight: 700;
576
+ }
577
+ .copy-btn:hover { background: var(--danger); color: #fff; }
578
+ .refresh-info { font-size: 10px; color: var(--muted); text-align: center; margin-top: 10px; }
579
+ @media (min-width: 600px) {
580
+ .telemetry-grid { grid-template-columns: 1fr 1fr 1fr; }
581
+ .vault-grid { grid-template-columns: 1fr 1fr; }
582
+ }
583
+ @media (min-width: 900px) {
584
+ .container { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
585
+ .container .full { grid-column: 1 / -1; }
586
+ }
587
+ </style>
588
+ </head>
589
+ <body>
590
+ <div class="header">
591
+ <div>
592
+ <h1>⬡ YT HISTRY · GOD-EYE</h1>
593
+ <div class="ver">APEX v9.0 · 100% Truthful Telemetry</div>
594
+ </div>
595
+ <div class="status-dot" id="statusDot"></div>
596
+ </div>
597
+
598
+ <div class="container">
599
+ <div class="error-banner" id="errorBanner">
600
+ <div style="display:flex; justify-content:space-between; align-items:center;">
601
+ <strong style="color:var(--danger);">❌ LAST ERROR</strong>
602
+ <button class="copy-btn" onclick="copyError()">COPY</button>
603
+ </div>
604
+ <pre id="errorText"></pre>
605
+ </div>
606
+
607
+ <div class="card">
608
+ <h2>📊 TELEMETRY</h2>
609
+ <div class="telemetry-grid">
610
+ <div class="tel">
611
+ <div class="label">DISK</div>
612
+ <div class="value"><span id="diskPercent">0</span><span class="unit">%</span></div>
613
+ <div class="progress-bar"><div class="progress-fill" id="diskBar" style="width:0%"></div></div>
614
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
615
+ <span id="diskUsed">0</span> / <span id="diskTotal">0</span> GB
616
+ </div>
617
+ </div>
618
+ <div class="tel">
619
+ <div class="label">CPU</div>
620
+ <div class="value"><span id="cpuPercent">0</span><span class="unit">%</span></div>
621
+ <div class="progress-bar"><div class="progress-fill" id="cpuBar" style="width:0%"></div></div>
622
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
623
+ Load: <span id="cpuLoad">0, 0, 0</span>
624
+ </div>
625
+ </div>
626
+ <div class="tel">
627
+ <div class="label">RAM</div>
628
+ <div class="value"><span id="memPercent">0</span><span class="unit">%</span></div>
629
+ <div class="progress-bar"><div class="progress-fill" id="memBar" style="width:0%"></div></div>
630
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;">
631
+ <span id="memUsed">0</span> / <span id="memTotal">0</span> MB
632
+ </div>
633
+ </div>
634
+ <div class="tel">
635
+ <div class="label">NEXT RUN</div>
636
+ <div class="value" id="nextRun" style="font-size:14px;">—</div>
637
+ <div style="font-size:10px; color:var(--muted); margin-top:4px;" id="nextRunCountdown">—</div>
638
+ </div>
639
+ </div>
640
+ </div>
641
+
642
+ <div class="card">
643
+ <h2>⚡ PIPELINE STAGE</h2>
644
+ <div class="stage-tracker" id="stageTracker">
645
+ <div class="stage active" data-stage="IDLE"><div class="dot"></div>IDLE</div>
646
+ <div class="stage-arrow">→</div>
647
+ <div class="stage" data-stage="TOPIC"><div class="dot"></div>TOPIC</div>
648
+ <div class="stage-arrow">→</div>
649
+ <div class="stage" data-stage="SCRIPT"><div class="dot"></div>SCRIPT</div>
650
+ <div class="stage-arrow">→</div>
651
+ <div class="stage" data-stage="TTS"><div class="dot"></div>TTS</div>
652
+ <div class="stage-arrow">→</div>
653
+ <div class="stage" data-stage="VISUAL"><div class="dot"></div>VISUAL</div>
654
+ <div class="stage-arrow">→</div>
655
+ <div class="stage" data-stage="RENDER"><div class="dot"></div>RENDER</div>
656
+ <div class="stage-arrow">→</div>
657
+ <div class="stage" data-stage="UPLOAD"><div class="dot"></div>UPLOAD</div>
658
+ <div class="stage-arrow">→</div>
659
+ <div class="stage" data-stage="DONE"><div class="dot"></div>DONE</div>
660
+ </div>
661
+ <div id="currentJob" style="margin-top:10px; padding:8px 10px; background:var(--card-2); border-radius:6px; font-size:11px; color:var(--text); display:none;">
662
+ <div style="color:var(--accent); font-weight:700; margin-bottom:4px;" id="jobTitle">—</div>
663
+ <div style="color:var(--muted); font-size:10px;" id="jobMessage">—</div>
664
+ </div>
665
+ <div id="progressBar" style="margin-top:10px; display:none;">
666
+ <div style="display:flex; justify-content:space-between; font-size:10px; color:var(--muted); margin-bottom:4px;">
667
+ <span>Progress</span><span id="progressPct">0%</span>
668
+ </div>
669
+ <div class="progress-bar" style="height:8px;"><div class="progress-fill" id="progressFill" style="width:0%;"></div></div>
670
+ </div>
671
+ <div class="stat-row" style="margin-top:14px;">
672
+ <div class="stat"><div class="num" id="statLongs">0</div><div class="lbl">Longs Today</div></div>
673
+ <div class="stat"><div class="num" id="statShorts">0</div><div class="lbl">Shorts Today</div></div>
674
+ <div class="stat"><div class="num" id="statFails">0</div><div class="lbl">Failures</div></div>
675
+ <div class="stat"><div class="num" id="statVault">0</div><div class="lbl">In Vault</div></div>
676
+ </div>
677
+ <div class="btn-row">
678
+ <button class="btn btn-success" id="forceBtn" onclick="forceBurst()">🚀 FORCE_BURST</button>
679
+ <button class="btn btn-danger" id="killBtn" onclick="killSwitch()">🛑 KILL_SWITCH</button>
680
+ </div>
681
+ </div>
682
+
683
+ <div class="card full">
684
+ <h2>🔮 NEURAL LINK · LIVE LOG</h2>
685
+ <div class="log-feed" id="logFeed"></div>
686
+ </div>
687
+
688
+ <div class="card full">
689
+ <h2>🏛️ THE VAULT</h2>
690
+ <div class="vault-grid" id="vaultGrid"></div>
691
+ </div>
692
+
693
+ <div class="refresh-info">
694
+ Auto-refresh every 2s · Last: <span id="lastRefresh">—</span>
695
+ </div>
696
+ </div>
697
+
698
+ <script>
699
+ async function fetchJson(url) {
700
+ try {
701
+ const res = await fetch(url);
702
+ return await res.json();
703
+ } catch (err) {
704
+ return null;
705
+ }
706
+ }
707
+
708
+ function classifyLogLine(line) {
709
+ let color = "#88c0d0", icon = "•";
710
+ if (line.includes("[FATAL]") || line.includes("ERROR") || line.includes("Traceback")) {
711
+ color = "#bf616a"; icon = "❌";
712
+ } else if (line.includes("WARNING")) {
713
+ color = "#ebcb8b"; icon = "⚠️";
714
+ } else if (line.includes("[UPLOAD]") || line.toLowerCase().includes("uploaded")) {
715
+ color = "#a3be8c"; icon = "📤";
716
+ } else if (line.includes("[OK]") || line.includes("✅")) {
717
+ color = "#a3be8c"; icon = "✅";
718
+ } else if (line.includes("[RENDER") || line.includes("Rendering")) {
719
+ color = "#b48ead"; icon = "🎬";
720
+ }
721
+ return {color, icon};
722
+ }
723
+
724
+ function humanizeAgo(seconds) {
725
+ if (seconds < 60) return seconds + "s ago";
726
+ if (seconds < 3600) return Math.floor(seconds/60) + "m ago";
727
+ if (seconds < 86400) return Math.floor(seconds/3600) + "h ago";
728
+ return Math.floor(seconds/86400) + "d ago";
729
+ }
730
+
731
+ function setStages(currentStage) {
732
+ const stages = ["IDLE","TOPIC","SCRIPT","TTS","VISUAL","RENDER","UPLOAD","DONE"];
733
+ const curIdx = stages.indexOf(currentStage);
734
+ document.querySelectorAll(".stage").forEach(el => {
735
+ el.classList.remove("active", "done");
736
+ const s = el.getAttribute("data-stage");
737
+ const idx = stages.indexOf(s);
738
+ if (idx < curIdx) el.classList.add("done");
739
+ else if (idx === curIdx) el.classList.add("active");
740
+ });
741
+ }
742
+
743
+ async function refresh() {
744
+ const telem = await fetchJson("/api/telemetry");
745
+ if (telem) {
746
+ document.getElementById("diskPercent").textContent = telem.disk.percent || 0;
747
+ document.getElementById("diskBar").style.width = (telem.disk.percent || 0) + "%";
748
+ document.getElementById("diskUsed").textContent = telem.disk.used_gb || 0;
749
+ document.getElementById("diskTotal").textContent = telem.disk.total_gb || 0;
750
+ document.getElementById("cpuPercent").textContent = telem.cpu.percent || 0;
751
+ document.getElementById("cpuBar").style.width = (telem.cpu.percent || 0) + "%";
752
+ document.getElementById("cpuLoad").textContent = (telem.cpu.load_avg || [0,0,0]).join(", ");
753
+ document.getElementById("memPercent").textContent = telem.memory.percent || 0;
754
+ document.getElementById("memBar").style.width = (telem.memory.percent || 0) + "%";
755
+ document.getElementById("memUsed").textContent = telem.memory.used_mb || 0;
756
+ document.getElementById("memTotal").textContent = telem.memory.total_mb || 0;
757
+ }
758
+
759
+ const status = await fetchJson("/api/status");
760
+ if (status) {
761
+ setStages(status.stage || "IDLE");
762
+ document.getElementById("statLongs").textContent = status.longs || 0;
763
+ document.getElementById("statShorts").textContent = status.shorts || 0;
764
+ document.getElementById("statFails").textContent = status.failures || 0;
765
+ document.getElementById("statVault").textContent = status.vault_count || 0;
766
+
767
+ // v10.1: Real next-run countdown
768
+ const nextRun = status.next_run || "—";
769
+ const countdown = status.next_run_seconds || 0;
770
+ let countdownText = "—";
771
+ if (countdown > 0) {
772
+ if (countdown < 60) {
773
+ countdownText = `${countdown}s`;
774
+ } else if (countdown < 3600) {
775
+ const m = Math.floor(countdown / 60);
776
+ const s = countdown % 60;
777
+ countdownText = `${m}m ${s}s`;
778
+ } else {
779
+ const h = Math.floor(countdown / 3600);
780
+ const m = Math.floor((countdown % 3600) / 60);
781
+ countdownText = `${h}h ${m}m`;
782
+ }
783
+ } else if (status.stage !== "IDLE") {
784
+ countdownText = "running...";
785
+ }
786
+ document.getElementById("nextRun").textContent = nextRun;
787
+ document.getElementById("nextRunCountdown").textContent = countdownText;
788
+
789
+ // v10.1: Show current job
790
+ const currentJob = document.getElementById("currentJob");
791
+ const progressBar = document.getElementById("progressBar");
792
+ if (status.stage === "RENDER" || status.stage === "JOB_DONE" ||
793
+ status.stage === "PLANNING" || status.stage === "ERROR") {
794
+ currentJob.style.display = "block";
795
+ const kind = (status.current_kind || "").toUpperCase();
796
+ const topic = status.current_topic || "";
797
+ document.getElementById("jobTitle").textContent =
798
+ `${kind}: ${topic || "processing..."}`;
799
+ document.getElementById("jobMessage").textContent = status.message || "";
800
+ if (status.progress_pct > 0) {
801
+ progressBar.style.display = "block";
802
+ document.getElementById("progressPct").textContent = status.progress_pct + "%";
803
+ document.getElementById("progressFill").style.width = status.progress_pct + "%";
804
+ } else {
805
+ progressBar.style.display = "none";
806
+ }
807
+ } else {
808
+ currentJob.style.display = "none";
809
+ progressBar.style.display = "none";
810
+ }
811
+
812
+ if (status.kill_active) {
813
+ document.getElementById("killBtn").innerHTML = "✅ KILLED";
814
+ document.getElementById("killBtn").classList.add("btn-secondary");
815
+ } else {
816
+ document.getElementById("killBtn").innerHTML = "🛑 KILL_SWITCH";
817
+ document.getElementById("killBtn").classList.remove("btn-secondary");
818
+ }
819
+ if (status.burst_active) {
820
+ document.getElementById("forceBtn").innerHTML = "⏳ BURSTING...";
821
+ document.getElementById("forceBtn").classList.add("btn-warning");
822
+ } else {
823
+ document.getElementById("forceBtn").innerHTML = "🚀 FORCE_BURST";
824
+ document.getElementById("forceBtn").classList.remove("btn-warning");
825
+ }
826
+ }
827
+
828
+ const logs = await fetchJson("/api/logs");
829
+ if (logs && logs.lines) {
830
+ const feed = document.getElementById("logFeed");
831
+ feed.innerHTML = logs.lines.map(line => {
832
+ const c = classifyLogLine(line);
833
+ return `<div class="log-line" style="color:${c.color}"><span class="log-icon">${c.icon}</span><span>${escapeHtml(line)}</span></div>`;
834
+ }).join("");
835
+ feed.scrollTop = feed.scrollHeight;
836
+ }
837
+
838
+ const err = await fetchJson("/api/errors");
839
+ if (err && err.last_error) {
840
+ document.getElementById("errorBanner").classList.add("active");
841
+ document.getElementById("errorText").textContent = err.last_error;
842
+ } else {
843
+ document.getElementById("errorBanner").classList.remove("active");
844
+ }
845
+
846
+ const vault = await fetchJson("/api/vault");
847
+ if (vault && vault.items) {
848
+ const grid = document.getElementById("vaultGrid");
849
+ if (vault.items.length === 0) {
850
+ 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>';
851
+ } else {
852
+ grid.innerHTML = vault.items.map(it => `
853
+ <div class="vault-item">
854
+ <div class="vault-thumb">🎬</div>
855
+ <div class="vault-info">
856
+ <div class="vault-name">${escapeHtml(it.name)}</div>
857
+ <div class="vault-meta">${it.size_mb} MB · ${it.ago_human}</div>
858
+ </div>
859
+ </div>
860
+ `).join("");
861
+ }
862
+ }
863
+
864
+ document.getElementById("lastRefresh").textContent = new Date().toLocaleTimeString();
865
+ }
866
+
867
+ function escapeHtml(text) {
868
+ return String(text).replace(/[&<>"']/g, m => ({
869
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"
870
+ }[m]));
871
+ }
872
+
873
+ async function forceBurst() {
874
+ await fetch("/api/force_burst", {method: "POST"});
875
+ refresh();
876
+ }
877
+
878
+ async function killSwitch() {
879
+ if (confirm("Activate KILL_SWITCH? This will stop the current run.")) {
880
+ await fetch("/api/kill", {method: "POST"});
881
+ refresh();
882
+ }
883
+ }
884
+
885
+ async function copyError() {
886
+ const text = document.getElementById("errorText").textContent;
887
+ try {
888
+ await navigator.clipboard.writeText(text);
889
+ alert("Error copied to clipboard");
890
+ } catch (err) {
891
+ alert("Copy failed: " + err);
892
+ }
893
+ }
894
+
895
+ refresh();
896
+ setInterval(refresh, 2000);
897
+ </script>
898
+ </body>
899
+ </html>"""
900
+
901
+
902
+ # ============================================================================
903
+ # FLASK APP
904
+ # ============================================================================
905
+
906
+ def create_app() -> "Flask":
907
+ if not FLASK_AVAILABLE:
908
+ raise RuntimeError("Flask not installed. Run: pip install flask")
909
+
910
+ app = Flask(__name__)
911
+
912
+ @app.route("/")
913
+ def index():
914
+ return render_template_string(HTML_TEMPLATE)
915
+
916
+ @app.route("/api/telemetry")
917
+ def api_telemetry():
918
+ return jsonify(get_telemetry())
919
+
920
+ @app.route("/api/logs")
921
+ def api_logs():
922
+ log_lines = tail_log(LOG_FILE, max_bytes=8192, max_lines=80)
923
+ error_lines = tail_log(ERROR_LOG_FILE, max_bytes=4096, max_lines=20)
924
+ # Combine, errors last (most recent at top of errors)
925
+ return jsonify({"lines": error_lines + log_lines[-60:]})
926
+
927
+ @app.route("/api/vault")
928
+ def api_vault():
929
+ return jsonify({"items": list_vault()})
930
+
931
+ @app.route("/api/errors")
932
+ def api_errors():
933
+ errs = tail_log(ERROR_LOG_FILE, max_bytes=8192, max_lines=50)
934
+ last_err = "\n".join(errs) if errs else ""
935
+ return jsonify({"last_error": last_err})
936
+
937
+ @app.route("/api/status")
938
+ def api_status():
939
+ report = list_run_report()
940
+ last_run = get_last_run()
941
+ vault = list_vault()
942
+ longs = sum(1 for r in report.get("results", []) if r.get("kind") == "long")
943
+ shorts = sum(1 for r in report.get("results", []) if r.get("kind") == "short")
944
+
945
+ # v10.1: Read live status from main.py
946
+ live_status = read_live_status()
947
+ # v10.1: Read schedule from runner.py
948
+ schedule = read_schedule()
949
+
950
+ # Determine stage: live_status takes priority, then log-based fallback
951
+ stage = live_status.get("stage", "IDLE")
952
+ if stage == "IDLE":
953
+ log_lines = tail_log(LOG_FILE, max_bytes=4096, max_lines=15)
954
+ joined = " ".join(log_lines).lower()
955
+ if "pipeline start" in joined or "rendering long" in joined or "rendering short" in joined:
956
+ if "uploading" in joined or "upload progress" in joined:
957
+ stage = "UPLOAD"
958
+ elif "rendering" in joined or "assembling" in joined:
959
+ stage = "RENDER"
960
+ elif "voice" in joined or "tts" in joined:
961
+ stage = "TTS"
962
+ elif "script" in joined:
963
+ stage = "SCRIPT"
964
+ elif "topic" in joined:
965
+ stage = "TOPIC"
966
+ else:
967
+ stage = "RENDER"
968
+
969
+ # last_run timestamp
970
+ last_run_ts = last_run.get("timestamp", "")
971
+ last_run_ago = "—"
972
+ if last_run_ts:
973
+ try:
974
+ dt = datetime.fromisoformat(last_run_ts.replace("Z", ""))
975
+ ago = (datetime.now(timezone.utc) - dt.replace(tzinfo=None)).total_seconds()
976
+ last_run_ago = humanize_ago(ago)
977
+ except Exception:
978
+ pass
979
+
980
+ # Last successful upload
981
+ last_upload_iso = ""
982
+ last_upload_url = ""
983
+ for r in last_run.get("results", []):
984
+ if r.get("uploaded"):
985
+ last_upload_iso = last_run.get("timestamp", "")
986
+ last_upload_url = r.get("url", "")
987
+ break
988
+
989
+ # Next run countdown
990
+ next_run_iso = schedule.get("next_run", live_status.get("next_run", ""))
991
+ next_run_display = "—"
992
+ next_run_seconds = 0
993
+ if next_run_iso:
994
+ try:
995
+ dt_next = datetime.fromisoformat(next_run_iso.replace("Z", ""))
996
+ now = datetime.now(timezone.utc)
997
+ delta = (dt_next - now).total_seconds()
998
+ next_run_seconds = max(0, int(delta))
999
+ if delta > 0:
1000
+ # Future: "in 5m 23s"
1001
+ if delta < 60:
1002
+ next_run_display = f"in {int(delta)}s"
1003
+ elif delta < 3600:
1004
+ m = int(delta // 60)
1005
+ s = int(delta % 60)
1006
+ next_run_display = f"in {m}m {s}s"
1007
+ else:
1008
+ h = int(delta // 3600)
1009
+ m = int((delta % 3600) // 60)
1010
+ next_run_display = f"in {h}h {m}m"
1011
+ elif delta > -60:
1012
+ next_run_display = "now"
1013
+ else:
1014
+ next_run_display = "now"
1015
+ except Exception:
1016
+ next_run_display = next_run_iso
1017
+
1018
+ return jsonify({
1019
+ "stage": stage,
1020
+ "message": live_status.get("message", ""),
1021
+ "current_topic": live_status.get("current_topic", ""),
1022
+ "current_kind": live_status.get("current_kind", ""),
1023
+ "progress_pct": live_status.get("progress_pct", 0),
1024
+ "longs": longs,
1025
+ "shorts": shorts,
1026
+ "failures": report["summary"].get("failure_count", 0),
1027
+ "vault_count": len(vault),
1028
+ "next_run": next_run_display,
1029
+ "next_run_iso": next_run_iso,
1030
+ "next_run_seconds": next_run_seconds,
1031
+ "last_run_ago": last_run_ago,
1032
+ "last_upload_iso": last_upload_iso,
1033
+ "last_upload_url": last_upload_url,
1034
+ "kill_active": is_kill_active(),
1035
+ "burst_active": is_burst_active(),
1036
+ "pid": live_status.get("pid"),
1037
+ })
1038
+
1039
+ @app.route("/api/kill", methods=["POST"])
1040
+ def api_kill():
1041
+ ok = trigger_kill_switch()
1042
+ return jsonify({"success": ok})
1043
+
1044
+ @app.route("/api/force_burst", methods=["POST"])
1045
+ def api_force_burst():
1046
+ ok = trigger_force_burst()
1047
+ return jsonify({"success": ok})
1048
+
1049
+ @app.route("/api/clear_burst", methods=["POST"])
1050
+ def api_clear_burst():
1051
+ ok = clear_burst()
1052
+ return jsonify({"success": ok})
1053
+
1054
+ @app.route("/api/report")
1055
+ def api_report():
1056
+ return jsonify(list_run_report())
1057
+
1058
+ @app.route("/health")
1059
+ def health():
1060
+ return jsonify({"status": "ok", "version": "9.0.0"})
1061
+
1062
+ return app
1063
+
1064
+
1065
+ def humanize_ago(seconds: float) -> str:
1066
+ if seconds < 60:
1067
+ return f"{int(seconds)}s ago"
1068
+ if seconds < 3600:
1069
+ return f"{int(seconds // 60)}m ago"
1070
+ if seconds < 86400:
1071
+ return f"{int(seconds // 3600)}h ago"
1072
+ return f"{int(seconds // 86400)}d ago"
1073
+
1074
+
1075
+ # ============================================================================
1076
+ # MAIN
1077
+ # ============================================================================
1078
+
1079
+ def main() -> int:
1080
+ log.info("GOD-EYE Dashboard starting on port %s", os.getenv("PORT", "7860"))
1081
+ app = create_app()
1082
+ port = int(os.getenv("PORT", "7860"))
1083
+ host = os.getenv("HOST", "0.0.0.0")
1084
+ app.run(host=host, port=port, debug=False, use_reloader=False, threaded=True)
1085
+ return 0
1086
+
1087
+
1088
+ if __name__ == "__main__":
1089
+ 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,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ v10.2: Pre-render queue cycle.
221
+ - At upload time: upload from queue OR render+upload
222
+ - After upload: IMMEDIATELY start rendering next video (background)
223
+ - Sleep until next upload time
224
+ - At next time: 1h random timer then upload
225
+
226
+ Args:
227
+ max_runs: stop after N runs (None = forever)
228
+ once: run pipeline once and exit
229
+ cleanup_interval_minutes: how often to run GC
230
+ """
231
+ log.info("=" * 70)
232
+ log.info("YT HISTRY APEX v10.2 - AUTONOMOUS RUNNER STARTED")
233
+ log.info("=" * 70)
234
+ log.info("Time: %s UTC", dt.datetime.now(timezone.utc).isoformat())
235
+ log.info("Once=%s, Max runs=%s, GC interval=%dmin",
236
+ once, max_runs, cleanup_interval_minutes)
237
+
238
+ # Signal handlers
239
+ signal.signal(signal.SIGINT, handle_signal)
240
+ signal.signal(signal.SIGTERM, handle_signal)
241
+
242
+ runs_completed = 0
243
+ last_cleanup = time.time()
244
+
245
+ while True:
246
+ try:
247
+ # 1. Check kill switch (always reset after run completes)
248
+ if is_kill_active():
249
+ log.warning("KILL_SWITCH active. Exiting.")
250
+ return 130
251
+
252
+ # 2. Check force burst (SKIPS random delay entirely)
253
+ force_burst = is_burst_active()
254
+
255
+ # 3. Plan jobs
256
+ if force_burst:
257
+ log.info("FORCE_BURST detected - SKIPPING random timer, running immediately.")
258
+ plan = {"longs": 1, "shorts": 2}
259
+ next_run = dt.datetime.now(timezone.utc)
260
+ else:
261
+ plan = plan_jobs()
262
+ next_run = compute_next_run()
263
+
264
+ # Persist health
265
+ write_health({
266
+ "next_run": next_run.isoformat() + "Z",
267
+ "plan": plan,
268
+ "force_burst": force_burst,
269
+ "last_update": dt.datetime.now(timezone.utc).isoformat() + "Z",
270
+ "runs_completed": runs_completed,
271
+ })
272
+
273
+ # 4. Sleep until next run (UNLESS FORCE_BURST)
274
+ now = dt.datetime.now(timezone.utc)
275
+ sleep_sec = (next_run - now).total_seconds()
276
+ if not force_burst and sleep_sec > 0:
277
+ log.info(
278
+ "Next run scheduled in %.0fs (%s UTC). Plan: %d long, %d short.",
279
+ sleep_sec, next_run.isoformat(),
280
+ plan["longs"], plan["shorts"],
281
+ )
282
+ # Sleep in small chunks so we can react to kill/burst quickly
283
+ chunk = 30
284
+ slept = 0
285
+ while slept < sleep_sec:
286
+ if is_kill_active():
287
+ log.warning("KILL_SWITCH during sleep. Exiting.")
288
+ return 130
289
+ if is_burst_active():
290
+ log.info("FORCE_BURST detected mid-sleep - SKIPPING REMAINING WAIT.")
291
+ break
292
+ time.sleep(min(chunk, sleep_sec - slept))
293
+ slept += chunk
294
+
295
+ # 5. Run pipeline (uploads + renders new ones)
296
+ args = []
297
+ if not force_burst:
298
+ if plan["longs"] > 0:
299
+ args.extend(["--long-count", str(plan["longs"])])
300
+ if plan["shorts"] > 0:
301
+ args.extend(["--short-count", str(plan["shorts"])])
302
+ else:
303
+ args.extend(["--force-burst"])
304
+ clear_burst()
305
+
306
+ log.info("Starting pipeline run #%d with args: %s",
307
+ runs_completed + 1, " ".join(args))
308
+ exit_code = run_main(args, timeout=7200)
309
+ runs_completed += 1
310
+ log.info("Run #%d completed with exit code %d", runs_completed, exit_code)
311
+
312
+ # 6. v10.2: PRE-RENDER NEXT VIDEO IN BACKGROUND
313
+ # After successful upload, immediately start rendering the next
314
+ # video (no limits, full compute). It saves to vault.
315
+ # The next scheduled upload will pick it up.
316
+ if exit_code == 0 and not force_burst:
317
+ log.info("Starting BACKGROUND pre-render of next video...")
318
+ try:
319
+ bg_args = ["--render-only", "--single"]
320
+ subprocess.Popen(
321
+ [sys.executable, "main.py", *bg_args],
322
+ cwd=str(ROOT),
323
+ stdout=open(LOG_DIR / "pre_render.log", "a"),
324
+ stderr=subprocess.STDOUT,
325
+ start_new_session=True,
326
+ )
327
+ log.info("Pre-render started in background.")
328
+ except Exception as exc:
329
+ log.warning("Failed to start pre-render: %s", exc)
330
+
331
+ # 7. Periodic cleanup
332
+ if time.time() - last_cleanup > cleanup_interval_minutes * 60:
333
+ cleanup_old(max_age_hours=48)
334
+ last_cleanup = time.time()
335
+
336
+ # 8. Stop conditions
337
+ if once:
338
+ log.info("--once mode: exiting.")
339
+ return exit_code
340
+ if max_runs is not None and runs_completed >= max_runs:
341
+ log.info("Max runs reached (%d). Exiting.", max_runs)
342
+ return exit_code
343
+
344
+ # Loop again
345
+ time.sleep(5) # brief pause between iterations
346
+
347
+ except KeyboardInterrupt:
348
+ log.warning("Interrupted. Exiting.")
349
+ return 130
350
+ except Exception as exc:
351
+ log.exception("Loop error: %s", exc)
352
+ time.sleep(60) # back off on error
353
+
354
+
355
+ def main() -> int:
356
+ parser = argparse.ArgumentParser(description="YT HISTRY Autonomous Runner")
357
+ parser.add_argument("--once", action="store_true",
358
+ help="Run pipeline once and exit.")
359
+ parser.add_argument("--max-runs", type=int, default=None,
360
+ help="Stop after N runs (default: forever).")
361
+ parser.add_argument("--cleanup-interval", type=int, default=360,
362
+ help="Garbage collection interval in minutes.")
363
+ parser.add_argument("--cleanup-only", action="store_true",
364
+ help="Run GC and exit.")
365
+ args = parser.parse_args()
366
+
367
+ if args.cleanup_only:
368
+ cleaned = cleanup_old(max_age_hours=48)
369
+ log.info("Cleanup complete: %d items removed.", cleaned)
370
+ return 0
371
+
372
+ return run_loop(
373
+ max_runs=args.max_runs,
374
+ once=args.once,
375
+ cleanup_interval_minutes=args.cleanup_interval,
376
+ )
377
+
378
+
379
+ if __name__ == "__main__":
380
+ raise SystemExit(main())
start.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # YT HISTRY APEX v10.2 - 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 v10.2 - BOOT SEQUENCE"
11
+ echo "============================================================"
12
+ echo " Time: $(date -u)"
13
+ echo " Port: ${PORT:-7860}"
14
+ echo " DRY_RUN env: ${DRY_RUN:-auto-detect}"
15
+ echo " Auto-detect: if YT secrets present, runs LIVE"
16
+ echo "============================================================"
17
+
18
+ # Ensure dirs exist
19
+ mkdir -p /app/state /app/artifacts /app/logs /app/vault /app/tmp_run
20
+
21
+ # Clean any stale kill/force flags from previous container
22
+ rm -f /app/state/KILL_SWITCH /app/state/FORCE_BURST
23
+
24
+ # Start the autonomous runner in background
25
+ echo "[1/2] Starting autonomous runner in background..."
26
+ nohup python3 runner.py >> /app/logs/runner_stdout.log 2>&1 &
27
+ RUNNER_PID=$!
28
+ echo " Runner PID: $RUNNER_PID"
29
+
30
+ # Give runner a moment to write its health file
31
+ sleep 3
32
+
33
+ # Start the GOD-EYE dashboard (foreground)
34
+ echo "[2/2] Starting GOD-EYE dashboard (port ${PORT:-7860})..."
35
+ echo " Open http://localhost:${PORT:-7860} in your browser."
36
+ echo "============================================================"
37
+ exec python3 app.py