Ver código fonte

feat: AI生图模块(自有key版,对齐F线工程逻辑)

- aigen.py: 8桶风格词库prompt组装 + cogview-3-flash主通道 + pollinations兜底
- cli: aigen/aigen-batch 命令
- tests/test_aigen.py: 5项单测全过
- config.json 进 gitignore(key不随仓库)
- 实测: cogview 1024x1024 出图验证通过
wubinggen 3 meses atrás
pai
commit
aa3145ae47

+ 5 - 1
.claude/settings.local.json

@@ -12,7 +12,11 @@
       "Bash(python -c \"import iced_x86; print\\('iced OK'\\)\")",
       "Bash(python -X utf8 junk_aware_disasm.py)",
       "Bash(python -X utf8)",
-      "Bash(python -X utf8 extract_did_pool.py)"
+      "Bash(python -X utf8 extract_did_pool.py)",
+      "Bash(echo \"config.json\")",
+      "Bash(python -X utf8 tests/test_aigen.py)",
+      "Bash(python -X utf8 -W ignore tests/test_aigen.py)",
+      "Bash(python -X utf8 -m kuaishou_tool.cli aigen \"a red ceramic teapot on marble table\" test_teapot)"
     ]
   }
 }

+ 1 - 0
.gitignore

@@ -5,3 +5,4 @@ __pycache__/
 
 # 运行时产物
 *.log
+config.json

+ 14 - 5
白盒重建/config.example.json

@@ -3,7 +3,8 @@
   "ai": {
     "zhipu_api_key": "在此填你自己的智谱APIKey(开放平台 bigmodel.cn 申请)",
     "model": "cogview-3-flash",
-    "pollinations_fallback": true
+    "pollinations_fallback": true,
+    "size": "1024x1024"
   },
   "translate": {
     "baidu_appid": "自己的百度翻译appid",
@@ -14,7 +15,9 @@
     "filters": {
       "min_likes": 0,
       "min_plays": 0,
-      "keywords_block": ["违禁词示例"],
+      "keywords_block": [
+        "违禁词示例"
+      ],
       "min_commission": 0.0,
       "max_price": 0.0,
       "ban_shops": []
@@ -22,8 +25,14 @@
   },
   "publish": {
     "fragment_mb": 8,
-    "delay_sec": [30, 180],
+    "delay_sec": [
+      30,
+      180
+    ],
     "daily_limit_per_account": 5
   },
-  "proxy": { "enabled": false, "api_url": "" }
-}
+  "proxy": {
+    "enabled": false,
+    "api_url": ""
+  }
+}

+ 170 - 0
白盒重建/kuaishou_tool/aigen.py

