thuthi-plugin 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +55 -0
- package/README.md +13 -2
- package/bin/parallel-browser.js +109 -0
- package/extension/background.js +1329 -0
- package/extension/config.json +1 -0
- package/extension/guard.js +44 -0
- package/extension/manifest.json +10 -0
- package/extension/overlay.js +104 -0
- package/extension/popup.html +34 -0
- package/extension/popup.js +39 -0
- package/extension-reloader/manifest.json +13 -0
- package/extension-reloader/sw.js +17 -0
- package/package.json +13 -4
- package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
- package/plugins/thuthi/context.md +3 -0
- package/plugins/thuthi/hooks/hooks.json +15 -0
- package/plugins/thuthi/skills/setup/SKILL.md +55 -0
- package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
- package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
- package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
- package/plugins/thuthi/tools/legacy_launcher.py +65 -0
- package/plugins/thuthi/tools/statusline/statusline.py +8 -0
- package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-accounts/bin/claude-switch +5 -0
- package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
- package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
- package/plugins/thuthi-accounts/lib/tls.py +68 -0
- package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
- package/plugins/thuthi-accounts/setup_check.py +21 -0
- package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
- package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
- package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
- package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
- package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
- package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-agenda-picker/context.md +3 -0
- package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
- package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
- package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
- package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
- package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
- package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
- package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-browser/context.md +3 -0
- package/plugins/thuthi-browser/hooks/hooks.json +15 -0
- package/plugins/thuthi-browser/lib/pbpage.py +397 -0
- package/plugins/thuthi-browser/setup_check.py +93 -0
- package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
- package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
- package/plugins/thuthi-demo-video/setup_check.py +14 -0
- package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
- package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
- package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-orca/context.md +5 -0
- package/plugins/thuthi-orca/hooks/hooks.json +18 -0
- package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
- package/plugins/thuthi-orca/setup_check.py +12 -0
- package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
- package/runtime/client.js +69 -0
- package/runtime/daemon.js +503 -0
- package/runtime/focus-monitor.js +53 -0
- package/runtime/keys.js +86 -0
- package/runtime/owner.js +64 -0
- package/runtime/recorder.js +267 -0
- package/runtime/relay.js +95 -0
- package/runtime/session.js +1599 -0
|
@@ -0,0 +1,2416 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""demo-video: 웹 앱 동작을 사람에게 보여 줄 시연 영상을 만든다.
|
|
4
|
+
|
|
5
|
+
브라우저는 parallel-browser 로 다룬다. 사용자의 Chrome · Edge 안에 있는 에이전트 전용 창에서 돌고,
|
|
6
|
+
포커스를 가져가지 않는다. 각 단계가 끝나면 (오류로 끝나도) 자기가 연 세션과 탭을 닫는다.
|
|
7
|
+
|
|
8
|
+
녹화 방식과 그렇게 한 이유:
|
|
9
|
+
* 화면 녹화(screencapture 등)는 창이 가려지면 대상이 사라진다. 쓰지 않는다.
|
|
10
|
+
* 녹화는 parallel-browser 의 것 (s.startRecording / s.stopRecording) 을 쓴다. 브라우저는 화면이 바뀔 때만 프레임을
|
|
11
|
+
주고 (Page.startScreencast), 데몬이 받는 대로 영상으로 구우며 프레임마다 도착 시각을 남긴다. 그 영상을 그대로 쓰면
|
|
12
|
+
정지 구간 길이는 맞지만 프레임 간격이 들쭉날쭉하다. 그래서 1/25초 칸마다 그 시각까지 받은 마지막 프레임을 채워
|
|
13
|
+
고정 25fps 영상으로 바꾼다 (assemble_cfr). Playwright 의 record_video 도 Chromium 에서는 같은 screencast 를 받아
|
|
14
|
+
같은 식으로 25fps 를 채운다.
|
|
15
|
+
* 실측 (2026-10-05, Edge 152): 에이전트 창이 다른 데스크톱 공간에 있어 화면에 전혀 그려지지 않고
|
|
16
|
+
(CoreGraphics onscreen=false), 녹화 탭도 그 창의 비활성 탭이며, 맨 앞 앱은 내내 다른 앱이었다.
|
|
17
|
+
그래도 CSS 애니메이션 동안 1440×900 프레임이 초당 75장(모니터 주사율) 들어왔다. 같은 시나리오를 옛 방식과
|
|
18
|
+
찍어 보니 진행 막대 65/65 칸, 화살표 링 42/42 칸, 클릭 물결 21/21 칸이 두 방식 모두 새 프레임으로 찼고
|
|
19
|
+
커서 글라이드는 둘 다 연속 8프레임(0.32초)이었다. 같은 페이지의 Playwright 무손실 스크린샷을 정답으로 두면
|
|
20
|
+
옛 원본 SSIM 0.9933 / PSNR 41.6dB, 새 원본 0.9952 / 41.2dB 다.
|
|
21
|
+
* 사용자 브라우저라 Playwright headless 와 다른 점 세 가지를 맞춘다.
|
|
22
|
+
- parallel-browser 가 페이지에 넣는 상태 표시(파란 테두리 · 라벨 · [내가 하기] 버튼)가 화면에 찍힌다.
|
|
23
|
+
녹화 탭과 렌더 탭에서는 CSS 로 숨긴다.
|
|
24
|
+
- macOS 스크롤바 설정에 따라 고전 스크롤바가 찍힌다. Emulation.setScrollbarsHidden 으로 숨긴다
|
|
25
|
+
(headless 의 --hide-scrollbars 와 같은 효과).
|
|
26
|
+
- 사용자 브라우저는 CSS 색을 창이 놓인 모니터의 색 공간으로 바꿔 그린다 (headless 는 --force-color-profile=srgb).
|
|
27
|
+
같은 탭에 색 보정판(16단계 4096색)을 그려 찍고, 역변환 3D LUT 를 만들어 ffmpeg lut3d 로 sRGB 로 되돌린다.
|
|
28
|
+
정지 화면을 정답과 비교하면 보정 전 PSNR 36.2dB, 보정 뒤 48.9dB 다. 모니터 색역 밖의 진한 색
|
|
29
|
+
(이 PC 의 LG ULTRAWIDE 에서는 진한 녹색)은 잘려 들어와 정확히 되돌릴 수 없다.
|
|
30
|
+
* 맞추지 못하는 차이: Edge 의 기본 포커스 테두리 · 폼 컨트롤 모양은 Chromium 과 다르다 (포커스 테두리가
|
|
31
|
+
파란색이 아니라 검은색). 사용자 브라우저의 다른 확장이 페이지에 넣는 것도 찍힌다.
|
|
32
|
+
|
|
33
|
+
세 단계로 나뉜다.
|
|
34
|
+
1) record 시나리오를 실행하며 원본 영상(25fps mp4) + 구간 메타(json) 을 남긴다
|
|
35
|
+
2) render 준비 구간을 잘라내고 표시된 구간만 N배속으로 만들어 mp4 로 굽는다
|
|
36
|
+
3) frames 결과에서 프레임을 뽑아 눈으로 확인한다 (납품 전 필수)
|
|
37
|
+
|
|
38
|
+
사용법:
|
|
39
|
+
demo_video.py doctor
|
|
40
|
+
demo_video.py record <시나리오.py> --dry-run 녹화 없이 시나리오만 빨리 돌려 본다
|
|
41
|
+
demo_video.py record <시나리오.py> --out raw.mp4 --meta raw.json
|
|
42
|
+
demo_video.py render --src raw.mp4 --meta raw.json --out final.mp4 [--speed 4] [--trim-end 초]
|
|
43
|
+
demo_video.py frames --src final.mp4 --sheet [--at 2,9,15] [--outdir 폴더]
|
|
44
|
+
demo_video.py concat a.mp4 b.mp4 … --out all.mp4 [--xfade 0.4]
|
|
45
|
+
|
|
46
|
+
모든 명령은 마지막 줄에 `RESULT ok …` 나 `RESULT fail …` 한 줄을 찍는다 (출력을 잘라 봐도 성패가 보이게).
|
|
47
|
+
|
|
48
|
+
python3 3.9 표준 라이브러리 + ffmpeg + parallel-browser 만 쓴다. Playwright 는 필요 없다.
|
|
49
|
+
"""
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import argparse
|
|
53
|
+
import base64
|
|
54
|
+
import importlib.util
|
|
55
|
+
import json
|
|
56
|
+
import math
|
|
57
|
+
import os
|
|
58
|
+
import queue
|
|
59
|
+
import re
|
|
60
|
+
import shutil
|
|
61
|
+
import subprocess
|
|
62
|
+
import sys
|
|
63
|
+
import tempfile
|
|
64
|
+
import threading
|
|
65
|
+
import time
|
|
66
|
+
from pathlib import Path
|
|
67
|
+
|
|
68
|
+
HERE = Path(__file__).resolve().parent
|
|
69
|
+
OVERLAY_JS = HERE / "overlay.js"
|
|
70
|
+
CURSOR_JS = HERE / "cursor.js"
|
|
71
|
+
TITLE_HTML = HERE / "title.html"
|
|
72
|
+
SPEED_MIN, SPEED_MAX = 1.0, 8.0
|
|
73
|
+
FPS = 25
|
|
74
|
+
TAIL_SEC = 1.0 # 정리 뒤 더 찍는 시간. Playwright 도 녹화 끝에 마지막 화면을 1초 이상 덧붙였다
|
|
75
|
+
# record --dry-run 에서 d.sleep / d.say(hold=) 가 실제로 기다리는 최대 시간. 박자를 맞추는 sleep 은 녹화 없이 돌려 볼 때
|
|
76
|
+
# 기다릴 이유가 없다. 페이지를 기다리는 일은 d.wait_text / d.wait_until 이 하므로 그대로 기다린다.
|
|
77
|
+
DRY_SLEEP_CAP = 0.3
|
|
78
|
+
# d.say(text, hold="auto") 가 자막을 읽을 시간으로 기다리는 길이: 기본 + 글자당, 최소 · 최대.
|
|
79
|
+
# 영상 기록의 d.sleep 값(3초 110번, 4초 50번, 1.5초 42번)과 자막 길이(대개 15~35자)에 맞춘 값이다.
|
|
80
|
+
SAY_HOLD_BASE, SAY_HOLD_PER_CHAR, SAY_HOLD_MIN, SAY_HOLD_MAX = 0.8, 0.07, 1.5, 6.0
|
|
81
|
+
|
|
82
|
+
# 이번 실행에서 나온 경고. 마지막 RESULT 줄에 개수를 붙이고 결과 JSON 에도 싣는다.
|
|
83
|
+
WARNINGS: list[str] = []
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def warn(msg: str) -> None:
|
|
87
|
+
WARNINGS.append(msg)
|
|
88
|
+
print(f" [경고] {msg}", file=sys.stderr)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ScenarioError(RuntimeError):
|
|
92
|
+
"""시나리오가 가리킨 대상이 화면에 없다. 녹화를 계속하면 화살표 · 줌이 빠진 영상이 끝까지 찍힌다."""
|
|
93
|
+
|
|
94
|
+
# pbpage: thuthi-browser 플러그인의 parallel-browser 다리 (lib/pbpage.py 는 그 복사본, scripts/sync_shared.py 가 맞춘다)
|
|
95
|
+
PB_LIB = Path(__file__).resolve().parents[3] / "lib"
|
|
96
|
+
sys.path.insert(0, str(PB_LIB))
|
|
97
|
+
try:
|
|
98
|
+
import pbpage
|
|
99
|
+
except ImportError as _e: # doctor 가 알려 준다
|
|
100
|
+
pbpage = None
|
|
101
|
+
_PBPAGE_ERROR = str(_e)
|
|
102
|
+
# parallel-browser 설치 안내는 thuthi-browser 플러그인에 있다 (이 플러그인이 의존한다)
|
|
103
|
+
PB_INSTALL_DOC = "thuthi-browser 플러그인의 skills/parallel-browser/references/install.md"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
107
|
+
# 환경 점검 · 부트스트랩
|
|
108
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
109
|
+
DOCTOR_ANIM_HTML = """<!doctype html><html><head><meta charset="utf-8"><style>
|
|
110
|
+
html,body{margin:0;background:#fff} i{position:absolute;top:80px;left:0;width:80px;height:80px;background:#2563eb;
|
|
111
|
+
animation:m 1s linear infinite} @keyframes m{from{transform:translateX(0)}to{transform:translateX(560px)}}
|
|
112
|
+
</style></head><body><i></i></body></html>"""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def doctor(fix: bool = False) -> int:
|
|
116
|
+
"""실행 환경을 점검한다. 브라우저 쪽은 실제로 세션을 열어 1.5초 녹화해 보고 닫는다.
|
|
117
|
+
--fix 는 ffmpeg 가 없을 때 brew 로 설치를 시도한다 (parallel-browser 는 thuthi:setup 이 설치한다)."""
|
|
118
|
+
problems: list[str] = []
|
|
119
|
+
|
|
120
|
+
print(f"python {sys.version.split()[0]} ({sys.executable})")
|
|
121
|
+
if sys.version_info < (3, 9):
|
|
122
|
+
problems.append("python 3.9 이상이 필요하다.")
|
|
123
|
+
|
|
124
|
+
if shutil.which("ffmpeg") and shutil.which("ffprobe"):
|
|
125
|
+
ver = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True).stdout.split("\n")[0]
|
|
126
|
+
filters = subprocess.run(["ffmpeg", "-hide_banner", "-filters"], capture_output=True, text=True).stdout
|
|
127
|
+
encoders = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True).stdout
|
|
128
|
+
missing = [n for n in ("lut3d", "zoompan", "xfade") if f" {n} " not in filters]
|
|
129
|
+
missing += [n for n in ("libx264",) if f" {n} " not in encoders]
|
|
130
|
+
print(f"ffmpeg {(ver.split() + ['?', '?', '?'])[2]}")
|
|
131
|
+
if missing:
|
|
132
|
+
problems.append("ffmpeg 에 " + ", ".join(missing) + " 가 없다. libx264 가 들어간 빌드가 필요하다 (brew install ffmpeg)")
|
|
133
|
+
else:
|
|
134
|
+
print("ffmpeg 없음")
|
|
135
|
+
if fix and shutil.which("brew"):
|
|
136
|
+
print(" → brew install ffmpeg")
|
|
137
|
+
subprocess.run(["brew", "install", "ffmpeg"], check=False)
|
|
138
|
+
if not (shutil.which("ffmpeg") and shutil.which("ffprobe")):
|
|
139
|
+
problems.append("ffmpeg 설치 (macOS: brew install ffmpeg / ubuntu: apt install ffmpeg)")
|
|
140
|
+
|
|
141
|
+
if pbpage is None:
|
|
142
|
+
print(f"pbpage 없음 ({PB_LIB})")
|
|
143
|
+
problems.append(f"lib/pbpage.py (thuthi-browser 의 것과 같은 복사본) 를 찾지 못했다: {_PBPAGE_ERROR}")
|
|
144
|
+
pb_cli = shutil.which("parallel-browser")
|
|
145
|
+
print(f"parallel-browser {pb_cli or '없음'}")
|
|
146
|
+
if not pb_cli:
|
|
147
|
+
problems.append(f"parallel-browser 명령이 없다. thuthi:setup 스킬로 설치하거나 {PB_INSTALL_DOC} 를 따른다")
|
|
148
|
+
connected = False
|
|
149
|
+
if pb_cli:
|
|
150
|
+
st = subprocess.run([pb_cli, "status"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=40)
|
|
151
|
+
try:
|
|
152
|
+
daemon = json.loads(st.stdout)["daemon"]
|
|
153
|
+
connected = bool(daemon.get("connected"))
|
|
154
|
+
ua = daemon.get("userAgent") or ""
|
|
155
|
+
m = re.search(r"Edg/(\d+)", ua) or re.search(r"Chrome/(\d+)", ua)
|
|
156
|
+
name = ("Edge " if "Edg/" in ua else "Chrome ") + m.group(1) if m else "?"
|
|
157
|
+
print(f"브라우저 연결 {'됨 (' + name + ')' if connected else '안 됨'}")
|
|
158
|
+
except (ValueError, KeyError):
|
|
159
|
+
print("브라우저 연결 확인 실패")
|
|
160
|
+
print(" " + (st.stderr or st.stdout).strip()[-300:])
|
|
161
|
+
if not connected:
|
|
162
|
+
problems.append("parallel-browser 가 브라우저에 연결되지 않았다. Chrome/Edge 를 켜고 확장을 확인한다 "
|
|
163
|
+
f"({PB_INSTALL_DOC})")
|
|
164
|
+
|
|
165
|
+
if connected and pbpage is not None:
|
|
166
|
+
try:
|
|
167
|
+
info = _doctor_probe()
|
|
168
|
+
print(f"녹화 시험 {info['fps']:.0f} 프레임/초 (애니메이션 1.5초, 25 이상이면 충분), "
|
|
169
|
+
f"탭 상태 {'보임' if info['visible'] else '안 보임 (렌더가 멈춘다)'}")
|
|
170
|
+
if info["fps"] < 20:
|
|
171
|
+
problems.append(f"녹화 시험에서 초당 {info['fps']:.0f} 프레임밖에 오지 않았다. 브라우저가 바쁘거나 창이 "
|
|
172
|
+
"최소화돼 렌더가 멈췄을 수 있다")
|
|
173
|
+
dev = info["color_deviation"]
|
|
174
|
+
print(f"모니터 색 변환 최대 {dev:.0f}/255 "
|
|
175
|
+
+ ("(sRGB 와 같다, 보정 없음)" if dev <= COLOR_FIX_MIN_DEV else "(record · render 가 자동으로 sRGB 로 되돌린다)"))
|
|
176
|
+
except Exception as e: # noqa: BLE001 점검이라 무엇이 터졌든 알려 준다
|
|
177
|
+
print(f"녹화 시험 실패: {e}")
|
|
178
|
+
problems.append(f"parallel-browser 로 녹화 시험이 실패했다: {e}")
|
|
179
|
+
|
|
180
|
+
if problems:
|
|
181
|
+
print("\n해결해야 할 것:")
|
|
182
|
+
for p in problems:
|
|
183
|
+
print(" -", p)
|
|
184
|
+
return 1
|
|
185
|
+
print("\n준비 완료.")
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _doctor_probe() -> dict:
|
|
190
|
+
"""세션을 열어 애니메이션을 1.5초 녹화해 초당 프레임 수를 재고, 모니터 색 변환 폭을 잰 뒤 닫는다."""
|
|
191
|
+
tmp = Path(tempfile.mkdtemp(prefix="dv-doctor-"))
|
|
192
|
+
rec = None
|
|
193
|
+
try:
|
|
194
|
+
with pbpage.Browser("demo-video doctor", accept_dialogs=False) as b:
|
|
195
|
+
pg = b.new_page(viewport=(CAL_W, CAL_H), dpr=1)
|
|
196
|
+
pg.cdp("Emulation.setScrollbarsHidden", {"hidden": True})
|
|
197
|
+
_, cal = calibrate(pg, tmp, build=False)
|
|
198
|
+
pg.set_viewport(640, 400, 1)
|
|
199
|
+
set_html(pg, DOCTOR_ANIM_HTML)
|
|
200
|
+
rec = PbRecorder(pg, tmp / "frames", 640, 400)
|
|
201
|
+
rec.start()
|
|
202
|
+
time.sleep(1.5)
|
|
203
|
+
index = rec.stop()
|
|
204
|
+
return {"fps": index.get("received", 0) / 1.5,
|
|
205
|
+
"visible": all(v.get("visible") for v in index.get("visibility", [])),
|
|
206
|
+
"color_deviation": cal["deviation"]}
|
|
207
|
+
finally:
|
|
208
|
+
if rec:
|
|
209
|
+
rec.kill()
|
|
210
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
214
|
+
# parallel-browser 쪽 부품: 상태 표시 숨김 · 색 보정 · 녹화 · 시나리오용 page · 정적 PNG
|
|
215
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
216
|
+
# parallel-browser 는 세션 탭 페이지에 상태 표시(테두리 · 라벨 · [내가 하기])를 넣고, 이게 screencast 와
|
|
217
|
+
# screenshot 에 그대로 찍힌다. 녹화 · 렌더 탭에서는 새 문서마다 이 style 을 넣어 숨긴다. pbpage 의 hide_overlay 와
|
|
218
|
+
# 같은 규칙이지만 id 를 달리해, pbpage.screenshot(clean=True) 가 자기 style 을 걷어 갈 때 같이 지워지지 않게 한다.
|
|
219
|
+
HIDE_PB_ID = "__dv_hide_pb__"
|
|
220
|
+
HIDE_PB_JS = """(() => {
|
|
221
|
+
const ID = '%s', CSS = '#__parallel_browser_overlay__, [data-parallel-browser] { display: none !important; }';
|
|
222
|
+
const put = () => {
|
|
223
|
+
if (document.getElementById(ID)) return true;
|
|
224
|
+
const root = document.documentElement; if (!root) return false;
|
|
225
|
+
const st = document.createElement('style'); st.id = ID; st.textContent = CSS; root.appendChild(st); return true;
|
|
226
|
+
};
|
|
227
|
+
put();
|
|
228
|
+
// 문서 뼈대가 아직 없거나, 앱이 <html> 의 자식을 갈아 끼워도 다시 넣는다.
|
|
229
|
+
new MutationObserver(() => put()).observe(document, { childList: true, subtree: false });
|
|
230
|
+
const watchRoot = () => { if (document.documentElement) new MutationObserver(() => put()).observe(document.documentElement, { childList: true }); };
|
|
231
|
+
if (document.documentElement) watchRoot(); else document.addEventListener('readystatechange', watchRoot, { once: true });
|
|
232
|
+
})();""" % HIDE_PB_ID
|
|
233
|
+
UNHIDE_PB_JS = f"(() => {{ const st = document.getElementById('{HIDE_PB_ID}'); if (st) st.remove(); }})()"
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def set_html(pg, html: str) -> None:
|
|
237
|
+
"""Playwright 의 set_content 처럼 지금 탭의 문서를 html 로 바꾼다 (상태 표시 숨김 포함)."""
|
|
238
|
+
pg._call("evaluate", f"document.open(); document.write({json.dumps(html)}); document.close(); 0")
|
|
239
|
+
pg._call("evaluate", HIDE_PB_JS)
|
|
240
|
+
pg._call("evaluate", "(async () => { if (document.readyState !== 'complete') await new Promise(r => "
|
|
241
|
+
"addEventListener('load', r, { once: true })); await document.fonts.ready; return 0; })()")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def capture_png(pg, dst: Path, transparent: bool = False) -> Path:
|
|
245
|
+
"""지금 뷰포트를 PNG 로 찍는다. transparent 면 페이지가 칠하지 않은 곳이 투명하게 남는다
|
|
246
|
+
(Playwright 의 omit_background 와 같은 CDP 호출)."""
|
|
247
|
+
if transparent:
|
|
248
|
+
pg.cdp("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}})
|
|
249
|
+
try:
|
|
250
|
+
data = pg.cdp("Page.captureScreenshot", {"format": "png"})["data"]
|
|
251
|
+
finally:
|
|
252
|
+
if transparent:
|
|
253
|
+
pg.cdp("Emulation.setDefaultBackgroundColorOverride", {})
|
|
254
|
+
dst.write_bytes(base64.b64decode(data))
|
|
255
|
+
return dst
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# -- 색 보정 ---------------------------------------------------------------
|
|
259
|
+
# 사용자 브라우저는 CSS 의 sRGB 색을 모니터 색 공간으로 바꿔 그리고, screencast · screenshot 도 바뀐 값을 준다
|
|
260
|
+
# (2026-10-05 실측, LG ULTRAWIDE: #1e293b → (27,37,51), rgb(51,194,87) → (5,184,86)). 같은 탭에 알려진 색
|
|
261
|
+
# 16³ 개를 그려 찍으면 "sRGB → 찍힌 값" 표가 생기고, 이것을 거꾸로 푼 3D LUT 를 ffmpeg lut3d 로 걸면 sRGB 로 돌아온다.
|
|
262
|
+
CAL_N, CAL_PATCH, CAL_W, CAL_H = 16, 16, 1440, 900 # 단계 16 → 0,17,…,255 (정수 간격). 4096칸 × 16px
|
|
263
|
+
CAL_LUT_SIZE = 33
|
|
264
|
+
COLOR_FIX_MIN_DEV = 2.0 # 찍힌 값이 이보다 덜 벗어나면 (/255) 모니터가 sRGB 와 같다고 보고 보정하지 않는다
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _calibration_html() -> str:
|
|
268
|
+
return f"""<!doctype html><html><head><meta charset="utf-8">
|
|
269
|
+
<style>html,body{{margin:0;background:#000;overflow:hidden}}</style></head>
|
|
270
|
+
<body><canvas id="c" width="{CAL_W}" height="{CAL_H}" style="display:block"></canvas><script>
|
|
271
|
+
const N = {CAL_N}, P = {CAL_PATCH}, cols = Math.floor({CAL_W} / P), ctx = document.getElementById('c').getContext('2d');
|
|
272
|
+
let k = 0;
|
|
273
|
+
for (let b = 0; b < N; b++) for (let g = 0; g < N; g++) for (let r = 0; r < N; r++) {{
|
|
274
|
+
const s = 255 / (N - 1);
|
|
275
|
+
ctx.fillStyle = 'rgb(' + r * s + ',' + g * s + ',' + b * s + ')';
|
|
276
|
+
ctx.fillRect((k % cols) * P, Math.floor(k / cols) * P, P, P); k++;
|
|
277
|
+
}}
|
|
278
|
+
</script></body></html>"""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _measure_chart(png: Path) -> list[tuple[float, float, float]]:
|
|
282
|
+
"""보정판 PNG 에서 칸마다 가운데 8×8 의 평균색 (0~1). 순서는 r + N·g + N²·b."""
|
|
283
|
+
data = subprocess.run(["ffmpeg", "-v", "error", "-i", str(png), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
|
|
284
|
+
capture_output=True, check=True).stdout
|
|
285
|
+
if len(data) != CAL_W * CAL_H * 3:
|
|
286
|
+
raise RuntimeError(f"보정판 크기가 다르다 ({len(data)} 바이트, 기대 {CAL_W}×{CAL_H})")
|
|
287
|
+
cols, lo, hi = CAL_W // CAL_PATCH, CAL_PATCH // 4, CAL_PATCH - CAL_PATCH // 4
|
|
288
|
+
out = []
|
|
289
|
+
for k in range(CAL_N ** 3):
|
|
290
|
+
x0, y0 = (k % cols) * CAL_PATCH, (k // cols) * CAL_PATCH
|
|
291
|
+
r = g = b = c = 0
|
|
292
|
+
for y in range(y0 + lo, y0 + hi):
|
|
293
|
+
row = (y * CAL_W + x0) * 3
|
|
294
|
+
for x in range(lo, hi):
|
|
295
|
+
i = row + x * 3
|
|
296
|
+
r += data[i]; g += data[i + 1]; b += data[i + 2]; c += 1
|
|
297
|
+
out.append((r / c / 255, g / c / 255, b / c / 255))
|
|
298
|
+
return out
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _forward(meas: list, s: list) -> list:
|
|
302
|
+
"""sRGB s (0~1) 가 찍히면 어떤 값이 되는지, 보정판 표를 삼선형 보간한다."""
|
|
303
|
+
n = CAL_N
|
|
304
|
+
f = [min(max(v, 0.0), 1.0) * (n - 1) for v in s]
|
|
305
|
+
i = [min(int(v), n - 2) for v in f]
|
|
306
|
+
t = [f[j] - i[j] for j in range(3)]
|
|
307
|
+
res = [0.0, 0.0, 0.0]
|
|
308
|
+
for dz in (0, 1):
|
|
309
|
+
wz = t[2] if dz else 1 - t[2]
|
|
310
|
+
for dy in (0, 1):
|
|
311
|
+
wy = t[1] if dy else 1 - t[1]
|
|
312
|
+
for dx in (0, 1):
|
|
313
|
+
w = (t[0] if dx else 1 - t[0]) * wy * wz
|
|
314
|
+
if w:
|
|
315
|
+
m = meas[(i[0] + dx) + n * (i[1] + dy) + n * n * (i[2] + dz)]
|
|
316
|
+
res[0] += w * m[0]; res[1] += w * m[1]; res[2] += w * m[2]
|
|
317
|
+
return res
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _write_inverse_lut(meas: list, path: Path, size: int = CAL_LUT_SIZE) -> None:
|
|
321
|
+
"""찍힌 값 → 원래 sRGB 로 가는 3D LUT (.cube). 칸마다 고정점 반복으로 _forward 를 거꾸로 푼다.
|
|
322
|
+
|
|
323
|
+
모니터 색역 밖의 색은 한 채널이 0(또는 255)으로 잘려 들어온다. 그런 값에는 sRGB 해가 여럿이다.
|
|
324
|
+
0 에서 풀기 시작하면 잘린 채널이 0 인 해(가장 진한 색)를 골라, 그라디언트가 색역 밖으로 들어가는 자리에
|
|
325
|
+
경계가 또렷한 띠가 생긴다. 잘린 채널은 안쪽(0.25 / 0.75)에서 출발해 잘림이 막 시작되는 해를 고르게 한다.
|
|
326
|
+
실측: 정지 화면 PSNR 41.7 → 48.9dB, 띠가 거의 사라졌다."""
|
|
327
|
+
lo, hi = 0.5 / 255, 1 - 0.5 / 255
|
|
328
|
+
lines = [f"LUT_3D_SIZE {size}"]
|
|
329
|
+
for b in range(size):
|
|
330
|
+
for g in range(size):
|
|
331
|
+
for r in range(size):
|
|
332
|
+
m = (r / (size - 1), g / (size - 1), b / (size - 1))
|
|
333
|
+
s = [0.25 if v <= lo else 0.75 if v >= hi else v for v in m]
|
|
334
|
+
for _ in range(120):
|
|
335
|
+
f = _forward(meas, s)
|
|
336
|
+
e = (m[0] - f[0], m[1] - f[1], m[2] - f[2])
|
|
337
|
+
if max(abs(e[0]), abs(e[1]), abs(e[2])) < 0.05 / 255:
|
|
338
|
+
break
|
|
339
|
+
nxt = [min(max(s[j] + 0.9 * e[j], 0.0), 1.0) for j in range(3)]
|
|
340
|
+
moved = max(abs(nxt[0] - s[0]), abs(nxt[1] - s[1]), abs(nxt[2] - s[2]))
|
|
341
|
+
s = nxt
|
|
342
|
+
if moved < 0.01 / 255: # 더 못 간다 (색역 밖 목표)
|
|
343
|
+
break
|
|
344
|
+
lines.append(f"{s[0]:.6f} {s[1]:.6f} {s[2]:.6f}")
|
|
345
|
+
path.write_text("\n".join(lines) + "\n", encoding="ascii")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def calibrate(pg, tmpdir: Path, build: bool = True) -> tuple[Path | None, dict]:
|
|
349
|
+
"""지금 탭에 보정판을 그려 찍고, 모니터 색 변환이 있으면 역변환 LUT 를 만든다.
|
|
350
|
+
돌려주는 것: (LUT 경로 또는 None, {"deviation": 최대 편차(/255), "lut": bool}). 끝나면 뷰포트는 보정판 크기다."""
|
|
351
|
+
pg.set_viewport(CAL_W, CAL_H, 1)
|
|
352
|
+
set_html(pg, _calibration_html())
|
|
353
|
+
time.sleep(0.1)
|
|
354
|
+
png = capture_png(pg, tmpdir / "color-chart.png")
|
|
355
|
+
meas = _measure_chart(png)
|
|
356
|
+
n = CAL_N
|
|
357
|
+
dev = max(abs(meas[r + n * g + n * n * b][j] - (r, g, b)[j] / (n - 1)) * 255
|
|
358
|
+
for b in range(n) for g in range(n) for r in range(n) for j in range(3))
|
|
359
|
+
info = {"deviation": round(dev, 1), "lut": False}
|
|
360
|
+
if not build or dev <= COLOR_FIX_MIN_DEV:
|
|
361
|
+
return None, info
|
|
362
|
+
cube = tmpdir / "color-fix.cube"
|
|
363
|
+
_write_inverse_lut(meas, cube)
|
|
364
|
+
info["lut"] = True
|
|
365
|
+
return cube, info
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _lut_filter(cube: Path) -> str:
|
|
369
|
+
return "lut3d=file='%s':interp=tetrahedral" % str(cube).replace("'", r"'\''")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def apply_lut_png(png: Path, cube: Path) -> None:
|
|
373
|
+
"""PNG 한 장에 보정 LUT 를 건다 (알파는 그대로)."""
|
|
374
|
+
tmp = png.with_name(png.stem + ".fixed.png")
|
|
375
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(png), "-vf", _lut_filter(cube), str(tmp)], check=True)
|
|
376
|
+
tmp.replace(png)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# -- 녹화 (parallel-browser 녹화 → 25fps CFR) -------------------------------
|
|
380
|
+
# 녹화는 parallel-browser 의 것 (s.startRecording / s.stopRecording) 을 그대로 쓴다. 데몬이 screencast 프레임을 받는 대로
|
|
381
|
+
# 영상으로 구워, 찍는 동안 디스크에는 그 영상만 있다 (예전에는 이 파일이 프레임을 따로 받아 JPEG 로 쌓았다가 끝에 구웠다.
|
|
382
|
+
# 2026-11-25 실측 24초 · 1920×1080: JPEG 134MB 대 영상 4MB). 시나리오(파이썬)가 무엇을 하든 프레임 수신은 데몬에서 따로 돈다.
|
|
383
|
+
# 받은 영상은 프레임마다 도착 시각을 가진 가변 프레임 영상이고, assemble_cfr 가 고정 25fps 로 바꾼다.
|
|
384
|
+
RECORD_FPS = 50 # 최종 25fps 의 두 배로 받는다. 칸마다 프레임이 둘쯤 들어와, 25fps 로 고를 때 칸이 비거나 겹치지 않는다
|
|
385
|
+
RECORD_CRF = 14 # 중간 원본이라 넉넉히. assemble_cfr (crf 10) 와 render (crf 22) 가 다시 굽는다
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class PbRecorder:
|
|
389
|
+
"""한 탭의 parallel-browser 녹화. 시작 · 끝과, 지금 찍히는 장면 한 장 (frame) 을 준다."""
|
|
390
|
+
|
|
391
|
+
def __init__(self, pg, workdir: Path, width: int, height: int):
|
|
392
|
+
self.pg = pg
|
|
393
|
+
self.dir = Path(workdir)
|
|
394
|
+
self.raw = self.dir.parent / "recorded.mp4"
|
|
395
|
+
self.width, self.height = width, height
|
|
396
|
+
self.wall0 = self.mono0 = None
|
|
397
|
+
self.active = False
|
|
398
|
+
|
|
399
|
+
def start(self) -> tuple[float, float]:
|
|
400
|
+
"""녹화를 켠다. 돌려주는 (monotonic, wall) 시각이 영상 타임라인의 0 이다."""
|
|
401
|
+
mono0, wall0 = time.monotonic(), time.time()
|
|
402
|
+
self.pg._call("startRecording", str(self.dir),
|
|
403
|
+
{"width": self.width, "height": self.height, "fps": RECORD_FPS, "crf": RECORD_CRF})
|
|
404
|
+
self.active = True
|
|
405
|
+
self.mono0, self.wall0 = mono0, wall0
|
|
406
|
+
return mono0, wall0
|
|
407
|
+
|
|
408
|
+
def frame(self, dst: Path) -> dict:
|
|
409
|
+
"""지금 영상에 찍히고 있는 장면 (브라우저가 마지막으로 보낸 프레임) 을 dst 에 JPEG 로 쓴다."""
|
|
410
|
+
return self.pg._call("recordingFrame", str(dst))
|
|
411
|
+
|
|
412
|
+
def stop(self) -> dict:
|
|
413
|
+
t_end = time.time()
|
|
414
|
+
r = self.pg._call("stopRecording", str(self.raw), timeout=150) or {}
|
|
415
|
+
self.active = False
|
|
416
|
+
if r.get("encoding"):
|
|
417
|
+
r = self.pg._call("waitForRecording", str(self.raw), timeout=1900) or {}
|
|
418
|
+
if not r.get("mp4"):
|
|
419
|
+
raise RuntimeError("녹화 프레임을 하나도 받지 못했다. doctor 로 브라우저 연결과 녹화 시험을 확인한다")
|
|
420
|
+
r.update({"wall0": self.wall0, "t_end": t_end, "raw": str(self.raw)})
|
|
421
|
+
return r
|
|
422
|
+
|
|
423
|
+
def kill(self) -> None:
|
|
424
|
+
"""오류 경로용. 세션이 닫히기 전에 불러 녹화를 멈춘다 (닫힌 뒤면 데몬이 찍던 것을 따로 남긴다)."""
|
|
425
|
+
if self.active:
|
|
426
|
+
self.active = False
|
|
427
|
+
try:
|
|
428
|
+
self.pg._call("stopRecording", timeout=20)
|
|
429
|
+
except Exception: # noqa: BLE001 이미 닫혔으면 할 일이 없다
|
|
430
|
+
pass
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def assemble_cfr(index: dict, out: Path, width: int, height: int,
|
|
434
|
+
cube: Path | None = None, fps: int = FPS) -> dict:
|
|
435
|
+
"""녹화 영상을 고정 fps 로 바꾼다: 칸 k (영상 시각 k/fps) 마다 그 시각까지 받은 마지막 프레임.
|
|
436
|
+
정지 구간은 같은 프레임이 이어지고, 움직이는 구간은 칸마다 새 프레임이 들어간다.
|
|
437
|
+
영상의 0초는 녹화를 켠 순간 (wall0) 이다. 첫 프레임이 그보다 늦게 왔으면 그만큼 첫 장면으로 채운다."""
|
|
438
|
+
n = max(1, math.ceil((index["t_end"] - index["wall0"]) * fps))
|
|
439
|
+
shift = float(index.get("t0") or index["wall0"]) - index["wall0"]
|
|
440
|
+
vf = [f"setpts=PTS+({shift:.6f})/TB", f"fps={fps}:start_time=0", "tpad=stop=-1:stop_mode=clone",
|
|
441
|
+
f"crop='min(iw,{width})':'min(ih,{height})':0:0", f"pad={width}:{height}:0:0:color=gray"]
|
|
442
|
+
if cube:
|
|
443
|
+
# 녹화 영상은 일반 범위 BT.601 이다 (parallel-browser 가 JPEG 를 그렇게 바꿔 굽는다). 보정은 RGB 에서 한다.
|
|
444
|
+
vf += ["scale=in_range=tv:in_color_matrix=bt601", "format=gbrp", _lut_filter(cube)]
|
|
445
|
+
vf += ["scale=out_range=tv:out_color_matrix=bt601", "format=yuv420p"]
|
|
446
|
+
if out.suffix.lower() == ".webm":
|
|
447
|
+
codec = ["-c:v", "libvpx-vp9", "-crf", "16", "-b:v", "0", "-deadline", "good", "-cpu-used", "4", "-row-mt", "1"]
|
|
448
|
+
else: # 중간 파일이라 화질을 넉넉히 (crf 10). render 가 최종 crf 22 로 다시 굽는다
|
|
449
|
+
codec = ["-c:v", "libx264", "-preset", "fast", "-crf", "10", "-movflags", "+faststart"]
|
|
450
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
451
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(index["raw"]),
|
|
452
|
+
"-vf", ",".join(vf), "-fps_mode", "cfr", "-r", str(fps), "-frames:v", str(n),
|
|
453
|
+
*codec, "-pix_fmt", "yuv420p", str(out)], check=True)
|
|
454
|
+
return {"slots": n, "distinct_frames": index.get("frames", 0), "received": index.get("received", 0),
|
|
455
|
+
"seconds": round(n / fps, 2)}
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# -- 시나리오용 page (Playwright 동기 API 의 일부를 같은 이름으로) ------------------------
|
|
459
|
+
CLICK_GLIDE_SEC = 0.38 # 클릭 전에 커서가 대상까지 미끄러져 가는 시간 (cursor.js 의 transition 과 맞춘다)
|
|
460
|
+
TYPE_CHAR_MS = 55 # fill 을 타이핑처럼 보일 때 글자 간격(ms)
|
|
461
|
+
TYPE_MAX_SEC = 1.5 # 긴 문장도 이 시간 안에 다 친다
|
|
462
|
+
_LEAD_COMMENTS = re.compile(r"^\s*(?:(?://[^\n]*(?:\n|$)|/\*.*?\*/)\s*)*", re.S)
|
|
463
|
+
_FN_RE = re.compile(r"^\s*(async\s+)?(function\b|\([^()]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)")
|
|
464
|
+
_AMBIGUOUS = re.compile(r"matches \d+ elements")
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _target(sel: str) -> str:
|
|
468
|
+
"""Playwright 선택자 → parallel-browser 선택자. CSS · text= · role= · xpath= · >> nth= 는 그대로 통한다."""
|
|
469
|
+
s = sel.strip()
|
|
470
|
+
if s.startswith("//") or s.startswith("(//") or s.startswith(".."):
|
|
471
|
+
return "xpath=" + s
|
|
472
|
+
return s
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _js_call(expr: str, arg) -> str:
|
|
476
|
+
"""Playwright 의 evaluate 처럼, 함수 문자열이면 arg 를 넣어 부르고 아니면 식으로 계산한다 (앞 주석은 건너뛴다)."""
|
|
477
|
+
body = _LEAD_COMMENTS.sub("", expr, count=1).rstrip().rstrip(";").rstrip()
|
|
478
|
+
if _FN_RE.match(body): # overlay.js 처럼 `};` 로 끝나는 함수도 Playwright 는 받아 줬다
|
|
479
|
+
return f"({body})({json.dumps(arg)})"
|
|
480
|
+
return expr
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class ScenarioMouse:
|
|
484
|
+
def __init__(self, page: "ScenarioPage"):
|
|
485
|
+
self.p = page
|
|
486
|
+
self._down = False
|
|
487
|
+
|
|
488
|
+
def move(self, x, y, steps: int = 1):
|
|
489
|
+
self.p._call("mouse.move", x, y, {"steps": steps, "button": "left" if self._down else "none"})
|
|
490
|
+
|
|
491
|
+
def down(self, button: str = "left", click_count: int = 1):
|
|
492
|
+
self._down = True
|
|
493
|
+
self.p._call("mouse.down", {"button": button, "clickCount": click_count})
|
|
494
|
+
|
|
495
|
+
def up(self, button: str = "left", click_count: int = 1):
|
|
496
|
+
self._down = False
|
|
497
|
+
self.p._call("mouse.up", {"button": button, "clickCount": click_count})
|
|
498
|
+
|
|
499
|
+
def click(self, x, y, button: str = "left", click_count: int = 1, delay=None):
|
|
500
|
+
self.p._call("mouse.click", x, y, {"button": button, "clickCount": click_count})
|
|
501
|
+
|
|
502
|
+
def dblclick(self, x, y, button: str = "left"):
|
|
503
|
+
self.click(x, y, button=button, click_count=2)
|
|
504
|
+
|
|
505
|
+
def wheel(self, delta_x, delta_y):
|
|
506
|
+
self.p._call("mouse.wheel", delta_x, delta_y)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
class ScenarioKeyboard:
|
|
510
|
+
def __init__(self, page: "ScenarioPage"):
|
|
511
|
+
self.p = page
|
|
512
|
+
|
|
513
|
+
def press(self, key: str, delay=None):
|
|
514
|
+
self.p._call("keyboard.press", "Space" if key == " " else key)
|
|
515
|
+
|
|
516
|
+
def down(self, key: str):
|
|
517
|
+
self.p._call("keyboard.down", key)
|
|
518
|
+
|
|
519
|
+
def up(self, key: str):
|
|
520
|
+
self.p._call("keyboard.up", key)
|
|
521
|
+
|
|
522
|
+
def insert_text(self, text: str):
|
|
523
|
+
self.p._call("keyboard.insertText", text)
|
|
524
|
+
|
|
525
|
+
def type(self, text: str, delay: float = 0):
|
|
526
|
+
"""한 글자씩 친다. 영문 · 숫자 · 기호는 실제 키 이벤트로, 한글 등은 입력 이벤트로 (Playwright 와 같다)."""
|
|
527
|
+
for ch in str(text):
|
|
528
|
+
if ch == "\n":
|
|
529
|
+
self.press("Enter")
|
|
530
|
+
elif ch == " ":
|
|
531
|
+
self.press("Space")
|
|
532
|
+
elif " " < ch <= "~" and ch != "+":
|
|
533
|
+
self.press(ch)
|
|
534
|
+
else:
|
|
535
|
+
self.insert_text(ch)
|
|
536
|
+
if delay:
|
|
537
|
+
time.sleep(delay / 1000)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
class ScenarioLocator:
|
|
541
|
+
"""Playwright Locator 의 자주 쓰는 일부. 선택자는 parallel-browser 문법 (CSS · text= · role= · label= · xpath=)."""
|
|
542
|
+
|
|
543
|
+
def __init__(self, page: "ScenarioPage", sel: str, nth: int | None = None):
|
|
544
|
+
self.page, self.sel, self.idx = page, _target(sel), nth
|
|
545
|
+
|
|
546
|
+
def _t(self) -> str:
|
|
547
|
+
return self.sel + (f" >> nth={self.idx}" if self.idx is not None else "")
|
|
548
|
+
|
|
549
|
+
@property
|
|
550
|
+
def first(self) -> "ScenarioLocator":
|
|
551
|
+
return ScenarioLocator(self.page, self.sel, 0)
|
|
552
|
+
|
|
553
|
+
@property
|
|
554
|
+
def last(self) -> "ScenarioLocator":
|
|
555
|
+
return ScenarioLocator(self.page, self.sel, -1)
|
|
556
|
+
|
|
557
|
+
def nth(self, i: int) -> "ScenarioLocator":
|
|
558
|
+
return ScenarioLocator(self.page, self.sel, i)
|
|
559
|
+
|
|
560
|
+
def locator(self, sub: str) -> "ScenarioLocator":
|
|
561
|
+
return ScenarioLocator(self.page, f"{self.sel} {sub}") # CSS 자손 선택자로만 잇는다
|
|
562
|
+
|
|
563
|
+
def _css(self, what: str) -> str:
|
|
564
|
+
if re.match(r"^(text|role|label|xpath|frame)=|^@\d", self.sel):
|
|
565
|
+
raise NotImplementedError(f"locator({self.sel!r}).{what} 는 CSS 선택자에서만 된다")
|
|
566
|
+
return re.sub(r"^css=", "", self.sel)
|
|
567
|
+
|
|
568
|
+
def click(self, **kw):
|
|
569
|
+
return self.page._click(self._t(), strict=True, **kw)
|
|
570
|
+
|
|
571
|
+
def dblclick(self, **kw):
|
|
572
|
+
return self.page._click(self._t(), strict=True, click_count=2, **kw)
|
|
573
|
+
|
|
574
|
+
def fill(self, value, **kw):
|
|
575
|
+
return self.page._fill(self._t(), value, strict=True, **kw)
|
|
576
|
+
|
|
577
|
+
def press(self, key: str, **kw):
|
|
578
|
+
self.page._call("press", self._t(), key)
|
|
579
|
+
|
|
580
|
+
def press_sequentially(self, text: str, delay: float = 0, **kw):
|
|
581
|
+
self.page._call("focus", self._t())
|
|
582
|
+
self.page.keyboard.type(text, delay=delay)
|
|
583
|
+
|
|
584
|
+
type = press_sequentially
|
|
585
|
+
|
|
586
|
+
def hover(self, **kw):
|
|
587
|
+
self.page._call("hover", self._t(), {"timeout": int(kw.get("timeout") or 10000)})
|
|
588
|
+
|
|
589
|
+
def focus(self, **kw):
|
|
590
|
+
self.page._call("focus", self._t())
|
|
591
|
+
|
|
592
|
+
def check(self, **kw):
|
|
593
|
+
self.page._call("check", self._t())
|
|
594
|
+
|
|
595
|
+
def uncheck(self, **kw):
|
|
596
|
+
self.page._call("uncheck", self._t())
|
|
597
|
+
|
|
598
|
+
def select_option(self, value, **kw):
|
|
599
|
+
return self.page._call("select", self._t(), value)
|
|
600
|
+
|
|
601
|
+
def inner_text(self, **kw) -> str:
|
|
602
|
+
return self.page._call("text", self._t())
|
|
603
|
+
|
|
604
|
+
text_content = inner_text
|
|
605
|
+
|
|
606
|
+
def wait_for(self, state: str = "visible", timeout=None):
|
|
607
|
+
ms = int(timeout or 30000)
|
|
608
|
+
self.page._call("waitFor", self._t(), {"state": state, "timeout": ms}, timeout=ms / 1000 + 10)
|
|
609
|
+
|
|
610
|
+
def count(self) -> int:
|
|
611
|
+
return self.page.evaluate("(s) => document.querySelectorAll(s).length", self._css("count()"))
|
|
612
|
+
|
|
613
|
+
def is_visible(self, **kw) -> bool:
|
|
614
|
+
return bool(self.page.evaluate(
|
|
615
|
+
"(a) => { const e = document.querySelectorAll(a.s)[a.i < 0 ? document.querySelectorAll(a.s).length + a.i : a.i];"
|
|
616
|
+
" return !!e && e.checkVisibility() && e.getClientRects().length > 0; }",
|
|
617
|
+
{"s": self._css("is_visible()"), "i": self.idx or 0}))
|
|
618
|
+
|
|
619
|
+
def bounding_box(self, **kw):
|
|
620
|
+
return self.page.evaluate(
|
|
621
|
+
"(a) => { const all = document.querySelectorAll(a.s); const e = all[a.i < 0 ? all.length + a.i : a.i];"
|
|
622
|
+
" if (!e) return null; const r = e.getBoundingClientRect();"
|
|
623
|
+
" return { x: r.x, y: r.y, width: r.width, height: r.height }; }",
|
|
624
|
+
{"s": self._css("bounding_box()"), "i": self.idx or 0})
|
|
625
|
+
|
|
626
|
+
def get_attribute(self, name: str, **kw):
|
|
627
|
+
return self.page.evaluate(
|
|
628
|
+
"(a) => { const all = document.querySelectorAll(a.s); const e = all[a.i < 0 ? all.length + a.i : a.i];"
|
|
629
|
+
" return e ? e.getAttribute(a.n) : null; }",
|
|
630
|
+
{"s": self._css("get_attribute()"), "i": self.idx or 0, "n": name})
|
|
631
|
+
|
|
632
|
+
def input_value(self, **kw):
|
|
633
|
+
return self.page.evaluate(
|
|
634
|
+
"(a) => { const all = document.querySelectorAll(a.s); const e = all[a.i < 0 ? all.length + a.i : a.i];"
|
|
635
|
+
" return e ? e.value : null; }", {"s": self._css("input_value()"), "i": self.idx or 0})
|
|
636
|
+
|
|
637
|
+
def scroll_into_view_if_needed(self, **kw):
|
|
638
|
+
self.page._call("scroll", self._t())
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
class ScenarioPage:
|
|
642
|
+
"""시나리오가 받는 page. Playwright 동기 Page 의 자주 쓰는 메서드를 같은 이름 · 같은 단위(ms)로 흉내 내고
|
|
643
|
+
parallel-browser (pbpage) 로 실행한다. click 은 커서가 대상까지 미끄러져 간 뒤 누르고, fill 은 한 글자씩 친다.
|
|
644
|
+
없는 기능은 page.pb (pbpage.Page) · page.cdp(...) 로 직접 부른다."""
|
|
645
|
+
|
|
646
|
+
def __init__(self, pb_page):
|
|
647
|
+
self.pb = pb_page
|
|
648
|
+
self.mouse = ScenarioMouse(self)
|
|
649
|
+
self.keyboard = ScenarioKeyboard(self)
|
|
650
|
+
|
|
651
|
+
def __getattr__(self, name):
|
|
652
|
+
raise AttributeError(f"demo-video 의 page 에는 '{name}' 이 없다. Playwright 의 일부만 흉내 낸다. "
|
|
653
|
+
"page.pb (pbpage.Page) 나 page.cdp(method, params) 로 직접 부른다")
|
|
654
|
+
|
|
655
|
+
def _call(self, path, *args, timeout: float = 60):
|
|
656
|
+
return self.pb._call(path, *args, timeout=timeout)
|
|
657
|
+
|
|
658
|
+
def cdp(self, method: str, params: dict | None = None):
|
|
659
|
+
return self.pb.cdp(method, params)
|
|
660
|
+
|
|
661
|
+
# -- 상태
|
|
662
|
+
@property
|
|
663
|
+
def viewport_size(self):
|
|
664
|
+
return self.pb.viewport_size
|
|
665
|
+
|
|
666
|
+
def set_viewport_size(self, size: dict):
|
|
667
|
+
# 녹화 중이면 record 가 정한 축소 배율을 그대로 쓴다. pb.set_viewport 로 바꾸면 배율이 풀리고 입력 배율만 남아
|
|
668
|
+
# 그 뒤 클릭이 빗나간다 (2026-10-09 실측). 녹화 프레임은 처음 크기 그대로라 그보다 크게 바꾸면 잘린다.
|
|
669
|
+
sc = getattr(self.pb, "view_scale", None)
|
|
670
|
+
if sc:
|
|
671
|
+
set_view(self.pb, size["width"], size["height"], sc)
|
|
672
|
+
else:
|
|
673
|
+
self.pb.set_viewport(size["width"], size["height"], 1)
|
|
674
|
+
|
|
675
|
+
@property
|
|
676
|
+
def url(self) -> str:
|
|
677
|
+
return self._call("url")
|
|
678
|
+
|
|
679
|
+
def title(self) -> str:
|
|
680
|
+
return self._call("title")
|
|
681
|
+
|
|
682
|
+
def content(self) -> str:
|
|
683
|
+
return self._call("content")
|
|
684
|
+
|
|
685
|
+
# -- 이동
|
|
686
|
+
def goto(self, url: str, wait_until: str = "load", timeout=None, **kw):
|
|
687
|
+
mode = {"networkidle": "networkidle", "commit": "none"}.get(wait_until or "load", "load")
|
|
688
|
+
self.pb.goto(url, wait_until=mode, timeout=(timeout or 30000) / 1000)
|
|
689
|
+
|
|
690
|
+
def reload(self, **kw):
|
|
691
|
+
self._call("reload")
|
|
692
|
+
|
|
693
|
+
def go_back(self, **kw):
|
|
694
|
+
self._call("back")
|
|
695
|
+
|
|
696
|
+
def go_forward(self, **kw):
|
|
697
|
+
self._call("forward")
|
|
698
|
+
|
|
699
|
+
# -- 읽기 · 기다리기
|
|
700
|
+
def evaluate(self, expression: str, arg=None):
|
|
701
|
+
return self._call("evaluate", _js_call(expression, arg))
|
|
702
|
+
|
|
703
|
+
def wait_for_timeout(self, ms: float):
|
|
704
|
+
time.sleep(ms / 1000)
|
|
705
|
+
|
|
706
|
+
def wait_for_function(self, expression: str, arg=None, timeout=None, polling=None):
|
|
707
|
+
"""참이 될 때까지 0.1초마다 확인한다. 리로드 중 예외는 삼킨다. 시간이 넘으면 TimeoutError."""
|
|
708
|
+
ms = 30000 if timeout is None else float(timeout)
|
|
709
|
+
until = time.monotonic() + ms / 1000
|
|
710
|
+
while True:
|
|
711
|
+
try:
|
|
712
|
+
v = self.evaluate(expression, arg)
|
|
713
|
+
if v:
|
|
714
|
+
return v
|
|
715
|
+
except pbpage.PBError:
|
|
716
|
+
pass
|
|
717
|
+
if time.monotonic() > until:
|
|
718
|
+
raise TimeoutError(f"wait_for_function {ms:g}ms 초과: {expression[:120]}")
|
|
719
|
+
time.sleep(0.1)
|
|
720
|
+
|
|
721
|
+
def wait_for_selector(self, selector: str, state: str = "visible", timeout=None):
|
|
722
|
+
ms = int(timeout or 30000)
|
|
723
|
+
self._call("waitFor", _target(selector), {"state": state, "timeout": ms}, timeout=ms / 1000 + 10)
|
|
724
|
+
|
|
725
|
+
def wait_for_load_state(self, state: str = "load", timeout=None):
|
|
726
|
+
ms = int(timeout or 30000)
|
|
727
|
+
if state == "networkidle":
|
|
728
|
+
self._call("waitForNetworkIdle", {"timeout": ms}, timeout=ms / 1000 + 10)
|
|
729
|
+
else:
|
|
730
|
+
self._call("waitForLoad", {"timeout": ms}, timeout=ms / 1000 + 10)
|
|
731
|
+
|
|
732
|
+
def wait_for_url(self, url: str, timeout=None):
|
|
733
|
+
ms = int(timeout or 30000)
|
|
734
|
+
self._call("waitForURL", url, {"timeout": ms}, timeout=ms / 1000 + 10)
|
|
735
|
+
|
|
736
|
+
def inner_text(self, selector: str, **kw) -> str:
|
|
737
|
+
return self._call("text", _target(selector))
|
|
738
|
+
|
|
739
|
+
text_content = inner_text
|
|
740
|
+
|
|
741
|
+
def get_attribute(self, selector: str, name: str, **kw):
|
|
742
|
+
return self.locator(selector).get_attribute(name)
|
|
743
|
+
|
|
744
|
+
def input_value(self, selector: str, **kw):
|
|
745
|
+
return self.locator(selector).input_value()
|
|
746
|
+
|
|
747
|
+
def is_visible(self, selector: str, **kw) -> bool:
|
|
748
|
+
return self.locator(selector).is_visible()
|
|
749
|
+
|
|
750
|
+
def locator(self, selector: str) -> ScenarioLocator:
|
|
751
|
+
return ScenarioLocator(self, selector)
|
|
752
|
+
|
|
753
|
+
def get_by_text(self, text: str, exact: bool = False) -> ScenarioLocator:
|
|
754
|
+
return ScenarioLocator(self, f"text={text}")
|
|
755
|
+
|
|
756
|
+
def get_by_role(self, role: str, name: str | None = None, **kw) -> ScenarioLocator:
|
|
757
|
+
return ScenarioLocator(self, f'role={role}' + (f'[name={json.dumps(name, ensure_ascii=False)}]' if name else ""))
|
|
758
|
+
|
|
759
|
+
def get_by_label(self, text: str, **kw) -> ScenarioLocator:
|
|
760
|
+
return ScenarioLocator(self, f"label={text}")
|
|
761
|
+
|
|
762
|
+
get_by_placeholder = get_by_label # parallel-browser 의 label= 은 placeholder 도 찾는다
|
|
763
|
+
|
|
764
|
+
def get_by_test_id(self, test_id: str) -> ScenarioLocator:
|
|
765
|
+
return ScenarioLocator(self, f'[data-testid={json.dumps(test_id)}]')
|
|
766
|
+
|
|
767
|
+
def screenshot(self, path: str | None = None, full_page: bool = False, **kw):
|
|
768
|
+
r = self._call("screenshot", str(path) if path else None, {"fullPage": full_page}, timeout=40)
|
|
769
|
+
return r
|
|
770
|
+
|
|
771
|
+
# -- 조작 (커서 글라이드 · 타이핑 연출 포함)
|
|
772
|
+
def _with_fallback(self, fn, target: str, strict: bool):
|
|
773
|
+
"""Playwright 의 page.click(선택자) 는 여러 개가 맞으면 첫 번째를 쓴다. parallel-browser 는 엄격하므로
|
|
774
|
+
page.* 에서만 '여러 개' 오류가 나면 첫 번째로 다시 한다 (locator 는 Playwright 도 엄격하다)."""
|
|
775
|
+
try:
|
|
776
|
+
return fn(target)
|
|
777
|
+
except pbpage.PBError as e:
|
|
778
|
+
if strict or ">> nth=" in target or not _AMBIGUOUS.search(str(e)):
|
|
779
|
+
raise
|
|
780
|
+
return fn(target + " >> nth=0")
|
|
781
|
+
|
|
782
|
+
def _glide(self, target: str, timeout_ms: int) -> None:
|
|
783
|
+
"""대상 가운데로 마우스를 한 번에 옮긴다. cursor.js 의 커서가 CSS transition 으로 미끄러져 가는 동안 기다린다."""
|
|
784
|
+
try:
|
|
785
|
+
self._call("hover", target, {"timeout": timeout_ms})
|
|
786
|
+
time.sleep(CLICK_GLIDE_SEC)
|
|
787
|
+
except pbpage.PBError:
|
|
788
|
+
pass # 대상이 없으면 이어지는 click 이 제 오류를 낸다
|
|
789
|
+
|
|
790
|
+
def _click(self, target: str, strict: bool = False, timeout=None, button: str = "left",
|
|
791
|
+
click_count: int = 1, **kw):
|
|
792
|
+
ms = int(timeout or 30000)
|
|
793
|
+
|
|
794
|
+
def go(t):
|
|
795
|
+
self._glide(t, min(ms, 10000))
|
|
796
|
+
return self._call("click", t, {"button": button, "clickCount": click_count, "timeout": ms},
|
|
797
|
+
timeout=ms / 1000 + 10)
|
|
798
|
+
return self._with_fallback(go, target, strict)
|
|
799
|
+
|
|
800
|
+
def click(self, selector: str, **kw):
|
|
801
|
+
return self._click(_target(selector), **kw)
|
|
802
|
+
|
|
803
|
+
def dblclick(self, selector: str, **kw):
|
|
804
|
+
return self._click(_target(selector), click_count=2, **kw)
|
|
805
|
+
|
|
806
|
+
def hover(self, selector: str, timeout=None, **kw):
|
|
807
|
+
self._with_fallback(lambda t: self._call("hover", t, {"timeout": int(timeout or 10000)}), _target(selector), False)
|
|
808
|
+
|
|
809
|
+
def focus(self, selector: str, **kw):
|
|
810
|
+
self._with_fallback(lambda t: self._call("focus", t), _target(selector), False)
|
|
811
|
+
|
|
812
|
+
def press(self, selector: str, key: str, **kw):
|
|
813
|
+
self._with_fallback(lambda t: self._call("press", t, key), _target(selector), False)
|
|
814
|
+
|
|
815
|
+
def type(self, selector: str, text: str, delay: float = 0, **kw):
|
|
816
|
+
self.focus(selector)
|
|
817
|
+
self.keyboard.type(text, delay=delay)
|
|
818
|
+
|
|
819
|
+
def check(self, selector: str, **kw):
|
|
820
|
+
self._call("check", _target(selector))
|
|
821
|
+
|
|
822
|
+
def uncheck(self, selector: str, **kw):
|
|
823
|
+
self._call("uncheck", _target(selector))
|
|
824
|
+
|
|
825
|
+
def select_option(self, selector: str, value, **kw):
|
|
826
|
+
return self._call("select", _target(selector), value)
|
|
827
|
+
|
|
828
|
+
def _fill(self, target: str, value, strict: bool = False, force: bool = False, **kw):
|
|
829
|
+
"""글자를 한 글자씩 친다. 무엇을 입력했는지 영상에 보이게. 길면 전체 TYPE_MAX_SEC 안에 끝낸다."""
|
|
830
|
+
text = str(value)
|
|
831
|
+
|
|
832
|
+
def plain(t):
|
|
833
|
+
return self._call("fill", t, text)
|
|
834
|
+
if not text or force or len(text) > 200:
|
|
835
|
+
return self._with_fallback(plain, target, strict)
|
|
836
|
+
|
|
837
|
+
def typed(t):
|
|
838
|
+
try:
|
|
839
|
+
self._glide(t, 10000)
|
|
840
|
+
self._call("click", t, {"timeout": 10000}, timeout=20)
|
|
841
|
+
# 비우기는 내부적으로 선택 후 지우기다. 그 사이 키 배지를 끈다.
|
|
842
|
+
self._call("evaluate", "window.__dvKeyMute = true")
|
|
843
|
+
self._call("fill", t, "")
|
|
844
|
+
self._call("evaluate", "window.__dvKeyMute = false")
|
|
845
|
+
self.keyboard.type(text, delay=min(TYPE_CHAR_MS, int(TYPE_MAX_SEC * 1000 / len(text))))
|
|
846
|
+
time.sleep(0.25)
|
|
847
|
+
except pbpage.PBError as e:
|
|
848
|
+
try:
|
|
849
|
+
self._call("evaluate", "window.__dvKeyMute = false")
|
|
850
|
+
except pbpage.PBError:
|
|
851
|
+
pass
|
|
852
|
+
if _AMBIGUOUS.search(str(e)):
|
|
853
|
+
raise
|
|
854
|
+
return plain(t)
|
|
855
|
+
return self._with_fallback(typed, target, strict)
|
|
856
|
+
|
|
857
|
+
def fill(self, selector: str, value, **kw):
|
|
858
|
+
return self._fill(_target(selector), value, **kw)
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
# -- 정적 PNG (창 프레임 · 줌 자막 · 타이틀) ---------------------------------------
|
|
862
|
+
class PngRenderer:
|
|
863
|
+
"""render 가 쓰는 PNG 들을 parallel-browser 탭 하나에서 찍는다. 처음 쓸 때 세션을 열고 색 보정을 재며,
|
|
864
|
+
close() 에서 세션을 닫는다 (with 로 쓰면 오류가 나도 닫힌다)."""
|
|
865
|
+
|
|
866
|
+
def __init__(self, color_fix: bool = True):
|
|
867
|
+
self.color_fix = color_fix
|
|
868
|
+
self.b = self.pg = self.cube = None
|
|
869
|
+
self.color: dict | None = None
|
|
870
|
+
self.tmp = Path(tempfile.mkdtemp(prefix="dv-png-"))
|
|
871
|
+
|
|
872
|
+
def _open(self) -> None:
|
|
873
|
+
self.b = pbpage.Browser("demo-video render", accept_dialogs=False)
|
|
874
|
+
self.pg = self.b.new_page(viewport=(CAL_W, CAL_H), dpr=1)
|
|
875
|
+
self.pg.cdp("Emulation.setScrollbarsHidden", {"hidden": True})
|
|
876
|
+
self.pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": HIDE_PB_JS})
|
|
877
|
+
if self.color_fix:
|
|
878
|
+
self.cube, self.color = calibrate(self.pg, self.tmp)
|
|
879
|
+
|
|
880
|
+
def shot(self, html: str, w: int, h: int, dst: Path, transparent: bool, settle_ms: int = 120) -> Path:
|
|
881
|
+
if self.b is None:
|
|
882
|
+
self._open()
|
|
883
|
+
self.pg.set_viewport(w, h, 1)
|
|
884
|
+
set_html(self.pg, html)
|
|
885
|
+
time.sleep(settle_ms / 1000)
|
|
886
|
+
capture_png(self.pg, dst, transparent=transparent)
|
|
887
|
+
if self.cube:
|
|
888
|
+
apply_lut_png(dst, self.cube)
|
|
889
|
+
return dst
|
|
890
|
+
|
|
891
|
+
def close(self) -> None:
|
|
892
|
+
if self.b is not None:
|
|
893
|
+
try:
|
|
894
|
+
self.pg._call("evaluate", UNHIDE_PB_JS)
|
|
895
|
+
except Exception: # noqa: BLE001 닫기 직전이라 무시
|
|
896
|
+
pass
|
|
897
|
+
self.b.close()
|
|
898
|
+
self.b = None
|
|
899
|
+
shutil.rmtree(self.tmp, ignore_errors=True)
|
|
900
|
+
|
|
901
|
+
def __enter__(self):
|
|
902
|
+
return self
|
|
903
|
+
|
|
904
|
+
def __exit__(self, *exc):
|
|
905
|
+
self.close()
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
909
|
+
# 시나리오가 쓰는 API
|
|
910
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
911
|
+
def _human_secs(sec: float) -> str:
|
|
912
|
+
sec = int(round(sec))
|
|
913
|
+
h, rem = divmod(sec, 3600)
|
|
914
|
+
m, s_ = divmod(rem, 60)
|
|
915
|
+
if h:
|
|
916
|
+
return f"{h}시간 {m}분" if m else f"{h}시간"
|
|
917
|
+
if m:
|
|
918
|
+
return f"{m}분 {s_}초" if s_ else f"{m}분"
|
|
919
|
+
return f"{s_}초"
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
class Director:
|
|
923
|
+
"""시나리오에 넘어가는 조종간. 화면 주석 · 대기 · 프로세스 · 배속 구간을 다룬다."""
|
|
924
|
+
|
|
925
|
+
def __init__(self, page, video_t0: float, url_timeline: list | None = None):
|
|
926
|
+
self.page = page
|
|
927
|
+
self._video_t0 = video_t0 # 영상 타임라인의 0 (= 페이지 생성 시점)
|
|
928
|
+
self.t0 = time.monotonic() # 본편 시작 (준비 구간 끝)
|
|
929
|
+
self.fast_ranges: list[list[float]] = []
|
|
930
|
+
self._open: float | None = None
|
|
931
|
+
self._speed = 4.0
|
|
932
|
+
self._js = OVERLAY_JS.read_text(encoding="utf-8")
|
|
933
|
+
self.style: dict = {}
|
|
934
|
+
# 주소 타임라인 — record 가 framenavigated 로 채우고, 여기서는 호출 때마다 대조해
|
|
935
|
+
# 이벤트가 놓친 변경(replaceState 등)을 메꾼다. 시나리오는 URL 을 적을 필요가 없다.
|
|
936
|
+
self.url_timeline: list = url_timeline if url_timeline is not None else []
|
|
937
|
+
# 주소창 화살표 구간 — [시작, 끝, 라벨, 방향] (영상 시각). render 가 프레임 PNG 에 그린다.
|
|
938
|
+
self.url_pointers: list = []
|
|
939
|
+
self._url_ptr_open: list | None = None
|
|
940
|
+
# 자막 타임라인 [시각, 문구|None] — 줌 구간에서 render 가 확대 밖에 자막을 다시 그릴 때 쓴다.
|
|
941
|
+
self.captions: list = []
|
|
942
|
+
# 줌 키프레임 [시각, 배율, 중심x, 중심y] (영상 시각 · 뷰포트 px, 중심 "url" 은 주소창).
|
|
943
|
+
# 키프레임 사이는 render 가 smootherstep 으로 보간한다 — 줌인 · 줌아웃 · 줌 상태의 이동(pan) 모두.
|
|
944
|
+
self.zoom_keyframes: list = []
|
|
945
|
+
self._zoom_state: tuple | None = None # (배율, cx, cy) — 줌 중이면
|
|
946
|
+
self._zoom_settle_at: float = 0.0 # 진행 중인 전환이 끝나는 monotonic 시각
|
|
947
|
+
# 장면 표시 [영상 시각, 종류, 문구] — render 가 출력 시각으로 바꿔 <out>.marks.json 에 남기고,
|
|
948
|
+
# frames --sheet 가 그 시각들을 한 장에 모아 보여 준다 (프레임을 하나씩 열어 보지 않게).
|
|
949
|
+
self.marks: list = []
|
|
950
|
+
# True 면 화살표 · 줌 대상을 못 찾을 때 ScenarioError 로 멈춘다 (시나리오의 STRICT, 기본 True).
|
|
951
|
+
self.strict = True
|
|
952
|
+
# record --dry-run 이면 True. 박자용 대기(d.sleep · say hold)를 DRY_SLEEP_CAP 로 줄인다.
|
|
953
|
+
self.dry = False
|
|
954
|
+
self.slept = 0.0 # 시나리오가 요청한 대기의 합 (dry-run 이 영상 길이를 어림한다)
|
|
955
|
+
self.waited = 0.0 # 그중 실제로 기다린 합
|
|
956
|
+
self._cut_label: str | None = None
|
|
957
|
+
|
|
958
|
+
# -- 줌 (render 단계에서 crop + scale, ease-in-out) ----------------------
|
|
959
|
+
def zoom(self, scale: float = 1.8, *, selector: str | None = None,
|
|
960
|
+
contains: str | None = None, x: float | None = None, y: float | None = None,
|
|
961
|
+
url: bool = False, duration: float = 1.0) -> bool:
|
|
962
|
+
"""대상을 중심으로 카메라가 다가가듯 확대한다 (render 가 crop + scale 로 처리).
|
|
963
|
+
중심은 selector / contains 로 찾은 요소의 가운데, x·y 뷰포트 좌표, 또는 url=True (주소창).
|
|
964
|
+
이미 줌 상태면 줌아웃 없이 새 대상으로 카메라가 이동한다 (배율도 함께 보간).
|
|
965
|
+
자막은 확대되지 않게 render 가 확대 밖에 다시 그린다. unzoom() 으로 돌아온다."""
|
|
966
|
+
if not 1.0 < scale <= 4.0:
|
|
967
|
+
raise ValueError(f"줌 배율은 1 초과 4 이하 (받은 값: {scale})")
|
|
968
|
+
if url:
|
|
969
|
+
cx, cy = "url", "url"
|
|
970
|
+
else:
|
|
971
|
+
cx, cy = x, y
|
|
972
|
+
if selector or contains:
|
|
973
|
+
self._ensure_visible(selector, contains)
|
|
974
|
+
found = self._target_center(selector, contains)
|
|
975
|
+
if not found:
|
|
976
|
+
self._missing("줌", "not-found", selector, contains)
|
|
977
|
+
return False
|
|
978
|
+
cx, cy = found
|
|
979
|
+
if cx is None or cy is None:
|
|
980
|
+
vp = self.page.viewport_size or {"width": 1440, "height": 900}
|
|
981
|
+
cx, cy = vp["width"] / 2, vp["height"] / 2
|
|
982
|
+
cx, cy = round(float(cx), 1), round(float(cy), 1)
|
|
983
|
+
self._wait_zoom_settled()
|
|
984
|
+
t = round(time.monotonic() - self._video_t0, 3)
|
|
985
|
+
if self._zoom_state is None:
|
|
986
|
+
self.zoom_keyframes.append([t, 1.0, cx, cy])
|
|
987
|
+
else:
|
|
988
|
+
ps, px, py = self._zoom_state
|
|
989
|
+
self.zoom_keyframes.append([t, ps, px, py])
|
|
990
|
+
self.zoom_keyframes.append([round(t + duration, 3), float(scale), cx, cy])
|
|
991
|
+
self._mark("zoom", f"×{scale:g} {selector or contains or ('주소창' if url else '')}".strip())
|
|
992
|
+
self._zoom_state = (float(scale), cx, cy)
|
|
993
|
+
self._zoom_settle_at = time.monotonic() + duration
|
|
994
|
+
return True
|
|
995
|
+
|
|
996
|
+
def unzoom(self, duration: float = 1.0) -> None:
|
|
997
|
+
"""확대를 풀고 전체 화면으로 돌아온다. 전환이 끝날 때까지(duration) 기다린다."""
|
|
998
|
+
if self._zoom_state is None:
|
|
999
|
+
return
|
|
1000
|
+
self._wait_zoom_settled()
|
|
1001
|
+
t = round(time.monotonic() - self._video_t0, 3)
|
|
1002
|
+
ps, px, py = self._zoom_state
|
|
1003
|
+
self.zoom_keyframes.append([t, ps, px, py])
|
|
1004
|
+
self.zoom_keyframes.append([round(t + duration, 3), 1.0, px, py])
|
|
1005
|
+
self._zoom_state = None
|
|
1006
|
+
self._zoom_settle_at = time.monotonic() + duration
|
|
1007
|
+
time.sleep(duration)
|
|
1008
|
+
|
|
1009
|
+
def _wait_zoom_settled(self) -> None:
|
|
1010
|
+
"""앞선 전환이 끝나기 전에 다음 키프레임을 찍으면 보간이 튄다 — 끝날 때까지 기다린다."""
|
|
1011
|
+
remain = self._zoom_settle_at - time.monotonic()
|
|
1012
|
+
if remain > 0:
|
|
1013
|
+
time.sleep(remain)
|
|
1014
|
+
|
|
1015
|
+
def _target_center(self, selector: str | None, contains: str | None):
|
|
1016
|
+
js = """(a) => {
|
|
1017
|
+
let el = null;
|
|
1018
|
+
if (a.selector) el = document.querySelector(a.selector);
|
|
1019
|
+
else if (a.contains) {
|
|
1020
|
+
const hits = [...document.querySelectorAll('body *')].filter(
|
|
1021
|
+
(n) => n.children.length === 0 && n.textContent && n.textContent.includes(a.contains));
|
|
1022
|
+
el = hits[hits.length - 1] || null;
|
|
1023
|
+
}
|
|
1024
|
+
if (!el) return null;
|
|
1025
|
+
const r = el.getBoundingClientRect();
|
|
1026
|
+
if (r.width === 0 && r.height === 0) return null;
|
|
1027
|
+
return [r.left + r.width / 2, r.top + r.height / 2];
|
|
1028
|
+
}"""
|
|
1029
|
+
try:
|
|
1030
|
+
return self.page.evaluate(js, {"selector": selector, "contains": contains})
|
|
1031
|
+
except Exception:
|
|
1032
|
+
return None
|
|
1033
|
+
|
|
1034
|
+
def point_url(self, label: str, direction: str = "우하") -> None:
|
|
1035
|
+
"""브라우저 창 프레임의 주소창을 가리킨다 (프레임이 켜져 있을 때만 보인다).
|
|
1036
|
+
페이지 안 화살표(point)와 한 번에 하나 — 다음 point / unpoint 에서 내려간다."""
|
|
1037
|
+
self._close_url_pointer()
|
|
1038
|
+
self._url_ptr_open = [round(time.monotonic() - self._video_t0, 3), None, label, direction]
|
|
1039
|
+
self._mark("point_url", label)
|
|
1040
|
+
|
|
1041
|
+
def _close_url_pointer(self) -> None:
|
|
1042
|
+
if self._url_ptr_open is not None:
|
|
1043
|
+
self._url_ptr_open[1] = round(time.monotonic() - self._video_t0, 3)
|
|
1044
|
+
self.url_pointers.append(self._url_ptr_open)
|
|
1045
|
+
self._url_ptr_open = None
|
|
1046
|
+
|
|
1047
|
+
def _note_url(self) -> None:
|
|
1048
|
+
try:
|
|
1049
|
+
url = self.page.url
|
|
1050
|
+
except Exception:
|
|
1051
|
+
return
|
|
1052
|
+
if not self.url_timeline or self.url_timeline[-1][1] != url:
|
|
1053
|
+
self.url_timeline.append([round(time.monotonic() - self._video_t0, 3), url])
|
|
1054
|
+
|
|
1055
|
+
def _mark(self, kind: str, label: str | None) -> None:
|
|
1056
|
+
self.marks.append([round(time.monotonic() - self._video_t0, 3), kind, label or ""])
|
|
1057
|
+
|
|
1058
|
+
def _missing(self, what: str, reason, selector, contains) -> None:
|
|
1059
|
+
msg = f"{what} 대상을 못 찾음: {reason} (selector={selector!r} contains={contains!r})"
|
|
1060
|
+
if self.strict:
|
|
1061
|
+
raise ScenarioError(msg + ". 셀렉터 · 문구를 고치거나, 그 장면 전에 대상이 뜨기를 d.wait_text / d.wait_until 로 "
|
|
1062
|
+
"기다린다. 경고만 하고 이어 찍으려면 시나리오에 STRICT = False")
|
|
1063
|
+
warn(msg)
|
|
1064
|
+
|
|
1065
|
+
# -- 화면 주석 --------------------------------------------------------
|
|
1066
|
+
def say(self, text: str | None, hold=None) -> None:
|
|
1067
|
+
"""하단 자막. None 이면 숨긴다.
|
|
1068
|
+
hold="auto" 면 자막을 읽을 시간만큼 (0.8초 + 글자당 0.07초, 1.5~6초) 기다린다. 숫자면 그 초만큼.
|
|
1069
|
+
자막마다 d.sleep 값을 손으로 맞추지 않아도 된다."""
|
|
1070
|
+
self._note_url()
|
|
1071
|
+
# 자막은 render 가 최종 1920×1080 위에 그린다 (크기가 페이지 배율 · 줌과 상관없이 같다). 여기서는 시각만 남긴다.
|
|
1072
|
+
self.captions.append([round(time.monotonic() - self._video_t0, 3), text])
|
|
1073
|
+
if text:
|
|
1074
|
+
self._mark("say", text)
|
|
1075
|
+
if hold is not None and hold is not False:
|
|
1076
|
+
self.sleep(self.read_time(text) if hold in ("auto", True) else float(hold))
|
|
1077
|
+
|
|
1078
|
+
@staticmethod
|
|
1079
|
+
def read_time(text: str | None) -> float:
|
|
1080
|
+
"""자막 하나를 읽는 데 주는 시간 (초)."""
|
|
1081
|
+
n = len((text or "").strip())
|
|
1082
|
+
return round(min(max(SAY_HOLD_BASE + SAY_HOLD_PER_CHAR * n, SAY_HOLD_MIN), SAY_HOLD_MAX), 2)
|
|
1083
|
+
|
|
1084
|
+
def point(self, label: str, direction: str = "우상", *,
|
|
1085
|
+
selector: str | None = None, contains: str | None = None,
|
|
1086
|
+
ring: bool = True) -> bool:
|
|
1087
|
+
"""대상을 가리킨다. direction 은 말풍선이 놓일 방향 —
|
|
1088
|
+
우상 / 좌상 / 좌하 / 우하 (tr / tl / bl / br 도 됨).
|
|
1089
|
+
대상은 CSS 셀렉터(selector) 또는 포함 텍스트(contains) 로 지정한다."""
|
|
1090
|
+
self._close_url_pointer() # 화살표는 한 번에 하나
|
|
1091
|
+
self._ensure_visible(selector, contains)
|
|
1092
|
+
res = self._overlay({
|
|
1093
|
+
"pointer": {"selector": selector, "contains": contains,
|
|
1094
|
+
"direction": direction, "label": label, "ring": ring, "scroll": False}
|
|
1095
|
+
})
|
|
1096
|
+
if isinstance(res, dict) and not res.get("ok"):
|
|
1097
|
+
self._missing("화살표", res.get("reason"), selector, contains)
|
|
1098
|
+
return False
|
|
1099
|
+
self._mark("point", label)
|
|
1100
|
+
return True
|
|
1101
|
+
|
|
1102
|
+
def unpoint(self) -> None:
|
|
1103
|
+
self._close_url_pointer()
|
|
1104
|
+
self._overlay({"pointer": None})
|
|
1105
|
+
|
|
1106
|
+
# -- 스크롤 (부드럽게) ----------------------------------------------------
|
|
1107
|
+
_FIND_JS = """(a) => {
|
|
1108
|
+
let el = null;
|
|
1109
|
+
if (a.selector) el = document.querySelector(a.selector);
|
|
1110
|
+
else if (a.contains) {
|
|
1111
|
+
const hits = [...document.querySelectorAll('body *')].filter(
|
|
1112
|
+
(n) => n.children.length === 0 && n.textContent && n.textContent.includes(a.contains));
|
|
1113
|
+
el = hits[hits.length - 1] || null;
|
|
1114
|
+
}
|
|
1115
|
+
return el;
|
|
1116
|
+
}"""
|
|
1117
|
+
|
|
1118
|
+
def _ensure_visible(self, selector: str | None, contains: str | None, timeout: float = 2.0) -> None:
|
|
1119
|
+
"""대상이 화면 밖이면 부드럽게 스크롤해 가운데로 가져오고, 멈출 때까지 기다린다
|
|
1120
|
+
(순간이동 scrollIntoView 는 화면이 툭 바뀌어 보는 사람이 놓친다). 중첩 스크롤 영역도 브라우저가 처리한다."""
|
|
1121
|
+
if not (selector or contains):
|
|
1122
|
+
return
|
|
1123
|
+
try:
|
|
1124
|
+
moved = self.page.evaluate(self._FIND_JS.replace("return el;", """
|
|
1125
|
+
if (!el) return false;
|
|
1126
|
+
const r = el.getBoundingClientRect();
|
|
1127
|
+
const out = r.top < 0 || r.bottom > innerHeight || r.left < 0 || r.right > innerWidth;
|
|
1128
|
+
if (out) el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
|
|
1129
|
+
return out;"""), {"selector": selector, "contains": contains})
|
|
1130
|
+
except Exception:
|
|
1131
|
+
return
|
|
1132
|
+
if not moved:
|
|
1133
|
+
return
|
|
1134
|
+
last, stable, until = None, 0, time.monotonic() + timeout
|
|
1135
|
+
while time.monotonic() < until and stable < 3:
|
|
1136
|
+
time.sleep(0.05)
|
|
1137
|
+
try:
|
|
1138
|
+
pos = self.page.evaluate(self._FIND_JS.replace("return el;",
|
|
1139
|
+
"return el ? [Math.round(el.getBoundingClientRect().top), Math.round(el.getBoundingClientRect().left)] : null;"),
|
|
1140
|
+
{"selector": selector, "contains": contains})
|
|
1141
|
+
except Exception:
|
|
1142
|
+
break
|
|
1143
|
+
stable = stable + 1 if pos == last else 0
|
|
1144
|
+
last = pos
|
|
1145
|
+
time.sleep(0.15)
|
|
1146
|
+
|
|
1147
|
+
def scroll(self, dy: float, duration: float = 0.8, x: float | None = None, y: float | None = None) -> None:
|
|
1148
|
+
"""휠로 dy 픽셀만큼 부드럽게 스크롤한다 (양수 = 아래). 실제 wheel 이벤트를 잘게 나눠 보내므로
|
|
1149
|
+
커서 아래의 중첩 스크롤 영역에도 먹는다. x, y 를 주면 그 지점 위에서 굴린다."""
|
|
1150
|
+
vp = self.page.viewport_size or {"width": 1440, "height": 900}
|
|
1151
|
+
px = vp["width"] / 2 if x is None else x
|
|
1152
|
+
py = vp["height"] / 2 if y is None else y
|
|
1153
|
+
try:
|
|
1154
|
+
self.page.mouse.move(px, py)
|
|
1155
|
+
except Exception:
|
|
1156
|
+
return
|
|
1157
|
+
steps = max(int(duration * 50), 8)
|
|
1158
|
+
done = 0.0
|
|
1159
|
+
for i in range(1, steps + 1):
|
|
1160
|
+
p = i / steps
|
|
1161
|
+
eased = p * p * p * (p * (p * 6 - 15) + 10) # smootherstep
|
|
1162
|
+
target = dy * eased
|
|
1163
|
+
delta = target - done
|
|
1164
|
+
done = target
|
|
1165
|
+
try:
|
|
1166
|
+
self.page.mouse.wheel(0, delta)
|
|
1167
|
+
except Exception:
|
|
1168
|
+
return
|
|
1169
|
+
time.sleep(duration / steps)
|
|
1170
|
+
time.sleep(0.15)
|
|
1171
|
+
|
|
1172
|
+
def _overlay(self, arg: dict):
|
|
1173
|
+
arg = {**arg, "style": self.style}
|
|
1174
|
+
try:
|
|
1175
|
+
return self.page.evaluate(self._js, arg)
|
|
1176
|
+
except Exception:
|
|
1177
|
+
return None # 리로드 중이면 다음 호출에서 다시 붙는다
|
|
1178
|
+
|
|
1179
|
+
# -- 배속 구간 --------------------------------------------------------
|
|
1180
|
+
def fast(self, speed: float = 4.0) -> None:
|
|
1181
|
+
"""여기서부터 빨리 감는다 (1 ~ 8배). 배속 표시는 render 가 그린다."""
|
|
1182
|
+
speed = float(speed)
|
|
1183
|
+
if not SPEED_MIN <= speed <= SPEED_MAX:
|
|
1184
|
+
raise ValueError(f"배속은 {SPEED_MIN:g} ~ {SPEED_MAX:g} 사이여야 합니다 (받은 값: {speed})")
|
|
1185
|
+
if self._open is None:
|
|
1186
|
+
self._open = time.monotonic() - self.t0
|
|
1187
|
+
self._speed = speed
|
|
1188
|
+
self._cut_label = None
|
|
1189
|
+
self._mark("fast", f"×{speed:g}")
|
|
1190
|
+
|
|
1191
|
+
def cut(self, label: str | None = None) -> None:
|
|
1192
|
+
"""여기서부터 d.normal() 까지를 영상에서 잘라 낸다. 8배속으로도 긴 기다림 (몇 분 · 몇 시간 걸리는 작업) 용.
|
|
1193
|
+
잘린 자리에는 가운데에 "▶▶| label" (기본: 걸린 시간, 예 "3분 12초 뒤") 이 1.2초 뜬다. 그동안 화면은 녹화되지만
|
|
1194
|
+
잘리는 구간이라 영상 길이에 들어가지 않는다."""
|
|
1195
|
+
if self._open is None:
|
|
1196
|
+
self._open = time.monotonic() - self.t0
|
|
1197
|
+
self._speed = 0.0
|
|
1198
|
+
self._cut_label = label
|
|
1199
|
+
self._mark("cut", label or "")
|
|
1200
|
+
|
|
1201
|
+
def normal(self) -> None:
|
|
1202
|
+
"""빨리 감기 · 잘라 내기 끝."""
|
|
1203
|
+
if self._open is not None:
|
|
1204
|
+
end = time.monotonic() - self.t0
|
|
1205
|
+
if self._speed == 0.0:
|
|
1206
|
+
label = self._cut_label or f"{_human_secs(end - self._open)} 뒤"
|
|
1207
|
+
self.fast_ranges.append([self._open, end, 0.0, label])
|
|
1208
|
+
else:
|
|
1209
|
+
self.fast_ranges.append([self._open, end, self._speed])
|
|
1210
|
+
self._open = None
|
|
1211
|
+
self._cut_label = None
|
|
1212
|
+
|
|
1213
|
+
# -- 대기 -------------------------------------------------------------
|
|
1214
|
+
def sleep(self, seconds: float) -> None:
|
|
1215
|
+
self._note_url()
|
|
1216
|
+
real = min(float(seconds), DRY_SLEEP_CAP) if self.dry else float(seconds)
|
|
1217
|
+
self.slept += float(seconds)
|
|
1218
|
+
self.waited += real
|
|
1219
|
+
time.sleep(real)
|
|
1220
|
+
self._note_url()
|
|
1221
|
+
|
|
1222
|
+
def wait_until(self, js: str, timeout: float = 30.0) -> bool:
|
|
1223
|
+
"""페이지 안에서 참이 될 때까지 기다린다. 리로드 중 예외는 삼킨다. 시간이 넘으면 False."""
|
|
1224
|
+
until = time.monotonic() + timeout
|
|
1225
|
+
while time.monotonic() < until:
|
|
1226
|
+
self._note_url()
|
|
1227
|
+
try:
|
|
1228
|
+
if self.page.evaluate(js):
|
|
1229
|
+
return True
|
|
1230
|
+
except Exception:
|
|
1231
|
+
pass
|
|
1232
|
+
time.sleep(0.25)
|
|
1233
|
+
return False
|
|
1234
|
+
|
|
1235
|
+
def wait_text(self, text: str, timeout: float = 30.0) -> bool:
|
|
1236
|
+
return self.wait_until(
|
|
1237
|
+
"() => document.body.innerText.includes(%s)" % json.dumps(text), timeout)
|
|
1238
|
+
|
|
1239
|
+
# -- 프로세스 (서버를 죽였다 살리는 시연용) -----------------------------
|
|
1240
|
+
@staticmethod
|
|
1241
|
+
def listen_pids(port: int) -> list[str]:
|
|
1242
|
+
out = subprocess.run(
|
|
1243
|
+
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
|
|
1244
|
+
capture_output=True, text=True).stdout
|
|
1245
|
+
return out.split()
|
|
1246
|
+
|
|
1247
|
+
def kill_port(self, port: int) -> None:
|
|
1248
|
+
"""그 포트를 **듣고 있는** 프로세스만 죽인다.
|
|
1249
|
+
|
|
1250
|
+
`lsof -ti:<port>` 를 쓰면 안 된다. 그 포트에 접속해 있는 클라이언트까지 돌려준다.
|
|
1251
|
+
녹화하는 브라우저는 사용자가 쓰는 Chrome · Edge 라서, 섞여 나온 PID 를 죽이면 사용자 브라우저가 통째로 꺼진다."""
|
|
1252
|
+
for pid in self.listen_pids(port):
|
|
1253
|
+
subprocess.run(["kill", pid])
|
|
1254
|
+
|
|
1255
|
+
def shell(self, cmd: str, cwd: str | None = None, env: dict | None = None,
|
|
1256
|
+
log: str = "/dev/null") -> None:
|
|
1257
|
+
"""백그라운드 셸 명령 (서버 기동 등). 동기 호출은 쓰지 않는다.
|
|
1258
|
+
녹화는 따로 돌아 끊기지 않지만, 시나리오가 그동안 멈춰 화면이 정지한 채 길게 찍힌다."""
|
|
1259
|
+
subprocess.Popen(
|
|
1260
|
+
["/bin/sh", "-c", f"nohup {cmd} > {log} 2>&1 &"],
|
|
1261
|
+
cwd=cwd, env={**os.environ, **(env or {})},
|
|
1262
|
+
)
|
|
1263
|
+
|
|
1264
|
+
def wait_port(self, port: int, up: bool = True, timeout: float = 60.0) -> bool:
|
|
1265
|
+
until = time.monotonic() + timeout
|
|
1266
|
+
while time.monotonic() < until:
|
|
1267
|
+
if bool(self.listen_pids(port)) == up:
|
|
1268
|
+
return True
|
|
1269
|
+
time.sleep(0.4)
|
|
1270
|
+
return False
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1274
|
+
# record
|
|
1275
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1276
|
+
def load_scenario(path: Path):
|
|
1277
|
+
spec = importlib.util.spec_from_file_location("dv_scenario", path)
|
|
1278
|
+
mod = importlib.util.module_from_spec(spec)
|
|
1279
|
+
spec.loader.exec_module(mod)
|
|
1280
|
+
for required in ("START_URL", "scenario"):
|
|
1281
|
+
if not hasattr(mod, required):
|
|
1282
|
+
raise SystemExit(f"시나리오에 {required} 가 없습니다: {path}")
|
|
1283
|
+
return mod
|
|
1284
|
+
|
|
1285
|
+
|
|
1286
|
+
def real_view(pg) -> tuple[int, int, float]:
|
|
1287
|
+
"""에이전트 창에서 탭이 실제로 차지하는 크기 (CSS px) 와 그 화면의 배율. 화면 크기 흉내를 잠깐 풀고 잰다.
|
|
1288
|
+
|
|
1289
|
+
screencast 는 흉내 낸 화면이 아니라 이 실제 영역을 찍는다. 흉내 크기가 이보다 크면 오른쪽 · 아래가 잘리고 회색 띠가
|
|
1290
|
+
생긴다 (2026-10-09 실측: 창 1200×800, 탭 영역 1046×707 에서 1440×900 으로 찍자 오른쪽이 잘리고 아래쪽 자막이 영상
|
|
1291
|
+
밖으로 나갔다). 그래서 record 는 흉내 낸 화면을 이 영역에 맞게 축소해 그린다 (fit_scale).
|
|
1292
|
+
이 경우는 녹화 탭이 에이전트 창 맨 앞 탭일 때다. 확장이 맨 앞에 빈 탭을 두고 세션 탭을 뒤에 두므로 (thuthi-browser 0.15)
|
|
1293
|
+
보통은 흉내 크기 그대로 찍힌다.
|
|
1294
|
+
"""
|
|
1295
|
+
pg.cdp("Emulation.clearDeviceMetricsOverride", {})
|
|
1296
|
+
w, h, dpr = pg.evaluate("[innerWidth, innerHeight, devicePixelRatio]")
|
|
1297
|
+
return int(w), int(h), float(dpr)
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def small_frames(fsizes: list, width: int, height: int) -> list:
|
|
1301
|
+
"""제 크기 (width × height) 에 못 미친 프레임 구간 [(시작, 끝 또는 None, 너비, 높이)]."""
|
|
1302
|
+
out = []
|
|
1303
|
+
for i, (t, w, h) in enumerate(fsizes):
|
|
1304
|
+
if w < width * 0.98 or h < height * 0.98:
|
|
1305
|
+
end = fsizes[i + 1][0] if i + 1 < len(fsizes) else None
|
|
1306
|
+
out.append((t, end, w, h))
|
|
1307
|
+
return out
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
FILL_MARK_JS = """(on) => { let m = document.getElementById('__dv_fill');
|
|
1311
|
+
if (!on) { if (m) m.remove(); return true; }
|
|
1312
|
+
if (!m) { m = document.createElement('div'); m.id = '__dv_fill';
|
|
1313
|
+
m.style.cssText = 'position:fixed;right:0;bottom:0;width:24px;height:24px;background:#ff00ff;z-index:2147483647;pointer-events:none';
|
|
1314
|
+
(document.body || document.documentElement).appendChild(m); }
|
|
1315
|
+
return true; }"""
|
|
1316
|
+
|
|
1317
|
+
|
|
1318
|
+
def _pixel(img: Path, x: int, y: int) -> tuple[int, int, int] | None:
|
|
1319
|
+
r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(img), "-vf", f"crop=4:4:{x}:{y},scale=1:1",
|
|
1320
|
+
"-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True)
|
|
1321
|
+
return tuple(r.stdout[:3]) if r.returncode == 0 and len(r.stdout) >= 3 else None
|
|
1322
|
+
|
|
1323
|
+
|
|
1324
|
+
def frame_filled(pg, rec: "PbRecorder", width: int, height: int) -> tuple[bool, object]:
|
|
1325
|
+
"""페이지 오른쪽 아래 구석에 자홍색 점을 잠깐 그리고, 지금 찍히는 프레임의 같은 자리에 그 색이 있는지 본다."""
|
|
1326
|
+
try:
|
|
1327
|
+
pg.evaluate(FILL_MARK_JS, True)
|
|
1328
|
+
except Exception: # noqa: BLE001 확인을 못 하면 된 것으로 친다
|
|
1329
|
+
return True, None
|
|
1330
|
+
px = None
|
|
1331
|
+
try:
|
|
1332
|
+
deadline = time.monotonic() + 3.0
|
|
1333
|
+
time.sleep(0.4)
|
|
1334
|
+
while time.monotonic() < deadline:
|
|
1335
|
+
probe = rec.dir.parent / "probe.jpg"
|
|
1336
|
+
try:
|
|
1337
|
+
rec.frame(probe)
|
|
1338
|
+
except Exception: # noqa: BLE001 아직 프레임이 없다
|
|
1339
|
+
probe = None
|
|
1340
|
+
if probe:
|
|
1341
|
+
px = _pixel(probe, width - 14, height - 14)
|
|
1342
|
+
if px and px[0] > 150 and px[1] < 120 and px[2] > 150:
|
|
1343
|
+
return True, px
|
|
1344
|
+
time.sleep(0.3)
|
|
1345
|
+
return False, px
|
|
1346
|
+
finally:
|
|
1347
|
+
try:
|
|
1348
|
+
pg.evaluate(FILL_MARK_JS, False)
|
|
1349
|
+
except Exception: # noqa: BLE001
|
|
1350
|
+
pass
|
|
1351
|
+
|
|
1352
|
+
|
|
1353
|
+
def choose_view(pg, rec: "PbRecorder", width: int, height: int, sc: float) -> float:
|
|
1354
|
+
"""녹화를 켠 뒤, 페이지가 프레임을 꽉 채우게 찍히는 방식을 실제로 찍어 보고 고른다. 고른 축소 배율을 돌려준다.
|
|
1355
|
+
|
|
1356
|
+
브라우저는 녹화 프레임을 두 가지로 준다. (1) 흉내 낸 화면 크기 그대로 (창이 작아도, 레티나면 2배까지) — 이때 축소를
|
|
1357
|
+
걸면 그 안에 페이지가 줄어 그려진다 (2026-10-11 실측: 1792×848 프레임 안에 0.584배). (2) 탭 영역만 — 이때는 축소해야
|
|
1358
|
+
다 담긴다 (2026-10-09 실측: 축소 없이 1440×900 이 잘리고 회색 띠). 갈리는 조건은 녹화 탭이 창 맨 앞 탭이냐다
|
|
1359
|
+
(맨 앞이면 (2), 뒤면 (1). 2026-11-16 Chrome for Testing 1792×848 흉내: 뒤 1792×848, 맨 앞 1200×600). 확장이 세션
|
|
1360
|
+
탭을 늘 뒤에 두지만 사람이 그 탭을 누르면 앞으로 올 수 있어, 축소 없이 먼저 찍어 보고 안 되면 축소해서 찍어 본다.
|
|
1361
|
+
둘 다 안 되면 녹화하지 않는다."""
|
|
1362
|
+
tried = []
|
|
1363
|
+
order = [1.0, sc] if sc < 1 else [1.0]
|
|
1364
|
+
if os.environ.get("DV_VIEW_TRY") == "scaled" and sc < 1: # 검사용: 축소 경로만 시험한다
|
|
1365
|
+
order = [sc]
|
|
1366
|
+
for k in order:
|
|
1367
|
+
set_view(pg, width, height, k)
|
|
1368
|
+
ok, px = frame_filled(pg, rec, width, height)
|
|
1369
|
+
tried.append(f"축소 {k:.3f}: 구석 색 {px}")
|
|
1370
|
+
if ok:
|
|
1371
|
+
return k
|
|
1372
|
+
raise SystemExit("녹화 프레임에 페이지가 꽉 차게 찍히지 않아 녹화하지 않았다 (" + ", ".join(tried) + ", 자홍색이어야 한다).\n"
|
|
1373
|
+
"에이전트 창을 화면에 보이게 두거나 (다른 창 뒤여도 된다), 창을 더 큰 모니터로 옮긴 뒤 다시 record 한다.")
|
|
1374
|
+
|
|
1375
|
+
|
|
1376
|
+
def check_window(b) -> None:
|
|
1377
|
+
"""에이전트 창이 최소화돼 있으면 녹화하지 않고 멈춘다.
|
|
1378
|
+
|
|
1379
|
+
최소화된 창은 레티나 픽셀 없이 1배로만 그려져, 페이지가 영상 왼쪽 위에 0.6배쯤으로 줄어 찍혔다 (2026-10-11
|
|
1380
|
+
실측, 경고 없이). 창을 되살리면 macOS 에서 사용자 포커스를 뺏으므로 직접 되살리지 않고 사용자에게 맡긴다."""
|
|
1381
|
+
try:
|
|
1382
|
+
state = (b.call("call", "agentWindow.get", {}) or {}).get("state")
|
|
1383
|
+
except Exception: # noqa: BLE001 확인을 못 하면 그대로 찍는다 (옛 확장)
|
|
1384
|
+
return
|
|
1385
|
+
if state == "minimized":
|
|
1386
|
+
raise SystemExit("에이전트 창이 최소화돼 있어 녹화하지 않았다. 최소화된 창은 1배로만 그려져 영상이 작게 찍힌다.\n"
|
|
1387
|
+
"Edge (또는 Chrome) 의 parallel-browser 에이전트 창을 Dock 에서 다시 띄운 뒤 (다른 창 뒤에 있어도 된다) 다시 record 한다.")
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
def fit_scale(width: int, height: int, rw: int, rh: int) -> float:
|
|
1391
|
+
"""width × height 로 그린 화면을 탭 영역 rw × rh 안에 넣는 축소 배율 (1 이하)."""
|
|
1392
|
+
return min(rw / width, rh / height, 1.0)
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
def set_view(pg, width: int, height: int, scale: float) -> None:
|
|
1396
|
+
"""width × height 로 흉내 낸 화면을 scale 배로 축소해 그리고, 입력 좌표도 같은 배율로 맞춘다 (runtime setInputScale).
|
|
1397
|
+
scale 을 걸면 브라우저가 클릭 좌표를 축소된 창 기준으로 읽어서, 맞추지 않으면 C 를 누를 때 B 가 눌린다 (2026-10-09 실측)."""
|
|
1398
|
+
pg.cdp("Emulation.setDeviceMetricsOverride", {"width": width, "height": height, "deviceScaleFactor": 1,
|
|
1399
|
+
"mobile": False, "scale": scale})
|
|
1400
|
+
pg.viewport_size = {"width": width, "height": height}
|
|
1401
|
+
pg.view_scale = scale
|
|
1402
|
+
pg._call("setInputScale", scale)
|
|
1403
|
+
|
|
1404
|
+
|
|
1405
|
+
def default_view(style: dict | None) -> tuple[int, int]:
|
|
1406
|
+
"""창 프레임을 붙인 최종 화면이 OUT_W × OUT_H 가 되는 녹화 (뷰포트) 크기. 프레임이 없으면 그대로."""
|
|
1407
|
+
cfg = frame_config(style, None)
|
|
1408
|
+
if not cfg:
|
|
1409
|
+
return OUT_W, OUT_H - CAPTION_BAND # 프레임이 없어도 아래 자막 띠는 비워 둔다 (render 가 검게 붙인다)
|
|
1410
|
+
w, h = OUT_W - 2 * int(cfg["pad"]), OUT_H - int(cfg["bar"]) - int(cfg["pad"]) - int(cfg["band"])
|
|
1411
|
+
return w - w % 2, h - h % 2
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
def make_director(page, video_t0: float, url_timeline: list, mod, dry: bool = False) -> "Director":
|
|
1415
|
+
d = Director(page, video_t0, url_timeline)
|
|
1416
|
+
d.style = getattr(mod, "STYLE", {})
|
|
1417
|
+
d.strict = bool(getattr(mod, "STRICT", True))
|
|
1418
|
+
d.dry = dry
|
|
1419
|
+
d._note_url() # 본편 시작 시점의 주소는 반드시 한 줄 남긴다
|
|
1420
|
+
return d
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
def run_scenario(mod, d: "Director") -> None:
|
|
1424
|
+
try:
|
|
1425
|
+
mod.scenario(d)
|
|
1426
|
+
finally:
|
|
1427
|
+
d.normal() # 열려 있던 배속 · 잘라 내기 구간을 닫는다
|
|
1428
|
+
d.unpoint() # 열려 있던 화살표(페이지 · 주소창)도 닫는다
|
|
1429
|
+
d.unzoom() # 열려 있던 줌도 닫는다
|
|
1430
|
+
d.say(None)
|
|
1431
|
+
|
|
1432
|
+
|
|
1433
|
+
def dry_run(scenario_path: Path, width: int | None, height: int | None) -> dict:
|
|
1434
|
+
"""녹화 · 색 보정 · 인코딩 없이 prepare 와 scenario 를 한 번 돌린다. 화살표 · 줌 대상, 셀렉터, 대기 조건이
|
|
1435
|
+
맞는지만 본다. 박자용 대기는 DRY_SLEEP_CAP 로 줄인다. 실제 녹화 전에 실패를 잡는 용도라 같은 크기로 그린다."""
|
|
1436
|
+
if pbpage is None:
|
|
1437
|
+
raise SystemExit(f"pbpage 를 불러오지 못했다 ({PB_LIB}). doctor 를 먼저 돌린다")
|
|
1438
|
+
mod = load_scenario(scenario_path)
|
|
1439
|
+
dw, dh = default_view(getattr(mod, "STYLE", {}))
|
|
1440
|
+
width, height = width or dw, height or dh
|
|
1441
|
+
t0 = time.monotonic()
|
|
1442
|
+
with pbpage.Browser("demo-video-dry", accept_dialogs=False) as b:
|
|
1443
|
+
pg = b.new_page(viewport=(CAL_W, CAL_H), dpr=1)
|
|
1444
|
+
pg.cdp("Emulation.setScrollbarsHidden", {"hidden": True})
|
|
1445
|
+
pg.goto("about:blank")
|
|
1446
|
+
rw, rh, _ = real_view(pg)
|
|
1447
|
+
set_view(pg, width, height, fit_scale(width, height, rw, rh))
|
|
1448
|
+
pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": HIDE_PB_JS})
|
|
1449
|
+
pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": CURSOR_JS.read_text(encoding="utf-8")})
|
|
1450
|
+
page = ScenarioPage(pg)
|
|
1451
|
+
page.goto(mod.START_URL, wait_until="domcontentloaded")
|
|
1452
|
+
if hasattr(mod, "prepare"):
|
|
1453
|
+
mod.prepare(page)
|
|
1454
|
+
d = make_director(page, time.monotonic(), [], mod, dry=True)
|
|
1455
|
+
run_scenario(mod, d)
|
|
1456
|
+
kinds: dict = {}
|
|
1457
|
+
for _, kind, _label in d.marks:
|
|
1458
|
+
kinds[kind] = kinds.get(kind, 0) + 1
|
|
1459
|
+
ran = time.monotonic() - d.t0
|
|
1460
|
+
return {"dry_run": True, "scenario": scenario_path.name, "size": [width, height],
|
|
1461
|
+
"seconds": round(time.monotonic() - t0, 1),
|
|
1462
|
+
# 실제 녹화에서 본편이 걸릴 시간 (줄인 대기를 되돌린 값, 배속 · 잘라 내기 반영 전)
|
|
1463
|
+
"scenario_seconds_when_recorded": round(ran - d.waited + d.slept, 1),
|
|
1464
|
+
"marks": kinds, "strict": d.strict}
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def record(scenario_path: Path, out: Path, meta: Path,
|
|
1468
|
+
width: int | None, height: int | None, color_fix: bool = True) -> None:
|
|
1469
|
+
if pbpage is None:
|
|
1470
|
+
raise SystemExit(f"pbpage 를 불러오지 못했다 ({PB_LIB}). doctor 를 먼저 돌린다")
|
|
1471
|
+
if (width and width % 2) or (height and height % 2):
|
|
1472
|
+
raise SystemExit(f"뷰포트 너비 · 높이는 짝수여야 한다 (h264). 받은 값: {width}×{height}")
|
|
1473
|
+
mod = load_scenario(scenario_path)
|
|
1474
|
+
dw, dh = default_view(getattr(mod, "STYLE", {}))
|
|
1475
|
+
width, height = width or dw, height or dh
|
|
1476
|
+
# 지난 녹화의 결과물을 먼저 지운다. 이번 녹화가 실패하면 --out 이 아예 없어야, 옛 원본을 모르고 render 하지 않는다
|
|
1477
|
+
# (2026-09-16 실측: 실패를 놓치고 옛 원본을 렌더했다).
|
|
1478
|
+
for stale in (out, meta):
|
|
1479
|
+
if stale.exists():
|
|
1480
|
+
stale.unlink()
|
|
1481
|
+
# 프로세스별 고유 임시 폴더. 고정 경로는 두 세션이 동시에 녹화하면 서로의 프레임을 지운다
|
|
1482
|
+
# (2026-09-15 실측: 워크트리 두 곳 동시 녹화).
|
|
1483
|
+
tmpdir = Path(tempfile.mkdtemp(prefix="dv-video-"))
|
|
1484
|
+
frames_dir = tmpdir / "frames" # 녹화가 쓰는 작업 폴더 (찍는 중인 영상 하나)
|
|
1485
|
+
url_timeline: list = []
|
|
1486
|
+
hidden: list = []
|
|
1487
|
+
fsizes: list = [] # [영상 시각, 프레임 너비, 높이] — 크기가 바뀔 때마다
|
|
1488
|
+
replaced: list = [] # 브라우저가 녹화 탭을 새 탭으로 바꾼 영상 시각
|
|
1489
|
+
rec: PbRecorder | None = None
|
|
1490
|
+
try:
|
|
1491
|
+
# 세션(탭 묶음) 하나. with 를 벗어나면 오류가 나도 탭까지 닫힌다.
|
|
1492
|
+
with pbpage.Browser("demo-video", accept_dialogs=False) as b:
|
|
1493
|
+
# 대화상자는 Playwright 기본값처럼 닫는다 (accept_dialogs=False).
|
|
1494
|
+
pg = b.new_page(viewport=(CAL_W, CAL_H), dpr=1)
|
|
1495
|
+
pg.cdp("Emulation.setScrollbarsHidden", {"hidden": True})
|
|
1496
|
+
pg.goto("about:blank")
|
|
1497
|
+
check_window(b)
|
|
1498
|
+
rw, rh, dpr = real_view(pg)
|
|
1499
|
+
# 흉내 낸 화면 (width × height) 을 탭 영역 안에 축소해 그린다 (Emulation scale). 창 크기는 건드리지 않는다.
|
|
1500
|
+
# 레티나 화면이면 탭 영역의 실제 픽셀 (rw × dpr) 이 넉넉해 width × height 를 그대로 선명하게 담는다.
|
|
1501
|
+
sc = fit_scale(width, height, rw, rh)
|
|
1502
|
+
cube, color = calibrate(pg, tmpdir) if color_fix else (None, {"deviation": None, "lut": False})
|
|
1503
|
+
set_view(pg, width, height, sc)
|
|
1504
|
+
# 새 문서마다: 상태 표시 숨김 + 클릭 시각화(커서 아이콘 · 물결 · 키 배지)
|
|
1505
|
+
hide_id = pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": HIDE_PB_JS})["identifier"]
|
|
1506
|
+
pg.cdp("Page.addScriptToEvaluateOnNewDocument", {"source": CURSOR_JS.read_text(encoding="utf-8")})
|
|
1507
|
+
pg.goto("about:blank") # 보정판을 지우고 빈 문서에서 시작
|
|
1508
|
+
|
|
1509
|
+
# 프레임은 탭 영역 전체다. 축소해 그린 화면이 그 왼쪽 위에 놓이므로, 프레임 크기를 탭 영역 ÷ 배율로 받으면
|
|
1510
|
+
# 그 화면이 width × height 픽셀로 들어오고 assemble_cfr 가 그만큼 잘라 쓴다.
|
|
1511
|
+
rec = PbRecorder(pg, frames_dir, math.ceil(rw / sc), math.ceil(rh / sc))
|
|
1512
|
+
try:
|
|
1513
|
+
page_created, _ = rec.start() # 영상 타임라인의 0
|
|
1514
|
+
view_mode = choose_view(pg, rec, width, height, sc) # 축소 없이 / 축소해서 중 실제로 꽉 차게 찍히는 쪽
|
|
1515
|
+
if view_mode < 1 and rw * dpr < width * 0.98:
|
|
1516
|
+
# 브라우저가 탭 영역만 주는 방식일 때만 해당한다 (흉내 크기 그대로 주면 창 크기와 상관없이 선명하다).
|
|
1517
|
+
warn(f"브라우저가 탭 영역만 녹화해 {width}×{height} 를 {view_mode:.2f} 배로 줄여 찍는다. 탭 영역 {rw}×{rh} "
|
|
1518
|
+
f"(배율 {dpr:g}) 이 작아 영상이 흐릴 수 있다")
|
|
1519
|
+
page = ScenarioPage(pg)
|
|
1520
|
+
|
|
1521
|
+
page.goto(mod.START_URL, wait_until="domcontentloaded")
|
|
1522
|
+
page.wait_for_timeout(2000)
|
|
1523
|
+
if hasattr(mod, "prepare"):
|
|
1524
|
+
mod.prepare(page) # 로그인 · 이동 · 준비 상태 확인
|
|
1525
|
+
|
|
1526
|
+
d = make_director(page, page_created, url_timeline, mod)
|
|
1527
|
+
video_offset = d.t0 - page_created
|
|
1528
|
+
run_scenario(mod, d)
|
|
1529
|
+
|
|
1530
|
+
time.sleep(TAIL_SEC) # 마지막 전환이 끝나는 것까지 담고, 끝맺음 페이드에 여유를 둔다
|
|
1531
|
+
index = rec.stop()
|
|
1532
|
+
# 녹화가 같이 적어 둔 것: 주소 이동 (새 문서 로드와 SPA 의 pushState), 프레임 크기 변화, 탭 교체, 안 보임.
|
|
1533
|
+
# 주소 타임라인은 렌더 단계가 브라우저 창 프레임의 주소창에 그린다.
|
|
1534
|
+
for ev in index.get("events", []):
|
|
1535
|
+
t = round(float(ev["t"]) - rec.wall0, 3)
|
|
1536
|
+
if ev["type"] == "nav":
|
|
1537
|
+
url_timeline.append([t, ev["url"]])
|
|
1538
|
+
elif ev["type"] == "size":
|
|
1539
|
+
fsizes.append([t, int(ev["width"]), int(ev["height"])])
|
|
1540
|
+
elif ev["type"] == "replaced":
|
|
1541
|
+
replaced.append(t)
|
|
1542
|
+
hidden += [round(v["at"] / 1000, 3) for v in index.get("visibility", []) if not v.get("visible")]
|
|
1543
|
+
# 상태 표시를 되살린다 (곧 세션을 닫지만, 숨긴 채로 남기지 않는다).
|
|
1544
|
+
pg.cdp("Page.removeScriptToEvaluateOnNewDocument", {"identifier": hide_id})
|
|
1545
|
+
pg._call("evaluate", UNHIDE_PB_JS)
|
|
1546
|
+
finally:
|
|
1547
|
+
rec.kill() # 오류로 나갈 때: 세션이 닫히기 전에 녹화를 멈춘다 (정상 경로에서는 이미 멈춰 있어 아무 일도 없다)
|
|
1548
|
+
stats = assemble_cfr(index, out, width, height, cube)
|
|
1549
|
+
finally:
|
|
1550
|
+
if rec:
|
|
1551
|
+
rec.kill()
|
|
1552
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
1553
|
+
|
|
1554
|
+
small = small_frames(fsizes, width, height)
|
|
1555
|
+
if small:
|
|
1556
|
+
spans = ", ".join(f"{max(a - video_offset, 0):.1f}~{(f'{e - video_offset:.1f}' if e else '끝')}초 ({w}×{h})" for a, e, w, h in small)
|
|
1557
|
+
warn(f"녹화 중 프레임이 {width}×{height} 보다 작게 들어온 구간이 있다: {spans}. "
|
|
1558
|
+
"그 구간은 페이지가 영상에 작게 찍혔다. 다시 찍는다")
|
|
1559
|
+
if replaced:
|
|
1560
|
+
warn(f"녹화 중 브라우저가 탭을 내렸다가 새 탭으로 다시 띄웠다 (영상 {replaced} 초). 페이지가 새로 읽혀 그 순간 화면이 "
|
|
1561
|
+
"처음부터 다시 그려졌다. 이어서 찍었지만 장면이 어긋났으면 다시 찍는다")
|
|
1562
|
+
if hidden:
|
|
1563
|
+
warn(f"녹화 중 브라우저가 탭을 '안 보임' 으로 알렸다 (영상 {hidden} 초). 그동안 화면이 멈춰 있을 수 있다. "
|
|
1564
|
+
"에이전트 창을 최소화하지 말 것")
|
|
1565
|
+
url_timeline.sort(key=lambda e: e[0])
|
|
1566
|
+
url_timeline[:] = [e for i, e in enumerate(url_timeline) if i == 0 or url_timeline[i - 1][1] != e[1]] # 같은 주소가 잇따르면 하나로
|
|
1567
|
+
meta.write_text(json.dumps({
|
|
1568
|
+
"scenario": scenario_path.name,
|
|
1569
|
+
"video_offset": round(video_offset, 2),
|
|
1570
|
+
"fast_ranges": d.fast_ranges,
|
|
1571
|
+
"size": [width, height],
|
|
1572
|
+
"url_timeline": url_timeline,
|
|
1573
|
+
"url_pointers": d.url_pointers,
|
|
1574
|
+
"captions": d.captions,
|
|
1575
|
+
"zoom_keyframes": d.zoom_keyframes,
|
|
1576
|
+
"marks": d.marks,
|
|
1577
|
+
"title": _json_safe(getattr(mod, "TITLE", None)),
|
|
1578
|
+
"style": _json_safe(d.style),
|
|
1579
|
+
"recorder": {"browser": "parallel-browser", **stats, "hidden_at": hidden, "frame_sizes": fsizes,
|
|
1580
|
+
"view_scale": view_mode, "tab_area": [rw, rh, dpr]},
|
|
1581
|
+
"color_fix": color,
|
|
1582
|
+
}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
1583
|
+
print(json.dumps({"video": str(out), "meta": str(meta),
|
|
1584
|
+
"offset": round(video_offset, 2),
|
|
1585
|
+
"fast_ranges": d.fast_ranges,
|
|
1586
|
+
"urls": len(url_timeline),
|
|
1587
|
+
"frames": stats,
|
|
1588
|
+
"color_fix": color,
|
|
1589
|
+
"warnings": WARNINGS}, ensure_ascii=False))
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
def _json_safe(value):
|
|
1593
|
+
"""STYLE 은 시나리오 모듈의 dict 라 JSON 에 못 싣는 값이 섞일 수 있다 — 그런 값만 뺀다."""
|
|
1594
|
+
try:
|
|
1595
|
+
json.dumps(value)
|
|
1596
|
+
return value
|
|
1597
|
+
except TypeError:
|
|
1598
|
+
if isinstance(value, dict):
|
|
1599
|
+
return {k: _json_safe(v) for k, v in value.items() if _json_safe(v) is not None}
|
|
1600
|
+
return None
|
|
1601
|
+
|
|
1602
|
+
|
|
1603
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1604
|
+
# render
|
|
1605
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1606
|
+
def duration(path: Path) -> float:
|
|
1607
|
+
return float(subprocess.run(
|
|
1608
|
+
["ffprobe", "-v", "error", "-show_entries", "format=duration",
|
|
1609
|
+
"-of", "default=nw=1:nk=1", str(path)],
|
|
1610
|
+
capture_output=True, text=True, check=True).stdout.strip())
|
|
1611
|
+
|
|
1612
|
+
|
|
1613
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1614
|
+
# 브라우저 창 프레임 (주소창 자동 표시)
|
|
1615
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1616
|
+
FRAME_HTML = HERE / "frame.html"
|
|
1617
|
+
# 최종 영상 크기는 늘 이것이다. record 는 창 프레임을 붙였을 때 이 크기가 되게 녹화 크기를 고르고, render 는 마지막에
|
|
1618
|
+
# 다른 크기면 비율을 지켜 맞추고 남는 곳을 검게 채운다 (2026-10-11 사용자 요청: 1920×1080 고정).
|
|
1619
|
+
OUT_W, OUT_H = 1920, 1080
|
|
1620
|
+
# 자막은 페이지 위가 아니라 창 아래 띠에 그린다 (2026-10-11 사용자: 자막이 실제 화면을 가린다). 띠 높이 기본값.
|
|
1621
|
+
CAPTION_BAND = 120
|
|
1622
|
+
|
|
1623
|
+
FRAME_DEFAULTS: dict = {
|
|
1624
|
+
"bg": None, # 배경 CSS (None 이면 기본 그라디언트)
|
|
1625
|
+
"pad": 64, # 창 바깥 여백(px), 위 · 왼쪽 · 오른쪽
|
|
1626
|
+
"band": 120, # 창 아래 자막 띠 높이(px). 자막이 페이지를 가리지 않게 창 밖 아래에 둔다
|
|
1627
|
+
"bar": 48, # 타이틀바 높이(px)
|
|
1628
|
+
"radius": 14, # 창 모서리 반지름(px)
|
|
1629
|
+
"hide_scheme": True, # http:// 를 숨긴다
|
|
1630
|
+
"hide_query": False, # ?a=b 를 숨긴다
|
|
1631
|
+
"origin": None, # 로컬 origin 을 이 문자열로 바꿔 보여 준다 (예: "aidu.studio")
|
|
1632
|
+
"rewrite": [], # [[정규식, 치환], ...] — origin 치환 뒤에 순서대로 적용
|
|
1633
|
+
}
|
|
1634
|
+
DEFAULT_BG = "linear-gradient(135deg, #dbe4f3 0%, #e9e2f7 45%, #fbe3e7 100%)"
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
def frame_config(style: dict | None, cli_frame: str | None) -> dict | None:
|
|
1638
|
+
"""STYLE["frame"] 과 CLI(--frame/--no-frame)를 합쳐 프레임 설정을 만든다. None 이면 프레임 없음."""
|
|
1639
|
+
raw = (style or {}).get("frame", True)
|
|
1640
|
+
if cli_frame == "off":
|
|
1641
|
+
return None
|
|
1642
|
+
if cli_frame == "on" and raw is False:
|
|
1643
|
+
raw = True
|
|
1644
|
+
if raw is False:
|
|
1645
|
+
return None
|
|
1646
|
+
cfg = dict(FRAME_DEFAULTS)
|
|
1647
|
+
if isinstance(raw, dict):
|
|
1648
|
+
cfg.update({k: v for k, v in raw.items() if k in FRAME_DEFAULTS})
|
|
1649
|
+
if not cfg["bg"]:
|
|
1650
|
+
cfg["bg"] = DEFAULT_BG
|
|
1651
|
+
return cfg
|
|
1652
|
+
|
|
1653
|
+
|
|
1654
|
+
def display_url(url: str, cfg: dict) -> tuple[str, str]:
|
|
1655
|
+
"""주소창에 보일 (host, 나머지) — 사람이 읽기 좋게 다듬는다."""
|
|
1656
|
+
import re
|
|
1657
|
+
from urllib.parse import urlsplit, unquote
|
|
1658
|
+
|
|
1659
|
+
parts = urlsplit(url)
|
|
1660
|
+
host = parts.netloc
|
|
1661
|
+
rest = parts.path or "/"
|
|
1662
|
+
if parts.query and not cfg["hide_query"]:
|
|
1663
|
+
rest += "?" + unquote(parts.query)
|
|
1664
|
+
if parts.fragment:
|
|
1665
|
+
rest += "#" + parts.fragment
|
|
1666
|
+
if cfg["origin"]:
|
|
1667
|
+
host = str(cfg["origin"])
|
|
1668
|
+
shown = host + rest
|
|
1669
|
+
if not cfg["hide_scheme"]:
|
|
1670
|
+
shown = f"{parts.scheme}://{shown}"
|
|
1671
|
+
for pattern, repl in cfg.get("rewrite") or []:
|
|
1672
|
+
shown = re.sub(pattern, repl, shown)
|
|
1673
|
+
# host 는 진하게, 나머지는 옅게 — 다듬은 뒤 다시 가른다
|
|
1674
|
+
body = shown.split("://", 1)[-1]
|
|
1675
|
+
prefix = shown[: len(shown) - len(body)]
|
|
1676
|
+
cut = len(body)
|
|
1677
|
+
for sep in ("/", "?", "#"):
|
|
1678
|
+
i = body.find(sep)
|
|
1679
|
+
if i >= 0:
|
|
1680
|
+
cut = min(cut, i)
|
|
1681
|
+
return prefix + body[:cut], body[cut:]
|
|
1682
|
+
|
|
1683
|
+
|
|
1684
|
+
def canvas_size(w: int, h: int, cfg: dict) -> tuple[int, int]:
|
|
1685
|
+
cw = w + 2 * cfg["pad"]
|
|
1686
|
+
ch = h + cfg["bar"] + cfg["pad"] + cfg["band"] # 위는 여백, 아래는 자막 띠
|
|
1687
|
+
return cw + (cw % 2), ch + (ch % 2) # h264 는 홀수 해상도를 거부한다
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
def hole_path(cfg: dict, w: int, h: int, cw: int, ch: int) -> str:
|
|
1691
|
+
"""배경을 도려낼 evenodd 경로 — 바깥 사각형 + 영상 자리(아래 두 모서리만 둥근 사각형)."""
|
|
1692
|
+
x, y, r = cfg["pad"], cfg["pad"] + cfg["bar"], cfg["radius"]
|
|
1693
|
+
outer = f"M0 0H{cw}V{ch}H0Z"
|
|
1694
|
+
inner = (f"M{x} {y}H{x + w}V{y + h - r}"
|
|
1695
|
+
f"A{r} {r} 0 0 1 {x + w - r} {y + h}H{x + r}"
|
|
1696
|
+
f"A{r} {r} 0 0 1 {x} {y + h - r}Z")
|
|
1697
|
+
return outer + inner
|
|
1698
|
+
|
|
1699
|
+
|
|
1700
|
+
FrameKey = tuple # (url, pointer_label | None, pointer_direction | None)
|
|
1701
|
+
|
|
1702
|
+
|
|
1703
|
+
def render_frame_pngs(keys: list[FrameKey], cfg: dict, w: int, h: int, outdir: Path,
|
|
1704
|
+
style: dict | None, renderer: PngRenderer) -> dict[FrameKey, Path]:
|
|
1705
|
+
"""(주소, 주소창 화살표) 조합마다 창 프레임 PNG 한 장 (영상 자리는 투명)."""
|
|
1706
|
+
cw, ch = canvas_size(w, h, cfg)
|
|
1707
|
+
template = FRAME_HTML.read_text(encoding="utf-8")
|
|
1708
|
+
style = style or {}
|
|
1709
|
+
made: dict[FrameKey, Path] = {}
|
|
1710
|
+
for i, key in enumerate(keys):
|
|
1711
|
+
url, label, direction = key
|
|
1712
|
+
host, rest = display_url(url, cfg)
|
|
1713
|
+
pointer = None
|
|
1714
|
+
if label:
|
|
1715
|
+
pointer = {"label": label, "direction": direction or "우하",
|
|
1716
|
+
"accent": style.get("accent"), "bubble": style.get("bubble"),
|
|
1717
|
+
"gapX": style.get("gapX"), "gapY": style.get("gapY")}
|
|
1718
|
+
html = (template
|
|
1719
|
+
.replace("__CW__", str(cw)).replace("__CH__", str(ch))
|
|
1720
|
+
.replace("__PAD__", str(cfg["pad"])).replace("__BAR__", str(cfg["bar"]))
|
|
1721
|
+
.replace("__W__", str(w)).replace("__H__", str(h)).replace("__R__", str(cfg["radius"]))
|
|
1722
|
+
.replace("__BG__", cfg["bg"])
|
|
1723
|
+
.replace("__HOLE_PATH__", hole_path(cfg, w, h, cw, ch))
|
|
1724
|
+
.replace("__URL_HOST__", _esc(host)).replace("__URL_REST__", _esc(rest))
|
|
1725
|
+
.replace("__POINTER_JSON__", json.dumps(pointer, ensure_ascii=False)))
|
|
1726
|
+
made[key] = renderer.shot(html, cw, ch, outdir / f"frame-{i}.png", transparent=True, settle_ms=120)
|
|
1727
|
+
return made
|
|
1728
|
+
|
|
1729
|
+
|
|
1730
|
+
def split_by_pointers(segs: list[tuple[float, float, str]],
|
|
1731
|
+
pointers: list[tuple[float, float, str, str]]) -> list[tuple[float, float, FrameKey]]:
|
|
1732
|
+
"""주소 구간을 화살표 구간 경계로 쪼개 (시작, 끝, (url, label, direction)) 목록으로."""
|
|
1733
|
+
cuts = sorted({t for a, b, _, _ in pointers for t in (a, b)})
|
|
1734
|
+
out: list[tuple[float, float, FrameKey]] = []
|
|
1735
|
+
for a, b, url in segs:
|
|
1736
|
+
edges = [a] + [t for t in cuts if a < t < b] + [b]
|
|
1737
|
+
for s, e in zip(edges, edges[1:]):
|
|
1738
|
+
mid = (s + e) / 2
|
|
1739
|
+
hit = next(((lb, dr) for pa, pb, lb, dr in pointers if pa <= mid < pb), (None, None))
|
|
1740
|
+
out.append((s, e, (url, hit[0], hit[1])))
|
|
1741
|
+
return out
|
|
1742
|
+
|
|
1743
|
+
|
|
1744
|
+
def _esc(s: str) -> str:
|
|
1745
|
+
return s.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
1746
|
+
|
|
1747
|
+
|
|
1748
|
+
def url_segments(timeline: list, offset: float, total: float,
|
|
1749
|
+
to_out) -> list[tuple[float, float, str]]:
|
|
1750
|
+
"""영상 시각의 주소 타임라인 → 출력 시각 구간 [(시작, 끝, url)]."""
|
|
1751
|
+
entries = sorted((float(t), u) for t, u in (timeline or []))
|
|
1752
|
+
if not entries:
|
|
1753
|
+
return []
|
|
1754
|
+
current = entries[0][1]
|
|
1755
|
+
for t, u in entries:
|
|
1756
|
+
if t <= offset:
|
|
1757
|
+
current = u
|
|
1758
|
+
later = [(t, u) for t, u in entries if t > offset]
|
|
1759
|
+
segs: list[tuple[float, float, str]] = []
|
|
1760
|
+
start_t = offset
|
|
1761
|
+
for t, u in later:
|
|
1762
|
+
if u == current:
|
|
1763
|
+
continue
|
|
1764
|
+
segs.append((to_out(start_t), to_out(t), current))
|
|
1765
|
+
current, start_t = u, t
|
|
1766
|
+
segs.append((to_out(start_t), to_out(total) + 1.0, current))
|
|
1767
|
+
return [s for s in segs if s[1] - s[0] > 0.0]
|
|
1768
|
+
|
|
1769
|
+
|
|
1770
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1771
|
+
# 줌 (zoompan, ease-in-out) + 줌 구간 자막 레이어
|
|
1772
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
1773
|
+
CAPTION_HTML = HERE / "caption.html"
|
|
1774
|
+
FPS = 25
|
|
1775
|
+
END_FADE_SEC = 0.8 # 영상 끝 페이드아웃(검정) 길이
|
|
1776
|
+
END_BLACK_SEC = 0.2 # 페이드가 끝난 뒤 완전한 검정으로 머무는 길이
|
|
1777
|
+
|
|
1778
|
+
|
|
1779
|
+
ZOOM_UPSCALE = 2 # zoompan 의 정수 픽셀 크롭이 튀지 않게 먼저 키운 뒤 잘라낸다
|
|
1780
|
+
|
|
1781
|
+
|
|
1782
|
+
def _ease(p: str) -> str:
|
|
1783
|
+
"""smootherstep (quintic) — 양끝의 속도·가속도가 0 이라 들어가고 나올 때 부드럽다."""
|
|
1784
|
+
q = f"clip({p},0,1)"
|
|
1785
|
+
return f"({q}*{q}*{q}*({q}*({q}*6-15)+10))"
|
|
1786
|
+
|
|
1787
|
+
|
|
1788
|
+
def _piecewise(keys: list[tuple[float, float]], T: str) -> str:
|
|
1789
|
+
"""키프레임 [(시각, 값)] → T 에서의 보간값 식. 구간 사이는 smootherstep, 밖은 양끝 값 유지."""
|
|
1790
|
+
if not keys:
|
|
1791
|
+
return "1"
|
|
1792
|
+
expr = f"{keys[-1][1]:.4f}"
|
|
1793
|
+
for (t0, v0), (t1, v1) in reversed(list(zip(keys, keys[1:]))):
|
|
1794
|
+
dt = max(t1 - t0, 0.001)
|
|
1795
|
+
seg = f"({v0:.4f}+({v1 - v0:.4f})*{_ease(f'(({T}-{t0:.3f})/{dt:.3f})')})"
|
|
1796
|
+
expr = f"if(lt({T},{t1:.3f}),{seg},{expr})"
|
|
1797
|
+
return f"if(lt({T},{keys[0][0]:.3f}),{keys[0][1]:.4f},{expr})"
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def zoom_expressions(keyframes: list[tuple[float, float, float, float]],
|
|
1801
|
+
upscale: int = ZOOM_UPSCALE) -> tuple[str, str, str]:
|
|
1802
|
+
"""출력 시각 기준 줌 키프레임 (t, z, cx, cy — 캔버스 px) → zoompan 의 z / x / y 식.
|
|
1803
|
+
zoompan 입력은 upscale 배 키운 프레임이라 중심 좌표도 그만큼 곱한다. T = 프레임 번호 / FPS."""
|
|
1804
|
+
T = f"(in/{FPS})"
|
|
1805
|
+
z = _piecewise([(t, z) for t, z, _, _ in keyframes], T)
|
|
1806
|
+
cx = _piecewise([(t, cx * upscale) for t, _, cx, _ in keyframes], T)
|
|
1807
|
+
cy = _piecewise([(t, cy * upscale) for t, _, _, cy in keyframes], T)
|
|
1808
|
+
x = f"clip({cx}-iw/(2*zoom),0,iw-iw/zoom)"
|
|
1809
|
+
y = f"clip({cy}-ih/(2*zoom),0,ih-ih/zoom)"
|
|
1810
|
+
return z, x, y
|
|
1811
|
+
|
|
1812
|
+
|
|
1813
|
+
def zoom_active_ranges(keyframes: list[tuple[float, float, float, float]]) -> list[tuple[float, float]]:
|
|
1814
|
+
"""배율이 1 을 넘는 구간 [(시작, 끝)] — 이 동안 페이지 자막이 숨겨져 있어 자막 레이어를 얹는다."""
|
|
1815
|
+
ranges, start = [], None
|
|
1816
|
+
for i, (t, z, _, _) in enumerate(keyframes):
|
|
1817
|
+
nxt = keyframes[i + 1][1] if i + 1 < len(keyframes) else 1.0
|
|
1818
|
+
if start is None and (z > 1.0 or nxt > 1.0):
|
|
1819
|
+
start = t
|
|
1820
|
+
elif start is not None and z <= 1.0 and nxt <= 1.0:
|
|
1821
|
+
ranges.append((start, t))
|
|
1822
|
+
start = None
|
|
1823
|
+
if start is not None:
|
|
1824
|
+
ranges.append((start, keyframes[-1][0]))
|
|
1825
|
+
return ranges
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
def render_caption_pngs(texts: list[str], cw: int, ch: int, bottom: int,
|
|
1829
|
+
style: dict | None, outdir: Path, renderer: PngRenderer) -> dict[str, Path]:
|
|
1830
|
+
"""자막 PNG (캔버스 크기, 투명 배경). render 가 최종 캔버스 위에 얹는다."""
|
|
1831
|
+
style = style or {}
|
|
1832
|
+
template = CAPTION_HTML.read_text(encoding="utf-8")
|
|
1833
|
+
made: dict[str, Path] = {}
|
|
1834
|
+
for i, text in enumerate(texts):
|
|
1835
|
+
html = (template.replace("__CW__", str(cw)).replace("__CH__", str(ch))
|
|
1836
|
+
.replace("__BOTTOM__", str(bottom))
|
|
1837
|
+
.replace("__BG__", str(style.get("caption", "rgba(18,18,18,0.86)")))
|
|
1838
|
+
.replace("__RADIUS__", str(style.get("captionRadius", 14)))
|
|
1839
|
+
.replace("__FONT__", str(style.get("font", "system-ui,-apple-system,'Apple SD Gothic Neo',sans-serif")))
|
|
1840
|
+
.replace("__TEXT__", _esc(text)))
|
|
1841
|
+
made[text] = renderer.shot(html, cw, ch, outdir / f"caption-{i}.png", transparent=True, settle_ms=60)
|
|
1842
|
+
return made
|
|
1843
|
+
|
|
1844
|
+
|
|
1845
|
+
def caption_pieces(captions: list, ranges: list[tuple[float, float]], offset: float,
|
|
1846
|
+
total: float, to_out) -> list[tuple[float, float, str]]:
|
|
1847
|
+
"""ranges 와 겹치는 자막 조각 [(시작, 끝, 문구)] (출력 시각). 전체를 원하면 [(0, 큰 값)]."""
|
|
1848
|
+
entries = sorted((float(t), text) for t, text in (captions or []))
|
|
1849
|
+
pieces: list[tuple[float, float, str]] = []
|
|
1850
|
+
for i, (t, text) in enumerate(entries):
|
|
1851
|
+
if not text:
|
|
1852
|
+
continue
|
|
1853
|
+
start = max(to_out(max(t, offset)), 0.0)
|
|
1854
|
+
end = to_out(min(entries[i + 1][0], total)) if i + 1 < len(entries) else to_out(total) + 1.0
|
|
1855
|
+
for z0, z1 in ranges:
|
|
1856
|
+
a, b = max(start, z0), min(end, z1)
|
|
1857
|
+
if b - a > 0.02:
|
|
1858
|
+
pieces.append((a, b, text))
|
|
1859
|
+
return pieces
|
|
1860
|
+
|
|
1861
|
+
|
|
1862
|
+
CAPTION_FADE = 0.18 # 자막이 나타나고 사라지는 시간 (초)
|
|
1863
|
+
SPEED_FLASH_SEC = 1.0 # 빨리 감기가 시작될 때 가운데 "▶▶ ×N" 을 보이는 시간
|
|
1864
|
+
|
|
1865
|
+
|
|
1866
|
+
def overlay_timed(graph: str, label: str, inputs: list, items: list, tag: str) -> tuple[str, str]:
|
|
1867
|
+
"""[(시작, 끝, PNG, 페이드 초)] 를 출력 시각에 맞춰 얹는다. PNG 는 반복 입력으로 넣어 알파 페이드를 건다."""
|
|
1868
|
+
prev = label
|
|
1869
|
+
for i, (a, b, png, fd) in enumerate(items):
|
|
1870
|
+
idx = _input_count(inputs)
|
|
1871
|
+
inputs += ["-loop", "1", "-t", f"{b + 0.5:.3f}", "-i", str(png)]
|
|
1872
|
+
fd = max(0.0, min(fd, (b - a) / 2))
|
|
1873
|
+
graph += (f";[{idx}:v]format=rgba,fade=t=in:st={a:.3f}:d={fd:.3f}:alpha=1,"
|
|
1874
|
+
f"fade=t=out:st={max(b - fd, a):.3f}:d={fd:.3f}:alpha=1[{tag}p{i}]"
|
|
1875
|
+
f";{prev}[{tag}p{i}]overlay=0:0:eof_action=pass:enable='between(t,{a:.3f},{b:.3f})'[{tag}{i}]")
|
|
1876
|
+
prev = f"[{tag}{i}]"
|
|
1877
|
+
return graph, prev
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def _input_count(inputs: list) -> int:
|
|
1881
|
+
return sum(1 for x in inputs if x == "-i")
|
|
1882
|
+
|
|
1883
|
+
|
|
1884
|
+
def render_speed_png(speed: float, cw: int, ch: int, style: dict, outdir: Path, renderer: PngRenderer) -> Path:
|
|
1885
|
+
"""빨리 감기가 시작될 때 가운데에 1초 보이는 큰 "▶▶ ×N" (투명 배경)."""
|
|
1886
|
+
sp = int(speed) if float(speed) == int(speed) else speed
|
|
1887
|
+
return render_badge_png(f"▶▶ ×{sp}", cw, ch, style, outdir, renderer, f"speed-{sp}")
|
|
1888
|
+
|
|
1889
|
+
|
|
1890
|
+
CUT_FLASH_SEC = 1.2 # d.cut 으로 잘라 낸 자리에 "▶▶| 3분 뒤" 를 보이는 시간 (⏩ 는 이모지로 그려져 쓰지 않는다)
|
|
1891
|
+
|
|
1892
|
+
|
|
1893
|
+
def render_badge_png(text: str, cw: int, ch: int, style: dict, outdir: Path, renderer: PngRenderer, name: str) -> Path:
|
|
1894
|
+
"""가운데 큰 배지 하나 (투명 배경). 배속 시작 "▶▶ ×N" 과 잘라 낸 자리 "▶▶| 3분 뒤" 가 같은 생김새다."""
|
|
1895
|
+
font = str(style.get("font", "system-ui,-apple-system,'Apple SD Gothic Neo',sans-serif"))
|
|
1896
|
+
size = 88 if len(text) <= 8 else 64
|
|
1897
|
+
html = (f"<html><head><meta charset='utf-8'><style>html,body{{margin:0;width:{cw}px;height:{ch}px;background:transparent}}"
|
|
1898
|
+
f".b{{position:absolute;left:50%;top:46%;transform:translate(-50%,-50%);padding:30px 56px;border-radius:28px;"
|
|
1899
|
+
f"background:{style.get('caption', 'rgba(18,18,18,0.78)')};color:#fff;font:800 {size}px/1 {font};letter-spacing:.02em;"
|
|
1900
|
+
f"white-space:nowrap;box-shadow:0 10px 40px rgba(0,0,0,.3)}}</style></head><body><div class='b'>{_esc(text)}</div></body></html>")
|
|
1901
|
+
return renderer.shot(html, cw, ch, outdir / f"{name}.png", transparent=True, settle_ms=60)
|
|
1902
|
+
|
|
1903
|
+
|
|
1904
|
+
def render_stripe_png(cw: int, ch: int, left: int, top: int, width: int, style: dict, outdir: Path,
|
|
1905
|
+
renderer: PngRenderer) -> Path:
|
|
1906
|
+
"""빨리 감는 동안 페이지 위쪽에 남는 줄무늬 띠 (투명 배경)."""
|
|
1907
|
+
acc = str(style.get("fastStripe", "#e5484d"))
|
|
1908
|
+
html = (f"<html><head><meta charset='utf-8'><style>html,body{{margin:0;width:{cw}px;height:{ch}px;background:transparent}}"
|
|
1909
|
+
f".s{{position:absolute;left:{left}px;top:{top}px;width:{width}px;height:8px;"
|
|
1910
|
+
f"background:repeating-linear-gradient(90deg,{acc} 0 40px,#ff8a8d 40px 80px)}}</style></head>"
|
|
1911
|
+
f"<body><div class='s'></div></body></html>")
|
|
1912
|
+
return renderer.shot(html, cw, ch, outdir / "stripe.png", transparent=True, settle_ms=60)
|
|
1913
|
+
|
|
1914
|
+
|
|
1915
|
+
def render_title_pngs(title: dict, cw: int, ch: int, bg_css: str, outdir: Path,
|
|
1916
|
+
renderer: PngRenderer) -> tuple[Path, Path]:
|
|
1917
|
+
"""타이틀 카드 두 장. 배경만(불투명) + 글자만(투명). 글자 레이어는 ffmpeg 가 애니메이션한다."""
|
|
1918
|
+
template = TITLE_HTML.read_text(encoding="utf-8")
|
|
1919
|
+
made = []
|
|
1920
|
+
for mode in ("bg", "text"):
|
|
1921
|
+
html = (template.replace("__CW__", str(cw)).replace("__CH__", str(ch))
|
|
1922
|
+
.replace("__BG__", bg_css).replace("__MODE__", mode)
|
|
1923
|
+
.replace("__BADGE__", _esc(str(title.get("badge") or "")))
|
|
1924
|
+
.replace("__TITLE__", _esc(str(title.get("title") or "")))
|
|
1925
|
+
.replace("__SUBTITLE__", _esc(str(title.get("subtitle") or ""))))
|
|
1926
|
+
made.append(renderer.shot(html, cw, ch, outdir / f"title-{mode}.png",
|
|
1927
|
+
transparent=(mode == "text"), settle_ms=120))
|
|
1928
|
+
return made[0], made[1]
|
|
1929
|
+
|
|
1930
|
+
|
|
1931
|
+
def render(src: Path, meta_path: Path, out: Path, default_speed: float,
|
|
1932
|
+
cli_frame: str | None = None, color_fix: bool = True, trim_end: float = 0.0) -> None:
|
|
1933
|
+
"""창 프레임 · 줌 자막 · 타이틀 PNG 는 parallel-browser 탭 하나에서 찍는다. 그 탭은 PNG 를 다 찍으면
|
|
1934
|
+
(ffmpeg 인코딩 전에) 닫고, 도중에 오류가 나도 닫는다."""
|
|
1935
|
+
if pbpage is None:
|
|
1936
|
+
raise SystemExit(f"pbpage 를 불러오지 못했다 ({PB_LIB}). doctor 를 먼저 돌린다")
|
|
1937
|
+
for f in (src, meta_path):
|
|
1938
|
+
if not f.is_file():
|
|
1939
|
+
raise SystemExit(f"없는 파일: {f} (record 가 실패했으면 --out · --meta 가 지워져 있다. record 의 RESULT 줄을 본다)")
|
|
1940
|
+
if out.exists(): # 실패하면 옛 결과물이 남아 있지 않게
|
|
1941
|
+
out.unlink()
|
|
1942
|
+
with PngRenderer(color_fix) as renderer:
|
|
1943
|
+
_render(src, meta_path, out, default_speed, cli_frame, renderer, trim_end)
|
|
1944
|
+
|
|
1945
|
+
|
|
1946
|
+
def _render(src: Path, meta_path: Path, out: Path, default_speed: float,
|
|
1947
|
+
cli_frame: str | None, renderer: PngRenderer, trim_end: float = 0.0) -> None:
|
|
1948
|
+
if not SPEED_MIN <= default_speed <= SPEED_MAX:
|
|
1949
|
+
raise SystemExit(f"배속은 {SPEED_MIN:g} ~ {SPEED_MAX:g} 사이여야 합니다")
|
|
1950
|
+
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
1951
|
+
offset = float(meta.get("video_offset", 0.0))
|
|
1952
|
+
total = duration(src)
|
|
1953
|
+
if trim_end > 0:
|
|
1954
|
+
# 원본 끝을 잘라 낸다 (마지막 장면이 너무 길게 찍혔을 때). 페이드아웃 · 메타 시각은 잘린 끝에 맞춰진다.
|
|
1955
|
+
if total - trim_end < offset + 0.5:
|
|
1956
|
+
raise SystemExit(f"--trim-end {trim_end:g} 초면 본편이 남지 않는다 (원본 {total:.1f}초, 준비 구간 {offset:.1f}초)")
|
|
1957
|
+
total -= trim_end
|
|
1958
|
+
|
|
1959
|
+
# 본편 기준 시각 → 영상 타임라인 시각. 구간이 자기 배속을 들고 있으면 그것을 쓴다. 배속 0 은 잘라 내기 (d.cut).
|
|
1960
|
+
def _speed(r) -> float:
|
|
1961
|
+
sp = float(r[2]) if len(r) > 2 else default_speed
|
|
1962
|
+
return 0.0 if sp == 0 else min(max(sp, SPEED_MIN), SPEED_MAX)
|
|
1963
|
+
ranges = [(offset + r[0], min(offset + r[1], total), _speed(r), str(r[3]) if len(r) > 3 else "")
|
|
1964
|
+
for r in meta.get("fast_ranges", []) if offset + r[0] < total]
|
|
1965
|
+
fast = [(a, b, sp) for a, b, sp, _ in ranges]
|
|
1966
|
+
|
|
1967
|
+
parts: list[tuple[float, float, float]] = []
|
|
1968
|
+
cursor = offset
|
|
1969
|
+
for a, b, sp in fast:
|
|
1970
|
+
if a > cursor:
|
|
1971
|
+
parts.append((cursor, a, 1.0))
|
|
1972
|
+
parts.append((a, min(b, total), sp))
|
|
1973
|
+
cursor = min(b, total)
|
|
1974
|
+
if cursor < total:
|
|
1975
|
+
parts.append((cursor, total, 1.0))
|
|
1976
|
+
|
|
1977
|
+
chains, labels = [], []
|
|
1978
|
+
for i, (a, b, sp) in enumerate(parts):
|
|
1979
|
+
if b - a < 0.1 or sp == 0:
|
|
1980
|
+
continue
|
|
1981
|
+
pts = "PTS-STARTPTS" if sp == 1.0 else f"(PTS-STARTPTS)/{sp}"
|
|
1982
|
+
chains.append(f"[0:v]trim={a:.3f}:{b:.3f},setpts={pts}[v{i}]")
|
|
1983
|
+
labels.append(f"[v{i}]")
|
|
1984
|
+
if not labels:
|
|
1985
|
+
raise SystemExit("자를 구간이 없습니다 — 녹화가 비어 있는지 확인하세요")
|
|
1986
|
+
graph = ";".join(chains) + f";{''.join(labels)}concat=n={len(labels)}:v=1[out]"
|
|
1987
|
+
|
|
1988
|
+
# 영상 시각 → 출력 시각 (잘라낸 앞부분과 배속 구간을 반영)
|
|
1989
|
+
def to_out(t: float) -> float:
|
|
1990
|
+
acc = 0.0
|
|
1991
|
+
for a, b, sp in parts:
|
|
1992
|
+
if t <= a:
|
|
1993
|
+
break
|
|
1994
|
+
if sp:
|
|
1995
|
+
acc += (min(t, b) - a) / sp
|
|
1996
|
+
return acc
|
|
1997
|
+
|
|
1998
|
+
# 브라우저 창 프레임 — 주소 타임라인 구간마다 PNG 를 얹는다 (영상 자리는 투명 구멍).
|
|
1999
|
+
inputs = ["-i", str(src)]
|
|
2000
|
+
final_label = "[out]"
|
|
2001
|
+
cfg = frame_config(meta.get("style"), cli_frame)
|
|
2002
|
+
segs: list[tuple[float, float, str]] = []
|
|
2003
|
+
tmpdir: Path | None = None
|
|
2004
|
+
if cfg:
|
|
2005
|
+
w, h = meta.get("size", [1440, 900])
|
|
2006
|
+
segs = url_segments(meta.get("url_timeline"), offset, total, to_out)
|
|
2007
|
+
if not segs:
|
|
2008
|
+
segs = [(0.0, to_out(total) + 1.0, "")]
|
|
2009
|
+
# 주소창 화살표(d.point_url) 구간 — 출력 시각으로 환산해 주소 구간을 다시 쪼갠다.
|
|
2010
|
+
pointers = [(to_out(float(p[0])), to_out(float(p[1])), str(p[2]), str(p[3] or "우하"))
|
|
2011
|
+
for p in meta.get("url_pointers") or [] if p[1] is not None]
|
|
2012
|
+
pieces = split_by_pointers(segs, pointers)
|
|
2013
|
+
tmpdir = Path(tempfile.mkdtemp(prefix="dv-frame-"))
|
|
2014
|
+
pngs = render_frame_pngs(list(dict.fromkeys(k for _, _, k in pieces)), cfg, w, h, tmpdir,
|
|
2015
|
+
meta.get("style"), renderer)
|
|
2016
|
+
cw, ch = canvas_size(w, h, cfg)
|
|
2017
|
+
order = list(pngs)
|
|
2018
|
+
for png in pngs.values():
|
|
2019
|
+
inputs += ["-i", str(png)]
|
|
2020
|
+
graph += f";[out]pad={cw}:{ch}:{cfg['pad']}:{cfg['pad'] + cfg['bar']}:color=black[pad0]"
|
|
2021
|
+
prev = "[pad0]"
|
|
2022
|
+
for i, (a, b, key) in enumerate(pieces):
|
|
2023
|
+
idx = order.index(key) + 1
|
|
2024
|
+
nxt = f"[fr{i}]"
|
|
2025
|
+
# PNG 입력은 1 프레임짜리라 곧 EOF — repeat 로 마지막 프레임을 계속 쓴다
|
|
2026
|
+
# (pass 면 EOF 뒤로 오버레이 없이 통과돼 프레임이 사라진다).
|
|
2027
|
+
graph += (f";{prev}[{idx}:v]overlay=0:0:eof_action=repeat:"
|
|
2028
|
+
f"enable='between(t,{a:.3f},{b:.3f})'{nxt}")
|
|
2029
|
+
prev = nxt
|
|
2030
|
+
final_label = prev
|
|
2031
|
+
|
|
2032
|
+
# 줌 — 합성이 끝난 캔버스 전체를 ease-in-out 으로 crop + scale (카메라가 다가가듯).
|
|
2033
|
+
# 페이지 자막은 줌 구간 동안 숨겨져 있으므로, 같은 생김새의 자막 PNG 를 확대 밖에 다시 얹는다.
|
|
2034
|
+
w0, h0 = meta.get("size", [1440, 900])
|
|
2035
|
+
if not cfg: # 프레임이 없으면 영상 아래에 검은 자막 띠를 붙인다 (자막이 페이지를 가리지 않게)
|
|
2036
|
+
graph += f";{final_label}pad={w0}:{h0 + CAPTION_BAND}:0:0:color=black[banded]"
|
|
2037
|
+
final_label = "[banded]"
|
|
2038
|
+
cw, ch = canvas_size(w0, h0, cfg) if cfg else (w0, h0 + CAPTION_BAND)
|
|
2039
|
+
ox, oy = (cfg["pad"], cfg["pad"] + cfg["bar"]) if cfg else (0, 0)
|
|
2040
|
+
def _center(v, axis: str) -> float:
|
|
2041
|
+
if v == "url": # 주소창 가운데 (프레임이 없으면 화면 위쪽 가운데)
|
|
2042
|
+
if axis == "x":
|
|
2043
|
+
return cw / 2
|
|
2044
|
+
return cfg["pad"] + cfg["bar"] / 2 if cfg else 0.0
|
|
2045
|
+
return float(v) + (ox if axis == "x" else oy)
|
|
2046
|
+
|
|
2047
|
+
keyframes = [(to_out(float(k[0])), float(k[1]), _center(k[2], "x"), _center(k[3], "y"))
|
|
2048
|
+
for k in meta.get("zoom_keyframes") or []]
|
|
2049
|
+
if keyframes:
|
|
2050
|
+
zx, xx, yx = zoom_expressions(keyframes)
|
|
2051
|
+
graph += (f";{final_label}fps={FPS},scale={cw * ZOOM_UPSCALE}:{ch * ZOOM_UPSCALE}:flags=lanczos,"
|
|
2052
|
+
f"zoompan=z='{zx}':x='{xx}':y='{yx}':d=1:s={cw}x{ch}:fps={FPS}[zoomed]")
|
|
2053
|
+
final_label = "[zoomed]"
|
|
2054
|
+
zooms = zoom_active_ranges(keyframes)
|
|
2055
|
+
|
|
2056
|
+
# 자막 · 배속 표시 — 확대가 끝난 최종 캔버스 위에 얹어, 크기가 늘 캔버스 (1920×1080) 기준으로 같다.
|
|
2057
|
+
style = meta.get("style") or {}
|
|
2058
|
+
cap_pieces = caption_pieces(meta.get("captions"), [(0.0, 1e9)], offset, total, to_out)
|
|
2059
|
+
fast_out = [(to_out(a), to_out(b), sp) for a, b, sp in fast if sp and to_out(b) - to_out(a) > 0.05]
|
|
2060
|
+
cuts_out = [(to_out(a), lb) for a, _, sp, lb in ranges if sp == 0]
|
|
2061
|
+
if cap_pieces or fast_out or cuts_out:
|
|
2062
|
+
tmpdir = tmpdir or Path(tempfile.mkdtemp(prefix="dv-frame-"))
|
|
2063
|
+
if cap_pieces:
|
|
2064
|
+
band = int(cfg["band"]) if cfg else CAPTION_BAND
|
|
2065
|
+
bottom = int(style.get("captionBottom", max(8, (band - 74) // 2))) # 띠 가운데 (말풍선 높이 약 74px)
|
|
2066
|
+
cap_pngs = render_caption_pngs(list(dict.fromkeys(t for _, _, t in cap_pieces)),
|
|
2067
|
+
cw, ch, bottom, style, tmpdir, renderer)
|
|
2068
|
+
graph, final_label = overlay_timed(graph, final_label, inputs,
|
|
2069
|
+
[(a, b, cap_pngs[t], CAPTION_FADE) for a, b, t in cap_pieces], "cap")
|
|
2070
|
+
if fast_out:
|
|
2071
|
+
top = (cfg["pad"] + cfg["bar"]) if cfg else 0
|
|
2072
|
+
left = cfg["pad"] if cfg else 0
|
|
2073
|
+
stripe = render_stripe_png(cw, ch, left, top, cw - 2 * left, style, tmpdir, renderer)
|
|
2074
|
+
bigs = {sp: render_speed_png(sp, cw, ch, style, tmpdir, renderer) for _, _, sp in fast_out}
|
|
2075
|
+
items = [(a, b, stripe, 0.15) for a, b, _ in fast_out]
|
|
2076
|
+
items += [(a, min(a + SPEED_FLASH_SEC, b), bigs[sp], 0.25) for a, b, sp in fast_out]
|
|
2077
|
+
graph, final_label = overlay_timed(graph, final_label, inputs, items, "spd")
|
|
2078
|
+
if cuts_out:
|
|
2079
|
+
cards = {lb: render_badge_png(f"▶▶| {lb}" if lb else "▶▶|", cw, ch, style, tmpdir, renderer, f"cut-{i}")
|
|
2080
|
+
for i, lb in enumerate(dict.fromkeys(lb for _, lb in cuts_out))}
|
|
2081
|
+
graph, final_label = overlay_timed(graph, final_label, inputs,
|
|
2082
|
+
[(a, a + CUT_FLASH_SEC, cards[lb], 0.2) for a, lb in cuts_out], "cut")
|
|
2083
|
+
|
|
2084
|
+
# 도입부 타이틀 카드 — 배경 + 글자(페이드 · 떠오름)를 앞에 붙이고 본편으로 크로스페이드.
|
|
2085
|
+
title = meta.get("title") or None
|
|
2086
|
+
if title and (title.get("title") or title.get("badge")):
|
|
2087
|
+
tmpdir = tmpdir or Path(tempfile.mkdtemp(prefix="dv-frame-"))
|
|
2088
|
+
bg_css = cfg["bg"] if cfg else DEFAULT_BG
|
|
2089
|
+
bg_png, text_png = render_title_pngs(title, cw, ch, bg_css, tmpdir, renderer)
|
|
2090
|
+
hold = float(title.get("duration", 2.2))
|
|
2091
|
+
xfade = 0.5
|
|
2092
|
+
base = _input_count(inputs)
|
|
2093
|
+
inputs += ["-loop", "1", "-t", f"{hold + xfade:.2f}", "-i", str(bg_png),
|
|
2094
|
+
"-loop", "1", "-t", f"{hold + xfade:.2f}", "-i", str(text_png)]
|
|
2095
|
+
# 글자는 0프레임부터 그대로 보인다(썸네일에 제목이 잡히게). 끝나기 0.6초 전부터
|
|
2096
|
+
# 페이드아웃하며 24px 떠오른 뒤, 배경이 본편으로 크로스페이드한다.
|
|
2097
|
+
out_st = max(hold - 0.6, 0.0)
|
|
2098
|
+
rise = _ease(f"((t-{out_st:.2f})/0.6)")
|
|
2099
|
+
graph += (f";[{base + 1}:v]format=rgba,fade=t=out:st={out_st:.2f}:d=0.6:alpha=1[ttx];"
|
|
2100
|
+
f"[{base}:v][ttx]overlay=x=0:y='-24*{rise}':eval=frame:shortest=1[tcard];"
|
|
2101
|
+
f"[tcard]fps={FPS},format=yuv420p,setpts=PTS-STARTPTS[tc];"
|
|
2102
|
+
f"{final_label}fps={FPS},format=yuv420p,setpts=PTS-STARTPTS[main];"
|
|
2103
|
+
f"[tc][main]xfade=transition=fade:duration={xfade}:offset={hold:.2f}[titled]")
|
|
2104
|
+
final_label = "[titled]"
|
|
2105
|
+
|
|
2106
|
+
# 최종 크기를 OUT_W × OUT_H 로 고정한다. 녹화 크기를 따로 줬거나 프레임 설정이 바뀌어 캔버스가 다르면,
|
|
2107
|
+
# 비율을 지켜 맞추고 남는 곳은 검게 채운다.
|
|
2108
|
+
if (cw, ch) != (OUT_W, OUT_H):
|
|
2109
|
+
graph += (f";{final_label}scale={OUT_W}:{OUT_H}:force_original_aspect_ratio=decrease:flags=lanczos,"
|
|
2110
|
+
f"pad={OUT_W}:{OUT_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1[sized]")
|
|
2111
|
+
final_label = "[sized]"
|
|
2112
|
+
|
|
2113
|
+
# 끝맺음 — 마지막 END_FADE_SEC 동안 검게 페이드아웃 (영상이 끝났다는 신호. 자막·카드 없이 검은 화면).
|
|
2114
|
+
end_at = to_out(total) + (float(title.get("duration", 2.2)) if title and (title.get("title") or title.get("badge")) else 0.0)
|
|
2115
|
+
graph += (f";{final_label}fade=t=out:st={max(end_at - END_FADE_SEC, 0):.2f}:d={END_FADE_SEC},"
|
|
2116
|
+
f"tpad=stop_mode=add:stop_duration={END_BLACK_SEC}:color=black[faded]")
|
|
2117
|
+
final_label = "[faded]"
|
|
2118
|
+
|
|
2119
|
+
color = renderer.color
|
|
2120
|
+
renderer.close() # PNG 는 다 찍었다. 인코딩 동안 탭을 열어 두지 않는다
|
|
2121
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
2122
|
+
subprocess.run(
|
|
2123
|
+
["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", graph,
|
|
2124
|
+
"-map", final_label, "-r", "25", "-c:v", "libx264", "-pix_fmt", "yuv420p",
|
|
2125
|
+
"-crf", "22", "-preset", "medium", "-movflags", "+faststart", str(out)],
|
|
2126
|
+
check=True)
|
|
2127
|
+
if tmpdir:
|
|
2128
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
2129
|
+
lead = float(title.get("duration", 2.2)) if title and (title.get("title") or title.get("badge")) else 0.0
|
|
2130
|
+
result_sec = duration(out)
|
|
2131
|
+
# 장면 표시를 출력 시각으로 — frames --sheet 가 이 시각들을 한 장에 모은다.
|
|
2132
|
+
marks = [[round(to_out(float(t)) + lead, 2), kind, label] for t, kind, label in meta.get("marks") or []
|
|
2133
|
+
if offset - 0.05 <= float(t) <= total] # 본편 첫 자막은 offset 과 같은 시각이다 (반올림 차)
|
|
2134
|
+
marks_path = marks_file(out)
|
|
2135
|
+
marks_path.write_text(json.dumps({"video": out.name, "seconds": round(result_sec, 2), "marks": marks},
|
|
2136
|
+
ensure_ascii=False, indent=1), encoding="utf-8")
|
|
2137
|
+
qc = check_video(out, result_sec, ignore_tail=END_FADE_SEC + END_BLACK_SEC + 0.3,
|
|
2138
|
+
fast=[(a + lead, b + lead) for a, b, _ in fast_out])
|
|
2139
|
+
print(json.dumps({
|
|
2140
|
+
"out": str(out),
|
|
2141
|
+
"marks": str(marks_path),
|
|
2142
|
+
"check": qc,
|
|
2143
|
+
"source_seconds": round(total, 2),
|
|
2144
|
+
"trimmed_intro": round(offset, 2),
|
|
2145
|
+
"fast_segments": [[round(a, 2), round(b, 2), sp] for a, b, sp in fast],
|
|
2146
|
+
"frame": bool(cfg),
|
|
2147
|
+
"title": bool(title),
|
|
2148
|
+
"zoom_ranges": [[round(a, 2), round(b, 2)] for a, b in (zooms if keyframes else [])],
|
|
2149
|
+
"captions": len(cap_pieces),
|
|
2150
|
+
"url_segments": [[round(a, 2), round(min(b, to_out(total)), 2), display_url(u, cfg)[0] + display_url(u, cfg)[1] if cfg else u]
|
|
2151
|
+
for a, b, u in segs],
|
|
2152
|
+
"cuts": [[round(a + lead, 2), lb] for a, lb in cuts_out],
|
|
2153
|
+
"result_seconds": round(result_sec, 2),
|
|
2154
|
+
"png_color_fix": color,
|
|
2155
|
+
"warnings": WARNINGS,
|
|
2156
|
+
}, ensure_ascii=False))
|
|
2157
|
+
|
|
2158
|
+
|
|
2159
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2160
|
+
# check — render 가 끝나면 기계가 잴 수 있는 것은 기계가 잰다
|
|
2161
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2162
|
+
def marks_file(video: Path) -> Path:
|
|
2163
|
+
"""render 가 남기는 장면 표시 파일 (final.mp4 → final.marks.json)."""
|
|
2164
|
+
return video.with_name(video.stem + ".marks.json")
|
|
2165
|
+
|
|
2166
|
+
|
|
2167
|
+
FREEZE_SEC = 6.0 # 이보다 길게 화면이 그대로면 알린다 (자막 하나 읽는 시간은 6초 안이다)
|
|
2168
|
+
|
|
2169
|
+
|
|
2170
|
+
def check_video(path: Path, seconds: float, ignore_tail: float = 0.0, fast: list | None = None) -> dict:
|
|
2171
|
+
"""검은 화면 · 오래 멈춘 화면 · 길이를 잰다. 프레임을 하나씩 열어 보기 전에 걸러 낼 것들이다.
|
|
2172
|
+
영상 끝의 페이드아웃(ignore_tail)은 검은 화면으로 치지 않는다."""
|
|
2173
|
+
r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(path), "-vf",
|
|
2174
|
+
f"blackdetect=d=0.4:pix_th=0.08,freezedetect=n=0.002:d={FREEZE_SEC:g}", "-an", "-f", "null", "-"],
|
|
2175
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
2176
|
+
black, freezes = [], []
|
|
2177
|
+
for m in re.finditer(r"black_start:([\d.]+) black_end:([\d.]+)", r.stderr):
|
|
2178
|
+
a, b = float(m.group(1)), float(m.group(2))
|
|
2179
|
+
if a < seconds - ignore_tail:
|
|
2180
|
+
black.append([round(a, 2), round(b, 2)])
|
|
2181
|
+
starts = [float(x) for x in re.findall(r"freeze_start: ([\d.]+)", r.stderr)]
|
|
2182
|
+
ends = [float(x) for x in re.findall(r"freeze_end: ([\d.]+)", r.stderr)]
|
|
2183
|
+
for i, a in enumerate(starts):
|
|
2184
|
+
b = ends[i] if i < len(ends) else seconds
|
|
2185
|
+
if b > seconds - ignore_tail:
|
|
2186
|
+
b = seconds - ignore_tail
|
|
2187
|
+
if b - a >= FREEZE_SEC:
|
|
2188
|
+
freezes.append([round(a, 2), round(b, 2)])
|
|
2189
|
+
for a, b in black:
|
|
2190
|
+
warn(f"검은 화면 {a:.1f}~{b:.1f}초 (녹화가 비었거나 페이지가 아직 안 그려졌다)")
|
|
2191
|
+
for a, b in freezes:
|
|
2192
|
+
hint = " — 기다리기만 하는 구간이면 d.fast() 나 d.cut() 으로 감싼다"
|
|
2193
|
+
warn(f"화면이 {b - a:.0f}초 동안 그대로다 ({a:.1f}~{b:.1f}초){hint}")
|
|
2194
|
+
out = {"seconds": round(seconds, 2), "black": black, "frozen": freezes}
|
|
2195
|
+
if seconds > 60:
|
|
2196
|
+
out["note"] = f"{seconds:.0f}초. 20초 안팎이 보기 좋다 (기다리는 구간은 d.fast / d.cut)"
|
|
2197
|
+
return out
|
|
2198
|
+
|
|
2199
|
+
|
|
2200
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2201
|
+
# frames — 납품 전 눈으로 확인
|
|
2202
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2203
|
+
SHEET_COLS, SHEET_W = 3, 640 # 한 장에 3열, 칸 하나 640×360 (16:9). 9~12칸이 한 번에 읽힌다
|
|
2204
|
+
SHEET_MAX = 12
|
|
2205
|
+
|
|
2206
|
+
|
|
2207
|
+
def _sheet_times(src: Path, seconds: float) -> list[tuple[float, str]]:
|
|
2208
|
+
"""한 장에 모을 시각. render 가 남긴 장면 표시가 있으면 장면마다 (시작 0.8초 뒤, 화살표 · 자막이 다 그려진 때),
|
|
2209
|
+
없으면 고르게 나눈다."""
|
|
2210
|
+
mf = marks_file(src)
|
|
2211
|
+
picked: list[tuple[float, str]] = []
|
|
2212
|
+
if mf.exists():
|
|
2213
|
+
marks = json.loads(mf.read_text(encoding="utf-8")).get("marks") or []
|
|
2214
|
+
for t, kind, label in marks:
|
|
2215
|
+
at = min(float(t) + 0.8, max(seconds - 1.2, 0))
|
|
2216
|
+
if picked and at - picked[-1][0] < 1.0:
|
|
2217
|
+
continue # 붙어 있는 표시는 한 칸으로
|
|
2218
|
+
picked.append((round(at, 2), f"{kind} {label}".strip()))
|
|
2219
|
+
if len(picked) > SHEET_MAX: # 많으면 고르게 솎는다
|
|
2220
|
+
step = len(picked) / SHEET_MAX
|
|
2221
|
+
picked = [picked[int(i * step)] for i in range(SHEET_MAX)]
|
|
2222
|
+
if not picked:
|
|
2223
|
+
n = 9
|
|
2224
|
+
picked = [(round(seconds * (i + 0.5) / n, 2), "") for i in range(n)]
|
|
2225
|
+
return picked
|
|
2226
|
+
|
|
2227
|
+
|
|
2228
|
+
def frames(src: Path, at: list[float] | None, outdir: Path, sheet: bool = False) -> None:
|
|
2229
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
2230
|
+
seconds = duration(src)
|
|
2231
|
+
if at is None and not sheet:
|
|
2232
|
+
raise SystemExit("--at 초 목록이나 --sheet 를 준다")
|
|
2233
|
+
points = [(t, "") for t in at] if at is not None else _sheet_times(src, seconds)
|
|
2234
|
+
made = []
|
|
2235
|
+
for i, (t, _) in enumerate(points):
|
|
2236
|
+
dst = outdir / (f"s{i:02d}.png" if sheet else f"t{t:g}s.png")
|
|
2237
|
+
vf = ["-vf", f"scale={SHEET_W}:-2"] if sheet else []
|
|
2238
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", str(t), "-i", str(src),
|
|
2239
|
+
"-frames:v", "1", *vf, str(dst)], check=True)
|
|
2240
|
+
made.append(dst)
|
|
2241
|
+
if not sheet:
|
|
2242
|
+
print(json.dumps({"frames": [str(m) for m in made]}, ensure_ascii=False))
|
|
2243
|
+
return
|
|
2244
|
+
# 칸들을 한 장으로. 읽는 쪽은 Read 한 번으로 영상 전체를 본다 (예전에는 세션당 이미지 Read 가 수십~200번이었다).
|
|
2245
|
+
rows = math.ceil(len(made) / SHEET_COLS)
|
|
2246
|
+
sheet_png = outdir / f"{src.stem}-sheet.png"
|
|
2247
|
+
inputs = []
|
|
2248
|
+
for m in made:
|
|
2249
|
+
inputs += ["-i", str(m)]
|
|
2250
|
+
blanks = rows * SHEET_COLS - len(made)
|
|
2251
|
+
graph = "".join(f"[{i}:v]" for i in range(len(made)))
|
|
2252
|
+
if blanks:
|
|
2253
|
+
graph = (f"color=c=black:s={SHEET_W}x{SHEET_W * 9 // 16}:d=1,format=rgb24,split={blanks}"
|
|
2254
|
+
+ "".join(f"[b{i}]" for i in range(blanks)) + ";" + graph + "".join(f"[b{i}]" for i in range(blanks)))
|
|
2255
|
+
graph += f"xstack=inputs={rows * SHEET_COLS}:layout=" + "|".join(
|
|
2256
|
+
f"{(k % SHEET_COLS) * SHEET_W}_{(k // SHEET_COLS) * (SHEET_W * 9 // 16 + 4)}" for k in range(rows * SHEET_COLS)
|
|
2257
|
+
) + ":fill=white"
|
|
2258
|
+
if rows * SHEET_COLS == 1:
|
|
2259
|
+
graph = "[0:v]null"
|
|
2260
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", graph, "-frames:v", "1", str(sheet_png)],
|
|
2261
|
+
check=True)
|
|
2262
|
+
for m in made:
|
|
2263
|
+
m.unlink()
|
|
2264
|
+
print(json.dumps({"sheet": str(sheet_png), "cols": SHEET_COLS,
|
|
2265
|
+
"cells": [{"n": i + 1, "at": t, "scene": lb} for i, (t, lb) in enumerate(points)]},
|
|
2266
|
+
ensure_ascii=False))
|
|
2267
|
+
|
|
2268
|
+
|
|
2269
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2270
|
+
# concat — 따로 찍은 영상을 하나로
|
|
2271
|
+
# ──────────────────────────────────────────────────────────────────────────
|
|
2272
|
+
def concat(srcs: list[Path], out: Path, xfade: float = 0.0) -> None:
|
|
2273
|
+
"""render 결과 여러 개를 이어 붙인다. 크기 · fps 가 달라도 1920×1080 25fps 로 맞춘다.
|
|
2274
|
+
xfade 초를 주면 이음매마다 크로스페이드한다 (그만큼 전체가 짧아진다)."""
|
|
2275
|
+
if len(srcs) < 2:
|
|
2276
|
+
raise SystemExit("이을 영상을 둘 이상 준다")
|
|
2277
|
+
for f in srcs:
|
|
2278
|
+
if not f.is_file():
|
|
2279
|
+
raise SystemExit(f"없는 파일: {f}")
|
|
2280
|
+
if out.exists():
|
|
2281
|
+
out.unlink()
|
|
2282
|
+
durs = [duration(f) for f in srcs]
|
|
2283
|
+
inputs, graph = [], []
|
|
2284
|
+
for i, f in enumerate(srcs):
|
|
2285
|
+
inputs += ["-i", str(f)]
|
|
2286
|
+
graph.append(f"[{i}:v]scale={OUT_W}:{OUT_H}:force_original_aspect_ratio=decrease:flags=lanczos,"
|
|
2287
|
+
f"pad={OUT_W}:{OUT_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps={FPS},format=yuv420p,"
|
|
2288
|
+
f"setpts=PTS-STARTPTS[n{i}]")
|
|
2289
|
+
if xfade > 0:
|
|
2290
|
+
prev, acc = "[n0]", durs[0]
|
|
2291
|
+
for i in range(1, len(srcs)):
|
|
2292
|
+
acc -= xfade
|
|
2293
|
+
graph.append(f"{prev}[n{i}]xfade=transition=fade:duration={xfade:.3f}:offset={acc:.3f}[x{i}]")
|
|
2294
|
+
prev, acc = f"[x{i}]", acc + durs[i]
|
|
2295
|
+
last = prev
|
|
2296
|
+
else:
|
|
2297
|
+
graph.append("".join(f"[n{i}]" for i in range(len(srcs))) + f"concat=n={len(srcs)}:v=1:a=0[cat]")
|
|
2298
|
+
last = "[cat]"
|
|
2299
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
2300
|
+
subprocess.run(["ffmpeg", "-v", "error", "-y", *inputs, "-filter_complex", ";".join(graph), "-map", last,
|
|
2301
|
+
"-an", "-r", str(FPS), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "22", "-preset", "medium",
|
|
2302
|
+
"-movflags", "+faststart", str(out)], check=True)
|
|
2303
|
+
# 장면 표시도 이어 붙인다 (frames --sheet 가 이어진 영상에서도 장면별로 고르게).
|
|
2304
|
+
marks, shift = [], 0.0
|
|
2305
|
+
for f, dsec in zip(srcs, durs):
|
|
2306
|
+
mf = marks_file(f)
|
|
2307
|
+
if mf.exists():
|
|
2308
|
+
for t, kind, label in json.loads(mf.read_text(encoding="utf-8")).get("marks") or []:
|
|
2309
|
+
marks.append([round(float(t) + shift, 2), kind, label])
|
|
2310
|
+
shift += dsec - (xfade if xfade > 0 else 0)
|
|
2311
|
+
total = duration(out)
|
|
2312
|
+
if marks:
|
|
2313
|
+
marks_file(out).write_text(json.dumps({"video": out.name, "seconds": round(total, 2), "marks": marks},
|
|
2314
|
+
ensure_ascii=False, indent=1), encoding="utf-8")
|
|
2315
|
+
print(json.dumps({"out": str(out), "parts": [[str(f), round(dsec, 2)] for f, dsec in zip(srcs, durs)],
|
|
2316
|
+
"result_seconds": round(total, 2)}, ensure_ascii=False))
|
|
2317
|
+
|
|
2318
|
+
|
|
2319
|
+
def main() -> None:
|
|
2320
|
+
for _f in (sys.stdout, sys.stderr): # Windows 콘솔(cp949)에서 ✓ · 한글을 찍다 죽지 않게
|
|
2321
|
+
try:
|
|
2322
|
+
_f.reconfigure(encoding="utf-8", errors="replace")
|
|
2323
|
+
except (AttributeError, ValueError):
|
|
2324
|
+
pass
|
|
2325
|
+
ap = argparse.ArgumentParser(description="시연 영상 녹화 도구")
|
|
2326
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
2327
|
+
|
|
2328
|
+
d = sub.add_parser("doctor", help="실행 환경 점검")
|
|
2329
|
+
d.add_argument("--fix", action="store_true", help="ffmpeg 가 없으면 brew 로 설치를 시도")
|
|
2330
|
+
|
|
2331
|
+
r = sub.add_parser("record", help="시나리오를 실행하며 녹화")
|
|
2332
|
+
r.add_argument("scenario", type=Path)
|
|
2333
|
+
r.add_argument("--out", type=Path)
|
|
2334
|
+
r.add_argument("--meta", type=Path)
|
|
2335
|
+
r.add_argument("--dry-run", action="store_true",
|
|
2336
|
+
help="녹화 없이 시나리오만 돌려 셀렉터 · 화살표 · 줌 대상 · 대기를 확인한다 (박자용 대기는 줄인다)")
|
|
2337
|
+
# 기본은 최종 영상이 1920×1080 이 되는 크기 (창 프레임 기본값이면 1792×904). 에이전트 창이 이보다 작아도 된다.
|
|
2338
|
+
# 창 크기는 건드리지 않고 이 크기로 그린 화면을 탭 영역에 축소해 찍는다. 다른 크기를 주면 render 가 1920×1080 에 맞춘다.
|
|
2339
|
+
r.add_argument("--width", type=int, default=None)
|
|
2340
|
+
r.add_argument("--height", type=int, default=None)
|
|
2341
|
+
r.add_argument("--no-color-fix", dest="color_fix", action="store_false",
|
|
2342
|
+
help="모니터 색 공간 → sRGB 보정을 끈다 (보정판 측정도 건너뛴다)")
|
|
2343
|
+
# 옛 옵션. 지금은 늘 사용자 브라우저의 에이전트 창에서 돌아 headless/headed 구분이 없다.
|
|
2344
|
+
r.add_argument("--headed", action="store_true", help=argparse.SUPPRESS)
|
|
2345
|
+
|
|
2346
|
+
v = sub.add_parser("render", help="잘라내기 + 배속 + mp4 인코딩")
|
|
2347
|
+
v.add_argument("--src", type=Path, required=True)
|
|
2348
|
+
v.add_argument("--meta", type=Path, required=True)
|
|
2349
|
+
v.add_argument("--out", type=Path, required=True)
|
|
2350
|
+
v.add_argument("--speed", type=float, default=4.0, help="구간에 배속이 없을 때 쓸 기본값 (1~8)")
|
|
2351
|
+
v.add_argument("--trim-end", type=float, default=0.0, help="원본 끝에서 이만큼(초) 잘라 낸다 (마지막 장면이 길게 찍혔을 때)")
|
|
2352
|
+
fr = v.add_mutually_exclusive_group()
|
|
2353
|
+
fr.add_argument("--frame", dest="frame", action="store_const", const="on",
|
|
2354
|
+
help="브라우저 창 프레임(주소창 자동 표시)을 강제로 켠다")
|
|
2355
|
+
fr.add_argument("--no-frame", dest="frame", action="store_const", const="off",
|
|
2356
|
+
help="브라우저 창 프레임을 끈다 (STYLE 과 무관하게)")
|
|
2357
|
+
v.add_argument("--no-color-fix", dest="color_fix", action="store_false",
|
|
2358
|
+
help="프레임 · 자막 · 타이틀 PNG 의 모니터 색 공간 → sRGB 보정을 끈다")
|
|
2359
|
+
|
|
2360
|
+
f = sub.add_parser("frames", help="확인용 프레임 추출")
|
|
2361
|
+
f.add_argument("--src", type=Path, required=True)
|
|
2362
|
+
f.add_argument("--at", default=None, help="초 단위, 쉼표 구분 (예: 2,9,15)")
|
|
2363
|
+
f.add_argument("--sheet", action="store_true",
|
|
2364
|
+
help="한 장(3열)에 모은다. --at 이 없으면 render 가 남긴 장면 표시(.marks.json)로 시각을 고른다")
|
|
2365
|
+
f.add_argument("--outdir", type=Path, default=None, help="기본: 영상 옆 <이름>-frames/")
|
|
2366
|
+
|
|
2367
|
+
c = sub.add_parser("concat", help="render 결과 여러 개를 이어 붙인다")
|
|
2368
|
+
c.add_argument("srcs", type=Path, nargs="+")
|
|
2369
|
+
c.add_argument("--out", type=Path, required=True)
|
|
2370
|
+
c.add_argument("--xfade", type=float, default=0.0, help="이음매 크로스페이드 초 (0 이면 그냥 잇는다)")
|
|
2371
|
+
|
|
2372
|
+
a = ap.parse_args()
|
|
2373
|
+
if a.cmd == "doctor":
|
|
2374
|
+
sys.exit(doctor(a.fix))
|
|
2375
|
+
try:
|
|
2376
|
+
summary = _run(a)
|
|
2377
|
+
except (Exception, SystemExit) as e: # noqa: BLE001 어떤 실패든 마지막 줄에 남긴다
|
|
2378
|
+
if isinstance(e, SystemExit) and e.code in (0, None):
|
|
2379
|
+
raise
|
|
2380
|
+
reason = str(e.code if isinstance(e, SystemExit) else f"{type(e).__name__}: {e}").strip().splitlines()
|
|
2381
|
+
if not isinstance(e, (SystemExit, ScenarioError)):
|
|
2382
|
+
import traceback
|
|
2383
|
+
traceback.print_exc()
|
|
2384
|
+
print(f"RESULT fail {a.cmd}: {reason[0] if reason else '알 수 없는 오류'}", flush=True)
|
|
2385
|
+
sys.exit(1)
|
|
2386
|
+
tail = f", 경고 {len(WARNINGS)}개 (위 [경고] 참고)" if WARNINGS else ""
|
|
2387
|
+
print(f"RESULT ok {a.cmd}{(' ' + summary) if summary else ''}{tail}", flush=True)
|
|
2388
|
+
|
|
2389
|
+
|
|
2390
|
+
def _run(a) -> str:
|
|
2391
|
+
"""명령 하나를 실행하고 RESULT 줄에 붙일 요약을 돌려준다."""
|
|
2392
|
+
if a.cmd == "record":
|
|
2393
|
+
if a.dry_run:
|
|
2394
|
+
r = dry_run(a.scenario, a.width, a.height)
|
|
2395
|
+
r["warnings"] = WARNINGS
|
|
2396
|
+
print(json.dumps(r, ensure_ascii=False))
|
|
2397
|
+
return f"dry-run {r['seconds']}초 (녹화하면 본편 약 {r['scenario_seconds_when_recorded']}초)"
|
|
2398
|
+
if not (a.out and a.meta):
|
|
2399
|
+
raise SystemExit("record 는 --out 과 --meta 가 필요하다 (녹화 없이 확인만 하려면 --dry-run)")
|
|
2400
|
+
record(a.scenario, a.out, a.meta, a.width, a.height, a.color_fix)
|
|
2401
|
+
return str(a.out)
|
|
2402
|
+
if a.cmd == "render":
|
|
2403
|
+
render(a.src, a.meta, a.out, a.speed, getattr(a, "frame", None), a.color_fix, a.trim_end)
|
|
2404
|
+
return f"{a.out} ({duration(a.out):.1f}초)"
|
|
2405
|
+
if a.cmd == "frames":
|
|
2406
|
+
outdir = a.outdir or a.src.with_name(a.src.stem + "-frames")
|
|
2407
|
+
frames(a.src, [float(x) for x in a.at.split(",")] if a.at else None, outdir, a.sheet)
|
|
2408
|
+
return str(outdir)
|
|
2409
|
+
if a.cmd == "concat":
|
|
2410
|
+
concat(a.srcs, a.out, a.xfade)
|
|
2411
|
+
return str(a.out)
|
|
2412
|
+
return ""
|
|
2413
|
+
|
|
2414
|
+
|
|
2415
|
+
if __name__ == "__main__":
|
|
2416
|
+
main()
|