# -*- coding: utf-8 -*- """ Tests fuer den BIO-Tagger (Slot-Extraktion). Testet BIOTagSet, generate_word_bio_tags, align_bio_to_tokens und decode_bio_tags. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any from unittest.mock import MagicMock import pytest from trixy_core.trainer.core.intent.bio_tagger import ( BIOTagSet, align_bio_to_tokens, decode_bio_tags, generate_word_bio_tags, ) # ========================================================================= # Hilfsfunktionen und Mock-Tokenizer # ========================================================================= class MockEncoding: """Simuliert ein HuggingFace Encoding-Objekt mit word_ids().""" def __init__(self, word_id_list: list[int | None]) -> None: self._word_ids = word_id_list def word_ids(self) -> list[int | None]: return self._word_ids class MockTokenizer: """ Mock-Tokenizer der word_ids und decode unterstuetzt. Konfiguration ueber Konstruktor-Parameter. """ def __init__( self, word_id_list: list[int | None] | None = None, decode_map: dict[tuple[int, ...], str] | None = None, ) -> None: self._word_id_list = word_id_list or [] self._decode_map = decode_map or {} def __call__(self, text: str, **kwargs: Any) -> MockEncoding: return MockEncoding(self._word_id_list) def decode(self, token_ids: list[int], skip_special_tokens: bool = True) -> str: """Gibt den decodierten Text fuer die Token-IDs zurueck.""" key = tuple(token_ids) if key in self._decode_map: return self._decode_map[key] # Fallback: IDs als String zusammenfuegen return " ".join(str(t) for t in token_ids) # ========================================================================= # BIOTagSet — Konstruktion und Grundlagen # ========================================================================= class TestBIOTagSetConstruction: """Tests fuer die Erstellung eines BIOTagSet.""" def test_construction_with_slots(self) -> None: """BIOTagSet mit Slots erstellt korrekte Tags.""" tagset = BIOTagSet(slot_names=["city", "date"]) assert tagset.num_tags == 6 # O, PAD, B-city, I-city, B-date, I-date def test_tag_ordering(self) -> None: """Tags werden in korrekter Reihenfolge erstellt: O, PAD, dann B/I sortiert.""" tagset = BIOTagSet(slot_names=["query", "city"]) tags = tagset.tags assert tags[0] == "O" assert tags[1] == "PAD" # Sortiert: city vor query assert tags[2] == "B-city" assert tags[3] == "I-city" assert tags[4] == "B-query" assert tags[5] == "I-query" def test_num_tags_formula(self) -> None: """num_tags = 2 + 2 * len(slot_names).""" for n in range(0, 6): slots = [f"slot_{i}" for i in range(n)] tagset = BIOTagSet(slot_names=slots) assert tagset.num_tags == 2 + 2 * n def test_empty_slots(self) -> None: """BIOTagSet ohne Slots hat nur O und PAD.""" tagset = BIOTagSet(slot_names=[]) assert tagset.num_tags == 2 assert tagset.tags == ["O", "PAD"] def test_single_slot(self) -> None: """BIOTagSet mit einem Slot hat 4 Tags.""" tagset = BIOTagSet(slot_names=["room"]) assert tagset.num_tags == 4 assert "B-room" in tagset.tags assert "I-room" in tagset.tags def test_slots_sorted_alphabetically(self) -> None: """Slot-Tags werden alphabetisch nach Slot-Name sortiert.""" tagset = BIOTagSet(slot_names=["zoo", "alpha", "middle"]) tags = tagset.tags # alpha kommt vor middle kommt vor zoo alpha_idx = tags.index("B-alpha") middle_idx = tags.index("B-middle") zoo_idx = tags.index("B-zoo") assert alpha_idx < middle_idx < zoo_idx class TestBIOTagSetIndices: """Tests fuer Index-Zugriffe auf BIOTagSet.""" def test_o_idx(self) -> None: """O-Index ist immer 0.""" tagset = BIOTagSet(slot_names=["city"]) assert tagset.o_idx == 0 def test_pad_idx(self) -> None: """PAD-Index ist immer 1.""" tagset = BIOTagSet(slot_names=["city"]) assert tagset.pad_idx == 1 def test_tag_to_idx_known(self) -> None: """Bekannte Tags geben korrekten Index zurueck.""" tagset = BIOTagSet(slot_names=["city"]) assert tagset.tag_to_idx("O") == 0 assert tagset.tag_to_idx("PAD") == 1 assert tagset.tag_to_idx("B-city") == 2 assert tagset.tag_to_idx("I-city") == 3 def test_tag_to_idx_unknown_returns_o_idx(self) -> None: """Unbekannte Tags geben O-Index (0) zurueck.""" tagset = BIOTagSet(slot_names=["city"]) assert tagset.tag_to_idx("B-unknown") == tagset.o_idx def test_idx_to_tag_known(self) -> None: """Bekannte Indizes geben korrekten Tag-Namen zurueck.""" tagset = BIOTagSet(slot_names=["query"]) assert tagset.idx_to_tag(0) == "O" assert tagset.idx_to_tag(1) == "PAD" def test_idx_to_tag_unknown_returns_o(self) -> None: """Unbekannte Indizes geben 'O' zurueck.""" tagset = BIOTagSet(slot_names=["city"]) assert tagset.idx_to_tag(999) == "O" def test_roundtrip_tag_to_idx_to_tag(self) -> None: """tag_to_idx und idx_to_tag sind inverse Operationen.""" tagset = BIOTagSet(slot_names=["city", "date", "query"]) for tag in tagset.tags: idx = tagset.tag_to_idx(tag) assert tagset.idx_to_tag(idx) == tag def test_roundtrip_idx_to_tag_to_idx(self) -> None: """idx_to_tag und tag_to_idx sind inverse Operationen.""" tagset = BIOTagSet(slot_names=["room", "status"]) for i in range(tagset.num_tags): tag = tagset.idx_to_tag(i) assert tagset.tag_to_idx(tag) == i class TestBIOTagSetSerialization: """Tests fuer to_dict / from_dict Serialisierung.""" def test_to_dict_contains_all_tags(self) -> None: """to_dict enthaelt alle Tags mit korrekten Indizes.""" tagset = BIOTagSet(slot_names=["city", "date"]) d = tagset.to_dict() assert d["O"] == 0 assert d["PAD"] == 1 assert "B-city" in d assert "I-city" in d assert "B-date" in d assert "I-date" in d assert len(d) == 6 def test_from_dict_reconstructs(self) -> None: """from_dict rekonstruiert ein identisches BIOTagSet.""" original = BIOTagSet(slot_names=["city", "date"]) d = original.to_dict() reconstructed = BIOTagSet.from_dict(d) assert reconstructed.to_dict() == d def test_from_dict_extracts_slot_names(self) -> None: """from_dict extrahiert Slot-Namen aus B- Tags.""" d = {"O": 0, "PAD": 1, "B-room": 2, "I-room": 3, "B-status": 4, "I-status": 5} tagset = BIOTagSet.from_dict(d) assert sorted(tagset.slot_names) == ["room", "status"] def test_roundtrip_empty_slots(self) -> None: """Roundtrip mit leeren Slots funktioniert.""" original = BIOTagSet(slot_names=[]) d = original.to_dict() reconstructed = BIOTagSet.from_dict(d) assert reconstructed.num_tags == 2 assert reconstructed.tags == ["O", "PAD"] def test_from_dict_ignores_extra_keys(self) -> None: """from_dict ignoriert Tags die nicht B- sind (ausser O/PAD).""" d = {"O": 0, "PAD": 1, "B-city": 2, "I-city": 3, "CUSTOM": 99} tagset = BIOTagSet.from_dict(d) # Nur city als Slot erkannt assert tagset.slot_names == ["city"] # ========================================================================= # generate_word_bio_tags # ========================================================================= class TestGenerateWordBioTags: """Tests fuer die Wort-Level BIO-Tag Generierung.""" def test_single_slot_at_end(self) -> None: """Einzelner Slot am Satzende.""" tags = generate_word_bio_tags( "Wie wird das Wetter in Berlin", {"city": "Berlin"}, ) assert tags == ["O", "O", "O", "O", "O", "B-city"] def test_single_slot_at_beginning(self) -> None: """Slot am Satzanfang.""" tags = generate_word_bio_tags( "Berlin hat gutes Wetter", {"city": "Berlin"}, ) assert tags == ["B-city", "O", "O", "O"] def test_single_slot_in_middle(self) -> None: """Slot in der Satzmitte.""" tags = generate_word_bio_tags( "das Wetter in Berlin ist gut", {"city": "Berlin"}, ) assert tags == ["O", "O", "O", "B-city", "O", "O"] def test_multi_word_slot(self) -> None: """Mehrwort-Slot erzeugt B- und I- Tags.""" tags = generate_word_bio_tags( "Wie ist das Wetter in New York", {"city": "New York"}, ) assert tags == ["O", "O", "O", "O", "O", "B-city", "I-city"] def test_three_word_slot(self) -> None: """Dreiwort-Slot erzeugt B-I-I.""" tags = generate_word_bio_tags( "spiele songs von Die Toten Hosen", {"artist": "Die Toten Hosen"}, ) assert tags == ["O", "O", "O", "B-artist", "I-artist", "I-artist"] def test_multi_value_slot(self) -> None: """Slot mit mehreren Werten (Liste) erzeugt mehrere B- Tags.""" tags = generate_word_bio_tags( "ich haette gerne Salami und Pilze", {"topping": ["Salami", "Pilze"]}, ) assert tags == ["O", "O", "O", "B-topping", "O", "B-topping"] def test_multiple_different_slots(self) -> None: """Mehrere verschiedene Slots im selben Satz.""" # Woerter: ["Wie", "wird", "das", "Wetter", "morgen", "in", "Berlin"] # 0 1 2 3 4 5 6 tags = generate_word_bio_tags( "Wie wird das Wetter morgen in Berlin", {"city": "Berlin", "date": "morgen"}, ) assert tags[4] == "B-date" # morgen (Index 4) assert tags[5] == "O" # in assert tags[6] == "B-city" # Berlin (letztes Wort) def test_empty_slots(self) -> None: """Leere Slots erzeugen nur O-Tags.""" tags = generate_word_bio_tags("Hallo wie geht es dir", {}) assert tags == ["O", "O", "O", "O", "O"] def test_no_match_found(self) -> None: """Slot-Wert der nicht im Text vorkommt erzeugt nur O-Tags.""" tags = generate_word_bio_tags( "Hallo wie geht es", {"city": "Berlin"}, ) assert tags == ["O", "O", "O", "O"] def test_case_insensitive_matching(self) -> None: """Wort-Matching ist case-insensitive.""" tags = generate_word_bio_tags( "spiele musik von RAMMSTEIN", {"artist": "rammstein"}, ) assert tags == ["O", "O", "O", "B-artist"] def test_case_insensitive_slot_upper(self) -> None: """Slot-Wert in Grossbuchstaben matcht Kleinschreibung im Text.""" tags = generate_word_bio_tags( "mach das licht im wohnzimmer an", {"room": "Wohnzimmer"}, ) assert tags[4] == "B-room" def test_punctuation_handling(self) -> None: """Interpunktion wird beim Matching ignoriert (z.B. 'Berlin,' matcht 'Berlin').""" tags = generate_word_bio_tags( "Wie ist das Wetter in Berlin, heute", {"city": "Berlin"}, ) assert tags == ["O", "O", "O", "O", "O", "B-city", "O"] def test_punctuation_exclamation(self) -> None: """Ausrufezeichen wird beim Matching ignoriert.""" tags = generate_word_bio_tags( "Stoppe die Musik!", {"action": "Musik"}, ) assert tags == ["O", "O", "B-action"] def test_single_word_text(self) -> None: """Einwort-Text mit Slot-Match.""" tags = generate_word_bio_tags("Berlin", {"city": "Berlin"}) assert tags == ["B-city"] def test_empty_text(self) -> None: """Leerer Text erzeugt leere Tag-Liste.""" # split() auf "" ergibt [] tags = generate_word_bio_tags("", {"city": "Berlin"}) assert tags == [] # ========================================================================= # align_bio_to_tokens # ========================================================================= class TestAlignBioToTokens: """Tests fuer das Alignment von Wort-BIO-Tags auf Subword-Tokens.""" def test_special_tokens_get_pad(self) -> None: """Spezial-Tokens ([CLS], [SEP], [PAD]) erhalten PAD-Tag.""" # Simuliert: [CLS] hallo [SEP] [PAD] # word_ids: None 0 None None word_bio_tags = ["O"] tokenizer = MockTokenizer(word_id_list=[None, 0, None, None]) result = align_bio_to_tokens(word_bio_tags, "hallo", tokenizer, max_length=4) assert result == ["PAD", "O", "PAD", "PAD"] def test_no_subword_splitting(self) -> None: """Woerter ohne Subword-Splitting behalten ihren BIO-Tag.""" # "Berlin ist schoen" → keine Splitting word_bio_tags = ["B-city", "O", "O"] tokenizer = MockTokenizer(word_id_list=[None, 0, 1, 2, None]) result = align_bio_to_tokens(word_bio_tags, "Berlin ist schoen", tokenizer, max_length=5) assert result == ["PAD", "B-city", "O", "O", "PAD"] def test_subword_splitting_b_to_i(self) -> None: """Subword-Splitting: B-xxx wird zu I-xxx fuer Folge-Subwords.""" # "Wohnzimmer" → ["▁Wohn", "zimmer"] (word_id=0 fuer beide) word_bio_tags = ["B-room"] tokenizer = MockTokenizer(word_id_list=[None, 0, 0, None]) result = align_bio_to_tokens(word_bio_tags, "Wohnzimmer", tokenizer, max_length=4) assert result == ["PAD", "B-room", "I-room", "PAD"] def test_subword_splitting_i_stays_i(self) -> None: """Subword-Splitting: I-xxx bleibt I-xxx fuer Folge-Subwords.""" # Zweites Wort eines Slots wird gesplittet word_bio_tags = ["B-city", "I-city"] tokenizer = MockTokenizer(word_id_list=[None, 0, 1, 1, None]) result = align_bio_to_tokens(word_bio_tags, "New York", tokenizer, max_length=5) assert result == ["PAD", "B-city", "I-city", "I-city", "PAD"] def test_subword_splitting_o_stays_o(self) -> None: """Subword-Splitting: O bleibt O fuer alle Subwords.""" word_bio_tags = ["O"] tokenizer = MockTokenizer(word_id_list=[None, 0, 0, 0, None]) result = align_bio_to_tokens(word_bio_tags, "zusammengesetzt", tokenizer, max_length=5) assert result == ["PAD", "O", "O", "O", "PAD"] def test_mixed_splitting_and_tags(self) -> None: """Gemischtes Szenario: Einige Woerter gesplittet, verschiedene Tags.""" # "spiele Wohnzimmer" → ["", "spiel", "e", "Wohn", "zimmer", ""] # word_ids: None 0 0 1 1 None word_bio_tags = ["O", "B-room"] tokenizer = MockTokenizer(word_id_list=[None, 0, 0, 1, 1, None]) result = align_bio_to_tokens(word_bio_tags, "spiele Wohnzimmer", tokenizer, max_length=6) assert result == ["PAD", "O", "O", "B-room", "I-room", "PAD"] def test_padding_tokens_at_end(self) -> None: """Padding-Tokens am Ende erhalten PAD-Tag.""" word_bio_tags = ["O"] tokenizer = MockTokenizer(word_id_list=[None, 0, None, None, None]) result = align_bio_to_tokens(word_bio_tags, "hallo", tokenizer, max_length=5) assert result[2:] == ["PAD", "PAD", "PAD"] def test_word_id_exceeds_bio_tags_length(self) -> None: """Wenn word_id >= len(word_bio_tags), wird O zurueckgegeben.""" word_bio_tags = ["O"] # Nur ein Wort-Tag tokenizer = MockTokenizer(word_id_list=[None, 0, 5, None]) # word_id 5 gibt es nicht result = align_bio_to_tokens(word_bio_tags, "hallo welt", tokenizer, max_length=4) assert result == ["PAD", "O", "O", "PAD"] # ========================================================================= # decode_bio_tags # ========================================================================= class TestDecodeBioTags: """Tests fuer das Decoding von BIO-Tags zurueck zu Slot-Werten.""" def _make_tagset(self, slot_names: list[str]) -> BIOTagSet: return BIOTagSet(slot_names=slot_names) def test_simple_b_slot_extraction(self) -> None: """Einfacher B-Slot wird korrekt extrahiert.""" tagset = self._make_tagset(["city"]) # Token-IDs: [CLS]=101, spiele=1, in=2, Berlin=3, [SEP]=102 # Tags: PAD, O, O, B-city, PAD tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("O"), tagset.tag_to_idx("O"), tagset.tag_to_idx("B-city"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 1, 2, 3, 102] tokenizer = MockTokenizer(decode_map={(3,): "Berlin"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"city": "Berlin"} def test_b_plus_i_continuation(self) -> None: """B-Slot + I-Slot Fortsetzung ergibt zusammenhaengenden Wert.""" tagset = self._make_tagset(["city"]) tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("B-city"), tagset.tag_to_idx("I-city"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 5, 6, 102] tokenizer = MockTokenizer(decode_map={(5, 6): "New York"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"city": "New York"} def test_multiple_b_same_slot_creates_list(self) -> None: """Mehrere B-Tags fuer denselben Slot erzeugen eine Liste.""" tagset = self._make_tagset(["topping"]) tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("B-topping"), tagset.tag_to_idx("O"), tagset.tag_to_idx("B-topping"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 10, 11, 12, 102] tokenizer = MockTokenizer(decode_map={(10,): "Salami", (12,): "Pilze"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"topping": ["Salami", "Pilze"]} def test_orphan_i_tag_ignored(self) -> None: """I-Tag ohne vorheriges B-Tag wird ignoriert.""" tagset = self._make_tagset(["city"]) tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("I-city"), # Orphan — kein B-city davor tagset.tag_to_idx("O"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 5, 6, 102] tokenizer = MockTokenizer(decode_map={(5,): "Berlin"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {} def test_transition_b_city_to_b_date(self) -> None: """Uebergang B-city → B-date schliesst city ab und startet date.""" tagset = self._make_tagset(["city", "date"]) tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("B-city"), tagset.tag_to_idx("B-date"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 10, 20, 102] tokenizer = MockTokenizer(decode_map={(10,): "Berlin", (20,): "morgen"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"city": "Berlin", "date": "morgen"} def test_all_pad_returns_empty(self) -> None: """Nur PAD-Tags ergeben leeres Ergebnis.""" tagset = self._make_tagset(["city"]) tag_indices = [tagset.pad_idx] * 4 token_ids = [101, 0, 0, 102] tokenizer = MockTokenizer() result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {} def test_all_o_returns_empty(self) -> None: """Nur O-Tags ergeben leeres Ergebnis.""" tagset = self._make_tagset(["city"]) tag_indices = [tagset.o_idx] * 4 token_ids = [1, 2, 3, 4] tokenizer = MockTokenizer() result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {} def test_slot_at_end_of_sequence(self) -> None: """Slot am Ende der Token-Sequenz wird korrekt abgeschlossen.""" tagset = self._make_tagset(["query"]) tag_indices = [ tagset.tag_to_idx("O"), tagset.tag_to_idx("B-query"), tagset.tag_to_idx("I-query"), ] token_ids = [1, 2, 3] tokenizer = MockTokenizer(decode_map={(2, 3): "rock musik"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"query": "rock musik"} def test_empty_decode_skipped(self) -> None: """Wenn decode einen leeren String ergibt, wird der Slot uebersprungen.""" tagset = self._make_tagset(["city"]) tag_indices = [ tagset.tag_to_idx("B-city"), tagset.tag_to_idx("O"), ] token_ids = [10, 20] tokenizer = MockTokenizer(decode_map={(10,): " "}) # Nur Leerzeichen result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {} def test_i_tag_wrong_slot_closes_current(self) -> None: """I-Tag fuer falschen Slot schliesst den aktuellen Slot ab.""" tagset = self._make_tagset(["city", "date"]) tag_indices = [ tagset.tag_to_idx("B-city"), tagset.tag_to_idx("I-date"), # Falscher Slot — schliesst city ab tagset.tag_to_idx("O"), ] token_ids = [10, 20, 30] tokenizer = MockTokenizer(decode_map={(10,): "Berlin"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"city": "Berlin"} def test_long_continuation_b_i_i_i(self) -> None: """Langer Slot mit B + mehreren I-Tags.""" tagset = self._make_tagset(["artist"]) tag_indices = [ tagset.tag_to_idx("PAD"), tagset.tag_to_idx("B-artist"), tagset.tag_to_idx("I-artist"), tagset.tag_to_idx("I-artist"), tagset.tag_to_idx("PAD"), ] token_ids = [101, 5, 6, 7, 102] tokenizer = MockTokenizer(decode_map={(5, 6, 7): "Die Toten Hosen"}) result = decode_bio_tags(tag_indices, token_ids, tagset, tokenizer) assert result == {"artist": "Die Toten Hosen"}