cat << 'EOF' > /Volumes/Gloway2T/Pano_Video/make_pano_video.py
import asyncio
import hashlib
import json
import math
import re
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps
import edge_tts
# ================= 可調整參數區 =================
WORK_DIR = Path("/Volumes/Gloway2T/Pano_Video")
IMAGE_FILE = WORK_DIR / "pano.jpg" # 全景圖(建議 11375x4000 8-bit JPG)
TEXT_FILE = WORK_DIR / "narration.txt" # 旁白文字檔
MANUAL_VOICE_CANDIDATES = ["voice.mp3", "voice.m4a", "voice.wav"]
BGM_CANDIDATES = ["bgm.mp3", "bgm.wav", "bgm.m4a"]
OUTPUT_FILE = WORK_DIR / "output_4k.mp4" # 輸出影片
SRT_FILE = WORK_DIR / "output_4k.srt" # 同步輸出的字幕檔
OUT_W, OUT_H = 3840, 2160 # 4K;想快速試跑可先改 1920, 1080
FPS = 30 # 30fps
TARGET_DURATION = 30.0 # 目標秒數
ZOOM_HEIGHT_RATIO = 0.75 # 取景框高度佔原圖高度比例
Y_START = 0.0 # 起點垂直位置:0.0=最上緣
Y_MID_END = 0.35 # 中後段垂直位置:保留主山峰與安瀾索橋、避開右下屋瓦
DOWN_FINISH_RATIO = 0.38 # 前 38% 時間降至目標高度,後 62% 純水平橫移
# 字幕模式:"soft"(QT 可開關軟字幕)、"hard"(直接燒錄進畫面)、"none"(僅產出 .srt 不入片)
SUBTITLE_MODE = "soft"
VOICE_FALLBACKS = [
"zh-TW-HsiaoChenNeural", # 台灣女聲(曉臻)
"zh-TW-HsiaoYuNeural", # 台灣女聲(曉雨)
"zh-CN-YunjianNeural", # 沉穩男聲備援
]
VOICE_RATE = "+0%" # 語速微調,如 "-5%" 變慢
VOICE_DELAY_SEC = 1.2 # 開場幾秒後開始旁白
BGM_VOLUME = 0.18 # 配樂音量(0.12~0.25 依音樂響度調整)
# ================================================
def smoothstep(t: float) -> float:
t = max(0.0, min(1.0, t))
return t * t * (3.0 - 2.0 * t)
def smootherstep(t: float) -> float:
t = max(0.0, min(1.0, t))
return t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
def strip_punct(s: str) -> str:
return re.sub(r"[\s,。!?;、:,.\-!?\"'「」『』()()]+", "", s)
def split_display_clauses(text: str) -> list[str]:
clauses: list[str] = []
sentences = [s.strip() for s in re.split(r"[。!?\n]+", text) if s.strip()]
for sent in sentences:
parts = [p.strip() for p in re.split(r"[,、;]+", sent) if p.strip()]
merged: list[str] = []
i = 0
while i < len(parts):
cur = parts[i]
if len(strip_punct(cur)) < 6:
if i + 1 < len(parts) and not merged:
parts[i + 1] = f"{cur},{parts[i + 1]}"
elif merged:
merged[-1] = f"{merged[-1]},{cur}"
else:
merged.append(cur)
else:
merged.append(cur)
i += 1
clauses.extend(merged)
return clauses
def fmt_srt_time(sec: float) -> str:
ms = int(round(max(0.0, sec) * 1000))
h, ms = divmod(ms, 3_600_000)
m, ms = divmod(ms, 60_000)
s, ms = divmod(ms, 1000)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def build_subtitles(
text: str,
events: list[dict],
voice_dur: float,
delay_sec: float,
video_dur: float,
) -> list[tuple[float, float, str]]:
clauses = split_display_clauses(text)
if not clauses:
return []
lens = [max(1, len(strip_punct(c))) for c in clauses]
total_chars = sum(lens)
char_times: list[tuple[float, float]] = []
for ev in events:
s = strip_punct(ev.get("text", ""))
if not s:
continue
t0 = ev["offset"] / 10_000_000.0
t1 = (ev["offset"] + ev["duration"]) / 10_000_000.0
if t1 <= t0:
t1 = t0 + 0.05
n = len(s)
dt = (t1 - t0) / n
for k in range(n):
char_times.append((t0 + k * dt, t0 + (k + 1) * dt))
raw_subs: list[list] = []
if char_times:
scale = len(char_times) / max(1, total_chars)
pos = 0
for c, n in zip(clauses, lens):
i0 = min(len(char_times) - 1, int(round(pos * scale)))
i1 = min(len(char_times) - 1, max(i0, int(round((pos + n) * scale)) - 1))
raw_subs.append([char_times[i0][0], char_times[i1][1], c])
pos += n
else:
pos = 0
for c, n in zip(clauses, lens):
t0 = (pos / max(1, total_chars)) * voice_dur
t1 = ((pos + n) / max(1, total_chars)) * voice_dur
raw_subs.append([t0, t1, c])
pos += n
result: list[tuple[float, float, str]] = []
for t0, t1, c in raw_subs:
start = max(0.0, t0 + delay_sec)
end = min(video_dur - 0.1, t1 + delay_sec)
if result and start < result[-1][1]:
start = result[-1][1]
if end <= start + 0.25:
end = min(video_dur - 0.05, start + 0.6)
result.append((start, end, c))
return result
def write_srt(subs: list[tuple[float, float, str]], path: Path):
lines = []
for idx, (t0, t1, c) in enumerate(subs, start=1):
lines.append(f"{idx}\n{fmt_srt_time(t0)} --> {fmt_srt_time(t1)}\n{c}\n")
path.write_text("\n".join(lines), encoding="utf-8")
async def generate_tts_with_timing(text: str, out_mp3: Path, out_json: Path) -> tuple[str, list[dict]]:
last_err = None
clean_text = "".join(line.strip() for line in text.splitlines() if line.strip())
for voice in VOICE_FALLBACKS:
for attempt in range(1, 4):
events: list[dict] = []
try:
print(f" 嘗試語音 {voice}(第 {attempt}/3 次)...")
communicate = edge_tts.Communicate(clean_text, voice, rate=VOICE_RATE)
with open(out_mp3, "wb") as f:
async for chunk in communicate.stream():
ctype = chunk.get("type")
if ctype == "audio":
f.write(chunk["data"])
elif ctype in ("WordBoundary", "SentenceBoundary"):
events.append({
"offset": chunk["offset"],
"duration": chunk["duration"],
"text": chunk["text"],
})
if out_mp3.exists() and out_mp3.stat().st_size > 1000:
out_json.write_text(json.dumps(events, ensure_ascii=False), encoding="utf-8")
return voice, events
except Exception as e:
last_err = e
if out_mp3.exists():
out_mp3.unlink()
print(f" 連線異常({type(e).__name__}),2 秒後重試...")
await asyncio.sleep(2)
raise RuntimeError(f"edge-tts 所有備援語音均失敗(最後錯誤:{last_err})。")
def get_audio_duration(path: Path) -> float:
cmd = [
"ffprobe", "-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
str(path),
]
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
return float(res.stdout.strip())
def find_first_existing(candidates: list[str]) -> Path | None:
for name in candidates:
p = WORK_DIR / name
if p.exists():
return p
return None
def load_cjk_font(size: int) -> ImageFont.FreeTypeFont:
candidates = [
Path("/System/Library/Fonts/PingFang.ttc"),
Path("/System/Library/Fonts/STHeiti Medium.ttc"),
Path("/System/Library/Fonts/Supplemental/Songti.ttc"),
Path("/System/Library/Fonts/Hiragino Sans GB.ttc"),
]
assets = Path("/System/Library/AssetsV2")
if assets.exists():
for p in assets.glob("com_apple_MobileAsset_Font*/*/AssetData/PingFang.ttc"):
candidates.insert(0, p)
for path in candidates:
if path.exists():
try:
return ImageFont.truetype(str(path), size=size, index=0)
except Exception:
continue
sys.exit("找不到可用的 macOS 中文字體,無法燒錄硬字幕。")
def draw_hard_subtitle(frame: Image.Image, text: str, font: ImageFont.FreeTypeFont):
draw = ImageDraw.Draw(frame)
stroke_w = max(2, frame.height // 450)
bbox = draw.textbbox((0, 0), text, font=font, stroke_width=stroke_w)
tw = bbox[2] - bbox[0]
th = bbox[3] - bbox[1]
x = (frame.width - tw) // 2
y = frame.height - th - int(frame.height * 0.065)
draw.text(
(x, y),
text,
font=font,
fill=(255, 255, 255),
stroke_width=stroke_w,
stroke_fill=(0, 0, 0),
)
def main():
if not IMAGE_FILE.exists():
sys.exit(f"找不到全景圖:{IMAGE_FILE}")
text = TEXT_FILE.read_text(encoding="utf-8").strip() if TEXT_FILE.exists() else ""
manual_voice = find_first_existing(MANUAL_VOICE_CANDIDATES)
events: list[dict] = []
if manual_voice:
print(f"[1/3] 偵測到自備旁白檔:{manual_voice.name}(跳過 edge-tts)")
voice_file = manual_voice
else:
if not text:
sys.exit(f"找不到旁白檔或內容為空:{TEXT_FILE}")
cache_sig = hashlib.md5(f"{VOICE_FALLBACKS[0]}|{VOICE_RATE}|{text}".encode("utf-8")).hexdigest()[:10]
voice_file = WORK_DIR / f"_voice_cache_{cache_sig}.mp3"
timing_file = WORK_DIR / f"_voice_cache_{cache_sig}.json"
if voice_file.exists() and voice_file.stat().st_size > 1000 and timing_file.exists():
print(f"[1/3] 沿用既有的旁白與時間軸快取:{voice_file.name}")
events = json.loads(timing_file.read_text(encoding="utf-8"))
else:
print("[1/3] 正在透過 edge-tts 生成旁白並擷取字幕時間軸...")
try:
used_voice, events = asyncio.run(generate_tts_with_timing(text, voice_file, timing_file))
print(f" 生成成功,使用語音:{used_voice}(取得 {len(events)} 筆時間標記)")
except RuntimeError as e:
sys.exit(str(e))
voice_dur = get_audio_duration(voice_file)
print(f" 旁白長度:{voice_dur:.2f} 秒")
min_needed = VOICE_DELAY_SEC + voice_dur + 1.5
duration = max(TARGET_DURATION, math.ceil(min_needed * 10) / 10)
if duration > TARGET_DURATION:
print(f" 旁白較長,影片自動延長為 {duration:.1f} 秒以避免結尾截斷。")
subs = build_subtitles(text, events, voice_dur, VOICE_DELAY_SEC, duration) if text else []
if subs:
write_srt(subs, SRT_FILE)
print(f" 已產出字幕檔:{SRT_FILE.name}(共 {len(subs)} 句,模式:{SUBTITLE_MODE})")
print(f"[2/3] 讀取全景圖:{IMAGE_FILE.name}")
Image.MAX_IMAGE_PIXELS = None
try:
img = ImageOps.exif_transpose(Image.open(IMAGE_FILE)).convert("RGB")
except Exception as e:
sys.exit(f"圖片讀取失敗(請確認為 8-bit JPG/PNG):{e}")
img_w, img_h = img.size
target_aspect = OUT_W / OUT_H
crop_h = img_h * ZOOM_HEIGHT_RATIO
crop_w = crop_h * target_aspect
if crop_w > img_w * 0.80:
crop_w = img_w * 0.75
crop_h = crop_w / target_aspect
if crop_h > img_h:
crop_h = float(img_h)
crop_w = min(float(img_w), crop_h * target_aspect)
max_x = max(0.0, img_w - crop_w)
max_y = max(0.0, img_h - crop_h)
total_frames = int(round(duration * FPS))
print(f" 原圖尺寸:{img_w}x{img_h},取景框:{crop_w:.0f}x{crop_h:.0f},總格數:{total_frames}")
delay_ms = int(VOICE_DELAY_SEC * 1000)
fade_out_start = max(0.0, duration - 2.5)
bgm_file = find_first_existing(BGM_CANDIDATES)
cmd = [
"ffmpeg", "-y",
"-f", "rawvideo",
"-vcodec", "rawvideo",
"-pix_fmt", "rgb24",
"-s", f"{OUT_W}x{OUT_H}",
"-r", str(FPS),
"-i", "-",
"-i", str(voice_file),
]
next_input_idx = 2
if bgm_file:
print(f" 偵測到背景音樂:{bgm_file.name}(自動裁切+淡入淡出混音)")
cmd += ["-stream_loop", "-1", "-i", str(bgm_file)]
filter_complex = (
f"[1:a]adelay={delay_ms}:all=1,"
f"aformat=sample_rates=44100:channel_layouts=stereo[v];"
f"[2:a]atrim=0:{duration:.2f},asetpts=PTS-STARTPTS,"
f"volume={BGM_VOLUME},"
f"afade=t=in:st=0:d=1.5,"
f"afade=t=out:st={fade_out_start:.2f}:d=2.5,"
f"aformat=sample_rates=44100:channel_layouts=stereo[b];"
f"[b][v]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[aout]"
)
next_input_idx = 3
else:
print(" 未偵測到 bgm.mp3 / bgm.wav / bgm.m4a,將僅輸出旁白音軌。")
filter_complex = (
f"[1:a]adelay={delay_ms}:all=1,"
f"apad=whole_dur={duration:.2f},"
f"aformat=sample_rates=44100:channel_layouts=stereo[aout]"
)
use_soft_sub = (SUBTITLE_MODE == "soft" and bool(subs) and SRT_FILE.exists())
if use_soft_sub:
cmd += ["-i", str(SRT_FILE)]
sub_idx = next_input_idx
cmd += [
"-filter_complex", filter_complex,
"-map", "0:v",
"-map", "[aout]",
]
if use_soft_sub:
cmd += [
"-map", f"{sub_idx}:0",
"-c:s", "mov_text",
"-metadata:s:s:0", "language=zho",
"-metadata:s:s:0", "title=繁體中文",
"-disposition:s:0", "default",
]
cmd += [
"-c:v", "libx264",
"-crf", "18",
"-preset", "fast",
"-pix_fmt", "yuv420p",
"-c:a", "aac",
"-b:a", "192k",
"-t", f"{duration:.2f}",
"-movflags", "+faststart",
str(OUTPUT_FILE),
]
font = load_cjk_font(int(OUT_H * 0.042)) if (SUBTITLE_MODE == "hard" and subs) else None
print(f"[3/3] 開始渲染 {OUT_W}x{OUT_H} @ {FPS}fps 影片...")
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
try:
for i in range(total_frames):
u = i / max(1, total_frames - 1)
x_norm = smootherstep(u)
if u < DOWN_FINISH_RATIO:
y_progress = smoothstep(u / DOWN_FINISH_RATIO)
y_norm = Y_START + (Y_MID_END - Y_START) * y_progress
else:
y_norm = Y_MID_END
x = min(max(0.0, x_norm * max_x), max_x)
y = min(max(0.0, y_norm * max_y), max_y)
x2 = min(float(img_w), x + crop_w)
y2 = min(float(img_h), y + crop_h)
frame = img.resize(
(OUT_W, OUT_H),
resample=Image.Resampling.BICUBIC,
box=(x, y, x2, y2),
)
if font is not None:
t_sec = i / FPS
for s0, s1, stext in subs:
if s0 <= t_sec <= s1:
draw_hard_subtitle(frame, stext, font)
break
proc.stdin.write(frame.tobytes())
if (i + 1) % max(1, total_frames // 10) == 0 or i == total_frames - 1:
pct = (i + 1) * 100 // total_frames
print(f" 進度:{pct}% ({i + 1}/{total_frames})")
finally:
if proc.stdin:
proc.stdin.close()
stderr_out = proc.stderr.read().decode("utf-8", errors="ignore")
ret = proc.wait()
if ret != 0:
sys.exit(f"FFmpeg 編碼失敗:\n{stderr_out[-1000:]}")
print(f"\n完成!輸出檔案:{OUTPUT_FILE}")
if __name__ == "__main__":
main()
EOF