IdleCloud commited on
Commit
591e9bc
·
1 Parent(s): 7602a13

Add custom video job API

Browse files
Files changed (6) hide show
  1. README.md +117 -3
  2. app.py +305 -85
  3. lora_loader.py +9 -4
  4. requirements.txt +2 -0
  5. tests/test_video_job_api.py +1084 -0
  6. video_job_api.py +1666 -0
README.md CHANGED
@@ -7,6 +7,120 @@ sdk: gradio
7
  sdk_version: 6.0.1
8
  app_file: app.py
9
  pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  sdk_version: 6.0.1
8
  app_file: app.py
9
  pinned: false
10
+ ---
11
+
12
+ # Wan 2.2 I2V 14B Lightning · ZeroGPU
13
+
14
+ 本 Space 保留 Gradio UI、MCP、`/generate_video` 与 `/extract_frame`,并额外提供一个不依赖 Gradio SSE 的异步视频任务 API。任务状态和幂等索引保存在当前进程内,Space 重启后不会保留;完成结果默认保存 1800 秒。
15
+
16
+ ## Space 配置
17
+
18
+ 必需 Secret:
19
+
20
+ - `HF_TOKEN`:仅用于读取模型或私有 LoRA,不会替代调用方的 Hugging Face 身份。
21
+ - `JOB_API_KEY`:至少 32 字符的随机共享密钥,仅通过 `X-API-Key` 传入,禁止提交到仓库。
22
+
23
+ 必需 Variable:
24
+
25
+ - `SPACE_HOST`:公开 Space 根地址,例如 `https://idlecloudx-i2v-1.hf.space`。
26
+ - `JOB_IMAGE_ALLOWED_HOSTS`:允许抓取首图和尾图的精确主机名,以逗号分隔,不支持通配符、协议、端口或路径。
27
+
28
+ 可选 Variable:
29
+
30
+ - `JOB_RESULT_TTL_SECONDS`:终态结果保留秒数,默认 `1800`。
31
+ - `JOB_POLL_AFTER_SECONDS`:建议轮询间隔,默认 `2`。
32
+ - `JOB_IMAGE_FETCH_TIMEOUT_SECONDS`:单图连接与总抓取期限,默认且最大 `15`。
33
+ - `JOB_IMAGE_MAX_BYTES`:单图字节上限,默认且最大 `20971520`(20 MiB)。
34
+ - `JOB_IMAGE_MAX_PIXELS`:单图像素上限,默认且最大 `40000000`。
35
+
36
+ 修改 Secret 或 Variable 会触发 Space 重启。
37
+
38
+ ## 自定义视频任务 API
39
+
40
+ 所有任务管理请求都需要 `X-API-Key`。`Idempotency-Key` 可省略,正式调用方应提供不超过 200 字符的稳定唯一值。相同键与相同请求体只会生成一次;相同键配合不同请求体返回 `409`。
41
+
42
+ 创建任务:
43
+
44
+ ```bash
45
+ curl -i -X POST "https://idlecloudx-i2v-1.hf.space/api/jobs" \
46
+ -H "X-API-Key: your-shared-random-key" \
47
+ -H "Idempotency-Key: caller-generated-unique-value" \
48
+ -H "Content-Type: application/json" \
49
+ --data '{
50
+ "input_image_url": "https://allowed.example/input.png",
51
+ "last_image_url": null,
52
+ "prompt": "make this image come alive, cinematic motion, smooth animation",
53
+ "steps": 6,
54
+ "negative_prompt": "",
55
+ "duration_seconds": 3.5,
56
+ "guidance_scale": 1,
57
+ "guidance_scale_2": 1,
58
+ "seed": 42,
59
+ "randomize_seed": false,
60
+ "quality": 6,
61
+ "scheduler": "UniPCMultistep",
62
+ "flow_shift": 3.0,
63
+ "frame_multiplier": 16,
64
+ "safe_mode": true,
65
+ "lora_groups": []
66
+ }'
67
+ ```
68
+
69
+ `input_image_url` 必须是白名单精确主机上的 HTTPS URL;`last_image_url` 可空。抓取禁止重定向、用户信息、非默认端口和非公网解析地址,不会向图片主机转发 `Authorization`、Cookie、API key 或 ZeroGPU 请求头。每张图片仅接受实际 PNG/JPEG/WebP。`lora_groups` 中每一项都必须与当前 UI 下拉框显示名称完全一致。
70
+
71
+ 字段边界:
72
+
73
+ | 字段 | 默认值 | 边界 |
74
+ | --- | --- | --- |
75
+ | `prompt` | 当前 UI 默认文案 | 非空,最长 5000 |
76
+ | `negative_prompt` | 当前 UI 默认文案 | 最长 5000,可空 |
77
+ | `steps` | `6` | 1–30 |
78
+ | `duration_seconds` | `3.5` | 0.5–20.1 |
79
+ | `guidance_scale`, `guidance_scale_2` | `1` | 0–10 |
80
+ | `seed` | `42` | 0–2147483647 |
81
+ | `randomize_seed` | `true` | 布尔值 |
82
+ | `quality` | `6` | 1–10 |
83
+ | `scheduler` | `UniPCMultistep` | UI 当前 7 个调度器之一 |
84
+ | `flow_shift` | `3.0` | 0.5–15 |
85
+ | `frame_multiplier` | `16` | 仅 16/32/64/128 |
86
+ | `safe_mode` | `true` | 布尔值 |
87
+
88
+ 成功创建返回 `202`,并同时设置 `Location` 与 `Cache-Control: no-store`:
89
+
90
+ ```json
91
+ {"job_id":"...","status_url":"https://.../api/jobs/...","poll_after_seconds":2}
92
+ ```
93
+
94
+ 使用同一个 API key 轮询 `GET /api/jobs/{job_id}`。排队或运行中返回 `202`、`Retry-After` 和 `{"status":"queued"}` / `{"status":"running"}`。完成后返回:
95
+
96
+ ```json
97
+ {"video_url":"https://.../api/jobs/.../video?token=...","used_seed":42}
98
+ ```
99
+
100
+ `video_url` 自带短期随机凭证,不再需要 API key。它支持 `GET`、`HEAD` 和单区间 `Range`:
101
+
102
+ ```bash
103
+ curl -I "https://.../api/jobs/.../video?token=..."
104
+ curl -H "Range: bytes=0-1023" "https://.../api/jobs/.../video?token=..." -o first-kib.bin
105
+ ```
106
+
107
+ 视频返回 `video/mp4`,有效单区间为 `206`;多区间或不可满足范围为 `416`。响应允许跨域播放,缓存策略为 `private, max-age=300`。
108
+
109
+ ## 身份、配额与并发
110
+
111
+ - 不带 `Authorization` 时,Hugging Face 将请求计入匿名共享 ZeroGPU 配额。
112
+ - 带 `Authorization: Bearer hf_<调用方令牌>` 时,由 Hugging Face 将生成计入调用方自己的 ZeroGPU 配额;应用仅保留代理注入的短效身份信息到任务启动,不保存或转发 Bearer 令牌。
113
+ - 内部模型下载使用的 `HF_TOKEN` 永远不会充当调用方身份。
114
+ - UI 和自定义 API 共用一个非阻塞推理槽位。已有任务运行时,新自定义提交立即返回 `503` 与 `Retry-After: 5`,不会在 Space 内排队。
115
+
116
+ ## 错误约定
117
+
118
+ - `400`:URL、��片内容或 `Idempotency-Key` 不合法。
119
+ - `401`:API key 或视频下载 token 缺失/错误。
120
+ - `404`:任务不存在或结果 TTL 已过期。
121
+ - `409`:幂等键冲突,或视频结果尚未就绪。
122
+ - `410`:任务元数据仍在但 MP4 已丢失。
123
+ - `422`:JSON Schema 校验失败,包括未知字段。
124
+ - `500`:生成失败;仅返回脱敏的 `GENERATION_FAILED`。
125
+ - `502` / `504`:图片源临时故障或抓取超时。
126
+ - `503`:推理槽位繁忙,或 Hugging Face 未提供 ZeroGPU 身份。
app.py CHANGED
@@ -1,6 +1,5 @@
1
- import os; os.system('pip install --upgrade --no-deps spaces')
2
  import spaces
3
- import shutil
4
  import subprocess
5
  import sys
6
  import copy
@@ -10,6 +9,7 @@ import warnings
10
  import time
11
  import gc
12
  import uuid
 
13
  from tqdm import tqdm
14
  import cv2
15
  import numpy as np
@@ -19,6 +19,7 @@ from torch.nn import functional as F
19
  from PIL import Image
20
 
21
  import gradio as gr
 
