利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
feat(packaging): add official mpt pip package
harry0703c3634de097ea
diff --git a/README-en.md b/README-en.mdindex bc41125d..50490739 100644--- a/README-en.md+++ b/README-en.md@@ -273,8 +273,9 @@ All examples below were generated with MoneyPrinterTurbo.### Recommended Paths- If you do not want to install or configure the project manually: generate videos with an AI Agent+- If you already have Python and want a direct installation: [install the official package with pip](#install-the-official-package-with-pip)- Windows users: use the one-click package first for the fastest local trial-- macOS / Linux users: use `uv` for the primary local setup path+- For source deployment or development: use `uv` to manage the environment and dependencies- If you want a more isolated runtime: use Docker deployment### Generate Videos with an AI Agent@@ -313,7 +314,56 @@ Use the local setup or Docker instructions below.## Installation & Deployment 📥-### Prerequisites+### Install the Official Package with pip++The official PyPI package is **[mpt](https://pypi.org/project/mpt/)**,+maintained by `harry0703`. The `MoneyPrinterTurbo` package on PyPI is maintained by a third party.++No repository clone is needed. Requires Python 3.11 or later; Python 3.11 is recommended.++**① Create and activate a virtual environment**++macOS / Linux:++```shell+python3 -m venv .venv+source .venv/bin/activate+```++Windows PowerShell:++```powershell+python -m venv .venv+.venv\Scripts\Activate.ps1+```++**② Install and start**++```shell+python -m pip install mpt+mpt webui+```++The WebUI opens in your browser automatically. Use `mpt webui --port 8503 --headless`+to select a port without opening a browser. For CLI video generation, see `mpt cli --help`.++**③ Configure services and find your files**++The application creates `config.toml` on first launch. Add the required API keys+for online models, footage, or speech services in the WebUI basic settings.+The installed application stores configuration and generated files here by default:++| System | Data directory |+| --- | --- |+| macOS | `~/Library/Application Support/MoneyPrinterTurbo` |+| Windows | `%LOCALAPPDATA%\MoneyPrinterTurbo` |+| Linux | `~/.local/share/MoneyPrinterTurbo`, or `$XDG_DATA_HOME/MoneyPrinterTurbo` |++Set `MPT_HOME` before launch to choose another directory. Generated videos are under+`storage/tasks` in that directory. To upgrade, activate your virtual environment and+run `python -m pip install --upgrade mpt`.++### Source Deployment Prerequisites- Local deployment requires Python 3.11 or later- On Windows, avoid project paths containing non-ASCII characters, special characters, or spacesdiff --git a/README-ja.md b/README-ja.mdindex 5ab32eb7..7749f699 100644--- a/README-ja.md+++ b/README-ja.md@@ -240,8 +240,9 @@### おすすめの手順- 手動でのインストールや設定をしたくない場合: AI エージェントで動画を生成する+- Python がインストール済みで、すぐに使いたい場合: [pip で公式パッケージをインストール](#pip-で公式パッケージをインストール)- Windows ユーザー: まずはワンクリックパッケージを使うのが最短で試せます-- macOS / Linux ユーザー: ローカル環境の主要な手順として `uv` を使用します+- ソースコードからのデプロイや開発: `uv` で環境と依存関係を管理します- より独立した実行環境が欲しい場合: Docker でデプロイします### AI エージェントで動画を生成する@@ -279,7 +280,57 @@ GitHub Releases から最新の Windows 用ワンクリックパッケージを## インストールとデプロイ 📥-### 前提条件+### pip で公式パッケージをインストール++公式の PyPI パッケージ名は **[mpt](https://pypi.org/project/mpt/)** で、`harry0703` が管理しています。+PyPI 上の `MoneyPrinterTurbo` という名前のパッケージは第三者が管理しています。++リポジトリのクローンは不要です。Python 3.11 以降が必要で、Python 3.11 を推奨します。++**① 仮想環境を作成して有効化する**++macOS / Linux:++```shell+python3 -m venv .venv+source .venv/bin/activate+```++Windows PowerShell:++```powershell+python -m venv .venv+.venv\Scripts\Activate.ps1+```++**② インストールして起動する**++```shell+python -m pip install mpt+mpt webui+```++WebUI がブラウザーで自動的に開きます。+ポートを指定し、ブラウザーを開かずに実行する場合は `mpt webui --port 8503 --headless` を使用してください。+CLI での動画生成については `mpt cli --help` を参照してください。++**③ サービスを設定し、保存先を確認する**++初回起動時に `config.toml` が自動作成されます。+オンラインのモデル、素材、音声サービスを利用する前に、WebUI の基本設定で必要な API キーを入力してください。+インストール版の設定と生成ファイルは、既定では以下の場所に保存されます:++| OS | データディレクトリ |+| --- | --- |+| macOS | `~/Library/Application Support/MoneyPrinterTurbo` |+| Windows | `%LOCALAPPDATA%\MoneyPrinterTurbo` |+| Linux | `~/.local/share/MoneyPrinterTurbo` または `$XDG_DATA_HOME/MoneyPrinterTurbo` |++起動前に `MPT_HOME` を設定すると、保存先を変更できます。+生成された動画は、そのディレクトリ内の `storage/tasks` に保存されます。+更新するには仮想環境を有効化して `python -m pip install --upgrade mpt` を実行してください。++### ソースコードからデプロイする場合の前提条件- ローカル環境へのデプロイには Python 3.11 以降が必要です- Windows では、プロジェクトのパスに非 ASCII 文字、特殊文字、スペースを含めないでくださいdiff --git a/README.md b/README.mdindex c964dc9c..b18b4f56 100644--- a/README.md+++ b/README.md@@ -277,8 +277,9 @@### 推荐使用方式- 不想手动安装和配置:直接使用 AI Agent 生成视频+- 已有 Python 环境,想直接安装使用:[通过 pip 安装官方包](#通过-pip-安装官方包)- Windows 用户:优先使用一键启动包,适合快速体验-- macOS / Linux 用户:优先使用 `uv` 进行本地部署+- 需要源码部署或二次开发:使用 `uv` 管理环境和依赖- 想要隔离运行环境:优先使用 Docker 部署### 使用 AI Agent 生成视频@@ -312,7 +313,54 @@## 安装部署 📥-### 前提条件+### 通过 pip 安装官方包++官方 PyPI 包名为 **[mpt](https://pypi.org/project/mpt/)**,由 `harry0703` 维护。+PyPI 上名为 `MoneyPrinterTurbo` 的包由第三方维护。++无需克隆仓库,需要 Python 3.11 或更高版本,推荐使用 Python 3.11。++**① 创建并激活虚拟环境**++macOS / Linux:++```shell+python3 -m venv .venv+source .venv/bin/activate+```++Windows PowerShell:++```powershell+python -m venv .venv+.venv\Scripts\Activate.ps1+```++**② 安装并启动**++```shell+python -m pip install mpt+mpt webui+```++WebUI 会自动打开浏览器。指定端口且不自动打开浏览器时,运行+`mpt webui --port 8503 --headless`;使用 CLI 生成视频前,可查看 `mpt cli --help`。++**③ 配置服务与管理文件**++首次启动会自动创建 `config.toml`。使用在线模型、素材或语音服务前,请在 WebUI+基础设置中填写相应的 API Key。安装版默认将配置和生成文件保存在:++| 系统 | 数据目录 |+| --- | --- |+| macOS | `~/Library/Application Support/MoneyPrinterTurbo` |+| Windows | `%LOCALAPPDATA%\MoneyPrinterTurbo` |+| Linux | `~/.local/share/MoneyPrinterTurbo`,或 `$XDG_DATA_HOME/MoneyPrinterTurbo` |++可在启动前设置 `MPT_HOME` 更改目录,生成的视频位于其中的 `storage/tasks` 下。+后续升级时,在已激活的虚拟环境中运行 `python -m pip install --upgrade mpt`。++### 源码部署前提条件- 本地部署需要 Python 3.11 或更高版本- Windows 用户建议避免使用包含中文、特殊字符或空格的项目路径diff --git a/app/__main__.py b/app/__main__.pynew file mode 100644index 00000000..71b9c37e--- /dev/null+++ b/app/__main__.py@@ -0,0 +1,5 @@+from app.launcher import main+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/app/config/config.py b/app/config/config.pyindex dadb9f4b..fa7ca10e 100644--- a/app/config/config.py+++ b/app/config/config.py@@ -10,9 +10,9 @@ from contextlib import contextmanagerimport tomlfrom loguru import logger-from app import __version__+from app import __version__, paths-root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))+root_dir = str(paths.runtime_root())config_file = f"{root_dir}/config.toml"_CONTAINER_CGROUP_MARKERS = ("docker", "containerd", "kubepods", "libpod", "podman")_DOCKER_HOST_GATEWAY_NAME = "host.docker.internal"@@ -507,6 +507,7 @@ def _initialize_config_from_example(example_file):def load_config():+ os.makedirs(root_dir, mode=0o700, exist_ok=True)# Docker may create an empty directory when a missing config.toml is bind-mounted.# Only remove that empty placeholder; a nonempty directory may contain user data.if os.path.isdir(config_file):@@ -529,6 +530,8 @@ def load_config():if not os.path.isfile(config_file):example_file = f"{root_dir}/config.example.toml"+ if not os.path.isfile(example_file):+ example_file = str(paths.config_template())if os.path.isfile(example_file):if _initialize_config_from_example(example_file):logger.info("copy config.example.toml to config.toml")diff --git a/app/launcher.py b/app/launcher.pynew file mode 100644index 00000000..f91126cd--- /dev/null+++ b/app/launcher.py@@ -0,0 +1,74 @@+"""pip 安装后的 mpt 启动入口,复用现有 WebUI 和 CLI。"""++import argparse+import socket+import subprocess+import sys+from pathlib import Path++from app import __version__, paths+++def _port_number(value: str) -> int:+ try:+ port = int(value)+ except ValueError as exc:+ raise argparse.ArgumentTypeError("port must be an integer") from exc+ if not 1 <= port <= 65535:+ raise argparse.ArgumentTypeError("port must be between 1 and 65535")+ return port+++def _available_port(host: str) -> int:+ # 与源码启动脚本保持一致:默认端口被占用时继续寻找,显式指定的端口则+ # 交给 Streamlit 原样绑定和报错,避免把用户带到另一个服务上。+ family = socket.AF_INET6 if ":" in host else socket.AF_INET+ for port in range(8501, 8600):+ try:+ with socket.socket(family, socket.SOCK_STREAM) as probe:+ probe.bind((host, port))+ return port+ except OSError:+ continue+ raise OSError(f"no available WebUI port on {host} between 8501 and 8599")+++def main(argv: list[str] | None = None) -> int:+ argv = list(sys.argv[1:] if argv is None else argv)+ # CLI 自己负责完整参数校验、帮助和退出码,避免两层解析器吞掉业务参数。+ if argv and argv[0] == "cli":+ if paths.is_source_checkout():+ import cli+ else:+ from app import cli++ cli._force_utf8_console()+ return cli.run_cli(argv[1:])++ parser = argparse.ArgumentParser(prog="mpt", description="MoneyPrinterTurbo")+ parser.add_argument("--version", action="version", version=__version__)+ commands = parser.add_subparsers(dest="command")+ commands.add_parser("cli", help="generate videos (mpt cli --help)")+ webui = commands.add_parser("webui", help="start the WebUI")+ webui.add_argument("--host", default="127.0.0.1", help="listen address")+ webui.add_argument("--port", type=_port_number, help="listen port (default: first free port from 8501)")+ webui.add_argument("--headless", action="store_true", help="do not open a browser")+ args = parser.parse_args(argv)+ if args.command != "webui":+ parser.print_help()+ return 0++ try:+ port = args.port if args.port is not None else _available_port(args.host)+ ui = Path(__file__).resolve().parent.parent / "webui" / "Main.py"+ return subprocess.call([+ sys.executable, "-m", "streamlit", "run", str(ui),+ f"--server.address={args.host}", f"--server.port={port}",+ f"--server.headless={str(args.headless).lower()}",+ "--browser.gatherUsageStats=false", "--client.toolbarMode=minimal",+ "--logger.hideWelcomeMessage=true", "--server.showEmailPrompt=false",+ ])+ except OSError as exc:+ parser.exit(1, f"mpt: {exc}\n")+ except KeyboardInterrupt:+ return 130diff --git a/app/paths.py b/app/paths.pynew file mode 100644index 00000000..979df34d--- /dev/null+++ b/app/paths.py@@ -0,0 +1,77 @@+"""统一源码版和安装版的资源、配置及运行数据目录。"""++import os+import shutil+import sys+import tempfile+from pathlib import Path+++SOURCE_ROOT = Path(__file__).resolve().parent.parent+BUNDLED_ROOT = Path(__file__).resolve().parent / "_assets"+++def is_source_checkout() -> bool:+ return (SOURCE_ROOT / "pyproject.toml").is_file() and (+ SOURCE_ROOT / "cli.py"+ ).is_file()+++def runtime_root() -> Path:+ """源码沿用项目目录;安装版使用用户目录,也允许显式指定 MPT_HOME。"""+ override = os.environ.get("MPT_HOME", "").strip()+ if override:+ return Path(override).expanduser().resolve()+ if is_source_checkout():+ return SOURCE_ROOT+ if sys.platform == "darwin":+ return Path.home() / "Library" / "Application Support" / "MoneyPrinterTurbo"+ if sys.platform == "win32":+ base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")+ else:+ base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")+ if not base.is_absolute():+ base = Path.home() / ".local" / "share"+ return base / "MoneyPrinterTurbo"+++def config_template() -> Path:+ base = SOURCE_ROOT if is_source_checkout() else BUNDLED_ROOT+ return base / "config.example.toml"+++def _copy_missing_resource(source: Path, target: Path) -> None:+ """原子补齐内置资源;并发启动和升级都不覆盖用户已有的文件。"""+ if target.exists():+ return+ target.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary = tempfile.mkstemp(prefix=".resource-", dir=target.parent)+ try:+ with os.fdopen(fd, "wb") as destination, source.open("rb") as origin:+ shutil.copyfileobj(origin, destination)+ try:+ # Windows rename 拒绝覆盖;POSIX 使用硬链接实现同样的独占发布。+ if os.name == "nt":+ os.rename(temporary, target)+ else:+ os.link(temporary, target)+ except FileExistsError:+ pass+ finally:+ Path(temporary).unlink(missing_ok=True)+++def resource_directory(sub_dir: str = "") -> Path:+ root = runtime_root()+ target = root / "resource" / sub_dir+ if is_source_checkout() and root == SOURCE_ROOT:+ return target++ # 字体和音乐仍可由用户扩充。放在运行目录,避免 WebUI 上传或后续升级写入+ # site-packages;只补齐缺失文件,保留用户编辑过的资源。+ origin = (SOURCE_ROOT if is_source_checkout() else BUNDLED_ROOT) / "resource" / sub_dir+ if origin.is_dir():+ for source in origin.rglob("*"):+ if source.is_file() and not source.name.startswith("."):+ _copy_missing_resource(source, target / source.relative_to(origin))+ return targetdiff --git a/app/utils/utils.py b/app/utils/utils.pyindex 0a5195c2..ab33e648 100644--- a/app/utils/utils.py+++ b/app/utils/utils.py@@ -12,6 +12,7 @@ from uuid import uuid4from loguru import logger+from app import pathsfrom app.models import const@@ -87,7 +88,7 @@ def normalize_clip_speed(value, default: float = 1.0) -> float:def root_dir():- return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))+ return str(paths.runtime_root())def storage_dir(sub_dir: str = "", create: bool = False):@@ -101,10 +102,7 @@ def storage_dir(sub_dir: str = "", create: bool = False):def resource_dir(sub_dir: str = ""):- d = os.path.join(root_dir(), "resource")- if sub_dir:- d = os.path.join(d, sub_dir)- return d+ return str(paths.resource_directory(sub_dir))def task_dir(sub_dir: str = ""):diff --git a/cli.py b/cli.pyindex a021b66e..59d62369 100644--- a/cli.py+++ b/cli.py@@ -241,7 +241,9 @@ def _bgm_type(value: str) -> str:def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:+ command = "mpt cli" if __name__ == "app.cli" else "uv run python cli.py"parser = argparse.ArgumentParser(+ prog="mpt cli" if __name__ == "app.cli" else None,description=("Generate MoneyPrinterTurbo videos without the WebUI.\n\n""Provider settings and credentials are read from config.toml.\n"@@ -295,7 +297,7 @@ Batch manifests:storage/resource lookup rules. --stop-at is a batch-wide CLI option. The summary hastotal, succeeded, failed, and tasks keys; every task entry has index, task_id,status, result, failed_stage, and error.-""",+""".replace("uv run python cli.py", command),formatter_class=_CliHelpFormatter,)@@ -1716,6 +1718,12 @@ def _run_batch_tasks(args: argparse.Namespace, tasks: list[VideoParams]) -> int:def run_cli(argv: Sequence[str] | None = None) -> int:args = parse_args(argv)+ from app.config import config+ from app.utils.logging_utils import configure_terminal_logger++ # 配置模块默认把终端日志发往 stdout。CLI 的 stdout 是机器可读 JSON,+ # 必须在素材预处理等步骤开始前切到 stderr,帮助和参数错误仍保持延迟导入。+ configure_terminal_logger(sys.stderr, level=config.log_level, colorize=False)if args.batch_file:try:tasks = _build_batch_tasks(args)diff --git a/docs/packaging.md b/docs/packaging.mdnew file mode 100644index 00000000..92eca313--- /dev/null+++ b/docs/packaging.md@@ -0,0 +1,93 @@+# pip 安装包与 PyPI 发布++发行包名采用 `mpt`,项目名称仍为 MoneyPrinterTurbo,版本沿用 `1.3.8`。+2026-10-16 已使用 `harry0703` 发布到+[PyPI](https://pypi.org/project/mpt/1.3.8/),同时提供 wheel 和 sdist。+已发布文件不可覆盖,后续代码变更需要提升版本后重新构建和验证。++## 构建和安装++需要 Python 3.11 或更新版本。依赖会随 wheel 一起解析安装,FFmpeg 优先使用系统+版本,也可使用 imageio-ffmpeg 提供的二进制。++用户从 PyPI 安装并启动:++```sh+python -m pip install mpt+mpt webui+mpt cli --help+```++本地构建和验证:++```sh+uv build --out-dir storage/package/mpt-dist+python -m pip install ./storage/package/mpt-dist/mpt-1.3.8-py3-none-any.whl+mpt --help+mpt webui+mpt cli --help+```++正式上传前应确认 PyPI 账号、目标版本和发行包哈希,避免使用混有旧包的目录+进行批量上传。每次发布均需用户明确授权,不随代码提交或推送自动发布。++## 发布前检查++```sh+uvx twine check --strict \+ storage/package/mpt-dist/mpt-1.3.8-py3-none-any.whl \+ storage/package/mpt-dist/mpt-1.3.8.tar.gz+```++检查 PyPI 说明页、发行包元数据和依赖可安装性,并在新虚拟环境中完成视频生成。+只有明确授权上传后才执行正式发布;账号密码、验证码和 API Token 不写入仓库、+命令示例或日志。各语种 README 提供用户安装入口,PyPI 的说明单独维护在+`docs/pypi-description.md`;更新仓库文档不会自动修改已经发布的 PyPI 介绍页。++`mpt webui` 默认仅监听 `127.0.0.1`,从 8501 开始选择空闲端口,自动打开浏览器。+可使用 `--host`、`--port` 指定地址,`--headless` 禁止自动打开浏览器:++```sh+mpt webui --port 8503 --headless+```++CLI 复用 `python cli.py` 的参数、任务流水线、退出码和 JSON 输出。完整离线示例:++```sh+mpt cli --video-script "A short video from local materials." \+ --video-source local --video-materials /absolute/path/clip.mp4 \+ --custom-audio-file /absolute/path/narration.wav \+ --no-subtitle-enabled --bgm-type none+```++在线文案、素材、TTS 等功能仍需相应服务的配置、密钥和网络连接。Whisper 模型按需+加载,不放入 wheel。CLI 日志写入 stderr,成功时 stdout 输出包含视频路径的 JSON。++## 配置与数据++源码运行继续使用项目根目录。安装版不依赖当前工作目录,默认运行目录为:++| 平台 | 运行目录 |+| --- | --- |+| macOS | `~/Library/Application Support/MoneyPrinterTurbo` |+| Windows | `%LOCALAPPDATA%\MoneyPrinterTurbo` |+| Linux | `$XDG_DATA_HOME/MoneyPrinterTurbo`,默认 `~/.local/share/MoneyPrinterTurbo` |++可通过 `MPT_HOME` 显式指定运行目录(源码版也支持)。其中:++- `config.toml`:首次运行从不含密钥的模板初始化,后续启动不会覆盖已有配置。+- `storage/tasks`:任务和生成的视频;其他缓存和上传文件在 `storage` 下。+- `resource/fonts`、`resource/songs`:首次使用时复制内置资源,可添加自己的文件。+- `models`:可放置手工下载的 Whisper 模型。++用户资源只补齐缺失文件,升级不覆盖已有文件。安装包包含两种默认中文字体、+越南语字体和内置背景音乐;备用的 `STHeitiLight.ttc`、`MicrosoftYaHeiNormal.ttc`+不进入发行包,以控制文件体积。需要这些字重时可放入运行目录的 `resource/fonts`。+源码版原有资源和外观不变。++## 本地验证要求++从 sdist 重建 wheel,安装到不继承系统包的新虚拟环境,离开源码目录并清除+`PYTHONPATH` 后验证 `mpt cli --help`、WebUI 实际页面和视频生成。输出视频应由+FFmpeg 完整解码,并确认配置与产物没有写入 site-packages。发行包不得包含+本机 `config.toml`、密钥、缓存、任务产物或本地协作指令。diff --git a/docs/pypi-description.md b/docs/pypi-description.mdnew file mode 100644index 00000000..4f1cfb6d--- /dev/null+++ b/docs/pypi-description.md@@ -0,0 +1,76 @@+# MoneyPrinterTurbo — Official Python Package++**mpt is the official Python distribution of+[MoneyPrinterTurbo](https://github.com/harry0703/MoneyPrinterTurbo), maintained by+[harry0703](https://pypi.org/user/harry0703/).**++Install the official package with **`python -m pip install mpt`**.+The separately named `MoneyPrinterTurbo` package on PyPI is a third-party+distribution and is not maintained by this project.++MoneyPrinterTurbo generates short videos from a topic or a prepared script.+It combines local or online materials, voice narration, subtitles, and background+music. Use the WebUI interactively or run the same video pipeline from the CLI.++## Install++Requires Python 3.11 or later. A virtual environment is recommended:++```sh+python -m venv .venv+# macOS / Linux+source .venv/bin/activate+# Windows PowerShell: .venv\Scripts\Activate.ps1+python -m pip install mpt+```++## Start the WebUI++```sh+mpt webui+```++The WebUI listens on localhost and opens in your browser. To select a port or run+without opening a browser:++```sh+mpt webui --port 8503 --headless+```++## Generate a video from the CLI++```sh+mpt cli --help+mpt cli --video-script "Your complete script." \+ --video-source local --video-materials /absolute/path/clip.mp4 \+ --custom-audio-file /absolute/path/narration.wav \+ --no-subtitle-enabled --bgm-type none+```++Local images and videos are supported. Online language models, stock media,+and speech providers require the appropriate configuration and network access.+Choose providers and enter credentials in the WebUI settings or `config.toml`.++The package includes default fonts, background music, and an FFmpeg binary through+imageio-ffmpeg. An installed system FFmpeg takes precedence. Whisper models are+loaded on demand.++## Configuration and generated files++The installed application keeps configuration, credentials, uploads, and generated+videos in your user directory:++| System | Default directory |+| --- | --- |+| macOS | `~/Library/Application Support/MoneyPrinterTurbo` |+| Windows | `%LOCALAPPDATA%\MoneyPrinterTurbo` |+| Linux | `~/.local/share/MoneyPrinterTurbo` (or `$XDG_DATA_HOME/MoneyPrinterTurbo`) |++Set `MPT_HOME` before starting the application to choose another directory.+Configuration is stored in `config.toml`; generated videos are under+`storage/tasks/<task-id>/`. Existing user configuration and resources are preserved+when the application starts or upgrades.++See the [project documentation](https://github.com/harry0703/MoneyPrinterTurbo)+for supported providers and advanced options. Report problems through+[GitHub Issues](https://github.com/harry0703/MoneyPrinterTurbo/issues).diff --git a/pyproject.toml b/pyproject.tomlindex a793b31d..34b44c4c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -6,21 +6,27 @@ requires = ["hatchling>=1.27.0"]build-backend = "hatchling.build"[project]-name = "moneyprinterturbo"+name = "mpt"version = "1.3.8"-description = "Generate short videos from prompts, local assets, subtitles, and TTS."-readme = "README-en.md"+description = "Official MoneyPrinterTurbo package with WebUI and CLI, maintained by harry0703."+readme = "docs/pypi-description.md"requires-python = ">=3.11"license = { text = "MIT" }dependencies = ["moviepy==2.2.1","streamlit==1.59.1",+ # Streamlit 1.59.1 的 gzip 适配依赖旧响应协议,新版本会使媒体响应失败。+ "starlette==1.2.1","streamlit-tour==1.1.0","edge-tts==7.3.1","fastapi==0.136.3","uvicorn==0.32.1","openai==2.24.0","faster-whisper==1.1.0",+ # 与 requirements.txt 保持一致:PyAV 19 移除了 Whisper 使用的参数。+ "av<19",+ "toml==0.10.2",+ "imageio-ffmpeg==0.6.0","loguru==0.7.3","dashscope==1.20.14","azure-cognitiveservices-speech==1.41.1",@@ -36,6 +42,13 @@ dependencies = ["google-genai==2.11.0",]+[project.scripts]+mpt = "app.launcher:main"++[project.urls]+Homepage = "https://github.com/harry0703/MoneyPrinterTurbo"+Issues = "https://github.com/harry0703/MoneyPrinterTurbo/issues"+[project.optional-dependencies]# Optional TwelveLabs (https://twelvelabs.io) video-understanding/embedding# integration. Only needed when `twelvelabs_api_keys` is configured; install@@ -72,8 +85,37 @@ show_missing = trueskip_covered = true[tool.hatch.build.targets.wheel]-packages = ["app"]+packages = ["app", "webui"]++# 字体保留中英文默认字体和越南语字体。两个大体积备用字重不进入安装包,+# 避免 wheel 超过 PyPI 默认文件大小限制;源码版的字体文件保持原样。+[tool.hatch.build.targets.wheel.force-include]+"cli.py" = "app/cli.py"+"config.example.toml" = "app/_assets/config.example.toml"+"resource/fonts/STHeitiMedium.ttc" = "app/_assets/resource/fonts/STHeitiMedium.ttc"+"resource/fonts/MicrosoftYaHeiBold.ttc" = "app/_assets/resource/fonts/MicrosoftYaHeiBold.ttc"+"resource/fonts/BeVietnamPro-Bold.ttf" = "app/_assets/resource/fonts/BeVietnamPro-Bold.ttf"+"resource/fonts/BeVietnamPro-Medium.ttf" = "app/_assets/resource/fonts/BeVietnamPro-Medium.ttf"+"resource/fonts/Charm-Bold.ttf" = "app/_assets/resource/fonts/Charm-Bold.ttf"+"resource/fonts/Charm-Regular.ttf" = "app/_assets/resource/fonts/Charm-Regular.ttf"+"resource/fonts/UTM Kabel KT.ttf" = "app/_assets/resource/fonts/UTM Kabel KT.ttf"+"resource/songs" = "app/_assets/resource/songs"+"resource/public" = "app/_assets/resource/public"++[tool.hatch.build]+exclude = ["**/.DS_Store", "**/__pycache__", "**/*.pyc", "**/.streamlit"]++[tool.hatch.build.targets.sdist]+# 使用白名单,禁止本机配置、凭据、storage、AGENTS.md 等混入源码发行包。+include = [+ "/app", "/cli.py", "/webui", "/config.example.toml", "/pyproject.toml",+ "/uv.lock", "/LICENSE", "/docs/pypi-description.md", "/docs/packaging.md",+ "/test/services/test_packaging.py", "/resource/songs", "/resource/public",+ "/resource/fonts/STHeitiMedium.ttc", "/resource/fonts/MicrosoftYaHeiBold.ttc",+ "/resource/fonts/BeVietnamPro-Bold.ttf", "/resource/fonts/BeVietnamPro-Medium.ttf",+ "/resource/fonts/Charm-Bold.ttf", "/resource/fonts/Charm-Regular.ttf",+ "/resource/fonts/UTM Kabel KT.ttf",+][tool.uv]-# 当前项目以应用运行形态为主,不作为可发布的 Python 包安装。-package = false+package = truediff --git a/requirements.txt b/requirements.txtindex 80b0f99f..ae2175da 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,7 @@# Keep legacy pip install support; primary deps moved to pyproject.toml / uv.lock.moviepy==2.2.1streamlit==1.59.1+starlette==1.2.1streamlit-tour==1.1.0edge_tts==7.3.1fastapi==0.136.3@@ -9,6 +10,8 @@ openai==2.24.0faster-whisper==1.1.0# faster-whisper passes metadata_errors to av.open(), which PyAV 19 removedav<19+toml==0.10.2+imageio-ffmpeg==0.6.0loguru==0.7.3google-genai==2.11.0dashscope==1.20.14diff --git a/test/services/test_packaging.py b/test/services/test_packaging.pynew file mode 100644index 00000000..c094b072--- /dev/null+++ b/test/services/test_packaging.py@@ -0,0 +1,143 @@+"""验证安装入口、可写目录与资源初始化的关键边界。"""++from concurrent.futures import ThreadPoolExecutor+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++from app import launcher, paths+++def test_source_checkout_keeps_legacy_paths(monkeypatch):+ monkeypatch.delenv("MPT_HOME", raising=False)+ assert paths.runtime_root() == paths.SOURCE_ROOT+ assert paths.resource_directory("fonts") == paths.SOURCE_ROOT / "resource/fonts"++[email protected]("platform", ["darwin", "win32", "linux"])+def test_installed_data_is_in_user_directory(monkeypatch, tmp_path, platform):+ monkeypatch.setattr(paths, "is_source_checkout", lambda: False)+ monkeypatch.setattr(paths.sys, "platform", platform)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ for key in ("MPT_HOME", "LOCALAPPDATA", "XDG_DATA_HOME"):+ monkeypatch.delenv(key, raising=False)+ expected = {+ "darwin": tmp_path / "Library/Application Support/MoneyPrinterTurbo",+ "win32": tmp_path / "AppData/Local/MoneyPrinterTurbo",+ "linux": tmp_path / ".local/share/MoneyPrinterTurbo",+ }+ assert paths.runtime_root() == expected[platform]+++def test_explicit_home_and_linux_xdg_directory(monkeypatch, tmp_path):+ monkeypatch.setenv("MPT_HOME", str(tmp_path / "explicit"))+ assert paths.runtime_root() == tmp_path / "explicit"+ monkeypatch.delenv("MPT_HOME")+ monkeypatch.setattr(paths, "is_source_checkout", lambda: False)+ monkeypatch.setattr(paths.sys, "platform", "linux")+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))+ assert paths.runtime_root() == tmp_path / "xdg/MoneyPrinterTurbo"+++def test_concurrent_resource_seeding_preserves_existing_files(monkeypatch, tmp_path):+ bundle = tmp_path / "bundle"+ fonts = bundle / "resource/fonts"+ fonts.mkdir(parents=True)+ (fonts / "default.ttf").write_bytes(b"complete font" * 10000)+ (fonts / "custom.ttf").write_bytes(b"bundled original")+ home = tmp_path / "user"+ target = home / "resource/fonts"+ target.mkdir(parents=True)+ (target / "custom.ttf").write_bytes(b"user font")+ monkeypatch.setattr(paths, "is_source_checkout", lambda: False)+ monkeypatch.setattr(paths, "BUNDLED_ROOT", bundle)+ monkeypatch.setenv("MPT_HOME", str(home))+ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(lambda _: paths.resource_directory("fonts"), range(8)))+ assert results == [target] * 8+ assert (target / "default.ttf").read_bytes() == (fonts / "default.ttf").read_bytes()+ assert (target / "custom.ttf").read_bytes() == b"user font"+ assert not list(target.glob(".resource-*"))+++def test_cli_preserves_arguments_and_exit_status(monkeypatch):+ import cli++ seen = []+ monkeypatch.setattr(cli, "run_cli", lambda args: seen.append(args) or 2)+ assert launcher.main(["cli", "--video-script", "中文", "--stop-at", "script"]) == 2+ assert seen == [["--video-script", "中文", "--stop-at", "script"]]+++def test_webui_launch_uses_current_python_and_bundled_ui(monkeypatch):+ called = []+ monkeypatch.setattr(launcher, "_available_port", lambda host: 8504)+ monkeypatch.setattr(launcher.subprocess, "call", lambda command: called.append(command) or 0)+ assert launcher.main(["webui", "--headless"]) == 0+ command = called[0]+ assert command[:3] == [launcher.sys.executable, "-m", "streamlit"]+ assert Path(command[4]) == paths.SOURCE_ROOT / "webui/Main.py"+ assert "--server.address=127.0.0.1" in command+ assert "--server.port=8504" in command+ assert "--server.headless=true" in command+++def test_explicit_webui_port_does_not_auto_switch(monkeypatch):+ monkeypatch.setattr(launcher, "_available_port", lambda _: pytest.fail("unexpected scan"))+ monkeypatch.setattr(launcher.subprocess, "call", lambda command: 1)+ assert launcher.main(["webui", "--port", "8501"]) == 1++[email protected]("port", ["0", "65536", "invalid"])+def test_invalid_port_is_rejected(port):+ with pytest.raises(SystemExit) as exc:+ launcher.main(["webui", "--port", port])+ assert exc.value.code == 2+++def test_sdist_and_wheel_allowlists_exclude_private_files():+ import tomllib++ project = tomllib.loads((paths.SOURCE_ROOT / "pyproject.toml").read_text())+ build = project["tool"]["hatch"]["build"]["targets"]+ assert project["project"]["scripts"]["mpt"] == "app.launcher:main"+ assert build["wheel"]["force-include"]["cli.py"] == "app/cli.py"+ for entry in build["sdist"]["include"]:+ assert entry not in ("/config.toml", "/storage", "/AGENTS.md", "/.env")+ assert "app" in build["wheel"]["packages"]+ assert "webui" in build["wheel"]["packages"]+++def test_cli_stdout_contains_only_json(tmp_path):+ env = os.environ.copy()+ env["MPT_HOME"] = str(tmp_path / "data")+ result = subprocess.run(+ [sys.executable, str(paths.SOURCE_ROOT / "cli.py"), "--video-script", "本地测试",+ "--stop-at", "script"],+ cwd=tmp_path, env=env, text=True, capture_output=True, timeout=30,+ )+ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout)["result"]["script"] == "本地测试"+ assert "load config" in result.stderr++[email protected]("media_type", ["image/png", "audio/mpeg", "video/mp4"])+def test_streamlit_media_responses_keep_valid_asgi_headers(media_type):+ from starlette.applications import Starlette+ from starlette.responses import Response+ from starlette.routing import Route+ from starlette.testclient import TestClient+ from streamlit.web.server.starlette.starlette_gzip_middleware import MediaAwareGZipMiddleware++ async def media(request):+ return Response(b"media payload" * 200, media_type=media_type)++ app = MediaAwareGZipMiddleware(Starlette(routes=[Route("/media", media)]))+ with TestClient(app) as client:+ result = client.get("/media", headers={"Accept-Encoding": "gzip"})+ assert result.status_code == 200+ assert result.content == b"media payload" * 200diff --git a/uv.lock b/uv.lockindex 773bf76b..72ea278d 100644--- a/uv.lock+++ b/uv.lock@@ -1497,17 +1497,46 @@ wheels = [][[package]]-name = "moneyprinterturbo"+name = "moviepy"+version = "2.2.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "decorator" },+ { name = "imageio" },+ { name = "imageio-ffmpeg" },+ { name = "numpy" },+ { name = "pillow" },+ { name = "proglog" },+ { name = "python-dotenv" },+]+sdist = { url = "https://files.pythonhosted.org/packages/de/61/15f9476e270f64c78a834e7459ca045d669f869cec24eed26807b8cd479d/moviepy-2.2.1.tar.gz", hash = "sha256:c80cb56815ece94e5e3e2d361aa40070eeb30a09d23a24c4e684d03e16deacb1", size = 58431438 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9a/73/7d3b2010baa0b5eb1e4dfa9e4385e89b6716be76f2fa21a6c0fe34b68e5a/moviepy-2.2.1-py3-none-any.whl", hash = "sha256:6b56803fec2ac54b557404126ac1160e65448e03798fa282bd23e8fab3795060", size = 129871 },+]++[[package]]+name = "mpmath"+version = "1.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 },+]++[[package]]+name = "mpt"version = "1.3.8"-source = { virtual = "." }+source = { editable = "." }dependencies = [{ name = "audioop-lts", marker = "python_full_version >= '3.13'" },+ { name = "av" },{ name = "azure-cognitiveservices-speech" },{ name = "dashscope" },{ name = "edge-tts" },{ name = "fastapi" },{ name = "faster-whisper" },{ name = "google-genai" },+ { name = "imageio-ffmpeg" },{ name = "litellm" },{ name = "loguru" },{ name = "moviepy" },@@ -1519,8 +1548,10 @@ dependencies = [{ name = "redis" },{ name = "requests" },{ name = "socksio" },+ { name = "starlette" },{ name = "streamlit" },{ name = "streamlit-tour" },+ { name = "toml" },{ name = "uvicorn" },]@@ -1539,12 +1570,14 @@ dev = [[package.metadata]requires-dist = [{ name = "audioop-lts", marker = "python_full_version >= '3.13'", specifier = "==0.2.2" },+ { name = "av", specifier = "<19" },{ name = "azure-cognitiveservices-speech", specifier = "==1.41.1" },{ name = "dashscope", specifier = "==1.20.14" },{ name = "edge-tts", specifier = "==7.3.1" },{ name = "fastapi", specifier = "==0.136.3" },{ name = "faster-whisper", specifier = "==1.1.0" },{ name = "google-genai", specifier = "==2.11.0" },+ { name = "imageio-ffmpeg", specifier = "==0.6.0" },{ name = "litellm", specifier = "==1.86.2" },{ name = "loguru", specifier = "==0.7.3" },{ name = "moviepy", specifier = "==2.2.1" },@@ -1556,8 +1589,10 @@ requires-dist = [{ name = "redis", specifier = "==5.2.0" },{ name = "requests", specifier = "==2.33.1" },{ name = "socksio", specifier = "==1.0.0" },+ { name = "starlette", specifier = "==1.2.1" },{ name = "streamlit", specifier = "==1.59.1" },{ name = "streamlit-tour", specifier = "==1.1.0" },+ { name = "toml", specifier = "==0.10.2" },{ name = "twelvelabs", marker = "extra == 'twelvelabs'", specifier = ">=1.2.8" },{ name = "uvicorn", specifier = "==0.32.1" },]@@ -1570,33 +1605,6 @@ dev = [{ name = "ruff", specifier = "==0.15.21" },]-[[package]]-name = "moviepy"-version = "2.2.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "decorator" },- { name = "imageio" },- { name = "imageio-ffmpeg" },- { name = "numpy" },- { name = "pillow" },- { name = "proglog" },- { name = "python-dotenv" },-]-sdist = { url = "https://files.pythonhosted.org/packages/de/61/15f9476e270f64c78a834e7459ca045d669f869cec24eed26807b8cd479d/moviepy-2.2.1.tar.gz", hash = "sha256:c80cb56815ece94e5e3e2d361aa40070eeb30a09d23a24c4e684d03e16deacb1", size = 58431438 }-wheels = [- { url = "https://files.pythonhosted.org/packages/9a/73/7d3b2010baa0b5eb1e4dfa9e4385e89b6716be76f2fa21a6c0fe34b68e5a/moviepy-2.2.1-py3-none-any.whl", hash = "sha256:6b56803fec2ac54b557404126ac1160e65448e03798fa282bd23e8fab3795060", size = 129871 },-]--[[package]]-name = "mpmath"-version = "1.3.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106 }-wheels = [- { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 },-]-[[package]]name = "multidict"version = "6.7.1"diff --git a/webui/Main.py b/webui/Main.pyindex 30f25d83..a811e935 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -91,8 +91,8 @@ style_file = Path(__file__).with_name("styles.css")streamlit_style = f"<style>{style_file.read_text(encoding='utf-8')}</style>"st.markdown(streamlit_style, unsafe_allow_html=True)# 定义资源目录-font_dir = os.path.join(root_dir, "resource", "fonts")-song_dir = os.path.join(root_dir, "resource", "songs")+font_dir = utils.font_dir()+song_dir = utils.song_dir()i18n_dir = os.path.join(root_dir, "webui", "i18n")config_file = os.path.join(root_dir, "webui", ".streamlit", "webui.toml")# 语言列表必须在会话状态初始化前可用,首次访问时才能把浏览器 locale 映射到@@ -1894,7 +1894,7 @@ def open_task_folder(task_id):# 通过路径拼接访问任务目录之外的位置,也避免后续打开目录时触发# 平台 shell 对特殊字符的解释。normalized_task_id = str(UUID(str(task_id)))- tasks_root = os.path.abspath(os.path.join(root_dir, "storage", "tasks"))+ tasks_root = os.path.abspath(utils.task_dir())path = os.path.abspath(os.path.join(tasks_root, normalized_task_id))# 即使 UUID 校验通过,也再次确认最终路径仍在任务根目录内,避免