Repository navigation
Expand file tree
/
Copy pathst.py
More file actions
376 lines (320 loc) · 13.4 KB
/
Copy pathst.py
File metadata and controls
376 lines (320 loc) · 13.4 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import os, sys, time
def _configure_utf8_console():
"""Allow Rich and task threads to print Unicode on Windows."""
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", errors="replace")
_configure_utf8_console()
from runtime_libraries import configure_ffmpeg
configure_ffmpeg(required=True)
import streamlit as st
from core.st_utils.imports_and_utils import *
from core.task_runner import TaskRunner
from core.pipeline import get_steps, truncated_dubbing_lines
from core.utils import load_key, update_key
from core.utils.onekeycleanup import cleanup
from core.utils.delete_retry_dubbing import delete_dubbing_files
from translations.translations import DISPLAY_LANGUAGES, init_display_language, set_display_language
from core.utils.models import _TEXT_DONE_MARKER, _AUDIO_DONE_MARKER
# SET PATH
current_dir = os.path.dirname(os.path.abspath(__file__))
os.environ["PATH"] += os.pathsep + current_dir
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
st.set_page_config(page_title="VideoLingo", page_icon="docs/logo.svg")
SUB_VIDEO = "output/output_sub.mp4"
DUB_VIDEO = "output/output_dub.mp4"
# ─── Task control UI (auto-refreshes every 1s while task is active) ───
@st.fragment(run_every=1)
def _task_control_panel(runner_key: str):
"""Renders progress bar + pause/stop buttons. Auto-refreshes every 1s."""
runner = _get_runner(runner_key)
if runner.state == "idle":
return
# Progress
step_text = (
f"({runner.current_step + 1}/{runner.total_steps}) {t(runner.current_label)}"
if runner.current_step >= 0
else ""
)
if runner.is_active:
if runner.state == "paused":
st.warning(f"⏸️ {t('Paused')} {step_text}")
if runner.pause_message:
st.info(t(runner.pause_message))
else:
st.info(f"⏳ {t('Running...')} {step_text}")
st.progress(runner.progress)
if runner.state == "stopping":
st.info(t("Stopping..."))
return
# Control buttons
col1, col2 = st.columns(2)
with col1:
if runner.state == "paused":
if st.button(
f"▶️ {t('Resume')}",
key=f"{runner_key}_resume",
use_container_width=True,
):
runner.resume()
st.rerun()
else:
if st.button(
f"⏸️ {t('Pause')}",
key=f"{runner_key}_pause",
use_container_width=True,
):
runner.pause()
st.rerun()
with col2:
if st.button(
f"⏹️ {t('Stop')}",
key=f"{runner_key}_stop",
use_container_width=True,
type="primary",
):
runner.stop()
st.rerun()
elif runner.state == "completed":
st.success(t("Task completed!"))
st.progress(1.0)
runner.reset()
time.sleep(0.5)
st.rerun(scope="app")
elif runner.state == "stopped":
st.warning(f"⏹️ {t('Task stopped')} {step_text}")
if st.button(t("OK"), key=f"{runner_key}_ack_stop", use_container_width=True):
runner.reset()
st.rerun(scope="app")
elif runner.state == "error":
st.error(f"❌ {t('Task error')}: {runner.error_msg}")
if st.button(t("OK"), key=f"{runner_key}_ack_error", use_container_width=True):
runner.reset()
st.rerun(scope="app")
# ─── Text processing ───
def _get_runner(key):
if key not in st.session_state:
st.session_state[key] = TaskRunner()
return st.session_state[key]
def _clear_path(path):
if os.path.exists(path):
try:
os.remove(path)
except OSError:
pass
def _subtitle_length_controls():
"""Render inline controls for the two subtitle-length tunables.
Both values live in config.yaml and are read by:
- max_split_length → core/_3_2_split_meaning.py (first pass NLP cut)
- subtitle.max_length → core/_5_split_sub.py (final subtitle line, by rendered width)
"""
DEFAULT_MAX_SPLIT_LENGTH = 20
DEFAULT_MAX_LENGTH = 80
MAX_LENGTH_KEY = "subtitle.max_length"
# Not shown here; a config.yaml from before the width measure has 1.2, made for counted characters
DEFAULT_TARGET_MULTIPLIER = 1.0
with st.expander(t("Subtitle length tuning"), expanded=False):
st.caption(
t(
"These two values control how subtitles are cut. "
"Smaller = more, shorter lines. Larger = fewer, longer lines."
)
)
new_max_split = st.number_input(
t("max_split_length (rough cut, words/tokens per chunk)"),
min_value=8,
max_value=60,
value=int(load_key("max_split_length")),
step=1,
help=t(
"Suggested: 18-25. Below 18 cuts too finely and hurts translation; "
"above 25 makes downstream subtitle splitting hard to align."
),
key="cfg_max_split_length",
width=220,
)
new_max_length = st.number_input(
t("max_length (width of a subtitle line, 80 = one row)"),
min_value=20,
max_value=200,
value=int(load_key(MAX_LENGTH_KEY)),
step=1,
help=t(
"Width as drawn: a Latin letter is about 1, a Chinese character about 2.3, "
"80 fills one landscape row. Lower to split lines sooner, raise to keep them longer."
),
key="cfg_max_length",
width=220,
)
changed = False
if new_max_split != load_key("max_split_length"):
update_key("max_split_length", int(new_max_split))
changed = True
if new_max_length != load_key(MAX_LENGTH_KEY):
update_key(MAX_LENGTH_KEY, int(new_max_length))
changed = True
def restore_defaults():
update_key("max_split_length", DEFAULT_MAX_SPLIT_LENGTH)
update_key(MAX_LENGTH_KEY, DEFAULT_MAX_LENGTH)
update_key("subtitle.target_multiplier", DEFAULT_TARGET_MULTIPLIER, add_missing=True)
# Otherwise the inputs keep showing the old values and write them back on the next run
for key in ("cfg_max_split_length", "cfg_max_length"):
st.session_state.pop(key, None)
st.button(
t("Restore defaults ({split}/{length})")
.replace("{split}", str(DEFAULT_MAX_SPLIT_LENGTH))
.replace("{length}", str(DEFAULT_MAX_LENGTH)),
key="restore_subtitle_length_defaults",
on_click=restore_defaults,
)
if changed:
st.rerun()
def text_processing_section():
st.header(t("b. Translate and Generate Subtitles"))
runner = _get_runner("_text_runner")
from core._1_ytdlp import is_audio_only_input
audio_only = is_audio_only_input()
with st.container(border=True):
final_text_step = t("Generate subtitle files") if audio_only else t("Merging subtitles into the video")
st.markdown(
f"""
<p style='font-size: 20px;'>
{t("This stage includes the following steps:")}
<p style='font-size: 20px;'>
1. {t("Word-level transcription and alignment")}<br>
2. {t("Sentence segmentation using NLP and LLM")}<br>
3. {t("Summarization and multi-step translation")}<br>
4. {t("Cutting and aligning long subtitles")}<br>
5. {final_text_step}
""",
unsafe_allow_html=True,
)
text_done = os.path.exists(_TEXT_DONE_MARKER) or (
os.path.exists("output/trans.srt")
and os.path.exists("output/src.srt")
and (audio_only or os.path.exists(SUB_VIDEO))
)
if runner.is_active or runner.is_done or not text_done:
if runner.is_active:
_task_control_panel("_text_runner")
elif runner.is_done:
_task_control_panel("_text_runner")
else:
_subtitle_length_controls()
if st.button(
t("Start Processing Subtitles"), key="text_processing_button"
):
steps = get_steps("subtitles")
runner.start(steps)
st.rerun()
from core._1_ytdlp import find_subtitle_file
if not find_subtitle_file():
# No `help`: its tooltip wrapper takes the button out of `button_style`
if st.button(t("Transcribe Only"), key="transcribe_only_button"):
runner.start(get_steps("transcribe"))
st.rerun()
st.caption(t("Only generate the source subtitles `src.srt`, without translation"))
if os.path.exists("output/src.srt"):
st.success(t("Source subtitles are ready. You can download them, or start processing subtitles to translate them."))
download_subtitle_zip_button(text=t("Download All Srt Files"))
else:
if not audio_only and load_key("burn_subtitles") and os.path.exists(SUB_VIDEO):
st.video(SUB_VIDEO)
download_subtitle_zip_button(text=t("Download All Srt Files"))
if st.button(t("Archive to 'history'"), key="cleanup_in_text_processing"):
cleanup()
st.rerun()
return True
# ─── Audio processing ───
def audio_processing_section():
from core._1_ytdlp import is_audio_only_input
audio_only = is_audio_only_input()
st.header(t("c. Dubbing"))
runner = _get_runner("_audio_runner")
with st.container(border=True):
st.markdown(
f"""
<p style='font-size: 20px;'>
{t("This stage includes the following steps:")}
<p style='font-size: 20px;'>
1. {t("Generate audio tasks and chunks")}<br>
2. {t("Extract reference audio")}<br>
3. {t("Generate and merge audio files")}<br>
4. {t("Merge full audio")}<br>
5. {t("Merge final audio into video")}
""",
unsafe_allow_html=True,
)
audio_done = os.path.exists(_AUDIO_DONE_MARKER) or (
os.path.exists("output/dub.mp3")
and (audio_only or os.path.exists(DUB_VIDEO))
)
if runner.is_active or runner.is_done or not audio_done:
if runner.is_active:
_task_control_panel("_audio_runner")
elif runner.is_done:
_task_control_panel("_audio_runner")
else:
if st.button(
t("Start Audio Processing"), key="audio_processing_button"
):
steps = get_steps("dubbing")
runner.start(steps)
st.rerun()
else:
st.success(
t(
"Audio processing is complete! You can check the audio files in the `output` folder."
)
)
truncated = truncated_dubbing_lines()
if truncated:
st.warning(t("{n} dubbed line(s) did not fit their time and were cut at the end. They are listed in `output/log/dub_truncated.json`.").replace("{n}", str(len(truncated))))
if not audio_only and os.path.exists(DUB_VIDEO):
st.video(DUB_VIDEO)
if st.button(t("Delete dubbing files"), key="delete_dubbing_files"):
_clear_path(_AUDIO_DONE_MARKER)
delete_dubbing_files()
st.rerun()
if st.button(t("Archive to 'history'"), key="cleanup_in_audio_processing"):
cleanup()
st.rerun()
# ─── Main ───
def main():
init_display_language()
st.set_option("client.toolbarMode", "viewer")
logo_col, lang_col = st.columns([3, 1])
with logo_col:
st.image("docs/logo.png", width="stretch")
with lang_col:
language_values = list(DISPLAY_LANGUAGES.values())
current_language = init_display_language()
selected_language = st.selectbox(
t("Display Language 🌐"),
options=list(DISPLAY_LANGUAGES.keys()),
index=language_values.index(current_language) if current_language in language_values else 0,
key="display_language_selector",
)
new_language = DISPLAY_LANGUAGES[selected_language]
if new_language != current_language:
set_display_language(new_language)
st.rerun()
st.markdown(button_style, unsafe_allow_html=True)
welcome_text = t(
'Welcome to VideoLingo! 👋 You can also try it online at <a href="https://videolingo.io" target="_blank">videolingo.io</a>.'
)
st.markdown(
f"<p style='font-size: 20px; color: #808080;'>{welcome_text}</p>",
unsafe_allow_html=True,
)
# add settings
with st.sidebar:
page_setting()
st.markdown(give_star_button(), unsafe_allow_html=True)
if download_video_section():
text_done = text_processing_section()
from core._1_ytdlp import is_audio_only_input
if text_done and not is_audio_only_input():
audio_processing_section()
if __name__ == "__main__":
main()