Runitdamar commited on
Commit
db07ba0
·
verified ·
1 Parent(s): 14eb60c

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -671
main.py DELETED
@@ -1,671 +0,0 @@
1
- import os
2
- import shutil
3
- import asyncio
4
- import subprocess
5
- import numpy as np
6
- from pathlib import Path
7
- from typing import Optional
8
- from contextlib import asynccontextmanager
9
-
10
- from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks
11
- from fastapi.middleware.cors import CORSMiddleware
12
- from fastapi.responses import FileResponse
13
-
14
- # ── paths ──────────────────────────────────────────────────────────────────────
15
- TMP = Path("/tmp/clipcut")
16
- TMP.mkdir(parents=True, exist_ok=True)
17
- os.environ["INSIGHTFACE_HOME"] = "/tmp"
18
-
19
- # ── lazy model ─────────────────────────────────────────────────────────────────
20
- _face_app = None
21
-
22
- def get_face_app():
23
- global _face_app
24
- if _face_app is None:
25
- from insightface.app import FaceAnalysis
26
- _face_app = FaceAnalysis(name="buffalo_sc", root="/tmp/insightface",
27
- providers=["CPUExecutionProvider"])
28
- _face_app.prepare(ctx_id=-1, det_size=(640, 640))
29
- return _face_app
30
-
31
- # ── job store ──────────────────────────────────────────────────────────────────
32
- jobs: dict[str, dict] = {}
33
-
34
- @asynccontextmanager
35
- async def lifespan(app):
36
- yield
37
-
38
- app = FastAPI(lifespan=lifespan)
39
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
40
-
41
- # ── utils ──────────────────────────────────────────────────────────────────────
42
-
43
- def cosine_sim(a, b) -> float:
44
- a, b = a.flatten(), b.flatten()
45
- d = np.linalg.norm(a) * np.linalg.norm(b)
46
- return float(np.dot(a, b) / d) if d > 0 else 0.0
47
-
48
- def clothing_hist(frame, bbox) -> Optional[np.ndarray]:
49
- import cv2
50
- x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
51
- region = frame[y1 + int((y2-y1)*0.3):y2, x1:x2]
52
- if region.size == 0:
53
- return None
54
- hsv = cv2.cvtColor(region, cv2.COLOR_BGR2HSV)
55
- h = cv2.calcHist([hsv], [0,1], None, [16,16], [0,180,0,256])
56
- cv2.normalize(h, h)
57
- return h.flatten()
58
-
59
- def hist_sim(h1, h2) -> float:
60
- import cv2
61
- if h1 is None or h2 is None:
62
- return 0.0
63
- return float(cv2.compareHist(h1.astype(np.float32).reshape(-1,1),
64
- h2.astype(np.float32).reshape(-1,1),
65
- cv2.HISTCMP_CORREL))
66
-
67
- def extract_ref_embedding(ref_path: Path) -> Optional[np.ndarray]:
68
- import cv2
69
- img = cv2.imread(str(ref_path))
70
- if img is None:
71
- return None
72
- faces = get_face_app().get(img)
73
- if not faces:
74
- return None
75
- largest = max(faces, key=lambda f: (f.bbox[2]-f.bbox[0])*(f.bbox[3]-f.bbox[1]))
76
- return largest.normed_embedding
77
-
78
- def video_info(path: Path) -> dict:
79
- import json
80
- r = subprocess.run([
81
- "ffprobe", "-v", "error", "-select_streams", "v:0",
82
- "-show_entries", "stream=width,height,r_frame_rate",
83
- "-show_entries", "format=duration", "-of", "json", str(path)
84
- ], capture_output=True, text=True)
85
- d = json.loads(r.stdout)
86
- s = d.get("streams", [{}])[0]
87
- num, den = s.get("r_frame_rate", "30/1").split("/")
88
- return {
89
- "fps": float(num)/float(den),
90
- "duration": float(d.get("format",{}).get("duration", 0)),
91
- "width": int(s.get("width", 1080)),
92
- "height": int(s.get("height", 1920))
93
- }
94
-
95
- def crop_size(w, h) -> tuple[int, int]:
96
- if (w/h) > (9/16):
97
- ch = h - h%2
98
- cw = int(ch*9/16) - int(ch*9/16)%2
99
- else:
100
- cw = w - w%2
101
- ch = int(cw*16/9) - int(cw*16/9)%2
102
- return cw, ch
103
-
104
- def clamp(cx, cy, cw, ch, fw, fh) -> tuple[int, int]:
105
- x = max(0, min(cx - cw//2, fw - cw))
106
- y = max(0, min(cy - ch//2, fh - ch))
107
- return x, y
108
-
109
- # ── scan video ─────────────────────────────────────────────────────────────────
110
-
111
- def scan_video(video_path: Path, ref_emb: np.ndarray, fps: float,
112
- job_id: str, p0=15, p1=82, label="Scanning"):
113
- import cv2
114
- import time
115
- fa = get_face_app()
116
- FACE_THRESH = 0.20
117
- BODY_THRESH = 0.55
118
- BODY_WINDOW = fps * 4
119
-
120
- cap = cv2.VideoCapture(str(video_path))
121
- total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
122
- fw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
123
- fh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
124
-
125
- timestamps, positions = [], {}
126
- ref_hist = None
127
- last_face_frame = -9999
128
- idx = 0
129
- start_time = time.time()
130
- preview_dir = TMP / job_id
131
- PREVIEW_EVERY = max(1, total // 20) # save ~20 previews during scan
132
-
133
- while True:
134
- # ── Check cancel flag ──
135
- if jobs.get(job_id, {}).get("cancelled"):
136
- cap.release()
137
- return [], {}
138
-
139
- ret, frame = cap.read()
140
- if not ret:
141
- break
142
-
143
- if idx % 2 == 0:
144
- faces = fa.get(frame)
145
- matched = False
146
- cx_r, cy_r = 0.5, 0.42
147
-
148
- for face in faces:
149
- if cosine_sim(face.normed_embedding, ref_emb) >= FACE_THRESH:
150
- matched = True
151
- last_face_frame = idx
152
- x1, y1, x2, y2 = face.bbox
153
- fh_box = y2 - y1
154
- cx_r = ((x1+x2)/2) / fw
155
- cy_r = min(0.88, ((y1+y2)/2 + fh_box*1.2) / fh)
156
- h = clothing_hist(frame, face.bbox)
157
- if h is not None:
158
- ref_hist = h
159
- break
160
-
161
- if not matched and ref_hist is not None and (idx - last_face_frame) <= BODY_WINDOW:
162
- best_s, best_bbox = 0.0, None
163
- for face in faces:
164
- s = hist_sim(ref_hist, clothing_hist(frame, face.bbox))
165
- if s > best_s:
166
- best_s, best_bbox = s, face.bbox
167
- if best_s >= BODY_THRESH and best_bbox is not None:
168
- matched = True
169
- x1, y1, x2, y2 = best_bbox
170
- cx_r = ((x1+x2)/2) / fw
171
- cy_r = min(0.88, ((y1+y2)/2) / fh)
172
-
173
- if matched:
174
- ts = idx / fps
175
- timestamps.append(ts)
176
- positions[ts] = (cx_r, cy_r)
177
-
178
- # ── Save preview frame every N frames ──
179
- if idx % PREVIEW_EVERY == 0 and frame is not None:
180
- try:
181
- preview_path = preview_dir / "preview.jpg"
182
- small = cv2.resize(frame, (360, int(fh * 360 / fw)))
183
- cv2.imwrite(str(preview_path), small, [cv2.IMWRITE_JPEG_QUALITY, 70])
184
- except Exception:
185
- pass
186
-
187
- # ── ETA calculation ──
188
- elapsed = time.time() - start_time
189
- prange = p1 - p0
190
- prog = p0 + int((idx / max(total, 1)) * prange)
191
- if idx > 0 and elapsed > 0:
192
- fps_proc = idx / elapsed
193
- frames_left = total - idx
194
- eta_sec = int(frames_left / fps_proc)
195
- if eta_sec >= 60:
196
- eta_str = f"{eta_sec//60}m {eta_sec%60}s"
197
- else:
198
- eta_str = f"{eta_sec}s"
199
- else:
200
- eta_str = "calculating..."
201
-
202
- jobs[job_id]["progress"] = prog
203
- jobs[job_id]["status_text"] = f"{label}: {idx}/{total} frames"
204
- jobs[job_id]["eta"] = eta_str
205
- idx += 1
206
-
207
- cap.release()
208
- return timestamps, positions
209
-
210
- # ── intervals ──────────────────────────────────────────────────────────────────
211
-
212
- def to_intervals(timestamps, fps, gap=3.0, min_dur=0.3):
213
- if not timestamps:
214
- return []
215
- fw = 1.0/fps
216
- intervals, start, end = [], timestamps[0], timestamps[0]+fw
217
- for ts in timestamps[1:]:
218
- if ts - end <= gap:
219
- end = ts + fw
220
- else:
221
- if end-start >= min_dur:
222
- intervals.append((start, end))
223
- start, end = ts, ts+fw
224
- if end-start >= min_dur:
225
- intervals.append((start, end))
226
- return intervals
227
-
228
- # ── cut clips with dynamic crop ────────────────────────────────────────────────
229
-
230
- def cut_clip(video_path, start, end, positions, vi, out_path) -> bool:
231
- w, h = vi["width"], vi["height"]
232
- fps = vi["fps"]
233
- cw, ch = crop_size(w, h)
234
- dur = end - start
235
-
236
- # Gather positions for this interval
237
- pts = {ts: pos for ts, pos in positions.items() if start-0.1 <= ts <= end+0.1}
238
-
239
- if len(pts) >= 2:
240
- sorted_ts = sorted(pts.keys())
241
- rel = [(ts-start, pts[ts]) for ts in sorted_ts]
242
-
243
- def interp(t):
244
- if t <= rel[0][0]: return rel[0][1]
245
- if t >= rel[-1][0]: return rel[-1][1]
246
- for i in range(len(rel)-1):
247
- t0, p0 = rel[i]; t1, p1 = rel[i+1]
248
- if t0 <= t <= t1:
249
- a = (t-t0)/max(t1-t0, 1e-6)
250
- return (p0[0]+a*(p1[0]-p0[0]), p0[1]+a*(p1[1]-p0[1]))
251
- return rel[-1][1]
252
-
253
- # Build per-frame positions
254
- step = 1.0/fps
255
- raw = []
256
- t = 0.0
257
- while t <= dur+step:
258
- cx_r, cy_r = interp(t)
259
- x, y = clamp(int(cx_r*w), int(cy_r*h), cw, ch, w, h)
260
- raw.append((t, x, y))
261
- t += step
262
-
263
- # Smooth with small window + weight recent frames more to reduce lag
264
- win = max(1, int(fps * 0.12)) # 0.12s — fast response to movement
265
- smoothed = []
266
- for i, (t, x, y) in enumerate(raw):
267
- i0, i1 = max(0, i-win), min(len(raw), i+win+1)
268
- weights = [1.0 / (abs(j-i)+1) for j in range(i0, i1)]
269
- xs = [raw[j][1] for j in range(i0, i1)]
270
- ys = [raw[j][2] for j in range(i0, i1)]
271
- sw = sum(weights)
272
- sx = int(sum(wt*xv for wt,xv in zip(weights,xs)) / sw)
273
- sy = int(sum(wt*yv for wt,yv in zip(weights,ys)) / sw)
274
- smoothed.append((t, sx, sy))
275
-
276
- # Write sendcmd file
277
- sc = out_path.parent / f"sc_{out_path.stem}.txt"
278
- with open(sc, "w") as f:
279
- for i, (t, x, y) in enumerate(smoothed):
280
- f.write(f"{t:.4f} crop x {x}; crop y {y};\n")
281
-
282
- cmd = [
283
- "ffmpeg", "-y", "-ss", str(start), "-i", str(video_path),
284
- "-t", str(dur),
285
- "-vf", f"crop={cw}:{ch}:0:0,sendcmd=f={sc},scale=1080:1920",
286
- "-c:v", "libx264", "-preset", "fast", "-crf", "23",
287
- "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart",
288
- str(out_path)
289
- ]
290
- r = subprocess.run(cmd, capture_output=True)
291
- if sc.exists(): sc.unlink()
292
- if r.returncode == 0 and out_path.exists():
293
- return True
294
-
295
- # Static fallback
296
- vals = list(pts.values()) if pts else [(0.5, 0.42)]
297
- cx_r = float(np.median([v[0] for v in vals]))
298
- cy_r = float(np.median([v[1] for v in vals]))
299
- x, y = clamp(int(cx_r*w), int(cy_r*h), cw, ch, w, h)
300
- cmd = [
301
- "ffmpeg", "-y", "-ss", str(start), "-i", str(video_path),
302
- "-t", str(dur),
303
- "-vf", f"crop={cw}:{ch}:{x}:{y},scale=1080:1920",
304
- "-c:v", "libx264", "-preset", "fast", "-crf", "23",
305
- "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart",
306
- str(out_path)
307
- ]
308
- r = subprocess.run(cmd, capture_output=True)
309
- return r.returncode == 0 and out_path.exists()
310
-
311
- def merge_clips(clips, out_path) -> bool:
312
- if not clips: return False
313
- if len(clips) == 1:
314
- shutil.copy(clips[0], out_path)
315
- return True
316
- lst = out_path.parent / "concat.txt"
317
- lst.write_text("\n".join(f"file '{c}'" for c in clips))
318
- r = subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0",
319
- "-i", str(lst), "-c", "copy", str(out_path)],
320
- capture_output=True)
321
- return r.returncode == 0
322
-
323
- # ── pipeline ───────────────────────────────────────────────────────────────────
324
-
325
- async def process_video(job_id: str, video_path: Path, ref_path: Path):
326
- job = jobs[job_id]
327
- try:
328
- job["status"] = "processing"
329
- job["status_text"] = "Analyzing reference photo..."
330
- job["progress"] = 5
331
-
332
- ref_emb = extract_ref_embedding(ref_path)
333
- if ref_emb is None:
334
- job["status"] = "failed"
335
- job["error"] = "No face detected in reference photo. Use a clear front-facing photo."
336
- return
337
-
338
- job["status_text"] = "Reading video..."
339
- job["progress"] = 10
340
- vi = video_info(video_path)
341
- fps, duration = vi["fps"], vi["duration"]
342
-
343
- loop = asyncio.get_event_loop()
344
- timestamps, positions = await loop.run_in_executor(
345
- None, lambda: scan_video(video_path, ref_emb, fps, job_id))
346
-
347
- if not timestamps or jobs[job_id].get("cancelled"):
348
- if jobs[job_id].get("cancelled"):
349
- job["status"] = "cancelled"
350
- job["status_text"] = "Cancelled."
351
- return
352
- job["status"] = "failed"
353
- job["error"] = "Could not find the reference person in the video. Try a clearer photo."
354
- return
355
-
356
- intervals = to_intervals(timestamps, fps)
357
- if not intervals:
358
- job["status"] = "failed"
359
- job["error"] = "Person found but clips too short to extract."
360
- return
361
-
362
- out_dir = video_path.parent
363
- clips = []
364
- total_intervals = len(intervals)
365
-
366
- for i, (s, e) in enumerate(intervals):
367
- job["status_text"] = f"Cutting clip {i+1} of {total_intervals}..."
368
- job["progress"] = 83 + int((i / max(total_intervals, 1)) * 10)
369
- op = out_dir / f"clip_{i:04d}.mp4"
370
- if cut_clip(video_path, s, e, positions, vi, op):
371
- clips.append(op)
372
-
373
- if not clips:
374
- job["status"] = "failed"
375
- job["error"] = "Failed to cut clips."
376
- return
377
-
378
- job["status_text"] = f"Merging {len(clips)} clip(s) into final video..."
379
- job["progress"] = 94
380
-
381
- final = out_dir / "result.mp4"
382
- if not merge_clips(clips, final):
383
- job["status"] = "failed"
384
- job["error"] = "Failed to merge clips."
385
- return
386
-
387
- job["status_text"] = "Finalizing video..."
388
- job["progress"] = 98
389
-
390
- total_kept = sum(e-s for s,e in intervals)
391
- job.update({
392
- "status": "done", "progress": 100, "status_text": "Done!",
393
- "result_path": str(final),
394
- "stats": {"duration": round(duration,1),
395
- "extracted": round(total_kept,1),
396
- "clips": len(intervals)}
397
- })
398
-
399
- except Exception as e:
400
- import traceback
401
- job["status"] = "failed"
402
- job["error"] = f"Error: {str(e)}"
403
- print(traceback.format_exc())
404
-
405
- # ── routes ─────────────────────────────────────────────────────────────────────
406
-
407
- @app.get("/health")
408
- def health():
409
- return {"status": "ok", "face_recognition": True, "device": "cpu"}
410
-
411
- @app.post("/upload-chunk")
412
- async def upload_chunk(job_id: str, chunk_index: int, total_chunks: int,
413
- file_type: str, chunk: UploadFile = File(...)):
414
- job_dir = TMP / job_id
415
- job_dir.mkdir(parents=True, exist_ok=True)
416
- chunk_dir = job_dir / f"{file_type}_chunks"
417
- chunk_dir.mkdir(exist_ok=True)
418
- (chunk_dir / f"{chunk_index:06d}").write_bytes(await chunk.read())
419
-
420
- received = len(list(chunk_dir.glob("*")))
421
- if received == total_chunks:
422
- ext = ".mp4" if file_type == "video" else ".jpg"
423
- final = job_dir / f"{file_type}{ext}"
424
- with open(final, "wb") as out:
425
- for i in range(total_chunks):
426
- out.write((chunk_dir / f"{i:06d}").read_bytes())
427
- shutil.rmtree(chunk_dir)
428
- return {"status": "complete"}
429
- return {"status": "partial", "received": received, "total": total_chunks}
430
-
431
- @app.post("/process")
432
- async def process(job_id: str, background_tasks: BackgroundTasks):
433
- job_dir = TMP / job_id
434
- video_path = next(
435
- (job_dir / f"video{ext}" for ext in [".mp4",".mov",".avi",".mkv",".webm"]
436
- if (job_dir / f"video{ext}").exists()), None)
437
- ref_path = job_dir / "reference.jpg"
438
- if not video_path:
439
- raise HTTPException(400, "Video not found.")
440
- if not ref_path.exists():
441
- raise HTTPException(400, "Reference photo not found.")
442
- jobs[job_id] = {"status": "queued", "progress": 0,
443
- "status_text": "Queued...", "result_path": None,
444
- "error": None, "stats": None, "cancelled": False, "eta": ""}
445
- background_tasks.add_task(process_video, job_id, video_path, ref_path)
446
- return {"job_id": job_id, "status": "queued"}
447
-
448
- @app.get("/status/{job_id}")
449
- def get_status(job_id: str):
450
- if job_id not in jobs:
451
- raise HTTPException(404, "Job not found")
452
- j = jobs[job_id]
453
- return {"status": j["status"], "progress": j["progress"],
454
- "status_text": j["status_text"], "error": j.get("error"),
455
- "stats": j.get("stats"), "eta": j.get("eta", "")}
456
-
457
- @app.post("/cancel/{job_id}")
458
- def cancel_job(job_id: str):
459
- if job_id not in jobs:
460
- raise HTTPException(404, "Job not found")
461
- jobs[job_id]["cancelled"] = True
462
- jobs[job_id]["status"] = "cancelled"
463
- jobs[job_id]["status_text"] = "Cancelling..."
464
- return {"cancelled": True}
465
-
466
- @app.get("/preview/{job_id}")
467
- def get_preview(job_id: str):
468
- preview_path = TMP / job_id / "preview.jpg"
469
- if not preview_path.exists():
470
- raise HTTPException(404, "No preview yet")
471
- return FileResponse(preview_path, media_type="image/jpeg")
472
-
473
- @app.get("/download/{job_id}")
474
- def download(job_id: str):
475
- if job_id not in jobs:
476
- raise HTTPException(404, "Job not found")
477
- j = jobs[job_id]
478
- if j["status"] != "done":
479
- raise HTTPException(400, "Not complete")
480
- p = Path(j["result_path"])
481
- if not p.exists():
482
- raise HTTPException(404, "File not found")
483
- return FileResponse(p, media_type="video/mp4", filename="clipcut_result.mp4")
484
-
485
- @app.delete("/job/{job_id}")
486
- def delete_job(job_id: str):
487
- d = TMP / job_id
488
- if d.exists(): shutil.rmtree(d)
489
- jobs.pop(job_id, None)
490
- return {"deleted": True}
491
-
492
- # ── VidFetch ───────────────────────────────────────────────────────────────────
493
-
494
- vf_jobs: dict[str, dict] = {}
495
-
496
- COBALT_URL = "https://runitdamar-cobalt.hf.space"
497
-
498
- async def run_vidfetch(job_id: str, urls: list, mode: str):
499
- import aiohttp
500
- job = vf_jobs[job_id]
501
- out_dir = TMP / job_id
502
- out_dir.mkdir(parents=True, exist_ok=True)
503
- downloaded = []
504
-
505
- try:
506
- total = len(urls)
507
- async with aiohttp.ClientSession() as session:
508
- for i, url in enumerate(urls):
509
- if job.get("cancelled"): break
510
- job["status_text"] = f"Fetching video {i+1} of {total}..."
511
- job["progress"] = int((i / total) * 80)
512
-
513
- # Call Cobalt API
514
- try:
515
- async with session.post(
516
- f"{COBALT_URL}/",
517
- json={"url": url},
518
- headers={"Accept": "application/json", "Content-Type": "application/json"},
519
- timeout=aiohttp.ClientTimeout(total=30)
520
- ) as resp:
521
- data = await resp.json()
522
- except Exception as e:
523
- job["status"] = "failed"
524
- job["error"] = f"Could not reach download service. Try again shortly."
525
- return
526
-
527
- # Cobalt returns either a direct URL or a tunnel URL
528
- download_url = data.get("url") or data.get("tunnel")
529
- if not download_url:
530
- status = data.get("status", "unknown")
531
- job["status"] = "failed"
532
- job["error"] = f"Could not get download link for video {i+1}. The link may be private or unsupported. (Status: {status})"
533
- return
534
-
535
- # Download the actual video file
536
- job["status_text"] = f"Downloading video {i+1} of {total}..."
537
- job["progress"] = int((i / total) * 80) + 20
538
-
539
- out_path = out_dir / f"video_{i:03d}.mp4"
540
- try:
541
- async with session.get(
542
- download_url,
543
- timeout=aiohttp.ClientTimeout(total=300),
544
- headers={"User-Agent": "Mozilla/5.0"}
545
- ) as dl_resp:
546
- if dl_resp.status != 200:
547
- job["status"] = "failed"
548
- job["error"] = f"Failed to download video {i+1}. Status: {dl_resp.status}"
549
- return
550
- with open(out_path, "wb") as f:
551
- async for chunk in dl_resp.content.iter_chunked(1024 * 64):
552
- f.write(chunk)
553
- except Exception as e:
554
- job["status"] = "failed"
555
- job["error"] = f"Download failed for video {i+1}: {str(e)}"
556
- return
557
-
558
- if out_path.exists() and out_path.stat().st_size > 0:
559
- downloaded.append(out_path)
560
- else:
561
- job["status"] = "failed"
562
- job["error"] = f"Video {i+1} downloaded but file is empty."
563
- return
564
-
565
- if job.get("cancelled"):
566
- job["status"] = "cancelled"
567
- return
568
-
569
- if not downloaded:
570
- job["status"] = "failed"
571
- job["error"] = "No videos were downloaded."
572
- return
573
-
574
- job["progress"] = 85
575
-
576
- if mode == "merge" and len(downloaded) > 1:
577
- job["status_text"] = "Merging videos..."
578
- job["progress"] = 90
579
- list_file = out_dir / "concat.txt"
580
- list_file.write_text("\n".join(f"file '{p}'" for p in downloaded))
581
- merged = out_dir / "merged.mp4"
582
- r = subprocess.run([
583
- "ffmpeg", "-y", "-f", "concat", "-safe", "0",
584
- "-i", str(list_file), "-c", "copy", str(merged)
585
- ], capture_output=True)
586
- if r.returncode != 0 or not merged.exists():
587
- job["status"] = "failed"
588
- job["error"] = "Failed to merge videos."
589
- return
590
- vi = video_info(merged)
591
- job.update({
592
- "status": "done", "progress": 100, "status_text": "Done!",
593
- "mode": "merge", "count": len(downloaded),
594
- "duration": round(vi["duration"], 1),
595
- "result_path": str(merged)
596
- })
597
- else:
598
- job.update({
599
- "status": "done", "progress": 100, "status_text": "Done!",
600
- "mode": "download", "count": len(downloaded),
601
- "result_paths": [str(p) for p in downloaded]
602
- })
603
-
604
- except Exception as e:
605
- import traceback
606
- job["status"] = "failed"
607
- job["error"] = f"Error: {str(e)}"
608
- print(traceback.format_exc())
609
-
610
- from pydantic import BaseModel
611
-
612
- class VidFetchRequest(BaseModel):
613
- job_id: str
614
- urls: list
615
- mode: str = "download"
616
-
617
- @app.post("/vidfetch")
618
- async def vidfetch(req: VidFetchRequest, background_tasks: BackgroundTasks):
619
- vf_jobs[req.job_id] = {
620
- "status": "queued", "progress": 0, "status_text": "Queued...",
621
- "cancelled": False, "error": None
622
- }
623
- background_tasks.add_task(asyncio.create_task, run_vidfetch(req.job_id, req.urls, req.mode))
624
- return {"job_id": req.job_id, "status": "queued"}
625
-
626
- @app.get("/vidfetch/status/{job_id}")
627
- def vidfetch_status(job_id: str):
628
- if job_id not in vf_jobs:
629
- raise HTTPException(404, "Job not found")
630
- j = vf_jobs[job_id]
631
- return {
632
- "status": j["status"], "progress": j["progress"],
633
- "status_text": j["status_text"], "error": j.get("error"),
634
- "mode": j.get("mode"), "count": j.get("count"),
635
- "duration": j.get("duration")
636
- }
637
-
638
- @app.post("/vidfetch/cancel/{job_id}")
639
- def vidfetch_cancel(job_id: str):
640
- if job_id not in vf_jobs:
641
- raise HTTPException(404, "Job not found")
642
- vf_jobs[job_id]["cancelled"] = True
643
- vf_jobs[job_id]["status"] = "cancelled"
644
- return {"cancelled": True}
645
-
646
- @app.get("/vidfetch/download/{job_id}")
647
- def vidfetch_download(job_id: str):
648
- if job_id not in vf_jobs:
649
- raise HTTPException(404, "Job not found")
650
- j = vf_jobs[job_id]
651
- if j["status"] != "done":
652
- raise HTTPException(400, "Not complete")
653
- path = Path(j.get("result_path", "") or j.get("result_paths", [""])[0])
654
- if not path.exists():
655
- raise HTTPException(404, "File not found")
656
- return FileResponse(path, media_type="video/mp4", filename="vidix_download.mp4")
657
-
658
- @app.get("/vidfetch/download/{job_id}/{index}")
659
- def vidfetch_download_single(job_id: str, index: int):
660
- if job_id not in vf_jobs:
661
- raise HTTPException(404, "Job not found")
662
- j = vf_jobs[job_id]
663
- if j["status"] != "done":
664
- raise HTTPException(400, "Not complete")
665
- paths = j.get("result_paths", [])
666
- if index >= len(paths):
667
- raise HTTPException(404, "File not found")
668
- path = Path(paths[index])
669
- if not path.exists():
670
- raise HTTPException(404, "File not found")
671
- return FileResponse(path, media_type="video/mp4", filename=f"vidix_video_{index+1}.mp4")