-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_parser.py
More file actions
197 lines (172 loc) · 7.14 KB
/
Copy pathscript_parser.py
File metadata and controls
197 lines (172 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# -*- coding: utf-8 -*-
"""
结构化台本解析器 v1.3
台词(可混用):
【角色名】台词 / 角色名:台词
指令行:
#BGM=音乐名 设置背景音乐(后续段落生效)
#BGM=音乐名,前奏秒,尾奏秒 同时指定淡入/淡出
#BGM=无 清除背景音乐
#SFX=音效名 穿插音效段
#SFX=音效名,音量 音量 0~1.5,默认 0.9
#MUSIC=名称,秒数 纯音乐留白段
#END=名称,秒数 片尾曲段(默认20秒)
注释:// 或 # 开头(指令除外)
段落类型:voice / sfx / music / end
"""
import re
BGM_DIRECTIVE_RE = re.compile(r'^#\s*BGM\s*[=:]\s*(.*?)\s*$', re.IGNORECASE)
SFX_DIRECTIVE_RE = re.compile(r'^#\s*SFX\s*[=:]\s*(.*?)\s*$', re.IGNORECASE)
MUSIC_DIRECTIVE_RE = re.compile(r'^#\s*(MUSIC|END)\s*[=:]\s*(.*?)\s*$', re.IGNORECASE)
BRACKET_RE = re.compile(r'^【\s*([^】]{1,32}?)\s*】\s*(.+)$', re.DOTALL)
COLON_RE = re.compile(r'^([^::【】()()《》"\'\s][^::【】()()]{0,30})\s*[::]\s*(.+)$', re.DOTALL)
DECO_RE = re.compile(r'^[\s═━─﹘—=_\-~*·•▪#│┃║▏▎▕▍+.\u3000]{3,}$')
NONE_WORDS = {"", "无", "none", "null", "关闭", "off", "false"}
DEFAULT_CHARACTER = "旁白"
DEFAULT_MUSIC_SECONDS = 10.0
DEFAULT_END_SECONDS = 20.0
DEFAULT_SFX_VOLUME = 0.9
def _num(s, default=None):
if s is None:
return default
s = str(s).strip()
if not s:
return default
m = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)(s|秒|S)?', s)
if not m:
return default
try:
v = float(m.group(1))
return v if v > 0 else default
except ValueError:
return default
def _parse_music_directive(kind, arg, current_bgm):
arg = (arg or "").strip().strip('"\'')
bgm = current_bgm
dur = DEFAULT_END_SECONDS if kind.lower() == "end" else DEFAULT_MUSIC_SECONDS
if arg:
parts = [p for p in re.split(r'[,,\s]+', arg) if p]
if parts:
if _num(parts[0]):
dur = _num(parts[0]) or dur
else:
bgm = parts[0]
if len(parts) >= 2 and _num(parts[1]):
dur = _num(parts[1]) or dur
dur = max(1.0, min(dur, 300.0))
seg_type = "end" if kind.lower() == "end" else "music"
return {"type": seg_type,
"character": "片尾曲" if seg_type == "end" else "纯音乐",
"text": "", "bgm": bgm, "duration": dur}
def _parse_sfx_directive(arg):
arg = (arg or "").strip().strip('"\'')
if not arg:
return None
parts = [p for p in re.split(r'[,,\s]+', arg) if p]
name = parts[0]
vol = DEFAULT_SFX_VOLUME
if len(parts) >= 2 and _num(parts[1]) is not None:
vol = max(0.05, min(_num(parts[1]), 1.5))
return {"type": "sfx", "character": "音效", "text": "",
"sfx": name, "volume": round(vol, 2)}
def parse_script(text):
segments = []
warnings = []
current_bgm = None
current_pre = None
current_post = None
if text is None:
text = ""
lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
for lineno, raw in enumerate(lines, 1):
line = raw.strip()
if not line:
continue
m = SFX_DIRECTIVE_RE.match(line)
if m:
seg = _parse_sfx_directive(m.group(1))
if seg:
segments.append(seg)
else:
warnings.append(f"第 {lineno} 行 #SFX 指令缺少音效名,已忽略。")
continue
m = MUSIC_DIRECTIVE_RE.match(line)
if m and m.group(1).upper() in ("MUSIC", "END"):
seg = _parse_music_directive(m.group(1), m.group(2), current_bgm)
if seg:
segments.append(seg)
continue
m = BGM_DIRECTIVE_RE.match(line)
if m:
val = m.group(1).strip().strip('"\'')
if val.lower() in {w.lower() for w in NONE_WORDS}:
current_bgm = None
current_pre = None
current_post = None
else:
parts = [p.strip() for p in re.split(r'[,,]', val) if p.strip()]
current_bgm = parts[0]
current_pre = _num(parts[1]) if len(parts) >= 2 else None
current_post = _num(parts[2]) if len(parts) >= 3 else None
continue
if line.startswith("//") or line.startswith("#"):
continue
if DECO_RE.match(line):
continue
m = BRACKET_RE.match(line)
if m:
segments.append({"type": "voice", "character": m.group(1).strip(),
"text": m.group(2).strip(), "bgm": current_bgm,
"pre_seconds": current_pre, "post_seconds": current_post})
continue
m = COLON_RE.match(line)
if m and m.group(1).strip() and m.group(2).strip() and not re.search(r'\s', m.group(1)):
segments.append({"type": "voice", "character": m.group(1).strip(),
"text": m.group(2).strip(), "bgm": current_bgm,
"pre_seconds": current_pre, "post_seconds": current_post})
continue
if segments and segments[-1].get("type", "voice") == "voice":
segments[-1]["text"] += "\n" + line
warnings.append(f"第 {lineno} 行未识别到角色前缀,已并入上一段台词。")
elif segments:
warnings.append(f"第 {lineno} 行未识别到角色前缀,且上一段是非台词段,该行已忽略。")
else:
segments.append({"type": "voice", "character": DEFAULT_CHARACTER,
"text": line, "bgm": current_bgm,
"pre_seconds": current_pre, "post_seconds": current_post})
warnings.append(f"第 {lineno} 行未识别到角色前缀,已默认归入『旁白』。")
for seg in segments:
if seg.get("type") != "voice":
seg["text"] = ""
continue
seg.setdefault("type", "voice")
seg["text"] = seg["text"].strip()
seg["character"] = seg["character"].strip() or DEFAULT_CHARACTER
segments = [s for s in segments if s.get("type") != "voice" or s["text"]]
return segments, warnings
def extract_characters(segments):
seen = []
for s in segments:
if s.get("type") != "voice":
continue
if s["character"] not in seen:
seen.append(s["character"])
return seen
if __name__ == "__main__":
demo = """【旁白】深夜,旧书店的铃铛忽然响了。
#SFX=门铃
【店主】这么晚,还来买书?
#SFX=脚步声,1.2
【女孩】[轻声] 我来找一本…不会老去的书。
#BGM=夜色钢琴,3,8
【旁白】灯光昏黄。
#MUSIC=12
【店主】[叹息] 这本书,等了你四十年。
#END=月光摇篮曲,15
"""
segs, warns = parse_script(demo)
types = [s["type"] for s in segs]
assert types.count("sfx") == 2 and types.count("music") == 1 and types.count("end") == 1
fade = [s for s in segs if s.get("pre_seconds")]
assert fade and fade[0]["pre_seconds"] == 3.0
print("PARSER v1.3 SELF-TEST PASSED:", types)