File size: 41,636 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
"""spatial_wrap の単体試験(声の生成・描画は使わない)。

実行: <B の venv の python> -B -m unittest test_spatial_wrap -v   (このフォルダで)
"""
import contextlib
import importlib.util
import io
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock

sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import spatial_wrap as sw  # noqa: E402
import run_spatial as entry  # noqa: E402


# The bundle may be tested beside product sources or with an explicit source-only copy.
sw.PRODUCT_DIR = Path(os.environ.get("SPATIAL_TEST_PRODUCT_ROOT", sw.PRODUCT_DIR)).resolve()


class ParseTests(unittest.TestCase):
    def parse(self, text):
        return sw.parse_script(text)

    def test_inherit_and_default_front(self):
        text = "はじめの行。\n{{位置:右の耳元}}次の行。\n続きの行。\n{{pos:left}}左の行。\n"
        p = self.parse(text)
        self.assertEqual([l["position"] for l in p["lines"]], ["front", "right", "right", "left"])
        self.assertEqual([l["inherited"] for l in p["lines"]], [True, False, True, False])
        self.assertEqual([l["wav_index"] for l in p["lines"]], [1, 2, 3, 4])

    def test_blank_lines_inherit_and_do_not_count(self):
        text = "{{位置:左の耳元}}あ。\n\n   \nい。\n\n{{位置:正面の近く}}う。\n"
        p = self.parse(text)
        speak = [l for l in p["lines"] if l["speakable"]]
        self.assertEqual([l["wav_index"] for l in speak], [1, 2, 3])
        self.assertEqual([l["position"] for l in speak], ["left", "left", "near"])
        self.assertEqual(p["speakable_count"], 3)

    def test_tag_only_line_sets_position_for_following(self):
        p = self.parse("{{位置:右の耳元}}\nあ。\nい。\n")
        speak = [l for l in p["lines"] if l["speakable"]]
        self.assertEqual([l["position"] for l in speak], ["right", "right"])
        self.assertEqual([l["wav_index"] for l in speak], [1, 2])

    def test_tag_only_line_does_not_insert_scene_boundary(self):
        text = "\ufeff一行目。\r\n  {{pos:right}} \r\n二行目。\r\n\r\n{{pos:left}}\r\n三行目。"
        parsed = self.parse(text)
        self.assertEqual(parsed["stripped"], "\ufeff一行目。\r\n二行目。\r\n\r\n三行目。")
        cli, _ = sw._load_product()
        self.assertEqual(cli.file_scenes(parsed["stripped"].removeprefix("\ufeff"))[1], [0, 0, 1])
        self.assertEqual(
            [(row["physical"], row["wav_index"], row["position"]) for row in parsed["lines"] if row["speakable"]],
            [(1, 1, "front"), (3, 2, "right"), (6, 3, "left")])

    def test_untagged_script_is_all_front(self):
        p = self.parse("あ。\nい。\n")
        self.assertEqual({l["position"] for l in p["lines"]}, {"front"})

    def test_symbol_only_line_gets_no_wav_like_product(self):
        # 製品は normalize_for_tts が空になる行(記号だけ等)を読まない
        p = self.parse("あ。\n。\n{{位置:右の耳元}}い。\n")
        self.assertEqual([l["wav_index"] for l in p["lines"]], [1, None, 2])

    def test_all_names_accepted(self):
        for name, key in sw.ALIASES.items():
            p = self.parse("{{位置:%s}}あ。\n" % name if not name.isascii() else "{{pos:%s}}あ。\n" % name)
            self.assertEqual(p["lines"][0]["position"], key)

    def test_midline_tag_is_error(self):
        with self.assertRaises(sw.SpatialWrapError) as cm:
            self.parse("あ。\nこんにちは。{{位置:右の耳元}}さようなら。\n")
        self.assertIn("2行目", str(cm.exception))
        self.assertIn("途中", str(cm.exception))

    def test_two_tags_in_one_line_is_error(self):
        with self.assertRaises(sw.SpatialWrapError) as cm:
            self.parse("{{位置:右の耳元}}{{位置:左の耳元}}あ。\n")
        self.assertIn("1行目", str(cm.exception))

    def test_unknown_name_is_error(self):
        with self.assertRaises(sw.SpatialWrapError) as cm:
            self.parse("{{位置:右耳}}あ。\n")
        self.assertIn("未知の位置名", str(cm.exception))

    def test_misspelled_tags_are_errors(self):
        for bad in ("{{位置:右の耳元}}あ。", "{位置:右の耳元}}あ。", "{{位置:右の耳元}あ。", "{{pos right}}あ。", "あ。{{位置:右の耳元"):
            with self.assertRaises(sw.SpatialWrapError, msg=bad):
                self.parse(bad + "\n")

    def test_single_braces_are_ordinary_text(self):
        p = self.parse("{位置:右の耳元}あ。\n")
        self.assertEqual(p["lines"][0]["position"], "front")  # B も同じ(波括弧1つはタグではない)

    def test_drama_brackets_kept(self):
        p = self.parse("{{位置:右の耳元}}[囁き]あ。\n")
        self.assertEqual(p["stripped"], "[囁き]あ。\n")

    def test_tag_inside_drama_bracket_is_error(self):
        with self.assertRaises(sw.SpatialWrapError):
            self.parse("[囁き{{位置:右の耳元}}]あ。\n")


