test_bio_tagger.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests fuer den BIO-Tagger (Slot-Extraktion).
  4. Testet BIOTagSet, generate_word_bio_tags, align_bio_to_tokens und decode_bio_tags.
  5. """
  6. from __future__ import annotations
  7. from dataclasses import dataclass, field
  8. from typing import Any
  9. from unittest.mock import MagicMock
  10. import pytest
  11. from trixy_core.trainer.core.intent.bio_tagger import (
  12. BIOTagSet,
  13. align_bio_to_tokens,
  14. decode_bio_tags,
  15. generate_word_bio_tags,
  16. )
  17. # =========================================================================
  18. # Hilfsfunktionen und Mock-Tokenizer
  19. # =========================================================================
  20. class MockEncoding:
  21. """Simuliert ein HuggingFace Encoding-Objekt mit word_ids()."""
  22. def __init__(self, word_id_list: list[int | None]) -> None:
  23. self._word_ids = word_id_list
  24. def word_ids(self) -> list[int | None]:
  25. return self._word_ids
  26. class MockTokenizer:
  27. """
  28. Mock-Tokenizer der word_ids und decode unterstuetzt.
  29. Konfiguration ueber Konstruktor-Parameter.
  30. """
  31. def __init__(
  32. self,
  33. word_id_list: list[int | None] | None = None,
  34. decode_map: dict[tuple[int, ...], str] | None = None,
  35. ) -> None:
  36. self._word_id_list = word_id_list or []
  37. self._decode_map = decode_map or {}
  38. def __call__(self, text: str, **kwargs: Any) -> MockEncoding:
  39. return MockEncoding(self._word_id_list)
  40. def decode(self, token_ids: list[int], skip_special_tokens: bool = True) -> str:
  41. """Gibt den decodierten Text fuer die Token-IDs zurueck."""
  42. key = tuple(token_ids)
  43. if key in self._decode_map:
  44. return self._decode_map[key]
  45. # Fallback: IDs als String zusammenfuegen
  46. return " ".join(str(t) for t in token_ids)
  47. # =========================================================================
  48. # BIOTagSet — Konstruktion und Grundlagen
  49. # =========================================================================
  50. class TestBIOTagSetConstruction:
  51. """Tests fuer die Erstellung eines BIOTagSet."""
  52. def test_construction_with_slots(self) -> None:
  53. """BIOTagSet mit Slots erstellt korrekte Tags."""
  54. tagset = BIOTagSet(slot_names=["city", "date"])
  55. assert tagset.num_tags == 6 # O, PAD, B-city, I-city, B-date, I-date
  56. def test_tag_ordering(self) -> None:
  57. """Tags werden in korrekter Reihenfolge erstellt: O, PAD, dann B/I sortiert."""
  58. tagset = BIOTagSet(slot_names=["query", "city"])
  59. tags = tagset.tags
  60. assert tags[0] == "O"
  61. assert tags[1] == "PAD"
  62. # Sortiert: city vor query
  63. assert tags[2] == "B-city"
  64. assert tags[3] == "I-city"
  65. assert tags[4] == "B-query"
  66. assert tags[5] == "I-query"
  67. def test_num_tags_formula(self) -> None:
  68. """num_tags = 2 + 2 * len(slot_names)."""
  69. for n in range(0, 6):
  70. slots = [f"slot_{i}" for i in range(n)]
  71. tagset = BIOTagSet(slot_names=slots)
  72. assert tagset.num_tags == 2 + 2 * n
  73. def test_empty_slots(self) -> None:
  74. """BIOTagSet ohne Slots hat nur O und PAD."""
  75. tagset = BIOTagSet(slot_names=[])
  76. assert tagset.num_tags == 2
  77. assert tagset.tags == ["O", "PAD"]
  78. def test_single_slot(self) -> None:
  79. """BIOTagSet mit einem Slot hat 4 Tags."""
  80. tagset = BIOTagSet(slot_names=["room"])
  81. assert tagset.num_tags == 4
  82. assert "B-room" in tagset.tags
  83. assert "I-room" in tagset.tags
  84. def test_slots_sorted_alphabetically(self) -> None:
  85. """Slot-Tags werden alphabetisch nach Slot-Name sortiert."""
  86. tagset = BIOTagSet(slot_names=["zoo", "alpha", "middle"])
  87. tags = tagset.tags
  88. # alpha kommt vor middle kommt vor zoo
  89. alpha_idx = tags.index("B-alpha")
  90. middle_idx = tags.index("B-middle")
  91. zoo_idx = tags.index("B-zoo")
  92. assert alpha_idx < middle_idx < zoo_idx
  93. class TestBIOTagSetIndices:
  94. """Tests fuer Index-Zugriffe auf BIOTagSet."""
  95. def test_o_idx(self) -> None:
  96. """O-Index ist immer 0."""
  97. tagset = BIOTagSet(slot_names=["city"])
  98. assert tagset.o_idx == 0
  99. def test_pad_idx(self) -> None:
  100. """PAD-Index ist immer 1."""
  101. tagset = BIOTagSet(slot_names=["city"])
  102. assert tagset.pad_idx == 1
  103. def test_tag_to_idx_known(self) -> None:
  104. """Bekannte Tags geben korrekten Index zurueck."""
  105. tagset = BIOTagSet(slot_names=["city"])
  106. assert tagset.tag_to_idx("O") == 0
  107. assert tagset.tag_to_idx("PAD") == 1
  108. assert tagset.tag_to_idx("B-city") == 2
  109. assert tagset.tag_to_idx("I-city") == 3
  110. def test_tag_to_idx_unknown_returns_o_idx(self) -> None:
  111. """Unbekannte Tags geben O-Index (0) zurueck."""
  112. tagset = BIOTagSet(slot_names=["city"])
  113. assert tagset.tag_to_idx("B-unknown") == tagset.o_idx
  114. def test_idx_to_tag_known(self) -> None:
  115. """Bekannte Indizes geben korrekten Tag-Namen zurueck."""
  116. tagset = BIOTagSet(slot_names=["query"])
  117. assert tagset.idx_to_tag(0) == "O"
  118. assert tagset.idx_to_tag(1) == "PAD"
  119. def test_idx_to_tag_unknown_returns_o(self) -> None:
  120. """Unbekannte Indizes geben 'O' zurueck."""
  121. tagset = BIOTagSet(slot_names=["city"])
  122. assert tagset.idx_to_tag(999) == "O"
  123. def test_roundtrip_tag_to_idx_to_tag(self) -> None:
  124. """tag_to_idx und idx_to_tag sind inverse Operationen."""
  125. tagset = BIOTagSet(slot_names=["city", "date", "query"])
  126. for tag in tagset.tags:
  127. idx = tagset.tag_to_idx(tag)
  128. assert tagset.idx_to_tag(idx) == tag
  129. def test_roundtrip_idx_to_tag_to_idx(self) -> None:
  130. """idx_to_tag und tag_to_idx sind inverse Operationen."""
  131. tagset = BIOTagSet(slot_names=["room", "status"])
  132. for i in range(tagset.num_tags):
  133. tag = tagset.idx_to_tag(i)
  134. assert tagset.tag_to_idx(tag) == i
  135. class TestBIOTagSetSerialization:
  136. """Tests fuer to_dict / from_dict Serialisierung."""
  137. def test_to_dict_contains_all_tags(self) -> None:
  138. """to_dict enthaelt alle Tags mit korrekten Indizes."""
  139. tagset = BIOTagSet(slot_names=["city", "date"])
  140. d = tagset.to_dict()
  141. assert d["O"] == 0
  142. assert d["PAD"] == 1
  143. assert "B-city" in d
  144. assert "I-city" in d
  145. assert "B-date" in d
  146. assert "I-date" in d
  147. assert len(d) == 6
  148. def test_from_dict_reconstructs(self) -> None:
  149. """from_dict rekonstruiert ein identisches BIOTagSet."""
  150. original = BIOTagSet(slot_names=["city", "date"])
  151. d = original.to_dict()
  152. reconstructed = BIOTagSet.from_dict(d)
  153. assert reconstructed.to_dict() == d
  154. def test_from_dict_extracts_slot_names(self) -> None:
  155. """from_dict extrahiert Slot-Namen aus B- Tags."""
  156. d = {"O": 0, "PAD": 1, "B-room": 2, "I-room": 3, "B-status": 4, "I-status": 5}
  157. tagset = BIOTagSet.from_dict(d)
  158. assert sorted(tagset.slot_names) == ["room", "status"]
  159. def test_roundtrip_empty_slots(self) -> None:
  160. """Roundtrip mit leeren Slots funktioniert."""
  161. original = BIOTagSet(slot_names=[])
  162. d = original.to_dict()
  163. reconstructed = BIOTagSet.from_dict(d)
  164. assert reconstructed.num_tags == 2
  165. assert reconstructed.tags == ["O", "PAD"]
  166. def test_from_dict_ignores_extra_keys(self) -> None:
  167. """from_dict ignoriert Tags die nicht B- sind (ausser O/PAD)."""
  168. d = {"O": 0, "PAD": 1, "B-city": 2, "I-city": 3, "CUSTOM": 99}
  169. tagset = BIOTagSet.from_dict(d)
  170. # Nur city als Slot erkannt
  171. assert tagset.slot_names == ["city"]
  172. # =========================================================================
  173. # generate_word_bio_tags
  174. # =========================================================================
  175. class TestGenerateWordBioTags:
  176. """Tests fuer die Wort-Level BIO-Tag Generierung."""
  177. def test_single_slot_at_end(self) -> None:
  178. """Einzelner Slot am Satzende."""
  179. tags = generate_word_bio_tags(
  180. "Wie wird das Wetter in Berlin",
  181. {"city": "Berlin"},
  182. )
  183. assert tags == ["O", "O", "O", "O", "O", "B-city"]
  184. def test_single_slot_at_beginning(self) -> None:
  185. """Slot am Satzanfang."""
  186. tags = generate_word_bio_tags(
  187. "Berlin hat gutes Wetter",
  188. {"city": "Berlin"},
  189. )
  190. assert tags == ["B-city", "O", "O", "O"]
  191. def test_single_slot_in_middle(self) -> None:
  192. """Slot in der Satzmitte."""
  193. tags = generate_word_bio_tags(
  194. "das Wetter in Berlin ist gut",
  195. {"city": "Berlin"},
  196. )
  197. assert tags == ["O", "O", "O", "B-city", "O", "O"]
  198. def test_multi_word_slot(self) -> None:
  199. """Mehrwort-Slot erzeugt B- und I- Tags."""
  200. tags = generate_word_bio_tags(
  201. "Wie ist das Wetter in New York",
  202. {"city": "New York"},
  203. )
  204. assert tags == ["O", "O", "O", "O", "O", "B-city", "I-city"]
  205. def test_three_word_slot(self) -> None:
  206. """Dreiwort-Slot erzeugt B-I-I."""
  207. tags = generate_word_bio_tags(
  208. "spiele songs von Die Toten Hosen",
  209. {"artist": "Die Toten Hosen"},
  210. )
  211. assert tags == ["O", "O", "O", "B-artist", "I-artist", "I-artist"]
  212. def test_multi_value_slot(self) -> None:
  213. """Slot mit mehreren Werten (Liste) erzeugt mehrere B- Tags."""
  214. tags = generate_word_bio_tags(
  215. "ich haette gerne Salami und Pilze",
  216. {"topping": ["Salami", "Pilze"]},
  217. )
  218. assert tags == ["O", "O", "O", "B-topping", "O", "B-topping"]
  219. def test_multiple_different_slots(self) -> None:
  220. """Mehrere verschiedene Slots im selben Satz."""
  221. # Woerter: ["Wie", "wird", "das", "Wetter", "morgen", "in", "Berlin"]
  222. # 0 1 2 3 4 5 6
  223. tags = generate_word_bio_tags(
  224. "Wie wird das Wetter morgen in Berlin",
  225. {"city": "Berlin", "date": "morgen"},
  226. )
  227. assert tags[4] == "B-date" # morgen (Index 4)
  228. assert tags[5] == "O" # in
  229. assert tags[6] == "B-city" # Berlin (letztes Wort)
  230. def test_empty_slots(self) -> None:
  231. """Leere Slots erzeugen nur O-Tags."""
  232. tags = generate_word_bio_tags("Hallo wie geht es dir", {})
  233. assert tags == ["O", "O", "O", "O", "O"]
  234. def test_no_match_found(self) -> None:
  235. """Slot-Wert der nicht im Text vorkommt erzeugt nur O-Tags."""
  236. tags = generate_word_bio_tags(
  237. "Hallo wie geht es",
  238. {"city": "Berlin"},
  239. )
  240. assert tags == ["O", "O", "O", "O"]
  241. def test_case_insensitive_matching(self) -> None:
  242. """Wort-Matching ist case-insensitive."""
  243. tags = generate_word_bio_tags(
  244. "spiele musik von RAMMSTEIN",
  245. {"artist": "rammstein"},
  246. )
  247. assert tags == ["O", "O", "O", "B-artist"]
  248. def test_case_insensitive_slot_upper(self) -> None:
  249. """Slot-Wert in Grossbuchstaben matcht Kleinschreibung im Text."""
  250. tags = generate_word_bio_tags(
  251. "mach das licht im wohnzimmer an",
  252. {"room": "Wohnzimmer"},
  253. )
  254. assert tags[4] == "B-room"
  255. def test_punctuation_handling(self) -> None:
  256. """Interpunktion wird beim Matching ignoriert (z.B. 'Berlin,' matcht 'Berlin')."""
  257. tags = generate_word_bio_tags(
  258. "Wie ist das Wetter in Berlin, heute",
  259. {"city": "Berlin"},
  260. )
  261. assert tags == ["O", "O", "O", "O", "O", "B-city", "O"]
  262. def test_punctuation_exclamation(self) -> None:
  263. """Ausrufezeichen wird beim Matching ignoriert."""
  264. tags = generate_word_bio_tags(
  265. "Stoppe die Musik!",
  266. {"action": "Musik"},
  267. )
  268. assert tags == ["O", "O", "B-action"]
  269. def test_single_word_text(self) -> None:
  270. """Einwort-Text mit Slot-Match."""
  271. tags = generate_word_bio_tags("Berlin", {"city": "Berlin"})
  272. assert tags == ["B-city"]
  273. def test_empty_text(self) -> None:
  274. """Leerer Text erzeugt leere Tag-Liste."""
  275. # split() auf "" ergibt []
  276. tags = generate_word_bio_tags("", {"city": "Berlin"})
  277. assert tags == []
  278. # =========================================================================
  279. # align_bio_to_tokens
  280. # =========================================================================
  281. class TestAlignBioToTokens:
  282. """Tests fuer das Alignment von Wort-BIO-Tags auf Subword-Tokens."""
  283. def test_special_tokens_get_pad(self) -> None:
  284. """Spezial-Tokens ([CLS], [SEP], [PAD]) erhalten PAD-Tag."""
  285. # Simuliert: [CLS] hallo [SEP] [PAD]
  286. # word_ids: None 0 None None
  287. word_bio_tags = ["O"]
  288. tokenizer = MockTokenizer(word_id_list=[None, 0, None, None])
  289. result = align_bio_to_tokens(word_bio_tags, "hallo", tokenizer, max_length=4)
  290. assert result == ["PAD", "O", "PAD", "PAD"]
  291. def test_no_subword_splitting(self) -> None:
  292. """Woerter ohne Subword-Splitting behalten ihren BIO-Tag."""
  293. # "Berlin ist schoen" → keine Splitting
  294. word_bio_tags = ["B-city", "O", "O"]
  295. tokenizer = MockTokenizer(word_id_list=[None, 0, 1, 2, None])
  296. result = align_bio_to_tokens(word_bio_tags, "Berlin ist schoen", tokenizer, max_length=5)
  297. assert result == ["PAD", "B-city", "O", "O", "PAD"]
  298. def test_subword_splitting_b_to_i(self) -> None:
  299. """Subword-Splitting: B-xxx wird zu I-xxx fuer Folge-Subwords."""
  300. # "Wohnzimmer" → ["▁Wohn", "zimmer"] (word_id=0 fuer beide)
  301. word_bio_tags = ["B-room"]
  302. tokenizer = MockTokenizer(word_id_list=[None, 0, 0, None])
  303. result = align_bio_to_tokens(word_bio_tags, "Wohnzimmer", tokenizer, max_length=4)
  304. assert result == ["PAD", "B-room", "I-room", "PAD"]
  305. def test_subword_splitting_i_stays_i(self) -> None:
  306. """Subword-Splitting: I-xxx bleibt I-xxx fuer Folge-Subwords."""
  307. # Zweites Wort eines Slots wird gesplittet
  308. word_bio_tags = ["B-city", "I-city"]
  309. tokenizer = MockTokenizer(word_id_list=[None, 0, 1, 1, None])
  310. result = align_bio_to_tokens(word_bio_tags, "New York", tokenizer, max_length=5)
  311. assert result == ["PAD", "B-city", "I-city", "I-city", "PAD"]
  312. def test_subword_splitting_o_stays_o(self) -> None:
  313. """Subword-Splitting: O bleibt O fuer alle Subwords."""
  314. word_bio_tags = ["O"]
  315. tokenizer = MockTokenizer(word_id_list=[None, 0, 0, 0, None])
  316. result = align_bio_to_tokens(word_bio_tags, "zusammengesetzt", tokenizer, max_length=5)
  317. assert result == ["PAD", "O", "O", "O", "PAD"]
  318. def test_mixed_splitting_and_tags(self) -> None:
  319. """Gemischtes Szenario: Einige Woerter gesplittet, verschiedene Tags."""
  320. # "spiele Wohnzimmer" → ["<s>", "spiel", "e", "Wohn", "zimmer", "</s>"]
  321. # word_ids: None 0 0 1 1 None
  322. word_bio_tags = ["O", "B-room"]
  323. tokenizer = MockTokenizer(word_id_list=[None, 0, 0, 1, 1, None])
  324. result = align_bio_to_tokens(word_bio_tags, "spiele Wohnzimmer", tokenizer, max_length=6)
  325. assert result == ["PAD", "O", "O", "B-room", "I-room", "PAD"]
  326. def test_padding_tokens_at_end(self) -> None:
  327. """Padding-Tokens am Ende erhalten PAD-Tag."""
  328. word_bio_tags = ["O"]
  329. tokenizer = MockTokenizer(word_id_list=[None, 0, None, None, None])
  330. result = align_bio_to_tokens(word_bio_tags, "hallo", tokenizer, max_length=5)
  331. assert result[2:] == ["PAD", "PAD", "PAD"]
  332. def test_word_id_exceeds_bio_tags_length(self) -> None:
  333. """Wenn word_id >= len(word_bio_tags), wird O zurueckgegeben."""
  334. word_bio_tags = ["O"] # Nur ein Wort-Tag
  335. tokenizer = MockTokenizer(word_id_list=[None, 0, 5, None]) # word_id 5 gibt es nicht
  336. result = align_bio_to_tokens(word_bio_tags, "hallo welt", tokenizer, max_length=4)
  337. assert result == ["PAD", "O", "O", "PAD"]
  338. # =========================================================================
  339. # decode_bio_tags
  340. # =========================================================================
  341. class TestDecodeBioTags:
  342. """Tests fuer das Decoding von BIO-Tags zurueck zu Slot-Werten."""
  343. def _make_tagset(self, slot_names: list[str]) -> BIOTagSet:
  344. return BIOTagSet(slot_names=slot_names)
  345. def test_simple_b_slot_extraction(self) -> None:
  346. """Einfacher B-Slot wird korrekt extrahiert."""
  347. tagset = self._make_tagset(["city"])
  348. # Token-IDs: [CLS]=101, spiele=1, in=2, Berlin=3, [SEP]=102
  349. # Tags: PAD, O, O, B-city, PAD
  350. tag_indices = [
  351. tagset.tag_to_idx("PAD"),
  352. tagset.tag_to_idx("O"),
  353. tagset.tag_to_idx("O"),
  354. tagset.tag_to_idx("B-city"),
  355. tagset.tag_to_idx("PAD"),
  356. ]
  357. token_ids = [101, 1, 2, 3, 102]
  358. tokenizer = MockTokenizer(decode_map={(3,): "Berlin"})
  359. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  360. assert result == {"city": "Berlin"}
  361. def test_b_plus_i_continuation(self) -> None:
  362. """B-Slot + I-Slot Fortsetzung ergibt zusammenhaengenden Wert."""
  363. tagset = self._make_tagset(["city"])
  364. tag_indices = [
  365. tagset.tag_to_idx("PAD"),
  366. tagset.tag_to_idx("B-city"),
  367. tagset.tag_to_idx("I-city"),
  368. tagset.tag_to_idx("PAD"),
  369. ]
  370. token_ids = [101, 5, 6, 102]
  371. tokenizer = MockTokenizer(decode_map={(5, 6): "New York"})
  372. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  373. assert result == {"city": "New York"}
  374. def test_multiple_b_same_slot_creates_list(self) -> None:
  375. """Mehrere B-Tags fuer denselben Slot erzeugen eine Liste."""
  376. tagset = self._make_tagset(["topping"])
  377. tag_indices = [
  378. tagset.tag_to_idx("PAD"),
  379. tagset.tag_to_idx("B-topping"),
  380. tagset.tag_to_idx("O"),
  381. tagset.tag_to_idx("B-topping"),
  382. tagset.tag_to_idx("PAD"),
  383. ]
  384. token_ids = [101, 10, 11, 12, 102]
  385. tokenizer = MockTokenizer(decode_map={(10,): "Salami", (12,): "Pilze"})
  386. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  387. assert result == {"topping": ["Salami", "Pilze"]}
  388. def test_orphan_i_tag_ignored(self) -> None:
  389. """I-Tag ohne vorheriges B-Tag wird ignoriert."""
  390. tagset = self._make_tagset(["city"])
  391. tag_indices = [
  392. tagset.tag_to_idx("PAD"),
  393. tagset.tag_to_idx("I-city"), # Orphan — kein B-city davor
  394. tagset.tag_to_idx("O"),
  395. tagset.tag_to_idx("PAD"),
  396. ]
  397. token_ids = [101, 5, 6, 102]
  398. tokenizer = MockTokenizer(decode_map={(5,): "Berlin"})
  399. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  400. assert result == {}
  401. def test_transition_b_city_to_b_date(self) -> None:
  402. """Uebergang B-city → B-date schliesst city ab und startet date."""
  403. tagset = self._make_tagset(["city", "date"])
  404. tag_indices = [
  405. tagset.tag_to_idx("PAD"),
  406. tagset.tag_to_idx("B-city"),
  407. tagset.tag_to_idx("B-date"),
  408. tagset.tag_to_idx("PAD"),
  409. ]
  410. token_ids = [101, 10, 20, 102]
  411. tokenizer = MockTokenizer(decode_map={(10,): "Berlin", (20,): "morgen"})
  412. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  413. assert result == {"city": "Berlin", "date": "morgen"}
  414. def test_all_pad_returns_empty(self) -> None:
  415. """Nur PAD-Tags ergeben leeres Ergebnis."""
  416. tagset = self._make_tagset(["city"])
  417. tag_indices = [tagset.pad_idx] * 4
  418. token_ids = [101, 0, 0, 102]
  419. tokenizer = MockTokenizer()
  420. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  421. assert result == {}
  422. def test_all_o_returns_empty(self) -> None:
  423. """Nur O-Tags ergeben leeres Ergebnis."""
  424. tagset = self._make_tagset(["city"])
  425. tag_indices = [tagset.o_idx] * 4
  426. token_ids = [1, 2, 3, 4]
  427. tokenizer = MockTokenizer()
  428. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  429. assert result == {}
  430. def test_slot_at_end_of_sequence(self) -> None:
  431. """Slot am Ende der Token-Sequenz wird korrekt abgeschlossen."""
  432. tagset = self._make_tagset(["query"])
  433. tag_indices = [
  434. tagset.tag_to_idx("O"),
  435. tagset.tag_to_idx("B-query"),
  436. tagset.tag_to_idx("I-query"),
  437. ]
  438. token_ids = [1, 2, 3]
  439. tokenizer = MockTokenizer(decode_map={(2, 3): "rock musik"})
  440. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  441. assert result == {"query": "rock musik"}
  442. def test_empty_decode_skipped(self) -> None:
  443. """Wenn decode einen leeren String ergibt, wird der Slot uebersprungen."""
  444. tagset = self._make_tagset(["city"])
  445. tag_indices = [
  446. tagset.tag_to_idx("B-city"),
  447. tagset.tag_to_idx("O"),
  448. ]
  449. token_ids = [10, 20]
  450. tokenizer = MockTokenizer(decode_map={(10,): " "}) # Nur Leerzeichen
  451. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  452. assert result == {}
  453. def test_i_tag_wrong_slot_closes_current(self) -> None:
  454. """I-Tag fuer falschen Slot schliesst den aktuellen Slot ab."""
  455. tagset = self._make_tagset(["city", "date"])
  456. tag_indices = [
  457. tagset.tag_to_idx("B-city"),
  458. tagset.tag_to_idx("I-date"), # Falscher Slot — schliesst city ab
  459. tagset.tag_to_idx("O"),
  460. ]
  461. token_ids = [10, 20, 30]
  462. tokenizer = MockTokenizer(decode_map={(10,): "Berlin"})
  463. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  464. assert result == {"city": "Berlin"}
  465. def test_long_continuation_b_i_i_i(self) -> None:
  466. """Langer Slot mit B + mehreren I-Tags."""
  467. tagset = self._make_tagset(["artist"])
  468. tag_indices = [
  469. tagset.tag_to_idx("PAD"),
  470. tagset.tag_to_idx("B-artist"),
  471. tagset.tag_to_idx("I-artist"),
  472. tagset.tag_to_idx("I-artist"),
  473. tagset.tag_to_idx("PAD"),
  474. ]
  475. token_ids = [101, 5, 6, 7, 102]
  476. tokenizer = MockTokenizer(decode_map={(5, 6, 7): "Die Toten Hosen"})
  477. result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer)
  478. assert result == {"artist": "Die Toten Hosen"}