feat: configure batch windows and variable multishot videos
@ -11,6 +11,8 @@ ADMIN_PASSWORD=
|
||||
# Set true behind public HTTPS. False is only for loopback HTTP/SSH preview.
|
||||
COOKIE_SECURE=false
|
||||
PUBLIC_ACCESS=false
|
||||
# API and the existing GPU worker read the SAME file. See deploy/runtime-policy.*.json.
|
||||
RUNTIME_POLICY_FILE=/workspace/projects/llm-services/config/runtime-policy.json
|
||||
MAX_INTERACTIVE_GPU_JOBS=8
|
||||
MAX_CREATION_COMMANDS_PER_MINUTE=6
|
||||
MAX_OWNER_JOBS=500
|
||||
|
||||
12
README.md
@ -16,9 +16,15 @@
|
||||
|
||||
历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。
|
||||
|
||||
V2 增加三分镜工作流、夜间批量、持久草稿、提交恢复、父子任务事件、版本锁和资源阶段。三镜头各取120帧,输出360帧/24fps的15秒多镜头成片;单模型原生视频任务仍约5秒。设计见 [实施方案V2](docs/实施方案V2_20261110.md)。
|
||||
2026-11-11扩展为可变多镜头工作流:增删/排序、每镜头选用1–5秒、动态音轨字幕范围、JSON导入导出及20镜头100秒鲲鹏示例。总时长由镜头选用帧数之和决定,旧三镜头草稿与成片继续兼容;单模型原生视频任务仍约5秒。
|
||||
|
||||
批量计算窗口为北京时间21:00–08:00。全天接受并持久保存任务;08:00关闭新镜头/新处理阶段准入,当前已执行阶段自然完成,后续排队。Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源。关闭浏览器、SSE或HTTP连接不会取消持久任务,更不会停止共享Qwen服务。显式取消已发出的Qwen/Kokoro请求时等待当前响应再丢弃结果;完成状态未知则隔离本应用相应资源池,等待运维对账。
|
||||
使用说明见[操作手册](docs/操作手册_20261111.md)和[鲲鹏长视频制作指南](docs/鲲鹏长视频制作指南_20261111.md),网站工作流页也提供两份在线帮助。模板位于`frontend/public/examples/kunpeng-storyboard.json`,载入后不会自动生成或保存。
|
||||
|
||||
本轮部署与真实验证见[2026-11-11开发与验收记录](docs/开发与验收记录_20261111.md)。手册更新后可运行`python scripts/render_manuals.py`生成HTML,再构建前端发布;45秒配音版模板同目录另有`kunpeng-storyboard-45s.json`。
|
||||
|
||||
批量时段由API与GPU worker共读的`/workspace/projects/llm-services/config/runtime-policy.json`决定。`batch_window_enabled=false`为开发全天模式,`true`恢复北京时间21:00–08:00准入;开启时08:00关闭新镜头/新处理阶段准入,当前阶段自然完成,后续排队。文件热读取,样例见`deploy/runtime-policy.development.json`与`deploy/runtime-policy.production.json`。文件缺失默认启用限制,格式错误关闭新batch准入。`workflow_max_shots`默认120,可配置1–1000,只限制新草稿/运行/编排的准入。
|
||||
|
||||
Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源;开发开关不绕过维护、手动暂停、额度和外部用户优先。关闭浏览器、SSE或HTTP连接不会取消持久任务,更不会停止共享Qwen服务。显式取消已发出的Qwen/Kokoro请求时等待当前响应再丢弃结果;完成状态未知则隔离本应用相应资源池,等待运维对账。
|
||||
|
||||
初始额度:每用户未结束叶任务500、全局2000;每用户未结束Run100、Batch20,全局Run1000、Batch200;每批最多100项。创建Job/Run/Batch共用每用户每分钟6次命令额度,内部子步骤不重复扣命令数,原键重放不扣额。所有数字可通过配置调整。
|
||||
|
||||
@ -32,7 +38,7 @@ V2 增加三分镜工作流、夜间批量、持久草稿、提交恢复、父
|
||||
| `audio.transcribe` | 既有 Whisper large-v3-turbo | 音频或有声视频转写;视频先在 CPU 提取音轨,最长 1800 秒。时间戳是约 30 秒分块边界,不是逐词对齐。 |
|
||||
| `math.solve` | 既有 Qwen 文本 HTTP 服务 | 数学解答文本;没有形式化证明或专业正确率验收承诺。 |
|
||||
| `media.structure` | Qwen 视觉 HTTP + CPU 抽帧 | 图片理解、视频实际抽帧后的主体/场景/OCR/标签。均匀抽帧不等同于完整镜头切分。 |
|
||||
| `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、上传音轨和人工字幕;最多 24 段、总长 30 分钟,帧率 24/25/30/60。没有热度预测。 |
|
||||
| `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、单音轨和人工字幕;片段数量由配置控制,总时长由片段决定,帧率24/25/30/60。保留磁盘、输出大小、源媒体和超时预算。 |
|
||||
| `audio.speech` | 独立 Kokoro-82M **CPU** 服务 | 中文配音 WAV,当前音色 `zf_xiaobei`、`zm_yunxi`;语速 0.5–2。仅在配置真实服务后启用,不提供音乐生成。 |
|
||||
|
||||
参数约束以登录后的 `/api/capabilities` 为准。生成步数字段为 `num_inference_steps`。只有图片和条件样本支持 `count=1..4`,批次拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。
|
||||
|
||||
@ -49,6 +49,7 @@ class Settings:
|
||||
inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key")
|
||||
gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json")
|
||||
gpu_scheduler_path: Path | None = Path("/workspace/projects/llm-services/state/gpu-scheduler.json")
|
||||
runtime_policy_file: Path | None = Path("/workspace/projects/llm-services/config/runtime-policy.json")
|
||||
qwen_base_url: str = "http://192.168.28.10:14081/v1"
|
||||
qwen_model: str = "Qwen/Qwen3.8-27B-FP8"
|
||||
qwen_api_key: str = ""
|
||||
@ -68,7 +69,7 @@ class Settings:
|
||||
if not value.is_relative_to(self.workspace_root):
|
||||
raise ValueError(field + " must stay inside WORKSPACE_ROOT")
|
||||
setattr(self, field, value)
|
||||
for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path"):
|
||||
for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path", "runtime_policy_file"):
|
||||
if getattr(self, field):
|
||||
setattr(self, field, Path(getattr(self, field)))
|
||||
if self.database_url:
|
||||
@ -106,6 +107,8 @@ class Settings:
|
||||
"gpu_status_path", "gpu_scheduler_path"):
|
||||
if field.upper() in env:
|
||||
values[field] = Path(env[field.upper()]) if env[field.upper()] else None
|
||||
if env.get("RUNTIME_POLICY_FILE"):
|
||||
values["runtime_policy_file"] = Path(env["RUNTIME_POLICY_FILE"])
|
||||
for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes", "max_owner_jobs", "max_global_jobs", "max_interactive_gpu_jobs", "max_creation_commands_per_minute", "max_owner_asset_bytes", "max_data_bytes", "min_free_bytes", "max_owner_runs", "max_global_runs", "max_owner_batches", "max_global_batches"):
|
||||
if field.upper() in env:
|
||||
values[field] = int(env[field.upper()])
|
||||
|
||||
@ -229,10 +229,19 @@ class Coordinator:
|
||||
await session.commit()
|
||||
|
||||
def _clock_allows(self,job):
|
||||
return job.execution_mode!="batch" or self._admission_clock.observe()
|
||||
if job.execution_mode!="batch":return True
|
||||
from .runtime_policy import read_runtime_policy
|
||||
from .resource_policy import execution_policy
|
||||
policy=read_runtime_policy(self.settings)
|
||||
if policy["configuration_error"]:return False
|
||||
if not policy["batch_window_enabled"]:return True
|
||||
return execution_policy()["batch_open"] and self._admission_clock.observe()
|
||||
|
||||
async def run_once(self, *, force=False):
|
||||
self._admission_clock.observe()
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(self.settings)
|
||||
if policy["batch_window_enabled"] and not policy["configuration_error"]:
|
||||
self._admission_clock.observe()
|
||||
async with self._run_lock:
|
||||
for job_id, task in list(self._cpu.items()):
|
||||
if task.done():
|
||||
@ -282,7 +291,7 @@ class Coordinator:
|
||||
# Query existing upstream IDs and collect artifacts at all hours.
|
||||
# Admission only protects NEW computational phases.
|
||||
from .maintenance import maintenance_active
|
||||
if job.state != "collecting" and not job.upstream_id and not job.cancel_requested and (not admits(job) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)):
|
||||
if job.state != "collecting" and not job.upstream_id and not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)):
|
||||
continue
|
||||
if job.task_type in GPU_TYPES:
|
||||
await self._gpu(job)
|
||||
@ -319,7 +328,7 @@ class Coordinator:
|
||||
async def prepare_phase(key,pool):
|
||||
from .resource_policy import admits
|
||||
current=await self._job(job.id)
|
||||
if not admits(current):raise PhaseDeferred()
|
||||
if not admits(current,settings=self.settings):raise PhaseDeferred()
|
||||
await self._enter_phase(job.id,key,pool,nonblocking=True)
|
||||
token=current_phase_callback.set(prepare_phase)
|
||||
try:
|
||||
@ -344,7 +353,7 @@ class Coordinator:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
from .resource_policy import admits
|
||||
if not job.cancel_requested and (not admits(job) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id)):return
|
||||
if not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id)):return
|
||||
if job.execution_mode == "batch":
|
||||
capabilities = await self.provider.upstream_capabilities() if hasattr(self.provider,"upstream_capabilities") else {}
|
||||
if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False):
|
||||
@ -473,7 +482,7 @@ class Coordinator:
|
||||
while True:
|
||||
job=await self._job(job_id)
|
||||
if job.cancel_requested:raise asyncio.CancelledError()
|
||||
if admits(job) and self._clock_allows(job) and pool not in self._blocked_pools and not maintenance_active(self.settings) and await self._owner_enabled(job.owner_id):break
|
||||
if admits(job,settings=self.settings) and self._clock_allows(job) and pool not in self._blocked_pools and not maintenance_active(self.settings) and await self._owner_enabled(job.owner_id):break
|
||||
if nonblocking:raise PhaseDeferred()
|
||||
await self._update(job_id,phase="waiting_phase:"+phase_key)
|
||||
await asyncio.sleep(min(1,self.settings.poll_seconds))
|
||||
@ -481,7 +490,7 @@ class Coordinator:
|
||||
await self._pools[pool].acquire()
|
||||
# Recheck after waiting for the slot; no closed-window compute starts.
|
||||
job=await self._job(job_id)
|
||||
if job.cancel_requested or not admits(job) or not self._clock_allows(job) or pool in self._blocked_pools or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id):
|
||||
if job.cancel_requested or not admits(job,settings=self.settings) or not self._clock_allows(job) or pool in self._blocked_pools or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id):
|
||||
self._pools[pool].release()
|
||||
if nonblocking:raise PhaseDeferred()
|
||||
return await self._enter_phase(job_id,phase_key,pool)
|
||||
|
||||
@ -56,7 +56,7 @@ def input_ids(inputs, parameters):
|
||||
return list(dict.fromkeys(result))
|
||||
|
||||
|
||||
async def validate_submission(session, body, owner_id, settings):
|
||||
async def validate_submission(session, body, owner_id, settings, *, frozen_workflow=False):
|
||||
if body.task_type not in GPU_TYPES | CPU_TYPES:
|
||||
fail(422, "unsupported_task", "不支持此任务类型")
|
||||
allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"}
|
||||
@ -96,6 +96,12 @@ async def validate_submission(session, body, owner_id, settings):
|
||||
if body.task_type == "video.compose" and not ids:
|
||||
fail(422, "clips_required", "请添加待合成片段")
|
||||
if body.task_type == "video.compose":
|
||||
if not frozen_workflow:
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(settings)
|
||||
if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员')
|
||||
if len(body.parameters.get('clips',[]))>policy['workflow_max_shots']:
|
||||
fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个视频片段")
|
||||
if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])):
|
||||
fail(422, "wrong_asset_kind", "编排片段必须为视频素材")
|
||||
audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id")
|
||||
@ -106,7 +112,7 @@ async def validate_submission(session, body, owner_id, settings):
|
||||
return ids
|
||||
|
||||
|
||||
async def create_jobs(session, body, actor, settings, key=None, internal=False):
|
||||
async def create_jobs(session, body, actor, settings, key=None, internal=False, *, frozen_workflow=False):
|
||||
if key is not None and not 1 <= len(key) <= 128:
|
||||
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
|
||||
payload = body.model_dump(mode="json")
|
||||
@ -140,7 +146,9 @@ async def create_jobs(session, body, actor, settings, key=None, internal=False):
|
||||
if body.execution_mode=="interactive" and body.task_type in GPU_TYPES:
|
||||
active=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==actor.id,Job.execution_mode=="interactive",Job.task_type.in_(GPU_TYPES),Job.state.notin_(TERMINAL)))
|
||||
if active+body.count>settings.max_interactive_gpu_jobs:fail(429,"quota_exceeded","Interactive GPU queue limit reached")
|
||||
ids = await validate_submission(session, body, actor.id, settings)
|
||||
# Internal quota accounting also covers newly submitted batch members.
|
||||
# Only children of an already accepted, frozen workflow bypass a new cap.
|
||||
ids = await validate_submission(session, body, actor.id, settings, frozen_workflow=frozen_workflow)
|
||||
scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None
|
||||
jobs = []
|
||||
for index in range(body.count):
|
||||
|
||||
@ -112,18 +112,24 @@ def create_app(settings=None, *, provider=None):
|
||||
async def capabilities():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
from .resource_policy import execution_policy
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(app.state.settings)
|
||||
return {"items": provider_capabilities(app.state.settings),
|
||||
"scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_policy()}
|
||||
"scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_policy(settings=app.state.settings),
|
||||
"workflow_limits":{"max_shots":policy["workflow_max_shots"],"source_frames":121,"max_clip_frames":120,"fps":24}}
|
||||
|
||||
@app.get("/api/system/status", dependencies=[Depends(auth.current_actor)])
|
||||
async def status():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
from .resource_policy import execution_policy
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(app.state.settings)
|
||||
online, scheduler = await asyncio.gather(app.state.provider.health(), app.state.provider.scheduler_status())
|
||||
return {"inference_online": online, "scheduler": scheduler, "models": provider_capabilities(app.state.settings),
|
||||
"environment": app.state.settings.mode,
|
||||
"database_backend": app.state.settings.sqlalchemy_url.get_backend_name(),
|
||||
"execution_policy": execution_policy(),
|
||||
"execution_policy": execution_policy(settings=app.state.settings),
|
||||
"workflow_limits":{"max_shots":policy["workflow_max_shots"],"source_frames":121,"max_clip_frames":120,"fps":24},
|
||||
"public_access": getattr(app.state.settings, "public_access", False)}
|
||||
|
||||
return app
|
||||
|
||||
@ -250,17 +250,20 @@ async def inspect_video_track(path: Path, settings) -> dict:
|
||||
|
||||
|
||||
async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=None):
|
||||
"""Fixed three-shot CPU renderer. Paths are internal resolved asset paths only."""
|
||||
"""Render a frozen multi-shot timeline from internal resolved asset paths."""
|
||||
from .providers import CpuResult
|
||||
if len(sources)!=3:raise MediaError('invalid_timeline','Exactly three source videos required.')
|
||||
if len(sources)!=len(plan.spec['shots']):raise MediaError('invalid_timeline','Source videos differ from the frozen shot count.')
|
||||
shot_frames=plan.shot_frames or (plan.clip_frames,)*len(sources)
|
||||
duration=plan.frames/plan.fps
|
||||
duration_text=f'{duration:.9f}'.rstrip('0').rstrip('.')
|
||||
sources=[confined(p,settings) for p in sources]
|
||||
work=Path(work_dir).resolve()
|
||||
if not work.is_relative_to(Path(settings.workspace_root).resolve()):raise MediaError('invalid_asset','Invalid work directory.')
|
||||
width,height=plan.canvas
|
||||
expected=(plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height'])
|
||||
for source in sources:
|
||||
for source,frames in zip(sources,shot_frames):
|
||||
info=await inspect_video_track(source,settings)
|
||||
if info['frames']<120:raise MediaError('short_source','Each source needs at least 120 decoded video frames.')
|
||||
if info['frames']<frames:raise MediaError('short_source',f'Each source needs at least {frames} decoded video frames for its selected duration.')
|
||||
if info['fps']!=24 or (info['width'],info['height'])!=expected:raise MediaError('invalid_video_profile','Source video differs from frozen enhanced profile.')
|
||||
audio_spec=plan.spec['render']['audio']
|
||||
if bool(audio_spec)!=bool(audio):raise MediaError('invalid_timeline','Audio source does not match timeline.')
|
||||
@ -273,13 +276,13 @@ async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=N
|
||||
result=control() if callable(control) else control.checkpoint()
|
||||
if hasattr(result,'__await__'):await result
|
||||
parts=[]
|
||||
for index,source in enumerate(sources):
|
||||
for index,(source,frames) in enumerate(zip(sources,shot_frames)):
|
||||
await checkpoint();target=work/f'shot-{index}.mp4'
|
||||
fit=plan.spec['render']['fit']
|
||||
canvas=f'scale={width}:{height}:force_original_aspect_ratio=' + ('decrease' if fit=='contain' else 'increase')
|
||||
canvas+=f',pad={width}:{height}:(ow-iw)/2:(oh-ih)/2' if fit=='contain' else f',crop={width}:{height}'
|
||||
vf='trim=start_frame=0:end_frame=120,setpts=PTS-STARTPTS,'+canvas+',setsar=1'
|
||||
await run_process([settings.ffmpeg_bin,'-v','error','-nostdin',*input_options(),'-i',str(source),'-map','0:v:0','-an','-vf',vf,'-r','24','-frames:v','120','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-threads','2','-fs',str(settings.max_output_bytes),str(target)],timeout=600)
|
||||
vf=f'trim=start_frame=0:end_frame={frames},setpts=PTS-STARTPTS,'+canvas+',setsar=1'
|
||||
await run_process([settings.ffmpeg_bin,'-v','error','-nostdin',*input_options(),'-i',str(source),'-map','0:v:0','-an','-vf',vf,'-r','24','-frames:v',str(frames),'-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-threads','2','-fs',str(settings.max_output_bytes),str(target)],timeout=600)
|
||||
parts.append(target)
|
||||
if sum(p.stat().st_size for p in parts)>=settings.max_output_bytes:raise MediaError('output_too_large','Intermediate media exceeds size budget.')
|
||||
listing=work/'concat.txt';listing.write_text(''.join(f"file '{p.name}'\n" for p in parts),encoding='utf-8')
|
||||
@ -294,14 +297,14 @@ async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=N
|
||||
if audio:
|
||||
start,end=audio_spec['source_start_ms']/1000,audio_spec['source_end_ms']/1000
|
||||
delay=audio_spec['offset_frame']*1000/24
|
||||
af=f'atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration=15'
|
||||
else:af='atrim=duration=15'
|
||||
af=f'atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}'
|
||||
else:af=f'atrim=duration={duration_text}'
|
||||
command+=['-map','0:v:0','-map','1:a:0']
|
||||
if filters:command+=['-vf',','.join(filters)]
|
||||
command+=['-af',af,'-frames:v','360','-r','24','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-c:a','aac','-ar','48000','-ac','2','-threads','2','-movflags','+faststart','-fs',str(settings.max_output_bytes),str(target)]
|
||||
await checkpoint();await run_process(command,timeout=600,cwd=work)
|
||||
command+=['-af',af,'-frames:v',str(plan.frames),'-r','24','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-c:a','aac','-ar','48000','-ac','2','-threads','2','-movflags','+faststart','-fs',str(settings.max_output_bytes),str(target)]
|
||||
await checkpoint();await run_process(command,timeout=min(3600,max(600,duration*5)),cwd=work)
|
||||
info=await inspect_video_track(target,settings)
|
||||
if info['frames']!=360 or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-15)>.10 or target.stat().st_size>=settings.max_output_bytes:
|
||||
raise MediaError('composition_incomplete','Final video must be 360 frames at 24fps and 15 seconds.')
|
||||
result={'frames':360,'fps':24,'duration_seconds':15,'width':width,'height':height,'clip_count':3,'subtitle_count':len(filters)}
|
||||
if info['frames']!=plan.frames or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-duration)>.10 or target.stat().st_size>=settings.max_output_bytes:
|
||||
raise MediaError('composition_incomplete','Final video differs from the frozen frame count, profile or duration.')
|
||||
result={'frames':plan.frames,'fps':24,'duration_seconds':duration,'width':width,'height':height,'clip_count':len(sources),'subtitle_count':len(filters)}
|
||||
return CpuResult([target],result,{'provider':'ffmpeg-cpu','profile':plan.spec['profile'],'template_version':'plain-v1'})
|
||||
|
||||
@ -86,6 +86,8 @@ def _voices(settings):
|
||||
|
||||
|
||||
def capabilities(settings) -> list[dict]:
|
||||
from .runtime_policy import read_runtime_policy
|
||||
compose_limit=read_runtime_policy(settings)['workflow_max_shots']
|
||||
image_defaults = {'width': 1024, 'height': 1024, 'num_inference_steps': 50, 'seed': 42, 'guidance_scale': 4.0}
|
||||
image_limits = {'width': {'min': 256, 'max': 2048, 'step': 16},
|
||||
'height': {'min': 256, 'max': 2048, 'step': 16},
|
||||
@ -129,8 +131,8 @@ def capabilities(settings) -> list[dict]:
|
||||
item('video.compose', '成片编排', 'FFmpeg CPU', True, ['video', 'audio'],
|
||||
{'width': 1280, 'height': 720, 'fps': 24},
|
||||
{'width': {'min': 256, 'max': 3840, 'step': 2}, 'height': {'min': 256, 'max': 2160, 'step': 2},
|
||||
'fps': {'values': [24, 25, 30, 60]}, 'clips': {'min': 1, 'max': 24},
|
||||
'duration_seconds': {'min': .05, 'max': 1800}},
|
||||
'fps': {'values': [24, 25, 30, 60]}, 'clips': {'min': 1, 'max': compose_limit},
|
||||
'source_duration_seconds': {'min': .05, 'max': 86400}},
|
||||
'按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'),
|
||||
item('audio.speech', '中文配音', getattr(settings, 'tts_model', '') or '尚未配置', speech, ['text'],
|
||||
{'voice': (_voices(settings) or [''])[0], 'speed': 1.0},
|
||||
@ -223,8 +225,8 @@ def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=
|
||||
except ValueError:
|
||||
raise _invalid('Invalid frozen workflow timeline.') from None
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or len(clips) != 3:
|
||||
raise _invalid('Exactly three workflow clips required.')
|
||||
if not isinstance(clips, list) or len(clips) != len(spec.shots):
|
||||
raise _invalid('Workflow clips must match the frozen shot count.')
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id'})
|
||||
_string(clip.get('asset_id'), 64)
|
||||
@ -236,13 +238,13 @@ def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=
|
||||
_keys(inputs, {'asset_ids', 'audio_asset_id'})
|
||||
_keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'})
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 24:
|
||||
raise _invalid('请选择1至24个视频片段。')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 1000:
|
||||
raise _invalid('请选择1至1000个视频片段,并遵守当前配置的资源上限。')
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id', 'start_seconds', 'end_seconds'})
|
||||
_string(clip.get('asset_id'), 64)
|
||||
start = _float(clip.get('start_seconds', 0), 0, 1800)
|
||||
if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 1800) <= start:
|
||||
start = _float(clip.get('start_seconds', 0), 0, 86400)
|
||||
if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 86400) <= start:
|
||||
raise _invalid('片段结束时间必须大于开始时间。')
|
||||
if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]:
|
||||
raise _invalid('素材顺序应与编排片段一致。')
|
||||
@ -257,7 +259,7 @@ def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=
|
||||
raise _invalid('人工字幕数量超出限制。')
|
||||
for cue in cues:
|
||||
_keys(cue, {'start', 'end', 'text'})
|
||||
start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800)
|
||||
start, end = _float(cue.get('start'), 0, 86400*1000), _float(cue.get('end'), 0, 86400*1000)
|
||||
text = _string(cue.get('text'), 2000)
|
||||
if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text):
|
||||
raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。')
|
||||
@ -750,8 +752,8 @@ class Provider:
|
||||
_keys(inputs, {'asset_ids', 'audio_asset_id'})
|
||||
_keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'})
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 24:
|
||||
raise _invalid('请选择1至24个视频片段。')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 1000:
|
||||
raise _invalid('请选择1至1000个视频片段。')
|
||||
width, height, fps = p.get('width', 1280), p.get('height', 720), p.get('fps', 24)
|
||||
_int(width, 256, 3840, 2)
|
||||
_int(height, 256, 2160, 2)
|
||||
@ -760,9 +762,9 @@ class Provider:
|
||||
normalized = []
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id', 'start_seconds', 'end_seconds'})
|
||||
start = _float(clip.get('start_seconds', 0), 0, 1800)
|
||||
start = _float(clip.get('start_seconds', 0), 0, 86400)
|
||||
end = clip.get('end_seconds')
|
||||
if end is not None and _float(end, 0, 1800) <= start:
|
||||
if end is not None and _float(end, 0, 86400) <= start:
|
||||
raise _invalid('片段结束时间必须大于开始时间。')
|
||||
normalized.append((self._asset(clip.get('asset_id'), assets), start, end))
|
||||
if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]:
|
||||
@ -777,7 +779,7 @@ class Provider:
|
||||
cues = []
|
||||
for cue in subtitles:
|
||||
_keys(cue, {'start', 'end', 'text'})
|
||||
start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800)
|
||||
start, end = _float(cue.get('start'), 0, 86400*1000), _float(cue.get('end'), 0, 86400*1000)
|
||||
text = _string(cue.get('text'), 2000)
|
||||
if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text):
|
||||
raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。')
|
||||
@ -791,8 +793,6 @@ class Provider:
|
||||
if start >= end or end > info['duration_seconds'] + .05 or end - start < .05:
|
||||
raise _invalid('裁剪范围超出视频实际时长。')
|
||||
total += end - start
|
||||
if total > 1800:
|
||||
raise _invalid('成片总时长不能超过30分钟。')
|
||||
parts.append((source, start, end - start, info.get('has_audio', False)))
|
||||
if any(end > total + .05 for _, end, _ in cues):
|
||||
raise _invalid('字幕超出成片时长。')
|
||||
|
||||
@ -1,21 +1,31 @@
|
||||
"""Admission is evaluated at phase boundaries. A closing window never cancels work."""
|
||||
from datetime import datetime,timezone,timedelta
|
||||
from .runtime_policy import read_runtime_policy
|
||||
# fixed UTC+8 has no DST; avoids depending on OS IANA data on Windows.
|
||||
SHANGHAI=timezone(timedelta(hours=8))
|
||||
|
||||
def execution_policy(now=None):
|
||||
def execution_policy(now=None, *, settings=None):
|
||||
policy=read_runtime_policy(settings)
|
||||
now=now or datetime.now(timezone.utc)
|
||||
if now.tzinfo is None: now=now.replace(tzinfo=timezone.utc)
|
||||
local=now.astimezone(SHANGHAI)
|
||||
opened=local.hour>=21 or local.hour<8
|
||||
next_at=local.replace(hour=21,minute=0,second=0,microsecond=0)
|
||||
if local.hour>=21: next_at+=timedelta(days=1)
|
||||
return {"timezone":"Asia/Shanghai","start":"21:00","end":"08:00","batch_open":opened,"next_batch_at":next_at.astimezone(timezone.utc).isoformat(),"close_behavior":"finish_current"}
|
||||
enabled=policy["batch_window_enabled"]
|
||||
return {"timezone":"Asia/Shanghai","start":"21:00","end":"08:00",
|
||||
"batch_window_enabled":enabled,"configuration_error":policy["configuration_error"],
|
||||
"batch_open":not policy["configuration_error"] and (not enabled or opened),
|
||||
"next_batch_at":next_at.astimezone(timezone.utc).isoformat() if enabled and not policy["configuration_error"] else None,
|
||||
"close_behavior":"finish_current"}
|
||||
|
||||
def admits(job,now=None):
|
||||
def admits(job,now=None, *, settings=None):
|
||||
if job.cancel_requested or job.desired_state!="run": return False
|
||||
if set(job.hold_reasons or [])-{"window"}: return False
|
||||
return job.execution_mode!="batch" or execution_policy(now)["batch_open"]
|
||||
if job.execution_mode!="batch":return True
|
||||
policy=read_runtime_policy(settings)
|
||||
if policy["configuration_error"]:return False
|
||||
return not policy["batch_window_enabled"] or execution_policy(now)["batch_open"]
|
||||
|
||||
def resource_plan(task_type,input_kind=None):
|
||||
if task_type=="audio.transcribe": return [("extract_audio","cpu_media"),("transcribe","new_gpu")] if input_kind=="video" else [("transcribe","new_gpu")]
|
||||
|
||||
36
backend/app/runtime_policy.py
Normal file
@ -0,0 +1,36 @@
|
||||
"""Hot-read, operator-owned policy. Client job data never selects this file."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def read_runtime_policy(settings=None):
|
||||
result = {"batch_window_enabled": True, "workflow_max_shots": 120,
|
||||
"configuration_error": None}
|
||||
path = getattr(settings, "runtime_policy_file", None)
|
||||
if path is None:
|
||||
return result
|
||||
try:
|
||||
with Path(path).open("rb") as stream:
|
||||
raw = stream.read(65537)
|
||||
except FileNotFoundError:
|
||||
return result
|
||||
except OSError:
|
||||
return {**result, "configuration_error": "runtime_policy_unavailable"}
|
||||
try:
|
||||
if len(raw) > 65536:
|
||||
raise ValueError("Policy too large")
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(value, dict) or set(value) - {
|
||||
"schema_version", "batch_window_enabled", "workflow_max_shots"}:
|
||||
raise ValueError("Unknown policy fields")
|
||||
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
|
||||
raise ValueError("Unsupported schema")
|
||||
if type(value.get("batch_window_enabled")) is not bool:
|
||||
raise ValueError("Expected boolean switch")
|
||||
max_shots = value.get("workflow_max_shots", 120)
|
||||
if type(max_shots) is not int or not 1 <= max_shots <= 1000:
|
||||
raise ValueError("Invalid shot limit")
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
return {**result, "configuration_error": "runtime_policy_invalid"}
|
||||
return {"batch_window_enabled": value["batch_window_enabled"],
|
||||
"workflow_max_shots": max_shots, "configuration_error": None}
|
||||
@ -1,8 +1,8 @@
|
||||
"""Versioned, strict three-shot contract. Public fields contain no executable paths."""
|
||||
"""Versioned short-clip story contract. Public fields contain no executable paths."""
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
import re
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator
|
||||
|
||||
class Strict(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', strict=True)
|
||||
@ -11,8 +11,9 @@ class ShotParameters(Strict):
|
||||
seed: int = Field(default=42, ge=0, le=2**32-1)
|
||||
|
||||
class Shot(Strict):
|
||||
key: Literal['shot_1','shot_2','shot_3']
|
||||
key: str = Field(pattern=r'^shot_[1-9][0-9]{0,3}$')
|
||||
prompt: str = Field(min_length=1,max_length=8000)
|
||||
duration_frames: int = Field(default=120,ge=24,le=120)
|
||||
image_asset_id: str | None = Field(default=None,min_length=1,max_length=64)
|
||||
parameters: ShotParameters = Field(default_factory=ShotParameters)
|
||||
@model_validator(mode='after')
|
||||
@ -21,8 +22,8 @@ class Shot(Strict):
|
||||
return self
|
||||
|
||||
class Subtitle(Strict):
|
||||
start_frame: int = Field(ge=0,lt=360)
|
||||
end_frame: int = Field(gt=0,le=360)
|
||||
start_frame: int = Field(ge=0)
|
||||
end_frame: int = Field(gt=0)
|
||||
text: str = Field(min_length=1,max_length=2000)
|
||||
@model_validator(mode='after')
|
||||
def safe(self):
|
||||
@ -34,33 +35,51 @@ class Audio(Strict):
|
||||
asset_id: str = Field(min_length=1,max_length=64)
|
||||
source_start_ms: int = Field(ge=0)
|
||||
source_end_ms: int = Field(gt=0)
|
||||
offset_frame: int = Field(default=0,ge=0,lt=360)
|
||||
offset_frame: int = Field(default=0,ge=0)
|
||||
short_policy: Literal['silence'] = 'silence'
|
||||
@model_validator(mode='after')
|
||||
def fits(self):
|
||||
if self.source_end_ms <= self.source_start_ms or (self.source_end_ms-self.source_start_ms)*24 > (360-self.offset_frame)*1000:
|
||||
raise ValueError('invalid_timeline: audio exceeds canvas')
|
||||
if self.source_end_ms <= self.source_start_ms:
|
||||
raise ValueError('invalid_timeline: invalid audio selection')
|
||||
return self
|
||||
|
||||
class Render(Strict):
|
||||
fps: Literal[24] = 24
|
||||
total_frames: Literal[360] = 360
|
||||
total_frames: int | None = Field(default=None,ge=1,le=120000)
|
||||
fit: Literal['contain','cover'] = 'contain'
|
||||
audio: Audio | None = None
|
||||
subtitles: list[Subtitle] = Field(default_factory=list,max_length=1000)
|
||||
template_version: Literal['plain-v1'] = 'plain-v1'
|
||||
|
||||
class WorkflowSpec(Strict):
|
||||
schema_version: Literal[1] = 1
|
||||
shots: list[Shot] = Field(min_length=3,max_length=3)
|
||||
schema_version: Literal[1,2] = 1
|
||||
shots: list[Shot] = Field(min_length=1,max_length=1000)
|
||||
profile: Literal['landscape_1080_v1','portrait_1080_v1'] = 'landscape_1080_v1'
|
||||
render: Render = Field(default_factory=Render)
|
||||
@model_validator(mode='after')
|
||||
def exact_keys(self):
|
||||
if [s.key for s in self.shots] != ['shot_1','shot_2','shot_3']:
|
||||
raise ValueError('exact ordered shot_1,shot_2,shot_3 required')
|
||||
def ordered_timeline(self):
|
||||
if self.schema_version == 1 and (len(self.shots) != 3 or any('duration_frames' in s.model_fields_set for s in self.shots)):
|
||||
raise ValueError('schema_version 1 requires three full-length shots')
|
||||
if [s.key for s in self.shots] != [f'shot_{i}' for i in range(1,len(self.shots)+1)]:
|
||||
raise ValueError('exact ordered sequential shot keys required')
|
||||
frames = sum(s.duration_frames for s in self.shots)
|
||||
if self.render.total_frames is not None and self.render.total_frames != frames:
|
||||
raise ValueError('invalid_timeline: total_frames differs from shots')
|
||||
self.render.total_frames = frames
|
||||
if any(c.end_frame > frames for c in self.render.subtitles):
|
||||
raise ValueError('invalid_timeline: subtitle exceeds canvas')
|
||||
audio = self.render.audio
|
||||
if audio and (audio.offset_frame >= frames or (audio.source_end_ms-audio.source_start_ms)*24 > (frames-audio.offset_frame)*1000):
|
||||
raise ValueError('invalid_timeline: audio exceeds canvas')
|
||||
return self
|
||||
|
||||
@model_serializer(mode='wrap')
|
||||
def legacy_compatible_dump(self, handler):
|
||||
data = handler(self)
|
||||
if self.schema_version == 1:
|
||||
for shot in data['shots']:shot.pop('duration_frames',None)
|
||||
return data
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimelinePlan:
|
||||
spec: dict
|
||||
@ -69,6 +88,12 @@ class TimelinePlan:
|
||||
frames: int = 360
|
||||
clip_frames: int = 120
|
||||
fps: int = 24
|
||||
shot_frames: tuple[int,...] = ()
|
||||
|
||||
|
||||
def ordered_step_keys(snapshot):
|
||||
"""The frozen shot array is authoritative, including shot_10 and later."""
|
||||
return [shot['key'] for shot in snapshot['shots']] + ['compose']
|
||||
|
||||
|
||||
def compile_timeline(spec, owned_assets) -> TimelinePlan:
|
||||
@ -83,4 +108,5 @@ def compile_timeline(spec, owned_assets) -> TimelinePlan:
|
||||
parameters = dict(width=704 if portrait else 1280,height=1280 if portrait else 704,
|
||||
num_frames=121,fps=24,upscale=True,upscale_width=1056 if portrait else 1920,
|
||||
upscale_height=1920 if portrait else 1056,num_inference_steps=50,guidance_scale=5.0,tile_size=128)
|
||||
return TimelinePlan(spec.model_dump(mode='json'),parameters,(1080,1920) if portrait else (1920,1080))
|
||||
return TimelinePlan(spec.model_dump(mode='json'),parameters,(1080,1920) if portrait else (1920,1080),
|
||||
frames=spec.render.total_frames,shot_frames=tuple(s.duration_frames for s in spec.shots))
|
||||
|
||||
@ -6,6 +6,7 @@ from .models import Job, utcnow
|
||||
from .v2_models import WorkflowRun, WorkflowStep, AssetReference
|
||||
from .jobs import TERMINAL
|
||||
from .workflows import RUN_TERMINAL, create_child, emit_run, selected_output
|
||||
from .timeline import ordered_step_keys
|
||||
|
||||
log=logging.getLogger(__name__)
|
||||
AUTOMATIC_HOLDS={'quota','storage'}
|
||||
@ -51,7 +52,7 @@ async def advance_run(session,run_id,settings):
|
||||
r.state='paused'
|
||||
else:
|
||||
r.state='running';r.started_at=r.started_at or utcnow()
|
||||
for key in ('shot_1','shot_2','shot_3','compose'):
|
||||
for key in ordered_step_keys(r.spec_snapshot):
|
||||
step=bykey[key]
|
||||
if step.state=='succeeded':continue
|
||||
if step.state=='cancelled':
|
||||
|
||||
@ -15,7 +15,8 @@ from .events import emit_asset, emit_job
|
||||
from .jobs import create_jobs, Submit, TERMINAL, GPU_TYPES
|
||||
from .models import Asset, Event, Job, User, utcnow
|
||||
from .submissions import accept_submission
|
||||
from .timeline import Strict, WorkflowSpec, compile_timeline
|
||||
from .timeline import Strict, WorkflowSpec, compile_timeline, ordered_step_keys
|
||||
from .runtime_policy import read_runtime_policy
|
||||
from .v2_models import WorkflowDraft, WorkflowRun, WorkflowStep, AssetReference, Execution
|
||||
|
||||
router=APIRouter(prefix='/workflows',tags=['workflows'])
|
||||
@ -23,8 +24,8 @@ runs_router=APIRouter(prefix='/workflow-runs',tags=['workflows'])
|
||||
RUN_TERMINAL={'succeeded','cancelled','failed'}
|
||||
|
||||
class DraftCreate(Strict):
|
||||
name: str = Field(default='三镜头工作流',min_length=1,max_length=255)
|
||||
kind: Literal['three_shot']='three_shot'
|
||||
name: str = Field(default='多镜头工作流',min_length=1,max_length=255)
|
||||
kind: Literal['three_shot','multi_shot']='multi_shot'
|
||||
spec: WorkflowSpec
|
||||
class DraftPatch(Strict):
|
||||
name: str | None = Field(default=None,min_length=1,max_length=255)
|
||||
@ -61,7 +62,9 @@ async def cursor(session,owner_id):
|
||||
async def snapshot_run(session,owner_id,run_id):
|
||||
r=await owned(session,WorkflowRun,run_id,owner_id)
|
||||
d=await owned(session,WorkflowDraft,r.draft_id,owner_id)
|
||||
steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id).order_by(WorkflowStep.step_key))).all()
|
||||
steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id))).all()
|
||||
order={key:i for i,key in enumerate(ordered_step_keys(r.spec_snapshot))}
|
||||
steps.sort(key=lambda step:(order.get(step.step_key,len(order)),step.step_key))
|
||||
selected=[step.selected_job_id for step in steps if step.selected_job_id]
|
||||
from sqlalchemy import or_
|
||||
jobs=(await session.scalars(select(Job).where(or_(Job.run_id==r.id,Job.id.in_(selected))).order_by(Job.created_at,Job.id))).all()
|
||||
@ -70,7 +73,7 @@ async def snapshot_run(session,owner_id,run_id):
|
||||
a=await session.get(Asset,r.current_output_asset_id)
|
||||
if a and a.ready and a.deleted_at is None: outputs=[asset_dto(a)]
|
||||
run={k:getattr(r,k) for k in ('id','draft_id','draft_revision','state','desired_state','execution_mode','version','batch_id','hold_reasons')}
|
||||
run.update(error=r.error_json,created_at=iso(r.created_at),started_at=iso(r.started_at),finished_at=iso(r.finished_at),result_assets=outputs,completed_steps=sum(s.state=='succeeded' for s in steps),total_steps=4)
|
||||
run.update(error=r.error_json,created_at=iso(r.created_at),started_at=iso(r.started_at),finished_at=iso(r.finished_at),result_assets=outputs,completed_steps=sum(s.state=='succeeded' for s in steps),total_steps=len(steps))
|
||||
return dict(draft=draft_dto(d),run=run,steps=[step_dto(s) for s in steps],jobs=[await job_dto(session,j) for j in jobs],cursor=await cursor(session,owner_id))
|
||||
|
||||
async def emit_run(session,r,increment=True):
|
||||
@ -78,8 +81,12 @@ async def emit_run(session,r,increment=True):
|
||||
snap=await snapshot_run(session,r.owner_id,r.id)
|
||||
emit_asset(session,r.owner_id,'workflow.updated',{k:snap[k] for k in ('run','steps','jobs')})
|
||||
|
||||
async def validate_spec(session,owner_id,spec):
|
||||
async def validate_spec(session,owner_id,spec,settings):
|
||||
spec=spec if isinstance(spec,WorkflowSpec) else WorkflowSpec.model_validate(spec)
|
||||
policy=read_runtime_policy(settings)
|
||||
if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员')
|
||||
if len(spec.shots)>policy['workflow_max_shots']:
|
||||
fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个镜头,可由管理员调整")
|
||||
ids=[s.image_asset_id for s in spec.shots if s.image_asset_id]
|
||||
if spec.render.audio:ids.append(spec.render.audio.asset_id)
|
||||
assets={}
|
||||
@ -125,18 +132,19 @@ async def create_run(session,owner_id,draft_id,expected_version,revision,mode='i
|
||||
await check_parent_capacity(session,settings,owner_id,'run')
|
||||
d=await owned(session,WorkflowDraft,draft_id,owner_id)
|
||||
if d.version!=expected_version or d.revision!=revision:fail(409,'draft_version_conflict','草稿已更新,请刷新版本')
|
||||
plan,assets=await validate_spec(session,owner_id,d.spec,settings)
|
||||
if mode=='interactive':
|
||||
active=await session.scalar(select(WorkflowRun.id).where(WorkflowRun.owner_id==owner_id,WorkflowRun.execution_mode=='interactive',WorkflowRun.state.not_in(RUN_TERMINAL)))
|
||||
if active:fail(429,'quota_exceeded','已有活动交互工作流')
|
||||
plan,assets=await validate_spec(session,owner_id,d.spec)
|
||||
snapshot={**plan.spec,'compiled':{'generation_parameters':plan.generation_parameters,'canvas':list(plan.canvas),'preset_version':'wan-three-shot-v1'}}
|
||||
snapshot={**plan.spec,'compiled':{'generation_parameters':plan.generation_parameters,'canvas':list(plan.canvas),'preset_version':'wan-three-shot-v1' if plan.spec['schema_version']==1 else 'wan-multi-shot-v2'}}
|
||||
r=WorkflowRun(owner_id=owner_id,draft_id=d.id,draft_revision=d.revision,spec_snapshot=snapshot,spec_hash=digest(snapshot),execution_mode=mode,batch_id=batch_id,batch_item_index=batch_item_index)
|
||||
session.add(r);await session.flush()
|
||||
reuse=None
|
||||
if reuse_run_id:reuse=await owned(session,WorkflowRun,reuse_run_id,owner_id)
|
||||
for shot in plan.spec['shots']:
|
||||
source=assets.get(shot.get('image_asset_id'))
|
||||
h=digest({'shot':shot,'generation_parameters':plan.generation_parameters,'source_sha256':source.sha256 if source else None})
|
||||
generation_shot={k:v for k,v in shot.items() if k!='duration_frames'}
|
||||
h=digest({'shot':generation_shot,'generation_parameters':plan.generation_parameters,'source_sha256':source.sha256 if source else None})
|
||||
step=WorkflowStep(run_id=r.id,step_key=shot['key'],kind='video.generate',dependencies=[],semantic_input_hash=h)
|
||||
if reuse:
|
||||
old=await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id==reuse.id,WorkflowStep.step_key==shot['key'],WorkflowStep.semantic_input_hash==h,WorkflowStep.state=='succeeded'))
|
||||
@ -147,7 +155,7 @@ async def create_run(session,owner_id,draft_id,expected_version,revision,mode='i
|
||||
step.selected_job_id=job.id;step.state='succeeded';step.explicit_attempt=old.explicit_attempt
|
||||
assets[out.id]=out
|
||||
session.add(step)
|
||||
session.add(WorkflowStep(run_id=r.id,step_key='compose',kind='video.compose',dependencies=['shot_1','shot_2','shot_3'],semantic_input_hash=digest(snapshot)))
|
||||
session.add(WorkflowStep(run_id=r.id,step_key='compose',kind='video.compose',dependencies=[shot['key'] for shot in plan.spec['shots']],semantic_input_hash=digest(snapshot)))
|
||||
for a in assets.values():session.add(AssetReference(owner_id=owner_id,asset_id=a.id,ref_kind='run',ref_id=r.id))
|
||||
d.current_run_id=r.id;d.version+=1;d.updated_at=utcnow()
|
||||
await session.flush();emit_asset(session,owner_id,'draft.updated',{'draft':draft_dto(d)});await emit_run(session,r,False)
|
||||
@ -166,9 +174,11 @@ async def create_child(session,r,step,settings):
|
||||
if shot.get('image_asset_id'):inputs['image_asset_id']=shot['image_asset_id']
|
||||
p={**snapshot['compiled']['generation_parameters'],**shot['parameters']}
|
||||
else:
|
||||
steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id,WorkflowStep.kind=='video.generate').order_by(WorkflowStep.step_key))).all()
|
||||
steps=(await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id==r.id,WorkflowStep.kind=='video.generate'))).all()
|
||||
bykey={s.step_key:s for s in steps}
|
||||
ids=[];hashes=[]
|
||||
for s in steps:
|
||||
for shot in snapshot['shots']:
|
||||
s=bykey[shot['key']]
|
||||
a=await selected_output(session,s.selected_job_id,r.owner_id)
|
||||
if not a:fail(409,'dependency_changed','镜头产物不存在')
|
||||
ids.append(a.id);hashes.append(a.sha256)
|
||||
@ -182,7 +192,7 @@ async def create_child(session,r,step,settings):
|
||||
from .batches import run_member_holds
|
||||
r.hold_reasons=sorted(await run_member_holds(session,r))
|
||||
step.explicit_attempt+=1
|
||||
jobs=await create_jobs(session,Submit(task_type=step.kind,input=inputs,parameters=p,execution_mode=r.execution_mode),SimpleNamespace(id=r.owner_id,auth_kind='session',scopes=[]),settings,key=f'run:{r.id}:{step.step_key}:{step.explicit_attempt}',internal=True)
|
||||
jobs=await create_jobs(session,Submit(task_type=step.kind,input=inputs,parameters=p,execution_mode=r.execution_mode),SimpleNamespace(id=r.owner_id,auth_kind='session',scopes=[]),settings,key=f'run:{r.id}:{step.step_key}:{step.explicit_attempt}',internal=True,frozen_workflow=True)
|
||||
j=jobs[0];j.run_id=r.id;j.step_key=step.step_key;j.batch_id=r.batch_id;j.batch_item_index=r.batch_item_index;j.explicit_attempt=step.explicit_attempt
|
||||
j.desired_state=r.desired_state;j.hold_reasons=list(r.hold_reasons or [])
|
||||
step.selected_job_id=j.id;step.state='ready';step.version+=1
|
||||
@ -220,8 +230,8 @@ async def post_draft(body:DraftCreate,request:Request,actor:Actor=Depends(csrf_a
|
||||
async with request.app.state.db.session() as s:
|
||||
from .maintenance import require_writable
|
||||
require_writable(request.app.state.settings)
|
||||
plan,assets=await validate_spec(s,actor.id,body.spec)
|
||||
d=WorkflowDraft(owner_id=actor.id,name=body.name,kind=body.kind,spec=body.spec.model_dump(mode='json'));s.add(d);await s.flush()
|
||||
plan,assets=await validate_spec(s,actor.id,body.spec,request.app.state.settings)
|
||||
d=WorkflowDraft(owner_id=actor.id,name=body.name,kind=body.kind,spec=plan.spec);s.add(d);await s.flush()
|
||||
for a in assets.values():s.add(AssetReference(owner_id=actor.id,asset_id=a.id,ref_kind='draft',ref_id=d.id))
|
||||
emit_asset(s,actor.id,'draft.updated',{'draft':draft_dto(d)});await s.commit();return draft_dto(d)
|
||||
|
||||
@ -248,10 +258,10 @@ async def patch_draft(id:str,body:DraftPatch,request:Request,if_match:str|None=H
|
||||
if if_match is None or if_match.strip('"')!=str(d.version):fail(409,'draft_version_conflict','草稿版本冲突')
|
||||
if body.name is not None:d.name=body.name
|
||||
if body.spec is not None:
|
||||
plan,assets=await validate_spec(s,actor.id,body.spec)
|
||||
plan,assets=await validate_spec(s,actor.id,body.spec,request.app.state.settings)
|
||||
await s.execute(delete(AssetReference).where(AssetReference.ref_kind=='draft',AssetReference.ref_id==d.id))
|
||||
for a in assets.values():s.add(AssetReference(owner_id=actor.id,asset_id=a.id,ref_kind='draft',ref_id=d.id))
|
||||
d.spec=body.spec.model_dump(mode='json');d.revision+=1
|
||||
d.spec=plan.spec;d.revision+=1
|
||||
d.version+=1;d.updated_at=utcnow();emit_asset(s,actor.id,'draft.updated',{'draft':draft_dto(d)});await s.commit();return draft_dto(d)
|
||||
|
||||
@router.post('/{id}/runs',status_code=202)
|
||||
|
||||
@ -37,3 +37,25 @@ async def test_real_119_frame_source_rejected(tmp_path):
|
||||
await run_process(['ffmpeg','-v','error','-f','lavfi','-i','color=c=red:s=1920x1056:r=24','-frames:v','119','-c:v','libx264','-preset','ultrafast','-threads','2',str(source)])
|
||||
with pytest.raises(MediaError,match='120'):
|
||||
await compose_workflow(compile_timeline(spec(),{}),tmp_path/'work',settings=settings,sources=[source]*3)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_real_variable_sixteen_second_workflow(tmp_path):
|
||||
from test_multishot_v3 import story
|
||||
settings=SimpleNamespace(workspace_root=tmp_path,ffmpeg_bin='ffmpeg',ffprobe_bin='ffprobe',max_output_bytes=100*1024*1024)
|
||||
body=story(durations=[24,120,120,120])
|
||||
body['render']={'subtitles':[{'start_frame':361,'end_frame':384,'text':'Beyond fifteen seconds'}]}
|
||||
plan=compile_timeline(body,{})
|
||||
sources=[]
|
||||
w,h=plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height']
|
||||
for index,color in enumerate(('red','green','blue','yellow')):
|
||||
source=tmp_path/f'source-{index}.mp4'
|
||||
await run_process(['ffmpeg','-v','error','-f','lavfi','-i',f'color=c={color}:s={w}x{h}:r=24','-frames:v','121','-c:v','libx264','-preset','ultrafast','-threads','2',str(source)])
|
||||
sources.append(source)
|
||||
result=await compose_workflow(plan,tmp_path/'work',settings=settings,sources=sources)
|
||||
track=await inspect_video_track(result.outputs[0],settings)
|
||||
assert track['frames']==384 and track['fps']==24
|
||||
assert (track['width'],track['height'])==(1920,1080)
|
||||
assert abs(track['duration']-16)<=.10
|
||||
assert result.result['clip_count']==4
|
||||
await run_process(['ffmpeg','-v','error','-i',str(result.outputs[0]),'-f','null','-'])
|
||||
|
||||
246
backend/tests/test_multishot_v3.py
Normal file
@ -0,0 +1,246 @@
|
||||
"""Variable story length without changing the short-clip model contract."""
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.models import Job
|
||||
from app.timeline import WorkflowSpec, compile_timeline
|
||||
from test_timeline_v2 import spec as legacy_spec
|
||||
from test_workflows_v2 import wf, run, publish_video
|
||||
|
||||
|
||||
def story(count=12, durations=None):
|
||||
durations = durations or [120] * count
|
||||
return {'schema_version': 2, 'shots': [
|
||||
{'key': f'shot_{i + 1}', 'prompt': f'镜头{i + 1}', 'duration_frames': frames,
|
||||
'parameters': {'seed': i + 1}}
|
||||
for i, frames in enumerate(durations)
|
||||
], 'profile': 'landscape_1080_v1'}
|
||||
|
||||
|
||||
def test_dynamic_timeline_derives_duration_and_accepts_late_audio_subtitles():
|
||||
body = story(durations=[24] + [120] * 11)
|
||||
body['render'] = {'audio': {'asset_id': 'voice', 'source_start_ms': 0,
|
||||
'source_end_ms': 10000, 'offset_frame': 960},
|
||||
'subtitles': [{'start_frame': 961, 'end_frame': 1344, 'text': '乘风南迁'}]}
|
||||
plan = compile_timeline(body, {'voice': {'kind': 'audio', 'duration_seconds': 10}})
|
||||
assert plan.frames == 1344
|
||||
assert plan.shot_frames == (24,) + (120,) * 11
|
||||
assert plan.spec['render']['total_frames'] == 1344
|
||||
assert plan.generation_parameters['num_frames'] == 121
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['keys', 'duplicate', 'zero', 'too_long', 'total', 'subtitle', 'audio'])
|
||||
def test_dynamic_timeline_rejects_inconsistent_order_and_bounds(change):
|
||||
body = story(4)
|
||||
if change == 'keys': body['shots'][1]['key'] = 'shot_12'
|
||||
elif change == 'duplicate': body['shots'][1]['key'] = 'shot_1'
|
||||
elif change == 'zero': body['shots'][0]['duration_frames'] = 0
|
||||
elif change == 'too_long': body['shots'][0]['duration_frames'] = 121
|
||||
elif change == 'total': body['render'] = {'total_frames': 481}
|
||||
elif change == 'subtitle': body['render'] = {'subtitles': [{'start_frame': 0, 'end_frame': 481, 'text': 'bad'}]}
|
||||
else: body['render'] = {'audio': {'asset_id': 'a', 'source_start_ms': 0, 'source_end_ms': 20000, 'offset_frame': 1}}
|
||||
with pytest.raises(ValidationError): WorkflowSpec.model_validate(body)
|
||||
|
||||
|
||||
def test_legacy_normalized_spec_and_exact_length_stay_compatible():
|
||||
plan = compile_timeline(legacy_spec(), {})
|
||||
assert plan.frames == 360
|
||||
assert all('duration_frames' not in shot for shot in plan.spec['shots'])
|
||||
bad = legacy_spec(); bad['shots'].append({'key': 'shot_4', 'prompt': 'extra'})
|
||||
with pytest.raises(ValidationError): WorkflowSpec.model_validate(bad)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_twelve_shot_run_uses_snapshot_order_then_compose(wf):
|
||||
from app.workflow_engine import advance_workflows
|
||||
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story()})
|
||||
assert response.status_code == 201, response.text
|
||||
snapshot = await run(wf, response.json())
|
||||
rid = snapshot['run']['id']
|
||||
assert snapshot['run']['total_steps'] == 13
|
||||
expected_keys = [f'shot_{i}' for i in range(1, 13)] + ['compose']
|
||||
assert [step['step_key'] for step in snapshot['steps']] == expected_keys
|
||||
ids = []
|
||||
for key in expected_keys[:-1]:
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
async with wf.app.state.db.session() as session:
|
||||
job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded'))
|
||||
assert job.step_key == key
|
||||
jid = job.id
|
||||
ids.append(await publish_video(wf, jid))
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
async with wf.app.state.db.session() as session:
|
||||
compose = await session.scalar(select(Job).where(Job.run_id == rid, Job.step_key == 'compose'))
|
||||
assert compose.input_json['asset_ids'] == ids
|
||||
assert compose.parameters['workflow_spec']['render']['total_frames'] == 1440
|
||||
await publish_video(wf, compose.id, compose=True)
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
snapshot = (await wf.client.get('/api/workflow-runs/' + rid)).json()
|
||||
assert snapshot['run']['state'] == 'succeeded'
|
||||
assert snapshot['run']['completed_steps'] == snapshot['run']['total_steps'] == 13
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_trim_only_revision_reuses_generated_shot(wf):
|
||||
from app.workflow_engine import advance_workflows
|
||||
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(1)})
|
||||
assert response.status_code == 201, response.text
|
||||
draft = response.json(); first = await run(wf, draft)
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
first = (await wf.client.get('/api/workflow-runs/' + first['run']['id'])).json()
|
||||
jid = first['steps'][0]['selected_job_id']
|
||||
await publish_video(wf, jid)
|
||||
await wf.client.post('/api/workflow-runs/' + first['run']['id'] + '/cancel', json={}, headers={'Idempotency-Key': 'cancel'})
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
draft = (await wf.client.get('/api/workflows/' + draft['id'])).json()
|
||||
body = story(1); body['shots'][0]['duration_frames'] = 48
|
||||
changed = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': body}, headers={'If-Match': str(draft['version'])})
|
||||
assert changed.status_code == 200, changed.text
|
||||
draft = changed.json()
|
||||
response = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={
|
||||
'draft_revision': draft['revision'], 'expected_version': draft['version'],
|
||||
'reuse_run_id': first['run']['id']}, headers={'Idempotency-Key': 'trim'})
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()['steps'][0]['selected_job_id'] == jid
|
||||
assert response.json()['steps'][0]['state'] == 'succeeded'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_cap_checks_new_save_run_but_not_frozen_children(wf, monkeypatch):
|
||||
from app import workflows
|
||||
from app import runtime_policy
|
||||
from app.workflow_engine import advance_workflows
|
||||
limit = [12]
|
||||
monkeypatch.setattr(workflows, 'read_runtime_policy', lambda settings: {'workflow_max_shots': limit[0], 'configuration_error': None})
|
||||
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', workflows.read_runtime_policy)
|
||||
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)})
|
||||
assert response.status_code == 201, response.text
|
||||
draft = response.json(); accepted = await run(wf, draft)
|
||||
limit[0] = 3
|
||||
rejected = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)})
|
||||
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
current = (await wf.client.get('/api/workflows/' + draft['id'])).json()
|
||||
rejected = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': story(4)}, headers={'If-Match': str(current['version'])})
|
||||
assert rejected.status_code == 422
|
||||
rejected = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={
|
||||
'draft_revision': current['revision'], 'expected_version': current['version']}, headers={'Idempotency-Key': 'over-limit'})
|
||||
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
rid = accepted['run']['id']
|
||||
for i in range(4):
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
async with wf.app.state.db.session() as session:
|
||||
job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded'))
|
||||
assert job.step_key == f'shot_{i + 1}'
|
||||
await publish_video(wf, job.id)
|
||||
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||||
result = (await wf.client.get('/api/workflow-runs/' + rid)).json()
|
||||
assert result['steps'][-1]['step_key'] == 'compose' and result['steps'][-1]['selected_job_id']
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_new_manual_composition_uses_configured_clip_cap(system, monkeypatch):
|
||||
from app import runtime_policy
|
||||
limit = [4]
|
||||
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
|
||||
'workflow_max_shots': limit[0], 'configuration_error': None})
|
||||
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
|
||||
aid = await publish_video(system, source.json()['jobs'][0]['id'])
|
||||
body = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4},
|
||||
'parameters': {'clips': [{'asset_id': aid}] * 4}}
|
||||
accepted = await system.client.post('/api/jobs', json=body)
|
||||
assert accepted.status_code == 202, accepted.text
|
||||
limit[0] = 3
|
||||
rejected = await system.client.post('/api/jobs', json=body)
|
||||
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_new_batch_composition_enforces_cap_and_rolls_back_atomically(system, monkeypatch):
|
||||
from sqlalchemy import func
|
||||
from app import runtime_policy
|
||||
from app.v2_models import Batch
|
||||
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
|
||||
'workflow_max_shots': 3, 'configuration_error': None})
|
||||
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
|
||||
aid = await publish_video(system, source.json()['jobs'][0]['id'])
|
||||
job = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4},
|
||||
'parameters': {'clips': [{'asset_id': aid}] * 4}}
|
||||
direct = await system.client.post('/api/jobs', json=job)
|
||||
assert direct.status_code == 422 and direct.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
batch = await system.client.post('/api/batches', json={'items': [
|
||||
{'kind': 'job', 'task_type': 'math.solve', 'input': {'prompt': '2+2'}},
|
||||
{'kind': 'job', **job}]}, headers={'Idempotency-Key': 'over-cap-batch'})
|
||||
assert batch.status_code == 422 and batch.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
async with system.app.state.db.session() as session:
|
||||
assert await session.scalar(select(func.count()).select_from(Batch)) == 0
|
||||
assert await session.scalar(select(func.count()).select_from(Job)) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_accepted_batch_replays_after_cap_reduction_but_new_batch_rejected(system, monkeypatch):
|
||||
from app import runtime_policy
|
||||
limit = [4]
|
||||
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
|
||||
'workflow_max_shots': limit[0], 'configuration_error': None})
|
||||
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
|
||||
aid = await publish_video(system, source.json()['jobs'][0]['id'])
|
||||
body = {'items': [{'kind': 'job', 'task_type': 'video.compose',
|
||||
'input': {'asset_ids': [aid] * 4}, 'parameters': {'clips': [{'asset_id': aid}] * 4}}]}
|
||||
accepted = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'})
|
||||
assert accepted.status_code == 202, accepted.text
|
||||
limit[0] = 3
|
||||
replay = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'})
|
||||
assert replay.status_code == 202 and replay.json()['batch']['id'] == accepted.json()['batch']['id']
|
||||
rejected = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'new-batch'})
|
||||
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manual_composition_can_exceed_twenty_four_clips_and_thirty_minutes(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from app import providers
|
||||
source = tmp_path / 'source.mp4'; source.write_bytes(b'x')
|
||||
work = tmp_path / 'work'; work.mkdir()
|
||||
calls = []
|
||||
async def inspect(path, settings):
|
||||
return {'kind': 'video', 'has_audio': False,
|
||||
'duration_seconds': 3600 if path.name == 'composition.mp4' else 120}
|
||||
async def process(argv, **kwargs):
|
||||
calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b''
|
||||
monkeypatch.setattr(providers, 'inspect_media', inspect)
|
||||
monkeypatch.setattr(providers, 'run_process', process)
|
||||
settings = SimpleNamespace(workspace_root=tmp_path, request_timeout_seconds=5,
|
||||
ffmpeg_bin='ffmpeg', max_output_bytes=1000000)
|
||||
provider = providers.Provider(settings)
|
||||
try:
|
||||
result = await provider._compose({'asset_ids': ['video'] * 30},
|
||||
{'clips': [{'asset_id': 'video'}] * 30}, {'video': source}, work)
|
||||
finally:
|
||||
await provider.aclose()
|
||||
assert len(calls) == 31
|
||||
assert result.result['clip_count'] == 30 and result.result['duration_seconds'] == 3600
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_media_variable_trims_and_total_frame_validation(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from app import media
|
||||
plan = compile_timeline(story(durations=[24, 120, 120, 120]), {})
|
||||
sources = [tmp_path / f'{i}.mp4' for i in range(4)]
|
||||
for p in sources: p.write_bytes(b'x')
|
||||
calls = []
|
||||
async def track(path, settings):
|
||||
return {'frames': 384 if path.name == 'workflow.mp4' else 121, 'fps': 24,
|
||||
'width': 1920, 'height': 1080 if path.name == 'workflow.mp4' else 1056,
|
||||
'duration': 16 if path.name == 'workflow.mp4' else 121 / 24}
|
||||
async def process(argv, **kwargs):
|
||||
calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b''
|
||||
monkeypatch.setattr(media, 'inspect_video_track', track)
|
||||
monkeypatch.setattr(media, 'run_process', process)
|
||||
result = await media.compose_workflow(plan, tmp_path / 'work', settings=SimpleNamespace(
|
||||
workspace_root=tmp_path, ffmpeg_bin='ffmpeg', max_output_bytes=1000000), sources=sources)
|
||||
assert [int(c[c.index('-frames:v') + 1]) for c in calls] == [24, 120, 120, 120, 384]
|
||||
assert 'atrim=duration=16' in calls[-1]
|
||||
assert result.result['duration_seconds'] == 16
|
||||
assert result.result['clip_count'] == 4
|
||||
130
backend/tests/test_runtime_policy.py
Normal file
@ -0,0 +1,130 @@
|
||||
"""Operator policy is hot-loaded; browser requests cannot override scheduling."""
|
||||
from datetime import datetime
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def write_policy(path, enabled, max_shots=120):
|
||||
path.write_text(json.dumps({"schema_version": 1,
|
||||
"batch_window_enabled": enabled, "workflow_max_shots": max_shots}), encoding="utf-8")
|
||||
|
||||
|
||||
def test_daytime_policy_switch_is_hot_loaded_without_changing_job_mode(tmp_path):
|
||||
from app.resource_policy import admits, execution_policy
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
settings = SimpleNamespace(runtime_policy_file=path)
|
||||
job = SimpleNamespace(execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[])
|
||||
noon = datetime.fromisoformat("2026-11-11T12:00:00+08:00")
|
||||
write_policy(path, False, 240)
|
||||
assert admits(job, now=noon, settings=settings)
|
||||
info = execution_policy(noon, settings=settings)
|
||||
assert info["batch_window_enabled"] is False and info["batch_open"]
|
||||
assert info["next_batch_at"] is None
|
||||
write_policy(path, True)
|
||||
assert not admits(job, now=noon, settings=settings)
|
||||
assert execution_policy(noon, settings=settings)["batch_window_enabled"] is True
|
||||
assert job.execution_mode == "batch"
|
||||
write_policy(path, False)
|
||||
job.hold_reasons = ["batch_pause"]
|
||||
assert not admits(job, now=noon, settings=settings)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
{"schema_version": 1, "batch_window_enabled": "false"},
|
||||
{"schema_version": True, "batch_window_enabled": False},
|
||||
{"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": True},
|
||||
{"schema_version": 1, "batch_window_enabled": False, "workflow_max_shots": 1001},
|
||||
{"schema_version": 1, "batch_window_enabled": False, "unexpected": True},
|
||||
[], None,
|
||||
])
|
||||
def test_bad_runtime_policy_only_blocks_batch(tmp_path, value):
|
||||
from app.runtime_policy import read_runtime_policy
|
||||
from app.resource_policy import admits, execution_policy
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
settings = SimpleNamespace(runtime_policy_file=path)
|
||||
path.write_text(json.dumps(value), encoding="utf-8")
|
||||
result = read_runtime_policy(settings)
|
||||
assert result["batch_window_enabled"] is True
|
||||
assert result["configuration_error"] == "runtime_policy_invalid"
|
||||
job = SimpleNamespace(execution_mode="batch", desired_state="run", cancel_requested=False, hold_reasons=[])
|
||||
night = datetime.fromisoformat("2026-11-11T22:00:00+08:00")
|
||||
assert not admits(job, now=night, settings=settings)
|
||||
assert not execution_policy(night, settings=settings)["batch_open"]
|
||||
job.execution_mode = "interactive"
|
||||
assert admits(job, now=night, settings=settings)
|
||||
|
||||
|
||||
def test_missing_file_is_production_default_and_environment_selects_file(tmp_path, monkeypatch):
|
||||
from app.config import Settings
|
||||
from app.runtime_policy import read_runtime_policy
|
||||
path = tmp_path / "missing.json"
|
||||
monkeypatch.setenv("CMVR_MODE", "test")
|
||||
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
|
||||
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("RUNTIME_POLICY_FILE", str(path))
|
||||
settings = Settings.from_env()
|
||||
assert settings.runtime_policy_file == path
|
||||
assert read_runtime_policy(settings) == {"batch_window_enabled": True,
|
||||
"workflow_max_shots": 120, "configuration_error": None}
|
||||
|
||||
|
||||
def test_empty_environment_path_keeps_shared_default_and_unreadable_file_fails_closed(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
from app.config import Settings
|
||||
from app.runtime_policy import read_runtime_policy
|
||||
monkeypatch.setenv("CMVR_MODE", "test")
|
||||
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
|
||||
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("RUNTIME_POLICY_FILE", "")
|
||||
assert Settings.from_env().runtime_policy_file == Path("/workspace/projects/llm-services/config/runtime-policy.json")
|
||||
policy = read_runtime_policy(SimpleNamespace(runtime_policy_file=tmp_path))
|
||||
assert policy["batch_window_enabled"] is True
|
||||
assert policy["configuration_error"] == "runtime_policy_unavailable"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_window_drains_same_waiting_job_and_preserves_corrupt_clock(system, monkeypatch):
|
||||
from app import resource_policy
|
||||
from app.models import Job
|
||||
from app.admission_clock import AdmissionClock
|
||||
path = system.settings.state_root / "runtime-policy.json"
|
||||
system.settings.runtime_policy_file = path
|
||||
write_policy(path, True)
|
||||
monkeypatch.setattr(resource_policy, "execution_policy", lambda now=None: {"batch_open": False})
|
||||
response = await system.client.post("/api/jobs", json={"task_type": "math.solve",
|
||||
"input": {"prompt": "2+3"}, "execution_mode": "batch"})
|
||||
assert response.status_code == 202, response.text
|
||||
job_id = response.json()["jobs"][0]["id"]
|
||||
coordinator = system.app.state.coordinator
|
||||
clock_file = system.settings.state_root / "admission-clock.json"
|
||||
clock_file.write_text("{corrupt", encoding="utf-8")
|
||||
coordinator._admission_clock = AdmissionClock(clock_file)
|
||||
await coordinator.run_once(force=True)
|
||||
assert system.provider.cpu_runs == 0
|
||||
write_policy(path, False)
|
||||
await coordinator.run_once(force=True)
|
||||
await coordinator._cpu[job_id]
|
||||
async with system.app.state.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
assert job.state == "succeeded" and job.attempt_count == 1
|
||||
assert job.execution_mode == "batch"
|
||||
assert clock_file.read_text(encoding="utf-8") == "{corrupt"
|
||||
write_policy(path, True)
|
||||
assert not coordinator._clock_allows(job)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_status_and_capabilities_share_live_policy_and_workflow_limits(system):
|
||||
path = system.settings.state_root / "runtime-policy.json"
|
||||
system.settings.runtime_policy_file = path
|
||||
write_policy(path, False, 240)
|
||||
for route in ["/api/capabilities", "/api/system/status"]:
|
||||
response = await system.client.get(route)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
assert body["execution_policy"]["batch_window_enabled"] is False
|
||||
assert body["execution_policy"]["configuration_error"] is None
|
||||
assert body["workflow_limits"] == {"max_shots": 240, "source_frames": 121,
|
||||
"max_clip_frames": 120, "fps": 24}
|
||||
@ -2,7 +2,7 @@ name: cmvr-visual
|
||||
services:
|
||||
api:
|
||||
build: ./backend
|
||||
image: cmvr-visual-api:v2-20261110
|
||||
image: cmvr-visual-api:v3-20261111
|
||||
container_name: cmvr-visual-api
|
||||
env_file: .env
|
||||
environment:
|
||||
@ -14,6 +14,7 @@ services:
|
||||
INFERENCE_API_KEY_FILE: /workspace/projects/llm-services/config/api_key
|
||||
GPU_STATUS_PATH: /run/llm-gpu-policy/status.json
|
||||
GPU_SCHEDULER_PATH: /workspace/projects/llm-services/state/gpu-scheduler.json
|
||||
RUNTIME_POLICY_FILE: /workspace/projects/llm-services/config/runtime-policy.json
|
||||
TTS_BASE_URL: http://cmvr-visual-tts:8001/v1
|
||||
TTS_MODEL: kokoro-82m
|
||||
TTS_VOICES: zf_xiaobei,zm_yunxi
|
||||
@ -41,7 +42,7 @@ services:
|
||||
logging: {driver: json-file, options: {max-size: 10m, max-file: '3'}}
|
||||
frontend:
|
||||
build: {context: ., dockerfile: deploy/Dockerfile.frontend}
|
||||
image: cmvr-visual-frontend:v2-20261110
|
||||
image: cmvr-visual-frontend:v3-20261111
|
||||
container_name: cmvr-visual-frontend
|
||||
ports: ['127.0.0.1:${WEB_PORT:-18193}:8080']
|
||||
depends_on: [api]
|
||||
|
||||
5
deploy/runtime-policy.development.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"batch_window_enabled": false,
|
||||
"workflow_max_shots": 120
|
||||
}
|
||||
5
deploy/runtime-policy.production.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"batch_window_enabled": true,
|
||||
"workflow_max_shots": 120
|
||||
}
|
||||
@ -87,6 +87,12 @@ HTTP remains the command/query channel, SSE the owner-scoped notification channe
|
||||
- Asset list additionally accepts `favorite` and `origin` SQL filters. Workflow references protect frozen inputs/outputs from physical deletion.
|
||||
- SSE adds `draft.updated:{draft}`, `workflow.updated:{run,steps,jobs}`, `batch.updated:{batch,items}` with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requires `events:read` and Authorization, never tokens in URLs.
|
||||
|
||||
Workflow spec schema1: exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`; `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames:360,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}`. Video track is exactly360 frames. Each enhanced shot contributes120 frames; short sources fail. Audio must fit the timeline explicitly, subtitles use whole-film half-open frame intervals.
|
||||
Legacy workflow spec schema1 remains exactly ordered `shot_1,shot_2,shot_3`, each `{key,prompt,image_asset_id:null|string,parameters:{seed}}`, with360 frames at24fps. Its serialization and generation hashes remain compatible.
|
||||
|
||||
Schema2 accepts1–1000 sequentially ordered `shot_N` entries with additional `duration_frames` (strict integer24–120, default120). New submissions are additionally bounded by the operator's configured shot limit. `profile=landscape_1080_v1|portrait_1080_v1`; `render={fps:24,total_frames?:integer,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}`. Omitted total_frames is derived from shots; a supplied unequal value fails validation. Every model call still produces121 source frames; composition trims to each requested frame count. Audio must fit the entire dynamic timeline explicitly and subtitles use whole-film half-open frame intervals. Run total_steps is shot count+1, and steps/compose inputs follow snapshot order, including shot_10. New draft kind is multi_shot; three_shot remains accepted.
|
||||
|
||||
Capabilities and system/status now include `workflow_limits={max_shots,source_frames:121,max_clip_frames:120,fps:24}` and `execution_policy.batch_window_enabled`, `configuration_error`, nullable `next_batch_at`. Both API and GPU worker hot-read the operator-owned RUNTIME_POLICY_FILE (default `/workspace/projects/llm-services/config/runtime-policy.json`): `{schema_version:1,batch_window_enabled:boolean,workflow_max_shots:integer1..1000}`. Missing means production defaults; malformed policy blocks new batch compute. False bypasses only the clock/window, preserves durable clock evidence and all manual/maintenance/owner/GPU priority controls. Client payloads cannot override this switch. Already admitted work finishes when the switch is re-enabled.
|
||||
|
||||
Manual video.compose no longer has a24-clip or1800-second final-duration cap. New commands respect the same configured clip-count limit; source cuts stay within decoded media and a86400-second source bound. Output/intermediate size, storage, process and overall execution time budgets still apply.
|
||||
|
||||
Private inference protocol2 carries server-generated `scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1'}`. Its `/capabilities` reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate `new_gpu`, `cpu_media`, `qwen_http` slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users.
|
||||
|
||||
@ -0,0 +1,63 @@
|
||||
# 可配置时段与多镜头长视频实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. Each owner writes a failing regression, implements the change, verifies it, and freezes for root review.
|
||||
|
||||
**Goal:** 开发环境全天测试批量任务,生产环境配置恢复夜间准入;可变镜头和选用帧数替代固定15秒,并交付中文手册与鲲鹏示例。
|
||||
|
||||
**Architecture:** API和既有GPU worker读取同一权威文件。工作流schema2用有序镜头,成片长度为选用帧数之和;旧schema1保持兼容。沿用Vue3/Pinia/Element Plus、FastAPI/MySQL、HTTP+SSE和现有GPU监管。
|
||||
|
||||
**Spec:** 用户2026-11-11三项修改及下列接口。用户授权直接处理;沿用现有项目与分支。
|
||||
|
||||
## 全局约束
|
||||
|
||||
- 配置:`/workspace/projects/llm-services/config/runtime-policy.json`,schema_version=1,batch_window_enabled严格布尔,workflow_max_shots严格整数1..1000(默认120)。缺失按生产限制;坏配置关闭新batch准入。
|
||||
- 开发部署batch_window_enabled=false。开启仍为北京时间21:00–08:00,当前镜头/阶段完成,后续排队;HTTP断开不影响共享Qwen。
|
||||
- 文件热读取;关闭限制绕过窗口和时钟水位门禁,但不删除水位。手动暂停、维护、用户停用和让卡始终有效。
|
||||
- schema2镜头1..1000,连续有序shot_N;duration_frames为24..120,默认120,24fps。模型仍生成121帧,合成裁剪,不把文本上下文当成视频时长。
|
||||
- 动态总帧数与字幕音轨范围;资源上限默认120镜头,可配置提高。已接受运行不受后续降低上限影响。
|
||||
- 保留schema1、历史Run、幂等键、fence及增强片选择;无数据库迁移,不操作共享Qwen进程。
|
||||
|
||||
## 审查重点
|
||||
|
||||
1. API全天而GPU仍等夜间的配置不一致。
|
||||
2. shot_10字符串排序到shot_2前面。
|
||||
3. 音轨字幕残留360帧边界或默默截断长旁白。
|
||||
4. 热开启终止当前执行、清水位,或客户端能关闭限制。
|
||||
5. 手册夸大自动拆镜、字幕对齐、身份一致和单次长生成。
|
||||
|
||||
## 任务1:共享配置
|
||||
|
||||
Owner:schedule_config_audit。Files:backend/runtime_policy、config/resource_policy/coordinator/main;inference/store/scheduling/api/worker及新回归。
|
||||
|
||||
- [x] RED:正午关闭可准入CPU/Qwen/GPU;热切换、坏配置、旧水位和手动限制。
|
||||
- [x] 严格只读解析,全路径准入和状态输出,workflow_limits输出上限。
|
||||
- [x] GREEN:针对性回归,无客户端旁路字段。
|
||||
|
||||
## 任务2:多镜头与媒体
|
||||
|
||||
Owner:long_video_backend_audit。Files:timeline/workflows/workflow_engine/providers/media/jobs及新回归。
|
||||
|
||||
- [x] RED:12镜头数值顺序、动态步骤、长音轨字幕、旧草稿、上限降低后的旧Run。
|
||||
- [x] schema2、动态依赖和合成、帧裁剪,生成语义参与复用哈希。
|
||||
- [x] GREEN:原V2回归,真实Linux FFmpeg4镜头[24,120,120,120]→384帧/16秒。
|
||||
|
||||
## 任务3:前端与说明
|
||||
|
||||
Owner:long_video_ui_manual_audit(frontend/src);root(public示例/文档)。
|
||||
|
||||
- [x] RED:增删/排序/时长、旧草稿、20镜头、动态边界、策略文案。
|
||||
- [x] 编辑器、JSON导入导出、鲲鹏示例;TTS对齐2000字上限。
|
||||
- [x] GREEN:完整前端测试/typecheck/build,桌面/手机实际编辑与保存。
|
||||
- [x] 手册覆盖现有入口/队列/账号/恢复/配置;20镜头100秒鲲鹏示例与详细步骤。
|
||||
|
||||
## 任务4:发布
|
||||
|
||||
Root负责,只在自管执行结束后更新已有服务,保留旧镜像/配置;不重启共享Qwen、工作区或监管容器。
|
||||
|
||||
- [x] 后端/GPU/前端完整测试与审查后发布。
|
||||
- [x] 注入正午时钟的批量准入、实机策略热读取、旧片保留、超过15秒合成完整解码和配置切换一致;实机当前为夜间,不改宿主时间。
|
||||
- [x] 文档注明验证范围;保持私有入口,交付代码与手册。
|
||||
|
||||
## 完成记录
|
||||
|
||||
最终后端Linux188项/20子测试,前端79项,推理149项/120子测试,真实FFmpeg6项通过。完整验证见[开发与验收记录](../../开发与验收记录_20261111.md)。实机热切换后保持开发全天;两份鲲鹏草稿未运行,完整旁白已生成。
|
||||
46
docs/开发与验收记录_20261111.md
Normal file
@ -0,0 +1,46 @@
|
||||
# 可配置时段与多镜头版本开发、部署及验收
|
||||
|
||||
2026-11-11,Asia/Shanghai。本轮在原项目、原数据库和原模型服务上增量更新,schema仍为003;没有新建第二个GPU worker。私有入口为 http://127.0.0.1:8000 ,项目代码位于`E:\workspace\hybrid\cmvr-visual`。
|
||||
|
||||
## 已完成
|
||||
|
||||
- 新增共享权威文件`/workspace/projects/llm-services/config/runtime-policy.json`。API和既有GPU worker热读取;当前`batch_window_enabled=false`,开发阶段批量全天可用。改为true恢复21:00–08:00后续阶段准入,当前阶段自然完成。文件缺失用生产默认,坏配置阻止新批量计算;工作流和编排新提交也需有效资源上限。原暂停、维护、停用、额度和外部用户优先仍生效。
|
||||
- schema2支持有序可变镜头、每镜头选用24–120帧、24fps,总帧数动态求和;默认资源上限120镜头,可配置1–1000。旧schema1三镜头、历史Run和生成哈希保持兼容。单次Wan仍生成121源帧,缩短选用时长是剪辑,不保证同比节省推理。
|
||||
- 镜头增删/排序/时长、动态音轨字幕范围、JSON导入导出、示例载入、超过shot_9后的数值顺序均已接通。新运行快照、依赖和合成输入依照分镜顺序。仅剪辑时长改变时可复用相同生成结果。
|
||||
- 普通成片编排移除24段/30分钟固定门槛,新提交受同一资源上限约束。已有工作流子任务可在上限降低后完成;新批次成员不能借内部标记绕过上限。输出大小、磁盘、源文件范围与执行超时继续保护服务器。
|
||||
- 选择旁白默认保留完整音频。超出成片范围会显示警告并阻止保存,直到用户增加镜头或明确裁剪。配音输入与后端2000字限制对齐。
|
||||
- 工作流页提供操作手册、鲲鹏步骤、20镜头100秒模板。另提供45秒紧凑版下载。HTML手册可在浏览器阅读/打印,Markdown可下载;生成脚本为`scripts/render_manuals.py`。
|
||||
|
||||
## 验证结果
|
||||
|
||||
| 范围 | 最终结果 |
|
||||
| --- | --- |
|
||||
| Linux后端完整回归 | 188 passed,20 subtests passed |
|
||||
| 前端完整回归 | 79 passed,typecheck/Vite构建通过 |
|
||||
| Linux推理服务完整回归 | 149 passed,120 subtests passed;1条Starlette弃用提示 |
|
||||
| 真实FFmpeg专项 | 6 passed;包括横竖版/适配、短源拒绝及4镜头16秒完整解码 |
|
||||
| 实机网页 | 20镜头载入、增删排序、时长、保存/刷新、桌面和390×844手机滚动通过,无页面异常 |
|
||||
| 旁白交互 | 44.425秒音频选进15秒草稿仍保留44425ms,保存前阻止;选入45秒草稿可完整容纳 |
|
||||
| 实际16秒影片 | 1920×1080、H264、384帧、24fps、5,699,705字节;完整解码与浏览器15.5秒seek通过 |
|
||||
| 配置热切换 | API与GPU实际同时读到true/false,最终恢复false,无重启共享服务 |
|
||||
| 关闭HTTP | Qwen批次在原调用端关闭后完成,答案15;CPU合成与配音持久执行 |
|
||||
|
||||
正午准入、08:00边界、坏配置、旧水位、启动前重新检查和启动后自然完成使用注入时钟/隔离Linux子进程验证。实机部署发生在夜间;没有修改宿主时间、伪造生产GPU状态或声称经历了真实白天/08:00边界。推理首次选错缺NumPy的轻量测试环境,已改用具备验证依赖的环境完整重跑通过,未修改模型运行环境。
|
||||
|
||||
独立审查发现的批次绕过上限问题已经RED→GREEN修复,并验证混合批次失败原子回滚、原键重放和已接受工作流继续执行。测试集合分别报告,不相加当作独立用例总数。
|
||||
|
||||
## 已准备的鲲鹏素材
|
||||
|
||||
- 草稿“鲲鹏·20镜头100秒示例(未运行)”:`265761009d2346598065033c377258b0`。
|
||||
- 草稿“鲲鹏·45秒旁白版(未运行)”:`cecafd1041a6465eb3982a0449717208`,已关联当前管理员的完整旁白。
|
||||
- 旁白“鲲鹏完整旁白(开发验收).wav”:203字,zm_yunxi、速度0.85,实际44.425秒,24kHz。素材编号`34e1c004c3214f298d201d3cc22d18a9`。
|
||||
|
||||
这两份草稿都没有启动全片生成。100秒是更舒缓叙事的视觉模板,不能把44秒旁白与100秒字幕直接当作已同步成片。45秒版更适合先测试完整故事;两版字幕都需试听校准,参考图片还需选择。未进行20个鲲鹏镜头的整片质量验收。
|
||||
|
||||
## 发布与数据保护
|
||||
|
||||
发布前确认本应用无运行/排队模型任务、无未知执行,保存SQL、上游SQLite和业务文件/旧源码联合恢复点,位于受保护目录`/root/cmvr-visual-v3-20261111`。清单记录字节数与SHA256,SQLite完整性为ok。旧API/前端镜像保留为`pre-v3-20261111`;本轮未重复上轮已完成的全量隔离恢复演练。
|
||||
|
||||
仅更新本应用API/前端容器,并在空闲期停止/重启既有模型服务的API/worker子进程以加载调度代码。共享Qwen两个容器、llmuser工作区容器、GPU监管和TTS容器ID及启动时间均未变化。未重建工作区、未调整其他用户GPU任务、未变更数据库密码或对互联网开放端口。
|
||||
|
||||
证据:`qa/v3-deployment.json`、`qa/v3-policy-hot.json`、`qa/v3-live.json`、`qa/v3-browser*.json`及相应截图。实际16秒影片副本在`qa/generated/v3-long-video-16s.mp4`(不提交Git)。配置更改与鲲鹏完整步骤见[操作手册](操作手册_20261111.md)和[制作指南](鲲鹏长视频制作指南_20261111.md)。
|
||||
175
docs/操作手册_20261111.md
Normal file
@ -0,0 +1,175 @@
|
||||
# CMVR Visual 操作手册
|
||||
|
||||
适用版本:2026-11-11的可配置时段、多镜头版本。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。
|
||||
|
||||
## 1. 登录与基本流程
|
||||
|
||||
现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。
|
||||
|
||||
使用分配的账号登录。默认管理员名为`admin`,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。
|
||||
|
||||
一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。
|
||||
|
||||
网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。
|
||||
|
||||
## 2. 功能入口
|
||||
|
||||
| 入口 | 用途 | 输入与输出 |
|
||||
| --- | --- | --- |
|
||||
| 创作:图片 | Qwen-Image文生图 | 提示词、尺寸、种子等 → 图片 |
|
||||
| 创作:视频 | Wan单镜头文生/图生视频 | 提示词、可选参考首帧 → 约5秒以内无声片段,可选增强 |
|
||||
| 创作:条件样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 |
|
||||
| 工作流 | 多镜头故事自动逐镜生成并合成 | 每镜头提示词/参考图/选用时长 → 一部多镜头影片 |
|
||||
| 声音 | 中文配音、Whisper转写 | 文本 → WAV;音频/有声视频 → 转写结果 |
|
||||
| 推演 | 复用共享Qwen做文本推演 | 问题 → 文本解答 |
|
||||
| 理解 | 图片理解、视频抽帧分析 | 素材 → 场景、主体、OCR、标签等 |
|
||||
| 成片 | 编辑已有视频素材 | 排序、裁切、单音轨、人工字幕 → MP4 |
|
||||
| 批量 | 混合提交任务或已保存工作流 | 任务清单 → 持久批次,运行时段服从配置 |
|
||||
| 素材 / 任务 / 账户 | 管理结果、进度、用户和令牌 | 见下文 |
|
||||
|
||||
## 3. 图片、短视频和条件样本
|
||||
|
||||
### 图片
|
||||
|
||||
1. 进入“创作”,切换到图片。
|
||||
2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
|
||||
3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
|
||||
4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。
|
||||
|
||||
### 单镜头视频
|
||||
|
||||
1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
|
||||
2. 可选择参考图片作为首帧;文生视频可不选图。
|
||||
3. 根据当前能力选择参数和1080p画质增强。当前单次接口最多121帧、24fps,约5秒;增加提示词长度不会自动延长单镜头。
|
||||
4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。
|
||||
|
||||
### 条件样本
|
||||
|
||||
选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。
|
||||
|
||||
## 4. 多镜头工作流
|
||||
|
||||
### 新建、编辑和保存
|
||||
|
||||
1. 打开“工作流”,点击“新建”,填写故事名称。
|
||||
2. 每个镜头填写提示词,选择种子和可选参考图片。
|
||||
3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。
|
||||
4. 每镜头选择1–5秒的选用时长。模型当前仍按121帧生成短片段,合成只取选用帧数;缩短选用时长主要影响剪辑,不承诺同比减少GPU推理耗时。
|
||||
5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。
|
||||
6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。
|
||||
|
||||
总时长由镜头选用时长相加,24fps下`总秒数=总帧数÷24`。例如4个5秒镜头为20秒,20个为100秒;不再固定为15秒。
|
||||
|
||||
默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。
|
||||
|
||||
### 音轨和字幕
|
||||
|
||||
工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。
|
||||
|
||||
- 源入点/出点单位是**毫秒**,表示取音频的哪一段。
|
||||
- 偏移单位是**帧**,表示从成片的哪一帧开始播放。24帧=1秒。
|
||||
- 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。
|
||||
- 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。
|
||||
|
||||
人工字幕的开始/结束是整片帧号,区间为`[开始帧,结束帧)`。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。
|
||||
|
||||
### 运行、复用与恢复
|
||||
|
||||
点击“保存并运行”。服务器冻结本次参数和修订,逐镜串行生成,然后合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
|
||||
|
||||
- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
|
||||
- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
|
||||
- “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。
|
||||
- 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。
|
||||
- “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。
|
||||
|
||||
JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。
|
||||
|
||||
## 5. 声音、推演与理解
|
||||
|
||||
“声音”选择“配音生成”,输入不超过2000字,选择`zf_xiaobei`或`zm_yunxi`,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。
|
||||
|
||||
转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。
|
||||
|
||||
“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。
|
||||
|
||||
## 6. 成片、素材与任务管理
|
||||
|
||||
“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。
|
||||
|
||||
“素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找;可修改名称和标签。被草稿/运行引用的素材应先解除引用再删除,避免破坏后续复用。
|
||||
|
||||
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。新GPU推理全局仅一个;配音/媒体CPU和Qwen HTTP各有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让行并重排本应用作业,等待排队本身不是故障。
|
||||
|
||||
## 7. 批量与开发/生产配置
|
||||
|
||||
“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。
|
||||
|
||||
权威配置位于容器内:
|
||||
|
||||
```text
|
||||
/workspace/projects/llm-services/config/runtime-policy.json
|
||||
```
|
||||
|
||||
服务器宿主机对应:
|
||||
|
||||
```text
|
||||
/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json
|
||||
```
|
||||
|
||||
开发模式:
|
||||
|
||||
```json
|
||||
{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}
|
||||
```
|
||||
|
||||
正式环境启用时段限制:
|
||||
|
||||
```json
|
||||
{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}
|
||||
```
|
||||
|
||||
API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。`true/false`是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。
|
||||
|
||||
- `false`:批量也可全天等待空闲资源;手动暂停、维护、账号禁用、容量限额和其他用户优先仍生效。
|
||||
- `true`:批量的新镜头/处理阶段只在北京时间21:00–08:00启动。08:00时当前阶段自然完成,后续排队到下一窗口。交互仍全天可用。
|
||||
- 文件不存在:使用生产默认限制。文件错误:关闭新批量准入并显示配置错误;不要为解决此问题删除时钟水位文件。
|
||||
- 上限降低只限制新提交/草稿保存,不会截断已经接受的长视频运行。
|
||||
|
||||
在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。
|
||||
|
||||
若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):
|
||||
|
||||
```text
|
||||
sftp llmuser@192.168.28.10
|
||||
put E:/workspace/hybrid/cmvr-visual/deploy/runtime-policy.production.json /workspace/projects/llm-services/config/runtime-policy.next.json
|
||||
rename /workspace/projects/llm-services/config/runtime-policy.next.json /workspace/projects/llm-services/config/runtime-policy.json
|
||||
bye
|
||||
```
|
||||
|
||||
切回开发模式时把上传源文件改为`runtime-policy.development.json`,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。
|
||||
|
||||
## 8. 账号、令牌和未确认提交
|
||||
|
||||
在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。每位用户只看自己的任务和素材。
|
||||
|
||||
机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。
|
||||
|
||||
“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见`docs/api-contract.md`和FastAPI接口文档。
|
||||
|
||||
## 9. 常见问题
|
||||
|
||||
| 现象 | 处理 |
|
||||
| --- | --- |
|
||||
| 一直等待窗口 | 在状态面板检查开关;开发模式需要API和GPU实际使用同一配置文件 |
|
||||
| 等待GPU/外部用户使用 | 等待空闲资源,不要停止他人的任务 |
|
||||
| 音轨放不进影片 | 先测实际音频长度,增加镜头或缩短旁白;检查毫秒与帧单位 |
|
||||
| 草稿版本冲突 | 保留本地内容,重新载入服务器版本后再决定合并,不反复覆盖 |
|
||||
| 角色变形、鲲鹏不一致 | 统一形象描述、使用参考首帧,分镜小步验证,人工挑选重做 |
|
||||
| 转写没有声音 | 检查源视频是否有音轨;模型生成片段默认无声 |
|
||||
| 结果未知/需要人工确认 | 运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止 |
|
||||
| 输出过大或空间不足 | 减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列 |
|
||||
|
||||
完整案例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。模板在`frontend/public/examples/kunpeng-storyboard.json`,原文旁白在同目录的`kunpeng-narration.txt`。
|
||||
|
||||
另提供`kunpeng-storyboard-45s.json`,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。
|
||||
103
docs/鲲鹏长视频制作指南_20261111.md
Normal file
@ -0,0 +1,103 @@
|
||||
# 鲲鹏长视频制作指南
|
||||
|
||||
本例把您给出的完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可修改的故事板,不是对原生模型生成100秒连续镜头的承诺。载入模板只修改本地草稿,不会自动耗用GPU或开始出片。
|
||||
|
||||
本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,`zm_yunxi`、速度0.85,时长**44.425秒**。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板`kunpeng-storyboard-45s.json`。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。
|
||||
|
||||
## 一、先明确成片方式
|
||||
|
||||
当前采用“逐镜生成短片段 → 选用所需帧 → 直切拼接 → 叠加一条旁白与人工字幕”。每镜头保持一个主要动作,使用统一形象和画风。跨镜头没有自动记忆,不能仅凭相同种子保证鲲、鹏长相一致。文本上下文长度控制提示词可包含多少信息,并不直接决定视频秒数;单次视频的帧数、显存、训练分布和动作复杂度也决定效果。
|
||||
|
||||
官方TI2V-5B支持720P、24fps文生/图生视频;本项目目前把每次生成控制在121帧,再做多镜头合成。官方说明见[Wan2.2模型卡](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B)。
|
||||
|
||||
## 二、准备故事原文与旁白
|
||||
|
||||
原文:
|
||||
|
||||
> 北方的大海里有一条鱼,它的名字叫鲲。鲲的体积,不知道大到有几千里。遇见大风的时候,鲲就会从鱼变化成为鸟,鸟的名字就叫做鹏。鹏的脊背,真不知道长到有几千里;当它奋起而飞的时候,那展开的翅膀就好像天边的云,正所谓大鹏一日同风起,浮云直上九万里。这只鹏鸟,当海动风气的时候就要迁徙到南方的大海去了。鹏往南方的大海迁徙的时候,翅膀拍打水面,能激起三千里的浪涛,环绕着旋风飞上了九万里的高空,乘着六月的风离开了北海。
|
||||
|
||||
1. 打开“声音”,切到“配音生成”,粘贴整段原文(本例小于2000字)。
|
||||
2. 选择希望的音色;先用速度1试听,再根据叙事节奏调整。`zm_yunxi`或`zf_xiaobei`都是当前可选音色,先听后选。
|
||||
3. 点击“生成配音”,在任务完成后试听素材,记录**实际音频时长T**。没有生成音频前,不应假定文字一定能在100秒读完。
|
||||
4. 如果T≤100秒,可沿用100秒故事板,留出的时间作为画面呼吸或尾部静音;如果T>100秒,增加镜头,或改写旁白/调整语速。不要硬把长音频截成15秒。
|
||||
5. 将旁白素材收藏或标记“鲲鹏-完整旁白”,方便后续选择。若用自己的配音或配乐混合音轨,先在外部音频工具完成混音,再上传一条最终音轨;当前网页没有多轨混音。
|
||||
|
||||
旁白原文也在`frontend/public/examples/kunpeng-narration.txt`。模板中的字幕只是按分镜分配的初稿,**并未与真实配音逐句对齐**。
|
||||
|
||||
使用现有旁白时,可跳过重新生成配音,在素材中按“鲲鹏/旁白”标签查找上述WAV。45秒模板从“导入工作流 JSON”载入,或打开服务器上预置的“鲲鹏·45秒旁白版(未运行)”草稿;后者已关联当前管理员的完整旁白,参考图片仍需选择。其他账号应生成/上传自己的素材。45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。
|
||||
|
||||
## 三、先确定鲲和鹏的形象
|
||||
|
||||
建议统一视觉设定:上古神话史诗、写实CG、冷蓝北海、淡金晨光。鲲为青黑色巨鱼、银白腹部、背部淡金云纹、金色眼睛;鹏继承青黑与淡金纹理、金色眼睛。
|
||||
|
||||
1. 在“创作→图片”分别生成鲲、鹏及关键变形姿态的参考图片,人工挑选满意版本。
|
||||
2. 在“素材”给参考图添加“鲲鹏/鲲/鹏/参考”标签。
|
||||
3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。
|
||||
4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。
|
||||
|
||||
## 四、载入100秒示例
|
||||
|
||||
1. 进入“工作流”,点击“载入鲲鹏示例”;如已有未保存内容,先保存或导出JSON,再确认替换。
|
||||
2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。
|
||||
3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。
|
||||
|
||||
| 镜头 | 成片时间 | 旁白初稿 | 画面与动作 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 · 北冥海面 | 0–5秒 | 北方的大海里有一条鱼, | 北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。 |
|
||||
| 2 · 鲲的眼睛 | 5–10秒 | 它的名字叫鲲。 | 青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。 |
|
||||
| 3 · 巨鲲全貌 | 10–15秒 | 鲲的体积, | 从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。 |
|
||||
| 4 · 千里之巨 | 15–20秒 | 不知道大到有几千里。 | 极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。 |
|
||||
| 5 · 大风将起 | 20–25秒 | 遇见大风的时候, | 北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。 |
|
||||
| 6 · 化鹏一瞬 | 25–30秒 | 鲲就会从鱼变化成为鸟, | 巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。 |
|
||||
| 7 · 鹏鸟显形 | 30–35秒 | 鸟的名字就叫做鹏。 | 水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。 |
|
||||
| 8 · 鹏背如山 | 35–40秒 | 鹏的脊背, | 巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。 |
|
||||
| 9 · 背脊无尽 | 40–45秒 | 真不知道长到有几千里; | 镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。 |
|
||||
| 10 · 奋起而飞 | 45–50秒 | 当它奋起而飞的时候, | 完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。 |
|
||||
| 11 · 翼若垂天云 | 50–55秒 | 那展开的翅膀就好像天边的云, | 从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。 |
|
||||
| 12 · 同风而起 | 55–60秒 | 正所谓大鹏一日同风起, | 巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。 |
|
||||
| 13 · 扶摇高空 | 60–65秒 | 浮云直上九万里。 | 从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。 |
|
||||
| 14 · 海动风气 | 65–70秒 | 这只鹏鸟,当海动风气的时候 | 北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。 |
|
||||
| 15 · 南冥召唤 | 70–75秒 | 就要迁徙到南方的大海去了。 | 云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。 |
|
||||
| 16 · 离海启程 | 75–80秒 | 鹏往南方的大海迁徙的时候, | 巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。 |
|
||||
| 17 · 拍海三千里 | 80–85秒 | 翅膀拍打水面,能激起三千里的浪涛, | 青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。 |
|
||||
| 18 · 扶摇九万里 | 85–90秒 | 环绕着旋风飞上了九万里的高空, | 一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。 |
|
||||
| 19 · 六月长风 | 90–95秒 | 乘着六月的风 | 温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。 |
|
||||
| 20 · 北海南迁 | 95–100秒 | 离开了北海。 | 辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。 |
|
||||
|
||||
## 五、添加音轨并校正字幕
|
||||
|
||||
1. 在“成片设置”选择横屏和“完整画面(留边)”;若希望填满画面,可改“填满画面”,但要检查巨鹏翅膀是否被裁掉。
|
||||
2. 点击“选择音频素材”,选前面生成的完整旁白。源入点填0,源出点填音频实际毫秒数,偏移填0帧。例如旁白实测92.4秒,出点为92400;这只是单位示例,不是本例实际配音结果。
|
||||
3. 若源出点+偏移超过2400帧,应增加镜头或调整时长。字幕与旁白不能超出最终总帧数。
|
||||
4. 按实际试听改字幕时间:`开始帧=开始秒数×24`、`结束帧=结束秒数×24`,取整数帧。例:一句实际出现在31.5至36秒,填756至864。
|
||||
5. 模板的20条字幕每条初始占5秒。改变镜头顺序/时长后重新检查,系统不会自动把字幕重新对齐到配音。
|
||||
|
||||
## 六、先做小样,再生成全片
|
||||
|
||||
建议先“新建”一个3镜头测试草稿,复制北海、变形、鹏鸟三种代表性提示词,选相应参考图,生成并检查。不要直接在20镜头模板上随意试全部参数。
|
||||
|
||||
检查角色外形、翅膀数量、变形可信度、海浪尺度、色调、镜头运动、参考图是否生效、横竖版裁切。如果复杂动作失败,把一个镜头拆成两个简单镜头。单次生成的短片也可以先用较低步数在“创作→视频”测试;工作流默认仍采用经过验收的50步规格。
|
||||
|
||||
小样满意后,打开保存的20镜头草稿,补全全部参考图、音轨和字幕,点击“保存草稿”,再“保存并运行”。仅保存不会开始生成。首次完整运行不应盲选不相关的旧Run复用。
|
||||
|
||||
## 七、观察与修改
|
||||
|
||||
任务会按镜头1、2……20顺序生成,再进入成片渲染,共21个步骤。网页可以关闭,服务器仍继续;外部用户使用GPU时会优先让卡,因此总等待时间不固定。
|
||||
|
||||
前轮3镜头默认规格实测约19分12秒,包含冷加载、Whisper插队与归档。按相近条件估算20镜头是小时级工作,约2小时只能作为粗略资源预算,不能作为完成时间保证。排队、抢占、模型切换和失败重试都会改变耗时。
|
||||
|
||||
如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。
|
||||
|
||||
想精细调整已有片段,可到“成片”选择这些视频,调整裁剪与顺序再导出。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。
|
||||
|
||||
## 八、成片验收与继续扩展
|
||||
|
||||
完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果您修改了时长,以工作流显示和媒体实测为准。
|
||||
|
||||
要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。
|
||||
|
||||
开发阶段批量时段限制关闭时可全天测试;生产启用后,批量08:00停止后续镜头/阶段准入,当前阶段完成,余下镜头等21:00。详情见[操作手册](操作手册_20261111.md)。
|
||||
|
||||
模板JSON:`frontend/public/examples/kunpeng-storyboard.json`。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。
|
||||
|
||||
45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供下载链接。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。
|
||||
1
frontend/public/examples/kunpeng-narration.txt
Normal file
@ -0,0 +1 @@
|
||||
北方的大海里有一条鱼,它的名字叫鲲。鲲的体积,不知道大到有几千里。遇见大风的时候,鲲就会从鱼变化成为鸟,鸟的名字就叫做鹏。鹏的脊背,真不知道长到有几千里;当它奋起而飞的时候,那展开的翅膀就好像天边的云,正所谓大鹏一日同风起,浮云直上九万里。这只鹏鸟,当海动风气的时候就要迁徙到南方的大海去了。鹏往南方的大海迁徙的时候,翅膀拍打水面,能激起三千里的浪涛,环绕着旋风飞上了九万里的高空,乘着六月的风离开了北海。
|
||||
295
frontend/public/examples/kunpeng-storyboard-45s.json
Normal file
@ -0,0 +1,295 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"shots": [
|
||||
{
|
||||
"key": "shot_1",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_2",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_3",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_4",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_5",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_6",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_7",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_8",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_9",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_10",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_11",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_12",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_13",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_14",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_15",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_16",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_17",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_18",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_19",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_20",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 54,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
}
|
||||
],
|
||||
"profile": "landscape_1080_v1",
|
||||
"render": {
|
||||
"fps": 24,
|
||||
"total_frames": 1080,
|
||||
"fit": "contain",
|
||||
"audio": null,
|
||||
"subtitles": [
|
||||
{
|
||||
"start_frame": 0,
|
||||
"end_frame": 54,
|
||||
"text": "北方的大海里有一条鱼,"
|
||||
},
|
||||
{
|
||||
"start_frame": 54,
|
||||
"end_frame": 108,
|
||||
"text": "它的名字叫鲲。"
|
||||
},
|
||||
{
|
||||
"start_frame": 108,
|
||||
"end_frame": 162,
|
||||
"text": "鲲的体积,"
|
||||
},
|
||||
{
|
||||
"start_frame": 162,
|
||||
"end_frame": 216,
|
||||
"text": "不知道大到有几千里。"
|
||||
},
|
||||
{
|
||||
"start_frame": 216,
|
||||
"end_frame": 270,
|
||||
"text": "遇见大风的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 270,
|
||||
"end_frame": 324,
|
||||
"text": "鲲就会从鱼变化成为鸟,"
|
||||
},
|
||||
{
|
||||
"start_frame": 324,
|
||||
"end_frame": 378,
|
||||
"text": "鸟的名字就叫做鹏。"
|
||||
},
|
||||
{
|
||||
"start_frame": 378,
|
||||
"end_frame": 432,
|
||||
"text": "鹏的脊背,"
|
||||
},
|
||||
{
|
||||
"start_frame": 432,
|
||||
"end_frame": 486,
|
||||
"text": "真不知道长到有几千里;"
|
||||
},
|
||||
{
|
||||
"start_frame": 486,
|
||||
"end_frame": 540,
|
||||
"text": "当它奋起而飞的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 540,
|
||||
"end_frame": 594,
|
||||
"text": "那展开的翅膀就好像天边的云,"
|
||||
},
|
||||
{
|
||||
"start_frame": 594,
|
||||
"end_frame": 648,
|
||||
"text": "正所谓大鹏一日同风起,"
|
||||
},
|
||||
{
|
||||
"start_frame": 648,
|
||||
"end_frame": 702,
|
||||
"text": "浮云直上九万里。"
|
||||
},
|
||||
{
|
||||
"start_frame": 702,
|
||||
"end_frame": 756,
|
||||
"text": "这只鹏鸟,当海动风气的时候"
|
||||
},
|
||||
{
|
||||
"start_frame": 756,
|
||||
"end_frame": 810,
|
||||
"text": "就要迁徙到南方的大海去了。"
|
||||
},
|
||||
{
|
||||
"start_frame": 810,
|
||||
"end_frame": 864,
|
||||
"text": "鹏往南方的大海迁徙的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 864,
|
||||
"end_frame": 918,
|
||||
"text": "翅膀拍打水面,能激起三千里的浪涛,"
|
||||
},
|
||||
{
|
||||
"start_frame": 918,
|
||||
"end_frame": 972,
|
||||
"text": "环绕着旋风飞上了九万里的高空,"
|
||||
},
|
||||
{
|
||||
"start_frame": 972,
|
||||
"end_frame": 1026,
|
||||
"text": "乘着六月的风"
|
||||
},
|
||||
{
|
||||
"start_frame": 1026,
|
||||
"end_frame": 1080,
|
||||
"text": "离开了北海。"
|
||||
}
|
||||
],
|
||||
"template_version": "plain-v1"
|
||||
}
|
||||
}
|
||||
295
frontend/public/examples/kunpeng-storyboard.json
Normal file
@ -0,0 +1,295 @@
|
||||
{
|
||||
"schema_version": 2,
|
||||
"shots": [
|
||||
{
|
||||
"key": "shot_1",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_2",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_3",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_4",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_5",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_6",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_7",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_8",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_9",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_10",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_11",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_12",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_13",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_14",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_15",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_16",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_17",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_18",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_19",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "shot_20",
|
||||
"prompt": "中国上古神话史诗电影,写实CG,真实海水与体积云,青黑与淡金配色,庄严、辽阔,画面无文字、无现代建筑、无人类。辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。",
|
||||
"image_asset_id": null,
|
||||
"duration_frames": 120,
|
||||
"parameters": {
|
||||
"seed": 42
|
||||
}
|
||||
}
|
||||
],
|
||||
"profile": "landscape_1080_v1",
|
||||
"render": {
|
||||
"fps": 24,
|
||||
"total_frames": 2400,
|
||||
"fit": "contain",
|
||||
"audio": null,
|
||||
"subtitles": [
|
||||
{
|
||||
"start_frame": 0,
|
||||
"end_frame": 120,
|
||||
"text": "北方的大海里有一条鱼,"
|
||||
},
|
||||
{
|
||||
"start_frame": 120,
|
||||
"end_frame": 240,
|
||||
"text": "它的名字叫鲲。"
|
||||
},
|
||||
{
|
||||
"start_frame": 240,
|
||||
"end_frame": 360,
|
||||
"text": "鲲的体积,"
|
||||
},
|
||||
{
|
||||
"start_frame": 360,
|
||||
"end_frame": 480,
|
||||
"text": "不知道大到有几千里。"
|
||||
},
|
||||
{
|
||||
"start_frame": 480,
|
||||
"end_frame": 600,
|
||||
"text": "遇见大风的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 600,
|
||||
"end_frame": 720,
|
||||
"text": "鲲就会从鱼变化成为鸟,"
|
||||
},
|
||||
{
|
||||
"start_frame": 720,
|
||||
"end_frame": 840,
|
||||
"text": "鸟的名字就叫做鹏。"
|
||||
},
|
||||
{
|
||||
"start_frame": 840,
|
||||
"end_frame": 960,
|
||||
"text": "鹏的脊背,"
|
||||
},
|
||||
{
|
||||
"start_frame": 960,
|
||||
"end_frame": 1080,
|
||||
"text": "真不知道长到有几千里;"
|
||||
},
|
||||
{
|
||||
"start_frame": 1080,
|
||||
"end_frame": 1200,
|
||||
"text": "当它奋起而飞的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 1200,
|
||||
"end_frame": 1320,
|
||||
"text": "那展开的翅膀就好像天边的云,"
|
||||
},
|
||||
{
|
||||
"start_frame": 1320,
|
||||
"end_frame": 1440,
|
||||
"text": "正所谓大鹏一日同风起,"
|
||||
},
|
||||
{
|
||||
"start_frame": 1440,
|
||||
"end_frame": 1560,
|
||||
"text": "浮云直上九万里。"
|
||||
},
|
||||
{
|
||||
"start_frame": 1560,
|
||||
"end_frame": 1680,
|
||||
"text": "这只鹏鸟,当海动风气的时候"
|
||||
},
|
||||
{
|
||||
"start_frame": 1680,
|
||||
"end_frame": 1800,
|
||||
"text": "就要迁徙到南方的大海去了。"
|
||||
},
|
||||
{
|
||||
"start_frame": 1800,
|
||||
"end_frame": 1920,
|
||||
"text": "鹏往南方的大海迁徙的时候,"
|
||||
},
|
||||
{
|
||||
"start_frame": 1920,
|
||||
"end_frame": 2040,
|
||||
"text": "翅膀拍打水面,能激起三千里的浪涛,"
|
||||
},
|
||||
{
|
||||
"start_frame": 2040,
|
||||
"end_frame": 2160,
|
||||
"text": "环绕着旋风飞上了九万里的高空,"
|
||||
},
|
||||
{
|
||||
"start_frame": 2160,
|
||||
"end_frame": 2280,
|
||||
"text": "乘着六月的风"
|
||||
},
|
||||
{
|
||||
"start_frame": 2280,
|
||||
"end_frame": 2400,
|
||||
"text": "离开了北海。"
|
||||
}
|
||||
],
|
||||
"template_version": "plain-v1"
|
||||
}
|
||||
}
|
||||
1
frontend/public/help/kunpeng.html
Normal file
103
frontend/public/help/kunpeng.md
Normal file
@ -0,0 +1,103 @@
|
||||
# 鲲鹏长视频制作指南
|
||||
|
||||
本例把您给出的完整故事拆成20个镜头,默认各5秒,共100秒、2400帧、24fps。这是可修改的故事板,不是对原生模型生成100秒连续镜头的承诺。载入模板只修改本地草稿,不会自动耗用GPU或开始出片。
|
||||
|
||||
本次已实际生成完整旁白:素材名“鲲鹏完整旁白(开发验收).wav”,`zm_yunxi`、速度0.85,时长**44.425秒**。因此另提供20镜头、每镜头2.25秒、共45秒的紧凑版模板`kunpeng-storyboard-45s.json`。建议先用45秒版验证完整故事;100秒版需要扩写旁白、加入停顿或重新设计节奏,不能直接把44秒旁白与100秒分镜字幕当作已经对齐的成片。
|
||||
|
||||
## 一、先明确成片方式
|
||||
|
||||
当前采用“逐镜生成短片段 → 选用所需帧 → 直切拼接 → 叠加一条旁白与人工字幕”。每镜头保持一个主要动作,使用统一形象和画风。跨镜头没有自动记忆,不能仅凭相同种子保证鲲、鹏长相一致。文本上下文长度控制提示词可包含多少信息,并不直接决定视频秒数;单次视频的帧数、显存、训练分布和动作复杂度也决定效果。
|
||||
|
||||
官方TI2V-5B支持720P、24fps文生/图生视频;本项目目前把每次生成控制在121帧,再做多镜头合成。官方说明见[Wan2.2模型卡](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B)。
|
||||
|
||||
## 二、准备故事原文与旁白
|
||||
|
||||
原文:
|
||||
|
||||
> 北方的大海里有一条鱼,它的名字叫鲲。鲲的体积,不知道大到有几千里。遇见大风的时候,鲲就会从鱼变化成为鸟,鸟的名字就叫做鹏。鹏的脊背,真不知道长到有几千里;当它奋起而飞的时候,那展开的翅膀就好像天边的云,正所谓大鹏一日同风起,浮云直上九万里。这只鹏鸟,当海动风气的时候就要迁徙到南方的大海去了。鹏往南方的大海迁徙的时候,翅膀拍打水面,能激起三千里的浪涛,环绕着旋风飞上了九万里的高空,乘着六月的风离开了北海。
|
||||
|
||||
1. 打开“声音”,切到“配音生成”,粘贴整段原文(本例小于2000字)。
|
||||
2. 选择希望的音色;先用速度1试听,再根据叙事节奏调整。`zm_yunxi`或`zf_xiaobei`都是当前可选音色,先听后选。
|
||||
3. 点击“生成配音”,在任务完成后试听素材,记录**实际音频时长T**。没有生成音频前,不应假定文字一定能在100秒读完。
|
||||
4. 如果T≤100秒,可沿用100秒故事板,留出的时间作为画面呼吸或尾部静音;如果T>100秒,增加镜头,或改写旁白/调整语速。不要硬把长音频截成15秒。
|
||||
5. 将旁白素材收藏或标记“鲲鹏-完整旁白”,方便后续选择。若用自己的配音或配乐混合音轨,先在外部音频工具完成混音,再上传一条最终音轨;当前网页没有多轨混音。
|
||||
|
||||
旁白原文也在`frontend/public/examples/kunpeng-narration.txt`。模板中的字幕只是按分镜分配的初稿,**并未与真实配音逐句对齐**。
|
||||
|
||||
使用现有旁白时,可跳过重新生成配音,在素材中按“鲲鹏/旁白”标签查找上述WAV。45秒模板从“导入工作流 JSON”载入,或打开服务器上预置的“鲲鹏·45秒旁白版(未运行)”草稿;后者已关联当前管理员的完整旁白,参考图片仍需选择。其他账号应生成/上传自己的素材。45秒模板总帧数1080,每镜头54帧;字幕仍须按试听调整。
|
||||
|
||||
## 三、先确定鲲和鹏的形象
|
||||
|
||||
建议统一视觉设定:上古神话史诗、写实CG、冷蓝北海、淡金晨光。鲲为青黑色巨鱼、银白腹部、背部淡金云纹、金色眼睛;鹏继承青黑与淡金纹理、金色眼睛。
|
||||
|
||||
1. 在“创作→图片”分别生成鲲、鹏及关键变形姿态的参考图片,人工挑选满意版本。
|
||||
2. 在“素材”给参考图添加“鲲鹏/鲲/鹏/参考”标签。
|
||||
3. 后面在对应镜头点击“选择参考图片”。一个镜头使用一张首帧参考,不要以为模型能自动读取其它镜头的参考图。
|
||||
4. 鲲变鹏属于复杂形变。先试云雾遮挡的剪影、随后切到完整鹏鸟;如果变形不稳定,用“鲲入水雾→鹏出云层”的剪辑衔接代替长时间暴露变形过程。
|
||||
|
||||
## 四、载入100秒示例
|
||||
|
||||
1. 进入“工作流”,点击“载入鲲鹏示例”;如已有未保存内容,先保存或导出JSON,再确认替换。
|
||||
2. 填写名称,例如“鲲鹏南迁-首版”。模板已填20段提示词、种子42、每段5秒、横屏画布和分镜字幕;参考图与音轨留空,需要您选择本账号素材。
|
||||
3. 逐镜检查下面的内容,修改词语、时长或镜头顺序。完整可复制提示词位于导入JSON;表格是简要分镜说明。
|
||||
|
||||
| 镜头 | 成片时间 | 旁白初稿 | 画面与动作 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 · 北冥海面 | 0–5秒 | 北方的大海里有一条鱼, | 北方无边的深靛蓝海面,云雾低垂,一条青黑色巨鱼的轮廓在海面下缓缓游过。高空极远景,镜头缓慢向前推进,以海浪衬托鱼体的巨大。 |
|
||||
| 2 · 鲲的眼睛 | 5–10秒 | 它的名字叫鲲。 | 青黑色巨鱼鲲的金色眼睛特写,银白色腹部边缘与淡金云纹若隐若现。鲲缓缓转动眼睛,细小水流掠过表面,镜头平稳侧移。 |
|
||||
| 3 · 巨鲲全貌 | 10–15秒 | 鲲的体积, | 从深海侧面看到完整的青黑巨鲲,银白腹部,背部淡金云纹,宽阔鱼鳍轻缓划水,形体如海底山脉。镜头缓慢后退,展示壮阔全貌。 |
|
||||
| 4 · 千里之巨 | 15–20秒 | 不知道大到有几千里。 | 极高空俯瞰,巨鲲的脊背仿佛一片移动的大陆穿过北海,身旁细小浪纹作为尺度参照,云影掠过青黑鱼背。固定广角,仅鱼体缓慢前进。 |
|
||||
| 5 · 大风将起 | 20–25秒 | 遇见大风的时候, | 北海远方乌云聚拢,大风推动海面形成巨大的波纹,青黑巨鲲露出一段背脊。广角平视,镜头慢慢抬起,云层成为画面主体。 |
|
||||
| 6 · 化鹏一瞬 | 25–30秒 | 鲲就会从鱼变化成为鸟, | 巨鲲跃出北海的侧面剪影,被逆光云雾和水幕包围;宽大鱼鳍在水幕遮挡中逐渐展开为羽翼,青黑与淡金纹理保持一致。一个主体,一次缓慢展开动作,固定侧面中远景。 |
|
||||
| 7 · 鹏鸟显形 | 30–35秒 | 鸟的名字就叫做鹏。 | 水雾散去,一只青黑色巨鹏出现在北海上空,金色眼睛,羽缘带淡金云纹。鹏保持完整鸟形,缓缓展开双翼,低机位仰拍。 |
|
||||
| 8 · 鹏背如山 | 35–40秒 | 鹏的脊背, | 巨鹏青黑羽毛覆盖的背脊近景,淡金纹理连成山峦般的起伏,薄云从羽毛上方掠过。镜头沿背部缓慢向前滑行。 |
|
||||
| 9 · 背脊无尽 | 40–45秒 | 真不知道长到有几千里; | 镜头从巨鹏背部缓缓升高并后退,鹏的背脊延伸到远方云海,金色羽缘在晨光下微亮,用云层显示宏大尺度。 |
|
||||
| 10 · 奋起而飞 | 45–50秒 | 当它奋起而飞的时候, | 完整的青黑巨鹏在云海上方振翅一次,身体随气流平稳抬升,淡金羽缘反光。正侧面全景,摄影机平稳跟随,不旋转。 |
|
||||
| 11 · 翼若垂天云 | 50–55秒 | 那展开的翅膀就好像天边的云, | 从鹏下方仰看,一只巨鹏的双翼横贯天空,青黑羽毛与淡金羽缘连成天边云幕,阳光从羽翼间透下。固定超广角,羽翼缓慢舒展。 |
|
||||
| 12 · 同风而起 | 55–60秒 | 正所谓大鹏一日同风起, | 巨鹏顺着强劲风流向上飞,青黑羽翼稳定展开,云带在其身后分开。宽幅远景,镜头以相同速度平稳上升。 |
|
||||
| 13 · 扶摇高空 | 60–65秒 | 浮云直上九万里。 | 从极远处看到一只完整巨鹏穿过明亮的云层上升,北海缩小在下方,青金色光线勾勒鸟的轮廓。镜头缓慢拉远,突出高空。 |
|
||||
| 14 · 海动风气 | 65–70秒 | 这只鹏鸟,当海动风气的时候 | 北海上空风云涌动,海面形成螺旋状涌浪,一只青黑巨鹏在高处顺风盘旋。高空广角,镜头缓慢横移,保持主体完整。 |
|
||||
| 15 · 南冥召唤 | 70–75秒 | 就要迁徙到南方的大海去了。 | 云层间露出南方温暖的金色天光,青黑巨鹏面向南方,羽缘淡金纹理清晰,北方冷蓝海面留在身后。镜头从侧后方缓慢跟随。 |
|
||||
| 16 · 离海启程 | 75–80秒 | 鹏往南方的大海迁徙的时候, | 巨鹏从北海海面上方向南方平稳掠过,广阔青黑双翼保持完整,海浪被气流分开。贴近海面的远距离侧向跟拍,主体缓慢前进。 |
|
||||
| 17 · 拍海三千里 | 80–85秒 | 翅膀拍打水面,能激起三千里的浪涛, | 青黑巨鹏的一次振翼掠过北海水面,强劲气流激起连绵巨浪,水花在金色逆光中飞散。极远景展示完整鸟形与波涛,镜头稳定。 |
|
||||
| 18 · 扶摇九万里 | 85–90秒 | 环绕着旋风飞上了九万里的高空, | 一只青黑巨鹏沿巨大气流旋涡的边缘平稳向上飞,云带环绕,北海在下方逐渐遥远。摄影机平稳抬升,不快速翻转,展现清晰鸟形。 |
|
||||
| 19 · 六月长风 | 90–95秒 | 乘着六月的风 | 温暖的六月阳光穿透薄云,巨鹏的淡金羽缘泛光,它借助稳定南风展开双翼滑翔。侧后方远景,镜头平缓跟随,冷蓝逐渐过渡到暖金。 |
|
||||
| 20 · 北海南迁 | 95–100秒 | 离开了北海。 | 辽阔高空全景,青黑巨鹏向南方明亮的海天交界滑翔,北海冷蓝云层渐渐远去,鹏的剪影逐渐变小。摄影机缓慢拉远,形成庄严宁静的结尾。 |
|
||||
|
||||
## 五、添加音轨并校正字幕
|
||||
|
||||
1. 在“成片设置”选择横屏和“完整画面(留边)”;若希望填满画面,可改“填满画面”,但要检查巨鹏翅膀是否被裁掉。
|
||||
2. 点击“选择音频素材”,选前面生成的完整旁白。源入点填0,源出点填音频实际毫秒数,偏移填0帧。例如旁白实测92.4秒,出点为92400;这只是单位示例,不是本例实际配音结果。
|
||||
3. 若源出点+偏移超过2400帧,应增加镜头或调整时长。字幕与旁白不能超出最终总帧数。
|
||||
4. 按实际试听改字幕时间:`开始帧=开始秒数×24`、`结束帧=结束秒数×24`,取整数帧。例:一句实际出现在31.5至36秒,填756至864。
|
||||
5. 模板的20条字幕每条初始占5秒。改变镜头顺序/时长后重新检查,系统不会自动把字幕重新对齐到配音。
|
||||
|
||||
## 六、先做小样,再生成全片
|
||||
|
||||
建议先“新建”一个3镜头测试草稿,复制北海、变形、鹏鸟三种代表性提示词,选相应参考图,生成并检查。不要直接在20镜头模板上随意试全部参数。
|
||||
|
||||
检查角色外形、翅膀数量、变形可信度、海浪尺度、色调、镜头运动、参考图是否生效、横竖版裁切。如果复杂动作失败,把一个镜头拆成两个简单镜头。单次生成的短片也可以先用较低步数在“创作→视频”测试;工作流默认仍采用经过验收的50步规格。
|
||||
|
||||
小样满意后,打开保存的20镜头草稿,补全全部参考图、音轨和字幕,点击“保存草稿”,再“保存并运行”。仅保存不会开始生成。首次完整运行不应盲选不相关的旧Run复用。
|
||||
|
||||
## 七、观察与修改
|
||||
|
||||
任务会按镜头1、2……20顺序生成,再进入成片渲染,共21个步骤。网页可以关闭,服务器仍继续;外部用户使用GPU时会优先让卡,因此总等待时间不固定。
|
||||
|
||||
前轮3镜头默认规格实测约19分12秒,包含冷加载、Whisper插队与归档。按相近条件估算20镜头是小时级工作,约2小时只能作为粗略资源预算,不能作为完成时间保证。排队、抢占、模型切换和失败重试都会改变耗时。
|
||||
|
||||
如果某镜头失败,在运行卡中“重试此阶段”。如果内容不满意,改草稿相应提示词后新建一次运行,并选择上一Run复用成功镜头。未改生成内容的镜头可复用,避免全片重新生成;改顺序导致编号变化时,某些镜头可能需要重新匹配或生成,请看提交后的步骤状态。
|
||||
|
||||
想精细调整已有片段,可到“成片”选择这些视频,调整裁剪与顺序再导出。该编辑器支持直切、一条音轨和人工字幕;没有自动转场、画面续写、口型同步或自动配乐。
|
||||
|
||||
## 八、成片验收与继续扩展
|
||||
|
||||
完成后打开“预览”,从头观看并跳转到不同镜头,检查画面/字幕/旁白;到素材库下载MP4。100秒模板应该有2400帧、24fps;如果您修改了时长,以工作流显示和媒体实测为准。
|
||||
|
||||
要扩展为几分钟影片,继续添加镜头并为每镜头写具体动作、参考和字幕,再按实际旁白长度调整总时长。默认资源上限为120镜头(5秒/镜头时10分钟),管理员可提高到1000;磁盘、任务额度和超时仍有效。不要通过给单镜头填整篇故事期待一次得到几分钟连续视频。
|
||||
|
||||
开发阶段批量时段限制关闭时可全天测试;生产启用后,批量08:00停止后续镜头/阶段准入,当前阶段完成,余下镜头等21:00。详情见[操作手册](操作手册_20261111.md)。
|
||||
|
||||
模板JSON:`frontend/public/examples/kunpeng-storyboard.json`。它不含任何账号、令牌或服务器文件路径;导入后需要手动选择您自己的参考图和音轨。
|
||||
|
||||
45秒版JSON:`frontend/public/examples/kunpeng-storyboard-45s.json`。网站帮助页提供下载链接。两版的画面提示词相同,只改变选用时长和字幕初始范围;45秒版生成镜头仍使用121帧源规格,GPU推理量不会按45/100同比减少。
|
||||
4
frontend/public/help/manual.html
Normal file
175
frontend/public/help/manual.md
Normal file
@ -0,0 +1,175 @@
|
||||
# CMVR Visual 操作手册
|
||||
|
||||
适用版本:2026-11-11的可配置时段、多镜头版本。模型在192.168.28.10运行,项目在`E:\workspace\hybrid\cmvr-visual`。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。
|
||||
|
||||
## 1. 登录与基本流程
|
||||
|
||||
现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。
|
||||
|
||||
使用分配的账号登录。默认管理员名为`admin`,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。
|
||||
|
||||
一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。
|
||||
|
||||
网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。
|
||||
|
||||
## 2. 功能入口
|
||||
|
||||
| 入口 | 用途 | 输入与输出 |
|
||||
| --- | --- | --- |
|
||||
| 创作:图片 | Qwen-Image文生图 | 提示词、尺寸、种子等 → 图片 |
|
||||
| 创作:视频 | Wan单镜头文生/图生视频 | 提示词、可选参考首帧 → 约5秒以内无声片段,可选增强 |
|
||||
| 创作:条件样本 | SDXL+Canny ControlNet | 参考图片、提示词、控制强度 → 合成图及Canny控制图 |
|
||||
| 工作流 | 多镜头故事自动逐镜生成并合成 | 每镜头提示词/参考图/选用时长 → 一部多镜头影片 |
|
||||
| 声音 | 中文配音、Whisper转写 | 文本 → WAV;音频/有声视频 → 转写结果 |
|
||||
| 推演 | 复用共享Qwen做文本推演 | 问题 → 文本解答 |
|
||||
| 理解 | 图片理解、视频抽帧分析 | 素材 → 场景、主体、OCR、标签等 |
|
||||
| 成片 | 编辑已有视频素材 | 排序、裁切、单音轨、人工字幕 → MP4 |
|
||||
| 批量 | 混合提交任务或已保存工作流 | 任务清单 → 持久批次,运行时段服从配置 |
|
||||
| 素材 / 任务 / 账户 | 管理结果、进度、用户和令牌 | 见下文 |
|
||||
|
||||
## 3. 图片、短视频和条件样本
|
||||
|
||||
### 图片
|
||||
|
||||
1. 进入“创作”,切换到图片。
|
||||
2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
|
||||
3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
|
||||
4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。
|
||||
|
||||
### 单镜头视频
|
||||
|
||||
1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
|
||||
2. 可选择参考图片作为首帧;文生视频可不选图。
|
||||
3. 根据当前能力选择参数和1080p画质增强。当前单次接口最多121帧、24fps,约5秒;增加提示词长度不会自动延长单镜头。
|
||||
4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。
|
||||
|
||||
### 条件样本
|
||||
|
||||
选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。
|
||||
|
||||
## 4. 多镜头工作流
|
||||
|
||||
### 新建、编辑和保存
|
||||
|
||||
1. 打开“工作流”,点击“新建”,填写故事名称。
|
||||
2. 每个镜头填写提示词,选择种子和可选参考图片。
|
||||
3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。
|
||||
4. 每镜头选择1–5秒的选用时长。模型当前仍按121帧生成短片段,合成只取选用帧数;缩短选用时长主要影响剪辑,不承诺同比减少GPU推理耗时。
|
||||
5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。
|
||||
6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。
|
||||
|
||||
总时长由镜头选用时长相加,24fps下`总秒数=总帧数÷24`。例如4个5秒镜头为20秒,20个为100秒;不再固定为15秒。
|
||||
|
||||
默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。
|
||||
|
||||
### 音轨和字幕
|
||||
|
||||
工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。
|
||||
|
||||
- 源入点/出点单位是**毫秒**,表示取音频的哪一段。
|
||||
- 偏移单位是**帧**,表示从成片的哪一帧开始播放。24帧=1秒。
|
||||
- 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。
|
||||
- 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。
|
||||
|
||||
人工字幕的开始/结束是整片帧号,区间为`[开始帧,结束帧)`。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。
|
||||
|
||||
### 运行、复用与恢复
|
||||
|
||||
点击“保存并运行”。服务器冻结本次参数和修订,逐镜串行生成,然后合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
|
||||
|
||||
- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
|
||||
- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
|
||||
- “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。
|
||||
- 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。
|
||||
- “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。
|
||||
|
||||
JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。
|
||||
|
||||
## 5. 声音、推演与理解
|
||||
|
||||
“声音”选择“配音生成”,输入不超过2000字,选择`zf_xiaobei`或`zm_yunxi`,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。
|
||||
|
||||
转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。
|
||||
|
||||
“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。
|
||||
|
||||
## 6. 成片、素材与任务管理
|
||||
|
||||
“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。
|
||||
|
||||
“素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找;可修改名称和标签。被草稿/运行引用的素材应先解除引用再删除,避免破坏后续复用。
|
||||
|
||||
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。新GPU推理全局仅一个;配音/媒体CPU和Qwen HTTP各有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让行并重排本应用作业,等待排队本身不是故障。
|
||||
|
||||
## 7. 批量与开发/生产配置
|
||||
|
||||
“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。
|
||||
|
||||
权威配置位于容器内:
|
||||
|
||||
```text
|
||||
/workspace/projects/llm-services/config/runtime-policy.json
|
||||
```
|
||||
|
||||
服务器宿主机对应:
|
||||
|
||||
```text
|
||||
/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json
|
||||
```
|
||||
|
||||
开发模式:
|
||||
|
||||
```json
|
||||
{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}
|
||||
```
|
||||
|
||||
正式环境启用时段限制:
|
||||
|
||||
```json
|
||||
{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}
|
||||
```
|
||||
|
||||
API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。`true/false`是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。
|
||||
|
||||
- `false`:批量也可全天等待空闲资源;手动暂停、维护、账号禁用、容量限额和其他用户优先仍生效。
|
||||
- `true`:批量的新镜头/处理阶段只在北京时间21:00–08:00启动。08:00时当前阶段自然完成,后续排队到下一窗口。交互仍全天可用。
|
||||
- 文件不存在:使用生产默认限制。文件错误:关闭新批量准入并显示配置错误;不要为解决此问题删除时钟水位文件。
|
||||
- 上限降低只限制新提交/草稿保存,不会截断已经接受的长视频运行。
|
||||
|
||||
在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。
|
||||
|
||||
若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):
|
||||
|
||||
```text
|
||||
sftp llmuser@192.168.28.10
|
||||
put E:/workspace/hybrid/cmvr-visual/deploy/runtime-policy.production.json /workspace/projects/llm-services/config/runtime-policy.next.json
|
||||
rename /workspace/projects/llm-services/config/runtime-policy.next.json /workspace/projects/llm-services/config/runtime-policy.json
|
||||
bye
|
||||
```
|
||||
|
||||
切回开发模式时把上传源文件改为`runtime-policy.development.json`,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。
|
||||
|
||||
## 8. 账号、令牌和未确认提交
|
||||
|
||||
在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。每位用户只看自己的任务和素材。
|
||||
|
||||
机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。
|
||||
|
||||
“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见`docs/api-contract.md`和FastAPI接口文档。
|
||||
|
||||
## 9. 常见问题
|
||||
|
||||
| 现象 | 处理 |
|
||||
| --- | --- |
|
||||
| 一直等待窗口 | 在状态面板检查开关;开发模式需要API和GPU实际使用同一配置文件 |
|
||||
| 等待GPU/外部用户使用 | 等待空闲资源,不要停止他人的任务 |
|
||||
| 音轨放不进影片 | 先测实际音频长度,增加镜头或缩短旁白;检查毫秒与帧单位 |
|
||||
| 草稿版本冲突 | 保留本地内容,重新载入服务器版本后再决定合并,不反复覆盖 |
|
||||
| 角色变形、鲲鹏不一致 | 统一形象描述、使用参考首帧,分镜小步验证,人工挑选重做 |
|
||||
| 转写没有声音 | 检查源视频是否有音轨;模型生成片段默认无声 |
|
||||
| 结果未知/需要人工确认 | 运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止 |
|
||||
| 输出过大或空间不足 | 减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列 |
|
||||
|
||||
完整案例见[鲲鹏长视频制作指南](鲲鹏长视频制作指南_20261111.md)。模板在`frontend/public/examples/kunpeng-storyboard.json`,原文旁白在同目录的`kunpeng-narration.txt`。
|
||||
|
||||
另提供`kunpeng-storyboard-45s.json`,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。
|
||||
@ -26,6 +26,6 @@ onMounted(()=>window.addEventListener('cmvr:unauthorized',expired));onBeforeUnmo
|
||||
<RouterView v-if="route.path==='/login'" />
|
||||
<div v-else class="app-shell"><aside class="sidebar"><router-link to="/create/image" class="brand" aria-label="CMVR Visual 创作首页"><span class="brand-glyph">V</span><span class="brand-caption">CMVR</span></router-link><nav class="side-nav"><router-link v-for="item in nav" :key="item.path" :to="item.path" :class="{selected:item.path==='/create/image'?route.path.startsWith('/create'):route.path.startsWith(item.path)}"><el-icon><component :is="item.icon" /></el-icon><span>{{ item.label }}</span><i v-if="item.path==='/tasks'&&jobs.active.length" class="nav-notification"/></router-link></nav><div class="sidebar-bottom"><el-tooltip content="服务状态" placement="right"><button aria-label="服务状态" @click="systemOpen=true"><el-icon><Connection /></el-icon></button></el-tooltip><el-dropdown trigger="click" placement="right-end"><button class="avatar-button" :aria-label="auth.user?.display_name||'账户'">{{ (auth.user?.display_name||auth.user?.username||'U').slice(0,1) }}</button><template #dropdown><el-dropdown-menu><el-dropdown-item disabled>{{ auth.user?.display_name||auth.user?.username }}</el-dropdown-item><el-dropdown-item divided :icon="SwitchButton" @click="logout">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div></aside>
|
||||
<div class="app-main"><header class="app-header"><div class="header-breadcrumb"><span>CMVR Visual</span><span class="breadcrumb-separator">/</span><strong>{{ route.meta.title }}</strong></div><div class="header-actions"><button class="connection-status" :class="jobs.connection" @click="systemOpen=true"><span class="live-dot"/>{{ connectionLabel }}</button><span class="header-divider"/><span class="local-label">{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}<template v-if="caps.environment && caps.environment !== 'production'"> · {{ caps.databaseBackend === 'mysql' ? 'MySQL' : 'SQLite' }}</template></span></div></header><div v-if="jobs.connection==='reconnecting'" class="connection-banner"><el-icon><Warning /></el-icon>连接恢复中,任务状态待同步。<button @click="jobs.refresh().catch(()=>undefined)">重新同步</button></div><main class="page-content"><div v-if="auth.user?.must_change_password" class="notice warning">请先到 <router-link to="/account">账户设置</router-link> 修改初始密码。</div><RouterView /></main><button v-if="ongoing" class="global-queue-bar" @click="router.push({path:'/tasks',query:{job:ongoing.id}})"><span class="queue-spinner"/><strong>{{ stateLabel(ongoing) }}</strong><span>{{ phaseLabel(ongoing) }}</span><small v-if="jobs.active.length>1">另有 {{ jobs.active.length-1 }} 项活动任务</small><el-icon><ArrowRight /></el-icon></button></div>
|
||||
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>连接与调度</h3><p>推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}</p><p v-if="caps.executionPolicy">批量窗口:{{ caps.executionPolicy.timezone }} {{ caps.executionPolicy.start }}–{{ caps.executionPolicy.end }} · {{ caps.executionPolicy.batch_open?"开放":"等待下一窗口" }}<br/>08:00 后当前阶段继续完成,新阶段等待下一窗口。<br/>下次窗口 {{ caps.executionPolicy.next_batch_at }}</p><h3>模型能力配置</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
|
||||
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>连接与调度</h3><p>推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}</p><template v-if="caps.executionPolicy"><p v-if="caps.executionPolicy.configuration_error" class="notice warning">调度配置异常,批量任务等待配置恢复。请联系管理员。</p><p v-else-if="caps.executionPolicy.batch_window_enabled===false">时段限制已关闭:开发测试可全天执行批量任务,仍需等待空闲资源。</p><p v-else>批量窗口:{{ caps.executionPolicy.timezone }} {{ caps.executionPolicy.start }}–{{ caps.executionPolicy.end }} · {{ caps.executionPolicy.batch_open?"开放":"等待下一窗口" }}<br/>{{ caps.executionPolicy.end }} 后当前阶段继续完成,新阶段等待下一窗口。<br/><template v-if="caps.executionPolicy.next_batch_at">下次窗口 {{ caps.executionPolicy.next_batch_at }}</template></p></template><h3>模型能力配置</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import {beforeEach,afterEach,describe,expect,it,vi} from 'vitest'
|
||||
import {api,setCsrfToken} from './api'
|
||||
import {pendingSubmissions,setStorageOwner} from './outbox'
|
||||
import {emptyWorkflow} from './v2types'
|
||||
const saved=new Map<string,string>()
|
||||
beforeEach(()=>{saved.clear();vi.stubGlobal('localStorage',{getItem:(k:string)=>saved.get(k)??null,setItem:(k:string,v:string)=>saved.set(k,v)});setStorageOwner('alice');setCsrfToken('csrf-test')})
|
||||
afterEach(()=>vi.unstubAllGlobals())
|
||||
describe('API recovery wire contract',()=>{
|
||||
it('creates new variable workflows with the multi_shot kind',async()=>{const fetcher=vi.fn().mockResolvedValue({ok:true,status:200,json:async()=>({})});vi.stubGlobal('fetch',fetcher);await api.createWorkflow('长片',emptyWorkflow());expect(JSON.parse(fetcher.mock.calls[0]![1].body).kind).toBe('multi_shot')})
|
||||
it('replays exact explicit retry nonce after a lost HTTP response',async()=>{const fetcher=vi.fn().mockRejectedValueOnce(new Error('lost')).mockResolvedValue({ok:true,status:200,json:async()=>({jobs:[]})});vi.stubGlobal('fetch',fetcher);await expect(api.retry('job-1')).rejects.toThrow();const original=pendingSubmissions()[0]!;await api.retry('job-1');const first=fetcher.mock.calls[0]![1],second=fetcher.mock.calls[1]![1];expect(first.headers.get('Idempotency-Key')).toBe(original.key);expect(second.headers.get('Idempotency-Key')).toBe(original.key);expect(second.headers.get('X-CSRF-Token')).toBe('csrf-test');expect(second.body).toBe(first.body);expect(original.operation).toBe('jobs.retry')})
|
||||
it('persists run revision and version for recovery rather than deriving from current draft',async()=>{vi.stubGlobal('fetch',vi.fn().mockRejectedValue(new Error('lost')));await api.recover({operation:'workflow.run',path:'/workflows/d/runs',body:'{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}'}).catch(()=>{});expect(pendingSubmissions()[0]?.body).toBe('{"draft_revision":2,"expected_version":3,"execution_mode":"interactive"}')})
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { durableRequest } from './outbox'
|
||||
import type { DraftDTO, RunSnapshot, RunDTO, BatchSnapshot, BatchDTO, WorkflowSpec, TokenRecord } from './v2types'
|
||||
import type { Asset, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability } from './types'
|
||||
import type { Asset, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability,ExecutionPolicy,WorkflowLimits } from './types'
|
||||
|
||||
let csrfToken = ''
|
||||
export function setCsrfToken(token: string) { csrfToken = token }
|
||||
@ -38,7 +38,7 @@ export async function request<T>(path: string, options: RequestInit = {}): Promi
|
||||
export const api = {
|
||||
workflows: (filters:Record<string,unknown>={}) => request<Page<DraftDTO>>(`/workflows${queryString(filters)}`),
|
||||
workflow: (id:string) => request<DraftDTO>(`/workflows/${id}`),
|
||||
createWorkflow: (name:string,spec:WorkflowSpec) => request<DraftDTO>('/workflows',{method:'POST',body:JSON.stringify({name,spec,kind:'three_shot'})}),
|
||||
createWorkflow: (name:string,spec:WorkflowSpec) => request<DraftDTO>('/workflows',{method:'POST',body:JSON.stringify({name,spec,kind:spec.schema_version===1?'three_shot':'multi_shot'})}),
|
||||
saveWorkflow: (draft:DraftDTO,name:string,spec:WorkflowSpec) => request<DraftDTO>(`/workflows/${draft.id}`,{method:'PATCH',headers:{'If-Match':String(draft.version)},body:JSON.stringify({name,spec})}),
|
||||
startRun: (draft:DraftDTO,execution_mode='interactive',reuse_run_id?:string) => durable<RunSnapshot>('workflow.run',`/workflows/${draft.id}/runs`,{draft_revision:draft.revision,expected_version:draft.version,execution_mode,...(reuse_run_id?{reuse_run_id}:{})}),
|
||||
runs: (filters:Record<string,unknown>={}) => request<Page<RunDTO>>(`/workflow-runs${queryString(filters)}`),
|
||||
@ -62,7 +62,7 @@ export const api = {
|
||||
login: (username: string, password: string) => request<AuthResponse>('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
|
||||
logout: () => request<void>('/auth/logout', { method: 'POST' }),
|
||||
capabilities: () => request<CapabilitiesResponse>('/capabilities'),
|
||||
systemStatus: () => request<{ execution_policy?: {timezone:string;start:string;end:string;batch_open:boolean;next_batch_at:string;close_behavior:string}; inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'),
|
||||
systemStatus: () => request<{ execution_policy?:ExecutionPolicy;workflow_limits?:WorkflowLimits; inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'),
|
||||
jobs: (filters: Record<string, unknown> = {}) => request<JobsPage>(`/jobs${queryString(filters)}`),
|
||||
job: (id: string) => request<Job>(`/jobs/${encodeURIComponent(id)}`),
|
||||
submit: (body: JobRequest) => durable<{jobs:Job[]}>('jobs.create','/jobs',body),
|
||||
|
||||
@ -20,6 +20,14 @@ describe('RunCard presentation',()=>{
|
||||
const html=await render({run:{...run,error:{code:'step_failed',step_key:'shot_2'}},steps:[],jobs:[]})
|
||||
expect(html).toContain('class="notice danger">镜头二执行失败,请查看子任务详情。')
|
||||
})
|
||||
it('sorts arbitrary shot numbers numerically before the final render',async()=>{
|
||||
const snapshot:RunSnapshot={run,steps:['compose','shot_10','shot_2','shot_1','shot_9'].map(step),jobs:[]}
|
||||
const html=await render(snapshot),labels=['镜头一','镜头二','镜头9','镜头10','成片渲染']
|
||||
const positions=labels.map(label=>html.indexOf(`<strong>${label}</strong>`))
|
||||
expect(positions.every(index=>index>=0)).toBe(true)
|
||||
expect(positions).toEqual([...positions].sort((a,b)=>a-b))
|
||||
expect(snapshot.steps[0]?.step_key).toBe('compose')
|
||||
})
|
||||
it.each([['storage_insufficient','存储空间不足'],['owner_disabled','账户已被管理员停用'],['dependency_changed','依赖素材或阶段已变更']])('explains backend code %s with no message',async(code,text)=>{
|
||||
expect(await render({run:{...run,error:{code,message:' '}},steps:[],jobs:[]})).toContain(text)
|
||||
})
|
||||
|
||||
@ -11,9 +11,9 @@ import JobDetail from './JobDetail.vue'
|
||||
import type {Asset} from '../types'
|
||||
const props=defineProps<{snapshot:RunSnapshot}>(),store=useWorkflowsStore(),jobs=useJobsStore(),busy=ref(false),preview=ref<Asset|null>(null),detail=ref<string|null>(null)
|
||||
const run=computed(()=>props.snapshot.run)
|
||||
const orderedSteps=computed(()=>{const order:Record<string,number>={shot_1:0,shot_2:1,shot_3:2,compose:3,render:3};return [...props.snapshot.steps].sort((a,b)=>(order[a.step_key]??4)-(order[b.step_key]??4))})
|
||||
const orderedSteps=computed(()=>{const order=(key:string)=>/^shot_[1-9]\d*$/.test(key)?Number(key.slice(5)):key==='compose'||key==='render'?Number.MAX_SAFE_INTEGER-1:Number.MAX_SAFE_INTEGER;return [...props.snapshot.steps].sort((a,b)=>order(a.step_key)-order(b.step_key))})
|
||||
async function control(action:'pause'|'resume'|'cancel'){busy.value=true;try{await store.controlRun(run.value,action)}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
|
||||
async function retry(step:StepDTO){if(!step.selected_job_id)return;busy.value=true;try{await store.retryStep(run.value,step.step_key,step.selected_job_id)}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
|
||||
function selectedState(step:StepDTO){const snapshot=props.snapshot.jobs.find(j=>j.id===step.selected_job_id),live=jobs.byId[step.selected_job_id||''];return (live&&(!snapshot||live.version>snapshot.version)?live:snapshot)?.state||step.state}
|
||||
</script>
|
||||
<template><article class="surface v2-panel"><div class="v2-toolbar"><strong>工作流 · {{ run.id.slice(0,8) }}</strong><span class="status-pill">{{ workflowState(run.state) }}</span><small>r{{ run.draft_revision }} · v{{ run.version }} · {{ run.execution_mode==='batch'?'夜间批量':'全天交互' }}</small><el-tag v-if="store.drafts[run.draft_id]&&store.drafts[run.draft_id]!.revision!==run.draft_revision" type="info">历史修订产物</el-tag><el-tag v-if="store.drafts[run.draft_id]?.current_run_id&&store.drafts[run.draft_id]!.current_run_id!==run.id" type="info">历史运行</el-tag><span>{{ run.completed_steps }}/{{ run.total_steps }}</span><el-button :loading="busy" @click="store.fetchRun(run.id)">同步</el-button><template v-if="!['succeeded','cancelled'].includes(run.state)"><el-button :disabled="busy" @click="control(run.desired_state==='pause'?'resume':'pause')">{{ run.desired_state==='pause'?'继续':'暂停后续阶段' }}</el-button><el-button type="danger" text :disabled="busy" @click="control('cancel')">取消</el-button></template></div><p v-if="run.hold_reasons?.length" class="notice warning">等待条件:{{ run.hold_reasons.map(holdLabel).join('、') }}</p><p v-if="run.desired_state==='pause'" class="muted">当前执行阶段完成后暂停后续阶段。</p><p v-if="run.error" class="notice danger">{{ workflowErrorLabel(run.error) }}</p><div class="v2-steps"><div v-for="step in orderedSteps" :key="step.id" class="v2-step"><strong>{{ workflowStepLabel(step.step_key) }}</strong><span>{{ workflowState(selectedState(step)) }}</span><small>显式尝试 {{ step.explicit_attempt }}</small><button v-if="step.selected_job_id" class="text-link" @click="detail=step.selected_job_id">子任务 {{ step.selected_job_id.slice(0,8) }}</button><el-button v-if="step.selected_job_id&&['failed','timed_out','needs_attention'].includes(selectedState(step))" text :disabled="busy" @click="retry(step)">重试此阶段</el-button></div></div><div class="v2-actions"><el-button v-for="asset in run.result_assets||[]" :key="asset.id" type="primary" @click="preview=asset">预览 {{ asset.name }}</el-button></div><AssetPreview v-model:asset="preview"/><JobDetail v-model:job-id="detail"/></article></template>
|
||||
<template><article class="surface v2-panel"><div class="v2-toolbar"><strong>工作流 · {{ run.id.slice(0,8) }}</strong><span class="status-pill">{{ workflowState(run.state) }}</span><small>r{{ run.draft_revision }} · v{{ run.version }} · {{ run.execution_mode==='batch'?'批量':'全天交互' }}</small><el-tag v-if="store.drafts[run.draft_id]&&store.drafts[run.draft_id]!.revision!==run.draft_revision" type="info">历史修订产物</el-tag><el-tag v-if="store.drafts[run.draft_id]?.current_run_id&&store.drafts[run.draft_id]!.current_run_id!==run.id" type="info">历史运行</el-tag><span>{{ run.completed_steps }}/{{ run.total_steps }}</span><el-button :loading="busy" @click="store.fetchRun(run.id)">同步</el-button><template v-if="!['succeeded','cancelled'].includes(run.state)"><el-button :disabled="busy" @click="control(run.desired_state==='pause'?'resume':'pause')">{{ run.desired_state==='pause'?'继续':'暂停后续阶段' }}</el-button><el-button type="danger" text :disabled="busy" @click="control('cancel')">取消</el-button></template></div><p v-if="run.hold_reasons?.length" class="notice warning">等待条件:{{ run.hold_reasons.map(holdLabel).join('、') }}</p><p v-if="run.desired_state==='pause'" class="muted">当前执行阶段完成后暂停后续阶段。</p><p v-if="run.error" class="notice danger">{{ workflowErrorLabel(run.error) }}</p><div class="v2-steps"><div v-for="step in orderedSteps" :key="step.id" class="v2-step"><strong>{{ workflowStepLabel(step.step_key) }}</strong><span>{{ workflowState(selectedState(step)) }}</span><small>显式尝试 {{ step.explicit_attempt }}</small><button v-if="step.selected_job_id" class="text-link" @click="detail=step.selected_job_id">子任务 {{ step.selected_job_id.slice(0,8) }}</button><el-button v-if="step.selected_job_id&&['failed','timed_out','needs_attention'].includes(selectedState(step))" text :disabled="busy" @click="retry(step)">重试此阶段</el-button></div></div><div class="v2-actions"><el-button v-for="asset in run.result_assets||[]" :key="asset.id" type="primary" @click="preview=asset">预览 {{ asset.name }}</el-button></div><AssetPreview v-model:asset="preview"/><JobDetail v-model:job-id="detail"/></article></template>
|
||||
|
||||
@ -37,7 +37,7 @@ export async function copyText(value: string) { await navigator.clipboard.writeT
|
||||
export function workflowState(value:string){return ({ready:"就绪",submitting:"正在提交",collecting:"正在归档",scheduled:"预约中",pausing:"正在暂停",waiting:"等待依赖",queued:"排队中",running:"执行中",paused:"已暂停",waiting_window:"等待夜间窗口",needs_attention:"需要处理",succeeded:"已完成",failed:"失败",cancelled:"已取消",cancelling:"取消中",completed_with_errors:"完成(含失败)",blocked:"等待处理",timed_out:"超时"} as Record<string,string>)[value]||value}
|
||||
export function holdLabel(value:string){return ({admin_suspend:"管理员已暂停任务",quota:"等待可用配额",storage:"等待可用存储空间",window:"等待夜间窗口;当前阶段完成后再等待",batch_pause:"批量已暂停",batch_fifo:"等待前序任务",batch_wait:"等待批量前序任务",manual:"手动暂停",maintenance:"维护中",external_gpu_usage:"外部 GPU 使用优先",disabled_user:"账户已禁用"} as Record<string,string>)[value]||value}
|
||||
|
||||
export function workflowStepLabel(key:string){return ({shot_1:'镜头一',shot_2:'镜头二',shot_3:'镜头三',render:'成片渲染',compose:'成片渲染'} as Record<string,string>)[key]||key}
|
||||
export function workflowStepLabel(key:string){return ({shot_1:'镜头一',shot_2:'镜头二',shot_3:'镜头三',render:'成片渲染',compose:'成片渲染'} as Record<string,string>)[key]||(/^shot_[1-9]\d*$/.test(key)?`镜头${Number(key.slice(5))}`:key)}
|
||||
export function workflowErrorLabel(error:{code:string;message?:string;step_key?:string}){
|
||||
if(error.message?.trim())return error.message
|
||||
const step=error.step_key?workflowStepLabel(error.step_key):'工作流阶段'
|
||||
|
||||
34
frontend/src/multishot.test.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import {describe,expect,it} from 'vitest'
|
||||
import {emptyWorkflow,validateWorkflow} from './v2types'
|
||||
import type {WorkflowSpec} from './v2types'
|
||||
|
||||
function story(count=20):WorkflowSpec{
|
||||
const spec=emptyWorkflow() as any
|
||||
spec.schema_version=2
|
||||
spec.shots=Array.from({length:count},(_,i)=>({key:`shot_${i+1}`,prompt:`画面 ${i+1}`,image_asset_id:null,parameters:{seed:42},duration_frames:120}))
|
||||
spec.render.total_frames=count*120
|
||||
return spec
|
||||
}
|
||||
describe('variable multi-shot contract',()=>{
|
||||
it('accepts a twenty-shot100-second timeline with audio and subtitles beyond15seconds',()=>{
|
||||
const spec=story();spec.render.audio={asset_id:'voice',source_start_ms:0,source_end_ms:100000,offset_frame:0,short_policy:'silence'}
|
||||
spec.render.subtitles=[{start_frame:2160,end_frame:2400,text:'乘六月之风,迁徙南冥。'}]
|
||||
expect(()=>validateWorkflow(spec)).not.toThrow()
|
||||
})
|
||||
it('enforces configured shot capacity rather than a hard three-shot limit',()=>{
|
||||
expect(()=>validateWorkflow(story(4),3)).toThrow()
|
||||
expect(()=>validateWorkflow(story(4),4)).not.toThrow()
|
||||
})
|
||||
it('rejects derived-frame mismatches and durations above the clip model limit',()=>{
|
||||
const spec=story(1);spec.render.total_frames=24
|
||||
expect(()=>validateWorkflow(spec)).toThrow()
|
||||
spec.render.total_frames=121;spec.shots[0]!.duration_frames=121
|
||||
expect(()=>validateWorkflow(spec)).toThrow()
|
||||
})
|
||||
it('preserves legacy three-shot drafts without requiring new duration fields',()=>{
|
||||
const spec=story(3) as any;spec.schema_version=1;spec.shots.forEach((s:any)=>delete s.duration_frames)
|
||||
expect(()=>validateWorkflow(spec)).not.toThrow()
|
||||
spec.shots.push({...spec.shots[0],key:'shot_4'});spec.render.total_frames=480
|
||||
expect(()=>validateWorkflow(spec)).toThrow()
|
||||
})
|
||||
})
|
||||
@ -8,8 +8,8 @@ export const router=createRouter({history:createWebHistory(),routes:[
|
||||
{path:'/math',component:()=>import('./views/ToolsView.vue'),meta:{title:'数学推演'}},
|
||||
{path:'/analyze',component:()=>import('./views/ToolsView.vue'),meta:{title:'素材理解'}},
|
||||
{path:'/compose',component:()=>import('./views/ComposeView.vue'),meta:{title:'成片编排'}},
|
||||
{path:'/workflow',component:()=>import('./views/WorkflowView.vue'),meta:{title:'三镜头工作流'}},
|
||||
{path:'/batch',component:()=>import('./views/BatchView.vue'),meta:{title:'夜间批量'}},
|
||||
{path:'/workflow',component:()=>import('./views/WorkflowView.vue'),meta:{title:'多镜头工作流'}},
|
||||
{path:'/batch',component:()=>import('./views/BatchView.vue'),meta:{title:'批量创作'}},
|
||||
{path:'/account',component:()=>import('./views/AccountView.vue'),meta:{title:'账户设置'}},
|
||||
{path:'/assets',component:()=>import('./views/AssetsView.vue'),meta:{title:'素材库'}},
|
||||
{path:'/tasks',component:()=>import('./views/TasksView.vue'),meta:{title:'任务中心'}},
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api } from '../api'
|
||||
import type { Capability, Scheduler, TaskType } from '../types'
|
||||
import type { Capability, Scheduler, TaskType,ExecutionPolicy,WorkflowLimits } from '../types'
|
||||
|
||||
export const useCapabilitiesStore = defineStore('capabilities', () => {
|
||||
const items = ref<Capability[]>([])
|
||||
@ -9,15 +9,16 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const inferenceOnline = ref<boolean|null>(null)
|
||||
const executionPolicy = ref<{timezone:string;start:string;end:string;batch_open:boolean;next_batch_at:string;close_behavior:string}|null>(null)
|
||||
const executionPolicy = ref<ExecutionPolicy|null>(null)
|
||||
const workflowLimits = ref<WorkflowLimits>({max_shots:120,source_frames:121,max_clip_frames:120,fps:24})
|
||||
const environment = ref<'production' | 'preview' | 'test' | null>(null)
|
||||
const databaseBackend = ref<'mysql' | 'sqlite' | null>(null)
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; inferenceOnline.value=status.inference_online;executionPolicy.value=status.execution_policy||null; error.value = '' }
|
||||
try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; inferenceOnline.value=status.inference_online;executionPolicy.value=status.execution_policy||response.execution_policy||null;workflowLimits.value=status.workflow_limits||response.workflow_limits||{max_shots:120,source_frames:121,max_clip_frames:120,fps:24}; error.value = '' }
|
||||
catch (caught) { error.value = caught instanceof Error ? caught.message : '无法读取模型能力' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
function forTask(type: TaskType) { return items.value.find(item => item.task_type === type) }
|
||||
return { inferenceOnline, executionPolicy, items, scheduler, loading, error, environment, databaseBackend, load, forTask }
|
||||
return { inferenceOnline, executionPolicy,workflowLimits, items, scheduler, loading, error, environment, databaseBackend, load, forTask }
|
||||
})
|
||||
|
||||
@ -33,4 +33,6 @@ export interface JobRequest {
|
||||
}
|
||||
export interface Page<T> { items: T[]; total: number; page: number; page_size: number }
|
||||
export interface JobsPage extends Page<Job> { cursor: number }
|
||||
export interface CapabilitiesResponse { items: Capability[]; scheduler: Scheduler }
|
||||
export interface ExecutionPolicy {timezone:string;start:string;end:string;batch_open:boolean;next_batch_at:string|null;close_behavior:string;batch_window_enabled:boolean;configuration_error?:string|null}
|
||||
export interface WorkflowLimits {max_shots:number;source_frames:number;max_clip_frames:number;fps:number}
|
||||
export interface CapabilitiesResponse { items: Capability[]; scheduler: Scheduler; execution_policy?:ExecutionPolicy;workflow_limits?:WorkflowLimits }
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import type {Asset,Job,JobRequest} from './types'
|
||||
export interface WorkflowSpec {schema_version:1;shots:{key:string;prompt:string;image_asset_id:string|null;parameters:{seed:number}}[];profile:'landscape_1080_v1'|'portrait_1080_v1';render:{fps:24;total_frames:360;fit:'contain'|'cover';audio:null|{asset_id:string;source_start_ms:number;source_end_ms:number;offset_frame:number;short_policy:'silence'};subtitles:{start_frame:number;end_frame:number;text:string}[];template_version:'plain-v1'}}
|
||||
export interface WorkflowShot {key:string;prompt:string;image_asset_id:string|null;parameters:{seed:number};duration_frames?:number}
|
||||
export interface WorkflowSpec {schema_version:1|2;shots:WorkflowShot[];profile:'landscape_1080_v1'|'portrait_1080_v1';render:{fps:24;total_frames:number;fit:'contain'|'cover';audio:null|{asset_id:string;source_start_ms:number;source_end_ms:number;offset_frame:number;short_policy:'silence'};subtitles:{start_frame:number;end_frame:number;text:string}[];template_version:'plain-v1'}}
|
||||
export interface DraftDTO {id:string;name:string;kind:string;spec:WorkflowSpec;revision:number;version:number;current_run_id?:string|null;created_at:string;updated_at:string}
|
||||
export interface RunDTO {id:string;draft_id:string;draft_revision:number;state:string;desired_state:string;execution_mode:string;version:number;batch_id?:string|null;hold_reasons?:string[];error?:{code:string;message?:string;step_key?:string}|null;created_at:string;started_at?:string|null;finished_at?:string|null;result_assets:Asset[];completed_steps:number;total_steps:number}
|
||||
export interface StepDTO {id:string;run_id:string;step_key:string;kind:string;state:string;selected_job_id:string|null;explicit_attempt:number;dependencies:string[];semantic_input_hash:string;version?:number}
|
||||
@ -9,10 +10,21 @@ export interface BatchItem {item_index:number;target_kind:string;target_id:strin
|
||||
export interface BatchSnapshot {batch:BatchDTO;items:BatchItem[];cursor?:number}
|
||||
export interface TokenRecord {id:string;name:string;scopes:string[];expires_at?:string|null;created_at?:string;last_used_at?:string|null;revoked_at?:string|null}
|
||||
export type BatchInput = {kind:'workflow';draft_id:string;draft_revision:number;expected_version:number}|({kind:'job'}&JobRequest)
|
||||
export function emptyWorkflow():WorkflowSpec{return {schema_version:1,shots:[1,2,3].map(i=>({key:`shot_${i}`,prompt:'',image_asset_id:null,parameters:{seed:42}})),profile:'landscape_1080_v1',render:{fps:24,total_frames:360,fit:'contain',audio:null,subtitles:[],template_version:'plain-v1'}}}
|
||||
export function validateWorkflow(spec:WorkflowSpec){
|
||||
if(spec.shots.length!==3||spec.shots.some((s,i)=>s.key!==`shot_${i+1}`||!s.prompt.trim()||s.prompt.length>8000||!Number.isInteger(s.parameters.seed)||s.parameters.seed<0||s.parameters.seed>4294967295))throw new Error('三个镜头均须填写 1–8000 字提示词及 0–4294967295 整数种子')
|
||||
if(spec.render.subtitles.length>1000)throw new Error('字幕最多 1000 条');
|
||||
for(const row of spec.render.subtitles)if(!Number.isInteger(row.start_frame)||!Number.isInteger(row.end_frame)||row.start_frame<0||row.end_frame>360||row.end_frame<=row.start_frame||!row.text.trim()||row.text.length>2000||/[\\{}\x00-\x1f\x7f]/.test(row.text))throw new Error('字幕须在 0–360 帧内,结束帧晚于开始帧,文字不超过 2000 字')
|
||||
const a=spec.render.audio;if(a&&(!a.asset_id||![a.source_start_ms,a.source_end_ms,a.offset_frame].every(Number.isInteger)||a.source_start_ms<0||a.source_end_ms<=a.source_start_ms||a.offset_frame<0||(a.source_end_ms-a.source_start_ms)*24/1000+a.offset_frame>360))throw new Error('音频选段与偏移必须在 360 帧内,不会自动截断长旁白')
|
||||
export function createWorkflowShot(index:number):WorkflowShot{return {key:`shot_${index+1}`,prompt:'',image_asset_id:null,parameters:{seed:42},duration_frames:120}}
|
||||
export function workflowFrames(spec:WorkflowSpec){return spec.shots.reduce((total,shot)=>total+(shot.duration_frames??120),0)}
|
||||
export function replaceWorkflowShots(spec:WorkflowSpec,shots:WorkflowShot[]):WorkflowSpec{
|
||||
const next={...spec,schema_version:2 as const,shots:shots.map((shot,index)=>({...shot,key:`shot_${index+1}`,parameters:{...shot.parameters},duration_frames:shot.duration_frames??120})),render:{...spec.render}}
|
||||
next.render.total_frames=workflowFrames(next);return next
|
||||
}
|
||||
export function emptyWorkflow():WorkflowSpec{return {schema_version:2,shots:Array.from({length:3},(_,index)=>createWorkflowShot(index)),profile:'landscape_1080_v1',render:{fps:24,total_frames:360,fit:'contain',audio:null,subtitles:[],template_version:'plain-v1'}}}
|
||||
export function validateWorkflow(spec:WorkflowSpec,maxShots=120){
|
||||
if(!spec||![1,2].includes(spec.schema_version)||!Array.isArray(spec.shots)||!spec.render)throw new Error('请选择有效的工作流 JSON,版本须为 1 或 2')
|
||||
if(!Number.isInteger(maxShots)||maxShots<1||maxShots>1000)throw new Error('工作流容量配置异常,请联系管理员')
|
||||
if(spec.shots.length<1||spec.shots.length>(spec.schema_version===1?3:maxShots)||spec.schema_version===1&&spec.shots.length!==3)throw new Error(`镜头数量须为 1–${maxShots};旧版工作流固定为 3 个镜头`)
|
||||
if(spec.shots.some((s,i)=>!s||s.key!==`shot_${i+1}`||typeof s.prompt!=='string'||!s.prompt.trim()||s.prompt.length>8000||!s.parameters||!Number.isInteger(s.parameters.seed)||s.parameters.seed<0||s.parameters.seed>4294967295||(s.image_asset_id!==null&&typeof s.image_asset_id!=='string')||!Number.isInteger(s.duration_frames??120)||(s.duration_frames??120)<24||(s.duration_frames??120)>120||spec.schema_version===1&&(s.duration_frames??120)!==120))throw new Error('各镜头须填写 1–8000 字提示词、整数种子和 24–120 帧时长,并按顺序编号')
|
||||
const total=workflowFrames(spec)
|
||||
if(!['landscape_1080_v1','portrait_1080_v1'].includes(spec.profile)||spec.render.fps!==24||!['contain','cover'].includes(spec.render.fit)||spec.render.template_version!=='plain-v1'||spec.render.total_frames!==total)throw new Error('成片参数不合法,总帧数须等于所有镜头的帧数之和')
|
||||
if(!Array.isArray(spec.render.subtitles)||spec.render.subtitles.length>1000)throw new Error('字幕最多 1000 条')
|
||||
for(const row of spec.render.subtitles)if(!row||!Number.isInteger(row.start_frame)||!Number.isInteger(row.end_frame)||row.start_frame<0||row.end_frame>total||row.end_frame<=row.start_frame||typeof row.text!=='string'||!row.text.trim()||row.text.length>2000||/[\\{}\x00-\x1f\x7f]/.test(row.text))throw new Error(`字幕须在 0–${total} 帧内,结束帧晚于开始帧,文字不超过 2000 字`)
|
||||
const a=spec.render.audio;if(a&&(!a.asset_id||![a.source_start_ms,a.source_end_ms,a.offset_frame].every(Number.isInteger)||a.source_start_ms<0||a.source_end_ms>86400000||a.source_end_ms<=a.source_start_ms||a.offset_frame<0||a.short_policy!=='silence'||(a.source_end_ms-a.source_start_ms)*24/1000+a.offset_frame>total))throw new Error(`音频选段与偏移必须在 ${total} 帧内,不会自动截断长旁白`)
|
||||
}
|
||||
|
||||
24
frontend/src/views/BatchView.policy.test.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import {describe,expect,it} from 'vitest'
|
||||
import {createSSRApp,defineComponent,h} from 'vue'
|
||||
import {renderToString} from 'vue/server-renderer'
|
||||
import {createPinia,setActivePinia} from 'pinia'
|
||||
import {useCapabilitiesStore} from '../stores/capabilities'
|
||||
import BatchView from './BatchView.vue'
|
||||
async function render(enabled:boolean,error?:string){
|
||||
const pinia=createPinia();setActivePinia(pinia)
|
||||
useCapabilitiesStore().executionPolicy={timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open:!enabled,next_batch_at:enabled?'2026-11-11T13:00:00Z':null,close_behavior:'finish_current',batch_window_enabled:enabled,configuration_error:error} as any
|
||||
const app=createSSRApp(BatchView);app.use(pinia)
|
||||
for(const name of ['ElButton','ElInput','ElSelect','ElOption','ElPagination','RouterLink'])app.component(name,defineComponent({setup(_,{slots}){return()=>h('div',slots.default?.())}}))
|
||||
return renderToString(app)
|
||||
}
|
||||
describe('batch policy presentation',()=>{
|
||||
it('explains that disabled restrictions allow daytime development work',async()=>{
|
||||
const html=await render(false);expect(html).toContain('时段限制已关闭');expect(html).not.toContain('批量模式固定为夜间执行')
|
||||
})
|
||||
it('retains finish-current behavior when the production window is enabled',async()=>{
|
||||
const html=await render(true);expect(html).toContain('21:00');expect(html).toContain('08:00');expect(html).toContain('当前阶段继续完成')
|
||||
})
|
||||
it('makes an invalid policy configuration visible without claiming unrestricted execution',async()=>{
|
||||
const html=await render(false,'invalid_policy');expect(html).toContain('调度配置异常');expect(html).not.toContain('时段限制已关闭')
|
||||
})
|
||||
})
|
||||
@ -4,10 +4,12 @@ import {ElMessage} from 'element-plus'
|
||||
import {errorMessage} from '../api'
|
||||
import {useWorkflowsStore} from '../stores/workflows'
|
||||
import {useDraftsStore} from '../stores/drafts'
|
||||
import {useCapabilitiesStore} from '../stores/capabilities'
|
||||
import {taskLabels} from '../format'
|
||||
import type {BatchInput,BatchSnapshot} from '../v2types'
|
||||
import type {TaskType} from '../types'
|
||||
const store=useWorkflowsStore(),local=useDraftsStore().page('batch',()=>({name:'夜间创作',json:'[]',taskType:'image.generate' as TaskType,prompts:'',draftId:''})),busy=ref(false),items=ref<BatchInput[]>([]),page=ref(1),total=ref(0),ids=ref<string[]>([])
|
||||
const caps=useCapabilitiesStore(),store=useWorkflowsStore(),local=useDraftsStore().page('batch',()=>({name:'批量创作',json:'[]',taskType:'image.generate' as TaskType,prompts:'',draftId:''})),busy=ref(false),items=ref<BatchInput[]>([]),page=ref(1),total=ref(0),ids=ref<string[]>([])
|
||||
const policyText=computed(()=>{const p=caps.executionPolicy;if(p?.configuration_error)return '调度配置异常:批量任务保留排队,请联系管理员检查配置。';if(p?.batch_window_enabled===false)return '时段限制已关闭:开发测试可全天执行批量任务,仍需等待空闲资源。';return p?`批量执行窗口:${p.timezone} ${p.start}–${p.end}。${p.end} 后不启动新的任务或阶段,当前阶段继续完成;后续阶段等待下一窗口。`:'正在读取服务端时段配置,提交后按服务端规则持久排队。'})
|
||||
const drafts=computed(()=>Object.values(store.drafts)),batches=computed(()=>ids.value.map(id=>store.batches[id]).filter((x):x is BatchSnapshot=>!!x))
|
||||
function preview(){try{const parsed=JSON.parse(local.json);if(!Array.isArray(parsed)||!parsed.length||parsed.length>100)throw new Error('批量清单须包含 1–100 项');for(const item of parsed){if(item.kind==='workflow'){if(!item.draft_id||!Number.isInteger(item.draft_revision)||!Number.isInteger(item.expected_version))throw new Error('工作流项须包含草稿编号、修订和版本')}else if(item.kind==='job'){if(!Object.keys(taskLabels).includes(item.task_type)||!item.input||!item.parameters||item.count!==undefined&&(!Number.isInteger(item.count)||item.count<1||item.count>4)||JSON.stringify(item.input).length>40000)throw new Error('任务项类型、输入、参数或数量不合法');if(item.input.prompt?.length>8000)throw new Error('提示词最多 8000 字')}else throw new Error('清单项 kind 仅支持 workflow / job')}items.value=parsed;return parsed}catch(e){items.value=[];throw e}}
|
||||
function bulk(){const prompts=local.prompts.split('\n').map((x:string)=>x.trim()).filter(Boolean);local.json=JSON.stringify(prompts.map((prompt:string)=>({kind:'job',task_type:local.taskType,input:{prompt},parameters:{}})),null,2);inspect()}
|
||||
@ -18,4 +20,4 @@ async function submit(){busy.value=true;const session=store.sessionId();try{if(!
|
||||
async function control(snapshot:BatchSnapshot,state:string){busy.value=true;try{await store.controlBatch(snapshot.batch,state)}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
|
||||
onMounted(()=>{void load();void store.refresh().catch(()=>undefined)})
|
||||
</script>
|
||||
<template><div class="v2-page"><header class="page-heading"><span class="eyebrow">NIGHT QUEUE · FIFO</span><h1>把重复创作,交给夜晚。</h1><p>批量模式固定为夜间执行。08:00 后不启动新的任务或阶段,当前阶段继续完成;下一阶段等待下一个窗口。</p></header><div class="notice">浏览器关闭后队列继续保留。交互任务全天可提交,外部 GPU 使用优先。</div><div class="v2-columns"><section class="surface v2-panel"><h2>快速整理</h2><label>任务类型<el-select v-model="local.taskType"><el-option v-for="(label,key) in taskLabels" :key="key" :value="key" :label="label"/></el-select></label><el-input v-model="local.prompts" type="textarea" :rows="6" placeholder="每行一个提示词;需要素材的类型请在 JSON 补全素材编号" maxlength="200000"/><el-button @click="bulk">生成任务清单预览</el-button><h3>加入已保存工作流</h3><el-select v-model="local.draftId" placeholder="选择工作流"><el-option v-for="d in drafts" :key="d.id" :value="d.id" :label="`${d.name} · r${d.revision}`"/></el-select><el-button @click="addWorkflow">加入清单</el-button></section><section class="surface v2-panel"><h2>类型化清单 JSON</h2><el-input v-model="local.name" maxlength="255" placeholder="批量名称"/><el-input v-model="local.json" type="textarea" :rows="14" @input="items=[]"/><div class="v2-actions"><el-button @click="inspect">校验与预览</el-button><el-button type="primary" :loading="busy" @click="submit">提交夜间批量</el-button></div><p class="muted">执行模式:夜间批量(固定)。清单中每项可为 job 或 workflow;服务端再次校验全部参数与素材权限。</p></section></div><section v-if="items.length" class="surface v2-panel"><h2>提交预览 · {{ items.length }} 项</h2><ol><li v-for="(item,i) in items" :key="i">{{ item.kind==='workflow'?`工作流 ${item.draft_id} · r${item.draft_revision}`:`${taskLabels[item.task_type]} · ${item.input.prompt||'素材任务'} × ${item.count||1}` }}</li></ol></section><h2>批量记录</h2><article v-for="s in batches" :key="s.batch.id" class="surface v2-panel"><div class="v2-toolbar"><strong>{{ s.batch.name }}</strong><span>{{ s.batch.state }}</span><small>v{{ s.batch.version }}</small><el-button :disabled="busy" @click="control(s,s.batch.desired_state==='pause'?'run':'pause')">{{ s.batch.desired_state==='pause'?'继续':'暂停后续任务' }}</el-button><el-button type="danger" text :disabled="busy" @click="control(s,'cancel')">取消批量</el-button></div><ol><li v-for="item in s.items" :key="item.item_index"><router-link :to="item.target_kind==='run'?{path:'/tasks',query:{run:item.target_id}}:{path:'/tasks',query:{job:item.target_id}}">{{ item.target_kind }} · {{ item.target_id.slice(0,8) }} · {{ item.state }}</router-link></li></ol></article><el-pagination v-if="total>20" v-model:current-page="page" :total="total" :page-size="20" layout="prev,pager,next" @current-change="load()"/></div></template>
|
||||
<template><div class="v2-page"><header class="page-heading"><span class="eyebrow">PERSISTENT QUEUE · FIFO</span><h1>把重复创作,交给队列。</h1><p>{{ policyText }}</p></header><div class="notice">浏览器关闭后队列继续保留。交互任务全天可提交,外部 GPU 使用优先。</div><div class="v2-columns"><section class="surface v2-panel"><h2>快速整理</h2><label>任务类型<el-select v-model="local.taskType"><el-option v-for="(label,key) in taskLabels" :key="key" :value="key" :label="label"/></el-select></label><el-input v-model="local.prompts" type="textarea" :rows="6" placeholder="每行一个提示词;需要素材的类型请在 JSON 补全素材编号" maxlength="200000"/><el-button @click="bulk">生成任务清单预览</el-button><h3>加入已保存工作流</h3><el-select v-model="local.draftId" placeholder="选择工作流"><el-option v-for="d in drafts" :key="d.id" :value="d.id" :label="`${d.name} · r${d.revision}`"/></el-select><el-button @click="addWorkflow">加入清单</el-button></section><section class="surface v2-panel"><h2>类型化清单 JSON</h2><el-input v-model="local.name" maxlength="255" placeholder="批量名称"/><el-input v-model="local.json" type="textarea" :rows="14" @input="items=[]"/><div class="v2-actions"><el-button @click="inspect">校验与预览</el-button><el-button type="primary" :loading="busy" @click="submit">提交批量</el-button></div><p class="muted">{{ policyText }} 清单中每项可为 job 或 workflow;服务端再次校验全部参数与素材权限。</p></section></div><section v-if="items.length" class="surface v2-panel"><h2>提交预览 · {{ items.length }} 项</h2><ol><li v-for="(item,i) in items" :key="i">{{ item.kind==='workflow'?`工作流 ${item.draft_id} · r${item.draft_revision}`:`${taskLabels[item.task_type]} · ${item.input.prompt||'素材任务'} × ${item.count||1}` }}</li></ol></section><h2>批量记录</h2><article v-for="s in batches" :key="s.batch.id" class="surface v2-panel"><div class="v2-toolbar"><strong>{{ s.batch.name }}</strong><span>{{ s.batch.state }}</span><small>v{{ s.batch.version }}</small><el-button :disabled="busy" @click="control(s,s.batch.desired_state==='pause'?'run':'pause')">{{ s.batch.desired_state==='pause'?'继续':'暂停后续任务' }}</el-button><el-button type="danger" text :disabled="busy" @click="control(s,'cancel')">取消批量</el-button></div><ol><li v-for="item in s.items" :key="item.item_index"><router-link :to="item.target_kind==='run'?{path:'/tasks',query:{run:item.target_id}}:{path:'/tasks',query:{job:item.target_id}}">{{ item.target_kind }} · {{ item.target_id.slice(0,8) }} · {{ item.state }}</router-link></li></ol></article><el-pagination v-if="total>20" v-model:current-page="page" :total="total" :page-size="20" layout="prev,pager,next" @current-change="load()"/></div></template>
|
||||
|
||||
@ -20,11 +20,12 @@ const saved=useDraftsStore().page('compose',()=>({clips:[] as Clip[],audio:null
|
||||
const route=useRoute(), assets=useAssetsStore(), caps=useCapabilitiesStore(), jobs=useJobsStore(), clips=toRef(saved,'clips'), picker=ref(false), selected=ref(0), audio=toRef(saved,'audio'), subtitles=toRef(saved,'subtitles'), busy=ref(false), lastJobId=ref<string|null>(null), detailId=ref<string|null>(null), preview=ref<Asset|null>(null)
|
||||
const capability=computed(()=>caps.forTask('video.compose')), parameters=toRef(saved,'parameters'), activeClip=computed(()=>clips.value[selected.value]), job=computed(()=>lastJobId.value?jobs.byId[lastJobId.value]:undefined)
|
||||
const frameRates=computed(()=>composeFrameRates(capability.value))
|
||||
const maxClips=computed(()=>capability.value?.constraints.clips?.max??caps.workflowLimits.max_shots)
|
||||
const totalDuration=computed(()=>clips.value.reduce((total,clip)=>total+Math.max(0,(clip.end??clip.asset.duration_seconds??0)-clip.start),0))
|
||||
let dragged=-1
|
||||
watch(()=>capability.value?.defaults, defaults=>{if(defaults)parameters.value={...defaults,...parameters.value}}, {immediate:true})
|
||||
watch(frameRates, values=>{if(!values.includes(parameters.value.fps)){const fallback=capability.value?.defaults.fps;parameters.value.fps=values.includes(fallback)?fallback:values[0]}}, {immediate:true})
|
||||
function addClip(asset:Asset){clips.value.push({key:newRequestId(),asset,start:0,end:asset.duration_seconds});selected.value=clips.value.length-1}
|
||||
function addClip(asset:Asset){if(clips.value.length>=maxClips.value){ElMessage.warning(`本环境最多编排 ${maxClips.value} 个片段`);return}clips.value.push({key:newRequestId(),asset,start:0,end:asset.duration_seconds});selected.value=clips.value.length-1}
|
||||
function move(index:number,target:number){if(target<0||target>=clips.value.length)return;const [clip]=clips.value.splice(index,1);if(clip)clips.value.splice(target,0,clip);selected.value=target}
|
||||
function remove(index:number){clips.value.splice(index,1);selected.value=Math.min(selected.value,Math.max(0,clips.value.length-1))}
|
||||
function addSubtitle(){subtitles.value.push({start:0,end:Math.min(totalDuration.value||5,5),text:''})}
|
||||
@ -32,6 +33,7 @@ async function submit(){
|
||||
if(busy.value)return
|
||||
if(!capability.value?.available){ElMessage.warning('成片服务尚未就绪');return}
|
||||
if(!clips.value.length){ElMessage.warning('先添加至少一个视频片段');return}
|
||||
if(clips.value.length>maxClips.value){ElMessage.warning(`片段数量超过本环境上限 ${maxClips.value},请调整后再导出`);return}
|
||||
if(!isComposeFrameRateAllowed(parameters.value.fps,capability.value)){ElMessage.warning('请选择服务支持的导出帧率');return}
|
||||
for(const clip of clips.value)if(!Number.isFinite(clip.start)||clip.start<0||(clip.end!==null&&(!Number.isFinite(clip.end)||clip.end<=clip.start))){ElMessage.warning('请检查片段入点和出点,出点需要晚于入点');return}
|
||||
for(const subtitle of subtitles.value)if(!subtitle.text.trim()||subtitle.end<=subtitle.start||subtitle.start<0){ElMessage.warning('请补全字幕文字及正确的时间范围');return}
|
||||
@ -44,7 +46,7 @@ watch(()=>route.query.asset,importClip);onMounted(importClip)
|
||||
</script>
|
||||
<template>
|
||||
<div class="compose-page"><header class="page-heading split-heading"><div><span class="eyebrow">MAKE YOUR STORY WHOLE</span><h1>让好片段,成为一个故事。</h1><p>调整片段顺序、裁切与人工字幕,用 FFmpeg 完成清晰可控的成片。</p></div><el-button type="primary" :icon="MagicStick" :loading="busy" :disabled="!capability?.available" @click="submit">导出成片 <el-icon><ArrowRight /></el-icon></el-button></header>
|
||||
<div class="compose-layout"><section class="compose-main"><div class="compose-preview"><video v-if="activeClip" :key="activeClip.key" :src="activeClip.asset.preview_url" :poster="activeClip.asset.thumbnail_url||undefined" controls playsinline /><div v-else class="empty-state"><el-icon :size="46"><Film /></el-icon><h3>把你的片段,带到这里</h3><p>从素材库选择视频,或上传已有作品。</p><el-button :icon="Plus" @click="picker=true">添加视频片段</el-button></div></div><div class="timeline-heading"><h2>片段编排 <span>{{ clips.length }} 段 · {{ formatDuration(totalDuration) }}</span></h2><el-button :icon="Plus" @click="picker=true">添加片段</el-button></div><div class="timeline-strip"><article v-for="(clip,index) in clips" :key="clip.key" class="clip-card" :class="{selected:selected===index}" draggable="true" @dragstart="dragged=index" @dragover.prevent @drop.prevent="move(dragged,index)" @click="selected=index"><div class="clip-thumbnail"><img v-if="clip.asset.thumbnail_url" :src="clip.asset.thumbnail_url" :alt="clip.asset.name" /><video v-else :src="clip.asset.preview_url" muted preload="metadata" /><span>{{ String(index+1).padStart(2,'0') }}</span></div><strong>{{ clip.asset.name }}</strong><small>{{ formatDuration((clip.end??clip.asset.duration_seconds??0)-clip.start) }}</small><div class="clip-actions"><el-button text :icon="ArrowUp" :disabled="index===0" aria-label="片段前移" @click.stop="move(index,index-1)"/><el-button text :icon="ArrowDown" :disabled="index===clips.length-1" aria-label="片段后移" @click.stop="move(index,index+1)"/><el-button text type="danger" :icon="Delete" aria-label="移除片段" @click.stop="remove(index)"/></div></article><button class="add-clip-card" @click="picker=true"><el-icon><Plus /></el-icon><span>添加片段</span></button></div><small class="muted">拖动调整顺序,或使用前移 / 后移按钮。当前采用直切拼接。</small>
|
||||
<div class="compose-layout"><section class="compose-main"><div class="compose-preview"><video v-if="activeClip" :key="activeClip.key" :src="activeClip.asset.preview_url" :poster="activeClip.asset.thumbnail_url||undefined" controls playsinline /><div v-else class="empty-state"><el-icon :size="46"><Film /></el-icon><h3>把你的片段,带到这里</h3><p>从素材库选择视频,或上传已有作品。</p><el-button :icon="Plus" @click="picker=true">添加视频片段</el-button></div></div><div class="timeline-heading"><h2>片段编排 <span>{{ clips.length }} / {{ maxClips }} 段 · {{ formatDuration(totalDuration) }}</span></h2><el-button :icon="Plus" :disabled="clips.length>=maxClips" @click="picker=true">添加片段</el-button></div><div class="timeline-strip"><article v-for="(clip,index) in clips" :key="clip.key" class="clip-card" :class="{selected:selected===index}" draggable="true" @dragstart="dragged=index" @dragover.prevent @drop.prevent="move(dragged,index)" @click="selected=index"><div class="clip-thumbnail"><img v-if="clip.asset.thumbnail_url" :src="clip.asset.thumbnail_url" :alt="clip.asset.name" /><video v-else :src="clip.asset.preview_url" muted preload="metadata" /><span>{{ String(index+1).padStart(2,'0') }}</span></div><strong>{{ clip.asset.name }}</strong><small>{{ formatDuration((clip.end??clip.asset.duration_seconds??0)-clip.start) }}</small><div class="clip-actions"><el-button text :icon="ArrowUp" :disabled="index===0" aria-label="片段前移" @click.stop="move(index,index-1)"/><el-button text :icon="ArrowDown" :disabled="index===clips.length-1" aria-label="片段后移" @click.stop="move(index,index+1)"/><el-button text type="danger" :icon="Delete" aria-label="移除片段" @click.stop="remove(index)"/></div></article><button class="add-clip-card" :disabled="clips.length>=maxClips" @click="picker=true"><el-icon><Plus /></el-icon><span>添加片段</span></button></div><small class="muted">拖动调整顺序,或使用前移 / 后移按钮。当前采用直切拼接,片段上限由服务器配置。</small>
|
||||
<section v-if="job" class="compose-job surface"><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><span>{{ phaseLabel(job) }}</span><button class="text-link" @click="detailId=job.id">查看任务</button><el-button v-for="asset in job.result_assets.filter(item=>item.kind==='video')" :key="asset.id" type="primary" @click="preview=asset">预览成片</el-button></section>
|
||||
</section><aside class="compose-settings surface"><div class="panel-heading"><h2>导出设置</h2><span class="tiny-model">FFmpeg</span></div><div class="parameter-form"><label>输出宽度<el-input-number v-model="parameters.width" :min="capability?.constraints.width?.min||256" :max="capability?.constraints.width?.max||3840" :step="2" /></label><label>输出高度<el-input-number v-model="parameters.height" :min="capability?.constraints.height?.min||256" :max="capability?.constraints.height?.max||2160" :step="2" /></label><label>帧率<el-select v-model="parameters.fps" placeholder="选择导出帧率" aria-label="导出帧率"><el-option v-for="fps in frameRates" :key="fps" :value="fps" :label="`${fps} fps`" /></el-select></label></div><template v-if="activeClip"><h3 class="settings-subheading">当前片段裁切</h3><div class="parameter-form"><label>入点(秒)<el-input-number v-model="activeClip.start" :min="0" :max="activeClip.asset.duration_seconds||86400" :precision="2" :step="0.1" /></label><label>出点(秒)<el-input-number v-model="activeClip.end" :min="0" :max="activeClip.asset.duration_seconds||86400" :precision="2" :step="0.1" /></label></div></template><h3 class="settings-subheading">音轨(可选)</h3><AssetInput v-model="audio" :kinds="['audio']" label="添加音轨" hint="上传或选择你的音频素材" /><h3 class="settings-subheading subtitle-heading">人工字幕<el-button text :icon="Plus" @click="addSubtitle">添加</el-button></h3><div v-for="(row,index) in subtitles" :key="index" class="subtitle-row"><div><el-input-number v-model="row.start" :min="0" :step="0.1" :precision="1" :controls="false" aria-label="字幕开始秒数"/><span>—</span><el-input-number v-model="row.end" :min="0" :step="0.1" :precision="1" :controls="false" aria-label="字幕结束秒数"/><el-button text :icon="Delete" aria-label="删除字幕" @click="subtitles.splice(index,1)"/></div><el-input v-model="row.text" type="textarea" :rows="2" placeholder="字幕文字" /></div><p v-if="!subtitles.length" class="muted small">字幕由你填写,不将分块转写时间冒充逐词对齐。</p><div v-if="!capability?.available" class="notice warning">{{ capability?.description||'正在确认成片服务能力' }}</div></aside></div>
|
||||
<AssetPicker v-model="picker" :kinds="['video']" @select="addClip"/><AssetPreview v-model:asset="preview"/><JobDetail v-model:job-id="detailId"/>
|
||||
|
||||
@ -56,7 +56,7 @@ onMounted(() => { void jobs.refresh().catch(() => undefined); void importAsset()
|
||||
<header class="page-heading"><span class="eyebrow">{{ kind === 'math' ? 'REASONING SPACE' : kind === 'analyze' ? 'UNDERSTAND YOUR MEDIA' : 'AUDIO WORKSPACE' }}</span><h1>{{ title }}</h1><p>{{ subtitle }}</p></header>
|
||||
<div v-if="kind === 'audio'" class="mode-switch audio-tabs"><button :class="{ active: audioMode === 'transcribe' }" @click="audioMode = 'transcribe'">语音转写</button><button :class="{ active: audioMode === 'speech' }" @click="audioMode = 'speech'">配音生成 <small v-if="!caps.forTask('audio.speech')?.available">待配置</small></button></div>
|
||||
<div class="tool-columns"><section class="tool-input-panel surface"><div class="panel-heading"><h2>{{ kind === 'math' ? '写下你的问题' : kind === 'analyze' ? '添加待解析素材' : audioMode === 'speech' ? '写下配音文本' : '添加声音素材' }}</h2><span class="tiny-model">{{ capability?.model || '本地服务' }}</span></div>
|
||||
<textarea v-if="kind === 'math' || (kind === 'audio' && audioMode === 'speech')" v-model="draft.prompt" class="tool-textarea" :placeholder="kind === 'math' ? '例如:一个圆的半径增加20%,面积增加多少?请说明解题步骤。' : '输入希望转为声音的文字…'" maxlength="8000" aria-label="任务输入文本" @keydown.ctrl.enter.prevent="submit" />
|
||||
<textarea v-if="kind === 'math' || (kind === 'audio' && audioMode === 'speech')" v-model="draft.prompt" class="tool-textarea" :placeholder="kind === 'math' ? '例如:一个圆的半径增加20%,面积增加多少?请说明解题步骤。' : '输入希望转为声音的文字…'" :maxlength="taskType==='audio.speech'?limit('text','max',2000):8000" aria-label="任务输入文本" @keydown.ctrl.enter.prevent="submit" />
|
||||
<AssetInput v-else v-model="reference" :kinds="kind === 'analyze' ? ['image', 'video'] : ['audio', 'video']" :label="kind === 'analyze' ? '上传图片或视频' : '上传音频或视频'" :hint="kind === 'analyze' ? '识别主体、场景和画面文字' : '支持从视频中提取音轨后转写'" />
|
||||
<audio v-if="reference && kind === 'audio'" class="source-audio" :src="reference.preview_url" controls />
|
||||
<div v-if="kind === 'math'" class="prompt-suggestions"><button @click="draft.prompt = '一个圆的半径增加20%,面积增加多少?请给出清晰的解题过程。'">比例与面积</button><button @click="draft.prompt = '解方程 x² − 5x + 6 = 0,并验证两个解。'">方程求解</button></div>
|
||||
|
||||
@ -78,7 +78,7 @@ onMounted(() => { void jobs.refresh().catch(() => undefined); void importReferen
|
||||
<div class="composer-controls"><div class="composer-parameters"><span class="model-chip"><span class="model-mark">M</span>{{ capability?.model || '正在读取模型' }}</span>
|
||||
<el-popover placement="top-start" :width="310" trigger="click"><template #reference><button class="parameter-chip">{{ draft.parameters.width || '—' }} × {{ draft.parameters.height || '—' }}</button></template><div class="parameter-form"><h3>画面尺寸</h3><div v-if="mode !== 'video'" class="ratio-options"><button @click="ratio(1024, 1024)">1:1</button><button @click="ratio(1280, 720)">16:9</button><button @click="ratio(720, 1280)">9:16</button></div><label>宽度<el-input-number v-model="draft.parameters.width" :min="bound('width','min',256)" :max="bound('width','max',2048)" :step="bound('width','step',16)" /></label><label>高度<el-input-number v-model="draft.parameters.height" :min="bound('height','min',256)" :max="bound('height','max',2048)" :step="bound('height','step',16)" /></label></div></el-popover>
|
||||
<span v-if="mode === 'video'" class="parameter-chip">约 5 秒 · 121 帧 · 24 fps</span><el-select v-else v-model="draft.count" class="count-select" aria-label="生成数量"><el-option v-for="count in bound('count','max',4)" :key="count" :value="count" :label="`${count} 张`" /></el-select>
|
||||
<el-popover trigger="click" placement="top" :width="340"><template #reference><button class="parameter-chip"><el-icon><Setting /></el-icon>参数</button></template><div class="parameter-form"><h3>生成参数</h3><label>步数<el-input-number v-model="draft.parameters.num_inference_steps" :min="bound('num_inference_steps','min',1)" :max="bound('num_inference_steps','max',100)" /></label><label v-if="draft.parameters.seed !== undefined">随机种子<el-input-number v-model="draft.parameters.seed" :min="0" :max="4294967295" :controls="false" /></label><label v-if="draft.parameters.guidance_scale !== undefined">引导强度<el-input-number v-model="draft.parameters.guidance_scale" :min="bound('guidance_scale','min',1)" :max="bound('guidance_scale','max',20)" :step="0.5" /></label><template v-if="mode === 'defect'"><label>结构控制强度<el-input-number v-model="draft.parameters.controlnet_conditioning_scale" :min="0" :max="2" :step="0.1" /></label><label>Canny低阈值<el-input-number v-model="draft.parameters.canny_low" :min="0" :max="254" /></label><label>Canny高阈值<el-input-number v-model="draft.parameters.canny_high" :min="1" :max="255" /></label></template><label v-if="mode === 'video'">1080p 画质增强<el-switch v-model="draft.parameters.upscale" /></label><label class="vertical-label">不希望出现的内容<el-input v-model="draft.negative_prompt" maxlength="8000" type="textarea" :rows="2" placeholder="可选,例如模糊、变形" /></label><small v-if="mode === 'defect'">输出合成图和 Canny 控制图,不提供缺陷真值掩膜。</small><small v-if="mode === 'video'">当前最长约 5 秒,尚未开放视频延长或15秒生成。</small></div></el-popover>
|
||||
<el-popover trigger="click" placement="top" :width="340"><template #reference><button class="parameter-chip"><el-icon><Setting /></el-icon>参数</button></template><div class="parameter-form"><h3>生成参数</h3><label>步数<el-input-number v-model="draft.parameters.num_inference_steps" :min="bound('num_inference_steps','min',1)" :max="bound('num_inference_steps','max',100)" /></label><label v-if="draft.parameters.seed !== undefined">随机种子<el-input-number v-model="draft.parameters.seed" :min="0" :max="4294967295" :controls="false" /></label><label v-if="draft.parameters.guidance_scale !== undefined">引导强度<el-input-number v-model="draft.parameters.guidance_scale" :min="bound('guidance_scale','min',1)" :max="bound('guidance_scale','max',20)" :step="0.5" /></label><template v-if="mode === 'defect'"><label>结构控制强度<el-input-number v-model="draft.parameters.controlnet_conditioning_scale" :min="0" :max="2" :step="0.1" /></label><label>Canny低阈值<el-input-number v-model="draft.parameters.canny_low" :min="0" :max="254" /></label><label>Canny高阈值<el-input-number v-model="draft.parameters.canny_high" :min="1" :max="255" /></label></template><label v-if="mode === 'video'">1080p 画质增强<el-switch v-model="draft.parameters.upscale" /></label><label class="vertical-label">不希望出现的内容<el-input v-model="draft.negative_prompt" maxlength="8000" type="textarea" :rows="2" placeholder="可选,例如模糊、变形" /></label><small v-if="mode === 'defect'">输出合成图和 Canny 控制图,不提供缺陷真值掩膜。</small><small v-if="mode === 'video'">单镜头最长约 5 秒;较长故事请前往工作流添加多个镜头。</small></div></el-popover>
|
||||
<el-popover trigger="click" placement="top" :width="300"><template #reference><button class="parameter-chip" :class="{ highlighted: draft.scheduledAt }"><el-icon><Clock /></el-icon>{{ draft.scheduledAt ? '已预约' : '预约' }}</button></template><div class="parameter-form"><h3>预约创作</h3><el-date-picker v-model="draft.scheduledAt" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DDTHH:mm:ss" clearable /><small>按当前浏览器时区选择。到达时间后进入串行队列。</small></div></el-popover>
|
||||
</div><el-button class="generate-button" type="primary" :loading="busy" :disabled="!capability?.available" :icon="MagicStick" @click="submit">{{ draft.scheduledAt ? '预约生成' : '开始生成' }} <el-icon v-if="!busy"><ArrowRight /></el-icon></el-button></div>
|
||||
</div><div class="composer-footnote"><span>{{ capability?.available ? '空闲算力串行执行 · 被占用时自动让行与重试' : capability?.description || '正在连接本地创作服务' }}</span><span>Ctrl + Enter 生成</span></div></section>
|
||||
|
||||
63
frontend/src/views/WorkflowView.multishot.test.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import {afterEach,describe,expect,it,vi} from 'vitest'
|
||||
import {createSSRApp,defineComponent,h} from 'vue'
|
||||
import {renderToString} from 'vue/server-renderer'
|
||||
import {createPinia,setActivePinia} from 'pinia'
|
||||
import {useDraftsStore} from '../stores/drafts'
|
||||
import {emptyWorkflow,replaceWorkflowShots,validateWorkflow} from '../v2types'
|
||||
import type {WorkflowSpec} from '../v2types'
|
||||
import WorkflowView from './WorkflowView.vue'
|
||||
const assetSelections=vi.hoisted(()=>[] as ((asset:any)=>unknown)[])
|
||||
vi.mock('../components/AssetPicker.vue',async()=>{const {defineComponent}=await import('vue');return {default:defineComponent({setup(_,{attrs}){if(typeof attrs.onSelect==='function')assetSelections.push(attrs.onSelect as (asset:any)=>unknown);return()=>null}})}})
|
||||
vi.mock('../components/RunCard.vue',()=>({default:{render:()=>null}}))
|
||||
afterEach(()=>vi.restoreAllMocks())
|
||||
async function editor(spec:WorkflowSpec){
|
||||
assetSelections.length=0
|
||||
const pinia=createPinia();setActivePinia(pinia)
|
||||
const local=useDraftsStore().page('workflow',()=>({name:'故事',spec,draftId:'',version:0}))
|
||||
const buttons:{label:string;click:()=>unknown}[]=[],changes:((value:number)=>unknown)[]=[]
|
||||
const app=createSSRApp(WorkflowView);app.use(pinia)
|
||||
app.component('ElButton',defineComponent({setup(_,{attrs,slots}){const nodes=slots.default?.()||[],label=nodes.map(n=>typeof n.children==='string'?n.children:'').join('');if(typeof attrs.onClick==='function')buttons.push({label,click:attrs.onClick as ()=>unknown});return()=>h('button',nodes)}}))
|
||||
app.component('ElInputNumber',defineComponent({setup(_,{attrs}){if(typeof attrs.onChange==='function')changes.push(attrs.onChange as (value:number)=>unknown);return()=>null}}))
|
||||
for(const name of ['ElInput','ElSelect','ElOption'])app.component(name,defineComponent({setup(_,{slots}){return()=>h('div',slots.default?.())}}))
|
||||
return {html:await renderToString(app),local,buttons,changes}
|
||||
}
|
||||
describe('compiled variable workflow editor',()=>{
|
||||
it('shows a100-second story and exposes explicit import/export without submitting it',async()=>{
|
||||
const spec=emptyWorkflow();spec.shots=Array.from({length:20},(_,i)=>({...spec.shots[0]!,key:`shot_${i+1}`,prompt:`画面${i+1}`}));spec.render.total_frames=2400
|
||||
const view=await editor(spec)
|
||||
expect(view.html).toContain('20 个镜头 · 2400 帧 · 100.00 秒')
|
||||
expect(view.html).toContain('载入鲲鹏示例');expect(view.html).toContain('导入工作流 JSON');expect(view.html).toContain('导出工作流 JSON')
|
||||
expect(view.local.draftId).toBe('')
|
||||
})
|
||||
it('adds, reorders, deletes and renumbers shots while preserving their content',async()=>{
|
||||
const spec=emptyWorkflow();spec.shots.forEach((s,i)=>s.prompt=`内容${i+1}`)
|
||||
const view=await editor(spec)
|
||||
await view.buttons.find(b=>b.label==='添加镜头')!.click();expect(view.local.spec.shots).toHaveLength(4)
|
||||
await view.buttons.filter(b=>b.label==='后移')[0]!.click();expect(view.local.spec.shots.slice(0,2).map(s=>s.prompt)).toEqual(['内容2','内容1'])
|
||||
await view.buttons.filter(b=>b.label==='删除镜头')[1]!.click();expect(view.local.spec.shots.map(s=>s.key)).toEqual(['shot_1','shot_2','shot_3']);expect(view.local.spec.shots[0]?.prompt).toBe('内容2')
|
||||
expect(view.local.spec.render.total_frames).toBe(360)
|
||||
})
|
||||
it('opens legacy data unchanged and upgrades it on a duration edit',async()=>{
|
||||
const spec=emptyWorkflow();spec.schema_version=1;spec.shots.forEach(s=>delete s.duration_frames)
|
||||
const view=await editor(spec);expect(view.local.spec.schema_version).toBe(1)
|
||||
view.changes[0]!(2)
|
||||
expect(view.local.spec.schema_version).toBe(2);expect(view.local.spec.shots[0]?.duration_frames).toBe(48);expect(view.local.spec.render.total_frames).toBe(288)
|
||||
})
|
||||
it('preserves existing absolute subtitle boundaries when reordering',()=>{
|
||||
const spec=emptyWorkflow();spec.render.subtitles=[{start_frame:240,end_frame:360,text:'结尾'}]
|
||||
const swapped=replaceWorkflowShots(spec,[spec.shots[2]!,spec.shots[0]!,spec.shots[1]!])
|
||||
expect(swapped.render.subtitles).toEqual(spec.render.subtitles)
|
||||
})
|
||||
it('keeps the full100-second narration selected and blocks a15-second export until explicitly resolved',async()=>{
|
||||
const spec=emptyWorkflow();spec.shots.forEach(s=>s.prompt='镜头')
|
||||
const view=await editor(spec)
|
||||
assetSelections[1]!({id:'long-voice',duration_seconds:100})
|
||||
expect(view.local.spec.render.audio?.source_end_ms).toBe(100000)
|
||||
expect(()=>validateWorkflow(view.local.spec)).toThrow('音频选段与偏移')
|
||||
const refreshed=await editor(view.local.spec)
|
||||
expect(refreshed.html).toContain('音频选段超过当前成片时长')
|
||||
const longer=replaceWorkflowShots(view.local.spec,Array.from({length:20},()=>spec.shots[0]!))
|
||||
expect(longer.render.audio?.source_end_ms).toBe(100000)
|
||||
expect(()=>validateWorkflow(longer)).not.toThrow()
|
||||
})
|
||||
})
|
||||
@ -1,26 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import {computed,onMounted,ref} from 'vue'
|
||||
import {ElMessage} from 'element-plus'
|
||||
import {computed,onMounted,ref,watch} from 'vue'
|
||||
import {ElMessage,ElMessageBox} from 'element-plus'
|
||||
import {errorMessage} from '../api'
|
||||
import {useWorkflowsStore} from '../stores/workflows'
|
||||
import {useDraftsStore} from '../stores/drafts'
|
||||
import {emptyWorkflow,validateWorkflow} from '../v2types'
|
||||
import type {DraftDTO} from '../v2types'
|
||||
import {useCapabilitiesStore} from '../stores/capabilities'
|
||||
import {createWorkflowShot,emptyWorkflow,replaceWorkflowShots,validateWorkflow,workflowFrames} from '../v2types'
|
||||
import type {DraftDTO,WorkflowSpec} from '../v2types'
|
||||
import type {Asset} from '../types'
|
||||
import AssetPicker from '../components/AssetPicker.vue'
|
||||
import RunCard from '../components/RunCard.vue'
|
||||
const reuse=ref(''), store=useWorkflowsStore(), local=useDraftsStore().page('workflow',()=>({name:'三镜头故事',spec:emptyWorkflow(),draftId:'',version:0})),busy=ref(false),picker=ref(false),pickShot=ref(0),audioPicker=ref(false)
|
||||
const drafts=computed(()=>Object.values(store.drafts).sort((a,b)=>b.updated_at.localeCompare(a.updated_at))),draft=computed(()=>store.drafts[local.draftId]),runs=computed(()=>Object.values(store.runs).filter(x=>x.run.draft_id===local.draftId).sort((a,b)=>b.run.created_at.localeCompare(a.run.created_at)))
|
||||
function choose(value:DraftDTO){local.name=value.name;local.spec=JSON.parse(JSON.stringify(value.spec));local.draftId=value.id;local.version=value.version}
|
||||
async function load(id:string){try{const loaded=await store.fetchDraft(id);if(loaded)choose(loaded)}catch(e){ElMessage.error(errorMessage(e))}}
|
||||
async function save(session:number){if(session!==store.sessionId())return;if(!local.name.trim()||local.name.length>255)throw new Error('名称须为 1–255 字');validateWorkflow(local.spec);const current=draft.value;if(current&¤t.version!==local.version)throw new Error('服务端草稿已更新,请重新载入后再编辑,当前本地内容仍保留');if(current&¤t.name===local.name&&JSON.stringify(current.spec)===JSON.stringify(local.spec))return current;const saved=await store.saveDraft(current?{...current,version:local.version}:undefined,local.name,local.spec,session);if(saved)choose(saved);return saved}
|
||||
const reuse=ref(''),store=useWorkflowsStore(),caps=useCapabilitiesStore()
|
||||
const local=useDraftsStore().page('workflow',()=>({name:'多镜头故事',spec:emptyWorkflow(),draftId:'',version:0}))
|
||||
const busy=ref(false),picker=ref(false),pickShot=ref(0),audioPicker=ref(false),fileInput=ref<HTMLInputElement>()
|
||||
const drafts=computed(()=>Object.values(store.drafts).sort((a,b)=>b.updated_at.localeCompare(a.updated_at)))
|
||||
const draft=computed(()=>store.drafts[local.draftId])
|
||||
const runs=computed(()=>Object.values(store.runs).filter(x=>x.run.draft_id===local.draftId).sort((a,b)=>b.run.created_at.localeCompare(a.run.created_at)))
|
||||
const maxShots=computed(()=>caps.workflowLimits.max_shots),totalFrames=computed(()=>workflowFrames(local.spec)),totalSeconds=computed(()=>totalFrames.value/24)
|
||||
const shotRanges=computed(()=>{let start=0;return local.spec.shots.map(shot=>{const range={start,end:start+(shot.duration_frames??120)};start=range.end;return range})})
|
||||
const audioOverflow=computed(()=>{const a=local.spec.render.audio;return !!a&&(a.source_end_ms-a.source_start_ms)*24/1000+a.offset_frame>totalFrames.value})
|
||||
let synchronizing=false
|
||||
// Opening legacy data preserves it. Editing upgrades it to the variable timeline.
|
||||
watch(()=>local.spec,spec=>{if(synchronizing)return;synchronizing=true;try{if(spec.schema_version===1)local.spec=replaceWorkflowShots(spec,spec.shots);else if(spec.render.total_frames!==workflowFrames(spec))spec.render.total_frames=workflowFrames(spec)}finally{synchronizing=false}},{deep:true,flush:'sync'})
|
||||
function choose(value:DraftDTO){synchronizing=true;try{local.name=value.name;local.spec=JSON.parse(JSON.stringify(value.spec));local.draftId=value.id;local.version=value.version}finally{synchronizing=false}}
|
||||
async function load(id:string){if(!id)return;try{const loaded=await store.fetchDraft(id);if(loaded)choose(loaded)}catch(e){ElMessage.error(errorMessage(e))}}
|
||||
async function save(session:number){if(session!==store.sessionId())return;if(!local.name.trim()||local.name.length>255)throw new Error('名称须为 1–255 字');validateWorkflow(local.spec,maxShots.value);const current=draft.value;if(current&¤t.version!==local.version)throw new Error('服务端草稿已更新,请重新载入后再编辑,当前本地内容仍保留');if(current&¤t.name===local.name&&JSON.stringify(current.spec)===JSON.stringify(local.spec))return current;const saved=await store.saveDraft(current?{...current,version:local.version}:undefined,local.name,local.spec,session);if(saved)choose(saved);return saved}
|
||||
async function act(run=false){if(busy.value)return;busy.value=true;const session=store.sessionId();try{const saved=await save(session);if(!saved)return;if(run){const snapshot=await store.startRun(saved,reuse.value||undefined,session);if(!snapshot)return;if(snapshot.draft)choose(snapshot.draft);ElMessage.success('工作流已提交')}else ElMessage.success('草稿已保存')}catch(e){ElMessage.error(errorMessage(e))}finally{busy.value=false}}
|
||||
function fresh(){local.name='三镜头故事';local.spec=emptyWorkflow();local.draftId='';local.version=0}
|
||||
function fresh(){synchronizing=true;try{local.name='多镜头故事';local.spec=emptyWorkflow();local.draftId='';local.version=0;reuse.value=''}finally{synchronizing=false}}
|
||||
function addShot(){if(local.spec.shots.length>=maxShots.value)return;local.spec=replaceWorkflowShots(local.spec,[...local.spec.shots,createWorkflowShot(local.spec.shots.length)])}
|
||||
function removeShot(index:number){if(local.spec.shots.length<=1)return;local.spec=replaceWorkflowShots(local.spec,local.spec.shots.filter((_,i)=>i!==index))}
|
||||
function moveShot(index:number,target:number){if(target<0||target>=local.spec.shots.length)return;const shots=[...local.spec.shots],shot=shots.splice(index,1)[0];if(shot){shots.splice(target,0,shot);local.spec=replaceWorkflowShots(local.spec,shots)}}
|
||||
function setDuration(index:number,seconds:number|undefined){if(!local.spec.shots[index]||seconds===undefined||!Number.isFinite(seconds))return;const frames=Math.max(24,Math.min(120,Math.round(seconds*24)));local.spec=replaceWorkflowShots(local.spec,local.spec.shots.map((shot,i)=>i===index?{...shot,duration_frames:frames}:shot))}
|
||||
function selectAudio(asset:Asset){local.spec.render.audio={asset_id:asset.id,source_start_ms:0,source_end_ms:Math.max(1,Math.round((asset.duration_seconds??totalSeconds.value)*1000)),offset_frame:0,short_policy:'silence'}}
|
||||
async function confirmImport(){if(!local.draftId&&local.name==='多镜头故事'&&JSON.stringify(local.spec)===JSON.stringify(emptyWorkflow()))return true;try{await ElMessageBox.confirm('载入内容将替换当前编辑区,尚未保存的修改会丢失;服务器上已保存的草稿仍保留。是否继续?','载入工作流',{confirmButtonText:'载入为新草稿',cancelButtonText:'保留当前内容',type:'warning'});return true}catch{return false}}
|
||||
async function applyImport(spec:WorkflowSpec,name:string,session:number){if(session!==store.sessionId())return;validateWorkflow(spec,maxShots.value);if(!await confirmImport()||session!==store.sessionId())return;synchronizing=true;try{local.name=name.slice(0,255);local.spec=JSON.parse(JSON.stringify(spec));local.draftId='';local.version=0;reuse.value=''}finally{synchronizing=false}ElMessage.success(`已载入 ${spec.shots.length} 个镜头,尚未保存或运行`)}
|
||||
async function importFile(event:Event){const input=event.target as HTMLInputElement,file=input.files?.[0];if(!file||busy.value)return;busy.value=true;const session=store.sessionId();try{if(file.size>32*1024*1024)throw new Error('工作流 JSON 文件不能超过 32 MiB');await applyImport(JSON.parse(await file.text()),file.name.replace(/\.json$/i,''),session)}catch(e){if(session===store.sessionId())ElMessage.error(errorMessage(e))}finally{input.value='';busy.value=false}}
|
||||
async function loadExample(){if(busy.value)return;busy.value=true;const session=store.sessionId();try{const response=await fetch('/examples/kunpeng-storyboard.json');if(!response.ok)throw new Error('示例暂不可用,请稍后重试');await applyImport(await response.json(),'鲲鹏·北冥南徙(20镜头)',session)}catch(e){if(session===store.sessionId())ElMessage.error(errorMessage(e))}finally{busy.value=false}}
|
||||
function exportJSON(){const url=URL.createObjectURL(new Blob([JSON.stringify(local.spec,null,2)],{type:'application/json;charset=utf-8'})),link=document.createElement('a');link.href=url;link.download=`${local.name.replace(/[\\/:*?"<>|]/g,'_')||'workflow'}.json`;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000)}
|
||||
onMounted(()=>store.refresh().catch(e=>ElMessage.error(errorMessage(e))))
|
||||
</script>
|
||||
<template><div class="v2-page"><header class="page-heading split-heading"><div><span class="eyebrow">THREE SHOTS · ONE STORY</span><h1>把三个瞬间,连成一个故事。</h1><p>每个镜头 120 帧,三段成片 360 帧 / 24 fps。交互创作全天候等待空闲算力。</p></div><div class="v2-actions"><el-button @click="fresh">新建</el-button><el-button :loading="busy" @click="act()">保存草稿</el-button><el-button type="primary" :loading="busy" @click="act(true)">保存并运行</el-button></div></header>
|
||||
<div class="v2-toolbar"><el-select :model-value="local.draftId" clearable placeholder="打开已保存工作流" @change="load"><el-option v-for="d in drafts" :key="d.id" :value="d.id" :label="`${d.name} · r${d.revision}`"/></el-select><el-input v-model="local.name" maxlength="255" placeholder="故事名称"/><small v-if="draft">修订 {{ draft.revision }} · 版本 {{ local.version }}<template v-if="draft.version!==local.version"> · 服务端已更新</template></small><el-button v-if="draft" text @click="load(draft.id)">重新载入</el-button></div>
|
||||
<div class="v2-shots"><section v-for="(shot,index) in local.spec.shots" :key="shot.key" class="surface v2-panel"><span class="eyebrow">SHOT {{ index+1 }} · {{ index*120 }}–{{ (index+1)*120 }} FRAMES</span><h2>镜头 {{ index+1 }}</h2><el-input v-model="shot.prompt" type="textarea" :rows="7" maxlength="8000" show-word-limit placeholder="描述这个镜头的画面、动作和光线"/><label>种子<el-input-number v-model="shot.parameters.seed" :min="0" :max="4294967295" :precision="0"/></label><div class="v2-actions"><el-button @click="pickShot=index;picker=true">选择参考图片</el-button><el-button v-if="shot.image_asset_id" text @click="shot.image_asset_id=null">移除</el-button></div><small class="muted">{{ shot.image_asset_id||'使用文生视频' }}</small></section></div>
|
||||
<section class="surface v2-panel"><h2>成片设置</h2><div class="v2-toolbar"><label>画幅<el-select v-model="local.spec.profile"><el-option value="landscape_1080_v1" label="横屏 1920 × 1080"/><el-option value="portrait_1080_v1" label="竖屏 1080 × 1920"/></el-select></label><label>适配<el-select v-model="local.spec.render.fit"><el-option value="contain" label="完整画面(留边)"/><el-option value="cover" label="填满画面(裁切)"/></el-select></label><span class="muted">固定 24 fps · 360 帧 · 15 秒</span></div><h3>音轨</h3><el-button @click="audioPicker=true">选择音频素材</el-button><template v-if="local.spec.render.audio"><el-button text @click="local.spec.render.audio=null">移除音轨</el-button><p class="muted">{{ local.spec.render.audio.asset_id }}</p><div class="v2-toolbar"><label>源入点 ms<el-input-number v-model="local.spec.render.audio.source_start_ms" :min="0" :max="86400000" :precision="0"/></label><label>源出点 ms<el-input-number v-model="local.spec.render.audio.source_end_ms" :min="1" :max="86400000" :precision="0"/></label><label>偏移帧<el-input-number v-model="local.spec.render.audio.offset_frame" :min="0" :max="359" :precision="0"/></label></div><p class="muted">短音频补静音。音频选段与偏移总计不可超过 360 帧,长旁白须手动选段。</p></template><h3>人工字幕(帧)</h3><div v-for="(row,index) in local.spec.render.subtitles" :key="index" class="v2-toolbar"><el-input-number v-model="row.start_frame" :min="0" :max="359" :precision="0" aria-label="字幕开始帧"/><span>至</span><el-input-number v-model="row.end_frame" :min="1" :max="360" :precision="0" aria-label="字幕结束帧"/><el-input v-model="row.text" maxlength="2000" placeholder="字幕文字"/><el-button text @click="local.spec.render.subtitles.splice(index,1)">删除</el-button></div><el-button :disabled="local.spec.render.subtitles.length>=1000" @click="local.spec.render.subtitles.push({start_frame:0,end_frame:120,text:''})">添加字幕</el-button></section>
|
||||
|
||||
<template><div class="v2-page">
|
||||
<header class="page-heading split-heading"><div><span class="eyebrow">MANY SHOTS · ONE STORY</span><h1>把每个瞬间,连成一个故事。</h1><p>自由增减镜头,总时长随分镜变化。交互创作全天等待空闲算力。</p></div><div class="v2-actions"><el-button :disabled="busy" @click="fresh">新建</el-button><el-button :loading="busy" @click="act()">保存草稿</el-button><el-button type="primary" :loading="busy" @click="act(true)">保存并运行</el-button></div></header>
|
||||
<div class="v2-toolbar"><el-select :model-value="local.draftId" :disabled="busy" clearable placeholder="打开已保存工作流" @change="load"><el-option v-for="d in drafts" :key="d.id" :value="d.id" :label="`${d.name} · r${d.revision}`"/></el-select><el-input v-model="local.name" maxlength="255" placeholder="故事名称"/><small v-if="draft">修订 {{ draft.revision }} · 版本 {{ local.version }}<template v-if="draft.version!==local.version"> · 服务端已更新</template></small><el-button v-if="draft" text :disabled="busy" @click="load(draft.id)">重新载入</el-button></div>
|
||||
<div class="v2-toolbar"><a class="el-button" href="/help/manual.html" target="_blank" rel="noopener">操作手册</a><a class="el-button" href="/help/kunpeng.html" target="_blank" rel="noopener">鲲鹏制作步骤</a><el-button :disabled="busy" @click="loadExample">载入鲲鹏示例</el-button><el-button :disabled="busy" @click="fileInput?.click()">导入工作流 JSON</el-button><el-button :disabled="busy" @click="exportJSON">导出工作流 JSON</el-button><input ref="fileInput" type="file" accept="application/json,.json" hidden @change="importFile"/><span class="muted">导入只更新本地编辑区,保存后才写入服务器,运行后才调用模型。</span></div>
|
||||
<section class="surface v2-panel"><div class="v2-toolbar"><strong>{{ local.spec.shots.length }} 个镜头 · {{ totalFrames }} 帧 · {{ totalSeconds.toFixed(2) }} 秒</strong><el-button :disabled="busy||local.spec.shots.length>=maxShots" @click="addShot">添加镜头</el-button><small class="muted">本环境最多 {{ maxShots }} 个镜头,可由管理员配置。</small></div><p class="muted">每镜头生成约 5 秒源片段,再选用其中 1–5 秒;缩短成片片段不会等比例缩短模型推理。镜头顺序或时长调整后,请复核音轨及字幕的绝对时间。</p></section>
|
||||
<div class="v2-shots"><section v-for="(shot,index) in local.spec.shots" :key="shot.key" class="surface v2-panel"><span class="eyebrow">SHOT {{ index+1 }} · {{ shotRanges[index]?.start }}–{{ shotRanges[index]?.end }} FRAMES</span><h2>镜头 {{ index+1 }}</h2><div class="v2-actions"><el-button :disabled="busy||index===0" @click="moveShot(index,index-1)">前移</el-button><el-button :disabled="busy||index===local.spec.shots.length-1" @click="moveShot(index,index+1)">后移</el-button><el-button text type="danger" :disabled="busy||local.spec.shots.length===1" @click="removeShot(index)">删除镜头</el-button></div><el-input v-model="shot.prompt" type="textarea" :rows="7" maxlength="8000" show-word-limit placeholder="描述这个镜头的画面、动作和光线"/><label>选用时长(秒)<el-input-number :model-value="(shot.duration_frames??120)/24" :min="1" :max="5" :step="0.25" :precision="2" @change="setDuration(index,$event)"/></label><small class="muted">{{ shot.duration_frames??120 }} 帧 · 24 fps</small><label>种子<el-input-number v-model="shot.parameters.seed" :min="0" :max="4294967295" :precision="0"/></label><div class="v2-actions"><el-button @click="pickShot=index;picker=true">选择参考图片</el-button><el-button v-if="shot.image_asset_id" text @click="shot.image_asset_id=null">移除参考图</el-button></div><small class="muted">{{ shot.image_asset_id||'使用文生视频' }}</small></section></div>
|
||||
<section class="surface v2-panel"><h2>成片设置</h2><div class="v2-toolbar"><label>画幅<el-select v-model="local.spec.profile"><el-option value="landscape_1080_v1" label="横屏 1920 × 1080"/><el-option value="portrait_1080_v1" label="竖屏 1080 × 1920"/></el-select></label><label>适配<el-select v-model="local.spec.render.fit"><el-option value="contain" label="完整画面(留边)"/><el-option value="cover" label="填满画面(裁切)"/></el-select></label><span class="muted">24 fps · {{ totalFrames }} 帧 · {{ totalSeconds.toFixed(2) }} 秒</span></div>
|
||||
<h3>音轨</h3><el-button @click="audioPicker=true">选择音频素材</el-button><template v-if="local.spec.render.audio"><el-button text @click="local.spec.render.audio=null">移除音轨</el-button><p class="muted">{{ local.spec.render.audio.asset_id }}</p><div class="v2-toolbar"><label>源入点 ms<el-input-number v-model="local.spec.render.audio.source_start_ms" :min="0" :max="86400000" :precision="0"/></label><label>源出点 ms<el-input-number v-model="local.spec.render.audio.source_end_ms" :min="1" :max="86400000" :precision="0"/></label><label>偏移帧<el-input-number v-model="local.spec.render.audio.offset_frame" :min="0" :max="totalFrames-1" :precision="0"/></label></div><p class="muted">短音频补静音。音频选段与偏移总计不可超过 {{ totalFrames }} 帧;默认选择完整音频,不会静默截断长旁白。若超过成片时长,请增加镜头或明确修改源出点后再保存。</p><p v-if="audioOverflow" class="notice warning">音频选段超过当前成片时长,请增加镜头或调整选段后再保存。</p></template>
|
||||
<h3>人工字幕(帧)</h3><p class="muted">1 秒 = 24 帧。字幕按整片绝对时间填写,不会随镜头移动自动对齐。</p><div v-for="(row,index) in local.spec.render.subtitles" :key="index" class="v2-toolbar"><el-input-number v-model="row.start_frame" :min="0" :max="totalFrames-1" :precision="0" aria-label="字幕开始帧"/><span>至</span><el-input-number v-model="row.end_frame" :min="1" :max="totalFrames" :precision="0" aria-label="字幕结束帧"/><el-input v-model="row.text" maxlength="2000" placeholder="字幕文字"/><el-button text @click="local.spec.render.subtitles.splice(index,1)">删除</el-button></div><el-button :disabled="local.spec.render.subtitles.length>=1000" @click="local.spec.render.subtitles.push({start_frame:0,end_frame:Math.min(120,totalFrames),text:''})">添加字幕</el-button></section>
|
||||
<div v-if="runs.length" class="v2-toolbar"><h2>运行记录</h2><el-select v-model="reuse" clearable placeholder="下次运行复用已完成镜头(可选)"><el-option v-for="s in runs" :key="s.run.id" :value="s.run.id" :label="`r${s.run.draft_revision} · ${s.run.id.slice(0,8)}`"/></el-select><small class="muted">仅复用输入完全一致且产物仍存在的成功镜头。</small></div><RunCard v-for="snapshot in runs" :key="snapshot.run.id" :snapshot="snapshot"/>
|
||||
<AssetPicker v-model="picker" :kinds="['image']" @select="asset=>local.spec.shots[pickShot]!.image_asset_id=asset.id"/><AssetPicker v-model="audioPicker" :kinds="['audio']" @select="asset=>local.spec.render.audio={asset_id:asset.id,source_start_ms:0,source_end_ms:Math.min(15000,Math.round((asset.duration_seconds||15)*1000)),offset_frame:0,short_policy:'silence'}"/>
|
||||
<AssetPicker v-model="picker" :kinds="['image']" @select="asset=>{const shot=local.spec.shots[pickShot];if(shot)shot.image_asset_id=asset.id}"/><AssetPicker v-model="audioPicker" :kinds="['audio']" @select="selectAudio"/>
|
||||
</div></template>
|
||||
|
||||
@ -84,7 +84,7 @@ def create_app(settings=None):
|
||||
return {"protocol_version": 2, "admission_policy": True,
|
||||
"features": {"scheduling": True, "admission_pause": True, "control_versions": True,
|
||||
"result_manifest": True, "final_output_indices": True, "forced_window_stop": False},
|
||||
"execution_policy": policy_status(time.time())}
|
||||
"execution_policy": policy_status(time.time(), policy_file=application.state.settings.runtime_policy_file)}
|
||||
|
||||
@application.post("/jobs", status_code=202, dependencies=secured)
|
||||
def submit(body: Submission, idempotency_key: str | None = Header(default=None)):
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
SHANGHAI = timezone(timedelta(hours=8), "Asia/Shanghai")
|
||||
FIELDS = {"execution_mode", "principal_id", "batch_id", "run_id", "step_key", "policy_version"}
|
||||
@ -29,7 +30,40 @@ def normalize_scheduling(value):
|
||||
return result
|
||||
|
||||
|
||||
def eligibility(mode, now):
|
||||
def read_runtime_policy(policy_file=None):
|
||||
"""Read the same operator schema as the web API; never read job payloads."""
|
||||
result = {"batch_window_enabled": True, "workflow_max_shots": 120,
|
||||
"configuration_error": None}
|
||||
if policy_file is None:
|
||||
return result
|
||||
try:
|
||||
with Path(policy_file).open("rb") as stream:
|
||||
raw = stream.read(65537)
|
||||
except FileNotFoundError:
|
||||
return result
|
||||
except OSError:
|
||||
return {**result, "configuration_error": "runtime_policy_unavailable"}
|
||||
try:
|
||||
if len(raw) > 65536:
|
||||
raise ValueError("Policy too large")
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(value, dict) or set(value) - {
|
||||
"schema_version", "batch_window_enabled", "workflow_max_shots"}:
|
||||
raise ValueError("Unknown policy fields")
|
||||
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
|
||||
raise ValueError("Unsupported schema")
|
||||
if type(value.get("batch_window_enabled")) is not bool:
|
||||
raise ValueError("Expected boolean switch")
|
||||
max_shots = value.get("workflow_max_shots", 120)
|
||||
if type(max_shots) is not int or not 1 <= max_shots <= 1000:
|
||||
raise ValueError("Invalid shot limit")
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
return {**result, "configuration_error": "runtime_policy_invalid"}
|
||||
return {"batch_window_enabled": value["batch_window_enabled"],
|
||||
"workflow_max_shots": max_shots, "configuration_error": None}
|
||||
|
||||
|
||||
def _window_eligibility(mode, now):
|
||||
if mode not in {"interactive", "batch"}:
|
||||
raise ValueError("Invalid execution mode")
|
||||
local = datetime.fromtimestamp(float(now), timezone.utc).astimezone(SHANGHAI)
|
||||
@ -40,15 +74,38 @@ def eligibility(mode, now):
|
||||
"next_eligible_at": None if mode == "interactive" or opened else next_start.timestamp()}
|
||||
|
||||
|
||||
def policy_status(now):
|
||||
batch = eligibility("batch", now)
|
||||
def _configured_eligibility(mode, now, policy):
|
||||
if mode not in {"interactive", "batch"}:
|
||||
raise ValueError("Invalid execution mode")
|
||||
if mode == "interactive":
|
||||
return {"eligible": True, "reason": None, "next_eligible_at": None}
|
||||
if policy["configuration_error"]:
|
||||
return {"eligible": False, "reason": policy["configuration_error"], "next_eligible_at": None}
|
||||
if not policy["batch_window_enabled"]:
|
||||
return {"eligible": True, "reason": None, "next_eligible_at": None}
|
||||
return _window_eligibility(mode, now)
|
||||
|
||||
|
||||
def eligibility(mode, now, *, policy_file=None):
|
||||
return _configured_eligibility(mode, now, read_runtime_policy(policy_file))
|
||||
|
||||
|
||||
def policy_status(now, *, policy_file=None):
|
||||
policy=read_runtime_policy(policy_file)
|
||||
batch = _configured_eligibility("batch", now, policy)
|
||||
return {"timezone": "Asia/Shanghai", "start": "21:00", "end": "08:00",
|
||||
"batch_window_enabled": policy["batch_window_enabled"],
|
||||
"configuration_error": policy["configuration_error"],
|
||||
"batch_open": batch["eligible"], "next_batch_at": batch["next_eligible_at"],
|
||||
"close_behavior": "finish_current"}
|
||||
|
||||
|
||||
def guarded_eligibility(now, max_seen=0, closed_through=""):
|
||||
def guarded_eligibility(now, max_seen=0, closed_through="", *, policy_file=None):
|
||||
"""Persist returned watermark and closed date before admitting a new runner."""
|
||||
policy=read_runtime_policy(policy_file)
|
||||
if policy["configuration_error"] or not policy["batch_window_enabled"]:
|
||||
# Keep clock evidence unchanged while development mode bypasses it.
|
||||
return _configured_eligibility("batch", now, policy),max_seen,closed_through
|
||||
try:
|
||||
watermark=float(max_seen)
|
||||
if not math.isfinite(watermark) or not 0<=watermark<=253402300799:raise ValueError()
|
||||
@ -59,7 +116,7 @@ def guarded_eligibility(now, max_seen=0, closed_through=""):
|
||||
local = datetime.fromtimestamp(now, timezone.utc).astimezone(SHANGHAI)
|
||||
latest_closed = local.date() if local.hour >= 8 else local.date() - timedelta(days=1)
|
||||
closed_through = max(closed_through, latest_closed.isoformat())
|
||||
result = eligibility("batch", now)
|
||||
result = _window_eligibility("batch", now)
|
||||
if now < float(max_seen) - 5:
|
||||
result.update(eligible=False, reason="clock_rollback", next_eligible_at=float(max_seen))
|
||||
elif result["eligible"]:
|
||||
|
||||
@ -86,12 +86,15 @@ class Settings:
|
||||
poll_seconds: float = .2
|
||||
terminate_grace_seconds: float = 5.0
|
||||
kill_wait_seconds: float = 10.0
|
||||
runtime_policy_file: Path | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
self.workspace_root = Path(self.workspace_root).resolve()
|
||||
self.app_root = Path(self.app_root).resolve()
|
||||
self.runtime_policy_file = Path(self.runtime_policy_file or self.app_root / "config" / "runtime-policy.json").resolve()
|
||||
try:
|
||||
self.app_root.relative_to(self.workspace_root)
|
||||
self.runtime_policy_file.relative_to(self.workspace_root)
|
||||
except ValueError as exc:
|
||||
raise ValueError("APP_ROOT must be below WORKSPACE_ROOT") from exc
|
||||
for field in ("poll_seconds", "terminate_grace_seconds", "kill_wait_seconds"):
|
||||
@ -144,7 +147,8 @@ class Settings:
|
||||
runner_python=os.environ.get("LLM_RUNNER_PYTHON", data.get("runner_python", cls.runner_python)),
|
||||
poll_seconds=data.get("poll_seconds", .2),
|
||||
terminate_grace_seconds=data.get("terminate_grace_seconds", 5),
|
||||
kill_wait_seconds=data.get("kill_wait_seconds", 10))
|
||||
kill_wait_seconds=data.get("kill_wait_seconds", 10),
|
||||
runtime_policy_file=os.environ.get("RUNTIME_POLICY_FILE") or None)
|
||||
|
||||
|
||||
def validate_request(task_type, inputs, parameters, workspace):
|
||||
@ -178,8 +182,9 @@ def validate_request(task_type, inputs, parameters, workspace):
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path):
|
||||
def __init__(self, path, *, policy_file=None):
|
||||
self.path = Path(path)
|
||||
self.policy_file = Path(policy_file) if policy_file is not None else None
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self._connection() as connection:
|
||||
connection.executescript("""
|
||||
@ -358,7 +363,7 @@ class Store:
|
||||
def _batch_eligibility(self, connection, now):
|
||||
result, watermark, closed = guarded_eligibility(now,
|
||||
self._state(connection, "clock_max_seen", "0"),
|
||||
self._state(connection, "closed_window_through", ""))
|
||||
self._state(connection, "closed_window_through", ""), policy_file=self.policy_file)
|
||||
self._set_state(connection, "clock_max_seen", watermark)
|
||||
self._set_state(connection, "closed_window_through", closed)
|
||||
return result
|
||||
@ -538,4 +543,4 @@ def initialize_store(settings):
|
||||
for directory in (settings.app_root, settings.state_dir, settings.jobs_dir, settings.outputs_dir):
|
||||
confined_path(directory, settings.workspace_root).mkdir(parents=True, exist_ok=True)
|
||||
confined_path(settings.db_path, settings.workspace_root)
|
||||
return Store(settings.db_path)
|
||||
return Store(settings.db_path, policy_file=settings.runtime_policy_file)
|
||||
|
||||
@ -159,7 +159,7 @@ class Worker:
|
||||
payload = {"state": state, "lease": lease, "job_id": job["id"] if job else None,
|
||||
"attempt_count": job["attempt_count"] if job else None,
|
||||
"reason": reason, "policy": policy_status, "worker_pid": os.getpid(),
|
||||
"execution_policy": execution_policy_status(self.clock())}
|
||||
"execution_policy": execution_policy_status(self.clock(), policy_file=self.settings.runtime_policy_file)}
|
||||
snapshot = json.dumps(payload, sort_keys=True, allow_nan=False)
|
||||
if snapshot != self._scheduler_snapshot:
|
||||
atomic_json(confined_path(self.settings.state_dir / "gpu-scheduler.json",
|
||||
|
||||
175
inference/tests/test_runtime_policy.py
Normal file
@ -0,0 +1,175 @@
|
||||
"""The operator file controls GPU admission, including already persisted jobs."""
|
||||
from datetime import datetime
|
||||
import json
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from llm_services.store import Store, Settings, initialize_store
|
||||
from llm_services.scheduling import policy_status
|
||||
|
||||
|
||||
def epoch(value):
|
||||
return datetime.fromisoformat(value).timestamp()
|
||||
|
||||
|
||||
def write_policy(path, enabled):
|
||||
path.write_text(json.dumps({"schema_version": 1, "batch_window_enabled": enabled,
|
||||
"workflow_max_shots": 120}), encoding="utf-8")
|
||||
|
||||
|
||||
def submit(store, mode="batch"):
|
||||
return store.submit("image.generate", {"prompt": "operator policy"}, {}, scheduling={
|
||||
"execution_mode": mode, "principal_id": "owner", "policy_version": "night-v1"})
|
||||
|
||||
|
||||
def test_hot_config_releases_same_gpu_queue_id_then_blocks_next_phase(tmp_path):
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
||||
job = submit(store)
|
||||
noon = epoch("2026-11-11T12:00:00+08:00")
|
||||
assert store.claim_next(now=noon) is None
|
||||
write_policy(path, False)
|
||||
assert store.claim_next(now=noon)["id"] == job["id"]
|
||||
assert store.admission(job["id"], now=noon)["eligible"]
|
||||
write_policy(path, True)
|
||||
assert not store.admission(job["id"], now=noon)["eligible"]
|
||||
# Re-enabling does not cancel an already admitted runner.
|
||||
store.finish(job["id"], "succeeded", result={"outputs": []})
|
||||
next_job = submit(store)
|
||||
assert store.claim_next(now=noon) is None
|
||||
write_policy(path, False)
|
||||
store.control(next_job["id"], "pause", command_id="manual-pause")
|
||||
assert store.claim_next(now=noon) is None
|
||||
store.control(next_job["id"], "run", command_id="manual-resume")
|
||||
assert store.claim_next(now=noon)["id"] == next_job["id"]
|
||||
|
||||
|
||||
def test_disabled_policy_does_not_erase_clock_corruption(tmp_path):
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
||||
submit(store)
|
||||
with store._connection() as connection:
|
||||
store._set_state(connection, "clock_max_seen", "NaN")
|
||||
write_policy(path, False)
|
||||
noon = epoch("2026-11-11T12:00:00+08:00")
|
||||
assert store.peek_next(now=noon)
|
||||
with store._connection() as connection:
|
||||
assert store._state(connection, "clock_max_seen") == "NaN"
|
||||
write_policy(path, True)
|
||||
assert store.peek_next(now=noon) is None
|
||||
assert store.waiting_summary(now=noon)["reason"] == "clock_state_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", ["{corrupt", '{"schema_version":1,"batch_window_enabled":"false"}',
|
||||
'{"schema_version":true,"batch_window_enabled":false}',
|
||||
'{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":1001}'])
|
||||
def test_invalid_policy_blocks_batch_even_at_night_but_not_interactive(tmp_path, content):
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
path.write_text(content, encoding="utf-8")
|
||||
store = Store(tmp_path / "jobs.sqlite3", policy_file=path)
|
||||
submit(store)
|
||||
now = epoch("2026-11-11T22:00:00+08:00")
|
||||
assert store.peek_next(now=now) is None
|
||||
interactive = submit(store, "interactive")
|
||||
assert store.claim_next(now=now)["id"] == interactive["id"]
|
||||
info = policy_status(now, policy_file=path)
|
||||
assert not info["batch_open"] and info["configuration_error"] == "runtime_policy_invalid"
|
||||
|
||||
|
||||
def test_settings_and_status_use_the_same_policy_path(tmp_path, monkeypatch):
|
||||
path = tmp_path / "config.json"
|
||||
write_policy(path, False)
|
||||
monkeypatch.setenv("APP_ROOT", str(tmp_path / "app"))
|
||||
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("RUNTIME_POLICY_FILE", str(path))
|
||||
settings = Settings.from_env()
|
||||
assert settings.runtime_policy_file == path
|
||||
store = initialize_store(settings)
|
||||
noon = epoch("2026-11-11T12:00:00+08:00")
|
||||
job = submit(store)
|
||||
assert store.peek_next(now=noon)["id"] == job["id"]
|
||||
info = policy_status(noon, policy_file=path)
|
||||
assert info["batch_window_enabled"] is False and info["batch_open"]
|
||||
assert info["next_batch_at"] is None and info["configuration_error"] is None
|
||||
|
||||
|
||||
def test_api_reports_hot_policy_but_rejects_client_window_override(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
from llm_services.api import create_app
|
||||
settings = Settings(tmp_path / "app", tmp_path)
|
||||
settings.key_file.parent.mkdir(parents=True)
|
||||
settings.key_file.write_text("test-only-runtime-policy-key")
|
||||
write_policy(settings.runtime_policy_file, False)
|
||||
headers = {"Authorization": "Bearer test-only-runtime-policy-key"}
|
||||
with TestClient(create_app(settings)) as client:
|
||||
body = client.get("/capabilities", headers=headers).json()
|
||||
assert body["execution_policy"]["batch_window_enabled"] is False
|
||||
write_policy(settings.runtime_policy_file, True)
|
||||
body = client.get("/capabilities", headers=headers).json()
|
||||
assert body["execution_policy"]["batch_window_enabled"] is True
|
||||
response = client.post("/jobs", headers=headers, json={"task_type": "image.generate",
|
||||
"input": {"prompt": "cannot bypass"}, "scheduling": {
|
||||
"execution_mode": "batch", "principal_id": "owner",
|
||||
"batch_window_enabled": False}})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="Linux process/flock integration")
|
||||
def test_running_worker_finishes_after_policy_reenabled_then_next_job_waits(tmp_path, monkeypatch):
|
||||
from llm_services.worker import Worker
|
||||
from llm_services import worker as worker_module
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
write_policy(path, False)
|
||||
settings = Settings(tmp_path / "app", tmp_path, runner_python=sys.executable,
|
||||
poll_seconds=.01, runtime_policy_file=path)
|
||||
store = initialize_store(settings)
|
||||
first, second = submit(store), submit(store)
|
||||
noon = epoch("2026-11-11T12:00:00+08:00")
|
||||
runner = tmp_path / "fake.py"
|
||||
runner.write_text('import json,pathlib,sys,time\nr=json.loads(pathlib.Path(sys.argv[1]).read_text());time.sleep(.05)\np=pathlib.Path(r["output_dir"])/"result.txt";p.write_text("finished")\npathlib.Path(sys.argv[2]).write_text(json.dumps({"outputs":[str(p)]}))')
|
||||
|
||||
class PolicyWorker(Worker):
|
||||
def _command(self, request_path, result_path):
|
||||
return [sys.executable, str(runner), str(request_path), str(result_path)]
|
||||
|
||||
real_popen = worker_module.subprocess.Popen
|
||||
|
||||
def launch_then_enable(*args, **kwargs):
|
||||
process = real_popen(*args, **kwargs)
|
||||
write_policy(path, True)
|
||||
return process
|
||||
|
||||
monkeypatch.setattr(worker_module.subprocess, "Popen", launch_then_enable)
|
||||
with PolicyWorker(settings, gpu_policy=None, clock=lambda: noon) as worker:
|
||||
assert worker.run_once()
|
||||
assert store.get(first["id"])["state"] == "succeeded"
|
||||
assert not worker.run_once()
|
||||
assert store.get(second["id"])["state"] == "queued"
|
||||
assert store.get(second["id"])["attempt_count"] == 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="Linux process/flock integration")
|
||||
def test_final_launch_gate_hot_reads_policy_after_command_preparation(tmp_path, monkeypatch):
|
||||
from llm_services.worker import Worker
|
||||
from llm_services import worker as worker_module
|
||||
path = tmp_path / "runtime-policy.json"
|
||||
write_policy(path, False)
|
||||
settings = Settings(tmp_path / "app", tmp_path, runner_python=sys.executable,
|
||||
poll_seconds=.01, runtime_policy_file=path)
|
||||
store = initialize_store(settings)
|
||||
job = submit(store)
|
||||
|
||||
class DeferredWorker(Worker):
|
||||
def _command(self, *args):
|
||||
write_policy(path, True)
|
||||
return [sys.executable, "-c", "raise SystemExit('must not launch')"]
|
||||
|
||||
def forbidden(*args, **kwargs):
|
||||
raise AssertionError("A daytime batch spawned after production policy was enabled")
|
||||
|
||||
monkeypatch.setattr(worker_module.subprocess, "Popen", forbidden)
|
||||
with DeferredWorker(settings, gpu_policy=None,
|
||||
clock=lambda: epoch("2026-11-11T12:00:00+08:00")) as worker:
|
||||
assert worker.run_once()
|
||||
assert store.get(job["id"])["state"] == "queued"
|
||||
10
qa/browser-v3-final.cjs
Normal file
@ -0,0 +1,10 @@
|
||||
const fs=require('fs'),path=require('path');const {chromium}=require('C:/Users/Administrator/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const root=path.resolve(__dirname,'..'),base='http://127.0.0.1:8000';const live=JSON.parse(fs.readFileSync(path.join(root,'qa/v3-live.json'),'utf8'));
|
||||
const env=Object.fromEntries(fs.readFileSync(path.join(root,'.env.server'),'utf8').split(/\r?\n/).filter(x=>x&&!x.startsWith('#')).map(x=>{const i=x.indexOf('=');return[x.slice(0,i),x.slice(i+1)]}));
|
||||
(async()=>{let browser;try{browser=await chromium.launch({headless:true,channel:'chrome'});const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/login');await page.getByPlaceholder('输入你的账号').fill(env.ADMIN_USERNAME);await page.getByPlaceholder('输入密码',{exact:true}).fill(env.ADMIN_PASSWORD);await page.getByRole('button',{name:'进入工作空间'}).click();await page.waitForURL('**/create/image');await page.goto(base+'/workflow');await page.getByRole('button',{name:'新建',exact:true}).click();
|
||||
for(const section of await page.locator('.v2-shots>section').all())await section.locator('textarea').fill('界面音轨完整时长校验,不运行');
|
||||
await page.getByRole('button',{name:'选择音频素材',exact:true}).click();await page.locator('.picker-item').filter({hasText:'鲲鹏完整旁白(开发验收).wav'}).click();await page.getByText('音频选段超过当前成片时长,请增加镜头或调整选段后再保存。',{exact:true}).waitFor();const audioEnd=()=>page.locator('label').filter({hasText:'源出点 ms'}).locator('input');if(Number(await audioEnd().inputValue())!==44425)throw new Error('Narration was silently truncated');let posts=0;page.on('request',r=>{if(r.url().endsWith('/api/workflows')&&r.method()==='POST')posts++});await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('音频选段与偏移必须在 360 帧内,不会自动截断长旁白',{exact:true}).waitFor();if(posts)throw new Error('Invalid overflow draft was submitted');
|
||||
await page.locator('.v2-toolbar .el-select').first().click();await page.locator('.el-select-dropdown__item').filter({hasText:'鲲鹏·45秒旁白版(未运行)'}).click();await page.getByText('20 个镜头 · 1080 帧 · 45.00 秒',{exact:true}).waitFor();if(Number(await audioEnd().inputValue())!==44425)throw new Error('Saved full narration missing');await page.locator('.v2-page').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'qa/v3-compact-desktop.png')});
|
||||
const media=await page.evaluate(async id=>{const v=document.createElement('video');v.src='/api/assets/'+id+'/content';v.muted=true;v.preload='auto';document.body.append(v);await new Promise((resolve,reject)=>{v.addEventListener('loadedmetadata',resolve,{once:true});v.addEventListener('error',()=>reject(new Error('Video metadata error')),{once:true})});await v.play();await new Promise(resolve=>{v.addEventListener('seeked',resolve,{once:true});v.currentTime=15.5});v.pause();const result={duration:v.duration,width:v.videoWidth,height:v.videoHeight,seek:v.currentTime,error:v.error?.message||null};v.remove();return result},live.composition.asset_id);if(Math.abs(media.duration-16)>.05||Math.abs(media.seek-15.5)>.2||media.error)throw new Error('Long video playback failed');
|
||||
await page.goto(base+'/help/kunpeng.html');await page.getByText('44.425秒',{exact:false}).first().waitFor();const href=await page.getByRole('link',{name:'下载45秒分镜',exact:true}).getAttribute('href');const example=await(await page.request.get(base+href)).json();if(example.render.total_frames!==1080||example.shots.length!==20)throw new Error('Compact download');await page.screenshot({path:path.join(root,'qa/v3-guide-desktop.png')});
|
||||
const report={full_audio_ms:44425,overflow_blocked_before_http:posts===0,compact_draft_id:live.compact_draft_id,compact_frames:1080,compact_download:true,media,errors};fs.writeFileSync(path.join(root,'qa/v3-browser-final.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));}finally{if(browser)await browser.close()}})().catch(e=>{console.error(e.message);process.exitCode=1});
|
||||
22
qa/browser-v3.cjs
Normal file
@ -0,0 +1,22 @@
|
||||
const fs=require('fs'),path=require('path');
|
||||
const {chromium}=require('C:/Users/Administrator/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
const root=path.resolve(__dirname,'..'),base='http://127.0.0.1:8000';
|
||||
const env=Object.fromEntries(fs.readFileSync(path.join(root,'.env.server'),'utf8').split(/\r?\n/).filter(x=>x&&!x.startsWith('#')).map(x=>{const i=x.indexOf('=');return[x.slice(0,i),x.slice(i+1)]}));
|
||||
(async()=>{let browser;try{
|
||||
browser=await chromium.launch({headless:true,channel:'chrome'});const page=await browser.newPage({viewport:{width:1440,height:1000}}),errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/login');await page.getByPlaceholder('输入你的账号').fill(env.ADMIN_USERNAME);await page.getByPlaceholder('输入密码',{exact:true}).fill(env.ADMIN_PASSWORD);await page.getByRole('button',{name:'进入工作空间'}).click();await page.waitForURL('**/create/image');await page.goto(base+'/workflow');await page.getByRole('heading',{name:'把每个瞬间,连成一个故事。'}).waitFor();
|
||||
await page.getByRole('button',{name:'新建',exact:true}).click();await page.getByRole('button',{name:'载入鲲鹏示例',exact:true}).click();await page.locator('.v2-shots>section').nth(19).waitFor();
|
||||
if(await page.locator('.v2-shots>section').count()!==20)throw new Error('Example shot count');
|
||||
await page.getByText('20 个镜头 · 2400 帧 · 100.00 秒',{exact:true}).waitFor();
|
||||
const first=page.locator('.v2-shots>section').first(),second=page.locator('.v2-shots>section').nth(1),original=await first.locator('textarea').inputValue();
|
||||
await first.getByRole('button',{name:'后移',exact:true}).click();if(await second.locator('textarea').inputValue()!==original)throw new Error('Move shot');await second.getByRole('button',{name:'前移',exact:true}).click();
|
||||
const duration=first.locator('.el-input-number input').first();await duration.fill('1');await duration.press('Tab');await page.getByText('20 个镜头 · 2304 帧 · 96.00 秒',{exact:true}).waitFor();await duration.fill('5');await duration.press('Tab');
|
||||
await page.getByRole('button',{name:'添加镜头',exact:true}).click();if(await page.locator('.v2-shots>section').count()!==21)throw new Error('Add shot');await page.locator('.v2-shots>section').last().getByRole('button',{name:'删除镜头',exact:true}).click();
|
||||
await page.getByPlaceholder('故事名称').fill('鲲鹏·20镜头100秒示例(未运行)');const pending=page.waitForResponse(r=>r.url().endsWith('/api/workflows')&&r.request().method()==='POST');await page.getByRole('button',{name:'保存草稿',exact:true}).click();const response=await pending;if(response.status()!==201)throw new Error('Save new example status '+response.status());const draft=await response.json();if(draft.current_run_id)throw new Error('Saving must not run');
|
||||
await page.reload();await page.getByText('20 个镜头 · 2400 帧 · 100.00 秒',{exact:true}).waitFor();await page.screenshot({path:path.join(root,'qa/v3-workflow-desktop.png')});
|
||||
await page.mouse.move(1000,700);await page.mouse.wheel(0,20000);await page.waitForTimeout(350);const desktop=await page.locator('.v2-page').evaluate(e=>({top:e.scrollTop,height:e.clientHeight,total:e.scrollHeight,overflow:e.scrollWidth>e.clientWidth+2}));if(desktop.top<1||desktop.overflow)throw new Error('Desktop scroll');
|
||||
await page.setViewportSize({width:390,height:844});await page.locator('.v2-page').evaluate(e=>e.scrollTop=0);await page.screenshot({path:path.join(root,'qa/v3-workflow-mobile.png')});await page.mouse.move(240,600);await page.mouse.wheel(0,50000);await page.waitForTimeout(350);const mobile=await page.locator('.v2-page').evaluate(e=>({top:e.scrollTop,height:e.clientHeight,total:e.scrollHeight,overflow:e.scrollWidth>e.clientWidth+2}));if(mobile.top<1||mobile.overflow||mobile.total-mobile.height-mobile.top>4)throw new Error('Mobile scroll or settings unreachable');await page.screenshot({path:path.join(root,'qa/v3-workflow-mobile-bottom.png')});
|
||||
const help=await browser.newPage({viewport:{width:1440,height:1000}});const manual=await help.goto(base+'/help/manual.html');if(manual.status()!==200)throw new Error('Manual unavailable');await help.getByRole('heading',{name:'CMVR Visual 操作手册',exact:true}).waitFor();await help.screenshot({path:path.join(root,'qa/v3-manual-desktop.png')});await help.setViewportSize({width:390,height:844});if(await help.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2))throw new Error('Manual mobile horizontal overflow');await help.screenshot({path:path.join(root,'qa/v3-manual-mobile.png')});
|
||||
await help.goto(base+'/help/kunpeng.html');await help.getByRole('heading',{name:'鲲鹏长视频制作指南',exact:true}).waitFor();if(await help.locator('tbody tr').count()!==20)throw new Error('Story guide shot table');
|
||||
const report={draft_id:draft.id,saved_without_running:true,shots:20,seconds:100,add_remove_reorder_duration:true,desktop,mobile,manuals:true,errors};fs.writeFileSync(path.join(root,'qa/v3-browser.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
|
||||
}finally{if(browser)await browser.close()}})().catch(e=>{console.error(e.message);process.exitCode=1});
|
||||
15
qa/v3-browser-final.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"full_audio_ms": 44425,
|
||||
"overflow_blocked_before_http": true,
|
||||
"compact_draft_id": "cecafd1041a6465eb3982a0449717208",
|
||||
"compact_frames": 1080,
|
||||
"compact_download": true,
|
||||
"media": {
|
||||
"duration": 16,
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"seek": 15.500183,
|
||||
"error": null
|
||||
},
|
||||
"errors": []
|
||||
}
|
||||
21
qa/v3-browser.json
Normal file
@ -0,0 +1,21 @@
|
||||
{
|
||||
"draft_id": "265761009d2346598065033c377258b0",
|
||||
"saved_without_running": true,
|
||||
"shots": 20,
|
||||
"seconds": 100,
|
||||
"add_remove_reorder_duration": true,
|
||||
"desktop": {
|
||||
"top": 5416,
|
||||
"height": 936,
|
||||
"total": 6352,
|
||||
"overflow": false
|
||||
},
|
||||
"mobile": {
|
||||
"top": 16069,
|
||||
"height": 786,
|
||||
"total": 16855,
|
||||
"overflow": false
|
||||
},
|
||||
"manuals": true,
|
||||
"errors": []
|
||||
}
|
||||
BIN
qa/v3-compact-desktop.png
Normal file
|
After Width: | Height: | Size: 248 KiB |
90
qa/v3-deployment.json
Normal file
@ -0,0 +1,90 @@
|
||||
{
|
||||
"readiness": {
|
||||
"status": "ready",
|
||||
"checks": {
|
||||
"database": true,
|
||||
"coordinator": true,
|
||||
"upstream_protocol": true,
|
||||
"accepting": true
|
||||
}
|
||||
},
|
||||
"images": {
|
||||
"cmvr-visual-api": "sha256:b6262aed3b888e815aefee2f25e810f984720c5907f928c4536223e0a67003ee",
|
||||
"cmvr-visual-frontend": "sha256:6337287848c6f817e1a4067015e04db1bf3951693a8d2590d2fa0e5bddbef472"
|
||||
},
|
||||
"isolation": {
|
||||
"cmvr-visual-tts": {
|
||||
"same_id": true,
|
||||
"same_start": true
|
||||
},
|
||||
"llmuser-workspace": {
|
||||
"same_id": true,
|
||||
"same_start": true
|
||||
},
|
||||
"llmuser-gpu-guard": {
|
||||
"same_id": true,
|
||||
"same_start": true
|
||||
},
|
||||
"cmvr-qwen38-fast": {
|
||||
"same_id": true,
|
||||
"same_start": true
|
||||
},
|
||||
"cmvr-qwen38-accurate": {
|
||||
"same_id": true,
|
||||
"same_start": true
|
||||
}
|
||||
},
|
||||
"checkpoint": {
|
||||
"directory": "/root/cmvr-visual-v3-20261111",
|
||||
"files": {
|
||||
"pre-v3-mysql.sql": {
|
||||
"bytes": 288437,
|
||||
"sha256": "f4b24ed13032dd79b5a5790714b9e3d335aaa6db82b90d388a17c3a09cc1faf4"
|
||||
},
|
||||
"pre-v3-model-queue.sqlite3": {
|
||||
"bytes": 77824,
|
||||
"sha256": "6ae33c04f38861f11fe8f86fcc1783e130e4490f5d37dc58f9234f9ce2d2ef88"
|
||||
},
|
||||
"pre-v3-workspace.tar": {
|
||||
"bytes": 359352320,
|
||||
"sha256": "2237f1c8ea948e1cc30591acde6d099f8690ffa48bb3dc0217e6ccb84522ea82"
|
||||
}
|
||||
},
|
||||
"sqlite_integrity": "ok",
|
||||
"tar_entries": 956
|
||||
},
|
||||
"runtime_policy": {
|
||||
"batch_window_enabled": false,
|
||||
"workflow_max_shots": 120
|
||||
},
|
||||
"schema": "003",
|
||||
"hot_policy_both_services_verified": true,
|
||||
"verification": {
|
||||
"backend": 188,
|
||||
"backend_subtests": 20,
|
||||
"frontend": 79,
|
||||
"inference": 149,
|
||||
"inference_subtests": 120,
|
||||
"real_ffmpeg": 6
|
||||
},
|
||||
"live_video": {
|
||||
"programs": [],
|
||||
"stream_groups": [],
|
||||
"streams": [
|
||||
{
|
||||
"codec_name": "h264",
|
||||
"width": 1920,
|
||||
"height": 1080,
|
||||
"avg_frame_rate": "24/1",
|
||||
"duration": "16.000000",
|
||||
"nb_read_frames": "384"
|
||||
}
|
||||
],
|
||||
"format": {
|
||||
"duration": "16.000000",
|
||||
"size": "5699705"
|
||||
},
|
||||
"full_decode": "passed",
|
||||
"sha256": "ea879240d7729e6c43e66435973a708907d58ea5e73ff2b75c805ad7343932d8"
|
||||
}
|
||||
}
|
||||
BIN
qa/v3-guide-desktop.png
Normal file
|
After Width: | Height: | Size: 134 KiB |
63
qa/v3-live.json
Normal file
@ -0,0 +1,63 @@
|
||||
{
|
||||
"execution_policy": {
|
||||
"timezone": "Asia/Shanghai",
|
||||
"start": "21:00",
|
||||
"end": "08:00",
|
||||
"batch_window_enabled": false,
|
||||
"configuration_error": null,
|
||||
"batch_open": true,
|
||||
"next_batch_at": null,
|
||||
"close_behavior": "finish_current"
|
||||
},
|
||||
"workflow_limits": {
|
||||
"max_shots": 120,
|
||||
"source_frames": 121,
|
||||
"max_clip_frames": 120,
|
||||
"fps": 24
|
||||
},
|
||||
"sample_draft_id": "265761009d2346598065033c377258b0",
|
||||
"sample_draft_not_run": true,
|
||||
"composition_job_id": "8a138a6cb1334b299499337340e27c7c",
|
||||
"narration_job_id": "d35d949b13c24cfeaf8ec22c85a552fa",
|
||||
"math_batch_id": "b14a496618754520ac80e46a69b602b2",
|
||||
"composition": {
|
||||
"asset_id": "f73cc20eda6c411d9bcfca68af4aec36",
|
||||
"result": {
|
||||
"fps": 24,
|
||||
"width": 1920,
|
||||
"frames": 384,
|
||||
"height": 1080,
|
||||
"clip_count": 4,
|
||||
"subtitle_count": 2,
|
||||
"duration_seconds": 16.0
|
||||
},
|
||||
"bytes": 5699705
|
||||
},
|
||||
"narration": {
|
||||
"asset_id": "34e1c004c3214f298d201d3cc22d18a9",
|
||||
"voice": "zm_yunxi",
|
||||
"speed": 0.85,
|
||||
"duration_seconds": 44.425,
|
||||
"bytes": 2132444,
|
||||
"characters": 203
|
||||
},
|
||||
"math_after_http_close": {
|
||||
"job_id": "d39ca29b18f74ba9b5022ec2e6928a5e",
|
||||
"succeeded": true,
|
||||
"answer": {
|
||||
"text": "15"
|
||||
}
|
||||
},
|
||||
"ready": {
|
||||
"status": "ready",
|
||||
"checks": {
|
||||
"database": true,
|
||||
"coordinator": true,
|
||||
"upstream_protocol": true,
|
||||
"accepting": true
|
||||
}
|
||||
},
|
||||
"compact_draft_id": "cecafd1041a6465eb3982a0449717208",
|
||||
"compact_frames": 1080,
|
||||
"compact_has_full_narration": true
|
||||
}
|
||||
BIN
qa/v3-manual-desktop.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
BIN
qa/v3-manual-mobile.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
46
qa/v3-policy-hot.json
Normal file
@ -0,0 +1,46 @@
|
||||
{
|
||||
"true": {
|
||||
"api_policy": {
|
||||
"timezone": "Asia/Shanghai",
|
||||
"start": "21:00",
|
||||
"end": "08:00",
|
||||
"batch_window_enabled": true,
|
||||
"configuration_error": null,
|
||||
"batch_open": true,
|
||||
"next_batch_at": "2026-11-11T13:00:00+00:00",
|
||||
"close_behavior": "finish_current"
|
||||
},
|
||||
"gpu_policy": {
|
||||
"timezone": "Asia/Shanghai",
|
||||
"start": "21:00",
|
||||
"end": "08:00",
|
||||
"batch_window_enabled": true,
|
||||
"configuration_error": null,
|
||||
"batch_open": true,
|
||||
"next_batch_at": null,
|
||||
"close_behavior": "finish_current"
|
||||
}
|
||||
},
|
||||
"false": {
|
||||
"api_policy": {
|
||||
"timezone": "Asia/Shanghai",
|
||||
"start": "21:00",
|
||||
"end": "08:00",
|
||||
"batch_window_enabled": false,
|
||||
"configuration_error": null,
|
||||
"batch_open": true,
|
||||
"next_batch_at": null,
|
||||
"close_behavior": "finish_current"
|
||||
},
|
||||
"gpu_policy": {
|
||||
"timezone": "Asia/Shanghai",
|
||||
"start": "21:00",
|
||||
"end": "08:00",
|
||||
"batch_window_enabled": false,
|
||||
"configuration_error": null,
|
||||
"batch_open": true,
|
||||
"next_batch_at": null,
|
||||
"close_behavior": "finish_current"
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
qa/v3-workflow-desktop.png
Normal file
|
After Width: | Height: | Size: 240 KiB |
BIN
qa/v3-workflow-mobile-bottom.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
qa/v3-workflow-mobile.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
88
qa/v3_live_acceptance.py
Normal file
@ -0,0 +1,88 @@
|
||||
"""Live private-entry acceptance. Keys are stable; never prints login secrets."""
|
||||
import json,time
|
||||
from pathlib import Path
|
||||
import requests
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
ENV=dict(line.split('=',1) for line in (ROOT/'.env.server').read_text(encoding='utf-8-sig').splitlines() if line and not line.startswith('#') and '=' in line)
|
||||
BASE='http://127.0.0.1:8000/api'
|
||||
OUT=ROOT/'qa/v3-live.json'
|
||||
report={}
|
||||
def save():OUT.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
def login():
|
||||
client=requests.Session()
|
||||
response=client.post(BASE+'/auth/login',json={'username':ENV['ADMIN_USERNAME'],'password':ENV['ADMIN_PASSWORD']},timeout=15)
|
||||
assert response.status_code==200,('login',response.status_code)
|
||||
client.headers['X-CSRF-Token']=response.json()['csrf_token'];return client
|
||||
def accepted(client,route,body,key):
|
||||
r=client.post(BASE+route,json=body,headers={'Idempotency-Key':key},timeout=25)
|
||||
assert r.status_code==202,(route,r.status_code)
|
||||
return r.json()
|
||||
def wait_job(client,id,seconds=300):
|
||||
deadline=time.monotonic()+seconds
|
||||
while time.monotonic()<deadline:
|
||||
r=client.get(BASE+'/jobs/'+id,timeout=15);assert r.status_code==200
|
||||
job=r.json()
|
||||
if job['state'] in {'succeeded','failed','timed_out','cancelled','needs_attention'}:
|
||||
assert job['state']=='succeeded',(id,job['state'],job.get('error',{}).get('code') if job.get('error') else None)
|
||||
return job
|
||||
time.sleep(1)
|
||||
raise TimeoutError('Live job did not finish within acceptance deadline')
|
||||
|
||||
client=login()
|
||||
try:
|
||||
caps=client.get(BASE+'/capabilities',timeout=15).json()
|
||||
assert caps['execution_policy']['batch_window_enabled'] is False
|
||||
assert caps['execution_policy']['configuration_error'] is None
|
||||
assert caps['workflow_limits']['max_shots']==120
|
||||
report['execution_policy']=caps['execution_policy'];report['workflow_limits']=caps['workflow_limits']
|
||||
spec=json.loads((ROOT/'frontend/public/examples/kunpeng-storyboard.json').read_text(encoding='utf-8'))
|
||||
name='鲲鹏·20镜头100秒示例(未运行)'
|
||||
drafts=client.get(BASE+'/workflows',params={'page_size':100},timeout=15).json()['items']
|
||||
existing=next((d for d in drafts if d['name']==name),None)
|
||||
if existing:draft=existing
|
||||
else:
|
||||
r=client.post(BASE+'/workflows',json={'name':name,'kind':'multi_shot','spec':spec},timeout=15)
|
||||
assert r.status_code==201,('sample_draft',r.status_code);draft=r.json()
|
||||
assert len(draft['spec']['shots'])==20 and draft['spec']['render']['total_frames']==2400
|
||||
assert not draft['current_run_id']
|
||||
report['sample_draft_id']=draft['id'];report['sample_draft_not_run']=True;save()
|
||||
|
||||
old=client.get(BASE+'/workflow-runs/5e9108a5d1bc4f989e11ffe7bd7e7707',timeout=15).json()
|
||||
sources=[next(a for a in j['result_assets'] if a['kind']=='video')['id'] for j in sorted(old['jobs'],key=lambda j:j['step_key'] or '') if j['step_key'] in {'shot_1','shot_2','shot_3'}]
|
||||
assert len(sources)==3
|
||||
sources.append(sources[0])
|
||||
short={'schema_version':2,'shots':[{'key':f'shot_{i+1}','prompt':'已有验收素材复用合成','parameters':{'seed':42},'duration_frames':frames} for i,frames in enumerate([24,120,120,120])],'profile':'landscape_1080_v1','render':{'fps':24,'total_frames':384,'fit':'contain','audio':None,'subtitles':[{'start_frame':0,'end_frame':24,'text':'多镜头长视频验收'},{'start_frame':361,'end_frame':384,'text':'超过15秒'}],'template_version':'plain-v1'}}
|
||||
composition=accepted(client,'/jobs',{'task_type':'video.compose','input':{'asset_ids':sources},'parameters':{'workflow_spec':short,'clips':[{'asset_id':id} for id in sources]},'execution_mode':'batch'},'v3-live-16s-20261111')['jobs'][0]
|
||||
narration=(ROOT/'frontend/public/examples/kunpeng-narration.txt').read_text(encoding='utf-8').strip()
|
||||
voice=accepted(client,'/jobs',{'task_type':'audio.speech','input':{'prompt':narration},'parameters':{'voice':'zm_yunxi','speed':0.85},'execution_mode':'batch'},'v3-live-narration-20261111')['jobs'][0]
|
||||
batch=accepted(client,'/batches',{'name':'开发全天配置验收','items':[{'kind':'job','task_type':'math.solve','input':{'prompt':'只输出一个数字:7加8等于多少?'},'parameters':{'max_tokens':32,'enable_thinking':False}}]},'v3-live-policy-batch-20261111')
|
||||
report.update(composition_job_id=composition['id'],narration_job_id=voice['id'],math_batch_id=batch['batch']['id']);save()
|
||||
finally:client.close()
|
||||
|
||||
# Closing the original HTTP client leaves all three persistent tasks running.
|
||||
client=login()
|
||||
try:
|
||||
job=wait_job(client,report['composition_job_id'])
|
||||
result=job['result'];assert result['frames']==384 and result['duration_seconds']==16 and result['clip_count']==4,result
|
||||
asset=next(a for a in job['result_assets'] if a['kind']=='video')
|
||||
r=client.patch(BASE+'/assets/'+asset['id'],json={'name':'多镜头16秒开发验收.mp4','tags':['开发验收','多镜头']},timeout=10);assert r.status_code==200
|
||||
target=ROOT/'qa/generated/v3-long-video-16s.mp4';target.parent.mkdir(parents=True,exist_ok=True)
|
||||
r=client.get(BASE+f"/assets/{asset['id']}/content",timeout=60);assert r.status_code==200;target.write_bytes(r.content)
|
||||
report['composition']={'asset_id':asset['id'],'result':result,'bytes':len(r.content)};save()
|
||||
job=wait_job(client,report['narration_job_id'])
|
||||
asset=next(a for a in job['result_assets'] if a['kind']=='audio')
|
||||
r=client.patch(BASE+'/assets/'+asset['id'],json={'name':'鲲鹏完整旁白(开发验收).wav','tags':['鲲鹏','旁白','开发验收']},timeout=10);assert r.status_code==200
|
||||
report['narration']={'asset_id':asset['id'],'voice':'zm_yunxi','speed':0.85,'duration_seconds':asset['duration_seconds'],'bytes':asset['size_bytes'],'characters':len(narration)};save()
|
||||
deadline=time.monotonic()+60
|
||||
while time.monotonic()<deadline:
|
||||
batch=client.get(BASE+'/batches/'+report['math_batch_id'],timeout=15).json()
|
||||
if batch['batch']['state']=='succeeded':break
|
||||
time.sleep(1)
|
||||
assert batch['batch']['state']=='succeeded'
|
||||
math=client.get(BASE+'/jobs/'+batch['items'][0]['target_id'],timeout=15).json()
|
||||
assert '15' in json.dumps(math['result'],ensure_ascii=False)
|
||||
report['math_after_http_close']={'job_id':math['id'],'succeeded':True,'answer':math['result']}
|
||||
report['ready']=client.get(BASE+'/ready',timeout=15).json();assert all(report['ready']['checks'].values())
|
||||
save();print(json.dumps(report,ensure_ascii=True))
|
||||
finally:client.close()
|
||||
60
scripts/render_manuals.py
Normal file
@ -0,0 +1,60 @@
|
||||
from pathlib import Path
|
||||
import html,re
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
out=root/'frontend/public/help';out.mkdir(parents=True,exist_ok=True)
|
||||
def inline(value):
|
||||
value=html.escape(value)
|
||||
value=re.sub(r'`([^`]+)`',r'<code>\1</code>',value)
|
||||
value=re.sub(r'\*\*([^*]+)\*\*',r'<strong>\1</strong>',value)
|
||||
def link(m):
|
||||
dest=m[2]
|
||||
if dest=='操作手册_20261111.md':dest='manual.html'
|
||||
if dest=='鲲鹏长视频制作指南_20261111.md':dest='kunpeng.html'
|
||||
if not (dest.startswith('https://') or dest in ['manual.html','kunpeng.html']):return m[1]
|
||||
return '<a href="'+dest+'">'+m[1]+'</a>'
|
||||
return re.sub(r'\[([^]]+)\]\(([^)]+)\)',link,value)
|
||||
|
||||
css='''body{margin:0;background:#f4f7f9;color:#1e293b;font:16px/1.85 "Microsoft YaHei",system-ui,sans-serif}a{color:#09685b}header{background:#112b32;color:#edf7f4;padding:28px max(5vw,20px)}header a{color:#a9ecda;margin-right:22px}main{max-width:1320px;margin:auto;display:grid;grid-template-columns:245px minmax(0,1fr);gap:30px;padding:28px}aside{align-self:start;position:sticky;top:20px;font-size:13px;max-height:90vh;overflow:auto}aside a{display:block;margin:7px 0}article{min-width:0;background:white;padding:36px;border-radius:12px;box-shadow:0 5px 30px #1330360a}h1{font-size:30px;line-height:1.5}h2{font-size:23px;margin-top:38px;border-bottom:1px solid #dbe5e9;padding-bottom:12px;scroll-margin-top:15px}h3{font-size:19px;margin-top:28px}p,li{overflow-wrap:anywhere}li{margin-bottom:10px}code{font:14px/1.6 Consolas,monospace;background:#edf2f5;padding:2px 5px;border-radius:4px;overflow-wrap:anywhere}pre{background:#102731;color:#d9ece7;padding:20px;overflow:auto;border-radius:8px}pre code{background:none;color:inherit;padding:0}blockquote{border-left:4px solid #60ae9a;margin:20px 0;padding:12px 20px;background:#eff7f4}.table-scroll{overflow:auto}table{border-collapse:collapse;width:100%;font-size:14px}th,td{border:1px solid #dbe5e9;padding:10px 12px;text-align:left;min-width:95px;vertical-align:top}th{background:#edf4f3}footer{margin-top:35px;color:#64748b;font-size:13px}@media(max-width:800px){main{display:block;padding:14px}aside{position:static;max-height:none;margin-bottom:20px}article{padding:20px}h1{font-size:25px}body{font-size:15px}}@media print{header,aside{display:none}main{display:block;padding:0}article{box-shadow:none;padding:0}h2{break-after:avoid}table{font-size:10px}a{color:inherit}}'''
|
||||
|
||||
for source,target,title in [('操作手册_20261111.md','manual','操作手册'),('鲲鹏长视频制作指南_20261111.md','kunpeng','鲲鹏长视频制作指南')]:
|
||||
text=(root/'docs'/source).read_text(encoding='utf-8')
|
||||
(out/(target+'.md')).write_text(text,encoding='utf-8')
|
||||
lines=text.splitlines();parts=[];toc=[];i=0;seq=0;list_type=None
|
||||
def close_list():
|
||||
global list_type
|
||||
if list_type:parts.append('</'+list_type+'>');list_type=None
|
||||
while i<len(lines):
|
||||
s=lines[i]
|
||||
if s.startswith('```'):
|
||||
close_list();block=[];i+=1
|
||||
while i<len(lines) and not lines[i].startswith('```'):block.append(lines[i]);i+=1
|
||||
parts.append('<pre><code>'+html.escape('\n'.join(block))+'</code></pre>');i+=1;continue
|
||||
if s.startswith('|') and i+1<len(lines) and re.match(r'^\|[\s:|\-]+$',lines[i+1]):
|
||||
close_list();rows=[];j=i
|
||||
while j<len(lines) and lines[j].startswith('|'):
|
||||
if j!=i+1:rows.append([x.strip() for x in lines[j].strip('|').split('|')])
|
||||
j+=1
|
||||
parts.append('<div class="table-scroll"><table><thead><tr>'+''.join('<th>'+inline(c)+'</th>' for c in rows[0])+'</tr></thead><tbody>')
|
||||
for row in rows[1:]:parts.append('<tr>'+''.join('<td>'+inline(c)+'</td>' for c in row)+'</tr>')
|
||||
parts.append('</tbody></table></div>');i=j;continue
|
||||
heading=re.match(r'^(#{1,4}) (.+)$',s)
|
||||
if heading:
|
||||
close_list();level=len(heading[1]);seq+=1;key=f'section-{seq}'
|
||||
parts.append(f'<h{level} id="{key}">'+inline(heading[2])+f'</h{level}>')
|
||||
if level==2:toc.append(f'<a href="#{key}">'+inline(heading[2])+'</a>')
|
||||
elif s.startswith('> '):close_list();parts.append('<blockquote>'+inline(s[2:])+'</blockquote>')
|
||||
else:
|
||||
item=re.match(r'^(?:([-]) |(\d+)\. )(.+)$',s)
|
||||
if item:
|
||||
kind='ul' if item[1] else 'ol'
|
||||
if list_type!=kind:close_list();parts.append('<'+kind+'>');list_type=kind
|
||||
parts.append('<li>'+inline(item[3])+'</li>')
|
||||
else:
|
||||
close_list()
|
||||
if s.strip():parts.append('<p>'+inline(s)+'</p>')
|
||||
i+=1
|
||||
close_list()
|
||||
page='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+title+' · CMVR Visual</title><style>'+css+'</style></head><body><header><strong>CMVR Visual · 使用帮助</strong><nav><a href="/workflow">返回工作流</a><a href="manual.html">操作手册</a><a href="kunpeng.html">鲲鹏制作步骤</a><a href="'+target+'.md" download>下载Markdown</a><a href="/examples/kunpeng-storyboard.json" download>下载100秒分镜</a><a href="/examples/kunpeng-storyboard-45s.json" download>下载45秒分镜</a></nav></header><main><aside><strong>目录</strong>'+''.join(toc)+'</aside><article>'+''.join(parts)+'<footer>版本:2026-11-11 · 文档随本项目发布。浏览器可打印为PDF。</footer></article></main></body></html>'
|
||||
(out/(target+'.html')).write_text(page,encoding='utf-8')
|
||||
print('Generated 2 HTML manuals with Markdown downloads')
|
||||