cmvr-visual/backend/app/providers.py

776 lines
45 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.

"""Database-independent adapters for deployed GPU jobs, text/vision and CPU media."""
from __future__ import annotations
import asyncio
import base64
from dataclasses import dataclass
from datetime import datetime, timezone
import html
from io import BytesIO
import json
import math
import os
from pathlib import Path
import re
import stat
import time
from urllib.parse import urlsplit
import uuid
import httpx
from PIL import Image, ImageOps
from .media import MediaError as ProviderError, confined, input_options, inspect_media, run_process
GPU_TASKS = {'image.generate', 'video.generate', 'defect.generate', 'audio.transcribe'}
LANGUAGES = ['zh', 'en', 'ja', 'ko', 'de', 'fr', 'es', 'ru', 'ar', 'pt', 'it', 'auto']
_UUID = re.compile(r'GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z')
@dataclass
class CpuResult:
outputs: list[Path]
result: dict
metadata: dict
def _invalid(message='任务输入或参数无效。'):
return ProviderError('invalid_input', message)
def _keys(value, allowed):
if not isinstance(value, dict) or set(value) - set(allowed):
raise _invalid('包含不支持的输入或参数。')
def _int(value, low, high, step=1):
if type(value) is not int or not low <= value <= high or value % step:
raise _invalid('整数参数超出范围或步长不正确。')
return value
def _float(value, low, high):
if isinstance(value, bool) or not isinstance(value, (float, int)):
raise _invalid('数值参数无效。')
try:
normalized = float(value)
except (ValueError, OverflowError):
raise _invalid('数值参数无效。') from None
if not math.isfinite(normalized) or not low <= normalized <= high:
raise _invalid('数值参数超出范围。')
return normalized
def _string(value, maximum=8000, *, required=True):
if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()):
raise _invalid('文字内容为空或超出长度限制。')
return value
def _voices(settings):
values = getattr(settings, 'tts_voices', ['zf_xiaobei', 'zm_yunxi'])
if isinstance(values, str):
values = [item.strip() for item in values.split(',') if item.strip()]
return [value for value in values if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,64}', value)]
def capabilities(settings) -> list[dict]:
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},
'num_inference_steps': {'min': 1, 'max': 100},
'guidance_scale': {'min': 1, 'max': 20}, 'seed': {'min': 0, 'max': 2**32 - 1},
'count': {'min': 1, 'max': 4}, 'max_pixels': 2048 * 2048}
video_defaults = dict(image_defaults, width=1280, height=704, guidance_scale=5.0,
num_frames=121, fps=24, upscale=True, upscale_width=1920, upscale_height=1080, tile_size=128)
video_limits = {**image_limits, 'width': {'min': 256, 'max': 1280, 'step': 32},
'height': {'min': 256, 'max': 1280, 'step': 32}, 'max_pixels': 1280 * 704,
'count': {'min': 1, 'max': 1}, 'num_frames': {'min': 5, 'max': 121, 'step': 4},
'fps': {'values': [24]}, 'upscale': {'values': [True, False]},
'upscale_width': {'min': 256, 'max': 3840, 'step': 2},
'upscale_height': {'min': 256, 'max': 2160, 'step': 2}, 'tile_size': {'min': 64, 'max': 256, 'step': 16}}
configured = bool(getattr(settings, 'inference_base_url', ''))
qwen = bool(getattr(settings, 'qwen_base_url', '') and getattr(settings, 'qwen_model', ''))
speech = bool(getattr(settings, 'tts_base_url', '') and getattr(settings, 'tts_model', '') and _voices(settings))
def item(task_type, label, model, available, types, defaults, constraints, description):
return dict(task_type=task_type, label=label, model=model, available=available,
input_types=types, defaults=defaults, constraints=constraints, description=description)
return [
item('image.generate', '图像生成', 'Qwen-Image', configured, ['text'], image_defaults, image_limits,
'文字生成图片;不包含图像编辑或风格 LoRA 管理。'),
item('video.generate', '视频生成', 'Wan2.2-TI2V-5B + Real-ESRGAN', configured, ['text', 'image'],
video_defaults, video_limits, '最多121帧、24fps,约5秒无声视频;可选1080p增强。'),
item('defect.generate', '条件样本生成', 'SDXL + Canny ControlNet', configured, ['text', 'image'],
dict(image_defaults, guidance_scale=7.5, controlnet_conditioning_scale=.8, canny_low=100, canny_high=200),
{**image_limits, 'controlnet_conditioning_scale': {'min': 0, 'max': 2},
'canny_low': {'min': 0, 'max': 255}, 'canny_high': {'min': 0, 'max': 255}},
'参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。'),
item('audio.transcribe', '语音转写', 'Whisper-large-v3-turbo', configured, ['audio', 'video'],
{'language': 'zh', 'max_audio_seconds': 1800},
{'language': {'values': LANGUAGES}, 'max_audio_seconds': {'min': 1, 'max': 1800}},
'支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。'),
item('math.solve', '数学推演', getattr(settings, 'qwen_model', ''), qwen, ['text'],
{'max_tokens': 2048, 'enable_thinking': False}, {'max_tokens': {'min': 1, 'max': 4096}},
'调用现有文本服务给出解答,未集成形式化证明或准确率评测。'),
item('media.structure', '素材理解', getattr(settings, 'qwen_model', ''), qwen, ['image', 'video'],
{'frame_count': 6}, {'frame_count': {'min': 1, 'max': 12}},
'视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。'),
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}},
'按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'),
item('audio.speech', '中文配音', getattr(settings, 'tts_model', '') or '尚未配置', speech, ['text'],
{'voice': (_voices(settings) or [''])[0], 'speed': 1.0},
{'voice': {'values': _voices(settings)}, 'speed': {'min': .5, 'max': 2}, 'text': {'max': 2000}},
'仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。'),
]
def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None:
"""Pure submission validation: no HTTP, file decoding, mkdir or model work."""
p = parameters
if task_type in GPU_TASKS:
allowed = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'}
if task_type in {'video.generate', 'defect.generate'}:
allowed.add('image_asset_id')
_keys(inputs, allowed)
defaults = next(item['defaults'] for item in capabilities(settings) if item['task_type'] == task_type)
_keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set()))
p = {**defaults, **p}
if task_type == 'audio.transcribe':
if not (inputs.get('audio_asset_id') or inputs.get('asset_id')):
raise _invalid('请选择转写素材。')
if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']:
raise _invalid('请仅选择一个转写素材。')
if p['language'] not in LANGUAGES:
raise _invalid('不支持此转写语言。')
_int(p['max_audio_seconds'], 1, 1800)
return
_string(inputs.get('prompt'))
_string(inputs.get('negative_prompt', ''), required=False)
if 'negative_prompt' in p:
_string(p['negative_prompt'], required=False)
video = task_type == 'video.generate'
for key in ('width', 'height'):
_int(p[key], 256, 1280 if video else 2048, 32 if video else 16)
if p['width'] * p['height'] > (1280 * 704 if video else 2048 * 2048):
raise _invalid('画面像素总数超出服务限制。')
_int(p['num_inference_steps'], 1, 100)
_int(p['seed'], 0, 2**32 - 1)
_float(p['guidance_scale'], 1, 20)
if task_type == 'defect.generate':
if not inputs.get('image_asset_id'):
raise _invalid('条件样本任务需要参考图片。')
_float(p['controlnet_conditioning_scale'], 0, 2)
_int(p['canny_low'], 0, 255)
_int(p['canny_high'], 0, 255)
if p['canny_low'] >= p['canny_high']:
raise _invalid('Canny低阈值必须小于高阈值。')
if video:
_int(p['num_frames'], 5, 121)
if p['num_frames'] % 4 != 1 or type(p['fps']) is not int or p['fps'] != 24 or type(p['upscale']) is not bool:
raise _invalid('视频帧数、帧率或增强开关无效。')
_int(p['upscale_width'], 256, 3840, 2)
_int(p['upscale_height'], 256, 2160, 2)
_int(p['tile_size'], 64, 256, 16)
return
if task_type == 'math.solve':
_keys(inputs, {'prompt'})
_keys(p, {'max_tokens', 'enable_thinking'})
_string(inputs.get('prompt'))
_int(p.get('max_tokens', 2048), 1, 4096)
if type(p.get('enable_thinking', False)) is not bool:
raise _invalid('思考开关必须为布尔值。')
return
if task_type == 'media.structure':
_keys(inputs, {'asset_id', 'image_asset_id'})
_keys(p, {'frame_count'})
if not (inputs.get('asset_id') or inputs.get('image_asset_id')):
raise _invalid('请选择待理解素材。')
if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']:
raise _invalid('请选择一个待理解素材。')
_int(p.get('frame_count', 6), 1, 12)
return
if task_type == 'audio.speech':
_keys(inputs, {'prompt'})
_keys(p, {'voice', 'speed'})
_string(inputs.get('prompt'), 2000)
voices = _voices(settings)
if not voices or p.get('voice', voices[0]) not in voices:
raise _invalid('请选择已配置的中文音色。')
_float(p.get('speed', 1), .5, 2)
return
if task_type == 'video.compose':
_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个视频片段。')
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:
raise _invalid('片段结束时间必须大于开始时间。')
if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]:
raise _invalid('素材顺序应与编排片段一致。')
if inputs.get('audio_asset_id') and p.get('audio_asset_id') and inputs['audio_asset_id'] != p['audio_asset_id']:
raise _invalid('请只选择一个成片音轨。')
_int(p.get('width', 1280), 256, 3840, 2)
_int(p.get('height', 720), 256, 2160, 2)
if type(p.get('fps', 24)) is not int or p.get('fps', 24) not in {24, 25, 30, 60}:
raise _invalid('不支持此成片帧率。')
cues = p.get('subtitles', [])
if not isinstance(cues, list) or len(cues) > 1000:
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)
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控制语法。')
return
raise _invalid('不支持此任务类型。')
def _read_key(path):
descriptor = None
try:
path = Path(path)
if not path.is_absolute() or path.is_symlink():
raise ValueError
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or (os.name == 'posix' and info.st_mode & 0o022):
raise ValueError
raw = os.read(descriptor, 4097)
value = raw.decode('utf-8').strip()
if not value or len(raw) > 4096 or '\n' in value or '\r' in value:
raise ValueError
return value
except (OSError, ValueError, UnicodeError):
raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) from None
finally:
if descriptor is not None:
os.close(descriptor)
def _url(base, suffix):
if not isinstance(base, str) or not base:
raise ProviderError('capability_unavailable', '此能力尚未配置。')
parsed = urlsplit(base)
if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ProviderError('provider_not_configured', '模型服务地址配置无效。', True)
return base.rstrip('/') + suffix
class Provider:
def __init__(self, settings):
self.settings = settings
self.client = httpx.AsyncClient(trust_env=False, follow_redirects=False,
timeout=httpx.Timeout(float(settings.request_timeout_seconds)),
limits=httpx.Limits(max_connections=4, max_keepalive_connections=2))
async def aclose(self):
await self.client.aclose()
def _headers(self, family='inference'):
key = getattr(self.settings, family + '_api_key', '') or ''
if family == 'inference' and getattr(self.settings, 'inference_api_key_file', None):
key = _read_key(self.settings.inference_api_key_file)
if not isinstance(key, str) or len(key) > 4096 or any(not 32 <= ord(char) <= 126 for char in key):
raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True)
return {'Authorization': 'Bearer ' + key} if key else {}
@staticmethod
def _http_error(status):
if status in {400, 413, 415, 422}:
return ProviderError('upstream_rejected', '模型服务拒绝了任务输入或参数。')
if status == 404:
return ProviderError('upstream_not_found', '模型服务未找到请求的任务或结果。', True)
if status == 409:
return ProviderError('upstream_conflict', '模型任务或幂等请求发生冲突。')
return ProviderError('upstream_unavailable', '模型服务暂时不可用。', True)
async def _json(self, method, url, *, payload=None, headers=None):
try:
async with asyncio.timeout(float(self.settings.request_timeout_seconds) + 1):
async with self.client.stream(method, url, json=payload, headers=headers) as response:
if not 200 <= response.status_code < 300:
raise self._http_error(response.status_code)
data, size = [], 0
async for chunk in response.aiter_bytes():
size += len(chunk)
if size > 2 * 1024 * 1024:
raise ProviderError('invalid_upstream_response', '模型服务响应超出限制。', True)
data.append(chunk)
value = json.loads(b''.join(data))
if not isinstance(value, dict):
raise ValueError
return value
except (httpx.HTTPError, asyncio.TimeoutError):
raise ProviderError('upstream_unavailable', '模型服务连接失败或响应超时。', True) from None
except (ValueError, UnicodeError, RecursionError):
raise ProviderError('invalid_upstream_response', '模型服务返回了无效响应。', True) from None
async def health(self):
try:
value = await self._json('GET', _url(self.settings.inference_base_url, '/health'), headers=self._headers())
return value.get('status') == 'ok'
except ProviderError:
return False
async def scheduler_status(self):
unavailable = {'available': False, 'state': 'unavailable', 'reason': 'GPU状态暂时不可用。', 'gpus': [], 'updated_at': None}
try:
path = Path(self.settings.gpu_status_path)
if path.stat().st_size > 1024 * 1024:
return unavailable
data = json.loads(path.read_bytes())
now = time.time()
generated = _float(data['generated_at'], 0, now + 1)
if data['schema_version'] != 1 or data.get('error') is not None or now - generated > 5:
return unavailable
seen, gpus = set(), []
for gpu in data['gpus']:
index = _int(gpu['index'], 0, 1024)
if index in seen or not isinstance(gpu['uuid'], str) or not _UUID.fullmatch(gpu['uuid']):
return unavailable
seen.add(index)
total = _float(gpu['total_gib'], .001, 100000)
free = _float(gpu['free_gib'], 0, total)
external, own = gpu['external_pids'], gpu['own_pids']
if not all(isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values)
for values in (external, own)):
return unavailable
idle = gpu.get('idle_since')
if idle is not None:
idle = _float(idle, 0, now + 1)
busy = bool(external or own)
gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy,
'eligible': not busy and free >= 76 and idle is not None and now - idle >= 15, 'free_gib': free})
state = 'ready' if any(gpu['eligible'] for gpu in gpus) else 'waiting'
reason = None if state == 'ready' else '等待可用GPU,外部任务优先。'
try:
scheduler_path = Path(self.settings.gpu_scheduler_path)
if scheduler_path.stat().st_size <= 1024 * 1024:
scheduler = json.loads(scheduler_path.read_bytes())
if scheduler.get('state') in {'blocked', 'preempting'}:
state = scheduler['state']
reason = '正在释放GPU并等待重新排队。' if state == 'preempting' else '执行器需要管理员检查。'
elif scheduler.get('state') == 'leased' and any(gpu['busy'] for gpu in gpus):
state, reason = 'running', '模型任务正在执行。'
except (OSError, ValueError, TypeError, AttributeError):
pass
return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus,
'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()}
except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
return unavailable
def _work(self, path):
work = confined(path, self.settings, exists=False, root=self.settings.job_work_root)
if not work.is_dir():
raise _invalid('任务工作目录不可用。')
return work
def _asset(self, asset_id, assets):
if not isinstance(asset_id, str) or asset_id not in assets:
raise _invalid('请选择可访问的素材。')
return confined(assets[asset_id], self.settings)
async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir):
validate_arguments(task_type, inputs, parameters, self.settings)
work = self._work(work_dir)
if task_type not in GPU_TASKS:
raise _invalid('不支持此模型任务类型。')
p = dict(parameters) if isinstance(parameters, dict) else parameters
allowed_input = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'}
if task_type in {'video.generate', 'defect.generate'}:
allowed_input.add('image_asset_id')
_keys(inputs, allowed_input)
defaults = next(item['defaults'] for item in capabilities(self.settings) if item['task_type'] == task_type)
_keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set()))
normalized = {**defaults, **p}
out = {}
if task_type == 'audio.transcribe':
asset_id = inputs.get('audio_asset_id') or inputs.get('asset_id')
if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']:
raise _invalid('请仅选择一个转写素材。')
source = self._asset(asset_id, assets)
info = await inspect_media(source, self.settings)
if normalized['language'] not in LANGUAGES:
raise _invalid('不支持此转写语言。')
_int(normalized['max_audio_seconds'], 1, 1800)
if info['kind'] not in {'audio', 'video'} or info['duration_seconds'] > normalized['max_audio_seconds']:
raise _invalid('请选择时长受限的音频或有声视频。')
if info['kind'] == 'video':
target = work / 'asr-input.wav'
temporary = work / ('asr-' + uuid.uuid4().hex + '.wav')
try:
await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(),
'-i', str(source), '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000',
'-c:a', 'pcm_s16le', '-t', str(normalized['max_audio_seconds']), '-threads', '2', str(temporary)], timeout=300)
if not temporary.is_file() or not temporary.stat().st_size:
raise _invalid('视频没有可转写的音轨。')
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
source = target
out['audio_path'] = str(source)
else:
out['prompt'] = _string(inputs.get('prompt'))
out['negative_prompt'] = _string(normalized.pop('negative_prompt', inputs.get('negative_prompt', '')), required=False)
video = task_type == 'video.generate'
for key in ('width', 'height'):
_int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16)
if normalized['width'] * normalized['height'] > (1280 * 704 if video else 2048 * 2048):
raise _invalid('画面像素总数超出服务限制。')
_int(normalized['num_inference_steps'], 1, 100)
_int(normalized['seed'], 0, 2**32 - 1)
normalized['guidance_scale'] = _float(normalized['guidance_scale'], 1, 20)
if 'image_asset_id' in inputs:
source = self._asset(inputs['image_asset_id'], assets)
if (await inspect_media(source, self.settings))['kind'] != 'image':
raise _invalid('参考素材必须是图片。')
out['image_path'] = str(source)
if task_type == 'defect.generate':
if 'image_path' not in out:
raise _invalid('条件样本任务需要参考图片。')
normalized['controlnet_conditioning_scale'] = _float(normalized['controlnet_conditioning_scale'], 0, 2)
_int(normalized['canny_low'], 0, 255)
_int(normalized['canny_high'], 0, 255)
if normalized['canny_low'] >= normalized['canny_high']:
raise _invalid('Canny低阈值必须小于高阈值。')
if video:
_int(normalized['num_frames'], 5, 121)
if normalized['num_frames'] % 4 != 1 or type(normalized['fps']) is not int or normalized['fps'] != 24:
raise _invalid('视频仅支持4n+1帧、最多121帧和24fps。')
if type(normalized['upscale']) is not bool:
raise _invalid('增强开关必须为布尔值。')
_int(normalized['upscale_width'], 256, 3840, 2)
_int(normalized['upscale_height'], 256, 2160, 2)
_int(normalized['tile_size'], 64, 256, 16)
return {'task_type': task_type, 'input': out, 'parameters': normalized, 'timeout_seconds': 3600}
async def submit(self, payload, idempotency_key):
_string(idempotency_key, 128)
if any(not 33 <= ord(char) <= 126 for char in idempotency_key):
raise _invalid('幂等请求标识无效。')
return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, '/jobs'), payload=payload,
headers={**self._headers(), 'Idempotency-Key': idempotency_key}))
@staticmethod
def _job_id(value):
if not isinstance(value, str) or re.fullmatch(r'[0-9a-f]{32}', value) is None:
raise _invalid('模型任务标识无效。')
return value
@staticmethod
def _sanitize_job(value):
if value.get('error'):
value['error'] = '模型任务执行失败,请检查任务输入或联系管理员。'
if value.get('last_preempted_reason'):
value['last_preempted_reason'] = 'GPU资源已让出,任务重新排队。'
return value
async def query(self, upstream_id):
return self._sanitize_job(await self._json('GET', _url(self.settings.inference_base_url,
'/jobs/' + self._job_id(upstream_id)), headers=self._headers()))
async def cancel(self, upstream_id):
return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url,
'/jobs/' + self._job_id(upstream_id) + '/cancel'), headers=self._headers()))
async def _download_url(self, url, destination, headers, *, payload=None):
target = confined(destination, self.settings, exists=False)
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex)
try:
async with asyncio.timeout(max(30, min(600, float(self.settings.request_timeout_seconds) * 4))):
async with self.client.stream('POST' if payload is not None else 'GET', url,
headers=headers, json=payload) as response:
if not 200 <= response.status_code < 300:
raise self._http_error(response.status_code)
limit = int(self.settings.max_output_bytes)
declared = response.headers.get('Content-Length')
if declared is not None and (not declared.isdigit() or int(declared) > limit):
raise ProviderError('output_too_large', '输出文件超出大小限制。')
count = 0
with temporary.open('xb') as stream:
async for chunk in response.aiter_bytes():
count += len(chunk)
if count > limit:
raise ProviderError('output_too_large', '输出文件超出大小限制。')
stream.write(chunk)
if not count or (declared is not None and count != int(declared)):
raise ProviderError('invalid_upstream_response', '输出文件为空或未传输完整。', True)
os.replace(temporary, target)
except (httpx.HTTPError, asyncio.TimeoutError):
raise ProviderError('upstream_unavailable', '输出文件传输失败,请稍后重试。', True) from None
except OSError:
raise ProviderError('output_unavailable', '无法保存输出文件。', True) from None
finally:
temporary.unlink(missing_ok=True)
async def download(self, upstream_id, index, destination):
_int(index, 0, 1000)
await self._download_url(_url(self.settings.inference_base_url,
'/jobs/' + self._job_id(upstream_id) + '/outputs/' + str(index)), destination, self._headers())
async def _chat(self, messages, *, max_tokens=2048, thinking=False):
if not self.settings.qwen_model:
raise ProviderError('capability_unavailable', '文本与视觉服务尚未配置。')
value = await self._json('POST', _url(self.settings.qwen_base_url, '/chat/completions'),
headers=self._headers('qwen'), payload={'model': self.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
@staticmethod
def _json_file(work, name, value):
target = work / name
temporary = work / (name + '.part-' + uuid.uuid4().hex)
try:
temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8')
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
return target
async def run_cpu(self, task_type, inputs, parameters, assets, work_dir):
work = self._work(work_dir)
validate_arguments(task_type, inputs, parameters, self.settings)
try:
if task_type == 'math.solve':
_keys(inputs, {'prompt'})
_keys(parameters, {'max_tokens', 'enable_thinking'})
tokens = _int(parameters.get('max_tokens', 2048), 1, 4096)
thinking = parameters.get('enable_thinking', False)
if type(thinking) is not bool:
raise _invalid('思考开关必须为布尔值。')
text = await self._chat([{'role': 'system', 'content': '请给出可复核的数学解题步骤和最终答案;不确定时明确说明。'},
{'role': 'user', 'content': _string(inputs.get('prompt'))}], max_tokens=tokens, thinking=thinking)
answer = work / 'answer.txt'
answer.write_text(text + '\n', encoding='utf-8')
result = {'text': text}
return CpuResult([answer, self._json_file(work, 'answer.json', result)], result,
{'provider': 'qwen', 'model': self.settings.qwen_model, 'formal_verification': False})
if task_type == 'media.structure':
return await self._structure(inputs, parameters, assets, work)
if task_type == 'video.compose':
return await self._compose(inputs, parameters, assets, work)
if task_type == 'audio.speech':
return await self._speech(inputs, parameters, work)
raise _invalid('不支持此CPU任务类型。')
except OSError:
raise ProviderError('output_unavailable', '任务文件处理失败。', True) from None
async def _image_uri(self, 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(self, 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 = self._asset(asset_id, assets)
info = await inspect_media(source, self.settings)
if info['kind'] not in {'image', 'video'}:
raise _invalid('素材理解支持图片或视频。')
samples, outputs = [(0.0, source)], []
if info['kind'] == 'video':
samples = []
for index in range(count):
timestamp = (index + .5) * info['duration_seconds'] / count
frame = work / f'frame-{index:03d}.jpg'
# Fixed filters and numeric seek only; never accept a filter from input.
_, diagnostics = await run_process([self.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 -.1 <= actual_time <= info['duration_seconds'] + .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 timestamp, frame in samples:
text = await self._chat([{'role': 'user', 'content': [
{'type': 'image_url', 'image_url': {'url': await self._image_uri(frame)}},
{'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(self._json_file(work, 'structure.json', result))
return CpuResult(outputs, result, {'provider': 'qwen', 'model': self.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)})
async def _speech(self, inputs, p, work):
if not self.settings.tts_base_url or not self.settings.tts_model or not _voices(self.settings):
raise ProviderError('capability_unavailable', '中文配音服务尚未配置。')
_keys(inputs, {'prompt'})
_keys(p, {'voice', 'speed'})
text = _string(inputs.get('prompt'), 2000)
voice = p.get('voice', _voices(self.settings)[0])
if voice not in _voices(self.settings):
raise _invalid('请选择已配置的中文音色。')
speed = _float(p.get('speed', 1.0), .5, 2)
target = work / 'speech.wav'
await self._download_url(_url(self.settings.tts_base_url, '/audio/speech'), target, self._headers('tts'),
payload={'model': self.settings.tts_model, 'input': text, 'voice': voice, 'speed': speed, 'response_format': 'wav'})
info = await inspect_media(target, self.settings)
if info['kind'] != 'audio' or info['mime_type'] != 'audio/wav':
target.unlink(missing_ok=True)
raise ProviderError('invalid_speech_response', '配音服务未返回有效的 WAV 音频。', True)
return CpuResult([target], {'text': text, 'voice': voice, 'duration_seconds': info['duration_seconds']},
{'provider': 'openai-compatible-tts', 'model': self.settings.tts_model, 'speed': speed})
async def _compose(self, inputs, p, assets, work):
_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个视频片段。')
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)
if type(fps) is not int or fps not in {24, 25, 30, 60}:
raise _invalid('不支持此成片帧率。')
normalized = []
for clip in clips:
_keys(clip, {'asset_id', 'start_seconds', 'end_seconds'})
start = _float(clip.get('start_seconds', 0), 0, 1800)
end = clip.get('end_seconds')
if end is not None and _float(end, 0, 1800) <= 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]:
raise _invalid('素材顺序应与编排片段一致。')
a, b = inputs.get('audio_asset_id'), p.get('audio_asset_id')
if a and b and a != b:
raise _invalid('请只选择一个成片音轨。')
audio = self._asset(a or b, assets) if a or b else None
subtitles = p.get('subtitles', [])
if not isinstance(subtitles, list) or len(subtitles) > 1000:
raise _invalid('人工字幕数量超出限制。')
cues = []
for cue in subtitles:
_keys(cue, {'start', 'end', 'text'})
start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800)
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控制语法。')
cues.append((start, end, html.escape(text, quote=False)))
parts, total = [], 0.0
for source, start, end in normalized:
info = await inspect_media(source, self.settings)
if info['kind'] != 'video':
raise _invalid('编排片段必须是视频素材。')
end = info['duration_seconds'] if end is None else end
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('字幕超出成片时长。')
if audio and (await inspect_media(audio, self.settings))['kind'] != 'audio':
raise _invalid('成片音轨必须为音频素材。')
files = []
async with asyncio.timeout(900):
for index, (source, start, duration, has_audio) in enumerate(parts):
target = work / f'clip-{index:03d}.mp4'
command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), '-i', str(source)]
if not has_audio:
command += ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000']
command += ['-ss', f'{start:.6f}', '-t', f'{duration:.6f}', '-map', '0:v:0', '-map',
'0:a:0' if has_audio else '1:a:0', '-vf',
f'scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}',
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p',
'-c:a', 'aac', '-ar', '48000', '-ac', '2', '-threads', '2', '-fs', str(self.settings.max_output_bytes), str(target)]
await run_process(command, timeout=min(600, max(60, duration * 5)))
files.append(target)
if sum(path.stat().st_size for path in files) >= self.settings.max_output_bytes:
raise ProviderError('output_too_large', '成片中间文件超出大小限制。')
listing = work / 'concat.txt'
listing.write_text(''.join(f"file '{path.name}'\n" for path in files), encoding='utf-8')
if cues:
def stamp(value):
milliseconds = round(value * 1000)
hours, milliseconds = divmod(milliseconds, 3600000)
minutes, milliseconds = divmod(milliseconds, 60000)
seconds, milliseconds = divmod(milliseconds, 1000)
return f'{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}'
(work / 'subtitles.srt').write_text(''.join(f'{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n'
for index, (start, end, text) in enumerate(cues, 1)), encoding='utf-8')
target = work / 'composition.mp4'
command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', '-f', 'concat', '-safe', '1', '-i', listing.name]
if audio:
command += [*input_options(), '-i', str(audio)]
command += ['-map', '0:v:0', '-map', '1:a:0' if audio else '0:a:0']
if cues:
command += ['-vf', 'subtitles=filename=subtitles.srt', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p']
else:
command += ['-c:v', 'copy']
command += ['-af', 'apad', '-t', f'{total:.6f}', '-c:a', 'aac', '-threads', '2',
'-movflags', '+faststart', '-fs', str(self.settings.max_output_bytes), str(target)]
await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work)
info = await inspect_media(target, self.settings)
if abs(info['duration_seconds'] - total) > max(.2, 2 / fps) or target.stat().st_size >= self.settings.max_output_bytes:
raise ProviderError('composition_incomplete', '成片未完整输出或超出大小限制。')
result = {'duration_seconds': info['duration_seconds'], 'width': width, 'height': height,
'fps': fps, 'clip_count': len(parts), 'subtitle_count': len(cues)}
manifest = self._json_file(work, 'composition.json', result)
return CpuResult([target, manifest], result, {'provider': 'ffmpeg-cpu', 'audio': 'uploaded' if audio else 'original-or-silence'})