|
|
@@ -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'),
|
|
|
+ )
|