22
  from diffusers import (
23
  FlowMatchEulerDiscreteScheduler,
24
  SASolverScheduler,
@@ -34,14 +35,22 @@ from diffusers.utils.export_utils import export_to_video
34
  from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
35
  import aoti
36
  import lora_loader
 
 
 
 
 
 
 
 
 
37
 
38
  os.environ["TOKENIZERS_PARALLELISM"] = "true"
39
  warnings.filterwarnings("ignore")
40
- IS_ZERO_GPU = bool(os.getenv("SPACES_ZERO_GPU"))
41
-
42
- # if IS_ZERO_GPU:
43
- # print("Loading...")
44
- # subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
45
 
46
  # --- FRAME EXTRACTION JS & LOGIC ---
47
 
@@ -297,12 +306,6 @@ for i, lora in enumerate(LORA_MODELS):
297
  print("Failed LoRA:", name_high_tr)
298
  pipe.unload_lora_weights()
299
 
300
- # if os.path.exists(CACHE_DIR):
301
- # shutil.rmtree(CACHE_DIR)
302
- # print("Deleted Hugging Face cache.")
303
- # else:
304
- # print("No hub cache found.")
305
-
306
  quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
307
  torch._dynamo.reset()
308
  quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
@@ -322,8 +325,8 @@ spaces.aoti_load(
322
  # pipe.vae.enable_slicing()
323
  # pipe.vae.enable_tiling()
324
 
325
- default_prompt_i2v = "make this image come alive, cinematic motion, smooth animation"
326
- default_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
327
 
328
 
329
  def model_title():
@@ -443,79 +446,137 @@ def run_inference(
443
  lora_groups=None,
444
  progress=gr.Progress(track_tqdm=True),
445
  ):
446
- scheduler_class = SCHEDULER_MAP.get(scheduler_name)
447
- if scheduler_class.__name__ != pipe.scheduler.config._class_name or flow_shift != pipe.scheduler.config.get("flow_shift", "shift"):
448
- config = copy.deepcopy(original_scheduler.config)
449
- if scheduler_class == FlowMatchEulerDiscreteScheduler:
450
- config['shift'] = flow_shift
451
- else:
452
- config['flow_shift'] = flow_shift
453
- pipe.scheduler = scheduler_class.from_config(config)
454
 
455
- clear_vram()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
 
 
 
 
457
  task_name = str(uuid.uuid4())[:8]
458
- print(f"Generating {num_frames} frames, task: {task_name}, {duration_seconds}, {resized_image.size}, lora={lora_groups}")
459
- start = time.time()
460
-
461
- lora_loaded = False
462
- if lora_groups:
463
- try:
464
- for idx, name in enumerate(lora_groups):
465
- if name and name != "(None)":
466
- lora_loader.load_lora_to_pipe(pipe, name, adapter_name=f"lora_{idx}")
467
- lora_loaded = True
468
- print(f"LoRA loaded: {lora_groups}")
469
- except Exception as e:
470
- print(f"LoRA warning: {e}")
471
-
472
- result = pipe(
473
- image=resized_image,
474
- last_image=processed_last_image,
475
- prompt=prompt,
476
- negative_prompt=negative_prompt,
477
- height=resized_image.height,
478
- width=resized_image.width,
479
- num_frames=num_frames,
480
- guidance_scale=float(guidance_scale),
481
- guidance_scale_2=float(guidance_scale_2),
482
- num_inference_steps=int(steps),
483
- generator=torch.Generator(device="cuda").manual_seed(current_seed),
484
- output_type="np"
485
- )
486
-
487
- if lora_loaded:
488
- lora_loader.unload_lora(pipe)
489
-
490
- print("gen time passed:", time.time() - start)
491
-
492
- raw_frames_np = result.frames[0] # Returns (T, H, W, C) float32
493
- pipe.scheduler = original_scheduler
494
 
495
- frame_factor = frame_multiplier // FIXED_FPS
496
- if frame_factor > 1:
497
  start = time.time()
498
- print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")
499
- rife_model.device()
500
- rife_model.flownet = rife_model.flownet.half()
501
- final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
502
- print("Interpolation time passed:", time.time() - start)
503
- else:
504
- final_frames = list(raw_frames_np)
505
-
506
- final_fps = FIXED_FPS * int(frame_factor)
507
 
508
- with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
509
- video_path = tmpfile.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
 
511
- start = time.time()
512
- with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
513
- pbar.update(2)
514
- export_to_video(final_frames, video_path, fps=final_fps, quality=quality)
515
- pbar.update(1)
516
- print(f"Export time passed, {final_fps} FPS:", time.time() - start)
517
 
518
- return video_path, task_name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
 
520
 
521
  def generate_video(
@@ -618,6 +679,161 @@ def generate_video(
618
  return (video_path if video_component else None), video_path, current_seed
619
 
620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
  CSS = """
622
  #hidden-timestamp {
623
  opacity: 0;
@@ -696,9 +912,11 @@ with gr.Blocks(delete_cache=(3600, 10800)) as demo:
696
  ]
697
 
698
  generate_button.click(
699
- fn=generate_video,
700
- inputs=ui_inputs,
701
- outputs=[video_output, file_output, seed_input]
 
 
702
  )
703
 
704
  # --- Frame Grabbing Events ---
@@ -718,8 +936,10 @@ with gr.Blocks(delete_cache=(3600, 10800)) as demo:
718
  )
719
 
720
  if __name__ == "__main__":
721
- demo.queue().launch(
722
  mcp_server=True,
723
  css=CSS,
724
  show_error=True,
725
- )
 
 
 
1
+ import os; os.system('pip install --no-deps spaces==0.51.1')
2
  import spaces
 
3
  import subprocess
4
  import sys
5
  import copy
 
9
  import time
10
  import gc
11
  import uuid
12
+ import threading
13
  from tqdm import tqdm
14
  import cv2
15
  import numpy as np
 
19
  from PIL import Image
20
 
21
  import gradio as gr
22
+ from gradio.context import LocalContext
23
  from diffusers import (
24
  FlowMatchEulerDiscreteScheduler,
25
  SASolverScheduler,
 
35
  from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
36
  import aoti
37
  import lora_loader
38
+ from video_job_api import (
39
+ DEFAULT_NEGATIVE_PROMPT,
40
+ DEFAULT_PROMPT,
41
+ VideoJobAPI,
42
+ VideoJobRequest,
43
+ VideoJobSettings,
44
+ bind_context_values,
45
+ create_job_api_lifespan,
46
+ )
47
 
48
  os.environ["TOKENIZERS_PARALLELISM"] = "true"
49
  warnings.filterwarnings("ignore")
50
+ VIDEO_JOB_SETTINGS = VideoJobSettings.from_env()
51
+ INFERENCE_SLOT = threading.Lock()
52
+ # UI 外层不能再次自动申请 GPU;唯一 ZeroGPU 边界由 run_inference 的动态装饰器负责。
53
+ spaces.disable_gradio_auto_wrap()
 
54
 
55
  # --- FRAME EXTRACTION JS & LOGIC ---
56
 
 
306
  print("Failed LoRA:", name_high_tr)
307
  pipe.unload_lora_weights()
308
 
 
 
 
 
 
 
309
  quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
310
  torch._dynamo.reset()
311
  quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
 
325
  # pipe.vae.enable_slicing()
326
  # pipe.vae.enable_tiling()
327
 
328
+ default_prompt_i2v = DEFAULT_PROMPT
329
+ default_negative_prompt = DEFAULT_NEGATIVE_PROMPT
330
 
331
 
332
  def model_title():
 
446
  lora_groups=None,
447
  progress=gr.Progress(track_tqdm=True),
448
  ):
449
+ """在 ZeroGPU 上执行现有 Wan I2V 推理并生成一个临时 MP4。
 
 
 
 
 
 
 
450
 
451
+ Args:
452
+ resized_image: 已按模型要求缩放的首图。
453
+ processed_last_image: 已匹配首图尺寸的可选尾图。
454
+ prompt: 正向提示词。
455
+ steps: 推理步数。
456
+ negative_prompt: 负向提示词。
457
+ num_frames: 模型需要生成的基础帧数。
458
+ guidance_scale: 高噪声阶段引导强度。
459
+ guidance_scale_2: 低噪声阶段引导强度。
460
+ current_seed: 本次实际使用的随机种子。
461
+ scheduler_name: 现有调度器映射中的名称。
462
+ flow_shift: 调度器流偏移值。
463
+ frame_multiplier: 输出目标帧率值。
464
+ quality: MP4 编码质量。
465
+ duration_seconds: 用于日志和 ZeroGPU 时长估算的视频秒数。
466
+ safe_mode: 是否为 ZeroGPU 估时增加安全余量。
467
+ lora_groups: 要动态加载的 LoRA 精确名称列表。
468
+ progress: Gradio 进度对象。
469
 
470
+ Returns:
471
+ 生成的单个临时 MP4 路径与截短任务标识。
472
+ """
473
  task_name = str(uuid.uuid4())[:8]
474
+ video_path = None
475
+ video_ready = False
476
+ lora_attempted = False
477
+ result = None
478
+ raw_frames_np = None
479
+ final_frames = None
480
+
481
+ try:
482
+ scheduler_class = SCHEDULER_MAP.get(scheduler_name)
483
+ if scheduler_class is None:
484
+ raise ValueError(f"Unsupported scheduler: {scheduler_name}")
485
+ if scheduler_class.__name__ != pipe.scheduler.config._class_name or flow_shift != pipe.scheduler.config.get("flow_shift", "shift"):
486
+ config = copy.deepcopy(original_scheduler.config)
487
+ if scheduler_class == FlowMatchEulerDiscreteScheduler:
488
+ config['shift'] = flow_shift
489
+ else:
490
+ config['flow_shift'] = flow_shift
491
+ pipe.scheduler = scheduler_class.from_config(config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
 
493
+ clear_vram()
494
+ print(f"Generating {num_frames} frames, task: {task_name}, {duration_seconds}, {resized_image.size}, lora={lora_groups}")
495
  start = time.time()
 
 
 
 
 
 
 
 
 
496
 
497
+ if lora_groups:
498
+ # 从第一项开始加载就视为已污染管线,部分加载失败也必须进入 finally 卸载。
499
+ lora_attempted = True
500
+ try:
501
+ for idx, name in enumerate(lora_groups):
502
+ if name and name != "(None)":
503
+ lora_loader.load_lora_to_pipe(pipe, name, adapter_name=f"lora_{idx}")
504
+ print(f"LoRA loaded: {lora_groups}")
505
+ except Exception as exc:
506
+ print(f"LoRA warning: {type(exc).__name__}")
507
+ # 保留原 UI 的降级语义,但不能让部分 LoRA 参与本次或后续推理。
508
+ lora_loader.unload_lora(pipe)
509
+ lora_attempted = False
510
+
511
+ result = pipe(
512
+ image=resized_image,
513
+ last_image=processed_last_image,
514
+ prompt=prompt,
515
+ negative_prompt=negative_prompt,
516
+ height=resized_image.height,
517
+ width=resized_image.width,
518
+ num_frames=num_frames,
519
+ guidance_scale=float(guidance_scale),
520
+ guidance_scale_2=float(guidance_scale_2),
521
+ num_inference_steps=int(steps),
522
+ generator=torch.Generator(device="cuda").manual_seed(current_seed),
523
+ output_type="np"
524
+ )
525
+ print("gen time passed:", time.time() - start)
526
+
527
+ raw_frames_np = result.frames[0] # Returns (T, H, W, C) float32
528
+ frame_factor = frame_multiplier // FIXED_FPS
529
+ if frame_factor > 1:
530
+ start = time.time()
531
+ print(f"Processing frames (RIFE Multiplier: {frame_factor}x)...")
532
+ rife_model.device()
533
+ rife_model.flownet = rife_model.flownet.half()
534
+ final_frames = interpolate_bits(raw_frames_np, multiplier=int(frame_factor))
535
+ print("Interpolation time passed:", time.time() - start)
536
+ else:
537
+ final_frames = list(raw_frames_np)
538
 
539
+ final_fps = FIXED_FPS * int(frame_factor)
540
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
541
+ video_path = tmpfile.name
 
 
 
542
 
543
+ start = time.time()
544
+ with tqdm(total=3, desc="Rendering Media", unit="clip") as pbar:
545
+ pbar.update(2)
546
+ export_to_video(final_frames, video_path, fps=final_fps, quality=quality)
547
+ pbar.update(1)
548
+ print(f"Export time passed, {final_fps} FPS:", time.time() - start)
549
+
550
+ video_ready = True
551
+ return video_path, task_name
552
+ finally:
553
+ # 无论模型、插帧还是编码在哪一步失败,都恢复可供下一任务复用的全局管线。
554
+ cleanup_error = None
555
+ try:
556
+ if lora_attempted:
557
+ lora_loader.unload_lora(pipe)
558
+ except Exception as exc:
559
+ cleanup_error = exc
560
+ try:
561
+ pipe.scheduler = copy.deepcopy(original_scheduler)
562
+ except Exception as exc:
563
+ cleanup_error = cleanup_error or exc
564
+ result = None
565
+ raw_frames_np = None
566
+ final_frames = None
567
+ try:
568
+ clear_vram()
569
+ except Exception as exc:
570
+ cleanup_error = cleanup_error or exc
571
+ if video_path is not None and (not video_ready or cleanup_error is not None):
572
+ try:
573
+ os.remove(video_path)
574
+ except FileNotFoundError:
575
+ pass
576
+ except OSError as exc:
577
+ print(f"Failed to remove temporary video: {type(exc).__name__}")
578
+ if cleanup_error is not None:
579
+ raise RuntimeError("Inference cleanup failed.") from cleanup_error
580
 
581
 
582
  def generate_video(
 
679
  return (video_path if video_component else None), video_path, current_seed
680
 
681
 
682
+ def generate_video_ui(
683
+ input_image,
684
+ last_image,
685
+ prompt,
686
+ steps=4,
687
+ negative_prompt=default_negative_prompt,
688
+ duration_seconds=MAX_DURATION,
689
+ guidance_scale=1,
690
+ guidance_scale_2=1,
691
+ seed=42,
692
+ randomize_seed=False,
693
+ quality=5,
694
+ scheduler="UniPCMultistep",
695
+ flow_shift=6.0,
696
+ frame_multiplier=16,
697
+ safe_mode=False,
698
+ lora_groups=None,
699
+ video_component=True,
700
+ progress=gr.Progress(track_tqdm=True),
701
+ ):
702
+ """让现有 UI 通过与自定义 API 共用的非阻塞推理槽位生成视频。
703
+
704
+ Args:
705
+ input_image: UI 上传的首图。
706
+ last_image: 可选尾图。
707
+ prompt: 正向提示词。
708
+ steps: 推理步数。
709
+ negative_prompt: 负向提示词。
710
+ duration_seconds: 目标视频时长。
711
+ guidance_scale: 高噪声阶段引导强度。
712
+ guidance_scale_2: 低噪声阶段引导强度。
713
+ seed: 固定随机种子。
714
+ randomize_seed: 是否在生成前随机化种子。
715
+ quality: MP4 编码质量。
716
+ scheduler: 调度器名称。
717
+ flow_shift: 调度器流偏移值。
718
+ frame_multiplier: 输出帧率倍数对应的帧率值。
719
+ safe_mode: 是否申请额外 ZeroGPU 运行时间。
720
+ lora_groups: 当前 LoRA 下拉框选择的精确名称列表。
721
+ video_component: 是否把结果同时显示在视频组件中。
722
+ progress: Gradio 进度对象。
723
+
724
+ Returns:
725
+ 与原 generate_video 一致的视频组件路径、下载路径和实际 seed。
726
+ """
727
+ if not INFERENCE_SLOT.acquire(blocking=False):
728
+ raise gr.Error("The generation service is busy. Please retry shortly.")
729
+ try:
730
+ return generate_video(
731
+ input_image,
732
+ last_image,
733
+ prompt,
734
+ steps,
735
+ negative_prompt,
736
+ duration_seconds,
737
+ guidance_scale,
738
+ guidance_scale_2,
739
+ seed,
740
+ randomize_seed,
741
+ quality,
742
+ scheduler,
743
+ flow_shift,
744
+ frame_multiplier,
745
+ safe_mode,
746
+ lora_groups,
747
+ video_component,
748
+ progress,
749
+ )
750
+ finally:
751
+ INFERENCE_SLOT.release()
752
+
753
+
754
+ def build_gradio_request(headers: dict[str, str], job_id: str) -> gr.Request:
755
+ """为后台 ZeroGPU 调用重建最小 Gradio 请求对象。
756
+
757
+ Args:
758
+ headers: 仅含 ZeroGPU 身份所需字段的筛选后请求头。
759
+ job_id: 用作隔离会话哈希的自定义任务标识。
760
+
761
+ Returns:
762
+ 可供 spaces.GPU 装饰器读取身份信息的 Gradio 请求。
763
+ """
764
+ return gr.Request(
765
+ username=headers.get("x-gradio-user"),
766
+ session_hash=job_id,
767
+ headers=dict(headers),
768
+ query_params={},
769
+ cookies={},
770
+ path_params={},
771
+ client={"host": "127.0.0.1", "port": 0},
772
+ url="",
773
+ )
774
+
775
+
776
+ def execute_video_job(
777
+ payload: VideoJobRequest,
778
+ input_image: Image.Image,
779
+ last_image: Image.Image | None,
780
+ zero_gpu_headers: dict[str, str],
781
+ job_id: str,
782
+ ) -> tuple[str, int]:
783
+ """在后台线程恢复 Gradio 上下文并调用现有视频生成链路。
784
+
785
+ Args:
786
+ payload: 已通过公开 Schema 校验的命名任务参数。
787
+ input_image: 已安全抓取并解码的首图。
788
+ last_image: 已安全抓取并解码的可选尾图。
789
+ zero_gpu_headers: 仅含短效 ZeroGPU 身份字段的请求头。
790
+ job_id: 用于隔离后台 Gradio 请求上下文的任务标识。
791
+
792
+ Returns:
793
+ 现有生成函数产生的临时 MP4 明确路径与实际使用的 seed。
794
+ """
795
+ request_context = build_gradio_request(zero_gpu_headers, job_id)
796
+
797
+ # 通用 ContextVar 绑定器保证成功或异��时都恢复四个 Gradio 本地上下文。
798
+ with bind_context_values(
799
+ (
800
+ (LocalContext.request, request_context),
801
+ (LocalContext.blocks, demo),
802
+ (LocalContext.in_event_listener, True),
803
+ (LocalContext.event_id, None),
804
+ )
805
+ ):
806
+ _, video_path, used_seed = generate_video(
807
+ input_image=input_image,
808
+ last_image=last_image,
809
+ prompt=payload.prompt,
810
+ steps=payload.steps,
811
+ negative_prompt=payload.negative_prompt,
812
+ duration_seconds=payload.duration_seconds,
813
+ guidance_scale=payload.guidance_scale,
814
+ guidance_scale_2=payload.guidance_scale_2,
815
+ seed=payload.seed,
816
+ randomize_seed=payload.randomize_seed,
817
+ quality=payload.quality,
818
+ scheduler=payload.scheduler,
819
+ flow_shift=payload.flow_shift,
820
+ frame_multiplier=payload.frame_multiplier,
821
+ safe_mode=payload.safe_mode,
822
+ lora_groups=payload.lora_groups,
823
+ video_component=False,
824
+ )
825
+ return video_path, int(used_seed)
826
+
827
+
828
+ VIDEO_JOB_API = VideoJobAPI(
829
+ settings=VIDEO_JOB_SETTINGS,
830
+ executor=execute_video_job,
831
+ allowed_loras=set(lora_loader.get_lora_choices()),
832
+ inference_slot=INFERENCE_SLOT,
833
+ )
834
+ JOB_API_LIFESPAN = create_job_api_lifespan(VIDEO_JOB_API)
835
+
836
+
837
  CSS = """
838
  #hidden-timestamp {
839
  opacity: 0;
 
912
  ]
913
 
914
  generate_button.click(
915
+ fn=generate_video_ui,
916
+ inputs=ui_inputs,
917
+ outputs=[video_output, file_output, seed_input],
918
+ api_name="generate_video",
919
+ concurrency_limit=1,
920
  )
921
 
922
  # --- Frame Grabbing Events ---
 
936
  )
937
 
938
  if __name__ == "__main__":
939
+ demo.queue(default_concurrency_limit=1).launch(
940
  mcp_server=True,
941
  css=CSS,
942
  show_error=True,
943
+ ssr_mode=False,
944
+ app_kwargs={"lifespan": JOB_API_LIFESPAN},
945
+ )
lora_loader.py CHANGED
@@ -195,7 +195,12 @@ def load_lora_to_pipe(pipe, group_name, adapter_name="lora"):
195
 
196
 
197
  def unload_lora(pipe):
198
- try:
199
- pipe.unload_lora_weights()
200
- except:
201
- pass
 
 
 
 
 
 
195
 
196
 
197
  def unload_lora(pipe):
198
+ """严格卸载动态 LoRA,使调用方能够感知并处理清理失败。
199
+
200
+ Args:
201
+ pipe: 当前全局 Wan 视频推理管线。
202
+
203
+ Returns:
204
+ 卸载完成后不返回数据;底层失败会原样抛给调用方。
205
+ """
206
+ pipe.unload_lora_weights()
requirements.txt CHANGED
@@ -9,6 +9,8 @@ imageio
9
  imageio-ffmpeg
10
  opencv-python
11
  torchao==0.17.0
 
 
12
 
13
  numpy>=1.16, <=1.23.5
14
  # tqdm>=4.35.0
 
9
  imageio-ffmpeg
10
  opencv-python
11
  torchao==0.17.0
12
+ httpx==0.28.1
13
+ Pillow>=10,<13
14
 
15
  numpy>=1.16, <=1.23.5
16
  # tqdm>=4.35.0
tests/test_video_job_api.py ADDED
@@ -0,0 +1,1084 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ import socket
6
+ import tempfile
7
+ import threading
8
+ import time
9
+ import unittest
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from contextvars import ContextVar
12
+ from pathlib import Path
13
+ from unittest.mock import patch
14
+ from urllib.parse import urlsplit
15
+
16
+ import httpx
17
+ from fastapi import FastAPI, HTTPException
18
+ from fastapi.testclient import TestClient
19
+ from PIL import Image
20
+
21
+ from video_job_api import (
22
+ ImageSourceError,
23
+ VideoJobAPI,
24
+ VideoJobRequest,
25
+ VideoJobSettings,
26
+ _parse_single_byte_range,
27
+ bind_context_values,
28
+ decode_image_bytes,
29
+ fetch_remote_image,
30
+ validate_image_url,
31
+ )
32
+
33
+
34
+ API_KEY = "k" * 48
35
+ VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42fake-video-payload"
36
+
37
+
38
+ class _TrackedImage:
39
+ def __init__(self, fail_on_close: bool = False) -> None:
40
+ self.closed = False
41
+ self.fail_on_close = fail_on_close
42
+
43
+ def close(self) -> None:
44
+ self.closed = True
45
+ if self.fail_on_close:
46
+ raise RuntimeError("close failed")
47
+
48
+
49
+ class _FakeStreamResponse:
50
+ def __init__(
51
+ self,
52
+ status_code: int,
53
+ body: bytes,
54
+ content_type: str = "image/png",
55
+ extra_headers: dict[str, str] | None = None,
56
+ peer_address: str = "93.184.216.34",
57
+ ) -> None:
58
+ self.status_code = status_code
59
+ self.body = body
60
+ self.headers = {
61
+ "content-type": content_type,
62
+ "content-length": str(len(body)),
63
+ }
64
+ if extra_headers:
65
+ self.headers.update(extra_headers)
66
+ self.extensions = {
67
+ "network_stream": type(
68
+ "NetworkStreamStub",
69
+ (),
70
+ {
71
+ "get_extra_info": lambda self, name: (
72
+ (peer_address, 443) if name == "server_addr" else None
73
+ )
74
+ },
75
+ )()
76
+ }
77
+
78
+ def __enter__(self) -> "_FakeStreamResponse":
79
+ return self
80
+
81
+ def __exit__(self, exc_type, exc, traceback) -> bool:
82
+ return False
83
+
84
+ def iter_bytes(self):
85
+ yield self.body
86
+
87
+
88
+ class VideoJobAPITest(unittest.TestCase):
89
+ def setUp(self) -> None:
90
+ self.clients: list[TestClient] = []
91
+ self.result_dirs: list[Path] = []
92
+ self.release_events: list[threading.Event] = []
93
+
94
+ def tearDown(self) -> None:
95
+ for release_event in self.release_events:
96
+ release_event.set()
97
+ time.sleep(0.02)
98
+ for client in self.clients:
99
+ client.close()
100
+ for result_dir in self.result_dirs:
101
+ if not result_dir.exists():
102
+ continue
103
+ # 测试清理也只对枚举出的明确文件逐一 unlink,不做递归目录删除。
104
+ for child_path in tuple(result_dir.iterdir()):
105
+ if child_path.is_file():
106
+ child_path.unlink(missing_ok=True)
107
+ try:
108
+ result_dir.rmdir()
109
+ except OSError:
110
+ pass
111
+
112
+ def _new_result_dir(self) -> Path:
113
+ """创建并登记一个测试专用结果目录。
114
+
115
+ Args:
116
+ 此辅助方法不接收参数。
117
+
118
+ Returns:
119
+ 当前测试可安全写入的唯一临时目录。
120
+ """
121
+ result_dir = Path(tempfile.mkdtemp(prefix="i2v-job-api-test-"))
122
+ self.result_dirs.append(result_dir)
123
+ return result_dir
124
+
125
+ def _settings(self, **overrides) -> VideoJobSettings:
126
+ """构造不读取环境变量的隔离任务设置。
127
+
128
+ Args:
129
+ overrides: 要覆盖的 VideoJobSettings 字段。
130
+
131
+ Returns:
132
+ 指向测试专用目录的任务设置。
133
+ """
134
+ values = {
135
+ "api_key": API_KEY,
136
+ "allowed_hosts": frozenset({"allowed.example"}),
137
+ "result_dir": self._new_result_dir(),
138
+ "result_ttl_seconds": 1800,
139
+ "poll_after_seconds": 1,
140
+ "fetch_timeout_seconds": 15.0,
141
+ "max_image_bytes": 20 * 1024 * 1024,
142
+ "max_image_pixels": 40_000_000,
143
+ "space_host": "https://space.example",
144
+ }
145
+ values.update(overrides)
146
+ return VideoJobSettings(**values)
147
+
148
+ @staticmethod
149
+ def _payload(**overrides) -> dict:
150
+ """生成最小合法 API 请求体。
151
+
152
+ Args:
153
+ overrides: 要覆盖或增加的 JSON 字段。
154
+
155
+ Returns:
156
+ 可直接提交给 POST /api/jobs 的字典。
157
+ """
158
+ payload = {
159
+ "input_image_url": "https://allowed.example/input.png?source=private",
160
+ "prompt": "animate naturally",
161
+ "randomize_seed": False,
162
+ "seed": 42,
163
+ "lora_groups": [],
164
+ }
165
+ payload.update(overrides)
166
+ return payload
167
+
168
+ @staticmethod
169
+ def _headers(**overrides) -> dict[str, str]:
170
+ """生成包含 API key 与模拟 ZeroGPU 身份的请求头。
171
+
172
+ Args:
173
+ overrides: 要覆盖或增加的请求头。
174
+
175
+ Returns:
176
+ 可直接传给 TestClient 的请求头字典。
177
+ """
178
+ headers = {"X-API-Key": API_KEY, "X-IP-Token": "zero-gpu-token"}
179
+ headers.update(overrides)
180
+ return headers
181
+
182
+ def _make_service(
183
+ self,
184
+ *,
185
+ executor=None,
186
+ image_fetcher=None,
187
+ inference_slot: threading.Lock | None = None,
188
+ settings: VideoJobSettings | None = None,
189
+ allowed_loras: set[str] | None = None,
190
+ add_catch_all: bool = False,
191
+ ) -> tuple[TestClient, VideoJobAPI, list[_TrackedImage], dict[str, int]]:
192
+ """创建不导入模型的 FastAPI 测试服务。
193
+
194
+ Args:
195
+ executor: 可选假视频执行器。
196
+ image_fetcher: 可选假图片抓取器。
197
+ inference_slot: 可选外部共享锁。
198
+ settings: 可选任务设置。
199
+ allowed_loras: 可选合法 LoRA 精确名称集合。
200
+ add_catch_all: 是否先注册一个模拟 Gradio 的通配路由。
201
+
202
+ Returns:
203
+ TestClient、VideoJobAPI、已创建图片列表与执行次数容器。
204
+ """
205
+ settings = settings or self._settings()
206
+ created_images: list[_TrackedImage] = []
207
+ counters = {"fetch": 0, "execute": 0}
208
+ counter_lock = threading.Lock()
209
+
210
+ if image_fetcher is None:
211
+ def image_fetcher(url, current_settings):
212
+ del url, current_settings
213
+ with counter_lock:
214
+ counters["fetch"] += 1
215
+ image = _TrackedImage()
216
+ created_images.append(image)
217
+ return image
218
+
219
+ if executor is None:
220
+ def executor(payload, input_image, last_image, headers, job_id):
221
+ del input_image, last_image, headers, job_id
222
+ with counter_lock:
223
+ counters["execute"] += 1
224
+ execution_index = counters["execute"]
225
+ source_path = settings.result_dir / f"source-{execution_index}.mp4"
226
+ source_path.write_bytes(VIDEO_BYTES)
227
+ return source_path, payload.seed
228
+
229
+ api = VideoJobAPI(
230
+ settings=settings,
231
+ executor=executor,
232
+ allowed_loras=allowed_loras or {"Valid LoRA"},
233
+ inference_slot=inference_slot or threading.Lock(),
234
+ image_fetcher=image_fetcher,
235
+ )
236
+ app = FastAPI()
237
+ if add_catch_all:
238
+ @app.api_route("/{path:path}", methods=["GET", "POST", "HEAD"])
239
+ def catch_all(path: str):
240
+ return {"catch_all": path}
241
+
242
+ api.install_on_app(app)
243
+ client = TestClient(app, base_url="https://space.example")
244
+ self.clients.append(client)
245
+ return client, api, created_images, counters
246
+
247
+ def _wait_for_terminal(
248
+ self,
249
+ client: TestClient,
250
+ job_id: str,
251
+ timeout_seconds: float = 3.0,
252
+ ):
253
+ """轮询测试任务直到进入成功或失败终态。
254
+
255
+ Args:
256
+ client: 当前隔离 FastAPI 客户端。
257
+ job_id: 要轮询的任务标识。
258
+ timeout_seconds: 测试允许的最长等待时间。
259
+
260
+ Returns:
261
+ 第一个非 202 状态响应。
262
+ """
263
+ deadline = time.monotonic() + timeout_seconds
264
+ while time.monotonic() < deadline:
265
+ response = client.get(
266
+ f"/api/jobs/{job_id}",
267
+ headers={"X-API-Key": API_KEY},
268
+ )
269
+ if response.status_code != 202:
270
+ return response
271
+ time.sleep(0.01)
272
+ self.fail(f"job {job_id} did not reach a terminal state")
273
+
274
+ def test_auth_schema_zero_gpu_and_route_precedence(self) -> None:
275
+ client, api, _, counters = self._make_service(add_catch_all=True)
276
+
277
+ unauthorized = client.post(
278
+ "/api/jobs",
279
+ json=self._payload(),
280
+ headers={"X-IP-Token": "token"},
281
+ )
282
+ self.assertEqual(unauthorized.status_code, 401)
283
+ self.assertEqual(counters["fetch"], 0)
284
+
285
+ unknown_field = client.post(
286
+ "/api/jobs",
287
+ json=self._payload(video_component=False),
288
+ headers=self._headers(),
289
+ )
290
+ self.assertEqual(unknown_field.status_code, 422)
291
+
292
+ for bad_payload in (
293
+ self._payload(steps=0),
294
+ self._payload(duration_seconds=20.2),
295
+ self._payload(frame_multiplier=24),
296
+ self._payload(prompt=" "),
297
+ self._payload(seed=2**31),
298
+ self._payload(scheduler="unknown"),
299
+ self._payload(input_image_url="http://allowed.example/input.png"),
300
+ ):
301
+ with self.subTest(payload=bad_payload):
302
+ response = client.post(
303
+ "/api/jobs",
304
+ json=bad_payload,
305
+ headers=self._headers(),
306
+ )
307
+ self.assertEqual(response.status_code, 422)
308
+
309
+ missing_identity = client.post(
310
+ "/api/jobs",
311
+ json=self._payload(),
312
+ headers={"X-API-Key": API_KEY},
313
+ )
314
+ self.assertEqual(missing_identity.status_code, 503)
315
+ self.assertEqual(missing_identity.headers["Retry-After"], "3")
316
+
317
+ with self.assertRaises(HTTPException) as unicode_key_error:
318
+ fake_request = type(
319
+ "RequestStub",
320
+ (),
321
+ {"headers": {"x-api-key": "密钥"}},
322
+ )()
323
+ api._require_api_key(fake_request)
324
+ self.assertEqual(unicode_key_error.exception.status_code, 401)
325
+
326
+ def test_schema_defaults_and_exact_lora_validation(self) -> None:
327
+ model = VideoJobRequest(input_image_url="https://allowed.example/a.png")
328
+ self.assertEqual(model.steps, 6)
329
+ self.assertEqual(model.duration_seconds, 3.5)
330
+ self.assertEqual(model.quality, 6)
331
+ self.assertEqual(model.frame_multiplier, 16)
332
+ self.assertTrue(model.randomize_seed)
333
+ self.assertTrue(model.safe_mode)
334
+
335
+ client, _, _, _ = self._make_service(allowed_loras={"Exact (HIGH only)"})
336
+ rejected = client.post(
337
+ "/api/jobs",
338
+ json=self._payload(lora_groups=["Exact"]),
339
+ headers=self._headers(),
340
+ )
341
+ self.assertEqual(rejected.status_code, 422)
342
+
343
+ accepted = client.post(
344
+ "/api/jobs",
345
+ json=self._payload(lora_groups=["Exact (HIGH only)"]),
346
+ headers=self._headers(),
347
+ )
348
+ self.assertEqual(accepted.status_code, 202)
349
+ self._wait_for_terminal(client, accepted.json()["job_id"])
350
+
351
+ def test_url_policy_requires_exact_public_https_host(self) -> None:
352
+ settings = self._settings()
353
+ public_record = (
354
+ socket.AF_INET,
355
+ socket.SOCK_STREAM,
356
+ socket.IPPROTO_TCP,
357
+ "",
358
+ ("93.184.216.34", 443),
359
+ )
360
+ with patch("video_job_api.socket.getaddrinfo", return_value=[public_record]):
361
+ validated = validate_image_url(
362
+ "https://allowed.example/image.png?private=query",
363
+ settings,
364
+ )
365
+ self.assertEqual(validated.host, "allowed.example")
366
+
367
+ for invalid_url in (
368
+ "http://allowed.example/image.png",
369
+ "https://user:password@allowed.example/image.png",
370
+ "https://allowed.example:444/image.png",
371
+ "https://sub.allowed.example/image.png",
372
+ "https://allowed.example/image.png#fragment",
373
+ ):
374
+ with self.subTest(url=invalid_url):
375
+ with self.assertRaises(ImageSourceError) as invalid_error:
376
+ validate_image_url(invalid_url, settings)
377
+ self.assertEqual(invalid_error.exception.status_code, 400)
378
+
379
+ private_record = (
380
+ socket.AF_INET,
381
+ socket.SOCK_STREAM,
382
+ socket.IPPROTO_TCP,
383
+ "",
384
+ ("127.0.0.1", 443),
385
+ )
386
+ mixed_records = [public_record, private_record]
387
+ with patch("video_job_api.socket.getaddrinfo", return_value=mixed_records):
388
+ with self.assertRaises(ImageSourceError) as private_error:
389
+ validate_image_url("https://allowed.example/image.png", settings)
390
+ self.assertEqual(private_error.exception.status_code, 400)
391
+
392
+ with patch(
393
+ "video_job_api.socket.getaddrinfo",
394
+ side_effect=socket.gaierror("secret resolver detail"),
395
+ ):
396
+ with self.assertRaises(ImageSourceError) as dns_error:
397
+ validate_image_url("https://allowed.example/image.png", settings)
398
+ self.assertEqual(dns_error.exception.status_code, 502)
399
+ self.assertNotIn("secret", dns_error.exception.public_message)
400
+
401
+ def slow_resolver(*args, **kwargs):
402
+ del args, kwargs
403
+ time.sleep(0.2)
404
+ return [public_record]
405
+
406
+ short_dns_settings = self._settings(fetch_timeout_seconds=0.02)
407
+ started_at = time.monotonic()
408
+ with patch("video_job_api.socket.getaddrinfo", side_effect=slow_resolver):
409
+ with self.assertRaises(ImageSourceError) as dns_timeout:
410
+ validate_image_url(
411
+ "https://allowed.example/image.png",
412
+ short_dns_settings,
413
+ )
414
+ self.assertEqual(dns_timeout.exception.status_code, 504)
415
+ self.assertLess(time.monotonic() - started_at, 0.15)
416
+
417
+ def test_image_decode_uses_actual_format_and_enforces_limits(self) -> None:
418
+ settings = self._settings(max_image_pixels=4)
419
+ png_buffer = io.BytesIO()
420
+ Image.new("RGB", (2, 2), "red").save(png_buffer, format="PNG")
421
+ png_bytes = png_buffer.getvalue()
422
+
423
+ decoded = decode_image_bytes(png_bytes, "application/octet-stream", settings)
424
+ self.assertEqual(decoded.mode, "RGB")
425
+ self.assertEqual(decoded.size, (2, 2))
426
+ decoded.close()
427
+
428
+ with self.assertRaises(ImageSourceError):
429
+ decode_image_bytes(
430
+ png_bytes,
431
+ "image/png",
432
+ self._settings(max_image_bytes=len(png_bytes) - 1),
433
+ )
434
+
435
+ with self.assertRaises(ImageSourceError):
436
+ decode_image_bytes(
437
+ png_bytes,
438
+ "image/png",
439
+ self._settings(max_image_pixels=3),
440
+ )
441
+
442
+ gif_buffer = io.BytesIO()
443
+ Image.new("RGB", (1, 1), "blue").save(gif_buffer, format="GIF")
444
+ with self.assertRaises(ImageSourceError):
445
+ decode_image_bytes(gif_buffer.getvalue(), "image/png", settings)
446
+
447
+ with self.assertRaises(ImageSourceError):
448
+ decode_image_bytes(b"not-an-image", "image/png", settings)
449
+
450
+ def test_fetch_has_fresh_headers_no_redirect_and_public_error_mapping(self) -> None:
451
+ settings = self._settings()
452
+ png_buffer = io.BytesIO()
453
+ Image.new("RGB", (1, 1), "green").save(png_buffer, format="PNG")
454
+ png_bytes = png_buffer.getvalue()
455
+ public_record = (
456
+ socket.AF_INET,
457
+ socket.SOCK_STREAM,
458
+ socket.IPPROTO_TCP,
459
+ "",
460
+ ("93.184.216.34", 443),
461
+ )
462
+ captured: dict = {}
463
+
464
+ class FakeClient:
465
+ def __init__(self, **kwargs):
466
+ captured["client_kwargs"] = kwargs
467
+
468
+ def __enter__(self):
469
+ return self
470
+
471
+ def __exit__(self, exc_type, exc, traceback):
472
+ return False
473
+
474
+ def close(self):
475
+ captured["closed"] = True
476
+ response = captured.get("response")
477
+ close_event = getattr(response, "close_event", None)
478
+ if close_event is not None:
479
+ close_event.set()
480
+
481
+ def stream(self, method, url, headers):
482
+ captured["method"] = method
483
+ captured["url"] = url
484
+ captured["headers"] = dict(headers)
485
+ return captured["response"]
486
+
487
+ with patch("video_job_api.socket.getaddrinfo", return_value=[public_record]), patch(
488
+ "video_job_api.httpx.Client",
489
+ FakeClient,
490
+ ):
491
+ captured["response"] = _FakeStreamResponse(200, png_bytes)
492
+ image = fetch_remote_image(
493
+ "https://allowed.example/image.png?do-not-log=this",
494
+ settings,
495
+ )
496
+ image.close()
497
+ self.assertFalse(captured["client_kwargs"]["follow_redirects"])
498
+ self.assertFalse(captured["client_kwargs"]["trust_env"])
499
+ self.assertEqual(
500
+ captured["headers"],
501
+ {"Accept": "image/png,image/jpeg,image/webp"},
502
+ )
503
+ for sensitive_header in (
504
+ "Authorization",
505
+ "Cookie",
506
+ "X-API-Key",
507
+ "X-IP-Token",
508
+ ):
509
+ self.assertNotIn(sensitive_header, captured["headers"])
510
+
511
+ captured["response"] = _FakeStreamResponse(302, b"")
512
+ with self.assertRaises(ImageSourceError) as redirect_error:
513
+ fetch_remote_image("https://allowed.example/redirect", settings)
514
+ self.assertEqual(redirect_error.exception.status_code, 400)
515
+
516
+ captured["response"] = _FakeStreamResponse(503, b"")
517
+ with self.assertRaises(ImageSourceError) as upstream_error:
518
+ fetch_remote_image("https://allowed.example/unavailable", settings)
519
+ self.assertEqual(upstream_error.exception.status_code, 502)
520
+
521
+ captured["response"] = _FakeStreamResponse(
522
+ 200,
523
+ png_bytes,
524
+ peer_address="127.0.0.1",
525
+ )
526
+ with self.assertRaises(ImageSourceError) as rebound_error:
527
+ fetch_remote_image("https://allowed.example/rebound", settings)
528
+ self.assertEqual(rebound_error.exception.status_code, 400)
529
+
530
+ captured["response"] = _FakeStreamResponse(
531
+ 200,
532
+ png_bytes,
533
+ extra_headers={"content-length": str(settings.max_image_bytes + 1)},
534
+ )
535
+ with self.assertRaises(ImageSourceError) as size_error:
536
+ fetch_remote_image("https://allowed.example/large", settings)
537
+ self.assertEqual(size_error.exception.status_code, 400)
538
+
539
+ streamed_limit_settings = self._settings(
540
+ max_image_bytes=len(png_bytes) - 1,
541
+ )
542
+ captured["response"] = _FakeStreamResponse(200, png_bytes)
543
+ captured["response"].headers.pop("content-length")
544
+ with self.assertRaises(ImageSourceError) as streamed_size_error:
545
+ fetch_remote_image(
546
+ "https://allowed.example/streamed-large",
547
+ streamed_limit_settings,
548
+ )
549
+ self.assertEqual(streamed_size_error.exception.status_code, 400)
550
+
551
+ captured["response"] = _FakeStreamResponse(200, png_bytes)
552
+ with patch("video_job_api.time.monotonic", side_effect=[0.0, 0.0, 16.0]):
553
+ with self.assertRaises(ImageSourceError) as timeout_error:
554
+ fetch_remote_image("https://allowed.example/slow", settings)
555
+ self.assertEqual(timeout_error.exception.status_code, 504)
556
+
557
+ class DeadlineResponse(_FakeStreamResponse):
558
+ def __init__(self):
559
+ super().__init__(200, png_bytes)
560
+ self.close_event = threading.Event()
561
+
562
+ def iter_bytes(self):
563
+ self.close_event.wait(timeout=0.5)
564
+ raise httpx.ReadError("closed by deadline")
565
+
566
+ deadline_settings = self._settings(fetch_timeout_seconds=0.05)
567
+ captured["response"] = DeadlineResponse()
568
+ deadline_started = time.monotonic()
569
+ with self.assertRaises(ImageSourceError) as hard_timeout_error:
570
+ fetch_remote_image(
571
+ "https://allowed.example/hard-timeout",
572
+ deadline_settings,
573
+ )
574
+ self.assertEqual(hard_timeout_error.exception.status_code, 504)
575
+ self.assertLess(time.monotonic() - deadline_started, 0.2)
576
+
577
+ def test_second_image_fetch_failure_closes_first_and_releases_slot(self) -> None:
578
+ shared_slot = threading.Lock()
579
+ first_image = _TrackedImage(fail_on_close=True)
580
+ fetch_count = 0
581
+
582
+ def fetcher(url, settings):
583
+ nonlocal fetch_count
584
+ del url, settings
585
+ fetch_count += 1
586
+ if fetch_count == 1:
587
+ return first_image
588
+ raise ImageSourceError(504, "The image download timed out.")
589
+
590
+ client, _, _, _ = self._make_service(
591
+ image_fetcher=fetcher,
592
+ inference_slot=shared_slot,
593
+ )
594
+ response = client.post(
595
+ "/api/jobs",
596
+ json=self._payload(
597
+ last_image_url="https://allowed.example/last.png",
598
+ ),
599
+ headers=self._headers(),
600
+ )
601
+ self.assertEqual(response.status_code, 504)
602
+ self.assertTrue(first_image.closed)
603
+ self.assertTrue(shared_slot.acquire(blocking=False))
604
+ shared_slot.release()
605
+
606
+ def test_success_dual_image_status_download_head_and_ranges(self) -> None:
607
+ seen: dict = {}
608
+
609
+ def executor(payload, input_image, last_image, headers, job_id):
610
+ seen.update(
611
+ {
612
+ "payload": payload,
613
+ "input_image": input_image,
614
+ "last_image": last_image,
615
+ "headers": dict(headers),
616
+ "job_id": job_id,
617
+ }
618
+ )
619
+ source_path = settings.result_dir / "source.mp4"
620
+ source_path.write_bytes(VIDEO_BYTES)
621
+ return source_path, 77
622
+
623
+ settings = self._settings()
624
+ client, api, images, _ = self._make_service(
625
+ settings=settings,
626
+ executor=executor,
627
+ )
628
+ created = client.post(
629
+ "/api/jobs",
630
+ json=self._payload(
631
+ last_image_url="https://allowed.example/last.webp",
632
+ seed=77,
633
+ ),
634
+ headers=self._headers(
635
+ **{
636
+ "X-Gradio-User": "caller",
637
+ "Authorization": "Bearer must-not-be-retained",
638
+ "Cookie": "must-not-be-retained",
639
+ }
640
+ ),
641
+ )
642
+ self.assertEqual(created.status_code, 202)
643
+ self.assertEqual(created.headers["Cache-Control"], "no-store")
644
+ self.assertEqual(created.headers["Location"], created.json()["status_url"])
645
+ job_id = created.json()["job_id"]
646
+
647
+ terminal = self._wait_for_terminal(client, job_id)
648
+ self.assertEqual(terminal.status_code, 200)
649
+ self.assertEqual(terminal.json()["used_seed"], 77)
650
+ self.assertEqual(seen["job_id"], job_id)
651
+ self.assertEqual(
652
+ seen["headers"],
653
+ {"x-ip-token": "zero-gpu-token", "x-gradio-user": "caller"},
654
+ )
655
+ self.assertIsNotNone(seen["last_image"])
656
+ self.assertTrue(all(image.closed for image in images))
657
+ self.assertEqual(api.jobs[job_id].zero_gpu_headers, {})
658
+
659
+ video_url = terminal.json()["video_url"]
660
+ parsed_video_url = urlsplit(video_url)
661
+ video_path = parsed_video_url.path
662
+ token = parsed_video_url.query.split("=", 1)[1]
663
+
664
+ self.assertEqual(client.get(video_path).status_code, 401)
665
+ self.assertEqual(
666
+ client.get(video_path, params={"token": "令牌"}).status_code,
667
+ 401,
668
+ )
669
+
670
+ head = client.head(video_path, params={"token": token}, headers={"Range": "bytes=0-0"})
671
+ self.assertEqual(head.status_code, 200)
672
+ self.assertEqual(head.headers["Content-Type"], "video/mp4")
673
+ self.assertEqual(int(head.headers["Content-Length"]), len(VIDEO_BYTES))
674
+ self.assertEqual(head.headers["Accept-Ranges"], "bytes")
675
+ self.assertEqual(head.headers["Access-Control-Allow-Origin"], "*")
676
+
677
+ complete = client.get(video_path, params={"token": token})
678
+ self.assertEqual(complete.status_code, 200)
679
+ self.assertEqual(complete.content, VIDEO_BYTES)
680
+ self.assertEqual(complete.headers["Cache-Control"], "private, max-age=300")
681
+
682
+ for range_value, expected_content, expected_range in (
683
+ ("bytes=0-0", VIDEO_BYTES[:1], f"bytes 0-0/{len(VIDEO_BYTES)}"),
684
+ ("bytes=5-", VIDEO_BYTES[5:], f"bytes 5-{len(VIDEO_BYTES)-1}/{len(VIDEO_BYTES)}"),
685
+ ("bytes=-3", VIDEO_BYTES[-3:], f"bytes {len(VIDEO_BYTES)-3}-{len(VIDEO_BYTES)-1}/{len(VIDEO_BYTES)}"),
686
+ ("bytes=0-999", VIDEO_BYTES, f"bytes 0-{len(VIDEO_BYTES)-1}/{len(VIDEO_BYTES)}"),
687
+ ):
688
+ with self.subTest(range_value=range_value):
689
+ ranged = client.get(
690
+ video_path,
691
+ params={"token": token},
692
+ headers={"Range": range_value},
693
+ )
694
+ self.assertEqual(ranged.status_code, 206)
695
+ self.assertEqual(ranged.content, expected_content)
696
+ self.assertEqual(ranged.headers["Content-Range"], expected_range)
697
+ self.assertEqual(
698
+ int(ranged.headers["Content-Length"]),
699
+ len(expected_content),
700
+ )
701
+
702
+ for invalid_range in (
703
+ "",
704
+ "items=0-1",
705
+ "bytes=0-1,3-4",
706
+ "bytes=-0",
707
+ f"bytes={len(VIDEO_BYTES)}-",
708
+ ):
709
+ with self.subTest(invalid_range=invalid_range):
710
+ rejected = client.get(
711
+ video_path,
712
+ params={"token": token},
713
+ headers={"Range": invalid_range},
714
+ )
715
+ self.assertEqual(rejected.status_code, 416)
716
+ self.assertEqual(
717
+ rejected.headers["Content-Range"],
718
+ f"bytes */{len(VIDEO_BYTES)}",
719
+ )
720
+ self.assertEqual(rejected.headers["Access-Control-Allow-Origin"], "*")
721
+ self.assertEqual(api.jobs[job_id].active_downloads, 0)
722
+
723
+ def test_idempotent_replay_conflict_and_busy_submission(self) -> None:
724
+ release_event = threading.Event()
725
+ started_event = threading.Event()
726
+ self.release_events.append(release_event)
727
+ settings = self._settings()
728
+ execution_count = 0
729
+ count_lock = threading.Lock()
730
+
731
+ def blocking_executor(payload, input_image, last_image, headers, job_id):
732
+ nonlocal execution_count
733
+ del input_image, last_image, headers, job_id
734
+ with count_lock:
735
+ execution_count += 1
736
+ started_event.set()
737
+ release_event.wait(timeout=3)
738
+ source_path = settings.result_dir / "blocking-source.mp4"
739
+ source_path.write_bytes(VIDEO_BYTES)
740
+ return source_path, payload.seed
741
+
742
+ client, _, _, counters = self._make_service(
743
+ settings=settings,
744
+ executor=blocking_executor,
745
+ )
746
+ headers = self._headers(**{"Idempotency-Key": "same-request"})
747
+ first = client.post("/api/jobs", json=self._payload(), headers=headers)
748
+ self.assertEqual(first.status_code, 202)
749
+ self.assertTrue(started_event.wait(timeout=1))
750
+
751
+ replay = client.post("/api/jobs", json=self._payload(), headers=headers)
752
+ self.assertEqual(replay.status_code, 202)
753
+ self.assertEqual(replay.json()["job_id"], first.json()["job_id"])
754
+ self.assertEqual(counters["fetch"], 1)
755
+
756
+ conflict = client.post(
757
+ "/api/jobs",
758
+ json=self._payload(seed=43),
759
+ headers=headers,
760
+ )
761
+ self.assertEqual(conflict.status_code, 409)
762
+
763
+ busy = client.post(
764
+ "/api/jobs",
765
+ json=self._payload(seed=44),
766
+ headers=self._headers(**{"Idempotency-Key": "different-request"}),
767
+ )
768
+ self.assertEqual(busy.status_code, 503)
769
+ self.assertEqual(busy.headers["Retry-After"], "5")
770
+ self.assertEqual(counters["fetch"], 1)
771
+
772
+ release_event.set()
773
+ terminal = self._wait_for_terminal(client, first.json()["job_id"])
774
+ self.assertEqual(terminal.status_code, 200)
775
+ self.assertEqual(execution_count, 1)
776
+
777
+ def test_concurrent_same_idempotency_key_creates_one_job(self) -> None:
778
+ fetch_barrier = threading.Barrier(2)
779
+ fetch_count = 0
780
+ execute_count = 0
781
+ count_lock = threading.Lock()
782
+ settings = self._settings()
783
+
784
+ def racing_fetcher(url, current_settings):
785
+ nonlocal fetch_count
786
+ del url, current_settings
787
+ with count_lock:
788
+ fetch_count += 1
789
+ fetch_barrier.wait(timeout=2)
790
+ return _TrackedImage()
791
+
792
+ def counting_executor(payload, input_image, last_image, headers, job_id):
793
+ nonlocal execute_count
794
+ del input_image, last_image, headers, job_id
795
+ with count_lock:
796
+ execute_count += 1
797
+ current_count = execute_count
798
+ source_path = settings.result_dir / f"race-source-{current_count}.mp4"
799
+ source_path.write_bytes(VIDEO_BYTES)
800
+ return source_path, payload.seed
801
+
802
+ client, _, _, _ = self._make_service(
803
+ settings=settings,
804
+ image_fetcher=racing_fetcher,
805
+ executor=counting_executor,
806
+ )
807
+ headers = self._headers(**{"Idempotency-Key": "concurrent-key"})
808
+
809
+ def submit():
810
+ return client.post("/api/jobs", json=self._payload(), headers=headers)
811
+
812
+ with ThreadPoolExecutor(max_workers=2) as pool:
813
+ responses = list(pool.map(lambda _: submit(), range(2)))
814
+ self.assertEqual([response.status_code for response in responses], [202, 202])
815
+ self.assertEqual(responses[0].json()["job_id"], responses[1].json()["job_id"])
816
+ terminal = self._wait_for_terminal(client, responses[0].json()["job_id"])
817
+ self.assertEqual(terminal.status_code, 200)
818
+ self.assertEqual(fetch_count, 2)
819
+ self.assertEqual(execute_count, 1)
820
+
821
+ def test_failure_is_sanitized_and_always_releases_images_and_slot(self) -> None:
822
+ shared_slot = threading.Lock()
823
+ secret_prompt = "PROMPT-MUST-NOT-APPEAR"
824
+
825
+ def failing_executor(payload, input_image, last_image, headers, job_id):
826
+ del payload, input_image, last_image, headers, job_id
827
+ raise RuntimeError("INTERNAL-SECRET-STACK-DATA")
828
+
829
+ client, api, images, _ = self._make_service(
830
+ executor=failing_executor,
831
+ inference_slot=shared_slot,
832
+ )
833
+ with self.assertLogs("video_job_api", level="ERROR") as captured_logs:
834
+ created = client.post(
835
+ "/api/jobs",
836
+ json=self._payload(prompt=secret_prompt),
837
+ headers=self._headers(),
838
+ )
839
+ terminal = self._wait_for_terminal(client, created.json()["job_id"])
840
+
841
+ self.assertEqual(terminal.status_code, 500)
842
+ self.assertEqual(
843
+ terminal.json(),
844
+ {"error": {"code": "GENERATION_FAILED"}},
845
+ )
846
+ combined_logs = "\n".join(captured_logs.output)
847
+ self.assertNotIn(secret_prompt, combined_logs)
848
+ self.assertNotIn("private", combined_logs)
849
+ self.assertNotIn("INTERNAL-SECRET-STACK-DATA", combined_logs)
850
+ self.assertTrue(all(image.closed for image in images))
851
+ self.assertEqual(api.jobs[created.json()["job_id"]].zero_gpu_headers, {})
852
+ self.assertTrue(shared_slot.acquire(blocking=False))
853
+ shared_slot.release()
854
+
855
+ def test_image_close_error_cannot_leak_shared_slot(self) -> None:
856
+ shared_slot = threading.Lock()
857
+ returned_image = _TrackedImage(fail_on_close=True)
858
+
859
+ def fetcher(url, settings):
860
+ del url, settings
861
+ return returned_image
862
+
863
+ client, _, _, _ = self._make_service(
864
+ image_fetcher=fetcher,
865
+ inference_slot=shared_slot,
866
+ )
867
+ created = client.post(
868
+ "/api/jobs",
869
+ json=self._payload(),
870
+ headers=self._headers(),
871
+ )
872
+ terminal = self._wait_for_terminal(client, created.json()["job_id"])
873
+ self.assertEqual(terminal.status_code, 200)
874
+ self.assertTrue(returned_image.closed)
875
+ self.assertTrue(shared_slot.acquire(blocking=False))
876
+ shared_slot.release()
877
+
878
+ def test_result_not_ready_missing_file_and_one_at_a_time_ttl_cleanup(self) -> None:
879
+ release_event = threading.Event()
880
+ started_event = threading.Event()
881
+ self.release_events.append(release_event)
882
+ settings = self._settings(result_ttl_seconds=60)
883
+
884
+ def blocking_executor(payload, input_image, last_image, headers, job_id):
885
+ del input_image, last_image, headers, job_id
886
+ started_event.set()
887
+ release_event.wait(timeout=3)
888
+ source_path = settings.result_dir / f"source-{payload.seed}.mp4"
889
+ source_path.write_bytes(VIDEO_BYTES)
890
+ return source_path, payload.seed
891
+
892
+ client, api, _, _ = self._make_service(
893
+ settings=settings,
894
+ executor=blocking_executor,
895
+ )
896
+ first = client.post(
897
+ "/api/jobs",
898
+ json=self._payload(seed=1),
899
+ headers=self._headers(),
900
+ )
901
+ first_job_id = first.json()["job_id"]
902
+ self.assertTrue(started_event.wait(timeout=1))
903
+ first_token = api.jobs[first_job_id].download_token
904
+ not_ready = client.get(
905
+ f"/api/jobs/{first_job_id}/video",
906
+ params={"token": first_token},
907
+ )
908
+ self.assertEqual(not_ready.status_code, 409)
909
+
910
+ release_event.set()
911
+ self.assertEqual(self._wait_for_terminal(client, first_job_id).status_code, 200)
912
+ first_path = api.jobs[first_job_id].result_path
913
+ self.assertIsNotNone(first_path)
914
+
915
+ started_event.clear()
916
+ release_event.clear()
917
+ second = client.post(
918
+ "/api/jobs",
919
+ json=self._payload(seed=2),
920
+ headers=self._headers(),
921
+ )
922
+ second_job_id = second.json()["job_id"]
923
+ self.assertTrue(started_event.wait(timeout=1))
924
+ release_event.set()
925
+ self.assertEqual(self._wait_for_terminal(client, second_job_id).status_code, 200)
926
+ second_path = api.jobs[second_job_id].result_path
927
+ self.assertIsNotNone(second_path)
928
+
929
+ assert first_path is not None and second_path is not None
930
+ first_path.unlink()
931
+ missing = client.get(
932
+ f"/api/jobs/{first_job_id}/video",
933
+ params={"token": first_token},
934
+ )
935
+ self.assertEqual(missing.status_code, 410)
936
+
937
+ # 恢复一个明确文件,随后把两个记录同时标为过期,验证一次只移除其中一个。
938
+ first_path.write_bytes(VIDEO_BYTES)
939
+ api.jobs[first_job_id].completed_at = time.time() - 100
940
+ api.jobs[second_job_id].completed_at = time.time() - 100
941
+ api.remove_one_expired_job()
942
+ self.assertEqual(len(api.jobs), 1)
943
+ remaining_record = next(iter(api.jobs.values()))
944
+ self.assertIsNotNone(remaining_record.result_path)
945
+ self.assertTrue(remaining_record.result_path.is_file())
946
+
947
+ def test_external_shared_slot_returns_busy_without_fetching(self) -> None:
948
+ shared_slot = threading.Lock()
949
+ shared_slot.acquire()
950
+ try:
951
+ client, _, _, counters = self._make_service(inference_slot=shared_slot)
952
+ response = client.post(
953
+ "/api/jobs",
954
+ json=self._payload(),
955
+ headers=self._headers(),
956
+ )
957
+ self.assertEqual(response.status_code, 503)
958
+ self.assertEqual(response.headers["Retry-After"], "5")
959
+ self.assertEqual(counters["fetch"], 0)
960
+ finally:
961
+ shared_slot.release()
962
+
963
+ def test_active_download_lease_defers_and_self_heals_ttl_cleanup(self) -> None:
964
+ settings = self._settings(result_ttl_seconds=60)
965
+ client, api, _, _ = self._make_service(settings=settings)
966
+ created = client.post(
967
+ "/api/jobs",
968
+ json=self._payload(),
969
+ headers=self._headers(),
970
+ )
971
+ job_id = created.json()["job_id"]
972
+ self.assertEqual(self._wait_for_terminal(client, job_id).status_code, 200)
973
+ record = api.jobs[job_id]
974
+ result_path = record.result_path
975
+ self.assertIsNotNone(result_path)
976
+
977
+ api._download_record(job_id, record.download_token)
978
+ record.completed_at = time.time() - 100
979
+ api.remove_one_expired_job()
980
+ self.assertIn(job_id, api.jobs)
981
+ assert result_path is not None
982
+ self.assertTrue(result_path.is_file())
983
+
984
+ record.download_lease_expires_at = time.time() - 1
985
+ api.remove_one_expired_job()
986
+ self.assertNotIn(job_id, api.jobs)
987
+ self.assertFalse(result_path.exists())
988
+
989
+ def test_thread_start_failure_rolls_back_and_next_job_can_run(self) -> None:
990
+ client, api, images, counters = self._make_service()
991
+ with patch("video_job_api.threading.Thread.start", side_effect=RuntimeError("start")):
992
+ with self.assertRaises(RuntimeError):
993
+ client.post(
994
+ "/api/jobs",
995
+ json=self._payload(),
996
+ headers=self._headers(**{"Idempotency-Key": "rollback-key"}),
997
+ )
998
+
999
+ self.assertEqual(api.jobs, {})
1000
+ self.assertEqual(api.idempotency_jobs, {})
1001
+ self.assertTrue(all(image.closed for image in images))
1002
+ self.assertFalse(api.inference_slot.locked())
1003
+
1004
+ retry = client.post(
1005
+ "/api/jobs",
1006
+ json=self._payload(),
1007
+ headers=self._headers(**{"Idempotency-Key": "rollback-key"}),
1008
+ )
1009
+ self.assertEqual(retry.status_code, 202)
1010
+ self.assertEqual(self._wait_for_terminal(client, retry.json()["job_id"]).status_code, 200)
1011
+ self.assertEqual(counters["execute"], 1)
1012
+
1013
+ def test_range_parser_contract(self) -> None:
1014
+ self.assertEqual(_parse_single_byte_range("bytes=0-0", 10), (0, 0))
1015
+ self.assertEqual(_parse_single_byte_range("bytes=5-", 10), (5, 9))
1016
+ self.assertEqual(_parse_single_byte_range("bytes=-3", 10), (7, 9))
1017
+ self.assertEqual(_parse_single_byte_range("bytes=0-99", 10), (0, 9))
1018
+ for invalid_range in ("", "items=0-1", "bytes=1-0", "bytes=-0", "bytes=0-1,2-3"):
1019
+ with self.subTest(invalid_range=invalid_range):
1020
+ with self.assertRaises(ValueError):
1021
+ _parse_single_byte_range(invalid_range, 10)
1022
+
1023
+ def test_app_source_preserves_gradio_and_shared_context_contract(self) -> None:
1024
+ app_source = (Path(__file__).parents[1] / "app.py").read_text(encoding="utf-8")
1025
+ required_fragments = (
1026
+ "spaces.disable_gradio_auto_wrap()",
1027
+ "if not INFERENCE_SLOT.acquire(blocking=False):",
1028
+ "inference_slot=INFERENCE_SLOT",
1029
+ "with bind_context_values(",
1030
+ "(LocalContext.request, request_context)",
1031
+ "(LocalContext.blocks, demo)",
1032
+ "(LocalContext.in_event_listener, True)",
1033
+ "(LocalContext.event_id, None)",
1034
+ "lora_attempted = True",
1035
+ "lora_loader.unload_lora(pipe)",
1036
+ "pipe.scheduler = copy.deepcopy(original_scheduler)",
1037
+ "if video_path is not None and (not video_ready or cleanup_error is not None):",
1038
+ "fn=generate_video_ui",
1039
+ 'api_name="generate_video"',
1040
+ "demo.queue(default_concurrency_limit=1).launch(",
1041
+ 'mcp_server=True',
1042
+ 'ssr_mode=False',
1043
+ 'app_kwargs={"lifespan": JOB_API_LIFESPAN}',
1044
+ )
1045
+ for fragment in required_fragments:
1046
+ with self.subTest(fragment=fragment):
1047
+ self.assertIn(fragment, app_source)
1048
+
1049
+ lora_source = (
1050
+ Path(__file__).parents[1] / "lora_loader.py"
1051
+ ).read_text(encoding="utf-8")
1052
+ strict_unload_body = lora_source.split("def unload_lora(pipe):", 1)[1]
1053
+ self.assertIn("pipe.unload_lora_weights()", strict_unload_body)
1054
+ self.assertNotIn("except:", strict_unload_body)
1055
+
1056
+ def test_context_bindings_restore_all_values_after_exception(self) -> None:
1057
+ request_context = ContextVar("request_context", default="request-before")
1058
+ blocks_context = ContextVar("blocks_context", default="blocks-before")
1059
+ listener_context = ContextVar("listener_context", default=False)
1060
+ event_context = ContextVar("event_context", default="event-before")
1061
+
1062
+ with self.assertRaises(RuntimeError):
1063
+ with bind_context_values(
1064
+ (
1065
+ (request_context, "request-during"),
1066
+ (blocks_context, "blocks-during"),
1067
+ (listener_context, True),
1068
+ (event_context, None),
1069
+ )
1070
+ ):
1071
+ self.assertEqual(request_context.get(), "request-during")
1072
+ self.assertEqual(blocks_context.get(), "blocks-during")
1073
+ self.assertTrue(listener_context.get())
1074
+ self.assertIsNone(event_context.get())
1075
+ raise RuntimeError("executor failed")
1076
+
1077
+ self.assertEqual(request_context.get(), "request-before")
1078
+ self.assertEqual(blocks_context.get(), "blocks-before")
1079
+ self.assertFalse(listener_context.get())
1080
+ self.assertEqual(event_context.get(), "event-before")
1081
+
1082
+
1083
+ if __name__ == "__main__":
1084
+ unittest.main()
video_job_api.py ADDED
@@ -0,0 +1,1666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import ipaddress
5
+ import io
6
+ import json
7
+ import logging
8
+ import os
9
+ import secrets
10
+ import socket
11
+ import tempfile
12
+ import threading
13
+ import time
14
+ import warnings
15
+ from collections.abc import Iterator
16
+ from contextlib import ExitStack, asynccontextmanager, contextmanager
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any, Callable, Literal
20
+ from urllib.parse import SplitResult, urlsplit
21
+
22
+ import httpx
23
+ from fastapi import APIRouter, HTTPException, Request, Response
24
+ from fastapi import status as http_status
25
+ from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
26
+ from PIL import Image, ImageOps, UnidentifiedImageError
27
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
28
+ from starlette.background import BackgroundTask
29
+
30
+
31
+ LOGGER = logging.getLogger(__name__)
32
+ DNS_RESOLVER_SLOTS = threading.BoundedSemaphore(4)
33
+ IMAGE_FETCH_SLOTS = threading.BoundedSemaphore(4)
34
+ DOWNLOAD_LEASE_SECONDS = 600
35
+
36
+ DEFAULT_PROMPT = "make this image come alive, cinematic motion, smooth animation"
37
+ DEFAULT_NEGATIVE_PROMPT = (
38
+ "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, "
39
+ "整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, "
40
+ "画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, "
41
+ "手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
42
+ )
43
+
44
+ SchedulerName = Literal[
45
+ "FlowMatchEulerDiscrete",
46
+ "SASolver",
47
+ "DEISMultistep",
48
+ "DPMSolverMultistepInverse",
49
+ "UniPCMultistep",
50
+ "DPMSolverMultistep",
51
+ "DPMSolverSinglestep",
52
+ ]
53
+ FrameMultiplier = Literal[16, 32, 64, 128]
54
+ JobStatus = Literal["queued", "running", "succeeded", "failed"]
55
+
56
+ VideoExecutor = Callable[
57
+ ["VideoJobRequest", Image.Image, Image.Image | None, dict[str, str], str],
58
+ tuple[str | os.PathLike[str], int],
59
+ ]
60
+ ImageFetcher = Callable[[str, "VideoJobSettings"], Image.Image]
61
+
62
+
63
+ @contextmanager
64
+ def bind_context_values(bindings: tuple[tuple[Any, Any], ...]):
65
+ """临时设置一组 ContextVar,并保证成功或异常后按逆序恢复。
66
+
67
+ Args:
68
+ bindings: 按设置顺序提供的 ContextVar 与临时值二元组。
69
+
70
+ Returns:
71
+ 进入上下文后不返回业务值,退出时恢复所有原值。
72
+ """
73
+ with ExitStack() as context_stack:
74
+ for context_variable, temporary_value in bindings:
75
+ token = context_variable.set(temporary_value)
76
+ context_stack.callback(context_variable.reset, token)
77
+ yield
78
+
79
+
80
+ def _read_int_env(name: str, default: int) -> int:
81
+ raw_value = os.getenv(name)
82
+ if raw_value is None or not raw_value.strip():
83
+ return default
84
+ try:
85
+ return int(raw_value)
86
+ except ValueError as exc:
87
+ raise RuntimeError(f"{name} must be an integer") from exc
88
+
89
+
90
+ def _read_float_env(name: str, default: float) -> float:
91
+ raw_value = os.getenv(name)
92
+ if raw_value is None or not raw_value.strip():
93
+ return default
94
+ try:
95
+ return float(raw_value)
96
+ except ValueError as exc:
97
+ raise RuntimeError(f"{name} must be a number") from exc
98
+
99
+
100
+ def normalize_allowed_hosts(raw_hosts: str) -> frozenset[str]:
101
+ """规范化图片抓取白名单中的精确主机名。
102
+
103
+ Args:
104
+ raw_hosts: 以逗号分隔的主机名,不允许包含协议、端口、路径或通配符。
105
+
106
+ Returns:
107
+ 小写并完成 IDNA 转换的不可变主机名集合。
108
+ """
109
+ normalized_hosts: set[str] = set()
110
+ for raw_host in raw_hosts.split(","):
111
+ host = raw_host.strip().rstrip(".")
112
+ if not host:
113
+ continue
114
+ if any(marker in host for marker in ("://", "/", "?", "#", "*", "@", ":")):
115
+ raise RuntimeError(
116
+ "JOB_IMAGE_ALLOWED_HOSTS must contain exact hostnames only"
117
+ )
118
+ try:
119
+ normalized_hosts.add(host.encode("idna").decode("ascii").lower())
120
+ except UnicodeError as exc:
121
+ raise RuntimeError(
122
+ "JOB_IMAGE_ALLOWED_HOSTS contains an invalid hostname"
123
+ ) from exc
124
+ if not normalized_hosts:
125
+ raise RuntimeError("JOB_IMAGE_ALLOWED_HOSTS must contain at least one hostname")
126
+ return frozenset(normalized_hosts)
127
+
128
+
129
+ @dataclass(frozen=True, slots=True)
130
+ class VideoJobSettings:
131
+ """保存自定义视频任务 API 的部署边界与资源限制。"""
132
+
133
+ api_key: str
134
+ allowed_hosts: frozenset[str]
135
+ result_dir: Path
136
+ result_ttl_seconds: int = 1800
137
+ poll_after_seconds: int = 2
138
+ fetch_timeout_seconds: float = 15.0
139
+ max_image_bytes: int = 20 * 1024 * 1024
140
+ max_image_pixels: int = 40_000_000
141
+ space_host: str = ""
142
+
143
+ @classmethod
144
+ def from_env(cls) -> "VideoJobSettings":
145
+ """从 Space Secret 与 Variables 读取并校验任务 API 配置。
146
+
147
+ Args:
148
+ 此方法不接��参数,配置统一从当前进程环境读取。
149
+
150
+ Returns:
151
+ 已完成边界校验的任务 API 设置。
152
+ """
153
+ api_key = os.getenv("JOB_API_KEY", "").strip()
154
+ if len(api_key) < 32:
155
+ raise RuntimeError(
156
+ "JOB_API_KEY must be configured as a Space Secret with at least 32 characters"
157
+ )
158
+
159
+ result_ttl_seconds = _read_int_env("JOB_RESULT_TTL_SECONDS", 1800)
160
+ poll_after_seconds = _read_int_env("JOB_POLL_AFTER_SECONDS", 2)
161
+ fetch_timeout_seconds = _read_float_env(
162
+ "JOB_IMAGE_FETCH_TIMEOUT_SECONDS", 15.0
163
+ )
164
+ max_image_bytes = _read_int_env(
165
+ "JOB_IMAGE_MAX_BYTES", 20 * 1024 * 1024
166
+ )
167
+ max_image_pixels = _read_int_env("JOB_IMAGE_MAX_PIXELS", 40_000_000)
168
+
169
+ if not 60 <= result_ttl_seconds <= 86400:
170
+ raise RuntimeError("JOB_RESULT_TTL_SECONDS must be between 60 and 86400")
171
+ if not 1 <= poll_after_seconds <= 30:
172
+ raise RuntimeError("JOB_POLL_AFTER_SECONDS must be between 1 and 30")
173
+ if not 1.0 <= fetch_timeout_seconds <= 15.0:
174
+ raise RuntimeError(
175
+ "JOB_IMAGE_FETCH_TIMEOUT_SECONDS must be between 1 and 15"
176
+ )
177
+ if not 1024 <= max_image_bytes <= 20 * 1024 * 1024:
178
+ raise RuntimeError("JOB_IMAGE_MAX_BYTES must be between 1 KiB and 20 MiB")
179
+ if not 1 <= max_image_pixels <= 40_000_000:
180
+ raise RuntimeError(
181
+ "JOB_IMAGE_MAX_PIXELS must be between 1 and 40000000"
182
+ )
183
+
184
+ result_dir = Path(tempfile.gettempdir()) / "i2v_job_results"
185
+ result_dir.mkdir(parents=True, exist_ok=True)
186
+ return cls(
187
+ api_key=api_key,
188
+ allowed_hosts=normalize_allowed_hosts(
189
+ os.getenv("JOB_IMAGE_ALLOWED_HOSTS", "")
190
+ ),
191
+ result_dir=result_dir,
192
+ result_ttl_seconds=result_ttl_seconds,
193
+ poll_after_seconds=poll_after_seconds,
194
+ fetch_timeout_seconds=fetch_timeout_seconds,
195
+ max_image_bytes=max_image_bytes,
196
+ max_image_pixels=max_image_pixels,
197
+ space_host=os.getenv("SPACE_HOST", "").strip().rstrip("/"),
198
+ )
199
+
200
+
201
+ class VideoJobRequest(BaseModel):
202
+ """定义视频任务的命名参数、默认值和公开校验边界。"""
203
+
204
+ model_config = ConfigDict(
205
+ extra="forbid",
206
+ str_strip_whitespace=True,
207
+ allow_inf_nan=False,
208
+ )
209
+
210
+ input_image_url: str = Field(min_length=1, max_length=4096)
211
+ last_image_url: str | None = Field(default=None, max_length=4096)
212
+ prompt: str = Field(default=DEFAULT_PROMPT, min_length=1, max_length=5000)
213
+ steps: int = Field(default=6, ge=1, le=30)
214
+ negative_prompt: str = Field(default=DEFAULT_NEGATIVE_PROMPT, max_length=5000)
215
+ duration_seconds: float = Field(default=3.5, ge=0.5, le=20.1)
216
+ guidance_scale: float = Field(default=1.0, ge=0.0, le=10.0)
217
+ guidance_scale_2: float = Field(default=1.0, ge=0.0, le=10.0)
218
+ seed: int = Field(default=42, ge=0, le=2**31 - 1)
219
+ randomize_seed: bool = True
220
+ quality: int = Field(default=6, ge=1, le=10)
221
+ scheduler: SchedulerName = "UniPCMultistep"
222
+ flow_shift: float = Field(default=3.0, ge=0.5, le=15.0)
223
+ frame_multiplier: FrameMultiplier = 16
224
+ safe_mode: bool = True
225
+ lora_groups: list[str] = Field(default_factory=list)
226
+
227
+ @field_validator("prompt")
228
+ @classmethod
229
+ def reject_blank_prompt(cls, value: str) -> str:
230
+ """拒绝清理空白后没有内容的正向提示词。
231
+
232
+ Args:
233
+ value: Pydantic 已完成基础类型检查的提示词。
234
+
235
+ Returns:
236
+ 去除两端空白后的有效提示词。
237
+ """
238
+ stripped_value = value.strip()
239
+ if not stripped_value:
240
+ raise ValueError("prompt cannot be blank")
241
+ return stripped_value
242
+
243
+ @field_validator("negative_prompt")
244
+ @classmethod
245
+ def strip_negative_prompt(cls, value: str) -> str:
246
+ """清理负向提示词两端空白。
247
+
248
+ Args:
249
+ value: 原始负向提示词。
250
+
251
+ Returns:
252
+ 去除两端空白后的负向提示词。
253
+ """
254
+ return value.strip()
255
+
256
+ @field_validator("last_image_url", mode="before")
257
+ @classmethod
258
+ def normalize_optional_url(cls, value: Any) -> Any:
259
+ """把空字符串形式的可选尾图 URL 规范化为空值。
260
+
261
+ Args:
262
+ value: 调用方提交的尾图 URL 原始值。
263
+
264
+ Returns:
265
+ 空白字符串返回 None,其余值保持不变。
266
+ """
267
+ if isinstance(value, str) and not value.strip():
268
+ return None
269
+ return value
270
+
271
+ @field_validator("input_image_url", "last_image_url")
272
+ @classmethod
273
+ def require_https_image_url(cls, value: str | None) -> str | None:
274
+ """在 Schema 阶段拒绝非 HTTPS 或携带凭据的图片 URL。
275
+
276
+ Args:
277
+ value: 首图或已规范化的可选尾图 URL。
278
+
279
+ Returns:
280
+ 通过基础 HTTPS 语法检查的原始 URL,或可选字段的 None。
281
+ """
282
+ if value is None:
283
+ return None
284
+ try:
285
+ parsed = urlsplit(value)
286
+ port = parsed.port
287
+ except ValueError as exc:
288
+ raise ValueError("image URL is invalid") from exc
289
+ if (
290
+ parsed.scheme.lower() != "https"
291
+ or not parsed.hostname
292
+ or parsed.username is not None
293
+ or parsed.password is not None
294
+ or parsed.fragment
295
+ or port not in {None, 443}
296
+ ):
297
+ raise ValueError(
298
+ "image URL must use credential-free HTTPS on the default port"
299
+ )
300
+ return value
301
+
302
+
303
+ @dataclass(frozen=True, slots=True)
304
+ class ValidatedImageURL:
305
+ """保存通过协议、主机与公网地址检查的图片 URL。"""
306
+
307
+ value: str
308
+ host: str
309
+
310
+
311
+ class ImageSourceError(RuntimeError):
312
+ """表示图片来源不合法或暂时无法抓取。"""
313
+
314
+ def __init__(self, status_code: int, public_message: str):
315
+ super().__init__(public_message)
316
+ self.status_code = status_code
317
+ self.public_message = public_message
318
+
319
+
320
+ def _resolve_host_addresses(host: str, timeout_seconds: float) -> list[Any]:
321
+ """在硬期限内解析主机地址,避免同步 DNS 无限阻塞请求线程。
322
+
323
+ Args:
324
+ host: 已通过精确白名单校验的规范化主机名。
325
+ timeout_seconds: DNS 解析允许占用的最长墙钟秒数。
326
+
327
+ Returns:
328
+ socket.getaddrinfo 返回的非空地址记录列表。
329
+ """
330
+ completed = threading.Event()
331
+ result: dict[str, Any] = {}
332
+ if not DNS_RESOLVER_SLOTS.acquire(blocking=False):
333
+ raise ImageSourceError(
334
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
335
+ "The image host resolution is temporarily busy.",
336
+ )
337
+
338
+ def resolve() -> None:
339
+ try:
340
+ result["records"] = socket.getaddrinfo(
341
+ host,
342
+ 443,
343
+ type=socket.SOCK_STREAM,
344
+ )
345
+ except Exception as exc:
346
+ result["error"] = exc
347
+ finally:
348
+ DNS_RESOLVER_SLOTS.release()
349
+ completed.set()
350
+
351
+ resolver = threading.Thread(
352
+ target=resolve,
353
+ name="i2v-image-dns",
354
+ daemon=True,
355
+ )
356
+ try:
357
+ resolver.start()
358
+ except Exception:
359
+ DNS_RESOLVER_SLOTS.release()
360
+ raise
361
+ if not completed.wait(timeout=max(0.001, timeout_seconds)):
362
+ raise ImageSourceError(
363
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
364
+ "The image host resolution timed out.",
365
+ )
366
+ resolution_error = result.get("error")
367
+ if resolution_error is not None:
368
+ raise ImageSourceError(
369
+ http_status.HTTP_502_BAD_GATEWAY,
370
+ "The image host could not be resolved.",
371
+ ) from resolution_error
372
+ address_records = result.get("records")
373
+ if not address_records:
374
+ raise ImageSourceError(
375
+ http_status.HTTP_502_BAD_GATEWAY,
376
+ "The image host did not return an address.",
377
+ )
378
+ return address_records
379
+
380
+
381
+ def validate_image_url(url: str, settings: VideoJobSettings) -> ValidatedImageURL:
382
+ """校验远程图片 URL 只指向白名单内的公网 HTTPS 主机。
383
+
384
+ Args:
385
+ url: 调用方提交的完整图片 URL。
386
+ settings: 包含白名单与网络资源限制的任务 API 设置。
387
+
388
+ Returns:
389
+ 已规范化主机名并可安全用于抓取的 URL 描述。
390
+ """
391
+ try:
392
+ parsed: SplitResult = urlsplit(url)
393
+ port = parsed.port
394
+ except ValueError as exc:
395
+ raise ImageSourceError(
396
+ http_status.HTTP_400_BAD_REQUEST, "The image URL is invalid."
397
+ ) from exc
398
+
399
+ if parsed.scheme.lower() != "https" or not parsed.hostname:
400
+ raise ImageSourceError(
401
+ http_status.HTTP_400_BAD_REQUEST,
402
+ "Image URLs must use HTTPS.",
403
+ )
404
+ if parsed.username is not None or parsed.password is not None or parsed.fragment:
405
+ raise ImageSourceError(
406
+ http_status.HTTP_400_BAD_REQUEST,
407
+ "The image URL contains unsupported credentials or fragments.",
408
+ )
409
+ if port not in {None, 443}:
410
+ raise ImageSourceError(
411
+ http_status.HTTP_400_BAD_REQUEST,
412
+ "The image URL must use the default HTTPS port.",
413
+ )
414
+
415
+ try:
416
+ normalized_host = (
417
+ parsed.hostname.rstrip(".").encode("idna").decode("ascii").lower()
418
+ )
419
+ except UnicodeError as exc:
420
+ raise ImageSourceError(
421
+ http_status.HTTP_400_BAD_REQUEST, "The image URL hostname is invalid."
422
+ ) from exc
423
+
424
+ if normalized_host not in settings.allowed_hosts:
425
+ raise ImageSourceError(
426
+ http_status.HTTP_400_BAD_REQUEST,
427
+ "The image URL host is not allowed.",
428
+ )
429
+
430
+ address_records = _resolve_host_addresses(
431
+ normalized_host,
432
+ settings.fetch_timeout_seconds,
433
+ )
434
+
435
+ # 白名单只能解决预期主机边界;逐个拒绝非公网解析结果可阻断错误配置和常见 DNS 绕过。
436
+ for address_record in address_records:
437
+ raw_address = address_record[4][0].split("%", 1)[0]
438
+ try:
439
+ resolved_ip = ipaddress.ip_address(raw_address)
440
+ except ValueError as exc:
441
+ raise ImageSourceError(
442
+ http_status.HTTP_400_BAD_REQUEST,
443
+ "The image host resolved to an invalid address.",
444
+ ) from exc
445
+ if not resolved_ip.is_global:
446
+ raise ImageSourceError(
447
+ http_status.HTTP_400_BAD_REQUEST,
448
+ "The image host must resolve only to public addresses.",
449
+ )
450
+
451
+ return ValidatedImageURL(value=url, host=normalized_host)
452
+
453
+
454
+ def _validate_connected_peer(response: httpx.Response) -> None:
455
+ """确认 HTTP 客户端实际连接的对端仍是公网 IP。
456
+
457
+ Args:
458
+ response: 已建立 TLS 连接并收到响应头的 httpx 响应。
459
+
460
+ Returns:
461
+ 对端地址可验证且属于公网时不返回数据。
462
+ """
463
+ network_stream = response.extensions.get("network_stream")
464
+ if network_stream is None:
465
+ raise ImageSourceError(
466
+ http_status.HTTP_502_BAD_GATEWAY,
467
+ "The image connection peer could not be verified.",
468
+ )
469
+ try:
470
+ peer_address = network_stream.get_extra_info("server_addr")
471
+ raw_address = peer_address[0].split("%", 1)[0]
472
+ peer_ip = ipaddress.ip_address(raw_address)
473
+ except (AttributeError, IndexError, TypeError, ValueError) as exc:
474
+ raise ImageSourceError(
475
+ http_status.HTTP_502_BAD_GATEWAY,
476
+ "The image connection peer could not be verified.",
477
+ ) from exc
478
+ if not peer_ip.is_global:
479
+ raise ImageSourceError(
480
+ http_status.HTTP_400_BAD_REQUEST,
481
+ "The image connection peer must be a public address.",
482
+ )
483
+
484
+
485
+ def decode_image_bytes(
486
+ image_bytes: bytes,
487
+ content_type: str,
488
+ settings: VideoJobSettings,
489
+ ) -> Image.Image:
490
+ """校验远程内容并解码为已脱离底层流的 RGB 图片。
491
+
492
+ Args:
493
+ image_bytes: 受大小上限约束后完整读取的图片字节。
494
+ content_type: 远程响应声明的 MIME 类型。
495
+ settings: 包含图片字节数与像素数上限的任务 API 设置。
496
+
497
+ Returns:
498
+ 完成 EXIF 方向修正并复制到内存的 RGB PIL 图片。
499
+ """
500
+ if not image_bytes or len(image_bytes) > settings.max_image_bytes:
501
+ raise ImageSourceError(
502
+ http_status.HTTP_400_BAD_REQUEST,
503
+ "The remote image is empty or exceeds the configured size limit.",
504
+ )
505
+
506
+ try:
507
+ with warnings.catch_warnings():
508
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
509
+ with Image.open(io.BytesIO(image_bytes)) as source_image:
510
+ if source_image.format not in {"JPEG", "PNG", "WEBP"}:
511
+ raise ImageSourceError(
512
+ http_status.HTTP_400_BAD_REQUEST,
513
+ "The remote image format is not supported.",
514
+ )
515
+ width, height = source_image.size
516
+ if width <= 0 or height <= 0 or width * height > settings.max_image_pixels:
517
+ raise ImageSourceError(
518
+ http_status.HTTP_400_BAD_REQUEST,
519
+ "The remote image exceeds the configured pixel limit.",
520
+ )
521
+ source_image.load()
522
+ return ImageOps.exif_transpose(source_image).convert("RGB").copy()
523
+ except ImageSourceError:
524
+ raise
525
+ except (
526
+ UnidentifiedImageError,
527
+ OSError,
528
+ ValueError,
529
+ Image.DecompressionBombError,
530
+ Image.DecompressionBombWarning,
531
+ ) as exc:
532
+ raise ImageSourceError(
533
+ http_status.HTTP_400_BAD_REQUEST,
534
+ "The remote image could not be decoded safely.",
535
+ ) from exc
536
+
537
+
538
+ def _fetch_remote_image_inner(url: str, settings: VideoJobSettings) -> Image.Image:
539
+ """从白名单公网主机流式抓取并安全解码一张图片。
540
+
541
+ Args:
542
+ url: 调用方提交的首图或尾图 HTTPS URL。
543
+ settings: 图片白名单、超时、体积和像素限制。
544
+
545
+ Returns:
546
+ 可直接交给现有 I2V 预处理逻辑的 RGB PIL 图片。
547
+ """
548
+ started_at = time.monotonic()
549
+ validated_url = validate_image_url(url, settings)
550
+ remaining_seconds = settings.fetch_timeout_seconds - (
551
+ time.monotonic() - started_at
552
+ )
553
+ if remaining_seconds <= 0:
554
+ raise ImageSourceError(
555
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
556
+ "The image download timed out.",
557
+ )
558
+ timeout = httpx.Timeout(
559
+ remaining_seconds,
560
+ connect=min(5.0, remaining_seconds),
561
+ )
562
+ deadline_reached = threading.Event()
563
+ client = httpx.Client(
564
+ timeout=timeout,
565
+ follow_redirects=False,
566
+ trust_env=False,
567
+ )
568
+
569
+ def stop_at_deadline() -> None:
570
+ deadline_reached.set()
571
+ try:
572
+ client.close()
573
+ except Exception:
574
+ pass
575
+
576
+ deadline_timer = threading.Timer(remaining_seconds, stop_at_deadline)
577
+ deadline_timer.daemon = True
578
+ try:
579
+ with client:
580
+ deadline_timer.start()
581
+ with client.stream(
582
+ "GET",
583
+ validated_url.value,
584
+ headers={"Accept": "image/png,image/jpeg,image/webp"},
585
+ ) as response:
586
+ if time.monotonic() - started_at > settings.fetch_timeout_seconds:
587
+ raise ImageSourceError(
588
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
589
+ "The image download timed out.",
590
+ )
591
+ _validate_connected_peer(response)
592
+ if 300 <= response.status_code < 400:
593
+ raise ImageSourceError(
594
+ http_status.HTTP_400_BAD_REQUEST,
595
+ "Image URL redirects are not allowed.",
596
+ )
597
+ if response.status_code == http_status.HTTP_408_REQUEST_TIMEOUT:
598
+ raise ImageSourceError(
599
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
600
+ "The image download timed out.",
601
+ )
602
+ if response.status_code == 429 or response.status_code >= 500:
603
+ raise ImageSourceError(
604
+ http_status.HTTP_502_BAD_GATEWAY,
605
+ "The image host is temporarily unavailable.",
606
+ )
607
+ if response.status_code != http_status.HTTP_200_OK:
608
+ raise ImageSourceError(
609
+ http_status.HTTP_400_BAD_REQUEST,
610
+ "The image URL did not return a readable resource.",
611
+ )
612
+
613
+ declared_length = response.headers.get("content-length")
614
+ if declared_length:
615
+ try:
616
+ parsed_length = int(declared_length)
617
+ if parsed_length < 0:
618
+ raise ValueError("negative content length")
619
+ if parsed_length > settings.max_image_bytes:
620
+ raise ImageSourceError(
621
+ http_status.HTTP_400_BAD_REQUEST,
622
+ "The remote image exceeds the configured size limit.",
623
+ )
624
+ except ValueError as exc:
625
+ raise ImageSourceError(
626
+ http_status.HTTP_400_BAD_REQUEST,
627
+ "The image host returned an invalid content length.",
628
+ ) from exc
629
+
630
+ image_buffer = bytearray()
631
+ for chunk in response.iter_bytes():
632
+ if time.monotonic() - started_at > settings.fetch_timeout_seconds:
633
+ raise ImageSourceError(
634
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
635
+ "The image download timed out.",
636
+ )
637
+ image_buffer.extend(chunk)
638
+ if len(image_buffer) > settings.max_image_bytes:
639
+ raise ImageSourceError(
640
+ http_status.HTTP_400_BAD_REQUEST,
641
+ "The remote image exceeds the configured size limit.",
642
+ )
643
+ decoded_image = decode_image_bytes(
644
+ bytes(image_buffer),
645
+ response.headers.get("content-type", ""),
646
+ settings,
647
+ )
648
+ deadline_timer.cancel()
649
+ if (
650
+ deadline_reached.is_set()
651
+ or time.monotonic() - started_at > settings.fetch_timeout_seconds
652
+ ):
653
+ decoded_image.close()
654
+ raise ImageSourceError(
655
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
656
+ "The image download timed out.",
657
+ )
658
+ return decoded_image
659
+ except ImageSourceError:
660
+ raise
661
+ except (httpx.RequestError, RuntimeError) as exc:
662
+ raise _map_image_request_error(exc, deadline_reached) from exc
663
+ finally:
664
+ deadline_timer.cancel()
665
+
666
+
667
+ def _map_image_request_error(
668
+ exc: Exception,
669
+ deadline_reached: threading.Event,
670
+ ) -> ImageSourceError:
671
+ """把底层 HTTP 错误映射为不含远程 URL 的公开错误。
672
+
673
+ Args:
674
+ exc: httpx 或客户端关闭路径产生的底层异常。
675
+ deadline_reached: 硬期限看门狗是否已经触发。
676
+
677
+ Returns:
678
+ 可由 API 层安全公开的图片来源错误。
679
+ """
680
+ if deadline_reached.is_set() or isinstance(exc, httpx.TimeoutException):
681
+ return ImageSourceError(
682
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
683
+ "The image download timed out.",
684
+ )
685
+ return ImageSourceError(
686
+ http_status.HTTP_502_BAD_GATEWAY,
687
+ "The image host is temporarily unavailable.",
688
+ )
689
+
690
+
691
+ def fetch_remote_image(url: str, settings: VideoJobSettings) -> Image.Image:
692
+ """以有界后台抓取器执行单图下载,并强制墙钟总期限。
693
+
694
+ Args:
695
+ url: 调用方提交的首图或尾图 HTTPS URL。
696
+ settings: 白名单、硬超时、体积与像素边界。
697
+
698
+ Returns:
699
+ 在总期限内完成验证和解码的 RGB PIL 图片。
700
+ """
701
+ if not IMAGE_FETCH_SLOTS.acquire(blocking=False):
702
+ raise ImageSourceError(
703
+ http_status.HTTP_502_BAD_GATEWAY,
704
+ "The image fetch service is temporarily busy.",
705
+ )
706
+
707
+ completed = threading.Event()
708
+ state_lock = threading.Lock()
709
+ state: dict[str, Any] = {"abandoned": False}
710
+
711
+ def fetch() -> None:
712
+ fetched_image: Image.Image | None = None
713
+ try:
714
+ fetched_image = _fetch_remote_image_inner(url, settings)
715
+ should_close = False
716
+ with state_lock:
717
+ if state["abandoned"]:
718
+ should_close = True
719
+ else:
720
+ state["image"] = fetched_image
721
+ fetched_image = None
722
+ if should_close and fetched_image is not None:
723
+ try:
724
+ fetched_image.close()
725
+ finally:
726
+ fetched_image = None
727
+ except Exception as exc:
728
+ with state_lock:
729
+ if not state["abandoned"]:
730
+ state["error"] = exc
731
+ finally:
732
+ if fetched_image is not None:
733
+ try:
734
+ fetched_image.close()
735
+ except Exception as exc:
736
+ LOGGER.warning(
737
+ "Failed to close an abandoned fetched image: %s",
738
+ type(exc).__name__,
739
+ )
740
+ IMAGE_FETCH_SLOTS.release()
741
+ completed.set()
742
+
743
+ fetch_thread = threading.Thread(
744
+ target=fetch,
745
+ name="i2v-image-fetch",
746
+ daemon=True,
747
+ )
748
+ try:
749
+ fetch_thread.start()
750
+ except Exception as exc:
751
+ IMAGE_FETCH_SLOTS.release()
752
+ raise ImageSourceError(
753
+ http_status.HTTP_502_BAD_GATEWAY,
754
+ "The image fetch service could not start.",
755
+ ) from exc
756
+
757
+ if not completed.wait(timeout=settings.fetch_timeout_seconds):
758
+ abandoned_image: Image.Image | None = None
759
+ with state_lock:
760
+ state["abandoned"] = True
761
+ abandoned_image = state.pop("image", None)
762
+ if abandoned_image is not None:
763
+ try:
764
+ abandoned_image.close()
765
+ except Exception as exc:
766
+ LOGGER.warning(
767
+ "Failed to close a timed-out fetched image: %s",
768
+ type(exc).__name__,
769
+ )
770
+ raise ImageSourceError(
771
+ http_status.HTTP_504_GATEWAY_TIMEOUT,
772
+ "The image download timed out.",
773
+ )
774
+
775
+ with state_lock:
776
+ fetch_error = state.get("error")
777
+ fetched_image = state.get("image")
778
+ if fetch_error is not None:
779
+ if isinstance(fetch_error, ImageSourceError):
780
+ raise fetch_error
781
+ raise ImageSourceError(
782
+ http_status.HTTP_502_BAD_GATEWAY,
783
+ "The image host is temporarily unavailable.",
784
+ ) from fetch_error
785
+ if fetched_image is None:
786
+ raise ImageSourceError(
787
+ http_status.HTTP_502_BAD_GATEWAY,
788
+ "The image response could not be completed.",
789
+ )
790
+ return fetched_image
791
+
792
+
793
+ def _constant_time_text_equal(supplied: str, expected: str) -> bool:
794
+ """以字节形式比较不可信文本,避免非 ASCII 输入触发类型异常。
795
+
796
+ Args:
797
+ supplied: 请求携带的待校验文本。
798
+ expected: 服务端保存的期望文本。
799
+
800
+ Returns:
801
+ 两个 UTF-8 字节序列完全一致时返回 True。
802
+ """
803
+ return secrets.compare_digest(
804
+ supplied.encode("utf-8", errors="surrogatepass"),
805
+ expected.encode("utf-8", errors="surrogatepass"),
806
+ )
807
+
808
+
809
+ def _parse_single_byte_range(range_header: str, file_size: int) -> tuple[int, int]:
810
+ """解析一个 HTTP bytes 区间并拒绝多区间或不可满足范围。
811
+
812
+ Args:
813
+ range_header: 客户端发送的完整 Range 请求头。
814
+ file_size: 当前 MP4 文件的总字节数。
815
+
816
+ Returns:
817
+ 已裁剪到文件边界内的闭区间起止偏移。
818
+ """
819
+ normalized_header = range_header.strip()
820
+ if file_size <= 0 or "=" not in normalized_header:
821
+ raise ValueError("invalid byte range")
822
+ unit, raw_spec = normalized_header.split("=", 1)
823
+ if unit.strip().lower() != "bytes" or "," in raw_spec:
824
+ raise ValueError("only one bytes range is supported")
825
+
826
+ range_spec = raw_spec.strip()
827
+ if range_spec.count("-") != 1:
828
+ raise ValueError("invalid byte range")
829
+ raw_start, raw_end = range_spec.split("-", 1)
830
+ if raw_start:
831
+ if not raw_start.isdigit() or (raw_end and not raw_end.isdigit()):
832
+ raise ValueError("invalid byte range")
833
+ start = int(raw_start)
834
+ if start >= file_size:
835
+ raise ValueError("byte range is not satisfiable")
836
+ end = file_size - 1 if not raw_end else min(int(raw_end), file_size - 1)
837
+ if end < start:
838
+ raise ValueError("byte range is not satisfiable")
839
+ return start, end
840
+
841
+ if not raw_end.isdigit():
842
+ raise ValueError("invalid suffix byte range")
843
+ suffix_length = int(raw_end)
844
+ if suffix_length <= 0:
845
+ raise ValueError("invalid suffix byte range")
846
+ return max(0, file_size - suffix_length), file_size - 1
847
+
848
+
849
+ def _iter_file_range(path: Path, start: int, end: int) -> Iterator[bytes]:
850
+ """按固定小块读取一个明确 MP4 文件的闭区间。
851
+
852
+ Args:
853
+ path: 要读取的单个结果文件路径。
854
+ start: 起始字节偏移。
855
+ end: 结束字节偏移,包含该字节。
856
+
857
+ Returns:
858
+ 依次产生不超过目标闭区间的二进制块迭代器。
859
+ """
860
+ remaining = end - start + 1
861
+ with path.open("rb") as video_file:
862
+ video_file.seek(start)
863
+ while remaining > 0:
864
+ chunk = video_file.read(min(1024 * 1024, remaining))
865
+ if not chunk:
866
+ break
867
+ remaining -= len(chunk)
868
+ yield chunk
869
+
870
+
871
+ def fingerprint_request(payload: VideoJobRequest) -> str:
872
+ """生成与 JSON 字段顺序无关的任务请求指纹。
873
+
874
+ Args:
875
+ payload: 已通过 Pydantic 校验的任务参数。
876
+
877
+ Returns:
878
+ 用于幂等键复用校验的 SHA-256 摘要。
879
+ """
880
+ canonical_payload = json.dumps(
881
+ payload.model_dump(mode="json"),
882
+ ensure_ascii=False,
883
+ separators=(",", ":"),
884
+ sort_keys=True,
885
+ )
886
+ return hashlib.sha256(canonical_payload.encode("utf-8")).hexdigest()
887
+
888
+
889
+ @dataclass(slots=True)
890
+ class VideoJobRecord:
891
+ """保存单个视频任务在当前 Space 进程内的生命周期数据。"""
892
+
893
+ job_id: str
894
+ payload: VideoJobRequest
895
+ request_fingerprint: str
896
+ input_image: Image.Image | None
897
+ last_image: Image.Image | None
898
+ zero_gpu_headers: dict[str, str]
899
+ download_token: str
900
+ idempotency_key: str | None = None
901
+ status: JobStatus = "queued"
902
+ created_at: float = field(default_factory=time.time)
903
+ started_at: float | None = None
904
+ completed_at: float | None = None
905
+ result_path: Path | None = None
906
+ used_seed: int | None = None
907
+ error_type: str | None = None
908
+ active_downloads: int = 0
909
+ download_lease_expires_at: float | None = None
910
+
911
+
912
+ class VideoJobAPI:
913
+ """实现与 Krea2 一致的异步视频任务 API 状态机。"""
914
+
915
+ def __init__(
916
+ self,
917
+ settings: VideoJobSettings,
918
+ executor: VideoExecutor,
919
+ allowed_loras: set[str] | frozenset[str],
920
+ inference_slot: threading.Lock,
921
+ image_fetcher: ImageFetcher = fetch_remote_image,
922
+ ) -> None:
923
+ """创建视频任务服务并注册路由定义。
924
+
925
+ Args:
926
+ settings: 已校验的部署配置和资源限制。
927
+ executor: 调用现有 Gradio/ZeroGPU 生成链路的适配函数。
928
+ allowed_loras: 当前 UI 可选择的 LoRA 名称集合。
929
+ inference_slot: 与 UI 共用的非阻塞单推理门闩。
930
+ image_fetcher: 可替换的远程图片抓取函数,便于隔离测试。
931
+
932
+ Returns:
933
+ 此初始化方法不返回数据。
934
+ """
935
+ self.settings = settings
936
+ self.executor = executor
937
+ self.allowed_loras = frozenset(allowed_loras)
938
+ self.inference_slot = inference_slot
939
+ self.image_fetcher = image_fetcher
940
+ self.jobs: dict[str, VideoJobRecord] = {}
941
+ self.idempotency_jobs: dict[str, str] = {}
942
+ self.jobs_lock = threading.RLock()
943
+ self.active_job_id: str | None = None
944
+
945
+ self.router = APIRouter(tags=["jobs"])
946
+ self.router.add_api_route(
947
+ "/api/jobs",
948
+ self.create_job,
949
+ methods=["POST"],
950
+ name="i2v_create_job",
951
+ )
952
+ self.router.add_api_route(
953
+ "/api/jobs/{job_id}",
954
+ self.get_job_status,
955
+ methods=["GET"],
956
+ name="i2v_get_job_status",
957
+ )
958
+ self.router.add_api_route(
959
+ "/api/jobs/{job_id}/video",
960
+ self.get_job_video,
961
+ methods=["GET"],
962
+ name="i2v_get_job_video",
963
+ )
964
+ self.router.add_api_route(
965
+ "/api/jobs/{job_id}/video",
966
+ self.head_job_video,
967
+ methods=["HEAD"],
968
+ name="i2v_head_job_video",
969
+ )
970
+
971
+ def install_on_app(self, app: Any) -> None:
972
+ """把自定义任务路由安装到 Gradio 创建的 FastAPI 应用前部。
973
+
974
+ Args:
975
+ app: Gradio 在 launch 阶段创建的 FastAPI 应用。
976
+
977
+ Returns:
978
+ 路由已存在或安装完成后不返回数据。
979
+ """
980
+ if getattr(app.state, "i2v_job_api_router_registered", False):
981
+ return
982
+ original_route_count = len(app.router.routes)
983
+ app.include_router(self.router)
984
+ added_routes = app.router.routes[original_route_count:]
985
+ original_routes = app.router.routes[:original_route_count]
986
+ # Gradio 带有宽泛路由,自定义 API 必须排在其前面才能稳定命中。
987
+ app.router.routes[:] = [*added_routes, *original_routes]
988
+ app.state.i2v_job_api_router_registered = True
989
+
990
+ def _require_api_key(self, request: Request) -> None:
991
+ supplied_key = request.headers.get("x-api-key", "")
992
+ if not supplied_key or not _constant_time_text_equal(
993
+ supplied_key,
994
+ self.settings.api_key,
995
+ ):
996
+ raise HTTPException(
997
+ status_code=http_status.HTTP_401_UNAUTHORIZED,
998
+ detail="A valid X-API-Key header is required.",
999
+ )
1000
+
1001
+ def _public_route_url(
1002
+ self,
1003
+ request: Request,
1004
+ route_name: str,
1005
+ **path_params: str,
1006
+ ) -> str:
1007
+ path = str(request.app.url_path_for(route_name, **path_params))
1008
+ if self.settings.space_host:
1009
+ space_host = self.settings.space_host
1010
+ if not space_host.startswith(("http://", "https://")):
1011
+ space_host = f"https://{space_host}"
1012
+ return f"{space_host}{path}"
1013
+ return str(request.url_for(route_name, **path_params))
1014
+
1015
+ def _is_expired(
1016
+ self,
1017
+ record: VideoJobRecord,
1018
+ now: float | None = None,
1019
+ ) -> bool:
1020
+ current_time = time.time() if now is None else now
1021
+ if record.active_downloads > 0:
1022
+ lease_deadline = record.download_lease_expires_at
1023
+ if lease_deadline is None or current_time < lease_deadline:
1024
+ return False
1025
+ # 响应异常可能跳过 BackgroundTask;过期租约必须能自行恢复。
1026
+ record.active_downloads = 0
1027
+ record.download_lease_expires_at = None
1028
+ if record.completed_at is None:
1029
+ return False
1030
+ return current_time - record.completed_at > self.settings.result_ttl_seconds
1031
+
1032
+ @staticmethod
1033
+ def _unlink_one(path: Path | None) -> None:
1034
+ if path is None:
1035
+ return
1036
+ try:
1037
+ path.unlink(missing_ok=True)
1038
+ except OSError as exc:
1039
+ LOGGER.warning(
1040
+ "Failed to remove video job file %s: %s",
1041
+ path.stem[:8],
1042
+ type(exc).__name__,
1043
+ )
1044
+
1045
+ @staticmethod
1046
+ def _close_images(*images: Image.Image | None) -> None:
1047
+ """逐一关闭已知图片并隔离单个清理异常。
1048
+
1049
+ Args:
1050
+ images: 要释放的零个或多个明确图片对象。
1051
+
1052
+ Returns:
1053
+ 清理完成后不返回数据;关闭错误仅写入脱敏日志。
1054
+ """
1055
+ for image in images:
1056
+ if image is not None:
1057
+ try:
1058
+ image.close()
1059
+ except Exception as exc:
1060
+ LOGGER.warning(
1061
+ "Failed to close a video job image: %s",
1062
+ type(exc).__name__,
1063
+ )
1064
+
1065
+ @staticmethod
1066
+ def _close_job_images(record: VideoJobRecord | None) -> None:
1067
+ if record is None:
1068
+ return
1069
+ VideoJobAPI._close_images(record.input_image, record.last_image)
1070
+ record.input_image = None
1071
+ record.last_image = None
1072
+
1073
+ def _remove_record_locked(self, record: VideoJobRecord) -> None:
1074
+ self.jobs.pop(record.job_id, None)
1075
+ if record.idempotency_key is not None:
1076
+ if self.idempotency_jobs.get(record.idempotency_key) == record.job_id:
1077
+ self.idempotency_jobs.pop(record.idempotency_key, None)
1078
+
1079
+ def remove_one_expired_job(self) -> None:
1080
+ """每次仅清理一个过期终态任务及其明确结果文件。
1081
+
1082
+ Args:
1083
+ 此方法不接收参数。
1084
+
1085
+ Returns:
1086
+ 清理完成后不返回数据。
1087
+ """
1088
+ expired_record: VideoJobRecord | None = None
1089
+ now = time.time()
1090
+ with self.jobs_lock:
1091
+ for record in self.jobs.values():
1092
+ if self._is_expired(record, now):
1093
+ expired_record = record
1094
+ self._remove_record_locked(record)
1095
+ break
1096
+ if expired_record is not None:
1097
+ self._close_job_images(expired_record)
1098
+ self._unlink_one(expired_record.result_path)
1099
+
1100
+ def _job_or_404(self, job_id: str) -> VideoJobRecord:
1101
+ expired_record: VideoJobRecord | None = None
1102
+ with self.jobs_lock:
1103
+ record = self.jobs.get(job_id)
1104
+ if record is not None and self._is_expired(record):
1105
+ expired_record = record
1106
+ self._remove_record_locked(record)
1107
+ record = None
1108
+ if expired_record is not None:
1109
+ self._close_job_images(expired_record)
1110
+ self._unlink_one(expired_record.result_path)
1111
+ if record is None:
1112
+ raise HTTPException(
1113
+ status_code=http_status.HTTP_404_NOT_FOUND,
1114
+ detail="Job not found or result expired.",
1115
+ )
1116
+ return record
1117
+
1118
+ def _validate_loras(self, lora_groups: list[str]) -> None:
1119
+ if len(lora_groups) != len(set(lora_groups)):
1120
+ raise HTTPException(
1121
+ status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY,
1122
+ detail="lora_groups cannot contain duplicate choices.",
1123
+ )
1124
+ unknown_loras = [
1125
+ lora_name
1126
+ for lora_name in lora_groups
1127
+ if lora_name not in self.allowed_loras
1128
+ ]
1129
+ if unknown_loras:
1130
+ raise HTTPException(
1131
+ status_code=http_status.HTTP_422_UNPROCESSABLE_ENTITY,
1132
+ detail="lora_groups contains an unsupported choice.",
1133
+ )
1134
+
1135
+ def _status_response(
1136
+ self,
1137
+ request: Request,
1138
+ record: VideoJobRecord,
1139
+ ) -> JSONResponse:
1140
+ status_url = self._public_route_url(
1141
+ request,
1142
+ "i2v_get_job_status",
1143
+ job_id=record.job_id,
1144
+ )
1145
+ return JSONResponse(
1146
+ status_code=http_status.HTTP_202_ACCEPTED,
1147
+ headers={
1148
+ "Location": status_url,
1149
+ "Cache-Control": "no-store",
1150
+ },
1151
+ content={
1152
+ "job_id": record.job_id,
1153
+ "status_url": status_url,
1154
+ "poll_after_seconds": self.settings.poll_after_seconds,
1155
+ },
1156
+ )
1157
+
1158
+ def _lookup_idempotent_job(
1159
+ self,
1160
+ idempotency_key: str | None,
1161
+ request_fingerprint: str,
1162
+ ) -> tuple[VideoJobRecord | None, Path | None]:
1163
+ if idempotency_key is None:
1164
+ return None, None
1165
+ expired_path: Path | None = None
1166
+ with self.jobs_lock:
1167
+ existing_job_id = self.idempotency_jobs.get(idempotency_key)
1168
+ record = self.jobs.get(existing_job_id or "")
1169
+ if record is not None and self._is_expired(record):
1170
+ self._remove_record_locked(record)
1171
+ expired_path = record.result_path
1172
+ record = None
1173
+ if record is None:
1174
+ if existing_job_id is not None:
1175
+ self.idempotency_jobs.pop(idempotency_key, None)
1176
+ return None, expired_path
1177
+ if not secrets.compare_digest(
1178
+ record.request_fingerprint,
1179
+ request_fingerprint,
1180
+ ):
1181
+ raise HTTPException(
1182
+ status_code=http_status.HTTP_409_CONFLICT,
1183
+ detail=(
1184
+ "Idempotency-Key was already used with a different "
1185
+ "request body."
1186
+ ),
1187
+ )
1188
+ return record, expired_path
1189
+
1190
+ def create_job(
1191
+ self,
1192
+ payload: VideoJobRequest,
1193
+ request: Request,
1194
+ ) -> JSONResponse:
1195
+ """验证远程图片并创建立即执行的异步视频任务。
1196
+
1197
+ Args:
1198
+ payload: 已通过 Pydantic 校验的命名视频参数。
1199
+ request: 包含共享密钥与 ZeroGPU 身份头的 FastAPI 请求。
1200
+
1201
+ Returns:
1202
+ HTTP 202 任务标识、状态 URL 与建议轮询间隔。
1203
+ """
1204
+ self._require_api_key(request)
1205
+ self.remove_one_expired_job()
1206
+ self._validate_loras(payload.lora_groups)
1207
+
1208
+ idempotency_key = request.headers.get("idempotency-key", "").strip() or None
1209
+ if idempotency_key is not None and len(idempotency_key) > 200:
1210
+ raise HTTPException(
1211
+ status_code=http_status.HTTP_400_BAD_REQUEST,
1212
+ detail="Idempotency-Key must be 200 characters or fewer.",
1213
+ )
1214
+ request_fingerprint = fingerprint_request(payload)
1215
+ existing_record, expired_path = self._lookup_idempotent_job(
1216
+ idempotency_key,
1217
+ request_fingerprint,
1218
+ )
1219
+ self._unlink_one(expired_path)
1220
+ if existing_record is not None:
1221
+ return self._status_response(request, existing_record)
1222
+
1223
+ x_ip_token = request.headers.get("x-ip-token")
1224
+ if not x_ip_token:
1225
+ raise HTTPException(
1226
+ status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
1227
+ detail=(
1228
+ "The ZeroGPU identity header is unavailable. "
1229
+ "Retry through the Space URL."
1230
+ ),
1231
+ headers={"Retry-After": "3"},
1232
+ )
1233
+
1234
+ with self.jobs_lock:
1235
+ active_record = self.jobs.get(self.active_job_id or "")
1236
+ api_job_active = active_record is not None and active_record.status in {
1237
+ "queued",
1238
+ "running",
1239
+ }
1240
+ # 抓图前先做快速忙检查;抓图后仍会在同一状态锁内做一次权威检查。
1241
+ if api_job_active or self.inference_slot.locked():
1242
+ raise HTTPException(
1243
+ status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
1244
+ detail="The generation service is busy.",
1245
+ headers={"Retry-After": "5"},
1246
+ )
1247
+
1248
+ slot_owned_by_request = False
1249
+ record: VideoJobRecord | None = None
1250
+ replay_record: VideoJobRecord | None = None
1251
+ input_image: Image.Image | None = None
1252
+ last_image: Image.Image | None = None
1253
+ second_expired_path: Path | None = None
1254
+ try:
1255
+ try:
1256
+ input_image = self.image_fetcher(payload.input_image_url, self.settings)
1257
+ last_image = (
1258
+ self.image_fetcher(payload.last_image_url, self.settings)
1259
+ if payload.last_image_url is not None
1260
+ else None
1261
+ )
1262
+ except ImageSourceError as exc:
1263
+ raise HTTPException(
1264
+ status_code=exc.status_code,
1265
+ detail=exc.public_message,
1266
+ ) from exc
1267
+
1268
+ with self.jobs_lock:
1269
+ # 两个相同幂等键可并发抓图;只有此处的二次判定有权创建任务。
1270
+ replay_record, second_expired_path = self._lookup_idempotent_job(
1271
+ idempotency_key,
1272
+ request_fingerprint,
1273
+ )
1274
+ if replay_record is None:
1275
+ active_record = self.jobs.get(self.active_job_id or "")
1276
+ if active_record is not None and active_record.status in {
1277
+ "queued",
1278
+ "running",
1279
+ }:
1280
+ raise HTTPException(
1281
+ status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
1282
+ detail="The generation service is busy.",
1283
+ headers={"Retry-After": "5"},
1284
+ )
1285
+ if not self.inference_slot.acquire(blocking=False):
1286
+ raise HTTPException(
1287
+ status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
1288
+ detail="The generation service is busy.",
1289
+ headers={"Retry-After": "5"},
1290
+ )
1291
+ slot_owned_by_request = True
1292
+
1293
+ job_id = secrets.token_urlsafe(24)
1294
+ zero_gpu_headers = {"x-ip-token": x_ip_token}
1295
+ x_gradio_user = request.headers.get("x-gradio-user")
1296
+ if x_gradio_user:
1297
+ zero_gpu_headers["x-gradio-user"] = x_gradio_user
1298
+
1299
+ record = VideoJobRecord(
1300
+ job_id=job_id,
1301
+ payload=payload,
1302
+ request_fingerprint=request_fingerprint,
1303
+ input_image=input_image,
1304
+ last_image=last_image,
1305
+ zero_gpu_headers=zero_gpu_headers,
1306
+ download_token=secrets.token_urlsafe(32),
1307
+ idempotency_key=idempotency_key,
1308
+ )
1309
+ self.jobs[job_id] = record
1310
+ self.active_job_id = job_id
1311
+ if idempotency_key is not None:
1312
+ self.idempotency_jobs[idempotency_key] = job_id
1313
+
1314
+ self._unlink_one(second_expired_path)
1315
+ second_expired_path = None
1316
+ if replay_record is not None:
1317
+ self._close_images(input_image, last_image)
1318
+ input_image = None
1319
+ last_image = None
1320
+ return self._status_response(request, replay_record)
1321
+
1322
+ if record is None:
1323
+ raise RuntimeError("Job initialization did not produce a record.")
1324
+
1325
+ response = self._status_response(request, record)
1326
+ worker = threading.Thread(
1327
+ target=self._execute_job,
1328
+ args=(record,),
1329
+ name=f"i2v-job-{record.job_id[:8]}",
1330
+ daemon=True,
1331
+ )
1332
+ worker.start()
1333
+ # 线程成功启动后,推理槽位所有权转交给 worker 最外层 finally。
1334
+ slot_owned_by_request = False
1335
+ return response
1336
+ except Exception:
1337
+ with self.jobs_lock:
1338
+ if record is not None:
1339
+ self._remove_record_locked(record)
1340
+ record.zero_gpu_headers.clear()
1341
+ if record is not None and self.active_job_id == record.job_id:
1342
+ self.active_job_id = None
1343
+ self._close_job_images(record)
1344
+ if record is None:
1345
+ # 尾图抓取、竞争判定或任务记录创建失败时,关闭已下载图片。
1346
+ self._close_images(input_image, last_image)
1347
+ if slot_owned_by_request:
1348
+ self.inference_slot.release()
1349
+ self._unlink_one(second_expired_path)
1350
+ raise
1351
+
1352
+ def _execute_job(self, record: VideoJobRecord) -> None:
1353
+ generated_path: Path | None = None
1354
+ final_path: Path | None = None
1355
+ try:
1356
+ with self.jobs_lock:
1357
+ current_record = self.jobs.get(record.job_id)
1358
+ if current_record is not record or record.status != "queued":
1359
+ return
1360
+ record.status = "running"
1361
+ record.started_at = time.time()
1362
+
1363
+ if record.input_image is None:
1364
+ raise RuntimeError("The job input image is unavailable.")
1365
+ generated_value, used_seed = self.executor(
1366
+ record.payload,
1367
+ record.input_image,
1368
+ record.last_image,
1369
+ record.zero_gpu_headers,
1370
+ record.job_id,
1371
+ )
1372
+ generated_path = Path(generated_value)
1373
+ if not generated_path.is_file() or generated_path.stat().st_size <= 0:
1374
+ raise RuntimeError("The video generator did not produce a readable MP4.")
1375
+
1376
+ final_path = self.settings.result_dir / f"{record.job_id}.mp4"
1377
+ os.replace(generated_path, final_path)
1378
+ generated_path = None
1379
+
1380
+ with self.jobs_lock:
1381
+ current_record = self.jobs.get(record.job_id)
1382
+ if current_record is record and record.status == "running":
1383
+ record.status = "succeeded"
1384
+ record.result_path = final_path
1385
+ record.used_seed = int(used_seed)
1386
+ record.completed_at = time.time()
1387
+ else:
1388
+ self._unlink_one(final_path)
1389
+ except Exception as exc:
1390
+ LOGGER.error(
1391
+ "Video job %s failed with %s",
1392
+ record.job_id[:8],
1393
+ type(exc).__name__,
1394
+ )
1395
+ self._unlink_one(generated_path)
1396
+ self._unlink_one(final_path)
1397
+ with self.jobs_lock:
1398
+ current_record = self.jobs.get(record.job_id)
1399
+ if current_record is record and record.status in {"queued", "running"}:
1400
+ record.status = "failed"
1401
+ record.error_type = type(exc).__name__
1402
+ record.completed_at = time.time()
1403
+ finally:
1404
+ with self.jobs_lock:
1405
+ record.zero_gpu_headers.clear()
1406
+ if self.active_job_id == record.job_id:
1407
+ self.active_job_id = None
1408
+ self._close_job_images(record)
1409
+ self.inference_slot.release()
1410
+ self.remove_one_expired_job()
1411
+
1412
+ def get_job_status(self, job_id: str, request: Request) -> JSONResponse:
1413
+ """读取视频任务状态并在成功后返回签名视频 URL。
1414
+
1415
+ Args:
1416
+ job_id: POST 创建任务时返回的自定义任务标识。
1417
+ request: 用于鉴权和生成公网路由地址的 FastAPI 请求。
1418
+
1419
+ Returns:
1420
+ 运行中返回 202,成功返回视频 URL 与实际 seed,失败返回 500。
1421
+ """
1422
+ self._require_api_key(request)
1423
+ record = self._job_or_404(job_id)
1424
+ with self.jobs_lock:
1425
+ status_value = record.status
1426
+ used_seed = record.used_seed
1427
+ download_token = record.download_token
1428
+
1429
+ if status_value in {"queued", "running"}:
1430
+ return JSONResponse(
1431
+ status_code=http_status.HTTP_202_ACCEPTED,
1432
+ headers={
1433
+ "Retry-After": str(self.settings.poll_after_seconds),
1434
+ "Cache-Control": "no-store",
1435
+ },
1436
+ content={"status": status_value},
1437
+ )
1438
+ if status_value == "failed":
1439
+ return JSONResponse(
1440
+ status_code=http_status.HTTP_500_INTERNAL_SERVER_ERROR,
1441
+ headers={"Cache-Control": "no-store"},
1442
+ content={
1443
+ "error": {
1444
+ "code": "GENERATION_FAILED",
1445
+ }
1446
+ },
1447
+ )
1448
+
1449
+ video_url = self._public_route_url(
1450
+ request,
1451
+ "i2v_get_job_video",
1452
+ job_id=job_id,
1453
+ )
1454
+ return JSONResponse(
1455
+ content={
1456
+ "video_url": f"{video_url}?token={download_token}",
1457
+ "used_seed": used_seed,
1458
+ },
1459
+ headers={"Cache-Control": "no-store"},
1460
+ )
1461
+
1462
+ def _download_record(
1463
+ self,
1464
+ job_id: str,
1465
+ token: str | None,
1466
+ ) -> tuple[VideoJobRecord, Path, int]:
1467
+ expired_record: VideoJobRecord | None = None
1468
+ with self.jobs_lock:
1469
+ record = self.jobs.get(job_id)
1470
+ if record is not None and self._is_expired(record):
1471
+ expired_record = record
1472
+ self._remove_record_locked(record)
1473
+ record = None
1474
+ if record is not None:
1475
+ if not token or not _constant_time_text_equal(
1476
+ token,
1477
+ record.download_token,
1478
+ ):
1479
+ raise HTTPException(
1480
+ status_code=http_status.HTTP_401_UNAUTHORIZED,
1481
+ detail="A valid video download token is required.",
1482
+ )
1483
+ if record.status != "succeeded" or record.result_path is None:
1484
+ raise HTTPException(
1485
+ status_code=http_status.HTTP_409_CONFLICT,
1486
+ detail="The job has not produced a video.",
1487
+ )
1488
+ try:
1489
+ file_size = record.result_path.stat().st_size
1490
+ except OSError as exc:
1491
+ raise HTTPException(
1492
+ status_code=http_status.HTTP_410_GONE,
1493
+ detail="The result file is no longer available.",
1494
+ ) from exc
1495
+ # 下载租约使 TTL 清理在响应完成前跳过该明确文件。
1496
+ record.active_downloads += 1
1497
+ lease_deadline = time.time() + DOWNLOAD_LEASE_SECONDS
1498
+ record.download_lease_expires_at = max(
1499
+ record.download_lease_expires_at or 0.0,
1500
+ lease_deadline,
1501
+ )
1502
+ return record, record.result_path, file_size
1503
+
1504
+ if expired_record is not None:
1505
+ self._close_job_images(expired_record)
1506
+ self._unlink_one(expired_record.result_path)
1507
+ raise HTTPException(
1508
+ status_code=http_status.HTTP_404_NOT_FOUND,
1509
+ detail="Job not found or result expired.",
1510
+ )
1511
+
1512
+ def _release_download(self, job_id: str) -> None:
1513
+ """释放一个视频响应租约并按需清理刚过期的单个文件。
1514
+
1515
+ Args:
1516
+ job_id: 当前下载响应对应的任务标识。
1517
+
1518
+ Returns:
1519
+ 租约释放和可选单文件清理完成后不返回数据。
1520
+ """
1521
+ expired_record: VideoJobRecord | None = None
1522
+ with self.jobs_lock:
1523
+ record = self.jobs.get(job_id)
1524
+ if record is None:
1525
+ return
1526
+ if record.active_downloads > 0:
1527
+ record.active_downloads -= 1
1528
+ if record.active_downloads == 0:
1529
+ record.download_lease_expires_at = None
1530
+ if self._is_expired(record):
1531
+ expired_record = record
1532
+ self._remove_record_locked(record)
1533
+ if expired_record is not None:
1534
+ self._close_job_images(expired_record)
1535
+ self._unlink_one(expired_record.result_path)
1536
+
1537
+ @staticmethod
1538
+ def _video_headers() -> dict[str, str]:
1539
+ return {
1540
+ "Cache-Control": "private, max-age=300",
1541
+ "Referrer-Policy": "no-referrer",
1542
+ "Accept-Ranges": "bytes",
1543
+ "Access-Control-Allow-Origin": "*",
1544
+ "Access-Control-Expose-Headers": (
1545
+ "Accept-Ranges, Content-Length, Content-Range"
1546
+ ),
1547
+ }
1548
+
1549
+ def get_job_video(
1550
+ self,
1551
+ job_id: str,
1552
+ request: Request,
1553
+ token: str | None = None,
1554
+ ) -> Response:
1555
+ """通过随机下载令牌返回支持 Range 的 MP4 文件。
1556
+
1557
+ Args:
1558
+ job_id: 自定义视频任务标识。
1559
+ request: 用于读取可选单区间 Range 请求头的 FastAPI 请求。
1560
+ token: 成功状态响应中视频 URL 携带的随机下载令牌。
1561
+
1562
+ Returns:
1563
+ 支持浏览器跨域播放和区间读取的 MP4 FileResponse。
1564
+ """
1565
+ record, result_path, file_size = self._download_record(job_id, token)
1566
+ background = BackgroundTask(self._release_download, job_id)
1567
+ range_header = request.headers.get("range")
1568
+ if range_header is not None:
1569
+ try:
1570
+ range_start, range_end = _parse_single_byte_range(
1571
+ range_header,
1572
+ file_size,
1573
+ )
1574
+ except ValueError as exc:
1575
+ error_headers = self._video_headers()
1576
+ error_headers["Content-Range"] = f"bytes */{file_size}"
1577
+ self._release_download(job_id)
1578
+ raise HTTPException(
1579
+ status_code=http_status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
1580
+ detail="The requested byte range is not satisfiable.",
1581
+ headers=error_headers,
1582
+ ) from exc
1583
+
1584
+ response_headers = self._video_headers()
1585
+ response_headers.update(
1586
+ {
1587
+ "Content-Length": str(range_end - range_start + 1),
1588
+ "Content-Range": (
1589
+ f"bytes {range_start}-{range_end}/{file_size}"
1590
+ ),
1591
+ "Content-Disposition": f'inline; filename="{job_id}.mp4"',
1592
+ }
1593
+ )
1594
+ return StreamingResponse(
1595
+ _iter_file_range(result_path, range_start, range_end),
1596
+ status_code=http_status.HTTP_206_PARTIAL_CONTENT,
1597
+ media_type="video/mp4",
1598
+ headers=response_headers,
1599
+ background=background,
1600
+ )
1601
+
1602
+ return FileResponse(
1603
+ result_path,
1604
+ media_type="video/mp4",
1605
+ filename=f"{job_id}.mp4",
1606
+ content_disposition_type="inline",
1607
+ headers=self._video_headers(),
1608
+ background=background,
1609
+ )
1610
+
1611
+ def head_job_video(
1612
+ self,
1613
+ job_id: str,
1614
+ token: str | None = None,
1615
+ ) -> Response:
1616
+ """验证签名视频链接并仅返回文件元数据。
1617
+
1618
+ Args:
1619
+ job_id: 自定义视频任务标识。
1620
+ token: 成功状态响应中视频 URL 携带的随机下载令牌。
1621
+
1622
+ Returns:
1623
+ 包含 MP4 类型、长度、Range 与跨域头的空响应。
1624
+ """
1625
+ _, _, file_size = self._download_record(job_id, token)
1626
+ try:
1627
+ headers = self._video_headers()
1628
+ headers.update(
1629
+ {
1630
+ "Content-Length": str(file_size),
1631
+ "Accept-Ranges": "bytes",
1632
+ }
1633
+ )
1634
+ return Response(
1635
+ status_code=http_status.HTTP_200_OK,
1636
+ media_type="video/mp4",
1637
+ headers=headers,
1638
+ )
1639
+ finally:
1640
+ self._release_download(job_id)
1641
+
1642
+
1643
+ def create_job_api_lifespan(job_api: VideoJobAPI):
1644
+ """创建供 Gradio launch 组合使用的自定义路由 lifespan。
1645
+
1646
+ Args:
1647
+ job_api: 已配置执行器和共享推理锁的视频任务服务。
1648
+
1649
+ Returns:
1650
+ 可传给 FastAPI app_kwargs 的异步 lifespan 上下文管理器。
1651
+ """
1652
+
1653
+ @asynccontextmanager
1654
+ async def job_api_lifespan(app: Any):
1655
+ """在 Gradio 应用开始接收请求前安装自定义任务路由。
1656
+
1657
+ Args:
1658
+ app: Gradio 创建并传入 lifespan 的 FastAPI 应用。
1659
+
1660
+ Returns:
1661
+ lifespan 启动和关闭阶段不返回业务数据。
1662
+ """
1663
+ job_api.install_on_app(app)
1664
+ yield
1665
+
1666
+ return job_api_lifespan