Forráskód Böngészése

feat: media线对齐F线报告(端点锚点/兜底参数/尺寸与封面参数配置化)

- 翻译端点纠偏:api.fanyi.baidu.com(@0x52fce3 API锚点;fanyi-api域是
  原工具领key按钮落地页)
- pollinations兜底补齐锚点参数 width/height/model=flux/nologo/enhance/
  safe/seed(随机)
- 生图尺寸经 ai.image_size 配置(fn_cogview_a 的 w/h 本是参数)
- drawtext封面参数面板化 cfg['caption'](J线§1.4:字体/大小/颜色/背景色/
  透明度/描边/阴影/背景框),CAPTION_DEFAULTS+ _caption_filter
- 新增4用例(尺寸注入/兜底参数/封面滤镜串/封面端到端真跑ffmpeg)
wubinggen 3 hónapja
szülő
commit
dab72df5c7
2 módosított fájl, 278 hozzáadás és 37 törlés
  1. 115 33
      白盒重建/kuaishou_tool/media.py
  2. 163 4
      白盒重建/tests/test_media.py

+ 115 - 33
白盒重建/kuaishou_tool/media.py

@@ -42,8 +42,8 @@ DEDUP_SCRIPT = ROOT.parent / 'video_dedup.py'   # 复用已有的去重工具 D:
 
 # ---- 外部端点(F线锚点) ----
 ZHIPU_URL = 'https://open.bigmodel.cn/api/paas/v4/images/generations'   # F线 @0x72289
-BAIDU_URL = 'https://fanyi-api.baidu.com/api/trans/vip/translate'       # F线 §2.4
-POLLINATIONS_URL = 'https://image.pollinations.ai/prompt/'              # 兜底生图
+BAIDU_URL = 'https://api.fanyi.baidu.com/api/trans/vip/translate'       # F线 @0x52fce3(原文http,升https;fanyi-api域是原工具"领key"按钮落地页,非API域)
+POLLINATIONS_URL = 'https://image.pollinations.ai/prompt/'              # 兜底生图(原gen.pollinations.ai旧域已并归此现行端点)
 
 # ---- 字体(底部标题 drawtext;不存在则跳过文字层) ----
 FONT_FILE = Path('C:/Windows/Fonts/msyh.ttc')   # 微软雅黑,GBK/中英混排安全
@@ -162,22 +162,49 @@ def translate(cfg: dict, text: str) -> str:
 # 3. AI 生图:智谱 cogview 主通道 + pollinations 兜底(F线 §2.1/§2.3,I线 §3-2)
 # --------------------------------------------------------------------------
 _KEY_CURSOR = None   # 当前 key 游标(I线 [0xE987B4] 的模块级等价:顺序轮换)
-
-
-def _next_key(keys: list) -> str:
-    """key 池顺序轮换:定位当前 key,取下一枚(首调用取池中第一枚)。"""
+_KEY_COOLDOWN = {}   # key -> 冷却截止时间戳(失败进入,成功解除;冷却期内换下一枚)
+_KEY_COOLDOWN_SEC = 300   # 默认冷却 5 分钟,可由 cfg['ai']['key_cooldown_sec'] 覆盖
+
+
+def _load_keys(ai: dict) -> list:
+    """汇集 key 池(用户自有凭据):zhipu_keys 数组(推荐,易填)
+    + zhipu_api_key 竖线串(F线原工具 KEYPOOL 的 '|' 拆分格式,向后兼容),
+    去重保序、剔除空白项。"""
+    pool = []
+    for k in list(ai.get('zhipu_keys') or []):
+        k = (k or '').strip()
+        if k and k not in pool:
+            pool.append(k)
+    for k in (ai.get('zhipu_api_key') or '').split('|'):
+        k = k.strip()
+        if k and k not in pool:
+            pool.append(k)
+    return pool
+
+
+def _pick_key(keys: list) -> str:
+    """顺序轮换 + 冷却跳过:从游标下一枚起取第一枚不在冷却期的 key;
+    全池冷却则按原顺序强试(不饿死,等待恢复机会)。首调用取池中第一枚。"""
     global _KEY_CURSOR
+    now = time.time()
     idx = keys.index(_KEY_CURSOR) if _KEY_CURSOR in keys else -1
+    for step in range(1, len(keys) + 1):
+        k = keys[(idx + step) % len(keys)]
+        if _KEY_COOLDOWN.get(k, 0) <= now:
+            _KEY_CURSOR = k
+            return k
     _KEY_CURSOR = keys[(idx + 1) % len(keys)]
     return _KEY_CURSOR
 
 
