185 lines
9.4 KiB
Python
185 lines
9.4 KiB
Python
"""图像与文本模型适配器:让统一模型注册表可以独立生成资产。
|
||
|
||
Mock 适配器用于离线自检,生成真实可打开的 PNG / 结构化文本;
|
||
HTTP 适配器用声明式 config 接入常见图像与文本供应商。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import random
|
||
import subprocess
|
||
from pathlib import Path
|
||
|
||
import httpx
|
||
|
||
from app.providers.base import (AssetGenRequest, AssetGenResult, FatalProviderError,
|
||
ImageProviderAdapter, RetryableProviderError, TextProviderAdapter)
|
||
from app.providers.http_generic import (_client, _headers, _raise_for_response, get_path,
|
||
render_template)
|
||
from app.services import ffmpeg as ff
|
||
|
||
|
||
def _stable_int(value: str) -> int:
|
||
return int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:8], 16)
|
||
|
||
|
||
class MockImageProvider(ImageProviderAdapter):
|
||
"""生成带渐变与几何构图的真实 PNG,用于离线验证资产生成链路。"""
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
return "mock_image"
|
||
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
if not ff.available():
|
||
raise FatalProviderError("Mock 图像生成需要 ffmpeg", code="ffmpeg_missing")
|
||
# 与 mock 视频适配器一致:注册表里的 failure_rate 是通用故障演练旋钮
|
||
config = config or {}
|
||
failure_rate = float(config.get("failure_rate", 0.0) or 0.0)
|
||
if failure_rate > 0 and random.random() < failure_rate:
|
||
raise RetryableProviderError("mock 适配器按 failure_rate 注入的临时失败",
|
||
code="mock_injected_failure")
|
||
out = Path(request.output_path or "mock-asset.png")
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
seed = request.seed if request.seed is not None else _stable_int(request.prompt + request.kind)
|
||
palettes = [
|
||
("0x111821", "0x2c5364", "0xd8a85c", "0x75a47a"),
|
||
("0x171426", "0x433d78", "0xd58973", "0x77c8d8"),
|
||
("0x1b1712", "0x63452f", "0xe2b56f", "0x9acb60"),
|
||
("0x101d1c", "0x265c58", "0xe0c36a", "0x8dd8c7"),
|
||
]
|
||
base, mid, accent, cool = palettes[seed % len(palettes)]
|
||
w, h = max(256, request.width), max(256, request.height)
|
||
x1 = int(w * (0.08 + (seed % 12) / 100))
|
||
y1 = int(h * (0.1 + (seed // 7 % 12) / 100))
|
||
box_w = int(w * 0.54)
|
||
box_h = int(h * 0.5)
|
||
x2 = max(0, w - box_w - int(w * 0.08))
|
||
y2 = max(0, h - box_h - int(h * 0.12))
|
||
vf = ",".join([
|
||
f"drawbox=x=0:y=0:w={w}:h={h}:color={base}:t=fill",
|
||
f"drawbox=x={x1}:y={y1}:w={int(w * 0.34)}:h={int(h * 0.72)}:color={mid}@0.72:t=fill",
|
||
f"drawbox=x={x2}:y={y2}:w={box_w}:h={box_h}:color={accent}@0.48:t=fill",
|
||
f"drawbox=x={int(w * 0.12)}:y={int(h * 0.78)}:w={int(w * 0.76)}:h=3:color={cool}@0.9:t=fill",
|
||
f"drawbox=x={int(w * 0.18)}:y={int(h * 0.16)}:w=2:h={int(h * 0.6)}:color={cool}@0.55:t=fill",
|
||
])
|
||
run = subprocess.run([
|
||
ff.FFMPEG, "-hide_banner", "-loglevel", "error", "-y",
|
||
"-f", "lavfi", "-i", f"color=c={base}:s={w}x{h}:d=1",
|
||
"-vf", vf, "-frames:v", "1", str(out),
|
||
], capture_output=True, text=True)
|
||
if run.returncode != 0 or not out.exists() or out.stat().st_size < 1024:
|
||
raise FatalProviderError(f"Mock 图像生成失败:{run.stderr[-500:]}", code="image_render_failed")
|
||
return AssetGenResult(
|
||
file_path=str(out), provider_job_id=f"mock-image-{seed}",
|
||
metadata={"mock": True, "seed": seed, "width": w, "height": h,
|
||
"prompt": request.prompt},
|
||
)
|
||
|
||
|
||
class HttpImageProvider(ImageProviderAdapter):
|
||
@property
|
||
def name(self) -> str:
|
||
return "http_image"
|
||
|
||
def is_available(self, config: dict | None = None) -> bool:
|
||
config = config or {}
|
||
return bool(config.get("url") or config.get("base_url"))
|
||
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
config = dict(config or {})
|
||
base_url = str(config.get("base_url") or "").rstrip("/")
|
||
url = str(config.get("url") or (f"{base_url}/images/generations" if base_url else ""))
|
||
if not url:
|
||
raise FatalProviderError("HTTP 图像模型缺少 url / base_url", code="provider_not_configured")
|
||
model = str(request.params.get("model") or config.get("model") or "")
|
||
ctx = {"prompt": request.prompt, "negative_prompt": request.negative_prompt,
|
||
"width": request.width, "height": request.height, "seed": request.seed,
|
||
"model": model, "params": request.params or {}}
|
||
body = render_template(config.get("body") or {
|
||
"model": "{{model}}", "prompt": "{{prompt}}", "negative_prompt": "{{negative_prompt}}",
|
||
"width": "{{width}}", "height": "{{height}}", "seed": "{{seed}}",
|
||
}, ctx)
|
||
out = Path(request.output_path or "http-asset.png")
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
with _client(config) as client:
|
||
try:
|
||
resp = client.post(url, headers=_headers(config, ""), json=body)
|
||
except httpx.HTTPError as exc:
|
||
raise RetryableProviderError(f"图像生成请求失败:{exc}") from exc
|
||
_raise_for_response(resp, context="图像生成")
|
||
ctype = resp.headers.get("content-type", "")
|
||
if ctype.startswith("image/"):
|
||
out.write_bytes(resp.content)
|
||
else:
|
||
data = resp.json()
|
||
image_url = get_path(data, config.get("result_url_path", "data.0.url")) \
|
||
or get_path(data, "url")
|
||
if not image_url:
|
||
raise FatalProviderError(f"图像响应缺少图片地址:{data}", code="missing_image")
|
||
try:
|
||
download = client.get(str(image_url), headers=config.get("download_headers") or {})
|
||
except httpx.HTTPError as exc:
|
||
raise RetryableProviderError(f"下载生成图片失败:{exc}") from exc
|
||
_raise_for_response(download, context="下载生成图片")
|
||
out.write_bytes(download.content)
|
||
if not out.exists() or out.stat().st_size < 128:
|
||
raise FatalProviderError("图像模型返回了空文件", code="empty_image")
|
||
return AssetGenResult(file_path=str(out), metadata={"provider": "http", "prompt": request.prompt})
|
||
|
||
|
||
class MockTextProvider(TextProviderAdapter):
|
||
@property
|
||
def name(self) -> str:
|
||
return "mock_text"
|
||
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
subject = (request.params.get("subject") or request.prompt or "未命名资产").strip()
|
||
asset_type = str(request.params.get("asset_type") or "character")
|
||
if asset_type == "scene":
|
||
text = (f"{subject}。电影级环境设定,空间层次清晰,前景、中景和背景可区分;"
|
||
"光线方向明确,材质细节可信,色调统一;保持同一场景在不同镜头中的建筑结构、"
|
||
"主要陈设、光源位置与时间氛围一致。")
|
||
else:
|
||
text = (f"{subject}。电影级角色设定,面部骨相、发型、体型、服装轮廓与标志性配饰保持稳定;"
|
||
"材质细节可信,避免不同镜头中的五官漂移和服装变化;表情克制自然,"
|
||
"可从全景到特写连续使用。")
|
||
return AssetGenResult(text=text, metadata={"mock": True, "asset_type": asset_type})
|
||
|
||
|
||
class HttpTextProvider(TextProviderAdapter):
|
||
@property
|
||
def name(self) -> str:
|
||
return "http_text"
|
||
|
||
def is_available(self, config: dict | None = None) -> bool:
|
||
config = config or {}
|
||
return bool(config.get("url") or config.get("base_url"))
|
||
|
||
def generate(self, request: AssetGenRequest, config: dict | None = None) -> AssetGenResult:
|
||
config = dict(config or {})
|
||
base_url = str(config.get("base_url") or "").rstrip("/")
|
||
url = str(config.get("url") or (f"{base_url}/chat/completions" if base_url else ""))
|
||
if not url:
|
||
raise FatalProviderError("HTTP 文本模型缺少 url / base_url", code="provider_not_configured")
|
||
model = str(request.params.get("model") or config.get("model") or "")
|
||
ctx = {"prompt": request.prompt, "model": model, "params": request.params or {}}
|
||
body = render_template(config.get("body") or {
|
||
"model": "{{model}}",
|
||
"messages": [{"role": "user", "content": "{{prompt}}"}],
|
||
"temperature": 0.7,
|
||
}, ctx)
|
||
with _client(config) as client:
|
||
try:
|
||
resp = client.post(url, headers=_headers(config, ""), json=body)
|
||
except httpx.HTTPError as exc:
|
||
raise RetryableProviderError(f"文本生成请求失败:{exc}") from exc
|
||
_raise_for_response(resp, context="文本生成")
|
||
data = resp.json()
|
||
text = get_path(data, config.get("text_path", "choices.0.message.content"))
|
||
if text is None:
|
||
text = get_path(data, "text") or get_path(data, "output_text")
|
||
if not text:
|
||
raise FatalProviderError(f"文本响应缺少内容:{data}", code="missing_text")
|
||
return AssetGenResult(text=str(text).strip(), metadata={"provider": "http", "model": model})
|