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