-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudio_server.py
More file actions
829 lines (685 loc) · 29.9 KB
/
studio_server.py
File metadata and controls
829 lines (685 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
"""
Avatar Studio Backend Server
=============================
Flask server that:
- Serves the Avatar Studio HTML + static assets
- Accepts video uploads and YouTube URL downloads
- Runs the SAM 3D Body processing pipeline in background
- Reports processing progress via polling
- Serves output web data (manifest.json, .bin mesh files)
Usage:
python studio_server.py
python studio_server.py --port 8899
python studio_server.py --host 0.0.0.0 --port 8080
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
from flask import Flask, request, jsonify, send_from_directory, abort
# ── Project root ──────────────────────────────────────────────────────────────
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_DIR = os.path.join(PROJECT_ROOT, "uploads")
os.makedirs(UPLOAD_DIR, exist_ok=True)
app = Flask(__name__, static_folder=None)
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024 * 1024 # 2 GB max upload
# ── Job State ─────────────────────────────────────────────────────────────────
jobs = {} # job_id -> dict
jobs_lock = threading.Lock()
ALLOWED_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".webm", ".flv", ".wmv"}
def get_job(job_id):
with jobs_lock:
return jobs.get(job_id)
def update_job(job_id, **kwargs):
with jobs_lock:
if job_id in jobs:
jobs[job_id].update(kwargs)
def save_jobs_index():
"""Persist a lightweight index of jobs to disk so they survive restarts."""
index_path = os.path.join(UPLOAD_DIR, "jobs_index.json")
with jobs_lock:
index = {}
for jid, jdata in jobs.items():
index[jid] = {
"status": jdata.get("status"),
"video_name": jdata.get("video_name"),
"created_at": jdata.get("created_at"),
"completed_at": jdata.get("completed_at"),
"video_path": jdata.get("video_path"),
"output_dir": jdata.get("output_dir"),
"web_dir": jdata.get("web_dir"),
"error": jdata.get("error"),
"progress": jdata.get("progress"),
"progress_message": jdata.get("progress_message"),
}
try:
with open(index_path, "w") as f:
json.dump(index, f, indent=2)
except Exception:
pass
def load_jobs_index():
"""Load persisted job index on startup."""
index_path = os.path.join(UPLOAD_DIR, "jobs_index.json")
if not os.path.exists(index_path):
return
try:
with open(index_path) as f:
index = json.load(f)
with jobs_lock:
for jid, jdata in index.items():
if jid not in jobs:
jobs[jid] = jdata
except Exception:
pass
# ── Static file serving ──────────────────────────────────────────────────────
@app.route("/")
def index():
return send_from_directory(PROJECT_ROOT, "avatar_studio.html")
@app.route("/<path:filepath>")
def static_files(filepath):
"""Serve any file from the project root (HTML, JS, CSS, video, web data)."""
full = os.path.normpath(os.path.join(PROJECT_ROOT, filepath))
# Security: don't serve outside project root
if not full.startswith(os.path.normpath(PROJECT_ROOT)):
abort(403)
if os.path.isfile(full):
directory = os.path.dirname(full)
filename = os.path.basename(full)
return send_from_directory(directory, filename)
abort(404)
# ── API: Upload ──────────────────────────────────────────────────────────────
@app.route("/api/upload", methods=["POST"])
def upload_video():
"""Upload a video file and create a processing job."""
if "video" not in request.files:
return jsonify({"error": "No 'video' file in request"}), 400
file = request.files["video"]
if not file.filename:
return jsonify({"error": "Empty filename"}), 400
ext = os.path.splitext(file.filename)[1].lower()
if ext not in ALLOWED_EXTENSIONS:
return jsonify({"error": f"Unsupported format: {ext}. Use: {', '.join(ALLOWED_EXTENSIONS)}"}), 400
# Create job
job_id = uuid.uuid4().hex[:12]
job_dir = os.path.join(UPLOAD_DIR, job_id)
os.makedirs(job_dir, exist_ok=True)
# Save video with original extension
safe_name = f"video{ext}"
video_path = os.path.join(job_dir, safe_name)
file.save(video_path)
file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
# Get video metadata
video_info = get_video_info(video_path)
with jobs_lock:
jobs[job_id] = {
"status": "uploaded",
"video_name": file.filename,
"video_path": video_path,
"job_dir": job_dir,
"output_dir": os.path.join(job_dir, "output"),
"frames_dir": os.path.join(job_dir, "frames"),
"web_dir": os.path.join(job_dir, "output", "web"),
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
"completed_at": None,
"file_size_mb": round(file_size_mb, 1),
"video_info": video_info,
"progress": 0,
"progress_message": "Video uploaded",
"error": None,
"log": [],
}
save_jobs_index()
return jsonify({
"job_id": job_id,
"video_name": file.filename,
"file_size_mb": round(file_size_mb, 1),
"video_info": video_info,
"status": "uploaded",
})
def get_video_info(video_path):
"""Get video metadata using OpenCV."""
try:
import cv2
cap = cv2.VideoCapture(video_path)
info = {
"width": int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
"height": int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
"fps": round(cap.get(cv2.CAP_PROP_FPS), 2),
"total_frames": int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
"duration_s": round(
int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / max(cap.get(cv2.CAP_PROP_FPS), 1), 1
),
}
cap.release()
return info
except Exception as e:
return {"error": str(e)}
# ── YouTube helpers ──────────────────────────────────────────────────────────
def _get_ffmpeg_path():
"""Find ffmpeg binary – check PATH first, then imageio_ffmpeg bundle."""
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, timeout=5, check=True)
return "ffmpeg" # on PATH
except Exception:
pass
try:
import imageio_ffmpeg
p = imageio_ffmpeg.get_ffmpeg_exe()
if os.path.isfile(p):
return p
except Exception:
pass
return None
def _yt_dlp_cmd():
"""Return the yt-dlp command prefix. Tries standalone first, falls back to python -m."""
try:
subprocess.run(["yt-dlp", "--version"], capture_output=True, timeout=10, check=True)
return ["yt-dlp"]
except Exception:
pass
try:
subprocess.run([sys.executable, "-m", "yt_dlp", "--version"],
capture_output=True, timeout=10, check=True)
return [sys.executable, "-m", "yt_dlp"]
except Exception:
return None
def _get_cookie_args():
"""Find cookie strategy for YouTube auth (mirrors download_karate_video.py)."""
base = _yt_dlp_cmd()
if not base:
return []
cookies_file = os.path.join(PROJECT_ROOT, "cookies.txt")
if os.path.exists(cookies_file):
return ["--cookies", cookies_file]
for browser in ["edge", "chrome", "firefox", "opera", "brave"]:
try:
result = subprocess.run(
base + ["--cookies-from-browser", browser, "--no-download",
"--print", "%(title)s", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
capture_output=True, text=True, timeout=25
)
if result.returncode == 0 and result.stdout.strip():
return ["--cookies-from-browser", browser]
except Exception:
continue
return []
def _yt_dlp_available():
return _yt_dlp_cmd() is not None
def _get_yt_info(url, cookie_args):
"""Fetch video metadata from YouTube URL."""
base = _yt_dlp_cmd()
if not base:
return None
cmd = base + cookie_args + ["--no-download", "--dump-json", "--no-playlist", url]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode != 0:
return None
return json.loads(result.stdout)
# ── API: YouTube Download ────────────────────────────────────────────────────
@app.route("/api/youtube-info", methods=["POST"])
def youtube_info():
"""Fetch metadata for a YouTube URL without downloading."""
data = request.get_json(silent=True) or {}
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
if not _yt_dlp_available():
return jsonify({"error": "yt-dlp is not installed. Run: pip install yt-dlp"}), 500
cookie_args = _get_cookie_args()
info = _get_yt_info(url, cookie_args)
if not info:
return jsonify({"error": "Could not fetch video info. Check the URL or cookies."}), 400
return jsonify({
"title": info.get("title", "Unknown"),
"duration": info.get("duration", 0),
"duration_string": info.get("duration_string", ""),
"channel": info.get("uploader", ""),
"thumbnail": info.get("thumbnail", ""),
"width": info.get("width", 0),
"height": info.get("height", 0),
"view_count": info.get("view_count", 0),
})
@app.route("/api/youtube-download", methods=["POST"])
def youtube_download():
"""Start downloading a YouTube video and create a job."""
data = request.get_json(silent=True) or {}
url = data.get("url", "").strip()
if not url:
return jsonify({"error": "No URL provided"}), 400
if not _yt_dlp_available():
return jsonify({"error": "yt-dlp is not installed. Run: pip install yt-dlp"}), 500
# Create job
job_id = uuid.uuid4().hex[:12]
job_dir = os.path.join(UPLOAD_DIR, job_id)
os.makedirs(job_dir, exist_ok=True)
video_path = os.path.join(job_dir, "video.mp4")
with jobs_lock:
jobs[job_id] = {
"status": "downloading",
"source": "youtube",
"youtube_url": url,
"video_name": "YouTube video",
"video_path": video_path,
"job_dir": job_dir,
"output_dir": os.path.join(job_dir, "output"),
"frames_dir": os.path.join(job_dir, "frames"),
"web_dir": os.path.join(job_dir, "output", "web"),
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
"completed_at": None,
"file_size_mb": 0,
"video_info": None,
"progress": 0,
"progress_message": "Starting YouTube download...",
"error": None,
"log": [],
}
save_jobs_index()
# Start download in background thread
auto_process = data.get("auto_process", True)
frame_skip = data.get("frame_skip", 6)
inference_type = data.get("inference_type", "full")
thread = threading.Thread(
target=_run_youtube_download,
args=(job_id, url, video_path, auto_process, frame_skip, inference_type),
daemon=True,
)
thread.start()
return jsonify({"job_id": job_id, "status": "downloading"})
def _run_youtube_download(job_id, url, video_path, auto_process, frame_skip, inference_type):
"""Background thread: download YouTube video via yt-dlp, then optionally process."""
try:
cookie_args = _get_cookie_args()
# Fetch video info first
info = _get_yt_info(url, cookie_args)
if info:
title = info.get("title", "YouTube video")
safe_title = re.sub(r'[^\w\s\-]', '', title)[:60].strip()
update_job(job_id, video_name=safe_title)
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(f"Title: {title}")
jobs[job_id]["log"].append(f"Duration: {info.get('duration_string', '?')}")
jobs[job_id]["log"].append(f"Channel: {info.get('uploader', '?')}")
update_job(job_id, progress=5, progress_message="Downloading video from YouTube...")
save_jobs_index()
# Download with yt-dlp
base = _yt_dlp_cmd()
ffmpeg_path = _get_ffmpeg_path()
# Prefer pre-merged single stream (no ffmpeg needed) then fall back to
# separate streams + merge (requires ffmpeg).
fmt = (
"best[height<=1080][ext=mp4]"
"/bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]"
"/best[ext=mp4]/best"
)
extra_args = []
if ffmpeg_path:
extra_args += ["--ffmpeg-location", ffmpeg_path]
cmd = (
base
+ cookie_args
+ extra_args
+ [
"-f", fmt,
"--merge-output-format", "mp4",
"--output", video_path,
"--no-playlist",
"--progress",
"--newline",
url,
]
)
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, cwd=PROJECT_ROOT, bufsize=1,
)
for line in iter(process.stdout.readline, ""):
line = line.rstrip()
if not line:
continue
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(line)
if len(jobs[job_id]["log"]) > 500:
jobs[job_id]["log"] = jobs[job_id]["log"][-300:]
# Parse yt-dlp download progress like "[download] 45.2% of ~50.00MiB"
m = re.search(r'\[download\]\s+([\d.]+)%', line)
if m:
dl_pct = float(m.group(1))
scaled = 5 + int(dl_pct * 0.4) # 5-45 range
update_job(job_id, progress=scaled,
progress_message=f"Downloading... {dl_pct:.0f}%")
elif "[download] 100%" in line or "has already been downloaded" in line:
update_job(job_id, progress=45, progress_message="Download complete")
elif "Merging" in line:
update_job(job_id, progress=47, progress_message="Merging audio/video...")
process.wait()
if process.returncode != 0:
# Try fallback format
update_job(job_id, progress=10, progress_message="Trying fallback format...")
cmd_fb = (
base + cookie_args
+ ["-f", "best", "--merge-output-format", "mp4",
"--output", video_path, "--progress", "--newline", "--no-playlist", url]
)
fb_proc = subprocess.run(cmd_fb, capture_output=True, text=True, timeout=600, cwd=PROJECT_ROOT)
if fb_proc.returncode != 0 or not os.path.exists(video_path):
update_job(job_id, status="error", error="YouTube download failed. Check cookies or URL.",
progress=0, progress_message="Download failed")
save_jobs_index()
return
# yt-dlp may produce a slightly different filename; scan for it
if not os.path.exists(video_path):
job_dir = os.path.dirname(video_path)
candidates = [
f for f in os.listdir(job_dir)
if f.endswith((".mp4", ".mkv", ".webm"))
and not re.search(r'\.f\d+\.', f) # skip partial stream files
]
if candidates:
actual = os.path.join(job_dir, candidates[0])
os.rename(actual, video_path)
else:
# Last resort: use the largest media file present
all_media = [
f for f in os.listdir(job_dir)
if f.endswith((".mp4", ".m4a", ".mkv", ".webm", ".mp4.part"))
]
if all_media:
largest = max(all_media, key=lambda f: os.path.getsize(os.path.join(job_dir, f)))
os.rename(os.path.join(job_dir, largest), video_path)
else:
update_job(job_id, status="error", error="Download produced no file",
progress=0, progress_message="Download failed")
save_jobs_index()
return
# Update with file info
file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
video_info = get_video_info(video_path)
update_job(job_id, status="uploaded", file_size_mb=round(file_size_mb, 1),
video_info=video_info, progress=50,
progress_message=f"Downloaded ({file_size_mb:.0f} MB). Ready to process.")
save_jobs_index()
print(f"[OK] YouTube download complete for job {job_id}: {file_size_mb:.1f} MB")
# Auto-process if requested
if auto_process:
update_job(job_id, status="processing", progress=50,
progress_message="Starting 3D processing pipeline...")
save_jobs_index()
run_pipeline(job_id, frame_skip, inference_type, 0.5)
except Exception as e:
import traceback
tb = traceback.format_exc()
update_job(job_id, status="error", error=str(e), progress=0,
progress_message=f"Error: {str(e)[:100]}")
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(f"EXCEPTION: {tb}")
save_jobs_index()
print(f"[!] YouTube download error for job {job_id}: {e}")
# ── API: Process ─────────────────────────────────────────────────────────────
@app.route("/api/process/<job_id>", methods=["POST"])
def start_processing(job_id):
"""Start the SAM 3D Body processing pipeline for a given job."""
job = get_job(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
if job["status"] in ("processing", "exporting"):
return jsonify({"error": "Job is already processing"}), 409
# Parse optional processing params from request body
params = request.get_json(silent=True) or {}
frame_skip = params.get("frame_skip", 6)
inference_type = params.get("inference_type", "full")
bbox_thresh = params.get("bbox_thresh", 0.5)
update_job(job_id, status="processing", progress=0, progress_message="Starting pipeline...", error=None)
save_jobs_index()
# Run in background thread
thread = threading.Thread(
target=run_pipeline,
args=(job_id, frame_skip, inference_type, bbox_thresh),
daemon=True,
)
thread.start()
return jsonify({"status": "processing", "job_id": job_id})
def run_pipeline(job_id, frame_skip, inference_type, bbox_thresh):
"""Background pipeline: extract frames → SAM 3D Body → export web data."""
job = get_job(job_id)
if not job:
return
video_path = job["video_path"]
job_dir = job["job_dir"]
output_dir = job["output_dir"]
frames_dir = job["frames_dir"]
web_dir = job["web_dir"]
try:
# ── STEP 1: Process video with process_karate_video.py ────────────
update_job(job_id, progress=5, progress_message="Step 1/3: Starting SAM 3D Body pipeline...")
save_jobs_index()
cmd = [
sys.executable, os.path.join(PROJECT_ROOT, "process_karate_video.py"),
"--video_path", video_path,
"--output_dir", output_dir,
"--frames_dir", frames_dir,
"--frame_skip", str(frame_skip),
"--inference_type", inference_type,
"--bbox_thresh", str(bbox_thresh),
"--skip_compile",
]
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
cwd=PROJECT_ROOT,
bufsize=1,
)
# Monitor stdout for progress
for line in iter(process.stdout.readline, ""):
line = line.rstrip()
if not line:
continue
# Parse progress from tqdm-style output
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(line)
# Keep log bounded
if len(jobs[job_id]["log"]) > 500:
jobs[job_id]["log"] = jobs[job_id]["log"][-300:]
# Try to detect progress from output
if "STEP 1" in line or "Extracting" in line:
update_job(job_id, progress=10, progress_message="Extracting video frames...")
elif "STEP 2" in line or "Loading SAM" in line:
update_job(job_id, progress=20, progress_message="Loading SAM 3D Body model...")
elif "STEP 3" in line or "Running 3D" in line:
update_job(job_id, progress=30, progress_message="Running 3D mesh inference...")
elif "%" in line and "frame" in line.lower():
# Try to parse tqdm percentage
try:
pct_str = line.split("%")[0].strip().split()[-1]
pct = int(pct_str)
# Scale to 30-80 range
scaled = 30 + int(pct * 0.5)
update_job(job_id, progress=scaled,
progress_message=f"Processing frames... {pct}%")
except (ValueError, IndexError):
pass
elif "All frames processed" in line:
update_job(job_id, progress=80, progress_message="Frame processing complete")
process.wait()
if process.returncode != 0:
update_job(job_id, status="error", error="Processing pipeline failed (see logs)",
progress=0, progress_message="Pipeline error")
save_jobs_index()
return
# ── STEP 2: Export web data ───────────────────────────────────────
update_job(job_id, status="exporting", progress=85,
progress_message="Step 2/3: Exporting web data...")
save_jobs_index()
export_cmd = [
sys.executable, os.path.join(PROJECT_ROOT, "export_web_data.py"),
"--mesh_dir", os.path.join(output_dir, "mesh_data"),
"--video_path", video_path,
"--output_dir", web_dir,
]
export_proc = subprocess.Popen(
export_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
cwd=PROJECT_ROOT,
)
for line in iter(export_proc.stdout.readline, ""):
line = line.rstrip()
if line:
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(line)
export_proc.wait()
if export_proc.returncode != 0:
update_job(job_id, status="error", error="Web export failed (see logs)",
progress=0, progress_message="Export error")
save_jobs_index()
return
# ── STEP 3: Copy video to web dir for playback ────────────────────
update_job(job_id, progress=95, progress_message="Step 3/3: Finalizing...")
video_copy_path = os.path.join(web_dir, "source_video.mp4")
try:
shutil.copy2(video_path, video_copy_path)
except Exception:
pass
# ── Done ──────────────────────────────────────────────────────────
update_job(
job_id,
status="complete",
progress=100,
progress_message="Processing complete!",
completed_at=time.strftime("%Y-%m-%d %H:%M:%S"),
)
save_jobs_index()
print(f"[OK] Job {job_id} complete")
except Exception as e:
import traceback
tb = traceback.format_exc()
update_job(job_id, status="error", error=str(e), progress=0,
progress_message=f"Error: {str(e)[:100]}")
with jobs_lock:
if job_id in jobs:
jobs[job_id]["log"].append(f"EXCEPTION: {tb}")
save_jobs_index()
print(f"[!] Job {job_id} error: {e}")
# ── API: Status ──────────────────────────────────────────────────────────────
@app.route("/api/status/<job_id>")
def job_status(job_id):
"""Get current status of a processing job."""
job = get_job(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
return jsonify({
"job_id": job_id,
"status": job.get("status"),
"progress": job.get("progress", 0),
"progress_message": job.get("progress_message", ""),
"error": job.get("error"),
"video_name": job.get("video_name"),
"video_info": job.get("video_info"),
"created_at": job.get("created_at"),
"completed_at": job.get("completed_at"),
})
@app.route("/api/logs/<job_id>")
def job_logs(job_id):
"""Get processing logs for a job (last N lines)."""
job = get_job(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
n = request.args.get("n", 50, type=int)
log = job.get("log", [])
return jsonify({"log": log[-n:]})
# ── API: List Jobs ───────────────────────────────────────────────────────────
@app.route("/api/jobs")
def list_jobs():
"""List all jobs."""
with jobs_lock:
result = []
for jid, jdata in jobs.items():
result.append({
"job_id": jid,
"status": jdata.get("status"),
"video_name": jdata.get("video_name"),
"created_at": jdata.get("created_at"),
"completed_at": jdata.get("completed_at"),
"progress": jdata.get("progress", 0),
"progress_message": jdata.get("progress_message", ""),
})
# Sort newest first
result.sort(key=lambda x: x.get("created_at", ""), reverse=True)
return jsonify(result)
# ── API: Serve job web data ──────────────────────────────────────────────────
@app.route("/api/jobs/<job_id>/web/<path:filepath>")
def serve_job_web(job_id, filepath):
"""Serve processed web data (manifest.json, .bin files, video) for a job."""
job = get_job(job_id)
if not job:
abort(404)
web_dir = job.get("web_dir")
if not web_dir or not os.path.isdir(web_dir):
abort(404)
full = os.path.normpath(os.path.join(web_dir, filepath))
if not full.startswith(os.path.normpath(web_dir)):
abort(403)
if os.path.isfile(full):
return send_from_directory(os.path.dirname(full), os.path.basename(full))
abort(404)
@app.route("/api/jobs/<job_id>/video")
def serve_job_video(job_id):
"""Serve the uploaded video for a job."""
job = get_job(job_id)
if not job:
abort(404)
video_path = job.get("video_path")
if not video_path or not os.path.isfile(video_path):
abort(404)
return send_from_directory(
os.path.dirname(video_path),
os.path.basename(video_path),
)
# ── API: Delete Job ──────────────────────────────────────────────────────────
@app.route("/api/jobs/<job_id>", methods=["DELETE"])
def delete_job(job_id):
"""Delete a job and its files."""
job = get_job(job_id)
if not job:
return jsonify({"error": "Job not found"}), 404
if job.get("status") == "processing":
return jsonify({"error": "Cannot delete a job that is currently processing"}), 409
job_dir = job.get("job_dir")
if job_dir and os.path.isdir(job_dir):
shutil.rmtree(job_dir, ignore_errors=True)
with jobs_lock:
jobs.pop(job_id, None)
save_jobs_index()
return jsonify({"deleted": job_id})
# ── Main ─────────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Avatar Studio Backend Server")
parser.add_argument("--host", default="127.0.0.1", help="Host (default: 127.0.0.1)")
parser.add_argument("--port", default=8899, type=int, help="Port (default: 8899)")
parser.add_argument("--debug", action="store_true", help="Enable Flask debug mode")
args = parser.parse_args()
load_jobs_index()
print(f"\n{'='*55}")
print(f" Karate 3D Avatar Studio Server")
print(f"{'='*55}")
print(f" URL: http://{args.host}:{args.port}")
print(f" Root: {PROJECT_ROOT}")
print(f" Uploads: {UPLOAD_DIR}")
print(f"{'='*55}\n")
app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)
if __name__ == "__main__":
main()