class StripTests(unittest.TestCase):
    def test_only_tags_removed_bytes_identical(self):
        text = "最初。\r\n\r\n  {{位置:右の耳元}} 全角空白の前に空白。\r\n{{pos:left}}二つ目。 \t\r\n\n最後の行(改行なし)"
        out = sw.strip_tags(text)
        expected = text.replace("{{位置:右の耳元}}", "").replace("{{pos:left}}", "")
        self.assertEqual(out.encode("utf-8"), expected.encode("utf-8"))
        # 行の数・空行の位置が同じ
        self.assertEqual(len(out.splitlines()), len(text.splitlines()))
        self.assertEqual([not l.strip() for l in out.splitlines()][:2], [False, True])

    def test_untagged_is_identical(self):
        text = "あ。\n\nい。\n"
        self.assertEqual(sw.strip_tags(text), text)

    def test_matches_b_script_text(self):
        """B の parse_script の tts_text と一致する(B の script-text の規則との食い違いが無い)。"""
        path = sw.B_EXTRA_CODE[0]
        sw._import_b()
        spec = importlib.util.spec_from_file_location("b_utterance_tags_for_test", path)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        texts = [
            "{{位置:右の耳元}}こんにちは。\n続き。\n{{pos:left}}左。\n",
            "最初は正面。\n\n{{位置:正面の近く}}近い。\n{{位置:正面の遠く}}遠い。\n",
            "{{位置:右の耳元}}[囁き]こんにちは。\n  {{位置:左の耳元}} 空白つき。\n",
        ]
        for text in texts:
            self.assertEqual(sw.strip_tags(text), module.parse_script(text)["tts_text"], text)
        self.assertEqual(sw.ALIASES, module.ALIASES)


class LocateTests(unittest.TestCase):
    def test_missing_wav_message(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            (Path(d) / "0001.wav").write_bytes(b"x")
            with self.assertRaises(sw.SpatialWrapError) as cm:
                sw.locate_product_output(d, 2, batch=dict(status="complete", completed=2))
            self.assertIn("0002.wav", str(cm.exception))

    def test_extra_wav_message(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            for n in (1, 2):
                (Path(d) / f"{n:04d}.wav").write_bytes(b"x")
            with self.assertRaises(sw.SpatialWrapError) as cm:
                sw.locate_product_output(d, 1, batch=dict(status="complete", completed=1))
            self.assertIn("余分", str(cm.exception))



def make_product(folder, text, pack=40, status="complete", flagged=(), with_log=True, wav_seconds=None,
                 freq=200.0, amplitude=0.3):
    """製品の出力フォルダを模した入れ物を作る。log.jsonl は、製品の cli.lines と同じ分け方で書く。"""
    import json
    import wave
    import numpy as np
    cli, _ = sw._load_product()
    folder = Path(folder)
    folder.mkdir(parents=True, exist_ok=True)
    rows = [r for r in text.splitlines() if r.strip() and sw._load_normalizer()(r)]
    records = []
    for number, row in enumerate(rows, 1):
        for chunk, part in enumerate(cli.lines(row, pack)[0], 1):
            records.append(dict(line=number, chunk=chunk, attempt=0, selected=True,
                                flagged=(number, chunk) in flagged, reasons=["quiet"] if (number, chunk) in flagged else [],
                                reason_labels=["無音・小さすぎ"] if (number, chunk) in flagged else [], text=part))
    batch = dict(requested=len(rows), completed=len(rows), status=status, pack_chars=pack,
                 exit=2 if flagged else 0, version="0.2.5")
    (folder / "batch.json").write_text(json.dumps(batch), encoding="utf-8")
    if with_log:
        (folder / "log.jsonl").write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records), encoding="utf-8")
    if wav_seconds:
        rate, pieces = 44100, []
        rng = np.random.default_rng(1)
        for number, seconds in enumerate(wav_seconds, 1):
            t = np.arange(int(rate * seconds)) / rate
            x = amplitude * np.sin(2 * np.pi * freq * (1 + 0.1 * number) * t) + 0.02 * rng.standard_normal(len(t))
            data = np.clip(np.rint(x * 32767), -32768, 32767).astype("<i2")
            with wave.open(str(folder / f"{number:04d}.wav"), "wb") as w:
                w.setparams((1, 2, rate, 0, "NONE", "not compressed"))
                w.writeframes(data.tobytes())
            pieces.append(data)
        gap = np.zeros(round(0.6 * rate), dtype="<i2")
        joined = np.concatenate([p if i == 0 else np.concatenate([gap, p]) for i, p in enumerate(pieces)])
        with wave.open(str(folder / "all.wav"), "wb") as w:
            w.setparams((1, 2, rate, 0, "NONE", "not compressed"))
            w.writeframes(joined.tobytes())
    return rows


