Download spatial/run_spatial.py from SABAROsk/Drama3-Small-ASMR: direct link, hf CLI and curl.
- Browser
- Download file 9.46 kB
-
https://huggingface.co/SABAROsk/Drama3-Small-ASMR/resolve/main/spatial/run_spatial.py
- Command line
-
hf download hf://SABAROsk/Drama3-Small-ASMR/spatial/run_spatial.py
-
curl -L -o run_spatial.py https://huggingface.co/SABAROsk/Drama3-Small-ASMR/resolve/main/spatial/run_spatial.py
9.46 kB
| """位置つき台本の生成と、CPUだけで行う位置処理の入口。""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import wave | |
| sys.dont_write_bytecode = True | |
| try: | |
| if __package__: | |
| from . import spatial_wrap as wrap | |
| else: | |
| import spatial_wrap as wrap | |
| except ImportError as error: | |
| if __name__ != "__main__": | |
| raise | |
| print(f"エラー: 位置処理の同梱物を読み込めません: {error.name or 'spatial_wrap.py'}。" | |
| "配布リポジトリ全体を同じフォルダーに取得し直してください。", file=sys.stderr) | |
| raise SystemExit(2) from None | |
| def nonnegative(value): | |
| count = int(value) | |
| if count < 0: | |
| raise argparse.ArgumentTypeError("0以上を指定してください。") | |
| return count | |
| def parser(): | |
| cli = argparse.ArgumentParser(description=__doc__, allow_abbrev=False) | |
| root_help = "製品の run.py と Python ソースがあるフォルダ(既定: spatial/ の親)" | |
| cli.add_argument("--product-root", type=Path, default=wrap.PRODUCT_DIR, help=root_help) | |
| commands = cli.add_subparsers(dest="command", required=True) | |
| commands.add_parser("check", help="DSPの依存と同梱ファイルを検査します。", allow_abbrev=False) | |
| say = commands.add_parser("say-file", help="声を生成してから位置を付けます。", allow_abbrev=False, | |
| epilog="-- の後ろの引数は、製品の say-file に渡します。") | |
| say.add_argument("script", type=Path, help="位置タグ付きの UTF-8 台本") | |
| say.add_argument("-o", "--output", dest="out_dir", required=True, type=Path, | |
| help="空か未作成の生成出力フォルダ") | |
| apply = commands.add_parser("apply", help="生成済みの声だけを使って位置を付けます。", allow_abbrev=False) | |
| apply.add_argument("--script", required=True, type=Path, help="位置タグ付きの UTF-8 台本") | |
| apply.add_argument("--out-dir", required=True, type=Path, help="生成済みの行 WAV と記録があるフォルダ") | |
| for command in (say, apply): | |
| command.add_argument("--product-root", type=Path, default=argparse.SUPPRESS, help=root_help) | |
| command.add_argument("--preset", choices=wrap.PRESETS, default=wrap.DEFAULT_PRESET, help="仕上げ(既定: %(default)s)") | |
| command.add_argument("--memory-wait-tries", type=nonnegative, default=0, help="空き RAM 不足時に30秒待つ回数(既定: %(default)s)") | |
| command.add_argument("--dry-run", action="store_true", help="台本と入力を検査し、処理せずに手順を表示") | |
| return cli | |
| def check(): | |
| failures = [] | |
| for inspect, display in ( | |
| (wrap.dependency_versions, lambda found: "依存: " + "、".join(f"{k} {v}" for k, v in found.items())), | |
| (wrap.b_code_snapshot, lambda found: f"同梱ファイル: {found['file_count']}点の SHA-256 とサイズが一致しました。"), | |
| ): | |
| try: | |
| print(display(inspect())) | |
| except wrap.SpatialWrapError as error: | |
| failures.append(str(error)) | |
| for failure in failures: | |
| print(f"エラー: {failure}", file=sys.stderr) | |
| return 2 if failures else 0 | |
| def apply_positions(args, script): | |
| print(f"位置の処理: {args.out_dir}(仕上げ {args.preset})", flush=True) | |
| try: | |
| report = wrap.process_script(script, args.out_dir, preset=args.preset, | |
| product_root=args.product_root, memory_wait_tries=args.memory_wait_tries) | |
| except wrap.RetryableProcessingError as error: | |
| if isinstance(error, wrap.SpatialMemoryError) and os.environ.get("DRAMA3_ASMR_LAYOUT_VERIFY") == "1": | |
| details = {"reason": "insufficient_memory", "message": str(error)} | |
| print("SPATIAL_FAILURE " + json.dumps(details, ensure_ascii=False), file=sys.stderr, flush=True) | |
| raise wrap.SpatialWrapError( | |
| f"位置の処理で停止しました: {error}\n" | |
| f"直した後は、元の台本と --out-dir 「{args.out_dir}」を指定して apply でやり直せます。" | |
| ) from error | |
| except (wrap.SpatialWrapError, OSError, ValueError, RuntimeError, KeyError, TypeError, wave.Error) as error: | |
| raise wrap.SpatialWrapError(f"位置の処理で停止しました: {error}") from error | |
| print(f"完了: {args.out_dir / report['output']['all_stereo']}") | |
| def generate(args, forwarded, tagged_bytes, parsed): | |
| product_run = args.product_root / "run.py" | |
| if not product_run.is_file(): | |
| raise wrap.SpatialWrapError(f"製品の入口がありません: {product_run}。--product-root を確認してください。") | |
| if args.out_dir.exists() and (not args.out_dir.is_dir() or any(args.out_dir.iterdir())): | |
| raise wrap.SpatialWrapError(f"声の出力先は空か未作成のフォルダを指定してください: {args.out_dir}") | |
| command = [sys.executable, "-B", "-X", "utf8", str(product_run), "say-file"] | |
| # Keep the wrapper's destination authoritative, while forwarding the original argument tokens. | |
| options = [*forwarded, "-o", str(args.out_dir)] | |
| if args.dry_run: | |
| print("声の生成:", json.dumps([*command, "<一時のタグなし台本>", *options], ensure_ascii=False)) | |
| print(f"位置の処理: {args.out_dir}(仕上げ {args.preset})") | |
| return | |
| with tempfile.TemporaryDirectory(prefix="drama3-spatial-script-") as temp: | |
| script = Path(temp) / "script.txt" | |
| tagged = Path(temp) / "tagged.txt" | |
| script.write_bytes(parsed["stripped"].encode("utf-8")) | |
| tagged.write_bytes(tagged_bytes) | |
| print(f"声の生成: 製品の say-file を呼び出します({args.out_dir})", flush=True) | |
| try: | |
| result = subprocess.run([*command, str(script), *options], | |
| env={**os.environ, "PYTHONUTF8": "1", "PYTHONDONTWRITEBYTECODE": "1"}) | |
| if result.returncode not in (0, 2): | |
| raise wrap.SpatialWrapError(f"製品の終了コード {result.returncode}") | |
| batch = wrap.read_batch(args.out_dir) | |
| if batch.get("requested") != parsed["speakable_count"]: | |
| raise wrap.SpatialWrapError("生成の要求行数が台本と一致しません。") | |
| wrap.locate_product_output(args.out_dir, parsed["speakable_count"], batch) | |
| if result.returncode == 2: | |
| if not wrap.product_warnings(args.out_dir): | |
| raise wrap.SpatialWrapError("終了コード2の理由を、採用された断片の警告で確認できません。") | |
| print("警告: 全行はそろっていますが、判定を通らず採用した断片があります。位置の処理へ進みます。") | |
| except (wrap.SpatialWrapError, OSError, ValueError, KeyError, TypeError) as error: | |
| raise wrap.SpatialWrapError( | |
| f"声の生成で停止しました: {error}。\n" | |
| "製品の表示を確認し、新しい出力フォルダで say-file をやり直してください。" | |
| ) from error | |
| apply_positions(args, tagged) | |
| def main(argv=None): | |
| cli = parser() | |
| argv = list(sys.argv[1:] if argv is None else argv) | |
| forwarded = [] | |
| if "--" in argv: | |
| boundary = argv.index("--") | |
| forwarded, argv = argv[boundary + 1:], argv[:boundary] | |
| has_separator = True | |
| else: | |
| has_separator = False | |
| args = cli.parse_args(argv) | |
| if has_separator and args.command != "say-file": | |
| cli.error("-- の後ろに生成の引数を指定できるのは say-file だけです。") | |
| if args.command == "check": | |
| return check() | |
| args.product_root = args.product_root.expanduser().resolve() | |
| args.out_dir = args.out_dir.expanduser().resolve() | |
| args.script = args.script.expanduser().resolve() | |
| try: | |
| if args.command == "apply" and not args.dry_run: | |
| apply_positions(args, args.script) | |
| return 0 | |
| print("台本の検査: 位置タグと発話行を確認します。") | |
| wrap.b_code_snapshot() | |
| wrap.dependency_versions() | |
| _, config = wrap._load_product(args.product_root) | |
| wrap.warn_product_version(config.VERSION, "本文照合に使う製品") | |
| tagged_bytes, text = wrap.read_script_bytes(args.script) | |
| parsed = wrap.parse_script(text, product_root=args.product_root) | |
| if not parsed["speakable_count"]: | |
| raise wrap.SpatialWrapError("発話する行を台本に書いてください。") | |
| print(f"台本の検査: 発話 {parsed['speakable_count']} 行。") | |
| if args.command == "say-file": | |
| generate(args, forwarded, tagged_bytes, parsed) | |
| else: | |
| batch = wrap.read_batch(args.out_dir) | |
| wrap.locate_product_output(args.out_dir, parsed["speakable_count"], batch) | |
| wrap.verify_text_against_log(args.out_dir, parsed, batch, product_root=args.product_root) | |
| print(f"位置の処理: {args.out_dir}(仕上げ {args.preset}、試行表示のみ)") | |
| except (wrap.SpatialWrapError, OSError, ValueError, KeyError, TypeError) as error: | |
| print(f"エラー: {error}", file=sys.stderr) | |
| return 2 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |