factorstudios commited on
Commit
907f99d
Β·
verified Β·
1 Parent(s): d01b941

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +106 -25
server.py CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env python3
2
  import os
3
  import json
4
  import asyncio
@@ -6,6 +6,7 @@ import tempfile
6
  import subprocess
7
  import shutil
8
  import time
 
9
  from pathlib import Path
10
  from datetime import datetime
11
  from dotenv import load_dotenv
@@ -193,32 +194,102 @@ async def run_processing_loop():
193
 
194
  add_log("Starting repository scan...")
195
  files = list_repo_files(repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
196
- movies = sorted(list(set(f.split("/")[1] for f in files if f.startswith(HOOKS_FOLDER + "/") and f.endswith(".json"))))
197
 
198
- add_log(f"Found {len(movies)} movies to process")
199
- for movie in movies:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  processing_state["current_file"] = movie
201
  add_log(f"--- Processing Movie: {movie} ---")
202
- video_path = hf_hub_download(repo_id=HF_DATASET_REPO, filename=f"{movie}.mkv", repo_type="dataset", token=HF_TOKEN)
203
- movie_hooks = sorted([f for f in files if f.startswith(f"{HOOKS_FOLDER}/{movie}/") and f.endswith(".json")])
204
- add_log(f"Found {len(movie_hooks)} segments for {movie}")
 
 
 
 
 
 
 
 
 
 
205
  temp_dir = tempfile.mkdtemp()
206
- for hook_file in movie_hooks:
207
- await asyncio.sleep(0.1)
208
- hook_path = hf_hub_download(repo_id=HF_DATASET_REPO, filename=hook_file, repo_type="dataset", token=HF_TOKEN)
209
- with open(hook_path, 'r') as f:
210
- data = json.load(f)
211
- num, start, end = data.get("segment_number", 1), data.get("start_time", "00:00:00"), data.get("end_time", "00:00:10")
212
- out_name = f"segment-{num:02d}.mp4"
213
- out_path = os.path.join(temp_dir, out_name)
214
- add_log(f"Processing Segment {num} ({start} to {end})")
215
- success = await asyncio.to_thread(process_video_sync, video_path, out_path, start, end)
216
- if success:
217
- upload_file(path_or_fileobj=out_path, path_in_repo=f"{READY_VIDEOS_FOLDER}/{movie}/{out_name}", repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
218
- add_log(f"βœ“ Segment {num} uploaded successfully")
219
- else:
220
- add_log(f"βœ— Segment {num} failed")
221
- shutil.rmtree(temp_dir)
 
 
 
 
 
 
 
 
 
 
 
222
  processing_state["processed_files"].append(movie)
223
  processing_state["total_processed"] += 1
224
  add_log(f"Finished movie: {movie}")
@@ -232,8 +303,18 @@ async def run_processing_loop():
232
 
233
  @app.on_event("startup")
234
  async def startup_event():
235
- # Only kick off the main loop, which now handles the 5s delay and model loading
236
- asyncio.create_task(run_processing_loop())
 
 
 
 
 
 
 
 
 
 
237
 
238
  @app.get("/")
239
  @app.get("/status")
 
1
+
2
  import os
3
  import json
4
  import asyncio
 
6
  import subprocess
7
  import shutil
8
  import time
9
+ import threading
10
  from pathlib import Path
11
  from datetime import datetime
12
  from dotenv import load_dotenv
 
194
 
195
  add_log("Starting repository scan...")
196
  files = list_repo_files(repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
 
197
 
198
+ # Find all movies with hooks
199
+ add_log("Scanning hooks directory...")
200
+ all_hooks_movies = {}
201
+ for f in files:
202
+ if f.startswith(HOOKS_FOLDER + "/") and f.endswith(".json"):
203
+ parts = f.split("/")
204
+ if len(parts) >= 3:
205
+ movie_name = parts[1]
206
+ if movie_name not in all_hooks_movies:
207
+ all_hooks_movies[movie_name] = []
208
+ all_hooks_movies[movie_name].append(f)
209
+
210
+ add_log(f"Found {len(all_hooks_movies)} movies in hooks folder")
211
+
212
+ # Find all movies with ready videos
213
+ add_log("Scanning ready_videos directory...")
214
+ processed_videos = {}
215
+ for f in files:
216
+ if f.startswith(READY_VIDEOS_FOLDER + "/") and f.endswith(".mp4"):
217
+ parts = f.split("/")
218
+ if len(parts) >= 3:
219
+ movie_name = parts[1]
220
+ if movie_name not in processed_videos:
221
+ processed_videos[movie_name] = set()
222
+ processed_videos[movie_name].add(parts[2])
223
+
224
+ add_log(f"Found {len(processed_videos)} movies with ready videos")
225
+
226
+ # Find unprocessed movies
227
+ unprocessed_movies = []
228
+ for movie_name, hooks in all_hooks_movies.items():
229
+ if movie_name not in processed_videos:
230
+ # Movie has no ready videos at all
231
+ unprocessed_movies.append((movie_name, hooks, []))
232
+ add_log(f" ⊘ {movie_name} (no ready videos, process all {len(hooks)} segments)")
233
+ else:
234
+ # Check which segments are already processed
235
+ processed_segments = processed_videos[movie_name]
236
+ unprocessed_hooks = [h for h in hooks if not any(f"segment-{json.loads(open(h).read()).get('segment_number', 1):02d}.mp4" in s for s in processed_segments)]
237
+ if unprocessed_hooks:
238
+ unprocessed_movies.append((movie_name, unprocessed_hooks, list(processed_segments)))
239
+ add_log(f" ⊘ {movie_name} (already has {len(processed_segments)} videos, {len(unprocessed_hooks)} segments remaining)")
240
+ else:
241
+ add_log(f" βœ“ {movie_name} (already complete with {len(processed_segments)} videos)")
242
+
243
+ add_log(f"\nTotal unprocessed movies to process: {len(unprocessed_movies)}\n")
244
+
245
+ if not unprocessed_movies:
246
+ add_log("All movies already processed!")
247
+ return
248
+
249
+ for movie, movie_hooks, existing_videos in unprocessed_movies:
250
  processing_state["current_file"] = movie
251
  add_log(f"--- Processing Movie: {movie} ---")
252
+
253
+ try:
254
+ video_path = hf_hub_download(repo_id=HF_DATASET_REPO, filename=f"{READY_VIDEOS_FOLDER}/{movie}.mkv", repo_type="dataset", token=HF_TOKEN)
255
+ except:
256
+ try:
257
+ # Try alternative path
258
+ video_path = hf_hub_download(repo_id=HF_DATASET_REPO, filename=f"{movie}.mkv", repo_type="dataset", token=HF_TOKEN)
259
+ except Exception as e:
260
+ add_log(f"βœ— Could not find video file for {movie}: {e}")
261
+ processing_state["error_count"] += 1
262
+ continue
263
+
264
+ add_log(f"Found {len(movie_hooks)} unprocessed segments for {movie}")
265
  temp_dir = tempfile.mkdtemp()
266
+
267
+ try:
268
+ for hook_file in movie_hooks:
269
+ await asyncio.sleep(0.1)
270
+ hook_path = hf_hub_download(repo_id=HF_DATASET_REPO, filename=hook_file, repo_type="dataset", token=HF_TOKEN)
271
+ with open(hook_path, 'r') as f:
272
+ data = json.load(f)
273
+ num, start, end = data.get("segment_number", 1), data.get("start_time", "00:00:00"), data.get("end_time", "00:00:10")
274
+ out_name = f"segment-{num:02d}.mp4"
275
+
276
+ # Skip if already exists
277
+ if out_name in existing_videos:
278
+ add_log(f" ⊘ Segment {num} (already processed)")
279
+ continue
280
+
281
+ out_path = os.path.join(temp_dir, out_name)
282
+ add_log(f"Processing Segment {num} ({start} to {end})")
283
+ success = await asyncio.to_thread(process_video_sync, video_path, out_path, start, end)
284
+ if success:
285
+ upload_file(path_or_fileobj=out_path, path_in_repo=f"{READY_VIDEOS_FOLDER}/{movie}/{out_name}", repo_id=HF_DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
286
+ add_log(f"βœ“ Segment {num} uploaded successfully")
287
+ else:
288
+ add_log(f"βœ— Segment {num} failed")
289
+ processing_state["error_count"] += 1
290
+ finally:
291
+ shutil.rmtree(temp_dir, ignore_errors=True)
292
+
293
  processing_state["processed_files"].append(movie)
294
  processing_state["total_processed"] += 1
295
  add_log(f"Finished movie: {movie}")
 
303
 
304
  @app.on_event("startup")
305
  async def startup_event():
306
+ """Schedule video processing loop on server startup with background thread."""
307
+ add_log("\n" + "="*80)
308
+ add_log("STARTUP EVENT TRIGGERED - Video Segment Processing Service")
309
+ add_log("="*80)
310
+
311
+ # Schedule processing in a background thread (more reliable for deployment)
312
+ def run_loop():
313
+ asyncio.run(run_processing_loop())
314
+
315
+ process_thread = threading.Thread(target=run_loop, daemon=True)
316
+ process_thread.start()
317
+ add_log("βœ“ Background processing thread scheduled")
318
 
319
  @app.get("/")
320
  @app.get("/status")