hit-cxf
2026-05-08 960bb1b488906eac16b62d81256edd112e3454fb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import json
import logging
import os
import re
 
from models.llm_client import LLM
from prompts.loader import format_prompt, load_prompt
 
from .api_media import generate_image_api, generate_video_api
from .storage import append_artifact, task_output_dir, update_task
from .tts import generate_edge_tts
from .utils import (
    artifact,
    concat_videos,
    create_static_image_clip,
    media_duration_seconds,
    render_static_text_image,
    replace_video_audio,
    run_blocking,
    write_json,
    write_text,
)
 
DEFAULT_STYLE_CONTROL = (
    "Minimalist black-and-white matchstick figure style illustration, clean lines, simple sketch style"
)
 
logger = logging.getLogger(__name__)
 
 
def required_param(params: dict, key: str) -> str:
    value = params.get(key)
    if not value:
        raise ValueError(f"standard pipeline requires {key}")
    return str(value)
 
 
def split_by_periods(text: str) -> list[str]:
    parts = re.findall(r"[^。..]+[。..]?|[^。..]+$", text.strip())
    return [part.strip() for part in parts if part.strip()]
 
 
def clamp_segment_count(value, default: int = 6) -> int:
    try:
        count = int(value)
    except (TypeError, ValueError):
        count = default
    return max(1, min(20, count))
 
 
def parse_json_object_response(text: str) -> dict:
    response = text.strip()
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", response, re.S)
        if not match:
            match = re.search(r"(\{.*\})", response, re.S)
        if not match:
            raise ValueError("Model response did not contain a JSON object.")
        return json.loads(match.group(1))
 
 
def parse_narrations_response(text: str, expected_count: int) -> list[str]:
    data = parse_json_object_response(text)
    narrations = data.get("narrations") if isinstance(data, dict) else None
    if not isinstance(narrations, list):
        raise ValueError("Model response missing narrations array.")
 
    segments = [str(item).strip() for item in narrations if str(item).strip()]
    if len(segments) != expected_count:
        raise ValueError(f"Expected {expected_count} narrations, got {len(segments)}.")
    return segments
 
 
def parse_image_prompts_response(text: str, expected_count: int) -> list[str]:
    data = parse_json_object_response(text)
 
    prompts = data.get("image_prompts") if isinstance(data, dict) else None
    if not isinstance(prompts, list):
        raise ValueError("Model response missing image_prompts array.")
 
    image_prompts = [str(prompt).strip() for prompt in prompts if str(prompt).strip()]
    if len(image_prompts) != expected_count:
        raise ValueError(
            f"Expected {expected_count} image prompts, got {len(image_prompts)}."
        )
    return image_prompts
 
 
def build_image_prompt(visual_prompt: str, style_control: str) -> str:
    style = style_control.strip()
    no_text_instruction = (
        "Do not include any text, captions, logos, watermarks, labels, typography, "
        "or written characters in the image."
    )
    if not style:
        return f"{no_text_instruction}\n{visual_prompt}"
    return f"{style}\n{no_text_instruction}\n{visual_prompt}"
 
 
async def generate_image_prompts(
    narrations: list[str],
    style_control: str,
    llm: LLM,
    llm_model: str,
) -> list[str]:
    template = load_prompt("pipelines", "standard_image_prompt_generation", "en")
    prompt = format_prompt(
        template,
        narrations_count=len(narrations),
        narrations_json=json.dumps({"narrations": narrations}, ensure_ascii=False, indent=2),
    )
    response = await run_blocking(llm.query, prompt, model=llm_model)
    visual_prompts = parse_image_prompts_response(response, len(narrations))
    return [build_image_prompt(visual_prompt, style_control) for visual_prompt in visual_prompts]
 
 
async def generate_narrations_from_inspiration(
    inspiration: str,
    segment_count: int,
    llm: LLM,
    llm_model: str,
) -> list[str]:
    template = load_prompt("pipelines", "standard_narration_generation", "zh")
    prompt = format_prompt(
        template,
        inspiration=inspiration,
        segment_count=segment_count,
    )
    response = await run_blocking(llm.query, prompt, model=llm_model)
    return parse_narrations_response(response, segment_count)
 
 
