# -*- coding: utf-8 -*- """vidkit —— 用代码做科普短视频的通用引擎(Vibe知识大赏 工具包)。 来源:https://ai.rongcraft.com/tools/vibe-knowledge · MIT 许可证,见 LICENSE。 项目脚本只需要定义:TITLE、OUT_DIR、WORK、SCENES、SCENE_FN,然后: from vidkit import * if __name__ == '__main__': main(__name__ 所在模块名) 命令:tts / stills <成片秒数...> / render / mux / all 默认偏好:不混配音(配音只用来给字幕定时长)、字幕淡入淡出、整片 1.25 倍速、 BGM 取 VIDKIT_BGM_DIR(默认是运行目录下的 BGM 文件夹)里的第一个音频文件。 中文字体自动在 Windows / macOS / Linux 的常见位置查找,也可以用 VIDKIT_FONT / VIDKIT_FONT_BOLD 指定。 """ import os, sys, json, math, asyncio, subprocess, wave, array, hashlib, glob, importlib from multiprocessing import Pool from PIL import Image, ImageDraw, ImageFont BGM_DIR = os.environ.get('VIDKIT_BGM_DIR', os.path.abspath('BGM')) W, H, S, FPS = 1920, 1080, 2, 30 VOICE, RATE = 'zh-CN-YunxiNeural', None # edge-tts 传 rate 会报 NoAudioReceived,别传 GAP = 0.3 SR = 24000 SPEED = 1.25 NARRATION = False SUB_FADE = 0.3 SUB_HOLD = 0.15 SUB_MODE = 'type' # 'type' = 打字机逐字出现(默认);'fade' = 整句淡入 SUB_TYPE = 0.8 # 打字完成所用的时间 = 该句时长 × SUB_TYPE(跟着阅读节奏走) SUB_FIRST_INSTANT = True # 全片第一句字幕整句直接出现(悬念开场,不让观众等打字) FIRST_NO_FADE = True # 第一个场景不做淡入,第一帧就是完整画面 # ---------------------------------------------------------------- 配色(主题) # 'dark':深色底 + 高饱和强调色(2026-10-11 起的默认);'warm':前 6 期的暖米色。 # 旧项目重新渲染时设环境变量 VIDKIT_THEME=warm。 THEMES = { 'warm': dict( BG=(243, 234, 219), INK=(43, 38, 35), MUTED=(140, 128, 115), CARD=(255, 252, 246), LIGHT=(226, 214, 194), ORANGE=(222, 112, 52), RED=(200, 64, 56), GREEN=(84, 160, 108), BLUE=(70, 120, 170), PURPLE=(126, 98, 168), CYAN=(60, 170, 190), PINK=(220, 110, 150), LIME=(150, 190, 70), SUNC=(246, 188, 72), SKY=(214, 230, 238), GROUND=(112, 158, 96), WHITE=(255, 255, 255), SUB_BOX=(43, 38, 35), SUB_EDGE=None, SUB_TXT=(250, 246, 238), COVER_RING=(236, 224, 204), COVER_HL=(252, 214, 150), COVER_HL_TXT=(43, 38, 35), ), 'dark': dict( BG=(18, 20, 28), INK=(242, 242, 246), MUTED=(150, 156, 176), CARD=(34, 37, 50), LIGHT=(60, 64, 82), ORANGE=(255, 138, 60), RED=(255, 92, 92), GREEN=(70, 214, 150), BLUE=(86, 170, 255), PURPLE=(172, 132, 255), CYAN=(64, 224, 232), PINK=(255, 112, 172), LIME=(196, 232, 92), SUNC=(255, 204, 80), SKY=(40, 60, 92), GROUND=(56, 118, 80), WHITE=(255, 255, 255), SUB_BOX=(8, 9, 14), SUB_EDGE=(70, 74, 92), SUB_TXT=(250, 250, 252), COVER_RING=(32, 35, 48), COVER_HL=(255, 204, 80), COVER_HL_TXT=(18, 20, 28), ), } THEME = os.environ.get('VIDKIT_THEME', 'dark') globals().update(THEMES[THEME]) # ---------------------------------------------------------------- 基础工具 def lerp(a, b, t): return a + (b - a) * t def clamp(x, a=0.0, b=1.0): return max(a, min(b, x)) def eo(x): x = clamp(x); return 1 - (1 - x) ** 3 def eio(x): x = clamp(x); return 4 * x ** 3 if x < .5 else 1 - (-2 * x + 2) ** 3 / 2 def eback(x): x = clamp(x); c1 = 1.70158; c3 = c1 + 1 return 1 + c3 * (x - 1) ** 3 + c1 * (x - 1) ** 2 def P(t, start, dur=0.5, ease=eo): return ease((t - start) / dur) if dur > 0 else float(t >= start) def mix(c1, c2, a): return tuple(int(round(c1[i] + (c2[i] - c1[i]) * a)) for i in range(3)) class _Ctx: pass CTX = _Ctx() CTX.raw = False def C(c, a=1.0): if c is None: return None if CTX.raw: return tuple(c) + (255,) return mix(CTX.bg, c, clamp(a) * CTX.sa) def X(v): return int(round(v * S)) def vis(a): return a * CTX.sa > 0.01 _FONTS = {} # 常见中文字体位置;都找不到时,用环境变量 VIDKIT_FONT(常规)和 VIDKIT_FONT_BOLD(粗体)指定字体文件。 _FONT_PATHS = { False: ['C:/Windows/Fonts/msyh.ttc', '/System/Library/Fonts/Hiragino Sans GB.ttc', '/System/Library/Fonts/PingFang.ttc', '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', '/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc', '/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc', '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'], True: ['C:/Windows/Fonts/msyhbd.ttc', '/System/Library/Fonts/STHeiti Medium.ttc', '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc', '/usr/share/fonts/noto-cjk/NotoSansCJK-Bold.ttc', '/usr/share/fonts/google-noto-cjk/NotoSansCJK-Bold.ttc'], } def font_path(bold=False): env = os.environ.get('VIDKIT_FONT_BOLD' if bold else 'VIDKIT_FONT') # 没有单独的粗体时退回常规字体(字会细一些,但不影响渲染)。 for p in [env] + _FONT_PATHS[bold] + ([os.environ.get('VIDKIT_FONT')] + _FONT_PATHS[False] if bold else []): if p and os.path.exists(p): return p raise RuntimeError('找不到中文字体:请把环境变量 VIDKIT_FONT(可选 VIDKIT_FONT_BOLD)设为一个 .ttf / .ttc / .otf 字体文件的路径') def F(size, bold=False): key = (size, bold) if key not in _FONTS: _FONTS[key] = ImageFont.truetype(font_path(bold), X(size)) return _FONTS[key] def tw(s, size, bold=False): return F(size, bold).getlength(s) / S def text(x, y, s, size, color, a=1.0, anchor='mm', bold=False): if not vis(a): return CTX.d.text((X(x), X(y)), s, font=F(size, bold), fill=C(color, a), anchor=anchor) def rrect(x0, y0, x1, y1, r=0, fill=None, outline=None, w=0, a=1.0): if not vis(a) or x1 - x0 < 1 or y1 - y0 < 1: return r = min(r, (x1 - x0) / 2, (y1 - y0) / 2) CTX.d.rounded_rectangle([X(x0), X(y0), X(x1), X(y1)], radius=X(r), fill=C(fill, a), outline=C(outline, a), width=X(w) if outline else 0) def ell(cx, cy, rx, ry, fill=None, outline=None, w=0, a=1.0): if not vis(a) or rx <= 0 or ry <= 0: return CTX.d.ellipse([X(cx - rx), X(cy - ry), X(cx + rx), X(cy + ry)], fill=C(fill, a), outline=C(outline, a), width=X(w) if outline else 0) def circ(cx, cy, r, **k): ell(cx, cy, r, r, **k) def poly(pts, fill=None, outline=None, w=0, a=1.0): if not vis(a): return CTX.d.polygon([(X(x), X(y)) for x, y in pts], fill=C(fill, a), outline=C(outline, a), width=max(1, X(w)) if outline else 1) def pie(cx, cy, r, start, end, fill, a=1.0): if not vis(a): return CTX.d.pieslice([X(cx - r), X(cy - r), X(cx + r), X(cy + r)], start, end, fill=C(fill, a)) def arc(cx, cy, r, start, end, color, w, a=1.0): if not vis(a): return CTX.d.arc([X(cx - r), X(cy - r), X(cx + r), X(cy + r)], start, end, fill=C(color, a), width=max(1, X(w))) def lines(pts, color, w, a=1.0, cap=True): if not vis(a) or len(pts) < 2: return CTX.d.line([(X(x), X(y)) for x, y in pts], fill=C(color, a), width=max(1, X(w)), joint='curve') if cap: for x, y in (pts[0], pts[-1]): circ(x, y, w / 2, fill=color, a=a) def dashed(x0, y0, x1, y1, color, w, dash=18, gap=12, a=1.0): L = math.dist((x0, y0), (x1, y1)) if L <= 0: return ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0 while s < L: e = min(L, s + dash) lines([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], color, w, a, cap=False) s += dash + gap def partial(pts, f): if f <= 0: return pts[:1] segs = [math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1)] target = sum(segs) * clamp(f); out = [pts[0]]; acc = 0 for i, sl in enumerate(segs): if acc + sl >= target: r = (target - acc) / sl if sl else 0 out.append((lerp(pts[i][0], pts[i + 1][0], r), lerp(pts[i][1], pts[i + 1][1], r))) return out out.append(pts[i + 1]); acc += sl return out def check(x, y, size, prog, color=GREEN, a=1.0): if prog <= 0: return pts = [(x - .42 * size, y + .02 * size), (x - .12 * size, y + .32 * size), (x + .45 * size, y - .35 * size)] lines(partial(pts, prog), color, size * .15, a) def cross(x, y, size, prog, color=RED, a=1.0): h = size / 2 if prog > 0: lines(partial([(x - h, y - h), (x + h, y + h)], prog * 2), color, size * .15, a) if prog > .5: lines(partial([(x + h, y - h), (x - h, y + h)], (prog - .5) * 2), color, size * .15, a) def rell(cx, cy, rx, ry, ang_deg, n=28): an = math.radians(ang_deg); ca, sn = math.cos(an), math.sin(an) out = [] for i in range(n): th = 2 * math.pi * i / n px, py = rx * math.cos(th), ry * math.sin(th) out.append((cx + px * ca - py * sn, cy - (px * sn + py * ca))) return out def rot_rect(cx, cy, w, h, ang_deg): an = math.radians(ang_deg); ca, sn = math.cos(an), math.sin(an) pts = [] for px, py in ((-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)): pts.append((cx + px * ca - py * sn, cy + px * sn + py * ca)) return pts def arrow(x0, y0, x1, y1, color, w, prog=1.0, a=1.0, head=28): if prog <= 0: return xe, ye = lerp(x0, x1, prog), lerp(y0, y1, prog) lines([(x0, y0), (xe, ye)], color, w, a) ang = math.atan2(ye - y0, xe - x0) pts = [(xe + math.cos(ang) * head * .6, ye + math.sin(ang) * head * .6), (xe + math.cos(ang + 2.5) * head, ye + math.sin(ang + 2.5) * head), (xe + math.cos(ang - 2.5) * head, ye + math.sin(ang - 2.5) * head)] poly(pts, fill=color, a=a) def speech(x0, y0, x1, y1, tip, a=1.0, bx=None): if not vis(a): return bx = bx if bx is not None else x0 + (x1 - x0) * .2 poly([(bx - 32, y1 - 4), (bx + 32, y1 - 4), tip], fill=CARD, outline=INK, w=3, a=a) rrect(x0, y0, x1, y1, r=26, fill=CARD, outline=INK, w=3, a=a) tx, ty = tip poly([(bx - 28, y1 - 6), (bx + 28, y1 - 6), (lerp(bx, tx, .75), lerp(y1, ty, .75))], fill=CARD, a=a) def thought(x0, y0, x1, y1, head, a=1.0): if not vis(a): return hx, hy = head; bx, by = (x0 + x1) / 2, y1 for f, r in ((.3, 16), (.58, 11), (.82, 7)): circ(lerp(bx, hx, f), lerp(by, hy, f), r, fill=CARD, outline=INK, w=3, a=a) rrect(x0, y0, x1, y1, r=(y1 - y0) / 2, fill=CARD, outline=INK, w=3, a=a) def card(x0, y0, x1, y1, a=1.0, outline=INK, fill=CARD, w=3): rrect(x0, y0, x1, y1, r=24, fill=fill, outline=outline, w=w, a=a) def tag(cx, cy, s, size, fill, color=None, a=1.0, bold=True, padx=28, h=None): color = WHITE if color is None else color w = tw(s, size, bold) + padx * 2; h = h or size * 1.7 rrect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2, r=h / 2, fill=fill, a=a) text(cx, cy, s, size, color, a, bold=bold) def layered(alpha, fn): """在独立透明图层上画 fn(),再按 alpha 叠到画面上——用于真正的半透明叠加(如叠加态的猫)。""" if alpha * CTX.sa <= 0.01: return main_img, main_d, sa = CTX.img, CTX.d, CTX.sa layer = Image.new('RGBA', main_img.size, (0, 0, 0, 0)) CTX.d = ImageDraw.Draw(layer); CTX.raw = True; CTX.sa = 1.0 try: fn() finally: CTX.d = main_d; CTX.raw = False; CTX.sa = sa a = clamp(alpha * sa) if a < 1: layer.putalpha(layer.getchannel('A').point(lambda v: int(v * a))) main_img.paste(layer, (0, 0), layer) # ---------------------------------------------------------------- 字幕 / 章节 def sub_rows(txt): rows = [txt] if tw(txt, 44) > 1300: mid = len(txt) / 2 cands = [i for i, ch in enumerate(txt) if ch in ',;:。' and 4 < i < len(txt) - 4] if any(txt[i] == '。' for i in cands): stops = [i for i in cands if txt[i] == '。'] if min(abs(i - mid) for i in stops) < len(txt) * .25: cands = stops if cands: i = min(cands, key=lambda k: abs(k - mid)) rows = [txt[:i + 1], txt[i + 1:]] out = [] for r in rows: r = r.strip(',。:;') buf, inq = '', False for ch in r: if ch == '“': inq = True elif ch == '”': inq = False buf += ch if (inq or ch not in ',。;') else ' ' out.append(buf.strip().replace('” ', '” ').replace(' “', ' “')) return out def draw_sub(img, txt, a=1.0, prog=None): """prog=None:整句显示;prog∈[0,1]:打字机效果,按进度逐字淡入(字幕框始终是整句宽度)。""" if a <= 0.01: return rows = sub_rows(txt) size, lh = 44, 62 wmax = max(tw(r, size) for r in rows) y1 = 1046; y0 = y1 - lh * len(rows) - 22 x0 = 960 - wmax / 2 - 34; x1 = 960 + wmax / 2 + 34 bx, by = X(x0), X(y0) layer = Image.new('RGBA', (X(x1) - bx, X(y1) - by), (0, 0, 0, 0)) d = ImageDraw.Draw(layer) d.rounded_rectangle([0, 0, layer.width - 1, layer.height - 1], radius=X(16), fill=SUB_BOX + (255,), outline=(SUB_EDGE + (255,)) if SUB_EDGE else None, width=X(2) if SUB_EDGE else 0) fnt = F(size) rev = None if prog is None else prog * sum(len(r) for r in rows) k = 0 for i, r in enumerate(rows): yy = X(y0 + 11 + lh * i + lh / 2) - by if rev is None: d.text((X(960) - bx, yy), r, font=fnt, fill=SUB_TXT + (255,), anchor='mm'); continue xs = X(960) - bx - fnt.getlength(r) / 2 for j, ch in enumerate(r): ca = clamp((rev - k) / 2); k += 1 if ca <= 0: break if ch != ' ': d.text((xs + fnt.getlength(r[:j]), yy), ch, font=fnt, fill=mix(SUB_BOX, SUB_TXT, ca) + (255,), anchor='lm') if a < 1: layer.putalpha(layer.getchannel('A').point(lambda v: int(v * a))) img.paste(layer, (bx, by), layer) def draw_chapter(chap): num, title = chap.split('|') w = tw(num, 30, True) + tw(title, 30) + 70 rrect(40, 34, 40 + w, 88, r=27, fill=CARD) text(66, 61, num, 30, ORANGE, anchor='lm', bold=True) text(66 + tw(num, 30, True) + 18, 61, title, 30, INK, anchor='lm') # ---------------------------------------------------------------- 时间轴与渲染 def build_timeline(proj, durs): t = 0.0; tl = [] for si, (sid, chap, lns, head, tail) in enumerate(proj.SCENES): local = head; L = [] for li, _ in enumerate(lns): d = durs[f'{si}_{li}'] L.append((local, d)); local += d + GAP if lns: local -= GAP dur = local + tail tl.append(dict(id=sid, chap=chap, start=t, dur=dur, lines=L, texts=lns)) t += dur return tl, t def load_tl(proj): with open(os.path.join(proj.WORK, 'durs.json'), encoding='utf-8') as fh: durs = json.load(fh) return build_timeline(proj, durs) def render_frame(proj, tl, f): t = f / FPS * SPEED sc = tl[-1] for s in tl: if s['start'] <= t < s['start'] + s['dur']: sc = s; break lt = t - sc['start']; D = sc['dur'] CTX.bg = BG; CTX.darken = 0.0; CTX.overlay = None; CTX.raw = False fade_in = 1.0 if (FIRST_NO_FADE and sc is tl[0]) else lt / .35 CTX.sa = clamp(min(fade_in, (D - lt) / .35)) img = Image.new('RGB', (W * S, H * S), BG) CTX.img = img; CTX.d = ImageDraw.Draw(img) proj.SCENE_FN[sc['id']](lt, sc['lines'], D) if sc['chap']: draw_chapter(sc['chap']) if CTX.darken > 0: img = Image.blend(img, Image.new('RGB', img.size, (0, 0, 0)), CTX.darken) CTX.img = img; CTX.d = ImageDraw.Draw(img) if CTX.overlay: CTX.bg = (0, 0, 0); CTX.sa = 1.0 CTX.overlay() for (st, d), txt in zip(sc['lines'], sc['texts']): end = st + d + SUB_HOLD if st <= lt < end: instant = SUB_FIRST_INSTANT and sc is tl[0] and st == sc['lines'][0][0] if SUB_MODE == 'type' and not instant: draw_sub(img, txt, clamp(min((lt - st) / .15, (end - lt) / SUB_FADE)), prog=(lt - st) / max(d * SUB_TYPE, .1)) elif instant: draw_sub(img, txt, clamp((end - lt) / SUB_FADE)) else: draw_sub(img, txt, clamp(min((lt - st) / SUB_FADE, (end - lt) / SUB_FADE))) break return img.reduce(S) def _render_chunk(args): modname, k, f0, f1 = args proj = importlib.import_module(modname) tl, _ = load_tl(proj) path = os.path.join(proj.WORK, 'segs', f'seg_{k:02d}.mp4') p = subprocess.Popen(['ffmpeg', '-v', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{W}x{H}', '-r', str(FPS), '-i', '-', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-g', '60', path], stdin=subprocess.PIPE) for f in range(f0, f1): p.stdin.write(render_frame(proj, tl, f).tobytes()) p.stdin.close(); p.wait() return path # ---------------------------------------------------------------- 配音(只用于定时) def clip_path(proj, text): h = hashlib.md5(f'{VOICE}|{RATE}|{text}'.encode('utf-8')).hexdigest()[:12] return os.path.join(proj.WORK, 'tts', f'{h}.mp3') async def _tts_all(jobs): import edge_tts for text, path in jobs: if os.path.exists(path) and os.path.getsize(path) > 1000: continue for attempt in range(8): try: c = edge_tts.Communicate(text, VOICE, rate=RATE) if RATE else edge_tts.Communicate(text, VOICE) await c.save(path) if os.path.getsize(path) > 1000: break except Exception as e: print(' 重试:', e) if os.path.exists(path): os.remove(path) await asyncio.sleep(1.5 * (attempt + 1)) else: raise RuntimeError('配音失败:' + text) def decode(path): return subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-f', 's16le', '-ac', '1', '-ar', str(SR), '-'], capture_output=True, check=True).stdout def do_tts(proj): os.makedirs(os.path.join(proj.WORK, 'tts'), exist_ok=True) jobs = [(txt, clip_path(proj, txt)) for _, _, lns, _, _ in proj.SCENES for txt in lns] asyncio.run(_tts_all(jobs)) durs = {} for si, (_, _, lns, _, _) in enumerate(proj.SCENES): for li, txt in enumerate(lns): durs[f'{si}_{li}'] = len(decode(clip_path(proj, txt))) / 2 / SR with open(os.path.join(proj.WORK, 'durs.json'), 'w', encoding='utf-8') as fh: json.dump(durs, fh, ensure_ascii=False, indent=1) tl, total = build_timeline(proj, durs) if NARRATION: buf = array.array('h', bytes(int(math.ceil(total * SR)) * 2)) for sc in tl: for (st, _), txt in zip(sc['lines'], sc['texts']): pcm = array.array('h'); pcm.frombytes(decode(clip_path(proj, txt))) off = int((sc['start'] + st) * SR); n = min(len(pcm), len(buf) - off) buf[off:off + n] = pcm[:n] with wave.open(os.path.join(proj.WORK, 'narration.wav'), 'wb') as wf: wf.setnchannels(1); wf.setsampwidth(2); wf.setframerate(SR); wf.writeframes(buf.tobytes()) print(f'脚本时长 {total:.1f}s → 成片 {total / SPEED:.1f}s') for sc in tl: print(f" {sc['id']:<10} 成片 {sc['start'] / SPEED:6.1f}s +{sc['dur'] / SPEED:.1f}s") def do_render(proj, modname): tl, total = load_tl(proj) nf = int(math.ceil(total / SPEED * FPS)) os.makedirs(os.path.join(proj.WORK, 'segs'), exist_ok=True) nproc = max(1, (os.cpu_count() or 4) - 2) step = math.ceil(nf / nproc) chunks = [(modname, k, k * step, min(nf, (k + 1) * step)) for k in range(nproc) if k * step < nf] with Pool(len(chunks)) as pool: paths = pool.map(_render_chunk, chunks) lst = os.path.join(proj.WORK, 'segs', 'list.txt') with open(lst, 'w', encoding='utf-8') as fh: for p in paths: fh.write(f"file '{p}'\n") subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', lst, '-c', 'copy', os.path.join(proj.WORK, 'video.mp4')], check=True) print('画面渲染完成', nf, '帧') def find_bgm(): if os.environ.get('VIDKIT_BGM'): return os.environ['VIDKIT_BGM'] files = sorted(p for p in glob.glob(os.path.join(BGM_DIR, '*')) if os.path.splitext(p)[1].lower() in ('.mp3', '.m4a', '.wav', '.flac', '.aac', '.ogg')) return files[0] if files else None def do_mux(proj): _, total = load_tl(proj) total /= SPEED os.makedirs(proj.OUT_DIR, exist_ok=True) bgm = find_bgm() out = os.path.join(proj.OUT_DIR, f'{proj.TITLE}.mp4' if bgm else f'{proj.TITLE}(无BGM).mp4') cmd = ['ffmpeg', '-v', 'error', '-y', '-i', os.path.join(proj.WORK, 'video.mp4')] fade = f'afade=t=in:d=1.0,afade=t=out:st={total - 3.5:.2f}:d=3.5' bgm_chain = f'atrim=0:{total:.2f},asetpts=N/SR/TB,loudnorm=I=-16:TP=-1.5:LRA=11,aresample=48000' if NARRATION: cmd += ['-i', os.path.join(proj.WORK, 'narration.wav')] voice = f'[1:a]atempo={SPEED},aresample=48000' if bgm: cmd += ['-stream_loop', '-1', '-i', bgm, '-filter_complex', f'{voice},asplit=2[v1][v2];[2:a]{bgm_chain},volume=0.28,{fade}[b];' f'[b][v1]sidechaincompress=threshold=0.03:ratio=6:attack=20:release=400[bd];' f'[bd][v2]amix=inputs=2:duration=first:normalize=0[a]', '-map', '0:v', '-map', '[a]'] else: cmd += ['-filter_complex', f'{voice}[a]', '-map', '0:v', '-map', '[a]'] elif bgm: cmd += ['-stream_loop', '-1', '-i', bgm, '-filter_complex', f'[1:a]{bgm_chain},{fade}[a]', '-map', '0:v', '-map', '[a]'] else: cmd += ['-map', '0:v'] cmd += ['-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-t', f'{total:.2f}', '-movflags', '+faststart', out] subprocess.run(cmd, check=True) print('输出:', out, '| BGM:', bgm or '无', '| 配音:', '有' if NARRATION else '无') def do_stills(proj, times): tl, _ = load_tl(proj) os.makedirs(os.path.join(proj.WORK, 'stills'), exist_ok=True) for ts in times: img = render_frame(proj, tl, int(float(ts) * FPS)) p = os.path.join(proj.WORK, 'stills', f'still_{float(ts):06.1f}.png') img.save(p); print(p) # ---------------------------------------------------------------- 封面模板 # 项目里定义 COVER = dict(series, ep, title, en, hook, art, s_v, s_h) # art(cx, base_y, s, horizontal) 负责画主角;版式、字号、配色在这里统一,保证整个账号封面风格一致。 def cover_template(w, h, c): vert = h > w if vert: circ(w / 2, 1010, 380, fill=COVER_RING) sw = tw(c['series'], 40, True) + 56; ew = tw(c['ep'], 40, True) x0 = (w - sw - 22 - ew) / 2 rrect(x0, 92, x0 + sw, 152, r=30, fill=ORANGE) text(x0 + sw / 2, 122, c['series'], 40, CARD, bold=True) text(x0 + sw + 22, 122, c['ep'], 40, INK, anchor='lm', bold=True) size = 170 while tw(c['title'], size, True) > w - 120: size -= 6 text(w / 2, 305, c['title'], size, INK, bold=True) text(w / 2, 425, c['en'], 40, MUTED) hw = tw(c['hook'], 60, True) / 2 rrect(w / 2 - hw - 30, 478, w / 2 + hw + 30, 566, r=14, fill=COVER_HL) text(w / 2, 520, c['hook'], 60, COVER_HL_TXT, bold=True) c['art'](w / 2, 1260, c.get('s_v', 1.5), False) else: circ(1070, 620, 400, fill=COVER_RING) sw = tw(c['series'], 36, True) + 50 rrect(90, 92, 90 + sw, 148, r=28, fill=ORANGE) text(90 + sw / 2, 120, c['series'], 36, CARD, bold=True) text(90 + sw + 20, 120, c['ep'], 36, INK, anchor='lm', bold=True) size = 150 while tw(c['title'], size, True) > 760: size -= 6 text(90, 330, c['title'], size, INK, anchor='lm', bold=True) text(94, 440, c['en'], 36, MUTED, anchor='lm') hw = tw(c['hook'], 54, True) rrect(80, 492, 80 + hw + 50, 572, r=14, fill=COVER_HL) text(105, 532, c['hook'], 54, COVER_HL_TXT, anchor='lm', bold=True) c['art'](1090, 960, c.get('s_h', 1.25), True) def do_cover(proj): os.makedirs(proj.OUT_DIR, exist_ok=True) for name, w, h in (('竖封面3x4', 1080, 1440), ('横封面4x3', 1440, 1080)): img = Image.new('RGB', (X(w), X(h)), BG) CTX.img = img; CTX.d = ImageDraw.Draw(img); CTX.bg = BG; CTX.sa = 1.0; CTX.raw = False cover_template(w, h, proj.COVER) p = os.path.join(proj.OUT_DIR, f'{proj.TITLE}_{name}.png') img.reduce(S).save(p); print(p) def main(modname): proj = importlib.import_module(modname) cmd = sys.argv[1] if len(sys.argv) > 1 else 'all' if cmd == 'cover': do_cover(proj) elif cmd == 'tts': do_tts(proj) elif cmd == 'stills': do_stills(proj, sys.argv[2:]) elif cmd == 'render': do_render(proj, modname) elif cmd == 'mux': do_mux(proj) elif cmd == 'all': do_tts(proj); do_render(proj, modname); do_mux(proj)