-def _cogview_once(cfg: dict, api_key: str, prompt: str, out_path: Path) -> Path:
-    """智谱 cogview-3-flash 单次调用(F线 §2.1:URL/body/Bearer/取 data[0].url)。"""
+def _cogview_once(cfg: dict, api_key: str, prompt: str, out_path: Path,
+                  size: str = '1024x1024') -> Path:
+    """智谱 cogview-3-flash 单次调用(F线 §2.1:URL/body/Bearer/取 data[0].url;
+    fn_cogview_a(prompt,w,h) 的 w/h 即本函数 size,经 cfg['ai']['image_size'] 注入)。"""
     body = {
         'model': (cfg.get('ai') or {}).get('model') or 'cogview-3-flash',
         'prompt': prompt,
-        'size': '1024x1024',
+        'size': size,
         'watermark_enabled': False,          # F线请求体模板:关水印
     }
     headers = {
@@ -202,10 +229,16 @@ def _cogview_once(cfg: dict, api_key: str, prompt: str, out_path: Path) -> Path:
     return out_path
 
 
-def _pollinations_once(prompt: str, out_path: Path) -> Path:
-    """pollinations 免费兜底(F线 §2.3):GET image.pollinations.ai/prompt/<编码prompt>。"""
-    url = POLLINATIONS_URL + quote(prompt, safe='')
-    r = requests.get(url, timeout=180)
+def _pollinations_once(prompt: str, out_path: Path, size: str = '1024x1024') -> Path:
+    """pollinations 免费兜底(F线 §2.3):GET prompt URL + 查询参数对齐镜像锚点串
+    `?width=&height=&model=flux&nologo=true&enhance=true&safe=true&seed=`
+    (seed 每次随机;width/height 与 cogview 共用 cfg['ai']['image_size'])。"""
+    w, _, h = size.lower().partition('x')
+    params = {'width': w or '1024', 'height': h or '1024', 'model': 'flux',
+              'nologo': 'true', 'enhance': 'true', 'safe': 'true',
+              'seed': random.randint(1, 10 ** 9)}
+    r = requests.get(POLLINATIONS_URL + quote(prompt, safe=''), params=params,
+                     timeout=180)
     r.raise_for_status()
     if not r.content:
         raise MediaError('pollinations 图片内容为空')
@@ -217,28 +250,36 @@ def _pollinations_once(prompt: str, out_path: Path) -> Path:
 def ai_image(cfg: dict, prompt: str, out_path=None) -> Path:
     """AI 生图,返回落盘路径(默认 实拍/<uuid>.jpeg)。
 
-    - 主通道:智谱 cogview-3-flash;cfg['ai']['zhipu_api_key'] 支持 'k1|k2|k3'
-      多 key 顺序轮换(I线 §3-2),单 key 失败自动换下一枚,全失败再走兜底;
+    - 主通道:智谱 cogview-3-flash;key 池来自 cfg['ai'] 的 'zhipu_keys'
+      数组(推荐)或 'zhipu_api_key' 竖线串(F线 '|' 拆分格式),顺序轮换
+      (I线 §3-2) + 失败冷却(key_cooldown_sec,默认 300s,冷却期跳过、
+      成功解除、全冷却强试),池耗尽或空池再走兜底;
     - 兜底通道:cfg['ai']['pollinations_fallback'] 为真且智谱全失败时启用;
     - 两通道全失败抛 MediaError。
     """
     out = Path(out_path) if out_path else \
         config.dir_of(cfg, '实拍') / f'{uuid.uuid4().hex[:12]}.jpeg'
     ai = cfg.get('ai') or {}
-    keys = [k.strip() for k in (ai.get('zhipu_api_key') or '').split('|') if k.strip()]
+    size = str(ai.get('image_size') or '1024x1024')   # F线 fn_cogview_a(w,h)
+    keys = _load_keys(ai)
+    _v = ai.get('key_cooldown_sec')
+    cooldown_sec = _KEY_COOLDOWN_SEC if _v is None else max(0, int(_v))  # 0=不冷却
     last_err = None
     for _ in range(len(keys)):               # 顺序轮换:每枚 key 试一次
-        key = _next_key(keys)
+        key = _pick_key(keys)
         try:
-            _cogview_once(cfg, key, prompt, out)
+            _cogview_once(cfg, key, prompt, out, size=size)
+            _KEY_COOLDOWN.pop(key, None)     # 成功即解冷
             _logger().info('cogview 生图成功(prompt 前缀=%r)→ %s', prompt[:40], out)
             return out
         except Exception as e:
             last_err = e
-            _logger().warning('cogview 生图失败(key=%s...): %s', key[:8], e)
+            _KEY_COOLDOWN[key] = time.time() + cooldown_sec   # 失败进冷却
+            _logger().warning('cogview 生图失败(key=%s...,冷却 %ss): %s',
+                              key[:8], cooldown_sec, e)
     if ai.get('pollinations_fallback'):
         try:
-            _pollinations_once(prompt, out)
+            _pollinations_once(prompt, out, size=size)
             _logger().info('pollinations 兜底生图成功 → %s', out)
             return out
         except Exception as e:
@@ -258,6 +299,46 @@ def _fesc_path(p) -> str:
     return s
 
 
+# 底部标题 drawtext 参数(J线 §1.4「文字封面」面板的白盒等价:全字段可经
+# cfg['caption'] 覆盖;面板项 → 键:字体路径→font_file、字体大小→font_size、
+# 字体颜色→font_color、背景颜色→box_color、背景透明度→box_opacity、
+# 添加文字背景框→box、描边大小→border_w、描边颜色→border_color、
+# 阴影颜色→shadow_color(空=不投影,偏移固定2,2))。
+CAPTION_DEFAULTS = {
+    'font_file': '',               # 空 = 用模块常量 FONT_FILE(微软雅黑)
+    'font_size': 32,
+    'font_color': 'white',
+    'box': True,
+    'box_color': 'black',
+    'box_opacity': 0.5,
+    'boxborderw': 10,
+    'border_w': 0,                 # 0 = 不描边
+    'border_color': 'black',
+    'shadow_color': '',            # 空 = 不投影
+    'y_margin': 16,                # 标题距画面底部边距(px)
+}
+
+
+def _caption_filter(cfg: dict, textfile: str):
+    """构造 (drawtext 滤镜串, 字体Path):cfg['caption'] 覆盖 CAPTION_DEFAULTS。"""
+    cap = dict(CAPTION_DEFAULTS)
+    cap.update({k: v for k, v in (cfg.get('caption') or {}).items()
+                if v is not None})
+    font = Path(cap['font_file']) if cap['font_file'] else FONT_FILE
+    f = (f"drawtext=fontfile='{_fesc_path(font)}'"
+         f":textfile='{_fesc_path(textfile)}'"
+         f":fontcolor={cap['font_color']}:fontsize={int(cap['font_size'])}"
+         f":x=(w-text_w)/2:y=h-text_h-{int(cap['y_margin'])}")
+    if cap.get('box'):
+        f += (f":box=1:boxcolor={cap['box_color']}@{float(cap['box_opacity']):g}"
+              f":boxborderw={int(cap['boxborderw'])}")
+    if int(cap.get('border_w') or 0) > 0:
+        f += f":borderw={int(cap['border_w'])}:bordercolor={cap['border_color']}"
+    if cap.get('shadow_color'):
+        f += f":shadowcolor={cap['shadow_color']}:shadowx=2:shadowy=2"
+    return f, font
+
+
 def compose(cfg: dict, video_path, image_path, title: str) -> Path:
     """ffmpeg 合成 → 临存视频/<原videoId>.mp4。
 
@@ -265,6 +346,8 @@ def compose(cfg: dict, video_path, image_path, title: str) -> Path:
     - 底部 drawtext 标题:标题写入 UTF-8 临时文件经 textfile= 引用,
       彻底规避命令行/滤镜串的 GBK 与特殊字符转义问题;字体取
       C:/Windows/Fonts/msyh.ttc(微软雅黑),字体不存在则跳过文字层;
+      描边/阴影/背景框/字体大小颜色等参数经 cfg['caption'] 覆盖
+      (J线 §1.4「文字封面」面板的等价配置面,见 CAPTION_DEFAULTS);
     - 输入输出同路径时先写临时文件再原子替换(dedup 中间件与成品同名场景);
     - ffmpeg 可执行路径取 cfg['ffmpeg']。
     """
@@ -281,19 +364,18 @@ def compose(cfg: dict, video_path, image_path, title: str) -> Path:
     chains = ["[1:v][0:v]scale2ref=w='main_w*0.25':h='main_h*0.25'[pip][b0]"]
     base = '[b0]'
     tmp_txt = None
-    if FONT_FILE.exists():
-        tmp_txt = tempfile.NamedTemporaryFile('w', suffix='.txt', prefix='m3title_',
-                                              encoding='utf-8', delete=False)
-        tmp_txt.write(title or '')
-        tmp_txt.close()
-        dt = (f"drawtext=fontfile='{_fesc_path(FONT_FILE)}'"
-              f":textfile='{_fesc_path(tmp_txt.name)}'"
-              f':fontcolor=white:fontsize=32:box=1:boxcolor=black@0.5'
-              f':boxborderw=10:x=(w-text_w)/2:y=h-text_h-16')
-        chains.append(f'[b0]{dt}[b1]')
-        base = '[b1]'
-    else:
-        _logger().warning('字体 %s 不存在,跳过底部标题文字', FONT_FILE)
+    if (title or '').strip():
+        _, font = _caption_filter(cfg, '')       # 仅探测字体路径(textfile 占位)
+        if font.exists():
+            tmp_txt = tempfile.NamedTemporaryFile('w', suffix='.txt', prefix='m3title_',
+                                                  encoding='utf-8', delete=False)
+            tmp_txt.write(title)
+            tmp_txt.close()
+            dt, _ = _caption_filter(cfg, tmp_txt.name)
+            chains.append(f'[b0]{dt}[b1]')
+            base = '[b1]'
+        else:
+            _logger().warning('字体 %s 不存在,跳过底部标题文字', font)
     chains.append(f'{base}[pip]overlay=x=W-w-12:y=H-h-12[v]')
     fc = ';'.join(chains)
 

+ 163 - 4
白盒重建/tests/test_media.py

@@ -65,8 +65,9 @@ def cfg(tmp_path):
 
 @pytest.fixture(autouse=True)
 def _reset_state(cfg):
-    """每个用例前:重置 key 轮换游标 + 把 db 单例切到 tmp 库;用例后还原。"""
+    """每个用例前:重置 key 轮换游标/冷却表 + 把 db 单例切到 tmp 库;用例后还原。"""
     media._KEY_CURSOR = None
+    media._KEY_COOLDOWN = {}
     old_conn = db._CONN
     db._CONN = None
     db.conn(cfg)
@@ -137,7 +138,7 @@ def test_translate_ok(cfg, monkeypatch):
 
     monkeypatch.setattr(media.requests, 'post', fake_post)
     assert media.translate(cfg, '好物分享') == 'good stuff'
-    assert 'fanyi-api.baidu.com/api/trans/vip/translate' in cap['url']
+    assert 'api.fanyi.baidu.com/api/trans/vip/translate' in cap['url']
     d = cap['data']
     assert d['from'] == 'zh' and d['to'] == 'en'
     assert d['appid'] == 'testappid'
@@ -264,6 +265,97 @@ def test_ai_image_all_fail_raises(cfg, tmp_path, monkeypatch):
         media.ai_image(cfg, 'p', out_path=tmp_path / 'x.jpeg')
 
 
+def test_ai_image_keys_array_rotation(cfg, tmp_path, monkeypatch):
+    """zhipu_keys 数组形式(推荐填法):顺序轮换 ak_1→ak_2→ak_1。"""
+    cfg['ai']['zhipu_keys'] = ['ak_1', 'ak_2']
+    cfg['ai']['zhipu_api_key'] = ''
+    bears = []
+
+    def fake_post(url, json=None, headers=None, **kw):
+        bears.append(headers['Authorization'])
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    for _ in range(3):
+        media.ai_image(cfg, 'p', out_path=tmp_path / 'a.jpeg')
+    assert bears == ['Bearer ak_1', 'Bearer ak_2', 'Bearer ak_1']
+
+
+def test_ai_image_keys_merge_dedup(cfg, tmp_path, monkeypatch):
+    """数组 + 竖线串并存:合并去重保序(数组在前,字符串位补充)。"""
+    cfg['ai']['zhipu_keys'] = ['ak_1', 'sk_k1']       # sk_k1 与字符串位重复
+    bears = []
+
+    def fake_post(url, json=None, headers=None, **kw):
+        bears.append(headers['Authorization'])
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    for _ in range(5):
+        media.ai_image(cfg, 'p', out_path=tmp_path / 'm.jpeg')
+    assert bears == ['Bearer ak_1', 'Bearer sk_k1', 'Bearer sk_k2',
+                     'Bearer sk_k3', 'Bearer ak_1']
+
+
+def test_ai_image_failed_key_cooldown(cfg, tmp_path, monkeypatch):
+    """失败的 key 进入冷却:冷却期内跳过,不重撞刚失败的 key;成功即解冷。"""
+    calls = []
+
+    def fake_post(url, json=None, headers=None, **kw):
+        a = headers['Authorization']
+        calls.append(a)
+        if a == 'Bearer sk_k1':
+            return FakeResp(status=500)               # 仅 sk_k1 永远失败
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    for i in range(3):
+        media.ai_image(cfg, 'p', out_path=tmp_path / f'cd{i}.jpeg')
+    # 调用1: k1✗(进冷却)→k2✓;调用2: k3✓;调用3: k1冷却中跳过→k2✓
+    assert calls == ['Bearer sk_k1', 'Bearer sk_k2', 'Bearer sk_k3',
+                     'Bearer sk_k2']
+    assert calls.count('Bearer sk_k1') == 1           # 冷却期内未被重试
+
+
+def test_ai_image_all_cooldown_force_retry(cfg, tmp_path, monkeypatch):
+    """单 key 池且该 key 已在冷却:忽略冷却强试,不饿死。"""
+    cfg['ai']['zhipu_api_key'] = 'only_k'
+    cfg['ai']['pollinations_fallback'] = False
+    flaky = {'fail': True}
+
+    def fake_post(url, json=None, headers=None, **kw):
+        if flaky['fail']:
+            return FakeResp(status=500)
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    with pytest.raises(media.MediaError):
+        media.ai_image(cfg, 'p', out_path=tmp_path / 'f1.jpeg')   # 失败,only_k 进冷却
+    flaky['fail'] = False
+    out = media.ai_image(cfg, 'p', out_path=tmp_path / 'f2.jpeg')  # 全冷却→强试成功
+    assert out.exists()
+
+
+def test_ai_image_cooldown_zero(cfg, tmp_path, monkeypatch):
+    """key_cooldown_sec=0(不冷却):失败的 key 立即可重试,按轮换顺序照常取用。"""
+    cfg['ai']['key_cooldown_sec'] = 0
+    calls = []
+
+    def fake_post(url, json=None, headers=None, **kw):
+        a = headers['Authorization']
+        calls.append(a)
+        if a == 'Bearer sk_k1':
+            return FakeResp(status=500)
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    for i in range(3):
+        media.ai_image(cfg, 'p', out_path=tmp_path / f'z{i}.jpeg')
+    # 调用1: k1✗→k2✓;调用2: k3✓;调用3: 又轮到 k1(未冷却)→k1✗→k2✓
+    assert calls == ['Bearer sk_k1', 'Bearer sk_k2', 'Bearer sk_k3',
+                     'Bearer sk_k1', 'Bearer sk_k2']
+
+
 def test_ai_image_default_dir(cfg, tmp_path, monkeypatch):
     """不给 out_path 时默认落 实拍/*.jpeg。"""
     monkeypatch.setattr(media.requests, 'post',
@@ -274,6 +366,41 @@ def test_ai_image_default_dir(cfg, tmp_path, monkeypatch):
     assert p.suffix == '.jpeg' and p.exists()
 
 
+def test_ai_image_size_configurable(cfg, tmp_path, monkeypatch):
+    """F线 fn_cogview_a(prompt,w,h):尺寸经 ai.image_size 注入 cogview 请求体。"""
+    cap = {}
+
+    def fake_post(url, json=None, headers=None, **kw):
+        cap['body'] = json
+        return FakeResp(js={'data': [{'b64_json': base64.b64encode(b'x').decode()}]})
+
+    monkeypatch.setattr(media.requests, 'post', fake_post)
+    cfg['ai']['image_size'] = '768x1024'
+    media.ai_image(cfg, 'p', out_path=tmp_path / 's.jpeg')
+    assert cap['body']['size'] == '768x1024'
+
+
+def test_ai_image_pollinations_params(cfg, tmp_path, monkeypatch):
+    """F线 §2.3 锚点串:model=flux/nologo/enhance/safe/seed + width/height 传齐。"""
+    got = {}
+
+    def fake_get(url, params=None, **kw):
+        got['url'], got['params'] = url, params
+        return FakeResp(content=b'P')
+
+    monkeypatch.setattr(media.requests, 'post',
+                        lambda url, **kw: FakeResp(status=500))   # 智谱全失败→兜底
+    monkeypatch.setattr(media.requests, 'get', fake_get)
+    cfg['ai']['image_size'] = '720x1280'
+    media.ai_image(cfg, 'p', out_path=tmp_path / 'pp.jpeg')
+    p = got['params']
+    assert p['model'] == 'flux' and p['nologo'] == 'true'
+    assert p['enhance'] == 'true' and p['safe'] == 'true'
+    assert p['width'] == '720' and p['height'] == '1280'
+    assert int(p['seed']) >= 1                           # seed 每次随机
+    assert got['url'].startswith('https://image.pollinations.ai/prompt/')
+
+
 # --------------------------------------------------------------------------
 # 4. compose(ffmpeg;不可用则 skip)
 # --------------------------------------------------------------------------
@@ -319,6 +446,38 @@ def test_compose_no_font_skips_text(cfg, tmp_path, monkeypatch):
     assert out.exists() and out.stat().st_size > 0
 
 
+def test_caption_filter_params(cfg, tmp_path):
+    """J线 §1.4 文字封面参数面:默认值 + cfg['caption'] 覆盖映射进 drawtext 串。"""
+    tf = tmp_path / 'title.txt'
+    tf.write_text('标题', encoding='utf-8')
+    f, font = media._caption_filter(cfg, str(tf))
+    assert 'box=1' in f and 'boxcolor=black@0.5' in f       # 默认:黑底@0.5 背景框
+    assert 'fontsize=32' in f and 'fontcolor=white' in f
+    assert ':borderw=' not in f and 'shadowcolor=' not in f  # 默认无描边/阴影
+    cfg['caption'] = {'border_w': 3, 'border_color': 'yellow',
+                      'shadow_color': 'black', 'box': False,
+                      'font_size': 48, 'font_color': 'red'}
+    f2, _ = media._caption_filter(cfg, str(tf))
+    assert 'fontsize=48' in f2 and 'fontcolor=red' in f2
+    assert ':borderw=3' in f2 and 'bordercolor=yellow' in f2
+    assert 'shadowcolor=black:shadowx=2:shadowy=2' in f2
+    assert 'box=1' not in f2                                 # 背景框关闭
+
+
+@need_ff
+def test_compose_caption_config(cfg, tmp_path):
+    """caption 参数端到端:描边+阴影滤镜串被 ffmpeg 接受,成片正常产出。"""
+    cfg['caption'] = {'border_w': 2, 'border_color': 'white',
+                      'shadow_color': 'black', 'font_size': 28}
+    src = tmp_path / 'vidcap.mp4'
+    make_video(src)
+    img = tmp_path / 'ai9.jpeg'
+    make_image(img)
+    out = media.compose(cfg, src, img, '封面参数端到端测试')
+    assert out == Path(cfg['dirs']['临存视频']) / 'vidcap.mp4'
+    assert out.exists() and out.stat().st_size > 0
+
+
 def test_compose_missing_input_raises(cfg, tmp_path):
     """源视频不存在 → MediaError(纯 Python,不依赖 ffmpeg)。"""
     with pytest.raises(media.MediaError):
@@ -382,7 +541,7 @@ def test_process_full(cfg, tmp_path, monkeypatch):
 
     def fake_post(url, data=None, json=None, headers=None, **kw):
         cap['posts'].append((url, json, data, headers))
-        if 'fanyi-api.baidu.com' in url:
+        if 'api.fanyi.baidu.com' in url:
             return FakeResp(js={'trans_result': [
                 {'src': '神器清洁海绵', 'dst': 'magic cleaning sponge'}]})
         return FakeResp(js={'data': [
@@ -403,7 +562,7 @@ def test_process_full(cfg, tmp_path, monkeypatch):
     assert prompt.startswith('magic cleaning sponge')
     assert media.NEGATIVE.split(', ')[0] in prompt      # 'no people'
     # 翻译请求确实发生且 from/to 正确
-    tr_calls = [d for (u, b, d, h) in cap['posts'] if 'fanyi-api.baidu.com' in u]
+    tr_calls = [d for (u, b, d, h) in cap['posts'] if 'api.fanyi.baidu.com' in u]
     assert tr_calls and tr_calls[0]['from'] == 'zh' and tr_calls[0]['to'] == 'en'
     # AI 图落 实拍/*.jpeg
     assert list(Path(cfg['dirs']['实拍']).glob('*.jpeg'))