async def run(task_id: str, params: dict) -> tuple[dict, list[dict]]:
    output_dir = task_output_dir(task_id)
    os.makedirs(output_dir, exist_ok=True)
 
    text = params.get("text") or params.get("topic") or ""
    if not text.strip():
        raise ValueError("standard pipeline requires narration text")
 
    mode = params.get("mode") or "copy"
    source_text = text.strip()
    llm = None
    llm_model = required_param(params, "llm_model")
    if mode == "inspiration":
        segment_count = clamp_segment_count(params.get("segment_count"))
        update_task(task_id, progress=6, message="Writing narration from inspiration")
        llm = LLM()
        narrations = await generate_narrations_from_inspiration(
            source_text,
            segment_count,
            llm,
            llm_model,
        )
        source_text = "\n".join(narrations)
    else:
        narrations = split_by_periods(source_text)
 
    if not narrations:
        raise RuntimeError("No narration segments were generated.")
 
    title = (params.get("title") or "").strip()
    if not title:
        update_task(task_id, progress=8, message="Generating title")
        if llm is None:
            llm = LLM()
        title = await run_blocking(
            llm.query,
            f"为下面的文艺短视频旁白生成一个简短中文标题,只输出标题:\n{source_text}",
            model=llm_model,
        )
        title = title.strip().splitlines()[0]
 
    style_control = (params.get("style_control") or params.get("negative_prompt") or DEFAULT_STYLE_CONTROL).strip()
    video_ratio = params.get("video_ratio") or "9:16"
    image_model = params.get("image_model") or params.get("image_workflow")
    if not image_model:
        raise ValueError("standard pipeline requires image_model")
    image_resolution = params.get("image_resolution") or "1080P"
    enable_subtitles = bool(params.get("enable_subtitles", False))
    video_mode = params.get("video_mode") or "image_concat"
    dynamic_video = video_mode == "dynamic_video" or bool(params.get("generate_videos", False))
    video_model = params.get("video_model")
    if dynamic_video and not video_model:
        raise ValueError("standard pipeline dynamic_video mode requires video_model")
    video_duration = clamp_segment_count(params.get("video_duration") or params.get("duration") or 5, default=5)
 
    update_task(task_id, progress=9, message="Generating image prompts")
    if llm is None:
        llm = LLM()
    try:
        image_prompts = await generate_image_prompts(narrations, style_control, llm, llm_model)
    except Exception as exc:
        logger.warning(
            "Failed to generate structured image prompts, fallback to narration prompts: task_id=%s error=%s",
            task_id,
            exc,
        )
        image_prompts = [build_image_prompt(narration, style_control) for narration in narrations]
 
    storyboard = {
        "title": title,
        "mode": mode,
        "input_text": text,
        "segment_count": len(narrations),
        "video_mode": "dynamic_video" if dynamic_video else "image_concat",
        "style_control": style_control,
        "frames": [
            {"index": idx + 1, "narration": narration, "image_prompt": image_prompts[idx]}
            for idx, narration in enumerate(narrations)
        ],
    }
    storyboard_path = write_json(os.path.join(output_dir, "storyboard.json"), storyboard)
    narration_path = write_text(os.path.join(output_dir, "narration.txt"), "\n".join(narrations))
 
    artifacts = [artifact(storyboard_path, "text", "storyboard"), artifact(narration_path, "text", "narration")]
    for item in artifacts:
        append_artifact(task_id, item)
 
    images = []
    for idx, prompt in enumerate(image_prompts, 1):
        update_task(
            task_id,
            progress=10 + int(40 * idx / len(image_prompts)),
            message=f"Generating image {idx}/{len(image_prompts)}",
        )
        image_path = await run_blocking(
            generate_image_api,
            prompt=prompt,
            model=image_model,
            output_dir=output_dir,
            task_id=task_id,
            video_ratio=video_ratio,
            resolution=image_resolution,
        )
        images.append(image_path)
        image_artifact = artifact(image_path, "image", f"image_{idx:02d}")
        artifacts.append(image_artifact)
        append_artifact(task_id, image_artifact)
        storyboard["frames"][idx - 1]["image_path"] = image_path
        write_json(storyboard_path, storyboard)
 
    audios = []
    for idx, narration in enumerate(narrations, 1):
        update_task(
            task_id,
            progress=50 + int(20 * idx / len(narrations)),
            message=f"Generating audio {idx}/{len(narrations)}",
        )
        audio_path = os.path.join(output_dir, f"audio_{idx:02d}.mp3")
        await generate_edge_tts(
            narration,
            output_path=audio_path,
            voice=params.get("tts_voice", "zh-CN-YunjianNeural"),
            speed=float(params.get("tts_speed", 1.2)),
        )
        audios.append(audio_path)
        audio_artifact = artifact(audio_path, "audio", f"audio_{idx:02d}")
        artifacts.append(audio_artifact)
        append_artifact(task_id, audio_artifact)
        storyboard["frames"][idx - 1]["audio_path"] = audio_path
        write_json(storyboard_path, storyboard)
 
    videos = []
    for idx, (image_path, audio_path) in enumerate(zip(images, audios), 1):
        update_task(
            task_id,
            progress=70 + int(20 * idx / len(images)),
            message=f"{'Generating dynamic video' if dynamic_video else 'Creating static clip'} {idx}/{len(images)}",
        )
        duration = media_duration_seconds(audio_path) or 3.0
        clip_image_path = image_path
        if enable_subtitles:
            captioned_image_path = os.path.join(output_dir, f"captioned_image_{idx:02d}.jpg")
            clip_image_path = await run_blocking(
                render_static_text_image,
                image_path,
                captioned_image_path,
                subtitle=narrations[idx - 1],
                title=title or None,
                video_ratio=video_ratio,
            )
            captioned_artifact = artifact(clip_image_path, "image", f"captioned_image_{idx:02d}")
            artifacts.append(captioned_artifact)
            append_artifact(task_id, captioned_artifact)
            storyboard["frames"][idx - 1]["captioned_image_path"] = clip_image_path
        video_path = os.path.join(output_dir, f"video_{idx:02d}.mp4")
        if dynamic_video:
            video_only_segment_path = os.path.join(output_dir, f"video_{idx:02d}_motion.mp4")
            await run_blocking(
                generate_video_api,
                prompt=image_prompts[idx - 1],
                model=video_model,
                output_path=video_only_segment_path,
                image_path=clip_image_path,
                duration=max(video_duration, int(duration + 0.999)),
                video_ratio=video_ratio,
            )
            motion_artifact = artifact(video_only_segment_path, "video", f"video_{idx:02d}_motion")
            artifacts.append(motion_artifact)
            append_artifact(task_id, motion_artifact)
            storyboard["frames"][idx - 1]["motion_video_path"] = video_only_segment_path
            video_path = await run_blocking(
                replace_video_audio,
                video_only_segment_path,
                audio_path,
                video_path,
            )
        else:
            await run_blocking(
                create_static_image_clip,
                clip_image_path,
                audio_path,
                video_path,
                video_ratio=video_ratio,
                duration=duration,
            )
        videos.append(video_path)
        video_artifact = artifact(video_path, "video", f"video_{idx:02d}")
        artifacts.append(video_artifact)
        append_artifact(task_id, video_artifact)
        storyboard["frames"][idx - 1]["video_path"] = video_path
        storyboard["frames"][idx - 1]["duration"] = duration
        write_json(storyboard_path, storyboard)
 
    video_only_path = None
    video_only_path = concat_videos(videos, os.path.join(output_dir, "final.mp4"))
    if not video_only_path:
        raise RuntimeError("Static short-video generation did not produce a final video.")
 
    final_path = video_only_path
 
    final_artifact = artifact(final_path, "video", "final")
    artifacts.append(final_artifact)
    append_artifact(task_id, final_artifact)
 
    write_json(storyboard_path, storyboard)
    output = {
        "title": title,
        "storyboard_path": storyboard_path,
        "narration_path": narration_path,
        "images": images,
        "audios": audios,
        "videos": videos,
        "video_mode": "dynamic_video" if dynamic_video else "image_concat",
        "video_model": video_model if dynamic_video else None,
        "video_only_path": video_only_path,
        "final_video": final_path,
    }
    return output, artifacts