File size: 54,191 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
"""製品の行 WAV に静止位置を付ける包み。経路の入口は run_spatial.py。

Windows 版からの変更:
- DSP の同梱ツリーを使い、製品の本文処理は指定した別 root から読み込む。
- タグだけの行は位置を継承させ、生成へ渡す本文から行ごと除く。
- DSP・両 SOFA のマニフェスト照合、読込元の検査、両 SOFA・依存版を含むキャッシュ鍵。
- DSP はハードリンクを確認した OS の一時領域で起動し、結果だけを出力先へ写す。
- 子には絶対パスを渡し、記録には出力 root 相対のパス、外部素材には名前と SHA を残す。
- 製品と生成済み出力の版の警告、公開入口向けの日本語エラー。
- 仕上げの既定は sleep。台本控えは内容の SHA で再利用し、通し音の行間も検査する。
詳細は CHANGES-from-windows-wrapper.md。
"""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import importlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import wave
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path

sys.dont_write_bytecode = True  # B・製品のフォルダへ __pycache__ を作らない

WRAP_VERSION = "SPATIAL-3-0.2"
HERE = Path(__file__).resolve().parent
B_ROOT = HERE / "work" / "static-voice-48k-20261029-r1" / "voice_asmr_oss"
B_EXTRA_CODE = (
    HERE / "work" / "utterance-tags-20261117-r1" / "utterance_tags.py",
    HERE / "work" / "continuous-motion-20261102-r1" / "continuous_motion.py",
)
HRIR_DIR = HERE / "drama3_asmr" / "spatial" / "hrir"
NF025_SOFA = HRIR_DIR / "fhk_nearfield" / "HRIR_CIRC360_NF025.sofa"
FRONT_SOFA = HRIR_DIR / "D1_HRIR_SOFA" / "D1_44K_16bit_256tap_FIR_SOFA.sofa"
PRODUCT_DIR = HERE.parent
VERIFIED_PRODUCT_VERSIONS = ("0.2.5", "0.3.0")
DEFAULT_PRESET = "sleep"
PRESETS = ("talk", "sleep", "none")
SPATIAL_REQUIREMENTS = ("numpy==2.2.6", "scipy==1.15.3", "h5py==3.16.0")

# B の utterance_tags.ALIASES と同じ(test で一致を確認する)
ALIASES = {
    "正面": "front", "front": "front",
    "右の耳元": "right", "right": "right",
    "左の耳元": "left", "left": "left",
    "正面の近く": "near", "near": "near",
    "正面の遠く": "far", "far": "far",
}
POSITION_LABEL = {"front": "正面", "right": "右の耳元", "left": "左の耳元", "near": "正面の近く", "far": "正面の遠く"}
# B の render() の規則(正面を0 dBとした相対)。報告用。
DESIGN_DB_VS_FRONT = {"front": 0.0, "right": 4.0, "left": 4.0, "near": 4.0, "far": -8.0}

HEAD_TAG = re.compile(r"^([ \t ]*)\{\{(?:位置|pos):([^{}\r\n]*)\}\}")
ANY_TAG = re.compile(r"\{\{(?:位置|pos):([^{}\r\n]*)\}\}")
# 全角の波括弧・コロンで書かれたタグらしい並び(B はタグと認めない。黙って半角にはしない)
FULLWIDTH_TAG = re.compile(r"{{|}}|{\s*(?:位置|pos)\s*[::]")
DEFAULT_GAP_SECONDS = 0.6
MIB = 1024 * 1024
LINUX_MEMINFO = Path("/proc/meminfo")
CGROUP_MEMORY = Path("/sys/fs/cgroup")
SPATIAL_DIRNAME = "spatial"
CACHE_NAME = re.compile(r"^L\d{4}-[a-z]+-[0-9a-f]{16}\.(wav|json)$")


class SpatialWrapError(Exception):
    """利用者へ日本語でそのまま見せるエラー。"""


class RetryableProcessingError(SpatialWrapError):
    """生成結果を保持したまま、処理環境を直してやり直せるエラー。"""


class SpatialMemoryError(RetryableProcessingError):
    """位置の処理に必要なメモリを確保できない。"""


# ---------------------------------------------------------------- 台本の解析

def _clip(text, n=40):
    text = text.replace("\t", " ")
    return text if len(text) <= n else text[:n] + "…"


def _load_product(product_root=None):
    return _load_product_at(Path(product_root or PRODUCT_DIR).resolve())


@lru_cache(maxsize=None)
def _load_product_at(product_root):
    """指定された製品のコードから、行の分け方を読み込む。"""
    package = product_root / "drama3_small_asmr"
    if not (package / "cli.py").is_file() or not (package / "__init__.py").is_file():
        raise SpatialWrapError(
            f"製品のPythonコードが見つかりません: {product_root}。"
            "--product-root に製品フォルダを指定してください(本文の照合に使います)。")
    name = "_spatial_product_" + sha256_bytes(str(product_root).encode())[:16]
    spec = importlib.util.spec_from_file_location(name, package / "__init__.py")
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    try:
        spec.loader.exec_module(module)
        return importlib.import_module(f"{name}.cli"), importlib.import_module(f"{name}.config")
    except (ImportError, OSError) as error:
        raise SpatialWrapError(
            f"製品の読み込みに失敗しました({error})。--product-root と check の結果を確認してください。") from error


def _load_normalizer(product_root=None):
    return _load_product(product_root)[0].normalize_for_tts


def warn_product_version(version, source, say=print):
    if version not in VERIFIED_PRODUCT_VERSIONS:
        say(f"警告: {source}の版 {version or '不明'} は確認済みの版 "
            f"({', '.join(VERIFIED_PRODUCT_VERSIONS)}) と異なります。本文を照合してから処理します。")


def parse_script(text, normalizer=None, *, product_root=None):
    """タグつき台本を解析する。

    返り値: dict(
      bom, stripped(位置タグとタグだけの行を除いた本文),
      lines=[dict(physical, raw, rest(タグを抜いた行), tag, position(実効), inherited, speakable, wav_index)],
      speakable_count)
    タグは行の頭(前の空白は可)にだけ書ける。1行に1つ。
    """
    normalize = normalizer or _load_normalizer(product_root)
    bom = "" if text.startswith("") else ""
    body = text[len(bom):]
    lines, out = [], []
    position, wav_index = "front", 0
    for number, piece in enumerate(body.splitlines(keepends=True), start=1):
        stripped_end = piece.rstrip("\r\n")
        ending = piece[len(stripped_end):]
        # splitlines は \x0b や 
 でも切る。末尾の改行類は raw から外して保持する。
        while stripped_end and stripped_end[-1] in "\x0b\x0c\x1c\x1d\x1e\x85

