File size: 9,462 Bytes
8d56a2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""位置つき台本の生成と、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())