feat(archivar): Selbstlernendes Keyword-Gewicht-System (Teil 2)
- KeywordWeightEntry + ManualOverride Dataclasses in archivar_state.py - Lernalgorithmus: confirm (+0.1), stay (-0.05), never (0.0+sticky) - Promotion: 3 confirmations + weight ≥0.85 → keywords_100 - Degradation + zeitbasierte Abwertung (Decay: 30d -10%, 90d -30%) - Cold-Start: Bootstrap Tag 1-7 (LR=0.2), Tag 8+ (LR=0.1) - Gewichtetes Scoring in find_room_by_keywords() - Feedback-Schleife in adapter_integration.py nach Move-Request-Auflösung - 54 Tests grün (inkl. 8 neue für gewichtetes Scoring)
This commit is contained in:
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
Tests für das selbstlernende Keyword-Gewicht-System.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from archivar_state import ArchivarState, KeywordWeightEntry, ManualOverride
|
||||
|
||||
|
||||
class TestArchivarStateKeywordWeights(unittest.TestCase):
|
||||
"""Tests für das selbstlernende Keyword-Gewicht-System."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
# Create a temporary file for the state
|
||||
self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json')
|
||||
self.temp_file.close()
|
||||
self.state_file_path = self.temp_file.name
|
||||
self.state = ArchivarState(self.state_file_path)
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up test fixtures."""
|
||||
# Remove the temporary file
|
||||
if os.path.exists(self.state_file_path):
|
||||
os.unlink(self.state_file_path)
|
||||
|
||||
def test_keyword_weight_entry_serialization(self):
|
||||
"""Test serialization of KeywordWeightEntry."""
|
||||
# Create a KeywordWeightEntry
|
||||
now = datetime.now().isoformat()
|
||||
entry = KeywordWeightEntry(
|
||||
weight=0.75,
|
||||
last_updated=now,
|
||||
confirmation_count=3,
|
||||
rejection_count=1,
|
||||
last_confirmation=now
|
||||
)
|
||||
|
||||
# Create an ArchivarState and add the entry
|
||||
self.state._keyword_weights = {
|
||||
"test_keyword": {
|
||||
"room1": entry
|
||||
}
|
||||
}
|
||||
|
||||
# Save and reload
|
||||
self.assertTrue(self.state.save())
|
||||
new_state = ArchivarState(self.state_file_path)
|
||||
self.assertTrue(new_state.load())
|
||||
|
||||
# Check that the entry was loaded correctly
|
||||
self.assertIn("test_keyword", new_state._keyword_weights)
|
||||
self.assertIn("room1", new_state._keyword_weights["test_keyword"])
|
||||
loaded_entry = new_state._keyword_weights["test_keyword"]["room1"]
|
||||
self.assertEqual(loaded_entry.weight, 0.75)
|
||||
self.assertEqual(loaded_entry.confirmation_count, 3)
|
||||
self.assertEqual(loaded_entry.rejection_count, 1)
|
||||
self.assertEqual(loaded_entry.last_updated, now)
|
||||
self.assertEqual(loaded_entry.last_confirmation, now)
|
||||
|
||||
def test_manual_override_serialization(self):
|
||||
"""Test serialization of ManualOverride."""
|
||||
# Create a ManualOverride
|
||||
now = datetime.now().isoformat()
|
||||
override = ManualOverride(
|
||||
override_weight=0.9,
|
||||
override_reason="Manual adjustment by admin",
|
||||
override_date=now,
|
||||
override_by="admin_user"
|
||||
)
|
||||
|
||||
# Create an ArchivarState and add the override
|
||||
self.state._manual_overrides = {
|
||||
"test_keyword": {
|
||||
"room1": override
|
||||
}
|
||||
}
|
||||
|
||||
# Save and reload
|
||||
self.assertTrue(self.state.save())
|
||||
new_state = ArchivarState(self.state_file_path)
|
||||
self.assertTrue(new_state.load())
|
||||
|
||||
# Check that the override was loaded correctly
|
||||
self.assertIn("test_keyword", new_state._manual_overrides)
|
||||
self.assertIn("room1", new_state._manual_overrides["test_keyword"])
|
||||
loaded_override = new_state._manual_overrides["test_keyword"]["room1"]
|
||||
self.assertEqual(loaded_override.override_weight, 0.9)
|
||||
self.assertEqual(loaded_override.override_reason, "Manual adjustment by admin")
|
||||
self.assertEqual(loaded_override.override_date, now)
|
||||
self.assertEqual(loaded_override.override_by, "admin_user")
|
||||
|
||||
def test_update_keyword_weight_confirm(self):
|
||||
"""Test updating keyword weight with confirm feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
),
|
||||
"room2": KeywordWeightEntry(
|
||||
weight=0.3,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=0,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply confirm feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "confirm")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was updated correctly
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
# With learning rate 0.2: new_weight = 0.5 + (1 - 0.5) * 0.2 = 0.6
|
||||
self.assertAlmostEqual(entry.weight, 0.6, places=2)
|
||||
self.assertEqual(entry.confirmation_count, 2)
|
||||
|
||||
# Check that other room weights were reduced
|
||||
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
||||
# With learning rate 0.2: reduced_weight = 0.3 - (0.3 * 0.2 / 1) = 0.24
|
||||
self.assertAlmostEqual(other_entry.weight, 0.24, places=2)
|
||||
|
||||
def test_update_keyword_weight_stay(self):
|
||||
"""Test updating keyword weight with stay feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
),
|
||||
"room2": KeywordWeightEntry(
|
||||
weight=0.3,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=0,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply stay feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "stay")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was updated correctly
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
# With learning rate 0.2: new_weight = 0.5 - 0.5 * 0.2 * 0.5 = 0.45
|
||||
self.assertAlmostEqual(entry.weight, 0.45, places=2)
|
||||
self.assertEqual(entry.rejection_count, 1)
|
||||
|
||||
# Check that other room weights were increased
|
||||
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
||||
# With learning rate 0.2: increased_weight = 0.3 + ((1 - 0.3) * 0.2 * 0.5 / 1) = 0.37
|
||||
self.assertAlmostEqual(other_entry.weight, 0.37, places=2)
|
||||
|
||||
def test_update_keyword_weight_never(self):
|
||||
"""Test updating keyword weight with never feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply never feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "never")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was set to 0.0
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertEqual(entry.weight, 0.0)
|
||||
self.assertEqual(entry.rejection_count, 2) # Counts as 2 negative confirmations
|
||||
|
||||
# Check that the keyword was added to sticky_keywords
|
||||
self.assertIn("plugin", self.state._sticky_keywords)
|
||||
self.assertIn("room1", self.state._sticky_keywords["plugin"])
|
||||
|
||||
def test_calculate_room_score_with_override(self):
|
||||
"""Test calculating room score with manual override."""
|
||||
# Set up a manual override
|
||||
now = datetime.now().isoformat()
|
||||
self.state._manual_overrides = {
|
||||
"plugin": {
|
||||
"room1": ManualOverride(
|
||||
override_weight=0.9,
|
||||
override_reason="Manual adjustment",
|
||||
override_date=now,
|
||||
override_by="admin"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Calculate score - should use override
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.9)
|
||||
|
||||
def test_calculate_room_score_with_sticky(self):
|
||||
"""Test calculating room score with sticky keyword."""
|
||||
# Set up a sticky keyword
|
||||
self.state._sticky_keywords = {
|
||||
"plugin": ["room1"]
|
||||
}
|
||||
|
||||
# Calculate score - should be 0.0
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.0)
|
||||
|
||||
def test_calculate_room_score_with_learned_weight(self):
|
||||
"""Test calculating room score with learned weight."""
|
||||
# Set up a learned weight
|
||||
now = datetime.now().isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.7,
|
||||
last_updated=now,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Calculate score - should use learned weight
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.7)
|
||||
|
||||
def test_check_promotion_eligibility(self):
|
||||
"""Test checking promotion eligibility."""
|
||||
# Set up a promotable keyword
|
||||
now = datetime.now().isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.9,
|
||||
last_updated=now,
|
||||
confirmation_count=3,
|
||||
rejection_count=0,
|
||||
last_confirmation=now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Check promotion eligibility
|
||||
result = self.state.check_promotion_eligibility("plugin", "room1")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that it was added to promotion candidates
|
||||
self.assertIn("plugin", self.state._promotion_candidates)
|
||||
self.assertIn("room1", self.state._promotion_candidates["plugin"])
|
||||
|
||||
def test_apply_decay(self):
|
||||
"""Test applying time-based decay."""
|
||||
# Set up a keyword weight with old last_updated date (45 days ago)
|
||||
old_date = (datetime.now() - timedelta(days=45)).isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.8,
|
||||
last_updated=old_date,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=old_date
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply decay
|
||||
result = self.state.apply_decay()
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was reduced (45 days is between 30 and 90 days,
|
||||
# so it should be reduced by 10%)
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertAlmostEqual(entry.weight, 0.8 * 0.9, places=2) # 0.72
|
||||
|
||||
# Test 90-day decay
|
||||
very_old_date = (datetime.now() - timedelta(days=95)).isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.8,
|
||||
last_updated=very_old_date,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=very_old_date
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply decay
|
||||
result = self.state.apply_decay()
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was reduced by 30% (90 days = 30% reduction)
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertAlmostEqual(entry.weight, 0.8 * 0.7, places=2) # 0.56
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
Tests für das gewichtete Scoring im RoomMap-Modul.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
class TestRoomMapWeightedScoring(unittest.TestCase):
|
||||
"""Tests für das gewichtete Scoring im RoomMap-Modul."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
# Create test rooms
|
||||
self.rooms = {
|
||||
"room1": RoomEntry(
|
||||
room_id="room1",
|
||||
name="#Plugin-Development",
|
||||
theme="Plugin development and bug fixes",
|
||||
keywords_100=["bug", "fix", "issue"],
|
||||
keywords_context=["plugin", "feature", "development"]
|
||||
),
|
||||
"room2": RoomEntry(
|
||||
room_id="room2",
|
||||
name="#Documentation",
|
||||
theme="Documentation and user guides",
|
||||
keywords_100=["doc", "document", "guide"],
|
||||
keywords_context=["documentation", "manual", "tutorial"]
|
||||
),
|
||||
"room3": RoomEntry(
|
||||
room_id="room3",
|
||||
name="#General",
|
||||
theme="General discussion",
|
||||
keywords_100=[],
|
||||
keywords_context=["general", "discussion", "chat"],
|
||||
catch_all=True
|
||||
)
|
||||
}
|
||||
|
||||
# Create a RoomMap instance
|
||||
self.room_map = RoomMap(
|
||||
rooms=self.rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2
|
||||
)
|
||||
|
||||
def test_calculate_weighted_score(self):
|
||||
"""Test calculating weighted scores."""
|
||||
# Get a room entry
|
||||
room = self.rooms["room1"]
|
||||
|
||||
# Test with text that matches some keywords
|
||||
text = "I need help with plugin development"
|
||||
score = self.room_map.calculate_weighted_score(text, room)
|
||||
|
||||
# Should match "plugin" and "development" -> 2 out of 3 keywords = 0.6667
|
||||
self.assertAlmostEqual(score, 2/3, places=2)
|
||||
|
||||
def test_find_room_by_keywords_with_100_percent_match(self):
|
||||
"""Test finding room with 100% keyword match."""
|
||||
# Text with a 100% match keyword
|
||||
text = "There is a bug in the plugin"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should find room1 because it has "bug" in keywords_100
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_with_context_match(self):
|
||||
"""Test finding room with context keyword match."""
|
||||
# Text with context keyword match
|
||||
text = "I'm working on plugin development"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should find room1 because it has "plugin" and "development" in keywords_context
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_with_origin_priority(self):
|
||||
"""Test finding room with origin room priority."""
|
||||
# Text with context keyword match
|
||||
text = "I'm working on plugin development"
|
||||
|
||||
# When origin_room_id is set to room2, it should still find room1
|
||||
# because 100% keywords take precedence
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text, origin_room_id="room2")
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
# Text without 100% match but with context match
|
||||
text2 = "plugin development discussion"
|
||||
room = self.room_map.find_room_by_keywords(text2, origin_room_id="room2")
|
||||
|
||||
# Should find room1 because it has better context match
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_no_match(self):
|
||||
"""Test finding room with no keyword matches."""
|
||||
# Text with no matching keywords
|
||||
text = "completely unrelated topic"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should not find any room
|
||||
self.assertIsNone(room)
|
||||
|
||||
def test_find_room_by_keywords_min_score(self):
|
||||
"""Test finding room with minimum score requirement."""
|
||||
# Text with only one context keyword match
|
||||
text = "plugin unrelated stuff"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text, min_score=2)
|
||||
|
||||
# Should not find any room because score is only 1 (below min_score of 2)
|
||||
self.assertIsNone(room)
|
||||
|
||||
# Same text with lower min_score
|
||||
room = self.room_map.find_room_by_keywords(text, min_score=1)
|
||||
|
||||
# Should find room1 because score is 1 (meets min_score of 1)
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user