":
            ending = stripped_end[-1] + ending
            stripped_end = stripped_end[:-1]
        if FULLWIDTH_TAG.search(stripped_end):
            raise SpatialWrapError(
                f"{number}行目: 位置タグが全角の波括弧またはコロンで書かれています(「{_clip(stripped_end)}」)。"
                "半角の {{位置:右の耳元}} または {{pos:right}} で書いてください(波括弧は半角2つずつ、コロンも半角)。")
        match = HEAD_TAG.match(stripped_end)
        tag = None
        rest = stripped_end
        if match:
            tag = match.group(2).strip()
            if tag not in ALIASES:
                raise SpatialWrapError(
                    f"{number}行目: 未知の位置名です「{tag}」。使えるのは 正面・右の耳元・左の耳元・正面の近く・正面の遠く"
                    "(英字は front・right・left・near・far)です。例: {{位置:右の耳元}}")
            rest = match.group(1) + stripped_end[match.end():]
        if "{{" in rest or "}}" in rest:
            if ANY_TAG.search(rest):
                raise SpatialWrapError(
                    f"{number}行目: 位置タグが行の途中にあるか、1行に2つ以上あります(「{_clip(rest)}」)。"
                    "位置タグは行の頭に1つだけ書けます。途中で位置を変えたいときは、行を分けてください。")
            hint = "(コロンが全角の「:」になっていませんか)" if ":" in rest else ""
            raise SpatialWrapError(
                f"{number}行目: 位置タグの綴りが正しくありません(「{_clip(rest)}」){hint}。"
                "{{位置:正面}} または {{pos:front}} の形式で、波括弧は2つずつ、コロンは半角です。")
        if tag is not None:
            position = ALIASES[tag]
        # 製品は rows = [row for row in text.splitlines() if row.strip() and normalize_for_tts(row)] で番号を振る。
        # 製品が受け取るのはタグを抜いた後の行なので、同じ判定をその行(rest)に対して行う。
        speakable = bool(rest.strip()) and bool(normalize(rest))
        if speakable:
            wav_index += 1
        lines.append(dict(
            physical=number, raw=stripped_end, rest=rest, tag=tag, position=position,
            inherited=tag is None, speakable=speakable,
            wav_index=wav_index if speakable else None,
        ))
        if tag is None or rest.strip():
            out.append(rest + ending)
    return dict(bom=bom, stripped=bom + "".join(out), lines=lines, speakable_count=wav_index)


def strip_tags(text, normalizer=None):
    return parse_script(text, normalizer)["stripped"]


def read_script_bytes(path):
    path = Path(path)
    if not path.is_file():
        raise SpatialWrapError(f"台本ファイルが見つかりません: {path}")
    data = path.read_bytes()
    try:
        return data, data.decode("utf-8")
    except UnicodeDecodeError as error:
        raise SpatialWrapError(f"台本はUTF-8で保存してください: {path}({error})") from error


# ---------------------------------------------------------------- 小さな道具

def sha256_bytes(data):
    return hashlib.sha256(data).hexdigest()


def sha256_path(path):
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def linux_available_memory():
    fields = {}
    try:
        for line in LINUX_MEMINFO.read_text(encoding="ascii").splitlines():
            key, _, raw = line.partition(":")
            if key in ("MemAvailable", "MemFree", "Buffers", "Cached"):
                amount, unit = raw.split()
                if unit == "kB" and int(amount) >= 0:
                    fields[key] = int(amount) * 1024
    except (OSError, ValueError):
        fields.clear()
    available = fields.get("MemAvailable")
    source = "MemAvailable"
    if available is None and {"MemFree", "Buffers", "Cached"} <= fields.keys():
        available = fields["MemFree"] + fields["Buffers"] + fields["Cached"]
        source = "MemFree + Buffers + Cached"
    try:
        limit = (CGROUP_MEMORY / "memory.max").read_text(encoding="ascii").strip()
        if limit != "max":
            used = int((CGROUP_MEMORY / "memory.current").read_text(encoding="ascii"))
            ceiling = max(0, int(limit) - used)
            if available is None or ceiling < available:
                return ceiling, "cgroup memory.max − memory.current"
    except (OSError, ValueError):
        return available, source
    return available, source


def available_memory():
    if sys.platform.startswith("linux"):
        return linux_available_memory()
    if os.name == "nt":
        import ctypes

        class Status(ctypes.Structure):
            _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong)] + [
                (n, ctypes.c_ulonglong) for n in
                ("total", "avail", "page", "availpage", "virtual", "availvirtual", "extended")]
        status = Status()
        status.length = ctypes.sizeof(status)
        if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
            raise ctypes.WinError()
        return int(status.avail), "Windows の利用可能な物理メモリ"
    return os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE"), "SC_AVPHYS_PAGES"


def b_code_snapshot(root=HERE):
    """固定のDSPコード・素材の一覧と実ファイルを照合する。"""
    manifest = root / "MANIFEST-spatial.json"
    package = B_ROOT / "voice_asmr"
    modules = ("__init__", "__main__", "cli", "config", "errors", "mask",
               "static_processing", "static_spatial", "wavio")
    code = {p.relative_to(HERE).as_posix() for p in (
        *(package / f"{name}.py" for name in modules), *B_EXTRA_CODE)}
    required = code | {p.relative_to(HERE).as_posix() for p in (NF025_SOFA, FRONT_SOFA)}
    try:
        raw = manifest.read_bytes()
        doc = json.loads(raw)
        files = {row["path"]: row for row in doc["files"]}
        if doc["schema"] != "drama3-spatial-bundle/1" or files.keys() != required or len(doc["files"]) != len(required):
            raise ValueError("同梱ファイルの一覧が想定と違います")
    except (OSError, ValueError, TypeError, KeyError) as error:
        raise SpatialWrapError(f"同梱の照合表 {manifest.name} を読めません({error})。同梱物を取り直してください。") from error
    code_roots = (B_ROOT, *(p.parent for p in B_EXTRA_CODE))
    found_code = {
        p.relative_to(root).as_posix()
        for directory in code_roots
        for p in (root / directory.relative_to(HERE)).rglob("*.py")
        if "__pycache__" not in p.parts and p.is_file()
    }
    if found_code - code:
        extra = "、".join(sorted(found_code - code))
        raise SpatialWrapError(f"マニフェストにない同梱コードがあります: {extra}。同梱物を取り直してください。")
    verified = {}
    for name, row in sorted(files.items()):
        path = root / name
        if path.resolve() != root.resolve() / name:
            raise SpatialWrapError(f"同梱ファイルの参照先が想定と違います: {name}。同梱物を取り直してください。")
        if not path.is_file():
            raise SpatialWrapError(f"同梱ファイルがありません: {name}。同梱物を取り直してください。")
        try:
            size, digest = path.stat().st_size, sha256_path(path)
        except OSError as error:
            raise SpatialWrapError(f"同梱ファイルを読めません: {name}({error})。") from error
        if digest != row.get("sha256") or size != row.get("bytes"):
            raise SpatialWrapError(f"同梱ファイルの SHA-256 またはサイズが一致しません: {name}。同梱物を取り直してください。")
        verified[name] = digest
    return dict(digest=sha256_bytes(raw), file_count=len(verified), files=verified)