@@ -0,0 +1,170 @@
+# -*- coding: utf-8 -*-
+"""AI 生图模块(对齐逆向 F 线的工程逻辑,凭据走自有 key)。
+
+链路复刻:
+  标题(或翻译后的英文) + 随机风格词库桶拼接 prompt
+  → cogview-3-flash 文生图(智谱开放平台, 自有 key)
+  → 失败时 pollinations.ai flux 兜底(免费)
+  → 落盘 \实拍\*.jpeg
+
+词库桶来源:原软件镜像的纯文本词组(风格描述词,无权属问题),
+按色调/光照/画质/场景/风格/构图/氛围/杰作 8 桶各随机取词。
+"""
+import json
+import logging
+import os
+import random
+import time
+from pathlib import Path
+
+import requests
+
+log = logging.getLogger(__name__)
+
+ZHIPU_URL = 'https://open.bigmodel.cn/api/paas/v4/images/generations'
+POLLINATIONS_URL = 'https://gen.pollinations.ai/image/'
+
+# 负面词:排除人物(纯产品图)与低质信号 —— F线 0x53e4f0 桶的清洗版
+NEGATIVE_HUMAN = ('people, person, human, man, woman, girl, boy, child, baby, '
+                  'figure, portrait, face, body, hands, arms, legs, crowd, '
+                  'nsfw, nude, naked, explicit')
+
+# 8 个风格词库桶(每桶取代表词, 源自镜像词组表的样本)
+VOCAB = {
+    'tone': 'warm golden|cool blue|neutral gray|earth brown|forest green|ocean blue|'
+            'sky cyan|sunset orange|sunrise pink|twilight purple|midnight navy|'
+            'moonlight silver|candlelight yellow|pastel soft|vibrant saturated',
+    'light': 'golden hour glow|blue hour light|magic hour|soft diffused light|'
+             'rim lighting|backlit glow|studio lighting|natural window light|'
+             'overcast soft|dappled sunlight',
+    'quality': 'ultra 8k resolution|16k ultra hd|professional photography|'
+               'sharp focus|high detail|crisp texture|photorealistic|'
+               'commercial product shot',
+    'scene': 'mountain sunrise|ocean horizon|forest clearing|city rooftop|'
+             'kitchen counter|marble table|wooden desk|linen backdrop|'
+             'minimalist studio|garden morning',
+    'style': 'cinematic photography|documentary style|commercial product|'
+             'fine art still life|editorial magazine|lifestyle photography|'
+             'flat lay|hero shot',
+    'composition': 'centered balanced|rule thirds|golden ratio|symmetrical frame|'
+                   'negative space|close-up macro|eye level shot|top down view',
+    'mood': 'peaceful tranquil|calm serene|quiet contemplative|fresh morning|'
+            'cozy warm|clean modern|elegant refined|bright airy',
+    'masterpiece': 'stunning masterpiece|detailed artwork|beautiful composition|'
+                   'award winning photo|magazine cover quality',
+}
+
+
+def build_prompt(subject_en: str) -> str:
+    """主体(英文) + 8 桶各随机一词 + 负面人物词。对齐 F 线 fn_ai_image_thread。"""
+    parts = [subject_en.strip()]
+    for bucket in VOCAB.values():
+        parts.append(random.choice(bucket.split('|')).strip())
+    parts.append(f'({NEGATIVE_HUMAN}: excluded)')
+    return ', '.join(parts)
+
+
+class AIGenerator:
+    """文生图:cogview 主通道 + pollinations 兜底。"""
+
+    def __init__(self, api_key: str = '', model: str = 'cogview-3-flash',
+                 fallback: bool = True, out_dir: str = '实拍',
+                 size: str = '1024x1024', timeout: int = 120):
+        self.api_key = (api_key or '').strip()
+        self.model = model
+        self.fallback = fallback
+        self.out_dir = Path(out_dir)
+        self.out_dir.mkdir(parents=True, exist_ok=True)
+        self.size = size
+        self.timeout = timeout
+
+    # ---- 主通道: 智谱 cogview ----
+    def _zhipu_generate(self, prompt: str) -> bytes | None:
+        if not self.api_key:
+            log.warning('未配置智谱 key, 跳过主通道')
+            return None
+        body = {
+            'model': self.model,
+            'prompt': prompt,
+            'size': self.size,
+        }
+        headers = {
+            'Content-Type': 'application/json',
+            'Authorization': f'Bearer {self.api_key}',
+        }
+        try:
+            r = requests.post(ZHIPU_URL, json=body, headers=headers,
+                              timeout=self.timeout)
+            if r.status_code != 200:
+                log.warning('cogview HTTP %s: %s', r.status_code, r.text[:200])
+                return None
+            data = r.json()
+            url = (data.get('data') or [{}])[0].get('url')
+            if not url:
+                log.warning('cogview 响应无 url: %s', str(data)[:200])
+                return None
+            img = requests.get(url, timeout=self.timeout)
+            if img.status_code == 200 and img.content:
+                return img.content
+            log.warning('图片下载失败 HTTP %s', img.status_code)
+            return None
+        except requests.RequestException as e:
+            log.warning('cogview 请求异常: %s', e)
+            return None
+
+    # ---- 兜底通道: pollinations flux(免费, 无需 key) ----
+    def _pollinations_generate(self, prompt: str, seed: int) -> bytes | None:
+        params = {
+            'width': self.size.split('x')[0],
+            'height': self.size.split('x')[1],
+            'model': 'flux',
+            'nologo': 'true',
+            'safe': 'true',
+            'seed': seed,
+        }
+        try:
+            r = requests.get(POLLINATIONS_URL + requests.utils.quote(prompt[:512]),
+                             params=params, timeout=self.timeout)
+            if r.status_code == 200 and r.content[:2] in (b'\xff\xd8', b'\x89P'):
+                return r.content
+            log.warning('pollinations HTTP %s', r.status_code)
+            return None
+        except requests.RequestException as e:
+            log.warning('pollinations 请求异常: %s', e)
+            return None
+
+    def generate(self, subject_en: str, name: str = None,
+                 prompt: str = None) -> Path | None:
+        """生成一张图, 落盘 \实拍\<name>.jpeg。成功返回路径, 失败 None。"""
+        prompt = prompt or build_prompt(subject_en)
+        name = name or time.strftime('img_%H%M%S')
+        seed = random.randint(1, 10**9)
+
+        img = self._zhipu_generate(prompt)
+        source = 'cogview'
+        if img is None and self.fallback:
+            log.info('主通道失败, pollinations 兜底: %s', subject_en[:40])
+            img = self._pollinations_generate(prompt, seed)
+            source = 'pollinations'
+
+        if img is None:
+            log.error('生图彻底失败: %s', subject_en[:40])
+            return None
+
+        path = self.out_dir / f'{name}.jpeg'
+        path.write_bytes(img)
+        log.info('生图成功[%s] -> %s (%d B, prompt=%s...)',
+                 source, path, len(img), prompt[:60])
+        return path
+
+
+def load_generator(cfg: dict, base_dir: str = '.') -> AIGenerator:
+    """从 config.json 的 ai 段构造生成器。"""
+    ai = cfg.get('ai', {}) if isinstance(cfg, dict) else {}
+    return AIGenerator(
+        api_key=ai.get('zhipu_api_key', ''),
+        model=ai.get('model', 'cogview-3-flash'),
+        fallback=bool(ai.get('pollinations_fallback', True)),
+        out_dir=os.path.join(base_dir, '实拍'),
+        size=ai.get('size', '1024x1024'),
+    )

