From cfc2c29994b7069cf3ca89346e857c64277a6ea9 Mon Sep 17 00:00:00 2001 From: taguesokoudjou Date: Sun, 19 Jul 2026 13:29:02 +0200 Subject: [PATCH] Include CPC subclass-field main groups in IPC fetch and lookup. Reads cpc_subclass_* as group-level symbols (e.g. H01M8/00) so descriptions and OpenAlex topic mappings cover the previously missing */00 codes. --- .../main/inse/patents/ipc_search_client.py | 37 +++- .../patents_openalex_keywords/ipc_entries.py | 58 ++++-- .../patents_openalex_keywords/matching.py | 20 +- .../test_ipc_entries.py | 175 ++++++++++++++++++ .../test_matching.py | 12 ++ .../src/main/inse/patents/test_ipc_lookup.py | 20 ++ .../inse/patents/test_ipc_search_client.py | 147 +++++++++++++++ 7 files changed, 447 insertions(+), 22 deletions(-) create mode 100644 service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py diff --git a/service/src/main/inse/patents/ipc_search_client.py b/service/src/main/inse/patents/ipc_search_client.py index 846a6a69..4eb2ec07 100644 --- a/service/src/main/inse/patents/ipc_search_client.py +++ b/service/src/main/inse/patents/ipc_search_client.py @@ -12,6 +12,7 @@ from . import model from inse.exceptions import MissingApiKeyError from .ipc_lookup import IpcHierarchyKeys from .ipc_lookup import build_ipc_classification +from .ipc_lookup import normalize_ipc_symbol from .ipc_lookup import parse_ipc_symbol from inse.integrations import elasticsearch @@ -26,6 +27,10 @@ _LEVELS: tuple[tuple[str, str, str], ...] = ( ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"), ) +# Main-group symbols (typically */00, e.g. H01M8/00) live under these fields. +_GROUP_FALLBACK_FIELDS = ("cpc_subclass_number", "cpc_subclass_name") + + class IpcSearchClient: def __init__( @@ -91,6 +96,16 @@ class IpcSearchClient: if level_symbols: results[level] = await self._lookup_level(number_field, name_field, level_symbols) + group_symbols = {s for s in symbols_by_level["group"] if s} + if group_symbols: + fallback_number, fallback_name = _GROUP_FALLBACK_FIELDS + fallback_hits = await self._lookup_level( + fallback_number, fallback_name, group_symbols + ) + for key, name in fallback_hits.items(): + if name and not results["group"].get(key): + results["group"][key] = name + return results async def _lookup_level( @@ -102,13 +117,22 @@ class IpcSearchClient: if not symbols: return {} + # Query both raw and fully normalized forms so spaced/unspaced inputs match. + query_symbols: set[str] = set() + for symbol in symbols: + cleaned = symbol.strip() + if not cleaned: + continue + query_symbols.add(cleaned) + query_symbols.add(normalize_ipc_symbol(cleaned)) + payload: dict[str, Any] = { - "size": min(len(symbols), 100), + "size": min(len(query_symbols), 100), "query": { "bool": { "should": [ {"bool": {"filter": [{"match_phrase": {number_field: symbol}}]}} - for symbol in sorted(symbols) + for symbol in sorted(query_symbols) ], "minimum_should_match": 1, } @@ -124,9 +148,12 @@ class IpcSearchClient: number = source.get(number_field) if not number: continue - normalized_number = number.strip().upper() - found[normalized_number] = source.get(name_field) - found[number.strip()] = source.get(name_field) + name = source.get(name_field) + stripped = str(number).strip() + normalized_number = normalize_ipc_symbol(stripped) + found[normalized_number] = name + found[stripped] = name + found[stripped.upper()] = name return found diff --git a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py index b89ad79e..8756d8da 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py @@ -73,11 +73,35 @@ async def fetch_unique_ipc_entries( ) -> dict[str, dict[str, str]]: entries: dict[str, dict[str, str]] = defaultdict(dict) + def _store_entry( + level: str, + symbol: str, + name: str, + *, + overwrite: bool, + ) -> None: + normalized = normalize_symbol(symbol) + if not normalized: + return + if level == "subclass": + if len(normalized) <= 3: + return + normalized = infer_subclass(symbol) or normalized + if level == "class" and len(normalized) != 3: + return + label = str(name).strip() + if not label: + return + if overwrite or normalized not in entries[level]: + entries[level][normalized] = label + async def _composite_with_label( level: str, number_field: str, name_field: str, page_size: int, + *, + overwrite: bool = True, ) -> bool: for field_name in (number_field, f"{number_field}.keyword"): after_key: dict[str, str] | None = None @@ -126,12 +150,7 @@ async def fetch_unique_ipc_entries( name = hits[0].get("_source", {}).get(name_field) if not name: continue - normalized = normalize_symbol(str(symbol)) - if level == "subclass": - if len(normalized) <= 3: - continue - normalized = infer_subclass(str(symbol)) or normalized - entries[level][normalized] = str(name).strip() + _store_entry(level, str(symbol), str(name), overwrite=overwrite) after_key = items.get("after_key") if not after_key: break @@ -144,6 +163,8 @@ async def fetch_unique_ipc_entries( number_field: str, name_field: str, size: int, + *, + overwrite: bool = True, ) -> None: for field_name in (number_field, f"{number_field}.keyword"): payload = { @@ -180,14 +201,7 @@ async def fetch_unique_ipc_entries( name = hits[0].get("_source", {}).get(name_field) if not name: continue - normalized = normalize_symbol(str(symbol)) - if level == "class" and len(normalized) != 3: - continue - if level == "subclass": - if len(normalized) <= 3: - continue - normalized = infer_subclass(str(symbol)) or normalized - entries[level][normalized] = str(name).strip() + _store_entry(level, str(symbol), str(name), overwrite=overwrite) if "section" in levels: await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30) @@ -196,6 +210,22 @@ async def fetch_unique_ipc_entries( if "group" in levels: if not await _composite_with_label("group", "cpc_group_number", "cpc_group_name", 1000): await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000) + # Main groups (e.g. H01M8/00) are stored under the historically misnamed + # cpc_subclass_* fields. Merge without overwriting existing group entries. + if not await _composite_with_label( + "group", + "cpc_subclass_number", + "cpc_subclass_name", + 1000, + overwrite=False, + ): + await _terms_with_label( + "group", + "cpc_subclass_number", + "cpc_subclass_name", + 20000, + overwrite=False, + ) if "subgroup" in levels: if not await _composite_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 1000): await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/matching.py b/service/src/main/inse/patents/patents_openalex_keywords/matching.py index 2467d4d6..872d2837 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/matching.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/matching.py @@ -271,6 +271,20 @@ def documents_to_json_mapping(documents: list[tuple[str, dict]]) -> dict[str, di return mapping +def _hierarchy_label(value: Any) -> str | None: + """Normalize OpenAlex hierarchy fields to plain strings for keyword mapping.""" + if value is None: + return None + if isinstance(value, dict): + display = value.get("display_name") or value.get("name") + if display is None: + return None + text = str(display).strip() + return text or None + text = str(value).strip() + return text or None + + class TopicVectorsMatcher: def __init__( @@ -337,9 +351,9 @@ class TopicVectorsMatcher: "rank": len(topic_matches) + 1, "topic_id": topic_id, "topic_display_name": topic_name, - "subfield": source.get("subfield"), - "field": source.get("field"), - "domain": source.get("domain"), + "subfield": _hierarchy_label(source.get("subfield")), + "field": _hierarchy_label(source.get("field")), + "domain": _hierarchy_label(source.get("domain")), "match_score": round(score, 4), } ) diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py new file mode 100644 index 00000000..be6e3a5a --- /dev/null +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_ipc_entries.py @@ -0,0 +1,175 @@ +"""Tests for IPC entry fetching, including cpc_subclass_* main groups.""" +from __future__ import annotations + +from unittest.mock import AsyncMock, patch + +import pytest + +from inse.patents.patents_openalex_keywords.ipc_entries import ( + fetch_unique_ipc_entries, + normalize_symbol, +) + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _composite_response(buckets: list[dict]) -> dict: + return {"aggregations": {"items": {"buckets": buckets, "after_key": None}}} + + +def _bucket(symbol: str, name_field: str, name: str) -> dict: + return { + "key": {"symbol": symbol}, + "sample": {"hits": {"hits": [{"_source": {name_field: name}}]}}, + } + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_includes_main_groups_from_cpc_subclass(): + """H01M8/00 from cpc_subclass_* is stored as group with a non-empty label.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + # terms agg path + terms = body.get("aggs", {}).get("items", {}).get("terms", {}) + if terms: + field = terms.get("field", "") + + if field.startswith("cpc_section"): + return {"aggregations": {"items": {"buckets": []}}} + if field.startswith("cpc_class"): + return { + "aggregations": { + "items": { + "buckets": [ + { + "key": "H01M", + "sample": { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_name": "BATTERIES" + } + } + ] + } + }, + } + ] + } + } + } + if "cpc_group_number" in field: + return _composite_response( + [ + _bucket( + "H01M8/08", + "cpc_group_name", + "Fuel cells with aqueous electrolytes", + ) + ] + ) + if "cpc_subclass_number" in field: + return _composite_response( + [ + _bucket("H01M8/00", "cpc_subclass_name", "Fuel cells Manufacture thereof"), + _bucket("H01M 8/00", "cpc_subclass_name", "Fuel cells Manufacture thereof"), + _bucket("A01B1/00", "cpc_subclass_name", "Hand tools"), + ] + ) + if "cpc_subgroup" in field: + return _composite_response( + [ + _bucket("H01M8/083", "cpc_subgroup_name", "Alkaline fuel cells"), + ] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries() + + assert "H01M8/00" in entries["group"] + assert entries["group"]["H01M8/00"] + assert "H01M 8/00" not in entries["group"] # spaced form normalized away + assert normalize_symbol("H01M 8/00") == "H01M8/00" + assert entries["group"]["H01M8/00"] == "Fuel cells Manufacture thereof" + assert "A01B1/00" in entries["group"] + + # Existing levels unchanged in role + assert "H01M" in entries["subclass"] + assert "H01M8/083" in entries["subgroup"] + assert "H01M8/08" in entries["group"] + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_dedupes_normalized_group_symbols(): + """Spaced and unspaced main-group variants collapse to one entry.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + terms = body.get("aggs", {}).get("items", {}).get("terms", {}) + if terms: + field = terms.get("field", "") + + if "cpc_group_number" in field: + return _composite_response([]) + if "cpc_subclass_number" in field: + return _composite_response( + [ + _bucket("H01M8/00", "cpc_subclass_name", "from-unspaced"), + _bucket("H01M 8/00", "cpc_subclass_name", "from-spaced"), + ] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries(levels=("group",)) + + assert list(entries["group"]) == ["H01M8/00"] + # First write wins when overwrite=False for the subclass-field merge; + # both normalize to the same key so only one label is kept. + assert entries["group"]["H01M8/00"] in {"from-unspaced", "from-spaced"} + + +@pytest.mark.anyio +async def test_fetch_unique_ipc_entries_prefers_existing_group_over_subclass_field(): + """cpc_group_* labels are not overwritten by cpc_subclass_*.""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + sources = body.get("aggs", {}).get("items", {}).get("composite", {}).get( + "sources", [] + ) + field = sources[0]["symbol"]["terms"]["field"] if sources else "" + if "cpc_group_number" in field: + return _composite_response( + [_bucket("X01A1/00", "cpc_group_name", "from-group-field")] + ) + if "cpc_subclass_number" in field: + return _composite_response( + [_bucket("X01A1/00", "cpc_subclass_name", "from-subclass-field")] + ) + return {"aggregations": {"items": {"buckets": []}}} + + with patch( + "inse.patents.patents_openalex_keywords.ipc_entries.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + entries = await fetch_unique_ipc_entries(levels=("group",)) + + assert entries["group"]["X01A1/00"] == "from-group-field" diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py index 66417433..4b7c5051 100644 --- a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py +++ b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py @@ -7,11 +7,23 @@ import pytest from inse.patents.patents_openalex_keywords.matching import ( EmbeddingMatcher, TopicCandidate, + _hierarchy_label, top_k_indices, topic_embedding_text, ) +def test_hierarchy_label_extracts_display_name_from_object() -> None: + assert ( + _hierarchy_label( + {"id": "https://openalex.org/subfields/2211", "display_name": "Mechanics of Materials"} + ) + == "Mechanics of Materials" + ) + assert _hierarchy_label("Oncology") == "Oncology" + assert _hierarchy_label(None) is None + + def test_topic_embedding_text_joins_hierarchy() -> None: topic = TopicCandidate( topic_id="T1", diff --git a/service/src/main/inse/patents/test_ipc_lookup.py b/service/src/main/inse/patents/test_ipc_lookup.py index 941ff03b..7d26dbad 100644 --- a/service/src/main/inse/patents/test_ipc_lookup.py +++ b/service/src/main/inse/patents/test_ipc_lookup.py @@ -127,3 +127,23 @@ def test_build_ipc_classification_falls_back_to_symbol_only() -> None: result = build_ipc_classification(keys, {}) assert result == IpcClassification(symbol="INVALID") + + +def test_build_ipc_classification_main_group_from_normalized_key() -> None: + """Group labels keyed by normalized */00 symbols resolve for spaced inputs.""" + keys = parse_ipc_symbol("H01M 8/00") + names = { + "section": {"H": "ELECTRICITY"}, + "class": { + "H01": None, + "H01M": "BATTERIES / FUEL CELLS", + }, + "group": {"H01M8/00": "Fuel cells Manufacture thereof"}, + "subgroup": {}, + } + + result = build_ipc_classification(keys, names) + + assert keys.main_group == "H01M8/00" + assert result.main_group == "H01M 8/00 - Fuel cells Manufacture thereof" + assert result.subclass == "H01M - BATTERIES / FUEL CELLS" diff --git a/service/src/main/inse/patents/test_ipc_search_client.py b/service/src/main/inse/patents/test_ipc_search_client.py index 78df758e..4abc4a67 100644 --- a/service/src/main/inse/patents/test_ipc_search_client.py +++ b/service/src/main/inse/patents/test_ipc_search_client.py @@ -1,6 +1,7 @@ from unittest.mock import AsyncMock, patch import pytest +from inse.patents.ipc_lookup import parse_ipc_symbol from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient @@ -59,3 +60,149 @@ async def test_resolve_symbols_does_not_crash_for_subclass_codes(): assert "A61J 1/14" in result assert "C07D 319/06" in result + + +@pytest.mark.anyio +async def test_resolve_symbols_main_group_from_cpc_subclass_field(): + """H01M8/00 description comes from cpc_subclass_name (main-group storage).""" + + async def fake_search(*, index, body, cluster): # noqa: ANN001 + source_fields = body.get("_source") or [] + if "cpc_subclass_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_subclass_number": "H01M8/00", + "cpc_subclass_name": "Fuel cells Manufacture thereof", + } + } + ] + } + } + if "cpc_class_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_number": "H01M", + "cpc_class_name": ( + "PROCESSES OR MEANS, e.g. BATTERIES, FOR THE " + "DIRECT CONVERSION OF CHEMICAL ENERGY INTO " + "ELECTRICAL ENERGY" + ), + } + } + ] + } + } + if "cpc_section_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + } + ] + } + } + return {"hits": {"hits": []}} + + with patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + client = IpcSearchClient() + result = await client.resolve_symbols(["H01M8/00", "H01M 8/00"]) + + for symbol in ("H01M8/00", "H01M 8/00"): + clas = result[symbol] + assert clas.main_group is not None + assert "Fuel cells Manufacture thereof" in clas.main_group + assert clas.subclass is not None + assert clas.subclass.startswith("H01M") + + +@pytest.mark.anyio +async def test_resolve_symbols_keeps_subgroup_and_subclass_roles(): + async def fake_search(*, index, body, cluster): # noqa: ANN001 + source_fields = body.get("_source") or [] + if "cpc_subgroup_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_subgroup_number": "H01M8/083", + "cpc_subgroup_name": "Alkaline fuel cells", + } + } + ] + } + } + if "cpc_group_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_group_number": "H01M8/08", + "cpc_group_name": "Fuel cells with aqueous electrolytes", + } + } + ] + } + } + if "cpc_class_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_class_number": "H01M", + "cpc_class_name": "BATTERIES / FUEL CELLS", + } + } + ] + } + } + if "cpc_section_number" in source_fields: + return { + "hits": { + "hits": [ + { + "_source": { + "cpc_section_number": "H", + "cpc_section_name": "ELECTRICITY", + } + } + ] + } + } + return {"hits": {"hits": []}} + + with patch( + "inse.integrations.elasticsearch.search", + new=AsyncMock(side_effect=fake_search), + ): + client = IpcSearchClient() + subgroup = (await client.resolve_symbols(["H01M8/083"]))["H01M8/083"] + subclass = (await client.resolve_symbols(["H01M"]))["H01M"] + + assert subgroup.subgroup is not None + assert "Alkaline fuel cells" in subgroup.subgroup + assert subclass.subclass is not None + assert subclass.subclass.startswith("H01M") + assert subclass.main_group is None + assert subclass.subgroup is None + + keys_subgroup = parse_ipc_symbol("H01M8/083") + assert keys_subgroup.subgroup == "H01M8/083" + keys_subclass = parse_ipc_symbol("H01M") + assert keys_subclass.subclass == "H01M" + assert keys_subclass.main_group is None