def dependency_versions(say=print):
    versions, missing = {}, []
    for requirement in SPATIAL_REQUIREMENTS:
        name, expected = requirement.split("==")
        try:
            versions[name] = importlib.import_module(name).__version__
        except (ImportError, OSError, ValueError) as error:
            missing.append(f"{name}({error})")
            continue
        if versions[name] != expected:
            say(f"警告: {name} {versions[name]} は確認済みの版 {expected} と異なります。")
    if missing:
        install = " ".join(SPATIAL_REQUIREMENTS)
        raise SpatialWrapError(f"依存を読み込めません: {'、'.join(missing)}。\n"
                               f"この Python の環境へ導入してください: python -m pip install {install}")
    return versions


def atomic_write_text(path, text):
    path = Path(path)
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(text, encoding="utf-8", newline="")
    os.replace(tmp, path)


def atomic_write_json(path, obj):
    atomic_write_text(path, json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n")


def _import_b():
    """B の公開関数を読み取り専用で読み込む(pycache を作らない)。"""
    if not B_ROOT.is_dir():
        raise SpatialWrapError(f"音声処理(voice_asmr_oss)が見つかりません: {B_ROOT}")
    sys.path.insert(0, str(B_ROOT))
    try:
        for name, filename in (("voice_asmr", "__init__.py"),
                               ("voice_asmr.static_processing", "static_processing.py"),
                               ("voice_asmr.wavio", "wavio.py")):
            loaded = sys.modules.get(name)
            spec = getattr(loaded, "__spec__", None) if loaded is not None else importlib.util.find_spec(name)
            origin = getattr(spec, "origin", None)
            if not origin or Path(origin).resolve() != B_ROOT / "voice_asmr" / filename:
                raise SpatialWrapError(f"同梱でない {name} を参照しています({origin})。"
                                       "別の voice_asmr を読み込んでいない Python で起動してください。")
        from voice_asmr import static_processing, wavio
    except ImportError as error:
        raise SpatialWrapError(
            f"音声処理の読み込みに失敗しました({error})。run_spatial.py check の結果を確認してください。") from error
    finally:
        sys.path.remove(str(B_ROOT))
    for module, filename in ((static_processing, "static_processing.py"), (wavio, "wavio.py")):
        if Path(module.__file__).resolve() != B_ROOT / "voice_asmr" / filename:
            raise SpatialWrapError(f"同梱でない {module.__name__} を読み込みました。"
                                   "別の voice_asmr を読み込んでいない Python で起動してください。")
    return static_processing, wavio


# ---------------------------------------------------------------- 製品の出力の読み取りと、本文の突き合わせ

def read_batch(out_dir):
    out_dir = Path(out_dir)
    if not out_dir.is_dir():
        raise SpatialWrapError(f"声の出力フォルダがありません: {out_dir}。--out-dir を確認してください(声の生成が先に必要です)。")
    path = out_dir / "batch.json"
    if not path.is_file():
        raise SpatialWrapError(f"{path} がありません。製品の say-file の出力フォルダを指定してください。")
    return json.loads(path.read_text(encoding="utf-8"))


def locate_product_output(out_dir, expected_lines, batch=None):
    out_dir = Path(out_dir)
    batch = read_batch(out_dir) if batch is None else batch
    if batch.get("status") != "complete":
        raise SpatialWrapError(
            f"声の生成が最後まで終わっていません(batch.json の status={batch.get('status')}、"
            f"完了 {batch.get('completed')}/{batch.get('requested')} 行)。"
            "声の生成を、新しいフォルダで最初からやり直してください。")
    if batch.get("completed") != expected_lines:
        raise SpatialWrapError(
            f"台本の発話は {expected_lines} 行ですが、声の出力は {batch.get('completed')} 行です。"
            "声の本文を変えた台本は、声の生成からやり直す必要があります(タグだけの変更なら一致するはずです)。")
    wavs = []
    for index in range(1, expected_lines + 1):
        path = out_dir / f"{index:04d}.wav"
        if not path.is_file():
            raise SpatialWrapError(f"{path.name} が {out_dir} にありません。台本の発話行数({expected_lines})と声の出力が合っていません。")
        wavs.append(path)
    extra = out_dir / f"{expected_lines + 1:04d}.wav"
    if extra.is_file():
        raise SpatialWrapError(f"{extra.name} が余分にあります。台本の発話行数({expected_lines})より声の出力が多いので、台本が違います。")
    return wavs, batch


def read_log(out_dir):
    path = Path(out_dir) / "log.jsonl"
    if not path.is_file():
        raise SpatialWrapError(
            f"声の記録 {path} がありません。声の本文と台本が同じか確かめられないので、止めます。"
            "製品の say-file の出力フォルダをそのまま指定してください。")
    records = []
    with path.open("r", encoding="utf-8") as f:
        for number, line in enumerate(f, 1):
            if line.strip():
                try:
                    records.append(json.loads(line))
                except json.JSONDecodeError as error:
                    raise SpatialWrapError(f"{path} の{number}行目を読めません({error})。声の出力が壊れています。") from error
    return records


def verify_text_against_log(out_dir, parsed, batch, *, product_root=None):
    """行ごとに、声を生成したときの断片の本文(log.jsonl の採用された試行の text)と、
    いまの台本のその行を、製品と同じ分け方・正規化にかけたものを、突き合わせる。

    製品は、各行を `lines(row, pack_chars)`(chunks.split_line → normalize_for_tts)で断片に分け、
    各断片を生成して、採用した試行の記録に text=断片 を書く。同じ関数を製品から import して、
    いまの台本の行 → 断片の並び を作り、記録の採用された断片の並び(chunk 順)と、行ごとに完全一致を求める。
    """
    cli, config = _load_product(product_root)
    pack = batch.get("pack_chars", config.DEFAULT_PACK_CHARS)
    records = read_log(out_dir)
    by_line = {}
    for rec in records:
        if rec.get("selected"):
            by_line.setdefault(int(rec["line"]), []).append(rec)
    mismatches = []
    for ln in parsed["lines"]:
        if not ln["speakable"]:
            continue
        number = ln["wav_index"]
        try:
            expected = list(cli.lines(ln["rest"], pack)[0])
        except ValueError as error:
            raise SpatialWrapError(f"{number}行目(台本の{ln['physical']}行): 製品が受け付けない本文です({error})。") from error
        chosen = sorted(by_line.get(number, []), key=lambda r: r["chunk"])
        if any("text" not in r for r in chosen):
            raise SpatialWrapError("声の記録(log.jsonl)に断片の本文(text)がありません。確かめられないので止めます。声を生成し直してください。")
        actual = [r["text"] for r in chosen]
        if actual != expected:
            mismatches.append((number, ln["physical"], "".join(expected), "".join(actual)))
    extra = sorted(set(by_line) - {ln["wav_index"] for ln in parsed["lines"] if ln["speakable"]})
    if extra:
        raise SpatialWrapError(f"声の記録に、台本にない行({extra[:5]})があります。別の台本で生成した出力です。")
    if mismatches:
        details = "\n".join(
            f"  {n}行目(台本の{p}行): いまの台本「{_clip(e, 24)}」/声を生成したときの本文「{_clip(a, 24)}」"
            for n, p, e, a in mismatches[:5])
        more = f"\n  …ほか {len(mismatches) - 5} 行" if len(mismatches) > 5 else ""
        raise SpatialWrapError(
            f"台本の声の本文が、声を生成したときと違う行があります({len(mismatches)}行):\n{details}{more}\n"
            "位置タグだけを変えたときは声の生成は不要ですが、本文を変えたときは、新しいフォルダで声の生成からやり直してください。")
    return dict(compared_lines=parsed["speakable_count"], pack_chars=pack, method="製品の cli.lines(chunks.split_line+normalize_for_tts)と log.jsonl の採用断片の text を行ごとに完全一致")


def product_warnings(out_dir):
    """判定に通らないまま採用された断片(製品の記録)を、行ごとに挙げる。"""
    warnings = []
    path = Path(out_dir) / "log.jsonl"
    if not path.is_file():
        return warnings
    for rec in read_log(out_dir):
        if rec.get("selected") and rec.get("flagged"):
            labels = "、".join(rec.get("reason_labels") or rec.get("reasons") or [])
            warnings.append(dict(line=rec["line"], chunk=rec["chunk"], reasons=labels))
    return warnings


def wav_header(path):
    try:
        with wave.open(str(path), "rb") as w:
            return dict(channels=w.getnchannels(), rate=w.getframerate(), samples=w.getnframes(), width=w.getsampwidth())
    except (wave.Error, EOFError) as error:
        raise SpatialWrapError(f"{Path(path).name} を読めません({error})。声の出力が壊れている可能性があります。") from error


def read_line_gap(out_dir, wavs, headers, rate):
    combined = out_dir / "all.wav"
    count = len(wavs)
    if not combined.is_file():
        return (0, "1行のため行間なし") if count == 1 else (
            round(DEFAULT_GAP_SECONDS * rate), "既定 0.6 秒(all.wav が無いため)")

    def invalid():
        return SpatialWrapError("all.wav が行WAVと等間隔の無音を連結した内容と一致しません。"
                                "元の生成結果一式を戻すか、新しいフォルダで声を生成してください。")

    together = wav_header(combined)
    for header in headers:
        if any(header[key] != together[key] for key in ("rate", "channels", "width")):
            raise invalid()
    remaining = together["samples"] - sum(header["samples"] for header in headers)
    gap, remainder = divmod(remaining, max(count - 1, 1))
    if remaining < 0 or remainder or (count == 1 and remaining):
        raise invalid()
    width = together["width"]
    silence_byte = 128 if width == 1 else 0
    with wave.open(str(combined), "rb") as joined:
        for index, (path, header) in enumerate(zip(wavs, headers)):
            if index:
                for offset in range(0, gap, 32768):
                    block = min(gap - offset, 32768)
                    if joined.readframes(block) != bytes([silence_byte]) * (block * width):
                        raise invalid()
            with wave.open(str(path), "rb") as line:
                for offset in range(0, header["samples"], 32768):
                    block = min(header["samples"] - offset, 32768)
                    pcm = line.readframes(block)
                    if len(pcm) != block * width or pcm != joined.readframes(block):
                        raise invalid()
    return gap, "1行のため行間なし" if count == 1 else "製品の all.wav の等間隔の無音を確認"


def verify_temp_hardlinks(work):
    source, link = work / "link-source", work / "link-check"
    source.touch()
    try:
        os.link(source, link)
    except OSError as error:
        raise SpatialWrapError(
            f"OS の一時フォルダでハードリンクを作れません({work.parent}: {error})。"
            "TMPDIR(Windowsでは TEMP または TMP)に、ハードリンクに対応したローカルのフォルダを指定してください。"
        ) from error


# ---------------------------------------------------------------- 描画(B のCLI)

B_CHILD = """
import importlib.util
from pathlib import Path
import runpy
import sys

sys.path.insert(0, str(Path.cwd()))
spec = importlib.util.find_spec("voice_asmr")
if not spec or not spec.origin or Path(spec.origin).resolve() != Path.cwd() / "voice_asmr" / "__init__.py":
    sys.exit("同梱でない voice_asmr が見つかりました。別の voice_asmr を読み込んでいない Python で起動してください。")
wrapper_root = sys.argv.pop(1)
if sys.platform.startswith("linux"):
    sys.path.insert(1, wrapper_root)
    from spatial_wrap import available_memory, MIB
    from voice_asmr import cli

    load_adapter = cli._load_position_adapter

    def load_with_linux_memory():
        adapter = load_adapter()

        def adapter_available_memory():
            available, _ = available_memory()
            if available is not None:
                return available
            # Keep the DSP's absolute clip-size limit if OS availability is unknown.
            return adapter.MEMORY_LIMIT_BYTES + 250 * MIB

        adapter.available_memory = adapter_available_memory
        return adapter

    cli._load_position_adapter = load_with_linux_memory
    sys.exit(cli.main())
runpy.run_module("voice_asmr", run_name="__main__", alter_sys=True)
"""


def _line_key(wav_sha, position, inputs):
    blob = json.dumps([wav_sha, position, inputs, WRAP_VERSION, sys.platform, "cli-defaults"], sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()[:16]


def render_line_with_b(wav_path, position, cache_dir, number, python, inputs, work, say):
    """1行を B の static-spatial(CLI)で描画する。結果は cache に置き、同じ入力なら再利用する。"""
    wav_sha = sha256_path(wav_path)
    key = _line_key(wav_sha, position, inputs)
    out_wav = cache_dir / f"L{number:04d}-{position}-{key}.wav"
    out_json = cache_dir / f"L{number:04d}-{position}-{key}.json"
    if out_wav.is_file() and out_json.is_file():
        report = json.loads(out_json.read_text(encoding="utf-8"))
        if report.get("output", {}).get("sha256") == sha256_path(out_wav):
            return out_wav, out_json, report, wav_sha, True
    with tempfile.TemporaryDirectory(prefix=f"L{number:04d}-", dir=work) as line_work:
        work = Path(line_work)
        script = work / "position-only.txt"
        # 1区画だけの台本なので本文は何でもよい(B は区画が1つなら切り替え時刻を推定しない)。
        script.write_text("{{pos:%s}}あ。\n" % position, encoding="utf-8")
        command = [python, "-I", "-B", "-X", "utf8", "-c", B_CHILD, str(HERE), "static-spatial",
                   "--input", str(wav_path), "--sofa", str(NF025_SOFA), "--script", str(script),
                   "--output", str(work / "out.wav"), "--report", str(work / "out.json")]
        say(f"  {number}行目: {POSITION_LABEL[position]}で描画しています…")
        started = time.time()
        try:
            result = subprocess.run(command, cwd=str(B_ROOT), capture_output=True, text=True,
                                    encoding="utf-8", errors="replace",
                                    env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONUTF8": "1"})
        except OSError as error:
            raise RetryableProcessingError(
                f"音声処理を起動できません({error})。Python のパス({python})を確認してください。") from error
        if result.returncode != 0:
            tail = (result.stderr or result.stdout or "").strip().splitlines()[-6:]
            error_type = (SpatialMemoryError if any("メモリ見積もりが上限を超えます" in line for line in tail)
                          else RetryableProcessingError)
            raise error_type(
                f"{number}行目({wav_path.name})の音声処理が失敗しました(終了コード {result.returncode}):\n  "
                + "\n  ".join(tail))
        report = json.loads((work / "out.json").read_text(encoding="utf-8"))
        out_dir = cache_dir.parents[1]
        report["input"]["path"] = wav_path.relative_to(out_dir).as_posix()
        report["output"]["path"] = out_wav.relative_to(out_dir).as_posix()
        report["script"].pop("path", None)  # DSP に渡した合成台本は一時ファイル
        report["front_hrir"].pop("path", None)
        report["front_hrir"]["file_name"] = FRONT_SOFA.name
        report["render"]["near_hrir"]["attribution"] = "spatial/LICENSES/FHK-ATTRIBUTION.md"
        report["wrap_note"] = dict(elapsed_s=round(time.time() - started, 2))
        fd, staged_name = tempfile.mkstemp(prefix=".spatial-", suffix=".tmp", dir=cache_dir)
        os.close(fd)
        staged = Path(staged_name)
        try:
            shutil.copyfile(work / "out.wav", staged)
            os.replace(staged, out_wav)
        finally:
            staged.unlink(missing_ok=True)
        atomic_write_json(out_json, report)
    return out_wav, out_json, report, wav_sha, False


def clean_cache(cache_dir, used):
    """この実行で使わなかった古い鍵のキャッシュと、失敗で残った作業フォルダを消す(包みが作ったものだけ)。"""
    removed = []
    for path in cache_dir.iterdir():
        if path.is_file() and CACHE_NAME.match(path.name) and path.name not in used:
            path.unlink()
            removed.append(path.name)
        elif path.is_dir() and re.match(r"^L\d{4}-", path.name):
            shutil.rmtree(path, ignore_errors=True)
            removed.append(path.name + "/")
    return removed


def _write_int16_wav(path, audio, rate):
    import numpy as np
    data = np.clip(np.rint(np.asarray(audio, dtype=np.float64) * 32767.0), -32768, 32767).astype("<i2")
    with wave.open(str(path), "wb") as w:
        w.setparams((data.shape[1], 2, rate, 0, "NONE", "not compressed"))
        w.writeframes(data.tobytes())
    return data


# ---------------------------------------------------------------- 本体

def process_script(script_path, out_dir, *, preset=DEFAULT_PRESET, product_root=None,
                   python=None, memory_wait_tries=0, memory_wait_seconds=30, say=print):
    before = b_code_snapshot()
    versions = dependency_versions(say)
    import numpy as np
    static, wavio = _import_b()
    python = python or sys.executable
    if preset not in PRESETS:
        raise SpatialWrapError(f"仕上げは talk・sleep・none のどれかです(指定: {preset})。")
    tagged_bytes, text = read_script_bytes(script_path)
    _, config = _load_product(product_root)
    warn_product_version(config.VERSION, "本文照合に使う製品", say)
    parsed = parse_script(text, product_root=product_root)
    n = parsed["speakable_count"]
    if n == 0:
        raise SpatialWrapError("台本に発話の行がありません。")
    out_dir = Path(out_dir).expanduser().resolve()
    batch = read_batch(out_dir)
    if batch.get("version") != config.VERSION:
        warn_product_version(batch.get("version"), "生成済み出力", say)
    wavs, batch = locate_product_output(out_dir, n, batch)
    text_check = verify_text_against_log(out_dir, parsed, batch, product_root=product_root)
    warnings = product_warnings(out_dir)
    for w in warnings:
        say(f"警告: 声の{w['line']}行目の第{w['chunk']}断片は、判定に通らないまま採用されています({w['reasons']})。聴いて確かめてください。")
    positions = {ln["wav_index"]: ln for ln in parsed["lines"] if ln["speakable"]}

    # --- 入力の検査(ヘッダだけ。音は1行ずつ読む)
    headers = [wav_header(p) for p in wavs]
    for path, h in zip(wavs, headers):
        if h["channels"] != 1 or h["rate"] not in (44100, 48000):
            raise SpatialWrapError(f"{path.name} は44100/48000 Hzのモノラルではありません({h['channels']}ch・{h['rate']} Hz)。")
    rates = {h["rate"] for h in headers}
    if len(rates) != 1:
        raise SpatialWrapError(f"行によってサンプリング周波数が違います: {sorted(rates)}")
    rate = rates.pop()

    gap_samples, gap_source = read_line_gap(out_dir, wavs, headers, rate)
    all_mono = out_dir / "all.wav"

    # --- メモリ。行は1本ずつ処理し、全行の音を同時に持たない。
    #     B のCLI(別プロセス): 64 MiB + samples×(192+16×3)。包みの本体: 行の配列(約160 B/サンプル)+ numpy/scipy。
    longest = max(h["samples"] for h in headers)
    need = max(64 * MIB + longest * (192 + 16 * 3), 100 * MIB + longest * 160) + 250 * MIB + 150 * MIB
    tries = 0
    while True:
        available, source = available_memory()
        if available is None:
            say("警告: Linux で使えるメモリ量を測れません。音声1行ごとの処理上限を保って続行します。")
            break
        if available >= need:
            break
        measured = f"使える量 {available / MIB:.0f} MiB({source})"
        if tries >= memory_wait_tries:
            raise SpatialMemoryError(
                f"空きメモリが足りません。{measured}、最長の行({longest / rate:.1f}秒)の処理に約 {need / MIB:.0f} MiB 必要です。"
                "ほかの重い処理(文字起こしなど)の終了を待つか、--memory-wait-tries を指定してください。")
        tries += 1
        say(f"{measured}(必要 {need / MIB:.0f} MiB)。{memory_wait_seconds}秒待ちます({tries}/{memory_wait_tries})…")
        time.sleep(memory_wait_seconds)

    # --- 包みの置き場(製品のファイルとぶつからない)。完了の印は最後に書く。
    spatial = out_dir / SPATIAL_DIRNAME
    stereo_dir = spatial / "stereo"
    cache_dir = spatial / "spatial-cache"
    scripts_dir = spatial / "scripts"
    marker = spatial / "COMPLETE.json"
    tagged_sha = sha256_bytes(tagged_bytes)
    stripped_bytes = parsed["stripped"].encode("utf-8")
    stripped_sha = sha256_bytes(stripped_bytes)
    tagged_copy = scripts_dir / f"tagged-{tagged_sha}.txt"
    stripped_copy = scripts_dir / f"stripped-{stripped_sha}.txt"

    hrir = {p.name: before["files"][p.relative_to(HERE).as_posix()] for p in (NF025_SOFA, FRONT_SOFA)}
    cache_inputs = dict(manifest=before["digest"], hrir=hrir, dependencies=versions)

    rows = []
    sum_src2, sum_pre2, count_mask = 0.0, 0.0, 0
    peak_pre = 0.0
    used_cache = set()
    with tempfile.TemporaryDirectory(prefix="spatial-work-") as work_name:
        work = Path(work_name)
        verify_temp_hardlinks(work)
        for directory in (spatial, stereo_dir, cache_dir, scripts_dir):
            directory.mkdir(exist_ok=True)
        marker.unlink(missing_ok=True)  # 途中で落ちたら、印が無いまま残る
        for path, content in ((tagged_copy, tagged_bytes), (stripped_copy, stripped_bytes)):
            if not path.is_file() or path.read_bytes() != content:
                atomic_write_text(path, content.decode("utf-8"))
        # --- 1パス目: 行ごとに B で描画。B が掛けた「単一位置用の最後の補正」を外す。
        #     B は1ファイル内で位置の間の関係(耳元は正面より+4 dB、近く+4 dB、遠く−8 dB)を保ち、最後に
        #     全体の active RMS を元に合わせる。行ごとに呼ぶとその補正が行ごとに掛かって関係が消えるので、
        #     補正(rms_match_gain × headroom_gain)を B の report から読んで外し、台本全体で1回だけ掛け直す。
        pre_files = []
        for index, wav_path in enumerate(wavs, start=1):
            position = positions[index]["position"]
            out_wav, out_json, report, wav_sha, reused = render_line_with_b(
                wav_path, position, cache_dir, index, python, cache_inputs, work, say)
            used_cache.update({out_wav.name, out_json.name})
            render = report["render"]
            undo = float(render["rms_match_gain"]) * float(render["headroom_gain"])
            if not (undo > 0.0):
                raise SpatialWrapError(f"{index}行目: B の report の補正値が不正です({undo})。")
            source = wavio.read_wav(wav_path)
            stereo = wavio.read_wav(out_wav)
            if stereo.channels != 2 or stereo.sample_count != source.sample_count:
                raise SpatialWrapError(f"{index}行目: B の出力の形が想定と違います({stereo.channels}ch・{stereo.sample_count}サンプル。入力は{source.sample_count})。")
            pre = stereo.values.astype(np.float64) / undo
            mono = source.values[:, 0].astype(np.float64)
            mask = static.mono_active_mask(mono, rate)
            if not mask.any():
                raise SpatialWrapError(f"{index}行目({wav_path.name})は無音(-50 dBFS未満)で、音量を合わせられません。この行は声を作り直してください。")
            sum_src2 += float(np.sum(mono[mask] ** 2))
            sum_pre2 += float(np.sum(pre[mask] ** 2) / 2.0)
            count_mask += int(mask.sum())
            peak_pre = max(peak_pre, float(np.max(np.abs(pre))))
            pre_path = work / f"pre-{index:04d}.npy"
            np.save(pre_path, pre.astype(np.float32))
            pre_files.append(pre_path)
            rows.append(dict(
                line=index, physical_line=positions[index]["physical"], position=position,
                position_label=POSITION_LABEL[position], tag_explicit=not positions[index]["inherited"],
                wav=wav_path.name, wav_sha256=wav_sha, samples=int(source.sample_count),
                seconds=round(source.sample_count / rate, 3),
                b_cache_wav=out_wav.relative_to(out_dir).as_posix(), b_report=out_json.relative_to(out_dir).as_posix(),
                b_reused=reused,
                b_render=dict(static_gains=render.get("static_gains"), rms_match_gain=render["rms_match_gain"],
                              headroom_gain=render["headroom_gain"],
                              full_source_calibration_delta_db_single_line=render.get("full_source_calibration_delta_db"),
                              level_rule=render.get("level_rule")),
                mask_active_samples=int(mask.sum()),
            ))
            del stereo, pre, mono, source

        target = (sum_src2 / count_mask) ** 0.5
        pre_rms = (sum_pre2 / count_mask) ** 0.5
        match = target / pre_rms
        headroom = min(1.0, static.PEAK_LIMIT / (peak_pre * match)) if peak_pre * match > 0 else 1.0
        scale = match * headroom

        # --- 2パス目: 仕上げ(talk / sleep)。B の static_processing.process_channels を行ごとに。
        preset_name, gain_db = (None, 0.0) if preset == "none" else static.resolve_gain_db(preset=preset)
        line_headroom, post_files = [], []
        for row, pre_path in zip(rows, pre_files):
            stage = np.load(pre_path).astype(np.float64) * scale
            if preset_name is None:
                final, line_h = stage, 1.0
            else:
                final, extra = static.process_channels(stage, rate, gain_db=gain_db, mask=None)
                lv = extra["levels"]
                line_h = float(lv["sample_headroom_gain"]) * float(lv["true_peak_headroom_gain"])
                row["preset_stage"] = dict(shelf_gain_db=gain_db, rms_match_gain=lv["rms_match_gain"],
                                           sample_headroom_gain=lv["sample_headroom_gain"],
                                           true_peak_headroom_gain=lv["true_peak_headroom_gain"])
            line_headroom.append(line_h)
            path = work / f"post-{row['line']:04d}.npy"
            np.save(path, final.astype(np.float32))
            post_files.append(path)
            del stage, final
        min_headroom = min(line_headroom)

        # --- 3パス目: 出力。仕上げのリミッタが一部の行にだけ掛かると行の間の関係が崩れるので、最も強い減衰に全行を揃える。
        report_path = spatial / "spatial-report.json"
        if report_path.is_file():
            os.replace(report_path, spatial / "spatial-report.prev.json")
        for stale in stereo_dir.glob("[0-9][0-9][0-9][0-9].wav"):
            if int(stale.stem) > n:
                stale.unlink()
        all_path = spatial / "all-stereo.wav"
        all_tmp = all_path.with_name("all-stereo.wav.tmp")
        silence = np.zeros((gap_samples, 2), dtype="<i2").tobytes()
        equalize, clip_count, peak_final = {}, 0, 0.0
        with wave.open(str(all_tmp), "wb") as joined:
            joined.setparams((2, 2, rate, 0, "NONE", "not compressed"))
            for row, post_path, line_h, wav_path in zip(rows, post_files, line_headroom, wavs):
                final = np.load(post_path).astype(np.float64)
                factor = min_headroom / line_h if line_h > 0 else 1.0
                if factor < 1.0:
                    final = final * factor
                    equalize[row["line"]] = factor
                clipped = int(np.sum(np.abs(final) > 1.0))
                clip_count += clipped
                peak_final = max(peak_final, float(np.max(np.abs(final))))
                line_path = stereo_dir / f"{row['line']:04d}.wav"
                tmp = line_path.with_name(line_path.name + ".tmp")
                data = _write_int16_wav(tmp, final, rate)
                os.replace(tmp, line_path)
                if row["line"] > 1:
                    joined.writeframesraw(silence)
                joined.writeframesraw(data.tobytes())
                mono = wavio.read_wav(wav_path).values[:, 0].astype(np.float64)
                mask = static.mono_active_mask(mono, rate)
                src_rms = float(np.sqrt(np.mean(mono[mask] ** 2)))
                out_rms = static.combined_active_rms(final, mask)
                row.update(stereo=line_path.relative_to(out_dir).as_posix(), stereo_sha256=sha256_path(line_path),
                           level_db_vs_source=float(20 * np.log10(out_rms / src_rms)),
                           left_minus_right_power_db=static.left_right_power_db(final, mask),
                           peak_abs=float(np.max(np.abs(final))), clipped_samples=clipped)
                del final, mono, data
        os.replace(all_tmp, all_path)

    removed = clean_cache(cache_dir, used_cache)
    after = b_code_snapshot()
    if after["digest"] != before["digest"]:
        raise SpatialWrapError("音声処理(B)のコードの SHA-256 が、実行の前後で変わっています。何かがB側のファイルを書き換えました。出力は信用しないでください。")
    distinct = sorted({r["position"] for r in rows})
    report = dict(
        schema="spatial-wrap/3", wrap_version=WRAP_VERSION, created_utc=datetime.now(timezone.utc).isoformat(),
        preset=preset, preset_gain_db=gain_db if preset_name else None,
        sample_rate=rate, gap_samples=gap_samples, gap_seconds=round(gap_samples / rate, 4), gap_source=gap_source,
        script=dict(sha256=tagged_sha, stripped_sha256=stripped_sha,
                    saved_as=tagged_copy.relative_to(out_dir).as_posix(),
                    stripped_saved_as=stripped_copy.relative_to(out_dir).as_posix()),
        text_check=text_check, product_warnings=warnings,
        product_output=dict(path=".", batch={key: batch.get(key) for key in (
            "version", "status", "exit", "requested", "completed", "pack_chars", "voice", "scenes")},
                            all_wav_sha256=sha256_path(all_mono) if all_mono.is_file() else None),
        scriptwide=dict(
            rule="B の render() の規則を台本全体で1回だけ適用: 行ごとの単一位置の描画から B の行ごとの補正を外し、"
                 "台本全体の active RMS(元の発話の active 区間)に合わせて1つのスカラを掛け、"
                 "0.95 を超えるときだけ共通の減衰。その後に仕上げ。",
            target_rms=target, pre_rms=pre_rms, rms_match_scalar=match, headroom_scalar=headroom,
            peak_before_headroom=peak_pre * match, distinct_positions=distinct,
            single_position_note=("位置が1種類だけなので、全体の音量整合が位置ごとの差(耳元 +4 dB・近く +4 dB・遠く −8 dB)を打ち消し、"
                                  "元との差はほぼ 0 dB になる(B と同じ規則)。" if len(distinct) == 1 else None),
            design_db_vs_front=DESIGN_DB_VS_FRONT,
            preset_headroom_equalized_lines=equalize, preset_min_headroom=min_headroom,
        ),
        lines=rows,
        output=dict(spatial_dir=spatial.relative_to(out_dir).as_posix(), stereo_dir=stereo_dir.relative_to(out_dir).as_posix(),
                    all_stereo=all_path.relative_to(out_dir).as_posix(),
                    all_stereo_sha256=sha256_path(all_path), format="PCM int16, 2ch",
                    peak_abs=peak_final, clipped_samples=clip_count, cache_removed=removed),
        b=dict(code_digest_before=before["digest"], code_digest_after=after["digest"],
               unchanged=after["digest"] == before["digest"], file_count=after["file_count"],
               hrir_sha256=hrir,
               called=["voice_asmr static-spatial(隔離した子Python・行ごと・位置タグ1区画・プリセットなし)",
                       "voice_asmr.static_processing.process_channels(仕上げ・行ごと)",
                       "voice_asmr.static_processing.mono_active_mask / combined_active_rms / left_right_power_db / resolve_gain_db",
                       "voice_asmr.wavio.read_wav"]),
        python=sys.version.split()[0],
        dependencies=versions,
        wrapper_sha256=sha256_path(Path(__file__)),
    )
    atomic_write_json(report_path, report)
    atomic_write_json(marker, dict(complete=True, created_utc=report["created_utc"], wrap_version=WRAP_VERSION,
                                   report_sha256=sha256_path(report_path), all_stereo_sha256=report["output"]["all_stereo_sha256"],
                                   lines=n))
    return report


# ---------------------------------------------------------------- CLI

def _cmd_strip(args):
    data, text = read_script_bytes(args.script)
    out = Path(args.output)
    if out.resolve() == Path(args.script).resolve() or (out.exists() and os.path.samefile(out, args.script)):
        raise SpatialWrapError(f"入力と出力が同じファイルです({out})。台本そのものは書き換えません。別の出力先を指定してください。")
    parsed = parse_script(text, product_root=args.product_root)
    if out.exists() and not args.force:
        raise SpatialWrapError(f"出力先が既にあります: {out}(上書きするには --force)。")
    out.write_bytes(parsed["stripped"].encode("utf-8"))
    print(f"タグを抜いた台本を保存しました: {out}(発話 {parsed['speakable_count']} 行)")
    for ln in parsed["lines"]:
        if ln["speakable"]:
            how = "指定" if not ln["inherited"] else "引き継ぎ"
            print(f"  {ln['wav_index']}行目(台本の{ln['physical']}行): {POSITION_LABEL[ln['position']]}({how})")
    return 0


def _cmd_apply(args):
    report = process_script(args.script, args.out_dir, preset=args.preset, python=args.python,
                             memory_wait_tries=args.memory_wait_tries, memory_wait_seconds=args.memory_wait_seconds,
                             product_root=args.product_root)
    print(f"ステレオの行の音: {report['output']['stereo_dir']}")
    print(f"通しの音: {report['output']['all_stereo']}")
    print(f"記録: {Path(report['output']['spatial_dir']) / 'spatial-report.json'}")
    for row in report["lines"]:
        lr = row["left_minus_right_power_db"]
        print(f"  {row['line']}行目 {row['position_label']}: 左−右 {lr:+.2f} dB / 元との差 {row['level_db_vs_source']:+.2f} dB")
    return 0


def _cmd_inspect(args):
    """製品が非0で終わったあと、音声処理へ進めるかを判定する。complete なら警告を出して0。"""
    try:
        batch = read_batch(args.out_dir)
    except SpatialWrapError as error:
        print(f"エラー: {error}", file=sys.stderr)
        return 2
    if batch.get("status") != "complete" or batch.get("completed") != batch.get("requested"):
        print(f"エラー: 声の生成が全部の行をそろえて終わっていません(status={batch.get('status')}、"
              f"完了 {batch.get('completed')}/{batch.get('requested')} 行)。新しいフォルダで声の生成からやり直してください。", file=sys.stderr)
        return 2
    for w in product_warnings(args.out_dir):
        print(f"警告: 声の{w['line']}行目の第{w['chunk']}断片は、判定に通らないまま採用されています({w['reasons']})。")
    return 0


def _cmd_sha(args):
    snap = b_code_snapshot()
    print(json.dumps({k: v for k, v in snap.items() if k != "files"}, ensure_ascii=False, indent=2))
    if args.save:
        atomic_write_json(args.save, snap)
    return 0


def build_parser():
    parser = argparse.ArgumentParser(description=f"声の生成の出力に、行ごとの位置で音声処理をかける({WRAP_VERSION})")
    sub = parser.add_subparsers(dest="command", required=True)
    strip = sub.add_parser("strip", help="位置タグを抜いた台本を書き出す(声の生成に渡す本文)")
    strip.add_argument("--script", required=True)
    strip.add_argument("--output", required=True)
    strip.add_argument("--force", action="store_true")
    strip.add_argument("--product-root", type=Path)
    strip.set_defaults(func=_cmd_strip)
    apply = sub.add_parser("apply", help="既にある声の出力フォルダに、音声処理だけをかける")
    apply.add_argument("--script", required=True)
    apply.add_argument("--out-dir", required=True)
    apply.add_argument("--preset", choices=PRESETS, default=DEFAULT_PRESET, help="仕上げ(既定: %(default)s)")
    apply.add_argument("--product-root", type=Path)
    apply.add_argument("--python", help="B のCLIを走らせる Python(省略時はこの Python)")
    apply.add_argument("--memory-wait-tries", type=int, default=0)
    apply.add_argument("--memory-wait-seconds", type=int, default=30)
    apply.set_defaults(func=_cmd_apply)
    inspect = sub.add_parser("inspect-product", help="製品の出力が全行そろっているか確かめ、判定に通らなかった断片を警告する")
    inspect.add_argument("--out-dir", required=True)
    inspect.set_defaults(func=_cmd_inspect)
    sha = sub.add_parser("b-sha", help="音声処理(B)のコードのSHA-256を出す")
    sha.add_argument("--save")
    sha.set_defaults(func=_cmd_sha)
    return parser


def main(argv=None):
    args = build_parser().parse_args(argv)
    try:
        return args.func(args)
    except SpatialWrapError as error:
        print(f"エラー: {error}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())