+ 18 - 1
白盒重建/kuaishou_tool/cli.py

@@ -11,10 +11,12 @@
     python -m kuaishou_tool.cli queue  <视频路径> <videoId> [goodsId] [账号UID]
     python -m kuaishou_tool.cli dispatcher                   # 只跑发布调度
     python -m kuaishou_tool.cli auto [--rounds N]            # 全自动托管
+    python -m kuaishou_tool.cli aigen "英文主体描述" [名称]   # AI生图到 \实拍\
+    python -m kuaishou_tool.cli aigen-batch 标题.txt          # 按标题批量生图
 """
 import sys
 
-from . import accounts, collect, config, db, media, publish, tasks
+from . import accounts, aigen, collect, config, db, media, publish, tasks
 
 
 def main(argv=None):
@@ -58,6 +60,21 @@ def main(argv=None):
         from . import scheduler
         rounds = int(argv[argv.index('--rounds') + 1]) if '--rounds' in argv else None
         scheduler.run_auto(cfg, rounds=rounds)
+    elif cmd == 'aigen' and len(argv) >= 2:
+        gen = aigen.load_generator(cfg, '.')
+        path = gen.generate(argv[1], argv[2] if len(argv) > 2 else None)
+        print('生成:', path if path else '失败(见日志)')
+        return 0 if path else 1
+    elif cmd == 'aigen-batch' and len(argv) >= 2:
+        gen = aigen.load_generator(cfg, '.')
+        titles = [l.strip() for l in open(argv[1], encoding='utf-8') if l.strip()]
+        ok = 0
+        for i, t in enumerate(titles):
+            if gen.generate(t, f'batch_{i:03d}'):
+                ok += 1
+            import time as _t
+            _t.sleep(3)
+        print(f'批量完成: {ok}/{len(titles)}')
     else:
         print(__doc__)
         return 1

+ 66 - 0
白盒重建/tests/test_aigen.py

@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+"""aigen 模块测试:prompt 组装与生成器构造(不发起网络请求)。"""
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from kuaishou_tool import aigen
+
+
+def test_build_prompt_structure():
+    p = aigen.build_prompt('a red ceramic teapot')
+    # 主体在首位
+    assert p.startswith('a red ceramic teapot')
+    # 负面人物词在末尾
+    assert 'people, person, human' in p
+    assert p.endswith('excluded)')
+
+
+def test_build_prompt_randomness():
+    # 词库随机:多次生成应产生差异(极小概率全同, 取8次比较)
+    ps = {aigen.build_prompt('x') for _ in range(8)}
+    assert len(ps) > 1
+
+
+def test_vocab_buckets_all_nonempty():
+    for name, bucket in aigen.VOCAB.items():
+        words = [w for w in bucket.split('|') if w.strip()]
+        assert len(words) >= 5, f'桶 {name} 词数不足: {words}'
+
+
+def test_load_generator_from_cfg(tmp_path=None):
+    cfg = {'ai': {'zhipu_api_key': 'k', 'model': 'cogview-3-flash',
+                  'pollinations_fallback': True}}
+    gen = aigen.load_generator(cfg, str(Path(tmp_path or '.')))
+    assert gen.api_key == 'k'
+    assert gen.model == 'cogview-3-flash'
+    assert gen.fallback is True
+    assert gen.out_dir.name == '实拍'
+
+
+def test_generator_no_key_skips_main_channel():
+    gen = aigen.AIGenerator(api_key='', out_dir='实拍')
+    r = gen._zhipu_generate('test prompt')
+    assert r is None  # 无 key 直接跳过主通道
+
+
+if __name__ == '__main__':
+    import inspect
+    fails = 0
+    for name, fn in sorted(inspect.getmembers(sys.modules[__name__], inspect.isfunction)):
+        if not name.startswith('test_'):
+            continue
+        try:
+            sig = inspect.signature(fn)
+            if 'tmp_path' in sig.parameters or 'caplog' in sig.parameters:
+                import tempfile
+                with tempfile.TemporaryDirectory() as td:
+                    fn(td if 'tmp_path' in sig.parameters else None)
+            else:
+                fn()
+            print(f'PASS {name}')
+        except Exception as e:
+            fails += 1
+            print(f'FAIL {name}: {e}')
+    sys.exit(1 if fails else 0)

BIN
白盒重建/实拍/test_teapot.jpeg