chenyuxiaojin/xiaochen-skills / plugins/cyxj-image-studio/skills/cyxj-video-cover
cyxj-video-cover
Verified无字底图生成引擎(当前默认图像模型,真人照片重绘保脸)。只出不带任何文字的场景图, 供 cyxj-release-kit 的 HTML 封面工作台当底图,或手动要一张无字人物场景图时用。 ⚠️ 封面成品、视频发布物料(标题/简介/封面)一律走 cyxj-release-kit—— 本 skill 不再直接产出带字封面,不要用它响应「做封面/生成封面」类请求。
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 2.5 KB |
| references/engines.md | markdown | 2.0 KB |
| scripts/generate.py | script | 23.1 KB |
scripts/generate.py
View on GitHub#!/usr/bin/env python3
"""
视频封面生成(真人版)
用当前默认图像模型(GPTIMG2 中转,地址见用户配置)+ 你的真人照片,生成带本人形象的封面。
照片走 /v1/images/edits 端点重绘入场,人脸保持一致;输出 2K 级别大图,url 方式返回后落地。
默认输出 4 个比例(YouTube 16:9 / 公众号 2.35:1 / 竖版 3:4 / 横版 4:3),
每比例 2 张供挑选,全部并行生成(约 1 分钟出齐)。
用法:
python3 generate.py --title "封面标题"
python3 generate.py --title "封面标题" --face ~/Pictures/封面形象/某张.png
python3 generate.py --title "封面标题" --ratios 16:9,3:4 --n 1
python3 generate.py --title "封面标题" --scene "坐在电脑前敲代码"
python3 generate.py --title "封面标题" --style arch-stickman # 俯拍真头火柴人 + 仰望拱形标题
python3 generate.py --title "本期标识" --style plate --ratios 16:9 --n 3 # 【无字】真人底图
python3 generate.py --title "本期标识" --style plate-noface --ratios 16:9 --n 3 # 【无人无字】底图
⚠ 给 cyxj-release-kit 出封面底图时,必须用 --style plate / plate-noface。
default 风格的 prompt 里硬编码了 Add this large bold Chinese title,会把中文渲进画面,
那是带字整图,不能当底图用(中文交给生图模型渲染 = 必掉字,见 release-kit 铁律)。
key 与中转站地址自动从密钥存储读取(无需手动 export):
~/项目/自己的应用/密钥存储/.env 里的 GPTIMG2_BASE_URL / GPTIMG2_API_KEY
也可用环境变量覆盖:GPTIMG2_BASE_URL / GPTIMG2_API_KEY
注意:GPTIMG2_BASE_URL(https://<中转域名>)末尾【没有】/v1,脚本拼端点时自己补。
"""
import argparse
import base64
import datetime
import json
import os
import sys
import time
import urllib.request
import urllib.error
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
# 插件级共享模块(凭据加载 + base 规整),位于 <插件根>/lib/
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "lib"))
import imgapi
# ---- 默认配置 ----
# 默认 gpt-image-2。2026-08-25 实测两条更正(用 /v1/models + 实跑核过):
# 1. 中转站这把 key 的分组(GPT-Image-2-4k)里【没有】gpt-image-2-vip,传它直接 503
# "No available channel for model gpt-image-2-vip"。别再把 vip 当默认。
# 2. gpt-image-2 现在【认 size】了——传 2560x1440 就出 2560x1440。早期
# "无视 size、强制 1254² 缩水" 的说法已过时,不必为此绕道 Gemini。
DEFAULT_MODEL = "gpt-image-2"
# 2026-08-25 实测这条中转通道的两种偶发失败,都不是请求本身有问题,直接重试即可:
# 1. 400 "This model only supports image generation and cannot process text conversation
# requests" —— 上游把图片请求错路由到对话模型。同一请求原样重放就能过。
# 2. 524 —— Cloudflare 网关超时(约 100s 上限)。并发越高单请求越慢,越容易撞线:
# 实测并发 6 时 3 成功(36/63/89s) / 3 个 524。所以并发别开太大,靠重试兜。
MAX_RETRIES = 4
RETRY_SLEEP = 3 # 秒
DEFAULT_FACE_DIR = Path.home() / "Pictures" / "封面形象"
DEFAULT_OUTPUT_DIR = Path.home() / "Pictures" / "封面出图" # 输出根:每次出图在它下面新建「日期-标签」子文件夹
# 比例 → 尺寸(2K 级别;边长均为 16 的倍数、长短比 ≤ 3:1,gpt-image-2 原生支持)
RATIO_SIZE = {
"16:9": "2560x1440", # YouTube 缩略图(2K)
"2.35:1": "2560x1088", # 公众号分享大图(长短比 2.35:1,对齐 16)
"3:4": "1536x2048", # 竖版(2K)
"4:3": "2048x1536", # 横版(2K)
}
DEFAULT_RATIOS = "16:9,2.35:1,3:4,4:3"
def load_credentials() -> tuple[str, str]:
"""读 base_url 和 api_key(走插件共享的 imgapi,支持 GPTIMG2_ENV_FILE 覆盖)。
返回的 base 已规整到以 /v1 结尾,调用方直接拼 /images/edits 等端点。
"""
base, key = imgapi.load_gptimg2()
return imgapi.api_base(base), key
def resolve_faces(face_arg: str | None) -> list[Path]:
"""确定参考人脸图:--face 指定(文件或目录)优先,否则用默认素材库目录。"""
target = Path(face_arg).expanduser() if face_arg else DEFAULT_FACE_DIR
if target.is_file():
return [target]
if target.is_dir():
imgs = sorted(
p for p in target.iterdir()
if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp")
)
if not imgs:
print(f"❌ {target} 里没有图片(png/jpg/jpeg/webp)", file=sys.stderr)
sys.exit(1)
# 默认只用第 1 张做主参考(多图更保真但更慢;需要时改这里取多张)
return imgs[:1]
print(f"❌ 参考图路径不存在:{target}", file=sys.stderr)
sys.exit(1)
def _prompt_default(title: str, scene: str | None) -> str:
"""默认风格:人在一侧半身、标题留白另一侧,高点击 YouTube 风格。
背景默认走简洁路线(纯色/弱虚化、少道具),让人物和标题主导画面,
避免背景太花抢视线。需要具体场景时用 --scene 传入。
"""
scene_line = (
f"The person is in this scene: {scene}." if scene
else "Give the person a meaningful pose that fits the title; "
"keep the surroundings minimal, no clutter."
)
return (
"Create a high click-through video cover / YouTube thumbnail. "
"Keep the SAME real person from the reference photo — same face, "
"same identity (do NOT turn into a cartoon or 3D character; keep photorealistic). "
"Composition: the person on one side as upper body, looking at camera with a "
"vivid, confident, slightly excited expression. "
"Leave clean space on the other side for a large bold Chinese title. "
f"{scene_line} "
"Background: SIMPLE and CLEAN — a solid or softly gradient color, or a heavily "
"blurred minimal setting. Avoid busy or cluttered backgrounds; do NOT fill it with "
"many props, screens, or UI panels. Keep the subject and title clearly dominant. "
f'Add this large bold Chinese title prominently: "{title}". '
"The title text must be accurate, large, high-contrast and easy to read "
"(black or white with an accent color outline). "
"Vivid, eye-catching, professional thumbnail style."
)
def _prompt_arch_stickman(title: str, scene: str | None) -> str:
"""arch-stickman 风格:高角度俯拍 + 真头火柴人 + 仰望 + 双行拱形标题 + 大留白。
人脸保留真实(仍走 edits 端点喂参考照),身体画成火柴人、脚下加柔和投影;
标题排成双行拱形罩在小人头顶,小人抬头仰望。极简、大量留白。
"""
scene_line = (
f"The figure is doing this: {scene}. " if scene
else "CRUCIAL: the figure's head is clearly TILTED BACK so the face looks straight UP "
"toward the arched title above — an unmistakable upward gaze, chin raised, eyes "
"looking up at the words. The face must NOT look at the camera straight on. "
)
return (
"Create a CLEAN, MINIMALIST YouTube thumbnail with a HIGH-ANGLE composition and LOTS "
"of negative space. Calm, simple, premium look. "
"Use the SAME real photographic face / head from the reference photo (keep the real "
"face clearly recognizable, photorealistic head), BUT render the BODY as a simple "
"hand-drawn STICK FIGURE — thin minimalist black drawn lines for the torso, arms and "
"legs. The result is a real photo head sitting on a stick-figure body. Give the figure "
"a soft cast shadow on the ground beneath it and subtle directional lighting, so it has "
"depth and gently pops off the clean background. "
"Perspective: a HIGH-ANGLE bird's-eye view looking DOWN from above. "
"Composition: the stick-figure person is SMALL but clearly visible (a bit larger, "
"occupying roughly the lower third of the frame), alone in the LOWER-CENTER, the head "
"tilted back and the face gazing UP at the arched title above. The whole area ABOVE it "
"is empty clean space. "
f"{scene_line}"
"Place the LARGE bold Chinese title in the empty space ABOVE the figure's head, with "
"the text arranged in a TWO-LINE ARCHED layout — the title curves like a dome or "
f'rainbow across the top in two stacked arcs, arcing over the little figure below: "{title}". Keep the characters '
"accurate and readable along the curve; big, clean, high-contrast, with ONE key word "
"in a bright orange accent. "
"Background: CLEAN, ABSTRACT and MINIMAL — a flat solid light / near-white single color, "
"NOT a literal sky or ground. NO props, NO arrows, NO clutter. Lots of breathing room. "
"Mood: a tiny person looking up at a huge title — small person, big message."
)
def _prompt_plate(title: str, scene: str | None) -> str:
"""plate 风格:【无字】真人底图,文字交给 cyxj-release-kit 的 HTML 封面工作台排。
铁律:中文永远不交给生图模型渲染。所以本 builder 【完全不把 title 写进 prompt】——
title 参数只用来标识这是哪一期,绝不进画面。这也是 cyxj-release-kit 把本 skill
"降级为底图生成器" 的落地形态:default 风格出的是带字整图,不能当底图用。
构图锁死账号暖棕主视觉(对齐 删80 / 找未知 / kimiK3):
人在左三分之一半身、右半边整片空墙留给排版。
"""
scene_line = (
f"The person is in this scene: {scene}. " if scene
else "He sits behind a dark wooden desk with an open silver laptop in front of him, "
"turned toward the camera with a relaxed confident slight smile. "
)
return (
"Create a photorealistic YouTube thumbnail BACKGROUND PLATE. "
"Keep the SAME real person from the reference photo — same face, same identity, "
"same glasses, same haircut, photorealistic, absolutely not a cartoon or 3D character. "
"COMPOSITION: the person occupies the LEFT THIRD of the frame as upper body. "
f"{scene_line}"
"The ENTIRE RIGHT HALF of the frame must be clean empty wall with nothing on it — "
"no props, no objects, no screens, no UI panels — it is reserved for typography "
"that will be added later in a browser. "
"BACKGROUND: warm dark-brown to chocolate gradient studio wall with a soft warm amber "
"glow radiating from behind his left shoulder, vignette falling off toward the dark "
"right edge. Cinematic soft studio lighting, shallow depth of field, warm brown grade. "
"CRITICAL: the image must contain NO text, NO letters, NO numbers, NO Chinese "
"characters, NO logos, NO watermarks, NO captions, NO signage of any kind anywhere "
"in the frame."
)
def _prompt_plate_noface(title: str, scene: str | None) -> str:
"""plate-noface 风格:【无人 + 无字】底图,走 /images/generations(不喂脸参考)。
用在这条片子没有真人出镜素材、或用户明确要求画面不出现人的时候。
同样一个字都不许进画面。
"""
scene_line = (
f"The scene is: {scene}. " if scene
else "In the lower LEFT third: a rich dark wooden desk with a single closed silver "
"laptop on it, an empty chair behind it, a warm table lamp glowing at the far left. "
)
return (
"A cinematic EMPTY scene shot, used as a YouTube thumbnail BACKGROUND PLATE. "
"Warm dark-brown to chocolate gradient studio wall, a soft warm amber glow radiating "
"from the left side of the frame, vignette falling off toward the dark right edge. "
f"{scene_line}"
"ABSOLUTELY NO PEOPLE — no person, no hands, no human figure, no silhouette anywhere. "
"The entire RIGHT HALF of the frame is clean empty wall with nothing on it, reserved "
"for typography added later. "
"CRITICAL: the image must contain NO text, NO letters, NO numbers, NO Chinese "
"characters, NO logos, NO watermarks, NO signage of any kind. "
"Soft professional studio lighting, shallow depth of field, photorealistic, high detail."
)
# 风格 → prompt 构建器
STYLE_BUILDERS = {
"default": _prompt_default,
"arch-stickman": _prompt_arch_stickman,
"plate": _prompt_plate,
"plate-noface": _prompt_plate_noface,
}
def build_prompt(title: str, scene: str | None, style: str = "default") -> str:
"""按 style 选择封面 prompt 构建器(未知 style 回退 default)。"""
return STYLE_BUILDERS.get(style, _prompt_default)(title, scene)
_PIL_MISSING_NOTED = False
def _center_crop_to_size(out_path: Path, size: str) -> None:
"""可选中心裁切:模型不认精确比例,装了 Pillow 就把落地图裁到 RATIO_SIZE 目标尺寸。
未装 Pillow 则保持原图并提示一句——本脚本卖点是仅标准库,Pillow 不是硬依赖。
"""
global _PIL_MISSING_NOTED
if size == "auto" or "x" not in size:
return
try:
from PIL import Image
except ImportError:
if not _PIL_MISSING_NOTED:
_PIL_MISSING_NOTED = True
print(" ℹ 未装 Pillow:跳过中心裁切,以实际出图尺寸为准"
"(pip install pillow 可自动裁到目标尺寸)")
return
tw, th = (int(x) for x in size.split("x"))
try:
with Image.open(out_path) as im:
w, h = im.size
if (w, h) == (tw, th):
return
# 先按"盖住目标"的最小比例缩放,再中心裁切到目标尺寸
scale = max(tw / w, th / h)
nw, nh = max(tw, round(w * scale)), max(th, round(h * scale))
im = im.resize((nw, nh), Image.LANCZOS)
left, top = (nw - tw) // 2, (nh - th) // 2
im.crop((left, top, left + tw, top + th)).save(out_path)
except Exception as e:
print(f"⚠ {out_path.name}: 中心裁切失败,保持原图 ({type(e).__name__} {e})",
file=sys.stderr)
def _multipart(fields: dict[str, str], image_paths: list[Path]) -> tuple[bytes, str]:
"""组装 multipart/form-data 请求体。"""
boundary = "----cyxjvideocover7f3a"
parts: list[bytes] = []
for name, val in fields.items():
parts.append(
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{val}\r\n'.encode()
)
for p in image_paths:
data = p.read_bytes()
mime = "image/png" if p.suffix.lower() == ".png" else "image/jpeg"
parts.append(
(f'--{boundary}\r\nContent-Disposition: form-data; name="image"; '
f'filename="{p.name}"\r\nContent-Type: {mime}\r\n\r\n').encode()
+ data + b"\r\n"
)
parts.append(f"--{boundary}--\r\n".encode())
return b"".join(parts), boundary
def generate_one(
base: str, key: str, model: str, title: str, scene: str | None,
ratio: str, idx: int, faces: list[Path], output_dir: Path,
style: str = "default",
) -> Path | None:
"""生成单张封面。返回保存路径或 None。"""
size = RATIO_SIZE.get(ratio)
if not size:
# 自定义比例兜底:交给中转站 auto
size = "auto"
prompt = build_prompt(title, scene, style)
# UA 说明:中转站前面挂了 Cloudflare,urllib 默认 UA(Python-urllib/x.y) 会被拦成
# 403 "error code: 1010",结果文件 CDN 同样拦。所有请求统一带浏览器 UA。
if style == "plate-noface":
# 无人底图:没有脸参考可喂,走纯文生图 /images/generations(JSON body)
# response_format=url 与 edits 一致:返回图片 url 再下载,不走 b64 大包体。
req = urllib.request.Request(
base + "/images/generations",
data=json.dumps({"model": model, "prompt": prompt, "size": size,
"n": 1, "response_format": "url"}).encode(),
headers={
"Authorization": "Bearer " + key,
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0",
},
method="POST",
)
else:
# edits 是 multipart 表单:size / response_format 作为表单字段传,要求返回图片 url
body, boundary = _multipart(
{
"model": model,
"prompt": prompt,
"size": size,
"n": "1",
"response_format": "url",
},
faces,
)
req = urllib.request.Request(
base + "/images/edits", data=body,
headers={
"Authorization": "Bearer " + key,
"Content-Type": f"multipart/form-data; boundary={boundary}",
"User-Agent": "Mozilla/5.0",
},
method="POST",
)
safe_ratio = ratio.replace(":", "x").replace(".", "_")
out_path = output_dir / f"cover_{safe_ratio}_{idx}.png"
for attempt in range(1, MAX_RETRIES + 1):
try:
with urllib.request.urlopen(req, timeout=300) as r:
d = json.load(r)
item = d["data"][0]
# 契约:优先走 url(response_format=url)下载落地;b64_json 作兜底
if item.get("url"):
# 下载结果图:CDN 拦 urllib 默认 UA(403),必须带浏览器 UA
dl_req = urllib.request.Request(item["url"], headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(dl_req, timeout=120) as ir:
output_dir.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(ir.read())
_center_crop_to_size(out_path, size)
return out_path
if item.get("b64_json"):
output_dir.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(base64.b64decode(item["b64_json"]))
_center_crop_to_size(out_path, size)
return out_path
print(f"⚠ {ratio} #{idx}: 返回里没有图片", file=sys.stderr)
return None
except urllib.error.HTTPError as e:
detail = e.read().decode("utf-8", "replace")[:200]
# 400 text_conversation / 5xx 都是上游抽风,重试;其余(401 鉴权、404 模型不存在)直接放弃
retryable = e.code >= 500 or "text conversation" in detail or "text_conversation" in detail
if retryable and attempt < MAX_RETRIES:
print(f" ↻ {ratio} #{idx}: HTTP {e.code} 上游抽风,第 {attempt}/{MAX_RETRIES} 次重试",
file=sys.stderr)
time.sleep(RETRY_SLEEP)
continue
print(f"❌ {ratio} #{idx}: HTTP {e.code} {detail}", file=sys.stderr)
return None
except Exception as e:
if attempt < MAX_RETRIES:
print(f" ↻ {ratio} #{idx}: {type(e).__name__} 第 {attempt}/{MAX_RETRIES} 次重试",
file=sys.stderr)
time.sleep(RETRY_SLEEP)
continue
print(f"❌ {ratio} #{idx}: {type(e).__name__} {str(e)[:200]}", file=sys.stderr)
return None
return None
def main():
parser = argparse.ArgumentParser(description="视频封面生成(真人版)")
parser.add_argument("--title", required=True, help="封面标题文字")
parser.add_argument("--scene", default=None, help="场景/动作描述(可选,不给则按标题自动)")
parser.add_argument("--ratios", default=DEFAULT_RATIOS,
help=f"输出比例,逗号分隔(默认全部:{DEFAULT_RATIOS})")
parser.add_argument("--n", type=int, default=2, help="每个比例出几张(默认 2)")
parser.add_argument("--face", default=None,
help=f"参考人脸图,文件或目录(默认 {DEFAULT_FACE_DIR})")
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"模型(默认 {DEFAULT_MODEL})")
parser.add_argument("--output", default=str(DEFAULT_OUTPUT_DIR),
help=f"输出根目录(默认 {DEFAULT_OUTPUT_DIR});实际落到 <根>/<日期-标签>/")
parser.add_argument("--label", default="未命名",
help="本批标签(如 测试 / 某视频名);输出子文件夹名 = <今日日期>-<标签>")
parser.add_argument("--style", default="default",
choices=["default", "arch-stickman", "plate", "plate-noface"],
help="封面风格:default(人在一侧半身,带字整图) / "
"arch-stickman(俯拍真头火柴人 + 仰望双行拱形标题 + 大留白) / "
"plate(【无字】真人底图,人在左右侧留白,交 HTML 工作台排字) / "
"plate-noface(【无人无字】底图,不喂脸,走文生图端点)。"
"给 cyxj-release-kit 出底图时只能用 plate / plate-noface——"
"default 会把中文渲进画面,不能当底图。")
args = parser.parse_args()
base, key = load_credentials()
# plate-noface 走文生图,没有脸参考可喂;此时不去解析脸目录(空目录会直接退出)
faces = [] if args.style == "plate-noface" else resolve_faces(args.face)
ratios = [r.strip() for r in args.ratios.split(",") if r.strip()]
# 每次出图新建「日期-标签」子文件夹,不同批次不互相覆盖
today = datetime.date.today().isoformat()
output_dir = Path(args.output).expanduser().resolve() / f"{today}-{args.label}"
print("🎬 视频封面生成(真人版)")
print(f" 标题: {args.title}")
print(f" 场景: {args.scene or '(按标题自动)'}")
print(f" 风格: {args.style}")
print(f" 比例: {', '.join(ratios)} ×{args.n} 张")
print(f" 参考: {', '.join(p.name for p in faces) if faces else '(无脸参考·纯文生图)'}")
print(f" 模型: {args.model} @ {base}")
print(f" 批次: {today}-{args.label}")
print(f" 输出: {output_dir}")
print(f" 共 {len(ratios) * args.n} 张,并行生成中...\n")
jobs = [(r, i + 1) for r in ratios for i in range(args.n)]
results: list[Path] = []
with ThreadPoolExecutor(max_workers=min(8, len(jobs))) as ex:
futs = {
ex.submit(generate_one, base, key, args.model, args.title,
args.scene, r, i, faces, output_dir, args.style): (r, i)
for r, i in jobs
}
for fut in as_completed(futs):
r, i = futs[fut]
try:
p = fut.result()
except Exception as e: # 单任务异常不掀翻整个汇总
print(f"❌ {r} #{i}: 任务异常 {type(e).__name__} {str(e)[:200]}",
file=sys.stderr)
continue
if p:
results.append(p)
print(f" ✅ {r} #{i} → {p.name}")
print(f"\n{'=' * 50}")
print(f"🏁 完成!{len(results)}/{len(jobs)} 张")
for p in sorted(results):
print(f" 📄 {p}")
print(f"{'=' * 50}")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |