cmvr-visual/backend/app/adapters/provider/qwen.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

200 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""共享 Qwen 的文本、图片与视频抽帧理解适配。"""
from __future__ import annotations
import asyncio
import base64
from io import BytesIO
import json
import math
import re
from PIL import Image, ImageOps
from app.adapters.media import input_options, inspect_media, run_process
from app.domain.execution import CpuResult, enter_phase
from app.domain.errors import MediaError as ProviderError
from .contracts import _invalid, _keys, _int, _string
from .transport import _url
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .client import Provider
async def _chat(provider: Provider, messages, *, max_tokens=2048, thinking=False):
# 取消只影响当前等待;常驻网关负责并发引用计数、排空和模型释放。
if not provider.settings.qwen_model:
raise ProviderError("capability_unavailable", "文本与视觉服务尚未配置。")
value = await provider._json(
"POST",
_url(provider.settings.qwen_base_url, "/chat/completions"),
headers=provider._headers("qwen"),
timeout=getattr(provider.settings, "qwen_timeout_seconds", 1800.0),
payload={
"model": provider.settings.qwen_model,
"messages": messages,
"stream": False,
"temperature": 0,
"max_tokens": max_tokens,
"chat_template_kwargs": {"enable_thinking": thinking},
},
)
choices = value.get("choices")
if (
isinstance(choices, list)
and choices
and isinstance(choices[0], dict)
and choices[0].get("finish_reason") == "length"
):
raise ProviderError(
"output_truncated",
"模型输出达到长度上限,内容不完整;请提高输出长度或简化要求后重新提交。",
)
try:
content = value["choices"][0]["message"]["content"]
if isinstance(content, list):
content = "".join(part["text"] for part in content if part.get("type") == "text")
content = _string(content, 200_000)
inline = re.fullmatch(r"\s*<think>.*?</think>\s*(.*)", content, flags=re.DOTALL)
if inline:
content = inline.group(1).strip()
if not content:
raise ValueError
return content
except (ValueError, TypeError, KeyError, IndexError, AttributeError, ProviderError):
raise ProviderError(
"invalid_upstream_response", "文本服务没有返回有效内容。", True
) from None
async def _image_uri(provider: Provider, source):
def encode():
with Image.open(source) as image:
image = ImageOps.exif_transpose(image).convert("RGB")
image.thumbnail((1280, 1280))
buffer = BytesIO()
image.save(buffer, format="JPEG", quality=85)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
return await asyncio.to_thread(encode)
async def _structure(provider: Provider, inputs, p, assets, work):
_keys(inputs, {"asset_id", "image_asset_id"})
_keys(p, {"frame_count"})
asset_id = inputs.get("asset_id") or inputs.get("image_asset_id")
if (
inputs.get("asset_id")
and inputs.get("image_asset_id")
and inputs["asset_id"] != inputs["image_asset_id"]
):
raise _invalid("请选择一个待理解素材。")
count = _int(p.get("frame_count", 6), 1, 12)
source = provider._asset(asset_id, assets)
info = await inspect_media(source, provider.settings)
if info["kind"] not in {"image", "video"}:
raise _invalid("素材理解支持图片或视频。")
samples, outputs = [(0.0, source)], []
if info["kind"] == "video":
await enter_phase("sample_frames", "cpu_media")
samples = []
for index in range(count):
timestamp = (index + 0.5) * info["duration_seconds"] / count
frame = work / f"frame-{index:03d}.jpg"
# 只使用固定滤镜与数值时间,不允许用户输入 FFmpeg 滤镜或协议。
_, diagnostics = await run_process(
[
provider.settings.ffmpeg_bin,
"-v",
"info",
"-nostdin",
"-copyts",
*input_options(),
"-ss",
f"{timestamp:.6f}",
"-i",
str(source),
"-frames:v",
"1",
"-vf",
"scale=1280:1280:force_original_aspect_ratio=decrease,showinfo",
"-threads",
"2",
str(frame),
],
timeout=90,
return_stderr=True,
)
if not frame.is_file() or not frame.stat().st_size:
raise ProviderError("frame_extraction_failed", "视频抽帧失败。")
actual_pts = re.search(rb"\bpts_time:([+-]?[0-9]+(?:\.[0-9]+)?)", diagnostics)
if actual_pts is None:
raise ProviderError("frame_extraction_failed", "无法确认抽帧的实际时间。")
actual_time = float(actual_pts.group(1)) - info.get("start_seconds", 0)
if (
not math.isfinite(actual_time)
or not -0.1 <= actual_time <= info["duration_seconds"] + 0.1
):
raise ProviderError("frame_extraction_failed", "抽帧时间超出素材范围。")
samples.append((max(0, actual_time), frame))
outputs.append(frame)
frames = []
prompt = (
"仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串,"
"ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。"
)
for index, (timestamp, frame) in enumerate(samples):
image_uri = await provider._image_uri(frame)
await enter_phase(f"describe_frame_{index}", "qwen_http")
text = await provider._chat(
[
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": image_uri}},
{"type": "text", "text": prompt},
],
}
]
)
try:
fenced = re.fullmatch(
r"\s*```(?:json)?\s*(.*?)\s*```\s*", text, flags=re.DOTALL | re.IGNORECASE
)
value = json.loads(fenced.group(1) if fenced else text)
scene = _string(value["scene"], 2000, required=False)
normalized = {}
for key in ("subjects", "ocr", "tags"):
items = value.get(key, []) if key == "tags" else value[key]
if not isinstance(items, list) or len(items) > 100:
raise ValueError
normalized[key] = list(
dict.fromkeys(_string(item, 2000, required=False) for item in items)
)
frames.append({"timestamp_seconds": round(timestamp, 6), "scene": scene, **normalized})
except (ValueError, KeyError, TypeError, AttributeError, ProviderError):
raise ProviderError(
"invalid_visual_response", "视觉服务未返回有效的结构化内容。", True
) from None
result = {
"subjects": list(dict.fromkeys(item for frame in frames for item in frame["subjects"])),
"scene": ";".join(dict.fromkeys(frame["scene"] for frame in frames)),
"ocr": list(dict.fromkeys(item for frame in frames for item in frame["ocr"])),
"tags": list(dict.fromkeys(item for frame in frames for item in frame["tags"])),
"frames": frames,
}
outputs.append(provider._json_file(work, "structure.json", result))
return CpuResult(
outputs,
result,
{
"provider": "qwen",
"model": provider.settings.qwen_model,
"sampling": "uniform seek" if info["kind"] == "video" else "single image",
"timestamp_precision": "decoded frame PTS relative to source start",
"frame_count": len(frames),
},
)