Home Information - Your home, your data, organized.
Python
HomeBox: keyword-driven EntityType heuristic (#365)
Tony C0a32fa57f246
diff --git a/src/hi/services/homebox/hb_converter.py b/src/hi/services/homebox/hb_converter.pyindex 2799f052..23b1a2dc 100644--- a/src/hi/services/homebox/hb_converter.py+++ b/src/hi/services/homebox/hb_converter.py@@ -1,6 +1,7 @@from typing import Dict, List, Optionalimport mimetypesimport os+import refrom django.core.files.base import ContentFile@@ -34,6 +35,144 @@ HB_ITEM_FIELD_PAIRS = []+# Keyword → EntityType map for heuristic type assignment of HomeBox+# items. Authoring order does not matter — ``_KEYWORD_PATTERNS`` below+# pre-sorts by specificity (word count descending, then char length+# descending, then alphabetical). Multi-word keywords always win over+# single-word matches; longer keywords win over shorter at equal word+# count.+#+# Add keywords liberally as real-world data accumulates. The+# false-positive risk is small as long as keywords are nouns naming+# the kind of thing (not adjectives or verbs).+HB_KEYWORD_ENTITY_TYPE_MAP = [+ # Multi-word patterns.+ ( 'access point', EntityType.ACCESS_POINT ),+ ( 'attic stairs', EntityType.ATTIC_STAIRS ),+ ( 'av receiver', EntityType.AV_RECEIVER ),+ ( 'battery storage', EntityType.BATTERY_STORAGE ),+ ( 'carbon monoxide', EntityType.CARBON_MONOXIDE_DETECTOR ),+ ( 'ceiling fan', EntityType.CEILING_FAN ),+ ( 'clothes dryer', EntityType.CLOTHES_DRYER ),+ ( 'clothes washer', EntityType.CLOTHES_WASHER ),+ ( 'coffee machine', EntityType.COFFEE_MAKER ),+ ( 'coffee maker', EntityType.COFFEE_MAKER ),+ ( 'door lock', EntityType.DOOR_LOCK ),+ ( 'electric meter', EntityType.ELECTRICITY_METER ),+ ( 'electric panel', EntityType.ELECTRIC_PANEL ),+ ( 'electrical outlet', EntityType.ELECTRICAL_OUTLET ),+ ( 'ev charger', EntityType.EV_CHARGER ),+ ( 'exhaust fan', EntityType.EXHAUST_FAN ),+ ( 'fire extinguisher', EntityType.FIRE_EXTINGUISHER ),+ ( 'garage door', EntityType.GARAGE_DOOR ),+ ( 'garbage disposal', EntityType.GARBAGE_DISPOSAL ),+ ( 'gas detector', EntityType.GAS_DETECTOR ),+ ( 'gas meter', EntityType.GAS_METER ),+ ( 'hedge trimmer', EntityType.HEDGE_TRIMMER ),+ ( 'lawn mower', EntityType.LAWN_MOWER ),+ ( 'leaf blower', EntityType.LEAF_BLOWER ),+ ( 'microwave oven', EntityType.MICROWAVE_OVEN ),+ ( 'motion sensor', EntityType.MOTION_SENSOR ),+ ( 'network switch', EntityType.NETWORK_SWITCH ),+ ( 'pool filter', EntityType.POOL_FILTER ),+ ( 'pool heater', EntityType.POOL_HEATER ),+ ( 'pool pump', EntityType.POOL_PUMP ),+ ( 'power washer', EntityType.POWER_WASHER ),+ ( 'pressure washer', EntityType.POWER_WASHER ),+ ( 'radon detector', EntityType.RADON_DETECTOR ),+ ( 'range hood', EntityType.RANGE_HOOD ),+ ( 'satellite dish', EntityType.SATELLITE_DISH ),+ ( 'smoke detector', EntityType.SMOKE_DETECTOR ),+ ( 'solar panel', EntityType.SOLAR_PANEL ),+ ( 'sump pump', EntityType.SUMP_PUMP ),+ ( 'wall switch', EntityType.WALL_SWITCH ),+ ( 'water filter', EntityType.WATER_FILTER ),+ ( 'water heater', EntityType.WATER_HEATER ),+ ( 'water meter', EntityType.WATER_METER ),+ ( 'water softener', EntityType.WATER_SOFTENER ),+ ( 'weather station', EntityType.WEATHER_STATION ),+ # Single-word patterns. Tools.+ ( 'drill', EntityType.TOOL ),+ ( 'hammer', EntityType.TOOL ),+ ( 'pliers', EntityType.TOOL ),+ ( 'sander', EntityType.TOOL ),+ ( 'saw', EntityType.TOOL ),+ ( 'screwdriver', EntityType.TOOL ),+ ( 'wrench', EntityType.TOOL ),+ # Lighting.+ ( 'bulb', EntityType.LIGHT ),+ ( 'chandelier', EntityType.LIGHT ),+ ( 'lamp', EntityType.LIGHT ),+ ( 'light', EntityType.LIGHT ),+ ( 'sconce', EntityType.LIGHT ),+ # Computer / network.+ ( 'computer', EntityType.COMPUTER ),+ ( 'desktop', EntityType.COMPUTER ),+ ( 'laptop', EntityType.COMPUTER ),+ ( 'modem', EntityType.MODEM ),+ ( 'printer', EntityType.PRINTER ),+ ( 'router', EntityType.NETWORK_SWITCH ),+ ( 'server', EntityType.SERVER ),+ ( 'ups', EntityType.UPS ),+ # Audio / visual.+ ( 'receiver', EntityType.AV_RECEIVER ),+ ( 'soundbar', EntityType.SPEAKER ),+ ( 'speaker', EntityType.SPEAKER ),+ ( 'television', EntityType.TELEVISION ),+ ( 'tv', EntityType.TELEVISION ),+ # Appliances.+ ( 'dishwasher', EntityType.DISHWASHER ),+ ( 'dryer', EntityType.CLOTHES_DRYER ),+ ( 'freezer', EntityType.FREEZER ),+ ( 'fridge', EntityType.REFRIGERATOR ),+ ( 'grill', EntityType.GRILL ),+ ( 'microwave', EntityType.MICROWAVE_OVEN ),+ ( 'oven', EntityType.OVEN ),+ ( 'refrigerator', EntityType.REFRIGERATOR ),+ ( 'washer', EntityType.CLOTHES_WASHER ),+ # Climate.+ ( 'barometer', EntityType.BAROMETER ),+ ( 'humidifier', EntityType.HUMIDIFIER ),+ ( 'hygrometer', EntityType.HYGROMETER ),+ ( 'thermometer', EntityType.THERMOMETER ),+ ( 'thermostat', EntityType.THERMOSTAT ),+ # Outdoor.+ ( 'blower', EntityType.LEAF_BLOWER ),+ ( 'generator', EntityType.GENERATOR ),+ ( 'inverter', EntityType.INVERTER ),+ ( 'mower', EntityType.LAWN_MOWER ),+ ( 'trimmer', EntityType.TRIMMER ),+ # Security / cameras.+ ( 'camera', EntityType.CAMERA ),+ ( 'doorbell', EntityType.DOORBELL ),+ # Fixtures.+ ( 'bathtub', EntityType.BATHTUB ),+ ( 'shower', EntityType.SHOWER ),+ ( 'sink', EntityType.SINK ),+ ( 'toilet', EntityType.TOILET ),+]+++# Fields scanned for keyword matches, in priority order. A match in+# an earlier-listed field wins over any match in a later field.+_TYPE_HEURISTIC_FIELDS = ( 'name', 'description' )+++# Pre-sorted keyword patterns. Multi-word matches always beat+# single-word matches within the same field; longer keywords beat+# shorter at equal word count; alphabetical break for determinism.+_KEYWORD_PATTERNS = [+ (+ re.compile( rf'\b{re.escape(keyword)}\b', re.IGNORECASE ),+ entity_type,+ )+ for keyword, entity_type in sorted(+ HB_KEYWORD_ENTITY_TYPE_MAP,+ key = lambda pair: ( -len( pair[0].split() ), -len( pair[0] ), pair[0] ),+ )+]++class HbConverter:@classmethod@@ -70,6 +209,27 @@ class HbConverter:@classmethoddef hb_item_to_entity_type( cls, hb_item: HbItem ) -> EntityType:+ """Heuristic EntityType assignment for a HomeBox item.++ Two-pass priority:+ 1. Field priority — ``name`` first, then ``description``.+ A match in name wins over any match in description.+ The user titled the item deliberately; the description+ is incidental commentary.+ 2. Keyword specificity — within a field, longer / multi-+ word keyword matches beat shorter ones (handled by the+ pre-sort in ``_KEYWORD_PATTERNS``).++ Fallback: ``EntityType.OTHER`` when no keyword matches+ either field.+ """+ for field_name in _TYPE_HEURISTIC_FIELDS:+ field_value = getattr( hb_item, field_name, None )+ if not field_value:+ continue+ for pattern, entity_type in _KEYWORD_PATTERNS:+ if pattern.search( field_value ):+ return entity_typereturn EntityType.OTHER@classmethoddiff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.pyindex 8f1413d2..808a3635 100644--- a/src/hi/services/homebox/tests/test_hb_converter.py+++ b/src/hi/services/homebox/tests/test_hb_converter.py@@ -132,3 +132,161 @@ class TestHbConverterPayloadTimestampOmission(TestCase):HbConverter.hb_item_to_entity_payload(hb_item=earlier),HbConverter.hb_item_to_entity_payload(hb_item=later),)+++class TestHbItemToEntityType(TestCase):+ """Heuristic EntityType assignment from HomeBox item text fields.++ Verifies the two-pass priority — outer field priority (name then+ description) and inner keyword specificity (longer / multi-word+ keywords win) — and that word-boundary semantics prevent false+ positives like ``drilling`` matching ``drill``."""++ def _item(self, name='', description=''):+ from unittest.mock import Mock+ api_dict = {+ 'id': 'test-item',+ 'name': name,+ 'description': description,+ 'location': {'id': 'loc-1', 'name': 'Garage'},+ 'tags': [],+ 'fields': [],+ 'attachments': [],+ }+ client = Mock()+ return HbItem(api_dict=api_dict, client=client)++ # --- positive matches across categories -----------------------++ def test_tool_match_in_name(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Cordless Drill')),+ EntityType.TOOL,+ )++ def test_light_match_in_name(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Floor Lamp')),+ EntityType.LIGHT,+ )++ def test_camera_match_in_name(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Front Door Camera')),+ EntityType.CAMERA,+ )++ def test_refrigerator_match_in_name(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Kitchen Refrigerator')),+ EntityType.REFRIGERATOR,+ )++ def test_router_match_in_name(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Wi-Fi Router')),+ EntityType.NETWORK_SWITCH,+ )++ # --- multi-word beats single-word within the same field ------++ def test_multi_word_beats_single_word_in_same_field(self):+ # Item named 'Ceiling Fan' should match the multi-word+ # 'ceiling fan' keyword (CEILING_FAN), not just 'fan'+ # — even if 'fan' were also in the keyword map.+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Ceiling Fan')),+ EntityType.CEILING_FAN,+ )++ def test_leaf_blower_beats_bare_blower(self):+ from hi.apps.entity.enums import EntityType+ # The bare 'blower' keyword would also match, but the multi-+ # word 'leaf blower' is sorted first by specificity and wins.+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='Leaf Blower')),+ EntityType.LEAF_BLOWER,+ )++ # --- field priority: name beats description ------------------++ def test_name_match_beats_description_match(self):+ from hi.apps.entity.enums import EntityType+ # Name says drill (TOOL); description mentions lamp (LIGHT).+ # Name wins.+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(+ name='Cordless Drill',+ description='Used as accessory next to the lamp',+ )),+ EntityType.TOOL,+ )++ def test_description_used_when_name_has_no_match(self):+ from hi.apps.entity.enums import EntityType+ # Name carries no category signal (just brand/model); the+ # description identifies it as a leaf blower.+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(+ name='Acme BG-2200',+ description='Cordless leaf blower with two batteries',+ )),+ EntityType.LEAF_BLOWER,+ )++ # --- word-boundary correctness -------------------------------++ def test_drilling_does_not_match_drill(self):+ from hi.apps.entity.enums import EntityType+ # 'drilling' is not the same as 'drill' — boundary regex+ # must reject the suffix match.+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(+ name='Drilling Machine',+ )),+ EntityType.OTHER,+ )++ def test_case_insensitive(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='DRILL')),+ EntityType.TOOL,+ )++ # --- edge cases ----------------------------------------------++ def test_no_match_returns_other(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(+ name='Mystery Object',+ description='Unknown thing',+ )),+ EntityType.OTHER,+ )++ def test_empty_name_and_description_returns_other(self):+ from hi.apps.entity.enums import EntityType+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(name='', description='')),+ EntityType.OTHER,+ )++ def test_only_description_present(self):+ from hi.apps.entity.enums import EntityType+ # No name field at all (None-like) — description still+ # contributes.+ self.assertEqual(+ HbConverter.hb_item_to_entity_type(hb_item=self._item(+ name='',+ description='Mountain bike camera mount',+ )),+ EntityType.CAMERA,+ )diff --git a/src/hi/services/homebox/tests/test_hb_entity_factory.py b/src/hi/services/homebox/tests/test_hb_entity_factory.pyindex a9b51168..b20454d8 100644--- a/src/hi/services/homebox/tests/test_hb_entity_factory.py+++ b/src/hi/services/homebox/tests/test_hb_entity_factory.py@@ -45,7 +45,8 @@ class TestHbEntityFactory(TestCase):self.assertEqual(entity.integration_id, HbMetaData.integration_id)self.assertEqual(entity.integration_name, 'item-create')self.assertEqual(entity.name, 'Drill')- self.assertEqual(entity.entity_type, EntityType.OTHER)+ # HbConverter's keyword heuristic resolves 'Drill' to TOOL.+ self.assertEqual(entity.entity_type, EntityType.TOOL)self.assertFalse(entity.allow_internal_attributes)self.assertTrue(entity.is_external)self.assertNotIn('description', entity.integration_payload)diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 50af8032..d13bdc5f 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -600,6 +600,33 @@ class Command(BaseCommand):'garage,workshop','consumables',]+ # Names and descriptions chosen to exercise the EntityType+ # keyword heuristic (HbConverter.hb_item_to_entity_type).+ # Most entries resolve to a specific EntityType; one+ # ("Garden Hose") falls through to OTHER for fallback coverage.+ # Ordering is deterministic — indices 6..24 cycle through+ # the palette modulo its length.+ name_description_palette = [+ ( 'Cordless Drill', 'Compact 18V drill with two batteries.' ),+ ( 'Floor Lamp', 'Adjustable arm reading lamp with LED bulb.' ),+ ( 'WiFi Router', 'Mesh-capable home router with three nodes.' ),+ ( 'Smart TV', '55-inch 4K television in the family room.' ),+ ( 'Bookshelf Speaker', 'Pair of bookshelf speakers for stereo setup.' ),+ ( 'Kitchen Refrigerator', 'Energy-efficient refrigerator with ice maker.' ),+ ( 'Microwave Oven', 'Countertop microwave with sensor cooking.' ),+ ( 'Front Door Camera', 'Outdoor security camera with night vision.' ),+ ( 'Lawn Mower', 'Battery-powered lawn mower with collection bag.' ),+ ( 'Leaf Blower', 'Cordless leaf blower with two batteries.' ),+ ( 'Pressure Washer', 'Electric pressure washer rated for driveway use.' ),+ ( 'Smart Thermostat', 'Programmable thermostat with WiFi connectivity.' ),+ ( 'Circular Saw', 'Heavy-duty corded circular saw with carrying case.' ),+ ( 'Claw Hammer', 'Steel-headed claw hammer with rubber grip.' ),+ ( 'Wrench Set', 'Metric and standard wrench set in a case.' ),+ ( 'Backup Laptop', 'Spare laptop kept in the office desk drawer.' ),+ ( 'AV Receiver', 'Multi-channel audio receiver, 7.2 surround.' ),+ ( 'Wireless Doorbell', 'Battery-powered doorbell with chime unit.' ),+ ( 'Garden Hose', 'Standard 50-foot garden hose with brass fittings.' ),+ ]# Attachment template buckets indexed modulo 25 — first ~5# empty, next ~10 single, next ~5 paired, last ~5 with# three+ templates. Different choices keep the mime mix@@ -639,16 +666,18 @@ class Command(BaseCommand):for index in range(6, 25):item_number = index + 1+ palette_index = ( index - 6 ) % len( name_description_palette )+ palette_name, palette_description = name_description_palette[ palette_index ]kwargs = {'item_id': f'volume-item-{item_number:03}','quantity': (index % 4) + 1,'attachment_keys': attachment_buckets[index],+ 'description': palette_description,}if index % 5 == 0:# Fully documented item: every top-level field populated.kwargs.update({- 'description': f'Stress-test inventory item #{item_number}','manufacturer': 'Acme','model_number': f'AC-{item_number:03}','serial_number': f'SN-{item_number:05}',@@ -676,7 +705,7 @@ class Command(BaseCommand):self._add_homebox_item(profile,- f'Volume Item {item_number:03}',+ palette_name,**kwargs,)return profile.db_sim_entities.count()