SCRIPT = "{{位置:右の耳元}}休みましょうか。\n\nふわっとしたお茶を入れたよ。少し温かいよ。\n{{位置:左の耳元}}おやすみなさい。\n"


class TextCheckTests(unittest.TestCase):
    """A-1: 本文と音の対応を、製品の log.jsonl で確かめる。"""

    def setUp(self):
        import tempfile
        self._tmp = tempfile.TemporaryDirectory()
        self.addCleanup(self._tmp.cleanup)
        self.dir = Path(self._tmp.name) / "out"
        make_product(self.dir, sw.strip_tags(SCRIPT))
        self.batch = sw.read_batch(self.dir)

    def check(self, script, directory=None):
        return sw.verify_text_against_log(directory or self.dir, sw.parse_script(script), self.batch)

    def test_same_text_passes_and_writes_nothing(self):
        before = sorted(p.name for p in self.dir.iterdir())
        info = self.check(SCRIPT)
        self.assertEqual(info["compared_lines"], 3)
        self.assertEqual(sorted(p.name for p in self.dir.iterdir()), before)  # 記録を作らない

    def test_tag_only_changes_pass(self):
        self.check(SCRIPT.replace("右の耳元", "正面の近く"))
        self.check(SCRIPT.replace("{{位置:左の耳元}}", ""))

    def test_tag_only_line_and_blank_lines_pass(self):
        self.check("{{位置:正面の遠く}}\n" + SCRIPT.replace("\n\n", "\n\n\n"))

    def test_different_text_stops_with_line_and_heads(self):
        other = SCRIPT.replace("少し温かいよ", "ちょっと熱いよ")
        with self.assertRaises(sw.SpatialWrapError) as cm:
            self.check(other)
        message = str(cm.exception)
        self.assertIn("2行目", message)
        self.assertIn("ちょっと熱い", message)
        self.assertIn("少し温かい", message)

    def test_other_script_entirely(self):
        with self.assertRaises(sw.SpatialWrapError):
            self.check("{{位置:右の耳元}}まったく別の台本です。\n全然違う行。\n三行目も違う。\n")

    def test_extra_or_missing_lines_stop(self):
        with self.assertRaises(sw.SpatialWrapError):
            self.check(SCRIPT + "もう一行。\n")  # 台本の行が多い: 記録に無い行
        with self.assertRaises(sw.SpatialWrapError):
            self.check("{{位置:右の耳元}}休みましょうか。\n")  # 台本が短い: 記録に台本にない行がある

    def test_missing_log_stops_and_does_not_create_record(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            make_product(Path(d) / "o", sw.strip_tags(SCRIPT), with_log=False)
            with self.assertRaises(sw.SpatialWrapError) as cm:
                self.check(SCRIPT, Path(d) / "o")
            self.assertIn("log.jsonl", str(cm.exception))
            self.assertEqual(sorted(p.name for p in (Path(d) / "o").iterdir()), ["batch.json"])

    def test_packed_and_chained_line(self):
        import tempfile
        long_text = "これは長い一つ目の文で、四十文字を超えるように作った文章です。そして二つ目の文がここに続いています。三つ目。\n"
        with tempfile.TemporaryDirectory() as d:
            make_product(Path(d) / "o", long_text)
            batch = sw.read_batch(Path(d) / "o")
            sw.verify_text_against_log(Path(d) / "o", sw.parse_script(long_text), batch)
            changed = long_text.replace("三つ目", "四つ目")
            with self.assertRaises(sw.SpatialWrapError):
                sw.verify_text_against_log(Path(d) / "o", sw.parse_script(changed), batch)


class FullWidthTests(unittest.TestCase):
    """A-2: 全角の波括弧・コロンは、黙って読み上げさせない。"""

    def test_fullwidth_braces_are_errors(self):
        for bad in ("{{位置:右の耳元}}あ。", "{{位置:右の耳元}}あ。", "{{位置:右の耳元}}あ。", "{位置:右の耳元}}あ。"):
            with self.assertRaises(sw.SpatialWrapError, msg=bad) as cm:
                sw.parse_script(bad + "\n")
            self.assertIn("全角", str(cm.exception))
            self.assertIn("半角", str(cm.exception))

    def test_fullwidth_in_midline_is_error(self):
        with self.assertRaises(sw.SpatialWrapError):
            sw.parse_script("{{位置:正面}}あ。{{位置:左の耳元}}い。\n")

    def test_halfwidth_braces_with_fullwidth_colon_matches_b(self):
        """B は {{位置:右の耳元}} を『不完全または未知のタグ』として止める。包みも止め、コロンの注意を出す。"""
        with self.assertRaises(sw.SpatialWrapError) as cm:
            sw.parse_script("{{位置:右の耳元}}あ。\n")
        self.assertIn("コロン", str(cm.exception))
        sw._import_b()
        spec = importlib.util.spec_from_file_location("b_ut_fw", sw.B_EXTRA_CODE[0])
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        with self.assertRaises(Exception):
            module.parse_script("{{位置:右の耳元}}あ。\n")
        # B は通すが包みは拒む例: 行の途中の文頭タグ(B は文の頭なら途中の行でも通す)
        b_text = "こんにちは。{{位置:右の耳元}}さようなら。\n"
        self.assertTrue(module.parse_script(b_text)["tagged"])
        with self.assertRaises(sw.SpatialWrapError):
            sw.parse_script(b_text)


class StripCommandTests(unittest.TestCase):
    def test_same_path_refused(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            script = Path(d) / "s.txt"
            script.write_text("{{位置:右の耳元}}あ。\n", encoding="utf-8")
            before = script.read_bytes()
            code = sw.main(["strip", "--script", str(script), "--output", str(script), "--force"])
            self.assertEqual(code, 2)
            self.assertEqual(script.read_bytes(), before)

    def test_strip_writes_output(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            script, out = Path(d) / "s.txt", Path(d) / "o.txt"
            script.write_text("{{位置:右の耳元}}あ。\n", encoding="utf-8")
            self.assertEqual(sw.main(["strip", "--script", str(script), "--output", str(out)]), 0)
            self.assertEqual(out.read_text(encoding="utf-8"), "あ。\n")


class InspectProductTests(unittest.TestCase):
    """B-4: 終了コード2(判定に通らない断片あり)でも、全行そろっていれば進む。"""

    def run_inspect(self, **kw):
        import contextlib
        import io
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            make_product(Path(d) / "o", "あいうえお。\nかきくけこ。\n", **kw)
            out = io.StringIO()
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
                code = sw.main(["inspect-product", "--out-dir", str(Path(d) / "o")])
            return code, out.getvalue()

    def test_complete_with_flagged_chunk_warns_and_proceeds(self):
        code, text = self.run_inspect(flagged={(2, 1)})
        self.assertEqual(code, 0)
        self.assertIn("2行目", text)
        self.assertIn("判定に通らない", text)

    def test_incomplete_stops(self):
        code, text = self.run_inspect(status="error")
        self.assertEqual(code, 2)

    def test_process_script_warning_in_report_data(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            make_product(Path(d) / "o", "あいうえお。\n", flagged={(1, 1)})
            self.assertEqual(sw.product_warnings(Path(d) / "o")[0]["line"], 1)


class CacheTests(unittest.TestCase):
    def test_clean_cache_removes_only_stale_wrap_files(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            cache = Path(d)
            keep = "L0001-front-0123456789abcdef.wav"
            stale = "L0001-right-fedcba9876543210.wav"
            (cache / keep).write_bytes(b"x")
            (cache / stale).write_bytes(b"x")
            (cache / "other.txt").write_bytes(b"x")
            (cache / "L0002-abcd1234").mkdir()
            (cache / "L0002-abcd1234" / "out.wav").write_bytes(b"x")
            removed = sw.clean_cache(cache, {keep})
            self.assertTrue((cache / keep).exists())
            self.assertFalse((cache / stale).exists())
            self.assertTrue((cache / "other.txt").exists())
            self.assertFalse((cache / "L0002-abcd1234").exists())
            self.assertEqual(len(removed), 2)


class IntegrationTests(unittest.TestCase):
    """B を実際に呼ぶ小さな合成の通し。B-3(置き場)・完了の印・ヘッドルーム・位置が1種類だけの台本。"""

    @classmethod
    def setUpClass(cls):
        import tempfile
        cls._tmp = tempfile.TemporaryDirectory()
        cls.root = Path(cls._tmp.name)
        cls.python = sys.executable

    @classmethod
    def tearDownClass(cls):
        cls._tmp.cleanup()

    def product(self, name, text, **kw):
        out = self.root / name
        make_product(out, sw.strip_tags(text), **kw)
        return out

    def snapshot(self, folder):
        return {p.name: sw.sha256_path(p) for p in folder.iterdir() if p.is_file()}

    def test_loud_lines_headroom_and_layout(self):
        """B のヘッドルーム補正が 1 未満になる(大きい音)場合。置き場は spatial\\ の中だけ。"""
        import importlib
        sys.path.insert(0, str(Path(__file__).resolve().parent))
        import verify_demo
        text = "{{位置:右の耳元}}あいうえおかきくけこ。\n{{位置:正面}}さしすせそたちつてと。\n"
        out = self.product("loud", text, wav_seconds=(1.5, 1.5), amplitude=0.8)
        before = self.snapshot(out)
        script = self.root / "loud.txt"
        script.write_text(text, encoding="utf-8")
        for preset in ("none", "sleep"):
            report = sw.process_script(script, out, preset=preset, python=self.python, say=lambda *_: None)
            self.assertEqual(self.snapshot(out), before)  # 製品のファイルは不変
            self.assertEqual(sorted(p.name for p in out.iterdir()), sorted(list(before) + ["spatial"]))
            self.assertTrue((out / "spatial" / "COMPLETE.json").is_file())
            right = report["lines"][0]
            kept_report = json.loads((out / right["b_report"]).read_bytes())
            self.assertEqual(kept_report["input"]["path"], "0001.wav")
            self.assertEqual(kept_report["output"]["path"], right["b_cache_wav"])
            self.assertNotIn("path", kept_report["script"])
            self.assertNotIn("path", kept_report["front_hrir"])
            self.assertEqual(kept_report["render"]["near_hrir"]["attribution"], "spatial/LICENSES/FHK-ATTRIBUTION.md")
            self.assertLess(right["b_render"]["headroom_gain"], 1.0)  # B 自身の補正が 1 未満
            self.assertLess(report["output"]["peak_abs"], 1.0)
            self.assertEqual(report["output"]["clipped_samples"], 0)
            results, problems, notes, *_ = verify_demo.verify(out)
            self.assertEqual(problems, [])
            diff = results[0]["level_db_vs_source"] - results[1]["level_db_vs_source"]
            self.assertAlmostEqual(diff, 4.0, delta=0.05)  # 耳元は正面より +4 dB
        # sleep のときは仕上げのリミッタが行ごとに違っても、全行を揃えている
        self.assertEqual(report["preset"], "sleep")
        self.assertTrue(all("preset_stage" in r for r in report["lines"]))
        self.assertEqual(len(list((out / "spatial" / "scripts").glob("tagged-*.txt"))), 1)
        self.assertEqual(len(list((out / "spatial" / "scripts").glob("stripped-*.txt"))), 1)
        self.assertEqual(report["wrapper_sha256"], sw.sha256_path(sw.HERE / "spatial_wrap.py"))
        verify = sw.HERE / "tests" / "verify_demo.py"
        result = subprocess.run([sys.executable, "-B", "-X", "utf8", str(verify), str(out)],
                                cwd=self.root, capture_output=True, encoding="utf-8")
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
        self.assertIn("すべて通過", result.stdout)

    def test_single_position_script_is_not_skipped(self):
        import verify_demo
        text = "{{位置:正面の近く}}あいうえおかきくけこ。\nさしすせそたちつてと。\n"
        out = self.product("single", text, wav_seconds=(1.2, 1.2), amplitude=0.1)
        script = self.root / "single.txt"
        script.write_text(text, encoding="utf-8")
        report = sw.process_script(script, out, preset="talk", python=self.python, say=lambda *_: None)
        self.assertIsNotNone(report["scriptwide"]["single_position_note"])
        results, problems, notes, *_ = verify_demo.verify(out)
        self.assertEqual(problems, [])
        self.assertTrue(notes)
        for r in results:
            self.assertAlmostEqual(r["level_db_vs_source"], 0.0, delta=0.1)  # 差が打ち消される

    def test_default_sleep_and_no_hardlinks_in_output_filesystem(self):
        text = "{{pos:right}}こんにちは。\n"
        out = self.product("no-links", text, wav_seconds=(0.5,), amplitude=0.1)
        script = self.root / "no-links.txt"
        script.write_text(text, encoding="utf-8")
        run = subprocess.run
        os_link = os.link
        render_dirs = []

        def no_links_in_output(source, destination, *args, **kwargs):
            if Path(destination).resolve().is_relative_to(out.resolve()):
                raise OSError("出力先はハードリンク非対応")
            return os_link(source, destination, *args, **kwargs)

        def enforce_child_output_fs(command, **kwargs):
            work = Path(command[command.index("--output") + 1]).parent
            render_dirs.append(work)
            self.assertTrue(work.resolve().is_relative_to(Path(tempfile.gettempdir()).resolve()))
            self.assertFalse(work.resolve().is_relative_to(out.resolve()))
            # 子でも同じ条件を適用。実際のDSPの os.link がどこで起こるかを試す。
            simulate = (
                "import os\nfrom pathlib import Path\nreal_link = os.link\n"
                "def outside_output(source, destination, *args, **kwargs):\n"
                f"    if Path(destination).resolve().is_relative_to(Path({str(out)!r}).resolve()):\n"
                "        raise OSError('output does not support hardlinks')\n"
                "    return real_link(source, destination, *args, **kwargs)\n"
                "os.link = outside_output\n"
            )
            command = list(command)
            command[command.index("-c") + 1] = simulate + sw.B_CHILD
            return run(command, **kwargs)

        with mock.patch.object(os, "link", side_effect=no_links_in_output), \
             mock.patch.object(sw.subprocess, "run", side_effect=enforce_child_output_fs):
            report = sw.process_script(script, out, say=lambda *_: None)
        self.assertEqual(report["preset"], "sleep")
        self.assertEqual(report["gap_samples"], 0)
        self.assertIn("1行のため行間なし", report["gap_source"])
        self.assertTrue((out / "spatial" / "all-stereo.wav").is_file())
        self.assertEqual(len(render_dirs), 1)
        self.assertFalse(render_dirs[0].parent.exists())

    def test_failure_leaves_no_complete_marker_and_no_work_dirs(self):
        text = "{{位置:右の耳元}}あいうえおかきくけこ。\n"
        out = self.product("失敗 の出力", text, wav_seconds=(1.0,), amplitude=0.1)
        script = self.root / "失敗 の台本.txt"
        script.write_text(text, encoding="utf-8")
        sw.process_script(script, out, preset="talk", python=self.python, say=lambda *_: None)
        self.assertTrue((out / "spatial" / "COMPLETE.json").is_file())
        # 2回目: B の呼び出しを壊して(存在しない Python)、失敗させる。キャッシュに無い位置へ変える。
        script.write_text(text.replace("右の耳元", "左の耳元"), encoding="utf-8")
        with self.assertRaises(Exception):
            sw.process_script(script, out, preset="talk", python=str(self.root / "no-such-python.exe"), say=lambda *_: None)
        self.assertFalse((out / "spatial" / "COMPLETE.json").exists())  # 完了の印は無い
        leftovers = [p.name for p in (out / "spatial" / "spatial-cache").iterdir() if p.is_dir()]
        self.assertEqual(leftovers, [])  # 失敗で残った作業フォルダを残さない


class EntryTests(unittest.TestCase):
    def setUp(self):
        temp = tempfile.TemporaryDirectory(prefix="spatial-test-")
        self.addCleanup(temp.cleanup)
        self.root = Path(temp.name)
        self.script = self.root / "位置 つき.txt"
        self.script.write_text("こんにちは。\n{{pos:right}}\nこんばんは。\n", encoding="utf-8")
        self.out = self.root / "声 の出力"
        self.args = ["say-file", self.script.name, "-o", self.out.name, "--product-root", str(sw.PRODUCT_DIR)]

    def run_entry(self, args):
        out = io.StringIO()
        previous = Path.cwd()
        try:
            os.chdir(self.root)
            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
                code = entry.main(args)
        finally:
            os.chdir(previous)
        return code, out.getvalue()

    def test_new_args_forwarded(self):
        args = ["--voice", "fixed", "--voice-text", "星 が光る。", "--future-option", "1"]
        with mock.patch.object(entry.subprocess, "run") as run:
            code, output = self.run_entry([*self.args, "--dry-run", "--", *args])
        self.assertEqual(code, 0, output)
        command = json.loads(next(line for line in output.splitlines() if line.startswith("声の生成:")).split(": ", 1)[1])
        self.assertEqual(command[7:-2], args)
        self.assertEqual(command[-2:], ["-o", str(self.out)])
        run.assert_not_called()
        self.assertFalse(self.out.exists())

    def test_not_forwarded_when_unspecified(self):
        code, output = self.run_entry([*self.args, "--dry-run"])
        self.assertEqual(code, 0, output)
        self.assertNotIn("--voice", output)
        self.assertNotIn("--pack-chars", output)

    def test_invalid_values_rejected(self):
        for opt in (["--preset", "bogus"], ["--memory-wait-tries", "-1"]):
            with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
                self.run_entry([*self.args, *opt])

    def test_spatial_only_refuses_voice_args(self):
        for extras in (["--voice", "scene"], ["--", "--voice", "scene"]):
            with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
                self.run_entry(["apply", "--script", str(self.script), "--out-dir", str(self.out), *extras])

    def say_file(self, exit_code, *, flagged=(), status="complete"):
        def simulate(command, **kwargs):
            self.assertEqual(command[4:6], [str(sw.PRODUCT_DIR / "run.py"), "say-file"])
            stripped = Path(command[6])
            self.assertTrue(stripped.is_absolute())
            text = stripped.read_text(encoding="utf-8")
            self.assertEqual(text, "こんにちは。\nこんばんは。\n")
            self.assertEqual(command[7:9], ["--voice", "scene"])
            self.assertEqual(Path(command[-1]), self.out)
            make_product(self.out, text, status=status, flagged=flagged, wav_seconds=(0.1, 0.1))
            return subprocess.CompletedProcess(command, exit_code)

        def fake_apply(script, directory, **kwargs):
            self.assertEqual(kwargs["product_root"], sw.PRODUCT_DIR)
            self.assertEqual(kwargs["memory_wait_tries"], 2)
            self.assertEqual(Path(directory), self.out)
            self.assertEqual(Path(script).read_bytes(), self.script.read_bytes())
            return {"output": {"all_stereo": "spatial/all-stereo.wav"}}

        with mock.patch.object(entry.subprocess, "run", side_effect=simulate) as run, \
             mock.patch.object(sw, "process_script", side_effect=fake_apply) as apply:
            code, output = self.run_entry([*self.args, "--memory-wait-tries", "2", "--", "--voice", "scene"])
        run.assert_called_once()
        return code, output, apply.call_count

    def test_say_file_calls_both_stages(self):
        code, output, applied = self.say_file(0)
        self.assertEqual((code, applied), (0, 1), output)
        self.assertIn("完了:", output)

    def test_code_two_with_all_rows_and_warning_applies(self):
        code, output, applied = self.say_file(2, flagged={(2, 1)})
        self.assertEqual((code, applied), (0, 1), output)
        self.assertIn("全行はそろっています", output)

    def test_code_two_without_warning_stops(self):
        code, output, applied = self.say_file(2)
        self.assertEqual((code, applied), (2, 0), output)
        self.assertIn("終了コード2の理由", output)

    def test_incomplete_code_two_stops(self):
        code, output, applied = self.say_file(2, status="error")
        self.assertEqual((code, applied), (2, 0), output)
        self.assertIn("新しい出力フォルダ", output)

    def test_check_succeeds(self):
        code, output = self.run_entry(["check"])
        self.assertEqual(code, 0, output)
        self.assertIn("13点", output)
        self.assertIn("h5py", output)

    def test_check_missing_dependency_displays_install(self):
        import_module = sw.importlib.import_module

        def missing(name):
            if name == "h5py":
                raise ImportError(name)
            return import_module(name)

        with mock.patch.object(sw.importlib, "import_module", side_effect=missing):
            code, output = self.run_entry(["check"])
        self.assertEqual(code, 2, output)
        self.assertIn("pip install numpy==", output)
        self.assertIn("h5py==3.16.0", output)

    def test_mismatched_sha_stops_before_apply_touches_output(self):
        from shutil import copyfile

        manifest = json.loads((sw.HERE / "MANIFEST-spatial.json").read_bytes())
        for item in manifest["files"]:
            dest = self.root / item["path"]
            dest.parent.mkdir(parents=True, exist_ok=True)
            copyfile(sw.HERE / item["path"], dest)
        (self.root / "MANIFEST-spatial.json").write_text(json.dumps(manifest), encoding="utf-8")
        changed = self.root / manifest["files"][0]["path"]
        with changed.open("ab") as f:
            f.write(b"\n")
        snapshot = sw.b_code_snapshot
        with mock.patch.object(sw, "b_code_snapshot", side_effect=lambda: snapshot(self.root)):
            code, output = self.run_entry(["apply", "--script", str(self.script), "--out-dir", str(self.out),
                                           "--product-root", str(sw.PRODUCT_DIR)])
        self.assertEqual(code, 2, output)
        self.assertIn("SHA-256", output)
        self.assertFalse(self.out.exists())

    def test_product_root_missing_and_version_warning(self):
        with self.assertRaisesRegex(sw.SpatialWrapError, "--product-root"):
            sw._load_product(self.root / "missing")
        messages = []
        sw.warn_product_version("0.9.0", "製品", messages.append)
        self.assertIn("0.9.0", messages[0])

    def test_cache_key_depends_on_both_hrirs_and_versions(self):
        inputs = dict(nd="nf025", front="sadie", numpy="1", scipy="2", h5py="3")
        key = sw._line_key("wav", "front", inputs)
        for changed in inputs:
            self.assertNotEqual(key, sw._line_key("wav", "front", {**inputs, changed: "different"}))

    def apply_args(self, *extra):
        return ["apply", "--script", str(self.script), "--out-dir", str(self.out),
                "--product-root", str(sw.PRODUCT_DIR), *extra]

    def make_input(self):
        make_product(self.out, "こんにちは。\nこんばんは。\n", wav_seconds=(0.1, 0.1))

    def test_temp_hardlink_failure_has_dedicated_message_and_cleans_up(self):
        self.make_input()
        with mock.patch.object(os, "link", side_effect=OSError("hardlink unavailable")) as link:
            code, message = self.run_entry(self.apply_args())
        self.assertEqual(code, 2, message)
        self.assertIn("一時フォルダでハードリンク", message)
        self.assertIn("TMPDIR", message)
        self.assertNotIn("apply でやり直せます", message)
        self.assertFalse(Path(link.call_args.args[0]).parent.exists())
        self.assertFalse((self.out / "spatial").exists())

    def test_text_mismatch_does_not_suggest_apply(self):
        self.make_input()
        self.script.write_text("違う本文です。\nこんばんは。\n", encoding="utf-8")
        code, message = self.run_entry(self.apply_args())
        self.assertEqual(code, 2, message)
        self.assertIn("声を生成したときと違う行", message)
        self.assertNotIn("apply でやり直せます", message)

    def test_memory_failure_can_retry_apply(self):
        self.make_input()
        with mock.patch.object(sw, "available_memory", return_value=(0, "test")):
            code, message = self.run_entry(self.apply_args())
        self.assertEqual(code, 2, message)
        self.assertIn("apply でやり直せます", message)

    def test_linux_guard_uses_available_even_when_memfree_disagrees(self):
        self.make_input()
        meminfo = self.root / "meminfo"
        for free, available, expected in ((1, 2048, "guard passed"), (2048, 1, "使える量 1 MiB(MemAvailable)")):
            with self.subTest(free=free, available=available):
                meminfo.write_text(f"MemFree: {free * 1024} kB\nMemAvailable: {available * 1024} kB\n",
                                   encoding="ascii")
                with mock.patch.object(sw, "LINUX_MEMINFO", meminfo), \
                        mock.patch.object(sw, "CGROUP_MEMORY", self.root), \
                        mock.patch.object(sw.sys, "platform", "linux"), \
                        mock.patch.object(sw, "verify_temp_hardlinks", side_effect=sw.SpatialWrapError("guard passed")):
                    code, message = self.run_entry(self.apply_args())
                self.assertEqual(code, 2, message)
                self.assertIn(expected, message)

    def test_linux_memory_fallback_and_cgroup_ceiling(self):
        meminfo = self.root / "meminfo"
        meminfo.write_text("MemFree: 100 kB\nBuffers: 200 kB\nCached: 300 kB\n", encoding="ascii")
        with mock.patch.object(sw, "LINUX_MEMINFO", meminfo), mock.patch.object(sw, "CGROUP_MEMORY", self.root):
            self.assertEqual(sw.linux_available_memory(), (600 * 1024, "MemFree + Buffers + Cached"))
            (self.root / "memory.max").write_text("200000\n", encoding="ascii")
            (self.root / "memory.current").write_text("150000\n", encoding="ascii")
            self.assertEqual(sw.linux_available_memory(), (50000, "cgroup memory.max − memory.current"))
            (self.root / "memory.max").write_text("max\n", encoding="ascii")
            meminfo.write_text("MemFree: 100 kB\n", encoding="ascii")
            self.assertIsNone(sw.linux_available_memory()[0])

    def test_linux_dsp_child_uses_same_probe_without_editing_adapter(self):
        from types import SimpleNamespace

        adapter = SimpleNamespace(MEMORY_LIMIT_BYTES=1024 * sw.MIB)
        cli = SimpleNamespace(_load_position_adapter=lambda: adapter)

        def main():
            loaded = cli._load_position_adapter()
            self.assertEqual(loaded.available_memory(), 900 * sw.MIB)
            return 0

        cli.main = main
        spec = SimpleNamespace(origin=str(Path.cwd() / "voice_asmr" / "__init__.py"))
        with mock.patch.dict(sys.modules, {"spatial_wrap": sw, "voice_asmr": SimpleNamespace(cli=cli)}), \
                mock.patch.object(sw.importlib.util, "find_spec", return_value=spec), \
                mock.patch.object(sys, "argv", ["-c", str(sw.HERE), "static-spatial"]), \
                mock.patch.object(sys, "path", list(sys.path)), mock.patch.object(sys, "platform", "linux"), \
                mock.patch.object(sw, "available_memory", return_value=(900 * sw.MIB, "MemAvailable")), \
                self.assertRaises(SystemExit) as exit_signal:
            exec(sw.B_CHILD, {})
        self.assertEqual(exit_signal.exception.code, 0)

    def test_external_voice_asmr_stops(self):
        from types import ModuleType
        from importlib.machinery import ModuleSpec

        other = ModuleType("voice_asmr")
        other.__spec__ = ModuleSpec("voice_asmr", None, origin=str(self.root / "voice_asmr/__init__.py"))
        with mock.patch.dict(sys.modules, {"voice_asmr": other}):
            with self.assertRaisesRegex(sw.SpatialWrapError, "同梱でない voice_asmr"):
                sw._import_b()

    def test_extra_python_file_stops_but_pycache_is_ignored(self):
        from shutil import copytree

        for source in ("work", "drama3_asmr"):
            copytree(sw.HERE / source, self.root / source)
        (self.root / "MANIFEST-spatial.json").write_bytes((sw.HERE / "MANIFEST-spatial.json").read_bytes())
        b_root = self.root / sw.B_ROOT.relative_to(sw.HERE)
        cache = b_root / "voice_asmr" / "__pycache__"
        cache.mkdir()
        (cache / "ignored.py").touch()
        self.assertEqual(sw.b_code_snapshot(self.root)["file_count"], 13)
        (b_root / "numpy.py").touch()
        with self.assertRaisesRegex(sw.SpatialWrapError, "マニフェストにない.*numpy.py"):
            sw.b_code_snapshot(self.root)

    def test_corrupt_all_wav_with_two_lines_stops(self):
        self.make_input()
        import wave
        all_wav = self.out / "all.wav"
        with wave.open(str(all_wav), "rb") as f:
            params, pcm = f.getparams(), bytearray(f.readframes(f.getnframes()))
        pcm[params.framerate // 10 * 2] = 17  # 1行目の直後の行間に混入
        with wave.open(str(all_wav), "wb") as f:
            f.setparams(params)
            f.writeframes(pcm)
        code, message = self.run_entry(self.apply_args())
        self.assertEqual(code, 2, message)
        self.assertIn("等間隔の無音", message)
        self.assertNotIn("apply でやり直せます", message)

    def test_apply_dry_run_checks_input_and_does_not_write(self):
        code, message = self.run_entry(self.apply_args("--dry-run"))
        self.assertEqual(code, 2, message)
        self.assertIn("声の出力フォルダがありません", message)
        self.make_input()
        code, message = self.run_entry(self.apply_args("--dry-run"))
        self.assertEqual(code, 0, message)
        self.assertIn("試行表示のみ", message)
        self.assertFalse((self.out / "spatial").exists())

    def test_dependency_version_mismatch_is_a_warning(self):
        import h5py

        with mock.patch.object(h5py, "__version__", "0.1.0"):
            code, message = self.run_entry(["check"])
        self.assertEqual(code, 0, message)
        self.assertIn("警告: h5py 0.1.0", message)

    def test_help_and_default_preset(self):
        args = entry.parser().parse_args(self.apply_args())
        self.assertEqual(args.preset, "sleep")
        help_text = io.StringIO()
        with self.assertRaises(SystemExit), contextlib.redirect_stdout(help_text):
            entry.main(["apply", "--help"])
        self.assertIn("既定: sleep", help_text.getvalue())


if __name__ == "__main__":
    unittest.main()