Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/plans/feature-roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ Upload-Post turned out to cover more than assumed: per-platform text fields (`ti
**Decision (2026-11-03): A — restructure Streamlit.** B is not planned; keep it possible by building new features API-first.
1. Split `Main.py` into `webui/common.py` and `webui/components/` (one module per panel). Pure move, no behavior change, existing UI tests guard it. **Done 2026-11-03** (uncommitted). Page-level modules come with step A.2 via `st.navigation`; avoid a `webui/pages/` folder, which Streamlit turns into automatic multipage navigation.
2. Create page becomes a stepper: Script → Voice → Visuals → Subtitles & Music → Render → Publish, with a sticky summary/preview column.
3. Library page: grid of rendered videos with thumbnail, state, re-run, publish status.
3. Library page: grid of rendered videos with thumbnail, state, re-run, publish status. **Done 2026-11-04 as a dialog** (top bar > Library): switching pages would skip rendering the generation form, and Streamlit drops the state of widgets it does not render, so a half-typed subject or script would be lost. Thumbnails are the frame at 0.5 s, cached next to the video.
4. Visual pass on `styles.css`: one token set, dark/light, consistent spacing.
5. In parallel, every new feature (local AI, publish) gets API endpoints first, UI second → B becomes a front-end-only project later.

Expand Down
119 changes: 119 additions & 0 deletions test/services/test_webui_library.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""视频库:缩略图、发布状态与弹窗交互。"""

import os
import subprocess
from pathlib import Path
from unittest.mock import patch

import pytest
from streamlit.testing.v1 import AppTest

from app.config import config
from app.models import const
from app.services import material as _material # noqa: F401 (resolve FFmpeg before patching)
from app.services import state as sm
from app.utils import utils
from webui.components import library

ROOT_DIR = Path(__file__).parent.parent.parent
WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"


def _tiny_video(path: Path) -> Path:
subprocess.run(
[
utils.get_ffmpeg_binary(), "-y", "-loglevel", "error",
"-f", "lavfi", "-i", "color=c=red:s=64x112:d=1",
"-pix_fmt", "yuv420p", str(path),
],
check=True, capture_output=True, timeout=60,
)
return path


def test_thumbnail_is_created_once_and_refreshed_for_newer_video(tmp_path):
video = _tiny_video(tmp_path / "final-1.mp4")
thumbnail = library.task_thumbnail(str(video))
assert thumbnail == str(tmp_path / library.THUMBNAIL_NAME)
assert os.path.getsize(thumbnail) > 0
with patch.object(library.subprocess, "run") as run:
assert library.task_thumbnail(str(video)) == thumbnail
run.assert_not_called()
future = os.path.getmtime(thumbnail) + 10
os.utime(video, (future, future))
with patch.object(library.subprocess, "run", wraps=subprocess.run) as run:
library.task_thumbnail(str(video))
run.assert_called()


def test_thumbnail_returns_none_when_ffmpeg_cannot_read_the_file(tmp_path):
video = tmp_path / "final-1.mp4"
video.write_bytes(b"not a video")
assert library.task_thumbnail(str(video)) is None


@pytest.mark.parametrize(
"task, expected",
[
({}, "library.publish.none"),
({"cross_post_state": const.CROSS_POST_STATE_PROCESSING}, "library.publish.pending"),
({"cross_post_state": const.CROSS_POST_STATE_FAILED, "cross_post_error": "boom"},
"library.publish.failed"),
({"cross_post_state": const.CROSS_POST_STATE_COMPLETE,
"cross_post_results": [{"success": True}]}, "library.publish.done"),
({"cross_post_state": const.CROSS_POST_STATE_COMPLETE,
"cross_post_results": [{"success": True, "scheduled": True, "job_id": "j"}]},
"library.publish.queued"),
],
)
def test_publish_status_labels(task, expected):
with patch.object(library, "tr", lambda key: key):
label, detail = library.publish_status(task)
assert label == expected
assert detail == ("boom" if expected == "library.publish.failed" else "")


def test_scheduled_status_shows_the_local_time():
task = {
"cross_post_state": const.CROSS_POST_STATE_COMPLETE,
"cross_post_results": [{"scheduled": True, "scheduled_date": "2026-11-04T13:00:00Z"}],
}
with patch.object(library, "tr", lambda key: "at {date}"):
label, _ = library.publish_status(task)
assert label.startswith("at 2026-11-0")


@pytest.fixture
def library_app(tmp_path, monkeypatch):
tasks_dir = tmp_path / "storage" / "tasks"
task_dir = tasks_dir / "library-task"
task_dir.mkdir(parents=True)
_tiny_video(task_dir / "final-1.mp4")
(task_dir / "script.json").write_text('{"params": {"video_subject": "Coffee ritual"}}', encoding="utf-8")
monkeypatch.setattr(utils, "task_dir", lambda *a: str(tasks_dir if not a else tasks_dir / a[0]))
monkeypatch.setattr(sm.state, "get_all_tasks", lambda *_a, **_k: ([], 0))
monkeypatch.setattr(
sm.state, "get_task",
lambda task_id: {"cross_post_state": const.CROSS_POST_STATE_COMPLETE,
"cross_post_results": [{"scheduled": True, "scheduled_date": "2026-11-04T13:00:00Z"}]},
)
with patch.object(config, "try_save_config", return_value=True):
app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
app.session_state["ui_language"] = "en"
app.run()
yield app, task_dir


def test_library_dialog_shows_videos_and_plays_them_inline(library_app):
app, task_dir = library_app
app.button(key="open_library_dialog_button").click().run()
assert not app.exception
captions = " ".join(item.value for item in app.caption)
assert "Scheduled for 2026-11-0" in captions
assert any("Coffee ritual" in item.value for item in app.markdown)
assert (task_dir / library.THUMBNAIL_NAME).is_file()

app.button(key="library_play_library_task").click().run()
assert not app.exception
assert app.session_state["library_preview_video"] == str(task_dir / "final-1.mp4")
assert len(app.get("video")) == 1
4 changes: 4 additions & 0 deletions webui/Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
)
from webui.components.audio_panel import _render_audio_settings
from webui.components.generation_controls import _render_generation_controls
from webui.components.library import render_library_dialog
from webui.components.script_panel import _render_script_settings
from webui.components.settings_dialog import _render_settings_dialog
from webui.components.settings_transfer import _apply_pending_settings_preset
Expand All @@ -65,8 +66,11 @@ def _render_application():
"""按固定顺序渲染顶部栏、弹窗、生成表单和任务结果。"""
_render_top_bar()

# Streamlit 同一时间只能打开一个弹窗,设置优先。
if st.session_state.get("settings_dialog_open", False):
_render_settings_dialog()
elif st.session_state.get("library_dialog_open", False):
render_library_dialog()

if _apply_pending_settings_preset():
st.success(tr("Settings Preset Imported"))
Expand Down
197 changes: 197 additions & 0 deletions webui/components/library.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
"""视频库弹窗:以缩略图网格浏览已生成的视频,并查看自动发布状态。

视频库用弹窗而不是独立页面:切换页面时生成表单不会渲染,Streamlit 会清掉
这些控件的会话状态,用户正在填写的主题和文案就会丢失。
"""

import os
import subprocess
from datetime import datetime

import streamlit as st
from loguru import logger

from app.models import const
from app.services import state as sm
from app.utils import utils
from webui.common import localized_dialog, tr
from webui.components.tasks import (
_collect_task_summaries,
_delete_task,
_format_task_time,
_open_task_path,
_queue_task_restore,
)

THUMBNAIL_NAME = "thumbnail.jpg"
_PAGE_SIZE = 12
_COLUMNS = 3
_THUMBNAIL_TIMEOUT_SECONDS = 30


def task_thumbnail(video_file: str) -> str | None:
"""返回视频首帧缩略图,缺失或比视频旧时用 ffmpeg 重新生成。"""
thumbnail = os.path.join(os.path.dirname(video_file), THUMBNAIL_NAME)
try:
if os.path.getmtime(thumbnail) >= os.path.getmtime(video_file):
return thumbnail
except OSError:
pass
# 片头常是黑场或淡入,先取 0.5 秒处;更短的视频退回第一帧。
for offset in ("0.5", "0"):
try:
subprocess.run(
[
utils.get_ffmpeg_binary(),
"-y", "-loglevel", "error",
"-ss", offset, "-i", video_file,
"-frames:v", "1", "-vf", "scale=360:-2",
thumbnail,
],
capture_output=True,
timeout=_THUMBNAIL_TIMEOUT_SECONDS,
check=False,
)
except (OSError, subprocess.SubprocessError) as error:
logger.warning(f"failed to create task thumbnail: {video_file}, {error}")
return None
if os.path.isfile(thumbnail) and os.path.getsize(thumbnail) > 0:
return thumbnail
return None


def _format_iso_time(value) -> str:
try:
moment = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return str(value or "")
return moment.astimezone().strftime("%Y-%m-%d %H:%M")


def publish_status(task: dict) -> tuple[str, str]:
"""视频的发布状态:(标签, 补充说明)。"""
state = task.get("cross_post_state")
if not state:
return tr("library.publish.none"), ""
if state in (const.CROSS_POST_STATE_PENDING, const.CROSS_POST_STATE_PROCESSING):
return tr("library.publish.pending"), ""
if state == const.CROSS_POST_STATE_FAILED:
return tr("library.publish.failed"), str(task.get("cross_post_error") or "")
results = [item for item in task.get("cross_post_results") or [] if isinstance(item, dict)]
scheduled = next((item for item in results if item.get("scheduled")), None)
if scheduled is None:
return tr("library.publish.done"), ""
when = scheduled.get("scheduled_date") or scheduled.get("queue_slot")
if when:
return tr("library.publish.scheduled").format(date=_format_iso_time(when)), ""
return tr("library.publish.queued"), ""


def _finished_videos():
tasks = _collect_task_summaries(limit=200)
return [
task for task in tasks
if task.get("video_file") and os.path.isfile(task["video_file"])
]


def _runtime_task(task_id: str) -> dict:
try:
return sm.state.get_task(task_id) or {}
except Exception as error:
logger.warning(f"failed to load task for the library: {task_id}, {error}")
return {}


def _safe_key(task_id: str) -> str:
return "".join(ch if ch.isalnum() else "_" for ch in task_id)[:40]


def _render_card(task: dict):
task_id = task["task_id"]
key = _safe_key(task_id)
with st.container(border=True, key=f"library_card_{key}"):
thumbnail = task_thumbnail(task["video_file"])
if thumbnail:
st.image(thumbnail, width="stretch")
st.markdown(f"**{task['subject']}**")
label, detail = publish_status(_runtime_task(task_id))
st.caption(f"{_format_task_time(task['mtime'])} · {label}")
if detail:
st.caption(detail)
actions = st.columns(4, gap="small")
# 回调在页面重跑前执行,播放器位于网格上方,本次重跑就能显示。
actions[0].button(
tr("library.play"), key=f"library_play_{key}", icon=":material/play_arrow:",
help=tr("library.play"), width="stretch",
on_click=st.session_state.__setitem__,
args=("library_preview_video", task["video_file"]),
)
if actions[1].button(
tr("Open Task Folder"), key=f"library_open_{key}", icon=":material/folder_open:",
help=tr("Open Task Folder"), width="stretch",
):
_open_task_path(task["task_path"])
has_restore_data = os.path.isfile(os.path.join(task["task_path"], "script.json"))
if actions[2].button(
tr("Regenerate Task"), key=f"library_restore_{key}", icon=":material/replay:",
help=tr("Regenerate Task"), width="stretch", disabled=not has_restore_data,
):
st.session_state.pop("library_dialog_open", None)
_queue_task_restore(task_id)
st.rerun()
if actions[3].button(
tr("Delete Task"), key=f"library_delete_{key}", icon=":material/delete:",
help=tr("Delete Task"), width="stretch",
):
if _delete_task(task_id, task["task_path"], task.get("state")):
st.toast(tr("Task Deleted"))
st.rerun()
else:
st.error(tr("Task Delete Failed"))


def _render_preview():
preview = st.session_state.get("library_preview_video")
if not preview:
return
tasks_root = os.path.abspath(utils.task_dir())
# 只播放任务目录内的文件,避免会话状态被改成任意本地路径。
if not (os.path.abspath(preview).startswith(tasks_root + os.sep) and os.path.isfile(preview)):
st.session_state.pop("library_preview_video", None)
return
# 竖屏视频按弹窗全宽显示会高过整个屏幕,放在中间一栏。
player = st.columns([1, 1, 1])[1]
with player:
st.video(preview, autoplay=True)
if st.button(tr("Close"), key="library_close_preview", width="stretch"):
st.session_state.pop("library_preview_video", None)
st.rerun()
st.divider()


def _dismiss_library():
st.session_state.pop("library_dialog_open", None)
st.session_state.pop("library_preview_video", None)


def open_library():
st.session_state["library_dialog_open"] = True


@localized_dialog("library.title", width="large", on_dismiss=_dismiss_library)
def render_library_dialog():
_render_preview()
tasks = _finished_videos()
if not tasks:
st.info(tr("library.empty"))
return
shown = st.session_state.get("library_shown", _PAGE_SIZE)
for start in range(0, min(shown, len(tasks)), _COLUMNS):
columns = st.columns(_COLUMNS)
for column, task in zip(columns, tasks[start:start + _COLUMNS]):
with column:
_render_card(task)
if len(tasks) > shown and st.button(tr("library.show_more"), key="library_show_more"):
st.session_state["library_shown"] = shown + _PAGE_SIZE
st.rerun()
10 changes: 10 additions & 0 deletions webui/components/top_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
locales,
tr,
)
from webui.components.library import open_library
from webui.components.tasks import _render_task_manager_entry


Expand Down Expand Up @@ -110,6 +111,15 @@ def _render_top_bar():
):
_render_task_manager_entry()

st.button(
tr("library.open"),
key="open_library_dialog_button",
type="secondary",
icon=":material/video_library:",
width="content",
on_click=open_library,
)

st.button(
tr("Settings"),
key="open_settings_dialog_button",
Expand Down
13 changes: 12 additions & 1 deletion webui/i18n/az.json
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,17 @@
"upload_post.schedule.queue": "Upload-Post növbəmdə növbəti boş vaxt",
"upload_post.schedule.delay": "Müəyyən saat sonra",
"upload_post.schedule.delay_hours": "Gözləmə saatı",
"upload_post.schedule.help": "Upload-Post planlaşdırılmış paylaşımları saxlayır və özü dərc edir, ona görə bu kompüter o vaxt sönülü ola bilər. Növbə vaxtlarını Upload-Post panelində qurun."
"upload_post.schedule.help": "Upload-Post planlaşdırılmış paylaşımları saxlayır və özü dərc edir, ona görə bu kompüter o vaxt sönülü ola bilər. Növbə vaxtlarını Upload-Post panelində qurun.",
"library.open": "Kitabxana",
"library.title": "Video kitabxanası",
"library.empty": "Hələ hazır video yoxdur. Yaratdığınız videolar burada görünəcək.",
"library.play": "Oynat",
"library.publish.none": "Dərc edilməyib",
"library.publish.pending": "Dərc edilir…",
"library.publish.done": "Dərc edildi",
"library.publish.scheduled": "{date} üçün planlaşdırılıb",
"library.publish.queued": "Upload-Post növbəsinə əlavə edildi",
"library.publish.failed": "Dərc etmək alınmadı",
"library.show_more": "Daha çox göstər"
}
}
Loading
Loading