diff --git a/service/README.md b/service/README.md index 6cdeceaf..eb7efe3d 100644 --- a/service/README.md +++ b/service/README.md @@ -23,15 +23,9 @@ Run tests: `./gradlew :service:test` Builds the `org_patents` Elasticsearch index for a given institution: fetches its OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee and/or inventor name, and reindexes. Each patent is tagged with a `match_type` -(`institution`, `name`, or `both`, the latter being highest confidence). Every -inventor-name match counts outright only if the assignee is the institution itself; -everything else matched on name alone — a personal-assignee match or a third-party -assignee (e.g. an industry partner on a co-invented patent) — only counts if the -patent's primary IPC/CPC classification also maps to OpenAlex research topics that -appear on the author's own profile. This applies regardless of how common the name -looks in our local OpenAlex data — a name can appear unique there while still being -common globally in EPO/USPTO, so a bare name match alone is never a strong enough -signal on its own. +(`institution`, `name`, or `both`, the latter being highest confidence). An +inventor-name match counts only if the assignee is the institution itself or the +person themselves — this avoids pulling in unrelated patents via a shared name. ```bash python scripts/patents/index_org_patents.py --institution-id diff --git a/service/scripts/patents/data/eval_runs/.gitignore b/service/scripts/patents/data/eval_runs/.gitignore new file mode 100644 index 00000000..c8dacad2 --- /dev/null +++ b/service/scripts/patents/data/eval_runs/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!labeling_presentation.json diff --git a/service/scripts/patents/data/eval_runs/labeling_presentation.json b/service/scripts/patents/data/eval_runs/labeling_presentation.json new file mode 100644 index 00000000..06648f6e --- /dev/null +++ b/service/scripts/patents/data/eval_runs/labeling_presentation.json @@ -0,0 +1,1854 @@ +{ + "created_at": "presentation", + "goldset": "patents\\data\\keyword_patent_goldset_presentation.json", + "cases": [ + { + "id": "fuel-cell", + "description": "Fuel cell – expected IPC H01M", + "keywords": [ + { + "keyword": "fuel cell", + "keyword_level": "fine", + "topic_id": "https://openalex.org/T10409", + "topic_display_name": "Fuel Cells and Related Materials", + "subfield_name": "Electrical and Electronic Engineering", + "field_name": "Engineering", + "relevance_score": 1.0 + } + ], + "expected_ipc_prefixes": [ + "H01M" + ], + "mapping_status": "mapped", + "diagnostics": { + "search_path": "ipc", + "es_query_size_per_index": 100, + "raw_patents_after_dedupe": 195, + "filtered_by_ipc": 0, + "filtered_by_relevance_gate": 0, + "filtered_by_min_score": 0, + "passed_relevance_gate": 195, + "scored_before_cap": 195, + "returned": 100, + "max_patents_cap": 100, + "hit_return_cap": true, + "ipc_cluster_selections": [ + { + "topic_key": "T10409", + "subclass": "H01M", + "symbol": "H01M8/083", + "level": "subgroup", + "match_score": 0.9871, + "cluster_mass": 38.5803, + "relative_mass": 0.2423, + "reason": "dominant_relative_mass" + } + ] + }, + "instructions": "Set grade 0=irrelevant, 1=relevant, 2=highly relevant. Copy graded patent_ids into goldset relevance_grades.", + "candidates": [ + { + "patent_id": "US12087951", + "title": "Electrochemical cell integrates electrolysis and fuel cell functions", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/90 20060101AFI20240910BHUS", + "C25B 11/081 20210101ALI20240910BHUS", + "H01M 8/0656 20160101ALI20240910BHUS", + "H01M 8/083 20160101ALI20240910BHUS" + ], + "cpc": [ + "H01M 4/9058 20130101FI20240910BHUS", + "C25B 11/081 20210101LI20240910BHUS", + "H01M 8/0656 20130101LI20240910BHUS", + "H01M 8/083 20130101LI20240910BHUS" + ], + "application_number": "17068023", + "current_rank": 1, + "grade": 2, + "notes": "Brennstoffzellenfunktion ist zentraler Gegenstand." + }, + { + "patent_id": "US10916789", + "title": "Alkaline exchange membrane fuel cells system having a bi-polar plate", + "source": "USPTO", + "publication_year": "2021", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/083 20160101AFI20210209BHUS", + "H01M 8/023 20160101ALI20210209BHUS", + "H01M 8/0289 20160101ALI20210209BHUS", + "H01M 8/0258 20160101ALI20210209BHUS", + "H01M 8/1062 20160101ALI20210209BHUS", + "H01M 8/1067 20160101ALI20210209BHUS", + "H01M 4/88 20060101ALI20210209BHUS", + "H01M 8/04119 20160101ALI20210209BHUS", + "H01M 8/0267 20160101ALN20210209BHUS", + "H01M 8/0234 20160101ALN20210209BHUS", + "H01M 8/0232 20160101ALN20210209BHUS", + "H01M 8/04029 20160101ALN20210209BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20210209BHUS", + "H01M 4/881 20130101LI20210209BHUS", + "H01M 4/8807 20130101LI20210209BHUS", + "H01M 8/023 20130101LI20210209BHUS", + "H01M 8/0258 20130101LI20210209BHUS", + "H01M 8/0289 20130101LI20210209BHUS", + "H01M 8/04119 20130101LI20210209BHUS", + "H01M 8/1062 20130101LI20210209BHUS", + "H01M 8/1067 20130101LI20210209BHUS", + "H01M 8/0232 20130101LA20210209BHUS", + "H01M 8/0234 20130101LA20210209BHUS", + "H01M 8/0267 20130101LA20210209BHUS", + "H01M 8/04029 20130101LA20210209BHUS" + ], + "application_number": "16085648", + "current_rank": 2, + "grade": 2, + "notes": "Brennstoffzellensystem und Bipolarplatte sind zentral." + }, + { + "patent_id": "US10847825", + "title": "Chloralkali process", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20160101AFI20201124BHUS", + "C25B 1/46 20060101ALI20201124BHUS", + "C25B 9/10 20060101ALI20201124BHUS", + "C25B 13/08 20060101ALI20201124BHUS", + "H01M 8/083 20160101ALI20201124BHUS" + ], + "cpc": [ + "H01M 8/0693 20130101FI20201124BHUS", + "C25B 1/46 20130101LI20201124BHUS", + "C25B 9/10 20130101LI20201124BHUS", + "C25B 13/08 20130101LI20201124BHUS", + "H01M 8/083 20130101LI20201124BHUS" + ], + "application_number": "15740882", + "current_rank": 3, + "grade": 0, + "notes": "Chloralkali-Verfahren; Brennstoffzelle ist nicht der zentrale Patentgegenstand." + }, + { + "patent_id": "US10847812", + "title": "Separator plate, membrane electrode assembly and fuel cell", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/0221 20160101AFI20201124BHUS", + "H01M 8/0258 20160101ALI20201124BHUS", + "H01M 8/1018 20160101ALI20201124BHUS", + "H01M 8/2418 20160101ALI20201124BHUS", + "H01M 8/0223 20160101ALI20201124BHUS", + "H01M 8/1004 20160101ALI20201124BHUS", + "H01M 8/1011 20160101ALN20201124BHUS", + "H01M 8/14 20060101ALN20201124BHUS", + "H01M 8/0267 20160101ALN20201124BHUS", + "H01M 8/083 20160101ALN20201124BHUS", + "H01M 8/124 20160101ALN20201124BHUS", + "H01M 8/086 20160101ALN20201124BHUS" + ], + "cpc": [ + "H01M 8/0221 20130101FI20201124BHUS", + "H01M 8/0223 20130101LI20201124BHUS", + "H01M 8/0258 20130101LI20201124BHUS", + "H01M 8/1004 20130101LI20201124BHUS", + "H01M 8/1018 20130101LI20201124BHUS", + "H01M 8/2418 20160201LI20201124BHUS", + "H01M 8/0267 20130101LA20201124BHUS", + "H01M 8/083 20130101LA20201124BHUS", + "H01M 8/086 20130101LA20201124BHUS", + "H01M 8/1011 20130101LA20201124BHUS", + "H01M 2008/1095 20130101LA20201124BHUS", + "H01M 2008/1293 20130101LA20201124BHUS", + "H01M 2008/147 20130101LA20201124BHUS" + ], + "application_number": "15852824", + "current_rank": 4, + "grade": 2, + "notes": "Brennstoffzellenkomponenten und Membran-Elektroden-Einheit sind zentral." + }, + { + "patent_id": "EP3549641", + "title": "FUEL TANK INERTING SYSTEM", + "source": "EPO", + "publication_year": "2019", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "A62C 3/06 20060101AFI20190820BHEP", + "A62C 3/08 20060101ALI20190820BHEP", + "A62C 99/00 20100101ALI20190820BHEP", + "B01D 53/32 20060101ALI20190820BHEP", + "H01M 8/00 20160101ALI20190820BHEP", + "H01M 8/083 20160101ALI20190820BHEP" + ], + "cpc": [], + "application_number": "19167279.9", + "current_rank": 5, + "grade": 0, + "notes": "Tank-Inertisierung; Brennstoffzellentechnik ist höchstens eine Teilkomponente." + }, + { + "patent_id": "US10297888", + "title": "Method and system for storing electricity in metals", + "source": "USPTO", + "publication_year": "2019", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 12/08 20060101AFI20190521BHUS", + "H01M 8/083 20160101ALI20190521BHUS", + "H01M 10/48 20060101ALI20190521BHUS", + "H01M 8/04828 20160101ALI20190521BHUS", + "H01M 10/44 20060101ALI20190521BHUS", + "H01M 8/18 20060101ALI20190521BHUS", + "H01M 8/04313 20160101ALI20190521BHUS", + "H01M 8/0444 20160101ALI20190521BHUS", + "H01M 8/04537 20160101ALI20190521BHUS" + ], + "cpc": [ + "H01M 12/08 20130101FI20190521BHUS", + "H01M 8/0444 20130101LI20190521BHUS", + "H01M 8/04537 20130101LI20190521BHUS", + "H01M 10/44 20130101LI20190521BHUS", + "H01M 10/48 20130101LI20190521BHUS", + "Y02E 60/128 20130101LA20190521BHUS" + ], + "application_number": "15053983", + "current_rank": 6, + "grade": 1, + "notes": "Elektrochemische Energiespeicherung mit technischer Nähe zu Brennstoffzellen." + }, + { + "patent_id": "US10096875", + "title": "System and method for increasing electrical efficiency of metal-air cell", + "source": "USPTO", + "publication_year": "2018", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/36 20060101AFI20181009BHUS", + "H01M 12/08 20060101ALI20181009BHUS", + "H01M 2/40 20060101ALI20181009BHUS", + "H01M 8/083 20160101ALI20181009BHUS", + "H01M 12/06 20060101ALI20181009BHUS" + ], + "cpc": [ + "H01M 12/08 20130101FI20181009BHUS", + "H01M 2/40 20130101LI20181009BHUS", + "H01M 8/083 20130101LI20181009BHUS", + "H01M 12/065 20130101LI20181009BHUS", + "H01M 2300/0014 20130101LA20181009BHUS", + "Y02E 60/128 20130101LA20181009BHUS" + ], + "application_number": "14779753", + "current_rank": 7, + "grade": 1, + "notes": "Metall-Luft-Zelle; elektrochemisch verwandt, aber keine klassische Brennstoffzelle." + }, + { + "patent_id": "US10006461", + "title": "Electrolyte circulation in fuel cells stacks with reduced leakage current", + "source": "USPTO", + "publication_year": "2018", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20160101AFI20180626BHUS", + "F04D 13/10 20060101ALI20180626BHUS", + "H01M 8/083 20160101ALI20180626BHUS", + "H01M 8/24 20160101ALI20180626BHUS", + "H01M 8/2485 20160101ALI20180626BHUS", + "H01M 8/04276 20160101ALI20180626BHUS", + "H01M 8/04291 20160101ALI20180626BHUS", + "H01M 8/0289 20160101ALN20180626BHUS" + ], + "cpc": [ + "F04D 13/10 20130101FI20180626BHUS", + "H01M 8/04276 20130101LI20180626BHUS", + "H01M 8/04291 20130101LI20180626BHUS", + "H01M 8/083 20130101LI20180626BHUS", + "H01M 8/2445 20130101LI20180626BHUS", + "H01M 8/2485 20130101LI20180626BHUS", + "H01M 8/0289 20130101LA20180626BHUS" + ], + "application_number": "14402650", + "current_rank": 8, + "grade": 2, + "notes": "Elektrolytzirkulation in Brennstoffzellenstapeln ist zentral." + }, + { + "patent_id": "EP3188296", + "title": "ADJUSTMENT METHOD OF THE ELECTROLYTE COMPOSITION FOR A FUEL CELL SYSTEM", + "source": "EPO", + "publication_year": "2017", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/0656 20160101AFI20170424BHEP", + "C25B 1/04 20060101ALI20170424BHEP", + "H01M 8/083 20160101ALI20170424BHEP", + "H01M 16/00 20060101ALI20170424BHEP", + "H01M 8/04276 20160101ALI20170424BHEP", + "H01M 8/0444 20160101ALI20170424BHEP", + "H01M 8/04791 20160101ALI20170424BHEP" + ], + "cpc": [], + "application_number": "16207072.6", + "current_rank": 9, + "grade": 2, + "notes": "Elektrolytzusammensetzung für ein Brennstoffzellensystem ist zentral." + }, + { + "patent_id": "US09564651", + "title": "Liquid electrolyte fuel cell system", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20160101AFI20170207BHUS", + "H01M 8/04 20160101ALN20170207BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20170207BHUS", + "H01M 8/04164 20130101LI20170207BHUS", + "H01M 8/04276 20130101LI20170207BHUS", + "H01M 8/0485 20130101LA20170207BHUS", + "H01M 2300/0014 20130101LA20170207BHUS", + "Y02E 60/50 20130101LA20170207BHUS" + ], + "application_number": "14370731", + "current_rank": 10, + "grade": 2, + "notes": "Flüssigelektrolyt-Brennstoffzellensystem ist zentral." + }, + { + "patent_id": "US09368819", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20160614BHUS", + "H01M 8/08 20160101ALI20160614BHUS", + "H01M 8/10 20160101ALI20160614BHUS", + "H01M 10/46 20060101ALI20160614BHUS", + "H02J 7/00 20060101ALI20160614BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20160614BHUS", + "H01M 8/0693 20130101LI20160614BHUS", + "H01M 8/083 20130101LI20160614BHUS", + "H01M 8/1002 20130101LI20160614BHUS", + "H01M 10/46 20130101LI20160614BHUS", + "H02J 7/0063 20130101LI20160614BHUS", + "H01M 2300/0014 20130101LA20160614BHUS", + "H01M 2300/0082 20130101LA20160614BHUS" + ], + "application_number": "14957760", + "current_rank": 11, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US09214691", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20151215BHUS", + "H01M 8/08 20060101ALI20151215BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20151215BHUS", + "H01M 8/083 20130101LI20151215BHUS", + "Y02E 60/50 20130101LA20151215BHUS" + ], + "application_number": "14552700", + "current_rank": 12, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US09083025", + "title": "Fuel cell stacks", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/04 20060101AFI20150714BHUS", + "H01M 8/08 20060101ALI20150714BHUS", + "H01M 8/24 20060101ALI20150714BHUS" + ], + "cpc": [ + "H01M 8/08 20130101FI20150714BHUS", + "H01M 8/083 20130101LI20150714BHUS", + "H01M 8/2445 20130101LI20150714BHUS", + "Y02E 60/50 20130101LA20150714BHUS" + ], + "application_number": "13695453", + "current_rank": 13, + "grade": 2, + "notes": "Brennstoffzellenstapel sind zentraler Gegenstand." + }, + { + "patent_id": "US08974984", + "title": "Power generation system using an alkaline fuel cell and fuel gas for alkaline fuel cells used in the system", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/22 20060101AFI20150310BHUS", + "H01M 8/08 20060101ALI20150310BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20150310BHUS", + "H01M 8/222 20130101LI20150310BHUS", + "Y02E 60/50 20130101LA20150310BHUS" + ], + "application_number": "13387130", + "current_rank": 14, + "grade": 2, + "notes": "Stromerzeugung mit alkalischer Brennstoffzelle ist zentral." + }, + { + "patent_id": "US08974983", + "title": "Electrical conductive member and polymer electrolyte fuel cell using the same", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/10 20060101AFI20150310BHUS", + "H01M 8/02 20060101ALI20150310BHUS", + "H01M 8/08 20060101ALN20150310BHUS", + "H01M 8/12 20060101ALN20150310BHUS", + "H01M 8/14 20060101ALN20150310BHUS" + ], + "cpc": [ + "H01M 8/0213 20130101FI20150310BHUS", + "H01M 8/0228 20130101LI20150310BHUS", + "H01M 8/0254 20130101LA20150310BHUS", + "H01M 8/083 20130101LA20150310BHUS", + "H01M 8/086 20130101LA20150310BHUS", + "H01M 2008/1095 20130101LA20150310BHUS", + "H01M 2008/1293 20130101LA20150310BHUS", + "H01M 2008/147 20130101LA20150310BHUS", + "Y02E 60/50 20130101LA20150310BHUS", + "Y02E 60/525 20130101LA20150310BHUS", + "Y02E 60/526 20130101LA20150310BHUS" + ], + "application_number": "13130979", + "current_rank": 15, + "grade": 2, + "notes": "Leitfähiges Bauteil für Polymer-Elektrolyt-Brennstoffzellen ist zentral." + }, + { + "patent_id": "US08895198", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2014", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20141125BHUS", + "H01M 8/08 20060101ALI20141125BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20141125BHUS", + "Y02E 60/50 20130101LA20141125BHUS", + "H01M 8/083 20130101LI20141125BHUS" + ], + "application_number": "12862746", + "current_rank": 16, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US08846266", + "title": "Carbohydrate anode for fuel cell and battery applications", + "source": "USPTO", + "publication_year": "2014", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20060101AFI20140930BHUS", + "H01M 8/22 20060101ALI20140930BHUS", + "H01M 4/96 20060101ALI20140930BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20140930BHUS", + "H01M 4/96 20130101LI20140930BHUS", + "H01M 2300/0014 20130101LA20140930BHUS", + "Y02E 60/50 20130101LA20140930BHUS" + ], + "application_number": "12769598", + "current_rank": 17, + "grade": 2, + "notes": "Anode für Brennstoffzellenanwendungen ist zentral." + }, + { + "patent_id": "US12512484", + "title": "Alkaline fuel cell electrode catalyst, alkaline fuel cell, and methods of making and using an electrode catalyst", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/90 20060101AFI20251230BHUS", + "H01M 4/88 20060101ALI20251230BHUS", + "H01M 8/083 20160101ALI20251230BHUS", + "H01M 4/86 20060101ALN20251230BHUS" + ], + "cpc": [ + "H01M 4/9016 20130101FI20251230BHUS", + "H01M 4/8882 20130101LI20251230BHUS", + "H01M 8/083 20130101LI20251230BHUS", + "H01M 2004/8689 20130101LA20251230BHUS" + ], + "application_number": "18081485", + "current_rank": 18, + "grade": 2, + "notes": "Elektrodenkatalysator und alkalische Brennstoffzelle sind zentral." + }, + { + "patent_id": "US12412912", + "title": "Electrochemical amine/nitrile redox method for ambient hydrogen storage", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/04082 20160101AFI20250909BHUS", + "H01M 8/04089 20160101ALI20250909BHUS", + "H01M 8/083 20160101ALI20250909BHUS", + "H01M 8/2457 20160101ALI20250909BHUS" + ], + "cpc": [ + "H01M 8/04216 20130101FI20250909BHUS", + "H01M 8/04089 20130101LI20250909BHUS", + "H01M 8/083 20130101LI20250909BHUS", + "H01M 8/2457 20160201LI20250909BHUS", + "H01M 2300/0014 20130101LA20250909BHUS" + ], + "application_number": "17875171", + "current_rank": 19, + "grade": 1, + "notes": "Wasserstoffspeicherung mit Nähe zu Brennstoffzellensystemen, aber nicht zentral." + }, + { + "patent_id": "US12368175", + "title": "Solid oxide fuel cell comprising anode alkaline-based promoter loaded", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/083 20160101AFI20250722BHUS", + "H01M 4/86 20060101ALI20250722BHUS", + "H01M 4/90 20060101ALI20250722BHUS", + "H01M 8/0217 20160101ALI20250722BHUS", + "H01M 8/12 20160101ALI20250722BHUS", + "H01M 8/1246 20160101ALI20250722BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20250722BHUS", + "H01M 4/8621 20130101LI20250722BHUS", + "H01M 4/9033 20130101LI20250722BHUS", + "H01M 8/0217 20130101LI20250722BHUS", + "H01M 8/1246 20130101LI20250722BHUS", + "H01M 2008/1293 20130101LA20250722BHUS" + ], + "application_number": "18659291", + "current_rank": 20, + "grade": 2, + "notes": "Festoxid-Brennstoffzelle ist zentraler Gegenstand." + } + ], + "relevance_grades": { + "US12087951": 2, + "US10916789": 2, + "US10847825": 0, + "US10847812": 2, + "EP3549641": 0, + "US10297888": 1, + "US10096875": 1, + "US10006461": 2, + "EP3188296": 2, + "US09564651": 2, + "US09368819": 2, + "US09214691": 2, + "US09083025": 2, + "US08974984": 2, + "US08974983": 2, + "US08895198": 2, + "US08846266": 2, + "US12512484": 2, + "US12412912": 1, + "US12368175": 2 + }, + "relevant_patent_ids": [ + "US12087951", + "US10916789", + "US10847812", + "US10297888", + "US10096875", + "US10006461", + "EP3188296", + "US09564651", + "US09368819", + "US09214691", + "US09083025", + "US08974984", + "US08974983", + "US08895198", + "US08846266", + "US12512484", + "US12412912", + "US12368175" + ], + "irrelevant_patent_ids": [ + "US10847825", + "EP3549641" + ] + }, + { + "id": "speech-recognition", + "description": "Speech recognition – expected IPC G10L", + "keywords": [ + { + "keyword": "speech recognition", + "keyword_level": "fine", + "topic_id": "https://openalex.org/T10201", + "topic_display_name": "Speech Recognition and Synthesis", + "subfield_name": "Artificial Intelligence", + "field_name": "Computer Science", + "relevance_score": 1.0 + } + ], + "expected_ipc_prefixes": [ + "G10L" + ], + "mapping_status": "mapped", + "diagnostics": { + "search_path": "ipc", + "es_query_size_per_index": 100, + "raw_patents_after_dedupe": 198, + "filtered_by_ipc": 4, + "filtered_by_relevance_gate": 16, + "filtered_by_min_score": 0, + "passed_relevance_gate": 178, + "scored_before_cap": 178, + "returned": 100, + "max_patents_cap": 100, + "hit_return_cap": true, + "ipc_cluster_selections": [ + { + "topic_key": "T10201", + "subclass": "G10L", + "symbol": "G10L17/14", + "level": "subgroup", + "match_score": 0.8808, + "cluster_mass": 22.8896, + "relative_mass": 0.4213, + "reason": "dominant_relative_mass" + }, + { + "topic_key": "T10201", + "subclass": "H04M", + "symbol": "H04M2201/405", + "level": "subgroup", + "match_score": 0.8556, + "cluster_mass": 6.5654, + "relative_mass": 0.1209, + "reason": "cumulative_mass_tail" + } + ] + }, + "instructions": "Set grade 0=irrelevant, 1=relevant, 2=highly relevant. Copy graded patent_ids into goldset relevance_grades.", + "candidates": [ + { + "patent_id": "US12137183", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20241105BHUS", + "G10L 15/01 20130101ALI20241105BHUS", + "G10L 15/06 20130101ALI20241105BHUS", + "G10L 15/22 20060101ALI20241105BHUS", + "G10L 15/26 20060101ALI20241105BHUS", + "G10L 21/10 20130101ALI20241105BHUS", + "H04M 1/247 20210101ALI20241105BHUS", + "H04M 1/72478 20210101ALI20241105BHUS", + "H04M 3/42 20060101ALI20241105BHUS", + "H04W 4/12 20090101ALI20241105BHUS", + "H04W 4/16 20090101ALI20241105BHUS", + "H04M 3/533 20060101ALN20241105BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20241105BHUS", + "G10L 15/01 20130101LI20241105BHUS", + "G10L 15/06 20130101LI20241105BHUS", + "G10L 15/22 20130101LI20241105BHUS", + "G10L 15/26 20130101LI20241105BHUS", + "G10L 21/10 20130101LI20241105BHUS", + "H04M 1/2475 20130101LI20241105BHUS", + "H04M 1/72478 20210101LI20241105BHUS", + "H04W 4/12 20130101LI20241105BHUS", + "H04W 4/16 20130101LI20241105BHUS", + "H04M 3/53366 20130101LA20241105BHUS", + "H04M 2201/18 20130101LA20241105BHUS", + "H04M 2201/40 20130101LA20241105BHUS", + "H04M 2201/405 20130101LA20241105BHUS" + ], + "application_number": "18123557", + "current_rank": 1, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US11627221", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20230411BHUS", + "H04M 3/42 20060101ALI20230411BHUS", + "G10L 15/06 20130101ALI20230411BHUS", + "G10L 15/22 20060101ALI20230411BHUS", + "H04M 1/247 20210101ALI20230411BHUS", + "H04M 1/72478 20210101ALI20230411BHUS", + "G10L 15/26 20060101ALI20230411BHUS", + "H04W 4/12 20090101ALI20230411BHUS", + "H04W 4/16 20090101ALI20230411BHUS", + "G10L 21/10 20130101ALI20230411BHUS", + "G10L 15/01 20130101ALI20230411BHUS", + "H04M 3/533 20060101ALN20230411BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20230411BHUS", + "G10L 15/01 20130101LI20230411BHUS", + "G10L 15/06 20130101LI20230411BHUS", + "G10L 15/22 20130101LI20230411BHUS", + "G10L 15/26 20130101LI20230411BHUS", + "G10L 21/10 20130101LI20230411BHUS", + "H04M 1/2475 20130101LI20230411BHUS", + "H04M 1/72478 20210101LI20230411BHUS", + "H04W 4/12 20130101LI20230411BHUS", + "H04W 4/16 20130101LI20230411BHUS", + "H04M 3/53366 20130101LA20230411BHUS", + "H04M 2201/18 20130101LA20230411BHUS", + "H04M 2201/40 20130101LA20230411BHUS", + "H04M 2201/405 20130101LA20230411BHUS" + ], + "application_number": "16911691", + "current_rank": 2, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US11601548", + "title": "Captioned telephone services improvement", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/42 20060101AFI20230307BHUS", + "G10L 15/26 20060101ALI20230307BHUS", + "H04M 3/436 20060101ALI20230307BHUS" + ], + "cpc": [ + "H04M 3/42382 20130101FI20230307BHUS", + "G10L 15/26 20130101LI20230307BHUS", + "H04M 3/42391 20130101LI20230307BHUS", + "H04M 3/436 20130101LI20230307BHUS", + "H04M 2201/405 20130101LA20230307BHUS" + ], + "application_number": "17184006", + "current_rank": 3, + "grade": 2, + "notes": "Automatische Transkription für Telefondienste ist zentral." + }, + { + "patent_id": "US10742805", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/42 20060101AFI20200811BHUS", + "G10L 15/06 20130101ALI20200811BHUS", + "G10L 15/22 20060101ALI20200811BHUS", + "H04M 1/247 20060101ALI20200811BHUS", + "H04M 1/725 20060101ALI20200811BHUS", + "G10L 15/26 20060101ALI20200811BHUS", + "H04W 4/12 20090101ALI20200811BHUS", + "H04W 4/16 20090101ALI20200811BHUS", + "G10L 21/10 20130101ALI20200811BHUS", + "G10L 15/01 20130101ALI20200811BHUS", + "H04M 3/533 20060101ALN20200811BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20200811BHUS", + "G10L 15/01 20130101LI20200811BHUS", + "G10L 15/06 20130101LI20200811BHUS", + "G10L 15/22 20130101LI20200811BHUS", + "G10L 15/26 20130101LI20200811BHUS", + "G10L 15/265 20130101LI20200811BHUS", + "G10L 21/10 20130101LI20200811BHUS", + "H04M 1/2475 20130101LI20200811BHUS", + "H04M 1/72591 20130101LI20200811BHUS", + "H04W 4/12 20130101LI20200811BHUS", + "H04W 4/16 20130101LI20200811BHUS", + "H04M 3/53366 20130101LA20200811BHUS", + "H04M 2201/18 20130101LA20200811BHUS", + "H04M 2201/40 20130101LA20200811BHUS", + "H04M 2201/405 20130101LA20200811BHUS" + ], + "application_number": "15477958", + "current_rank": 4, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US09769314", + "title": "Personal voice-based information retrieval system", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20170919BHUS", + "G06F 3/16 20060101ALI20170919BHUS", + "G10L 15/26 20060101ALI20170919BHUS", + "G06F 17/30 20060101ALI20170919BHUS", + "G10L 15/08 20060101ALI20170919BHUS", + "G10L 25/54 20130101ALI20170919BHUS", + "G10L 13/08 20130101ALI20170919BHUS", + "G10L 15/02 20060101ALI20170919BHUS", + "G10L 15/22 20060101ALI20170919BHUS", + "G10L 17/24 20130101ALN20170919BHUS", + "G10L 15/06 20130101ALN20170919BHUS", + "H04L 29/08 20060101ALN20170919BHUS" + ], + "cpc": [ + "H04M 3/4938 20130101FI20170919BHUS", + "G06F 3/167 20130101LI20170919BHUS", + "G06F 17/30769 20130101LI20170919BHUS", + "G06F 17/30861 20130101LI20170919BHUS", + "G10L 13/08 20130101LI20170919BHUS", + "G10L 15/02 20130101LI20170919BHUS", + "G10L 15/08 20130101LI20170919BHUS", + "G10L 15/22 20130101LI20170919BHUS", + "G10L 15/26 20130101LI20170919BHUS", + "G10L 25/54 20130101LI20170919BHUS", + "H04L 67/02 20130101LI20170919BHUS", + "G10L 15/06 20130101LA20170919BHUS", + "G10L 17/24 20130101LA20170919BHUS", + "G10L 2015/223 20130101LA20170919BHUS", + "H04L 29/0809 20130101LA20170919BHUS", + "H04M 2201/39 20130101LA20170919BHUS", + "H04M 2201/40 20130101LA20170919BHUS", + "H04M 2201/405 20130101LA20170919BHUS", + "H04M 2207/40 20130101LA20170919BHUS" + ], + "application_number": "15193517", + "current_rank": 5, + "grade": 2, + "notes": "Sprachbasierte Informationssuche mit Spracherkennung ist zentral." + }, + { + "patent_id": "US09685159", + "title": "Speaker recognition from telephone calls", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/00 20130101AFI20170620BHUS", + "G10L 17/02 20130101ALI20170620BHUS", + "G10L 17/06 20130101ALI20170620BHUS", + "H04M 3/22 20060101ALN20170620BHUS", + "H04M 3/436 20060101ALN20170620BHUS" + ], + "cpc": [ + "G10L 17/00 20130101FI20170620BHUS", + "G10L 17/02 20130101LI20170620BHUS", + "G10L 17/06 20130101LI20170620BHUS", + "H04M 3/2281 20130101LA20170620BHUS", + "H04M 3/436 20130101LA20170620BHUS", + "H04M 2201/405 20130101LA20170620BHUS", + "H04M 2201/41 20130101LA20170620BHUS" + ], + "application_number": "14817182", + "current_rank": 6, + "grade": 1, + "notes": "Sprechererkennung ist eng verwandt, aber nicht klassische Spracherkennung." + }, + { + "patent_id": "US09377992", + "title": "Personal voice-based information retrieval system", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G06F 3/16 20060101AFI20160628BHUS", + "G10L 15/26 20060101ALI20160628BHUS", + "G10L 17/24 20130101ALN20160628BHUS", + "G10L 15/06 20130101ALN20160628BHUS", + "H04M 3/493 20060101ALN20160628BHUS", + "H04L 29/08 20060101ALN20160628BHUS" + ], + "cpc": [ + "G06F 3/167 20130101FI20160628BHUS", + "G10L 15/26 20130101LI20160628BHUS", + "G10L 15/06 20130101LA20160628BHUS", + "G10L 17/24 20130101LA20160628BHUS", + "H04L 29/0809 20130101LA20160628BHUS", + "H04M 3/4938 20130101LA20160628BHUS", + "H04M 2201/405 20130101LA20160628BHUS", + "H04M 2207/40 20130101LA20160628BHUS" + ], + "application_number": "12787801", + "current_rank": 7, + "grade": 2, + "notes": "Sprachbasierte Informationssuche mit Spracherkennung ist zentral." + }, + { + "patent_id": "US09736309", + "title": "Real-time transcription and interaction with a caller based on the transcription", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.862, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 1/64 20060101AFI20170815BHUS", + "H04M 3/527 20060101ALI20170815BHUS", + "G10L 15/26 20060101ALI20170815BHUS", + "G10L 13/08 20130101ALI20170815BHUS", + "G10L 15/30 20130101ALI20170815BHUS" + ], + "cpc": [ + "H04M 3/527 20130101FI20170815BHUS", + "G10L 13/08 20130101LI20170815BHUS", + "G10L 15/26 20130101LI20170815BHUS", + "G10L 15/30 20130101LI20170815BHUS", + "H04M 2201/39 20130101LA20170815BHUS", + "H04M 2201/40 20130101LA20170815BHUS", + "H04M 2201/60 20130101LA20170815BHUS" + ], + "application_number": "15241555", + "current_rank": 8, + "grade": 2, + "notes": "Echtzeit-Transkription gesprochener Sprache ist zentral." + }, + { + "patent_id": "US12579986", + "title": "Systems and methods for distinguishing between human speech and machine generated speech", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/14 20130101AFI20260317BHUS", + "G06F 40/30 20200101ALI20260317BHUS", + "G10L 15/26 20060101ALI20260317BHUS", + "G10L 17/00 20130101ALI20260317BHUS", + "G10L 17/02 20130101ALI20260317BHUS", + "G10L 17/22 20130101ALI20260317BHUS", + "G10L 17/26 20130101ALI20260317BHUS", + "H04M 3/51 20060101ALI20260317BHUS" + ], + "cpc": [ + "G10L 17/14 20130101FI20260317BHUS", + "G06F 40/30 20200101LI20260317BHUS", + "G10L 15/26 20130101LI20260317BHUS", + "G10L 17/00 20130101LI20260317BHUS", + "G10L 17/02 20130101LI20260317BHUS", + "G10L 17/22 20130101LI20260317BHUS", + "H04M 3/5166 20130101LI20260317BHUS" + ], + "application_number": "18602835", + "current_rank": 9, + "grade": 1, + "notes": "Klassifikation menschlicher und synthetischer Sprache ist fachlich angrenzend." + }, + { + "patent_id": "US10397400", + "title": "Electronic call assistant based on a caller-status and a callee-status", + "source": "USPTO", + "publication_year": "2019", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20190827BHUS", + "G10L 17/14 20130101ALI20190827BHUS", + "A61B 5/00 20060101ALN20190827BHUS", + "G10L 15/26 20060101ALN20190827BHUS" + ], + "cpc": [ + "H04M 3/493 20130101FI20190827BHUS", + "G10L 17/14 20130101LI20190827BHUS", + "H04M 3/4936 20130101LI20190827BHUS", + "A61B 5/6802 20130101LA20190827BHUS", + "G10L 15/265 20130101LA20190827BHUS", + "H04M 2201/405 20130101LA20190827BHUS" + ], + "application_number": "15802695", + "current_rank": 10, + "grade": 0, + "notes": "Allgemeiner elektronischer Anrufassistent; Spracherkennung ist nicht zentral." + }, + { + "patent_id": "US09369577", + "title": "Transparent voice registration and verification method and system", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20160614BHUS", + "G10L 17/14 20130101ALI20160614BHUS", + "H04M 3/42 20060101ALI20160614BHUS", + "H04M 3/51 20060101ALI20160614BHUS", + "H04M 3/38 20060101ALI20160614BHUS", + "G10L 17/04 20130101ALN20160614BHUS" + ], + "cpc": [ + "H04M 3/4936 20130101FI20160614BHUS", + "G10L 17/14 20130101LI20160614BHUS", + "H04M 3/385 20130101LI20160614BHUS", + "H04M 3/42221 20130101LI20160614BHUS", + "H04M 3/51 20130101LI20160614BHUS", + "G10L 17/04 20130101LA20160614BHUS", + "H04M 2201/36 20130101LA20160614BHUS", + "H04M 2201/41 20130101LA20160614BHUS", + "H04M 2203/6045 20130101LA20160614BHUS" + ], + "application_number": "14526933", + "current_rank": 11, + "grade": 1, + "notes": "Stimmregistrierung und Sprecherverifikation sind fachlich angrenzend." + }, + { + "patent_id": "US12615335", + "title": "Voice fingerprinting system for detecting hoax emergency reports", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20260428BHUS", + "G10L 17/02 20130101ALI20260428BHUS", + "G10L 17/04 20130101ALI20260428BHUS", + "G10L 17/06 20130101ALI20260428BHUS", + "G10L 17/18 20130101ALI20260428BHUS", + "G10L 25/18 20130101ALI20260428BHUS", + "G10L 25/24 20130101ALI20260428BHUS", + "H04M 3/22 20060101ALI20260428BHUS", + "H04M 3/51 20060101ALI20260428BHUS", + "G06Q 50/26 20120101ALN20260428BHUS" + ], + "cpc": [ + "H04M 3/5116 20130101FI20260428BHUS", + "G10L 17/02 20130101LI20260428BHUS", + "G10L 17/04 20130101LI20260428BHUS", + "G10L 17/06 20130101LI20260428BHUS", + "G10L 17/18 20130101LI20260428BHUS", + "G10L 25/18 20130101LI20260428BHUS", + "G10L 25/24 20130101LI20260428BHUS", + "H04M 3/2281 20130101LI20260428BHUS", + "H04M 3/5175 20130101LI20260428BHUS", + "H04M 3/5191 20130101LI20260428BHUS", + "G06Q 50/265 20130101LA20260428BHUS", + "H04M 2201/405 20130101LA20260428BHUS" + ], + "application_number": "18732780", + "current_rank": 12, + "grade": 1, + "notes": "Voice-Fingerprinting und Sprechererkennung sind fachlich angrenzend." + }, + { + "patent_id": "US12592239", + "title": "Active voice liveness detection system", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/26 20130101AFI20260331BHUS", + "G06F 21/32 20130101ALI20260331BHUS", + "G10L 15/02 20060101ALI20260331BHUS", + "G10L 17/00 20130101ALI20260331BHUS", + "G10L 17/02 20130101ALI20260331BHUS", + "G10L 17/04 20130101ALI20260331BHUS", + "G10L 17/08 20130101ALI20260331BHUS", + "G10L 17/18 20130101ALI20260331BHUS", + "G10L 25/30 20130101ALI20260331BHUS", + "G10L 25/51 20130101ALI20260331BHUS", + "G10L 25/60 20130101ALI20260331BHUS", + "H04M 3/22 20060101ALI20260331BHUS", + "H04M 3/42 20060101ALI20260331BHUS", + "H04M 3/51 20060101ALI20260331BHUS" + ], + "cpc": [ + "G10L 17/26 20130101FI20260331BHUS", + "G06F 21/32 20130101LI20260331BHUS", + "G10L 15/02 20130101LI20260331BHUS", + "G10L 17/00 20130101LI20260331BHUS", + "G10L 17/02 20130101LI20260331BHUS", + "G10L 17/04 20130101LI20260331BHUS", + "G10L 17/08 20130101LI20260331BHUS", + "G10L 17/18 20130101LI20260331BHUS", + "G10L 25/51 20130101LI20260331BHUS", + "G10L 25/60 20130101LI20260331BHUS", + "H04M 3/2281 20130101LI20260331BHUS", + "H04M 3/42221 20130101LI20260331BHUS", + "H04M 3/5175 20130101LI20260331BHUS", + "H04M 3/5183 20130101LI20260331BHUS", + "G10L 25/30 20130101LA20260331BHUS", + "H04M 2201/405 20130101LA20260331BHUS" + ], + "application_number": "18646310", + "current_rank": 13, + "grade": 1, + "notes": "Voice-Liveness-Erkennung ist biometrisch verwandt, aber keine klassische Spracherkennung." + }, + { + "patent_id": "US09571617", + "title": "Controlling mute function on telephone", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/00 20060101AFI20170214BHUS", + "H04M 1/19 20060101ALI20170214BHUS", + "H04M 1/247 20060101ALI20170214BHUS", + "G10L 15/22 20060101ALI20170214BHUS", + "G10L 17/04 20130101ALI20170214BHUS", + "G10L 17/06 20130101ALI20170214BHUS", + "G10L 25/84 20130101ALI20170214BHUS", + "H04M 1/60 20060101ALN20170214BHUS" + ], + "cpc": [ + "H04M 1/19 20130101FI20170214BHUS", + "G10L 15/22 20130101LI20170214BHUS", + "G10L 17/04 20130101LI20170214BHUS", + "G10L 17/06 20130101LI20170214BHUS", + "G10L 25/84 20130101LI20170214BHUS", + "H04M 1/247 20130101LI20170214BHUS", + "H04M 1/6033 20130101LI20170214BHUS", + "G10L 2015/223 20130101LA20170214BHUS", + "H04M 1/6008 20130101LA20170214BHUS", + "H04M 2201/405 20130101LA20170214BHUS", + "H04M 2203/258 20130101LA20170214BHUS", + "H04M 2250/74 20130101LA20170214BHUS" + ], + "application_number": "15168757", + "current_rank": 14, + "grade": 1, + "notes": "Sprachgesteuerte Stummschaltung; Spracherkennung ist eine relevante Teilfunktion." + }, + { + "patent_id": "US12482458", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/183 20130101AFI20251125BHUS", + "G10L 15/26 20060101ALI20251125BHUS", + "G10L 25/60 20130101ALI20251125BHUS", + "H04M 1/247 20210101ALI20251125BHUS", + "H04M 1/72433 20210101ALI20251125BHUS", + "H04M 1/72478 20210101ALI20251125BHUS", + "H04M 3/42 20060101ALI20251125BHUS" + ], + "cpc": [ + "G10L 15/183 20130101FI20251125BHUS", + "G10L 15/26 20130101LI20251125BHUS", + "G10L 25/60 20130101LI20251125BHUS", + "H04M 1/2475 20130101LI20251125BHUS", + "H04M 1/72433 20210101LI20251125BHUS", + "H04M 1/72478 20210101LI20251125BHUS", + "H04M 3/42391 20130101LI20251125BHUS", + "H04M 2201/40 20130101LA20251125BHUS", + "H04M 2201/60 20130101LA20251125BHUS" + ], + "application_number": "16422662", + "current_rank": 15, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US12132865", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20241029BHUS", + "G06F 40/205 20200101ALI20241029BHUS", + "G10L 17/04 20130101ALI20241029BHUS", + "G10L 17/08 20130101ALI20241029BHUS", + "G10L 25/51 20130101ALI20241029BHUS", + "G10L 25/63 20130101ALI20241029BHUS", + "G10L 25/87 20130101ALI20241029BHUS", + "H04M 3/42 20060101ALI20241029BHUS", + "G10L 15/26 20060101ALN20241029BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20241029BHUS", + "G06F 40/205 20200101LI20241029BHUS", + "G10L 17/04 20130101LI20241029BHUS", + "G10L 17/08 20130101LI20241029BHUS", + "G10L 25/51 20130101LI20241029BHUS", + "G10L 25/63 20130101LI20241029BHUS", + "H04M 3/42 20130101LI20241029BHUS", + "G10L 15/26 20130101LA20241029BHUS", + "G10L 25/87 20130101LA20241029BHUS", + "H04M 2201/40 20130101LA20241029BHUS", + "H04M 2201/41 20130101LA20241029BHUS", + "H04M 2203/40 20130101LA20241029BHUS", + "H04M 2203/401 20130101LA20241029BHUS" + ], + "application_number": "18376605", + "current_rank": 16, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US12088761", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20240910BHUS", + "G06F 40/205 20200101ALI20240910BHUS", + "G10L 15/26 20060101ALI20240910BHUS", + "G10L 17/04 20130101ALI20240910BHUS", + "G10L 17/08 20130101ALI20240910BHUS", + "G10L 25/51 20130101ALI20240910BHUS", + "G10L 25/63 20130101ALI20240910BHUS", + "G10L 25/87 20130101ALI20240910BHUS", + "H04M 3/42 20060101ALI20240910BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20240910BHUS", + "G06F 40/205 20200101LI20240910BHUS", + "G10L 17/04 20130101LI20240910BHUS", + "G10L 17/08 20130101LI20240910BHUS", + "G10L 25/51 20130101LI20240910BHUS", + "G10L 25/63 20130101LI20240910BHUS", + "H04M 3/42 20130101LI20240910BHUS", + "G10L 15/26 20130101LA20240910BHUS", + "G10L 25/87 20130101LA20240910BHUS", + "H04M 2201/40 20130101LA20240910BHUS", + "H04M 2201/41 20130101LA20240910BHUS", + "H04M 2203/40 20130101LA20240910BHUS", + "H04M 2203/401 20130101LA20240910BHUS" + ], + "application_number": "18203094", + "current_rank": 17, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US11811970", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20231107BHUS", + "G10L 17/04 20130101ALI20231107BHUS", + "G10L 25/51 20130101ALI20231107BHUS", + "G10L 25/63 20130101ALI20231107BHUS", + "G10L 25/87 20130101ALI20231107BHUS", + "H04M 3/42 20060101ALI20231107BHUS", + "G06F 40/205 20200101ALI20231107BHUS", + "G10L 17/08 20130101ALI20231107BHUS", + "G10L 15/26 20060101ALN20231107BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20231107BHUS", + "G06F 40/205 20200101LI20231107BHUS", + "G10L 17/04 20130101LI20231107BHUS", + "G10L 17/08 20130101LI20231107BHUS", + "G10L 25/51 20130101LI20231107BHUS", + "G10L 25/63 20130101LI20231107BHUS", + "H04M 3/42 20130101LI20231107BHUS", + "G10L 15/26 20130101LA20231107BHUS", + "G10L 25/87 20130101LA20231107BHUS", + "H04M 2201/40 20130101LA20231107BHUS", + "H04M 2201/41 20130101LA20231107BHUS", + "H04M 2203/40 20130101LA20231107BHUS", + "H04M 2203/401 20130101LA20231107BHUS" + ], + "application_number": "17690099", + "current_rank": 18, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US11706338", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20230718BHUS", + "G10L 17/04 20130101ALI20230718BHUS", + "G10L 25/51 20130101ALI20230718BHUS", + "G10L 25/63 20130101ALI20230718BHUS", + "G10L 25/87 20130101ALI20230718BHUS", + "H04M 3/42 20060101ALI20230718BHUS", + "G06F 40/205 20200101ALI20230718BHUS", + "G10L 17/08 20130101ALI20230718BHUS", + "G10L 15/26 20060101ALN20230718BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20230718BHUS", + "G06F 40/205 20200101LI20230718BHUS", + "G10L 17/04 20130101LI20230718BHUS", + "G10L 17/08 20130101LI20230718BHUS", + "G10L 25/51 20130101LI20230718BHUS", + "G10L 25/63 20130101LI20230718BHUS", + "H04M 3/42 20130101LI20230718BHUS", + "G10L 15/26 20130101LA20230718BHUS", + "G10L 25/87 20130101LA20230718BHUS", + "H04M 2201/40 20130101LA20230718BHUS", + "H04M 2201/41 20130101LA20230718BHUS", + "H04M 2203/40 20130101LA20230718BHUS", + "H04M 2203/401 20130101LA20230718BHUS" + ], + "application_number": "17472557", + "current_rank": 19, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US10863033", + "title": "Voice recognition system and voice recognition method", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 11/00 20060101AFI20201208BHUS", + "H04M 3/58 20060101ALI20201208BHUS", + "H04M 3/493 20060101ALI20201208BHUS", + "G10L 17/22 20130101ALI20201208BHUS", + "H04M 3/42 20060101ALI20201208BHUS", + "G10L 15/22 20060101ALI20201208BHUS" + ], + "cpc": [ + "H04M 3/58 20130101FI20201208BHUS", + "G10L 15/22 20130101LI20201208BHUS", + "G10L 17/22 20130101LI20201208BHUS", + "H04M 3/42221 20130101LI20201208BHUS", + "H04M 3/4931 20130101LI20201208BHUS", + "H04M 3/4936 20130101LI20201208BHUS", + "G10L 2015/223 20130101LA20201208BHUS", + "H04M 3/4933 20130101LA20201208BHUS", + "H04M 2201/18 20130101LA20201208BHUS", + "H04M 2201/39 20130101LA20201208BHUS", + "H04M 2201/40 20130101LA20201208BHUS" + ], + "application_number": "16432362", + "current_rank": 20, + "grade": 2, + "notes": "Sprach- und Stimmerkennung sind zentraler Gegenstand." + } + ], + "relevance_grades": { + "US12137183": 2, + "US11627221": 2, + "US11601548": 2, + "US10742805": 2, + "US09769314": 2, + "US09685159": 1, + "US09377992": 2, + "US09736309": 2, + "US12579986": 1, + "US10397400": 0, + "US09369577": 1, + "US12615335": 1, + "US12592239": 1, + "US09571617": 1, + "US12482458": 2, + "US12132865": 2, + "US12088761": 2, + "US11811970": 2, + "US11706338": 2, + "US10863033": 2 + }, + "relevant_patent_ids": [ + "US12137183", + "US11627221", + "US11601548", + "US10742805", + "US09769314", + "US09685159", + "US09377992", + "US09736309", + "US12579986", + "US09369577", + "US12615335", + "US12592239", + "US09571617", + "US12482458", + "US12132865", + "US12088761", + "US11811970", + "US11706338", + "US10863033" + ], + "irrelevant_patent_ids": [ + "US10397400" + ] + } + ], + "labeling_status": { + "completed": true, + "criterion": { + "0": "irrelevant / False Positive", + "1": "fachlich angrenzend oder relevante Teilanwendung", + "2": "Thema ist zentraler Patentgegenstand" + }, + "warning": "KI-gestützte Vorlabelierung anhand von Titel sowie IPC/CPC-Evidenz. Für einen wissenschaftlichen Goldstandard sollten Grenzfälle fachlich geprüft werden." + } +} \ No newline at end of file diff --git a/service/scripts/patents/data/keyword_patent_goldset_presentation.json b/service/scripts/patents/data/keyword_patent_goldset_presentation.json new file mode 100644 index 00000000..af14c599 --- /dev/null +++ b/service/scripts/patents/data/keyword_patent_goldset_presentation.json @@ -0,0 +1,1787 @@ +{ + "version": 1, + "presentation": true, + "description": "goldset for two IPC cases.", + "ks": [ + 5, + 10, + 20 + ], + "cases": [ + { + "id": "fuel-cell", + "description": "Fuel cell – expected IPC H01M", + "keywords": [ + { + "keyword": "fuel cell", + "keyword_level": "fine", + "topic_id": "https://openalex.org/T10409", + "topic_display_name": "Fuel Cells and Related Materials", + "subfield_name": "Electrical and Electronic Engineering", + "field_name": "Engineering", + "relevance_score": 1.0 + } + ], + "expected_ipc_prefixes": [ + "H01M" + ], + "relevant_patent_ids": [ + "US12087951", + "US10916789", + "US10847812", + "US10297888", + "US10096875", + "US10006461", + "EP3188296", + "US09564651", + "US09368819", + "US09214691", + "US09083025", + "US08974984", + "US08974983", + "US08895198", + "US08846266", + "US12512484", + "US12412912", + "US12368175" + ], + "irrelevant_patent_ids": [ + "US10847825", + "EP3549641" + ], + "relevance_grades": { + "US12087951": 2, + "US10916789": 2, + "US10847825": 0, + "US10847812": 2, + "EP3549641": 0, + "US10297888": 1, + "US10096875": 1, + "US10006461": 2, + "EP3188296": 2, + "US09564651": 2, + "US09368819": 2, + "US09214691": 2, + "US09083025": 2, + "US08974984": 2, + "US08974983": 2, + "US08895198": 2, + "US08846266": 2, + "US12512484": 2, + "US12412912": 1, + "US12368175": 2 + }, + "labeling_candidates": [ + { + "patent_id": "US12087951", + "title": "Electrochemical cell integrates electrolysis and fuel cell functions", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/90 20060101AFI20240910BHUS", + "C25B 11/081 20210101ALI20240910BHUS", + "H01M 8/0656 20160101ALI20240910BHUS", + "H01M 8/083 20160101ALI20240910BHUS" + ], + "cpc": [ + "H01M 4/9058 20130101FI20240910BHUS", + "C25B 11/081 20210101LI20240910BHUS", + "H01M 8/0656 20130101LI20240910BHUS", + "H01M 8/083 20130101LI20240910BHUS" + ], + "application_number": "17068023", + "current_rank": 1, + "grade": 2, + "notes": "Brennstoffzellenfunktion ist zentraler Gegenstand." + }, + { + "patent_id": "US10916789", + "title": "Alkaline exchange membrane fuel cells system having a bi-polar plate", + "source": "USPTO", + "publication_year": "2021", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/083 20160101AFI20210209BHUS", + "H01M 8/023 20160101ALI20210209BHUS", + "H01M 8/0289 20160101ALI20210209BHUS", + "H01M 8/0258 20160101ALI20210209BHUS", + "H01M 8/1062 20160101ALI20210209BHUS", + "H01M 8/1067 20160101ALI20210209BHUS", + "H01M 4/88 20060101ALI20210209BHUS", + "H01M 8/04119 20160101ALI20210209BHUS", + "H01M 8/0267 20160101ALN20210209BHUS", + "H01M 8/0234 20160101ALN20210209BHUS", + "H01M 8/0232 20160101ALN20210209BHUS", + "H01M 8/04029 20160101ALN20210209BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20210209BHUS", + "H01M 4/881 20130101LI20210209BHUS", + "H01M 4/8807 20130101LI20210209BHUS", + "H01M 8/023 20130101LI20210209BHUS", + "H01M 8/0258 20130101LI20210209BHUS", + "H01M 8/0289 20130101LI20210209BHUS", + "H01M 8/04119 20130101LI20210209BHUS", + "H01M 8/1062 20130101LI20210209BHUS", + "H01M 8/1067 20130101LI20210209BHUS", + "H01M 8/0232 20130101LA20210209BHUS", + "H01M 8/0234 20130101LA20210209BHUS", + "H01M 8/0267 20130101LA20210209BHUS", + "H01M 8/04029 20130101LA20210209BHUS" + ], + "application_number": "16085648", + "current_rank": 2, + "grade": 2, + "notes": "Brennstoffzellensystem und Bipolarplatte sind zentral." + }, + { + "patent_id": "US10847825", + "title": "Chloralkali process", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20160101AFI20201124BHUS", + "C25B 1/46 20060101ALI20201124BHUS", + "C25B 9/10 20060101ALI20201124BHUS", + "C25B 13/08 20060101ALI20201124BHUS", + "H01M 8/083 20160101ALI20201124BHUS" + ], + "cpc": [ + "H01M 8/0693 20130101FI20201124BHUS", + "C25B 1/46 20130101LI20201124BHUS", + "C25B 9/10 20130101LI20201124BHUS", + "C25B 13/08 20130101LI20201124BHUS", + "H01M 8/083 20130101LI20201124BHUS" + ], + "application_number": "15740882", + "current_rank": 3, + "grade": 0, + "notes": "Chloralkali-Verfahren; Brennstoffzelle ist nicht der zentrale Patentgegenstand." + }, + { + "patent_id": "US10847812", + "title": "Separator plate, membrane electrode assembly and fuel cell", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/0221 20160101AFI20201124BHUS", + "H01M 8/0258 20160101ALI20201124BHUS", + "H01M 8/1018 20160101ALI20201124BHUS", + "H01M 8/2418 20160101ALI20201124BHUS", + "H01M 8/0223 20160101ALI20201124BHUS", + "H01M 8/1004 20160101ALI20201124BHUS", + "H01M 8/1011 20160101ALN20201124BHUS", + "H01M 8/14 20060101ALN20201124BHUS", + "H01M 8/0267 20160101ALN20201124BHUS", + "H01M 8/083 20160101ALN20201124BHUS", + "H01M 8/124 20160101ALN20201124BHUS", + "H01M 8/086 20160101ALN20201124BHUS" + ], + "cpc": [ + "H01M 8/0221 20130101FI20201124BHUS", + "H01M 8/0223 20130101LI20201124BHUS", + "H01M 8/0258 20130101LI20201124BHUS", + "H01M 8/1004 20130101LI20201124BHUS", + "H01M 8/1018 20130101LI20201124BHUS", + "H01M 8/2418 20160201LI20201124BHUS", + "H01M 8/0267 20130101LA20201124BHUS", + "H01M 8/083 20130101LA20201124BHUS", + "H01M 8/086 20130101LA20201124BHUS", + "H01M 8/1011 20130101LA20201124BHUS", + "H01M 2008/1095 20130101LA20201124BHUS", + "H01M 2008/1293 20130101LA20201124BHUS", + "H01M 2008/147 20130101LA20201124BHUS" + ], + "application_number": "15852824", + "current_rank": 4, + "grade": 2, + "notes": "Brennstoffzellenkomponenten und Membran-Elektroden-Einheit sind zentral." + }, + { + "patent_id": "EP3549641", + "title": "FUEL TANK INERTING SYSTEM", + "source": "EPO", + "publication_year": "2019", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "A62C 3/06 20060101AFI20190820BHEP", + "A62C 3/08 20060101ALI20190820BHEP", + "A62C 99/00 20100101ALI20190820BHEP", + "B01D 53/32 20060101ALI20190820BHEP", + "H01M 8/00 20160101ALI20190820BHEP", + "H01M 8/083 20160101ALI20190820BHEP" + ], + "cpc": [], + "application_number": "19167279.9", + "current_rank": 5, + "grade": 0, + "notes": "Tank-Inertisierung; Brennstoffzellentechnik ist höchstens eine Teilkomponente." + }, + { + "patent_id": "US10297888", + "title": "Method and system for storing electricity in metals", + "source": "USPTO", + "publication_year": "2019", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 12/08 20060101AFI20190521BHUS", + "H01M 8/083 20160101ALI20190521BHUS", + "H01M 10/48 20060101ALI20190521BHUS", + "H01M 8/04828 20160101ALI20190521BHUS", + "H01M 10/44 20060101ALI20190521BHUS", + "H01M 8/18 20060101ALI20190521BHUS", + "H01M 8/04313 20160101ALI20190521BHUS", + "H01M 8/0444 20160101ALI20190521BHUS", + "H01M 8/04537 20160101ALI20190521BHUS" + ], + "cpc": [ + "H01M 12/08 20130101FI20190521BHUS", + "H01M 8/0444 20130101LI20190521BHUS", + "H01M 8/04537 20130101LI20190521BHUS", + "H01M 10/44 20130101LI20190521BHUS", + "H01M 10/48 20130101LI20190521BHUS", + "Y02E 60/128 20130101LA20190521BHUS" + ], + "application_number": "15053983", + "current_rank": 6, + "grade": 1, + "notes": "Elektrochemische Energiespeicherung mit technischer Nähe zu Brennstoffzellen." + }, + { + "patent_id": "US10096875", + "title": "System and method for increasing electrical efficiency of metal-air cell", + "source": "USPTO", + "publication_year": "2018", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/36 20060101AFI20181009BHUS", + "H01M 12/08 20060101ALI20181009BHUS", + "H01M 2/40 20060101ALI20181009BHUS", + "H01M 8/083 20160101ALI20181009BHUS", + "H01M 12/06 20060101ALI20181009BHUS" + ], + "cpc": [ + "H01M 12/08 20130101FI20181009BHUS", + "H01M 2/40 20130101LI20181009BHUS", + "H01M 8/083 20130101LI20181009BHUS", + "H01M 12/065 20130101LI20181009BHUS", + "H01M 2300/0014 20130101LA20181009BHUS", + "Y02E 60/128 20130101LA20181009BHUS" + ], + "application_number": "14779753", + "current_rank": 7, + "grade": 1, + "notes": "Metall-Luft-Zelle; elektrochemisch verwandt, aber keine klassische Brennstoffzelle." + }, + { + "patent_id": "US10006461", + "title": "Electrolyte circulation in fuel cells stacks with reduced leakage current", + "source": "USPTO", + "publication_year": "2018", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20160101AFI20180626BHUS", + "F04D 13/10 20060101ALI20180626BHUS", + "H01M 8/083 20160101ALI20180626BHUS", + "H01M 8/24 20160101ALI20180626BHUS", + "H01M 8/2485 20160101ALI20180626BHUS", + "H01M 8/04276 20160101ALI20180626BHUS", + "H01M 8/04291 20160101ALI20180626BHUS", + "H01M 8/0289 20160101ALN20180626BHUS" + ], + "cpc": [ + "F04D 13/10 20130101FI20180626BHUS", + "H01M 8/04276 20130101LI20180626BHUS", + "H01M 8/04291 20130101LI20180626BHUS", + "H01M 8/083 20130101LI20180626BHUS", + "H01M 8/2445 20130101LI20180626BHUS", + "H01M 8/2485 20130101LI20180626BHUS", + "H01M 8/0289 20130101LA20180626BHUS" + ], + "application_number": "14402650", + "current_rank": 8, + "grade": 2, + "notes": "Elektrolytzirkulation in Brennstoffzellenstapeln ist zentral." + }, + { + "patent_id": "EP3188296", + "title": "ADJUSTMENT METHOD OF THE ELECTROLYTE COMPOSITION FOR A FUEL CELL SYSTEM", + "source": "EPO", + "publication_year": "2017", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/0656 20160101AFI20170424BHEP", + "C25B 1/04 20060101ALI20170424BHEP", + "H01M 8/083 20160101ALI20170424BHEP", + "H01M 16/00 20060101ALI20170424BHEP", + "H01M 8/04276 20160101ALI20170424BHEP", + "H01M 8/0444 20160101ALI20170424BHEP", + "H01M 8/04791 20160101ALI20170424BHEP" + ], + "cpc": [], + "application_number": "16207072.6", + "current_rank": 9, + "grade": 2, + "notes": "Elektrolytzusammensetzung für ein Brennstoffzellensystem ist zentral." + }, + { + "patent_id": "US09564651", + "title": "Liquid electrolyte fuel cell system", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20160101AFI20170207BHUS", + "H01M 8/04 20160101ALN20170207BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20170207BHUS", + "H01M 8/04164 20130101LI20170207BHUS", + "H01M 8/04276 20130101LI20170207BHUS", + "H01M 8/0485 20130101LA20170207BHUS", + "H01M 2300/0014 20130101LA20170207BHUS", + "Y02E 60/50 20130101LA20170207BHUS" + ], + "application_number": "14370731", + "current_rank": 10, + "grade": 2, + "notes": "Flüssigelektrolyt-Brennstoffzellensystem ist zentral." + }, + { + "patent_id": "US09368819", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20160614BHUS", + "H01M 8/08 20160101ALI20160614BHUS", + "H01M 8/10 20160101ALI20160614BHUS", + "H01M 10/46 20060101ALI20160614BHUS", + "H02J 7/00 20060101ALI20160614BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20160614BHUS", + "H01M 8/0693 20130101LI20160614BHUS", + "H01M 8/083 20130101LI20160614BHUS", + "H01M 8/1002 20130101LI20160614BHUS", + "H01M 10/46 20130101LI20160614BHUS", + "H02J 7/0063 20130101LI20160614BHUS", + "H01M 2300/0014 20130101LA20160614BHUS", + "H01M 2300/0082 20130101LA20160614BHUS" + ], + "application_number": "14957760", + "current_rank": 11, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US09214691", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20151215BHUS", + "H01M 8/08 20060101ALI20151215BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20151215BHUS", + "H01M 8/083 20130101LI20151215BHUS", + "Y02E 60/50 20130101LA20151215BHUS" + ], + "application_number": "14552700", + "current_rank": 12, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US09083025", + "title": "Fuel cell stacks", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/04 20060101AFI20150714BHUS", + "H01M 8/08 20060101ALI20150714BHUS", + "H01M 8/24 20060101ALI20150714BHUS" + ], + "cpc": [ + "H01M 8/08 20130101FI20150714BHUS", + "H01M 8/083 20130101LI20150714BHUS", + "H01M 8/2445 20130101LI20150714BHUS", + "Y02E 60/50 20130101LA20150714BHUS" + ], + "application_number": "13695453", + "current_rank": 13, + "grade": 2, + "notes": "Brennstoffzellenstapel sind zentraler Gegenstand." + }, + { + "patent_id": "US08974984", + "title": "Power generation system using an alkaline fuel cell and fuel gas for alkaline fuel cells used in the system", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/22 20060101AFI20150310BHUS", + "H01M 8/08 20060101ALI20150310BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20150310BHUS", + "H01M 8/222 20130101LI20150310BHUS", + "Y02E 60/50 20130101LA20150310BHUS" + ], + "application_number": "13387130", + "current_rank": 14, + "grade": 2, + "notes": "Stromerzeugung mit alkalischer Brennstoffzelle ist zentral." + }, + { + "patent_id": "US08974983", + "title": "Electrical conductive member and polymer electrolyte fuel cell using the same", + "source": "USPTO", + "publication_year": "2015", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/10 20060101AFI20150310BHUS", + "H01M 8/02 20060101ALI20150310BHUS", + "H01M 8/08 20060101ALN20150310BHUS", + "H01M 8/12 20060101ALN20150310BHUS", + "H01M 8/14 20060101ALN20150310BHUS" + ], + "cpc": [ + "H01M 8/0213 20130101FI20150310BHUS", + "H01M 8/0228 20130101LI20150310BHUS", + "H01M 8/0254 20130101LA20150310BHUS", + "H01M 8/083 20130101LA20150310BHUS", + "H01M 8/086 20130101LA20150310BHUS", + "H01M 2008/1095 20130101LA20150310BHUS", + "H01M 2008/1293 20130101LA20150310BHUS", + "H01M 2008/147 20130101LA20150310BHUS", + "Y02E 60/50 20130101LA20150310BHUS", + "Y02E 60/525 20130101LA20150310BHUS", + "Y02E 60/526 20130101LA20150310BHUS" + ], + "application_number": "13130979", + "current_rank": 15, + "grade": 2, + "notes": "Leitfähiges Bauteil für Polymer-Elektrolyt-Brennstoffzellen ist zentral." + }, + { + "patent_id": "US08895198", + "title": "Systems and methods of securing immunity to air CO2 in alkaline fuel cells", + "source": "USPTO", + "publication_year": "2014", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/06 20060101AFI20141125BHUS", + "H01M 8/08 20060101ALI20141125BHUS" + ], + "cpc": [ + "H01M 8/0668 20130101FI20141125BHUS", + "Y02E 60/50 20130101LA20141125BHUS", + "H01M 8/083 20130101LI20141125BHUS" + ], + "application_number": "12862746", + "current_rank": 16, + "grade": 2, + "notes": "Schutz alkalischer Brennstoffzellen vor CO2 ist zentral." + }, + { + "patent_id": "US08846266", + "title": "Carbohydrate anode for fuel cell and battery applications", + "source": "USPTO", + "publication_year": "2014", + "match_score": 0.9923, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/08 20060101AFI20140930BHUS", + "H01M 8/22 20060101ALI20140930BHUS", + "H01M 4/96 20060101ALI20140930BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20140930BHUS", + "H01M 4/96 20130101LI20140930BHUS", + "H01M 2300/0014 20130101LA20140930BHUS", + "Y02E 60/50 20130101LA20140930BHUS" + ], + "application_number": "12769598", + "current_rank": 17, + "grade": 2, + "notes": "Anode für Brennstoffzellenanwendungen ist zentral." + }, + { + "patent_id": "US12512484", + "title": "Alkaline fuel cell electrode catalyst, alkaline fuel cell, and methods of making and using an electrode catalyst", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 4/90 20060101AFI20251230BHUS", + "H01M 4/88 20060101ALI20251230BHUS", + "H01M 8/083 20160101ALI20251230BHUS", + "H01M 4/86 20060101ALN20251230BHUS" + ], + "cpc": [ + "H01M 4/9016 20130101FI20251230BHUS", + "H01M 4/8882 20130101LI20251230BHUS", + "H01M 8/083 20130101LI20251230BHUS", + "H01M 2004/8689 20130101LA20251230BHUS" + ], + "application_number": "18081485", + "current_rank": 18, + "grade": 2, + "notes": "Elektrodenkatalysator und alkalische Brennstoffzelle sind zentral." + }, + { + "patent_id": "US12412912", + "title": "Electrochemical amine/nitrile redox method for ambient hydrogen storage", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/04082 20160101AFI20250909BHUS", + "H01M 8/04089 20160101ALI20250909BHUS", + "H01M 8/083 20160101ALI20250909BHUS", + "H01M 8/2457 20160101ALI20250909BHUS" + ], + "cpc": [ + "H01M 8/04216 20130101FI20250909BHUS", + "H01M 8/04089 20130101LI20250909BHUS", + "H01M 8/083 20130101LI20250909BHUS", + "H01M 8/2457 20160201LI20250909BHUS", + "H01M 2300/0014 20130101LA20250909BHUS" + ], + "application_number": "17875171", + "current_rank": 19, + "grade": 1, + "notes": "Wasserstoffspeicherung mit Nähe zu Brennstoffzellensystemen, aber nicht zentral." + }, + { + "patent_id": "US12368175", + "title": "Solid oxide fuel cell comprising anode alkaline-based promoter loaded", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.9423, + "ipc_score": 0.9871, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "fuel cell" + ], + "matched_ipc_symbols": [ + "H01M8/083" + ], + "text_retrieval": false, + "ipc": [ + "H01M 8/083 20160101AFI20250722BHUS", + "H01M 4/86 20060101ALI20250722BHUS", + "H01M 4/90 20060101ALI20250722BHUS", + "H01M 8/0217 20160101ALI20250722BHUS", + "H01M 8/12 20160101ALI20250722BHUS", + "H01M 8/1246 20160101ALI20250722BHUS" + ], + "cpc": [ + "H01M 8/083 20130101FI20250722BHUS", + "H01M 4/8621 20130101LI20250722BHUS", + "H01M 4/9033 20130101LI20250722BHUS", + "H01M 8/0217 20130101LI20250722BHUS", + "H01M 8/1246 20130101LI20250722BHUS", + "H01M 2008/1293 20130101LA20250722BHUS" + ], + "application_number": "18659291", + "current_rank": 20, + "grade": 2, + "notes": "Festoxid-Brennstoffzelle ist zentraler Gegenstand." + } + ] + }, + { + "id": "speech-recognition", + "description": "Speech recognition – expected IPC G10L", + "keywords": [ + { + "keyword": "speech recognition", + "keyword_level": "fine", + "topic_id": "https://openalex.org/T10201", + "topic_display_name": "Speech Recognition and Synthesis", + "subfield_name": "Artificial Intelligence", + "field_name": "Computer Science", + "relevance_score": 1.0 + } + ], + "expected_ipc_prefixes": [ + "G10L" + ], + "relevant_patent_ids": [ + "US12137183", + "US11627221", + "US11601548", + "US10742805", + "US09769314", + "US09685159", + "US09377992", + "US09736309", + "US12579986", + "US09369577", + "US12615335", + "US12592239", + "US09571617", + "US12482458", + "US12132865", + "US12088761", + "US11811970", + "US11706338", + "US10863033" + ], + "irrelevant_patent_ids": [ + "US10397400" + ], + "relevance_grades": { + "US12137183": 2, + "US11627221": 2, + "US11601548": 2, + "US10742805": 2, + "US09769314": 2, + "US09685159": 1, + "US09377992": 2, + "US09736309": 2, + "US12579986": 1, + "US10397400": 0, + "US09369577": 1, + "US12615335": 1, + "US12592239": 1, + "US09571617": 1, + "US12482458": 2, + "US12132865": 2, + "US12088761": 2, + "US11811970": 2, + "US11706338": 2, + "US10863033": 2 + }, + "labeling_candidates": [ + { + "patent_id": "US12137183", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20241105BHUS", + "G10L 15/01 20130101ALI20241105BHUS", + "G10L 15/06 20130101ALI20241105BHUS", + "G10L 15/22 20060101ALI20241105BHUS", + "G10L 15/26 20060101ALI20241105BHUS", + "G10L 21/10 20130101ALI20241105BHUS", + "H04M 1/247 20210101ALI20241105BHUS", + "H04M 1/72478 20210101ALI20241105BHUS", + "H04M 3/42 20060101ALI20241105BHUS", + "H04W 4/12 20090101ALI20241105BHUS", + "H04W 4/16 20090101ALI20241105BHUS", + "H04M 3/533 20060101ALN20241105BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20241105BHUS", + "G10L 15/01 20130101LI20241105BHUS", + "G10L 15/06 20130101LI20241105BHUS", + "G10L 15/22 20130101LI20241105BHUS", + "G10L 15/26 20130101LI20241105BHUS", + "G10L 21/10 20130101LI20241105BHUS", + "H04M 1/2475 20130101LI20241105BHUS", + "H04M 1/72478 20210101LI20241105BHUS", + "H04W 4/12 20130101LI20241105BHUS", + "H04W 4/16 20130101LI20241105BHUS", + "H04M 3/53366 20130101LA20241105BHUS", + "H04M 2201/18 20130101LA20241105BHUS", + "H04M 2201/40 20130101LA20241105BHUS", + "H04M 2201/405 20130101LA20241105BHUS" + ], + "application_number": "18123557", + "current_rank": 1, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US11627221", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20230411BHUS", + "H04M 3/42 20060101ALI20230411BHUS", + "G10L 15/06 20130101ALI20230411BHUS", + "G10L 15/22 20060101ALI20230411BHUS", + "H04M 1/247 20210101ALI20230411BHUS", + "H04M 1/72478 20210101ALI20230411BHUS", + "G10L 15/26 20060101ALI20230411BHUS", + "H04W 4/12 20090101ALI20230411BHUS", + "H04W 4/16 20090101ALI20230411BHUS", + "G10L 21/10 20130101ALI20230411BHUS", + "G10L 15/01 20130101ALI20230411BHUS", + "H04M 3/533 20060101ALN20230411BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20230411BHUS", + "G10L 15/01 20130101LI20230411BHUS", + "G10L 15/06 20130101LI20230411BHUS", + "G10L 15/22 20130101LI20230411BHUS", + "G10L 15/26 20130101LI20230411BHUS", + "G10L 21/10 20130101LI20230411BHUS", + "H04M 1/2475 20130101LI20230411BHUS", + "H04M 1/72478 20210101LI20230411BHUS", + "H04W 4/12 20130101LI20230411BHUS", + "H04W 4/16 20130101LI20230411BHUS", + "H04M 3/53366 20130101LA20230411BHUS", + "H04M 2201/18 20130101LA20230411BHUS", + "H04M 2201/40 20130101LA20230411BHUS", + "H04M 2201/405 20130101LA20230411BHUS" + ], + "application_number": "16911691", + "current_rank": 2, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US11601548", + "title": "Captioned telephone services improvement", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/42 20060101AFI20230307BHUS", + "G10L 15/26 20060101ALI20230307BHUS", + "H04M 3/436 20060101ALI20230307BHUS" + ], + "cpc": [ + "H04M 3/42382 20130101FI20230307BHUS", + "G10L 15/26 20130101LI20230307BHUS", + "H04M 3/42391 20130101LI20230307BHUS", + "H04M 3/436 20130101LI20230307BHUS", + "H04M 2201/405 20130101LA20230307BHUS" + ], + "application_number": "17184006", + "current_rank": 3, + "grade": 2, + "notes": "Automatische Transkription für Telefondienste ist zentral." + }, + { + "patent_id": "US10742805", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/42 20060101AFI20200811BHUS", + "G10L 15/06 20130101ALI20200811BHUS", + "G10L 15/22 20060101ALI20200811BHUS", + "H04M 1/247 20060101ALI20200811BHUS", + "H04M 1/725 20060101ALI20200811BHUS", + "G10L 15/26 20060101ALI20200811BHUS", + "H04W 4/12 20090101ALI20200811BHUS", + "H04W 4/16 20090101ALI20200811BHUS", + "G10L 21/10 20130101ALI20200811BHUS", + "G10L 15/01 20130101ALI20200811BHUS", + "H04M 3/533 20060101ALN20200811BHUS" + ], + "cpc": [ + "H04M 3/42391 20130101FI20200811BHUS", + "G10L 15/01 20130101LI20200811BHUS", + "G10L 15/06 20130101LI20200811BHUS", + "G10L 15/22 20130101LI20200811BHUS", + "G10L 15/26 20130101LI20200811BHUS", + "G10L 15/265 20130101LI20200811BHUS", + "G10L 21/10 20130101LI20200811BHUS", + "H04M 1/2475 20130101LI20200811BHUS", + "H04M 1/72591 20130101LI20200811BHUS", + "H04W 4/12 20130101LI20200811BHUS", + "H04W 4/16 20130101LI20200811BHUS", + "H04M 3/53366 20130101LA20200811BHUS", + "H04M 2201/18 20130101LA20200811BHUS", + "H04M 2201/40 20130101LA20200811BHUS", + "H04M 2201/405 20130101LA20200811BHUS" + ], + "application_number": "15477958", + "current_rank": 4, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US09769314", + "title": "Personal voice-based information retrieval system", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20170919BHUS", + "G06F 3/16 20060101ALI20170919BHUS", + "G10L 15/26 20060101ALI20170919BHUS", + "G06F 17/30 20060101ALI20170919BHUS", + "G10L 15/08 20060101ALI20170919BHUS", + "G10L 25/54 20130101ALI20170919BHUS", + "G10L 13/08 20130101ALI20170919BHUS", + "G10L 15/02 20060101ALI20170919BHUS", + "G10L 15/22 20060101ALI20170919BHUS", + "G10L 17/24 20130101ALN20170919BHUS", + "G10L 15/06 20130101ALN20170919BHUS", + "H04L 29/08 20060101ALN20170919BHUS" + ], + "cpc": [ + "H04M 3/4938 20130101FI20170919BHUS", + "G06F 3/167 20130101LI20170919BHUS", + "G06F 17/30769 20130101LI20170919BHUS", + "G06F 17/30861 20130101LI20170919BHUS", + "G10L 13/08 20130101LI20170919BHUS", + "G10L 15/02 20130101LI20170919BHUS", + "G10L 15/08 20130101LI20170919BHUS", + "G10L 15/22 20130101LI20170919BHUS", + "G10L 15/26 20130101LI20170919BHUS", + "G10L 25/54 20130101LI20170919BHUS", + "H04L 67/02 20130101LI20170919BHUS", + "G10L 15/06 20130101LA20170919BHUS", + "G10L 17/24 20130101LA20170919BHUS", + "G10L 2015/223 20130101LA20170919BHUS", + "H04L 29/0809 20130101LA20170919BHUS", + "H04M 2201/39 20130101LA20170919BHUS", + "H04M 2201/40 20130101LA20170919BHUS", + "H04M 2201/405 20130101LA20170919BHUS", + "H04M 2207/40 20130101LA20170919BHUS" + ], + "application_number": "15193517", + "current_rank": 5, + "grade": 2, + "notes": "Sprachbasierte Informationssuche mit Spracherkennung ist zentral." + }, + { + "patent_id": "US09685159", + "title": "Speaker recognition from telephone calls", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/00 20130101AFI20170620BHUS", + "G10L 17/02 20130101ALI20170620BHUS", + "G10L 17/06 20130101ALI20170620BHUS", + "H04M 3/22 20060101ALN20170620BHUS", + "H04M 3/436 20060101ALN20170620BHUS" + ], + "cpc": [ + "G10L 17/00 20130101FI20170620BHUS", + "G10L 17/02 20130101LI20170620BHUS", + "G10L 17/06 20130101LI20170620BHUS", + "H04M 3/2281 20130101LA20170620BHUS", + "H04M 3/436 20130101LA20170620BHUS", + "H04M 2201/405 20130101LA20170620BHUS", + "H04M 2201/41 20130101LA20170620BHUS" + ], + "application_number": "14817182", + "current_rank": 6, + "grade": 1, + "notes": "Sprechererkennung ist eng verwandt, aber nicht klassische Spracherkennung." + }, + { + "patent_id": "US09377992", + "title": "Personal voice-based information retrieval system", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.8634, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G06F 3/16 20060101AFI20160628BHUS", + "G10L 15/26 20060101ALI20160628BHUS", + "G10L 17/24 20130101ALN20160628BHUS", + "G10L 15/06 20130101ALN20160628BHUS", + "H04M 3/493 20060101ALN20160628BHUS", + "H04L 29/08 20060101ALN20160628BHUS" + ], + "cpc": [ + "G06F 3/167 20130101FI20160628BHUS", + "G10L 15/26 20130101LI20160628BHUS", + "G10L 15/06 20130101LA20160628BHUS", + "G10L 17/24 20130101LA20160628BHUS", + "H04L 29/0809 20130101LA20160628BHUS", + "H04M 3/4938 20130101LA20160628BHUS", + "H04M 2201/405 20130101LA20160628BHUS", + "H04M 2207/40 20130101LA20160628BHUS" + ], + "application_number": "12787801", + "current_rank": 7, + "grade": 2, + "notes": "Sprachbasierte Informationssuche mit Spracherkennung ist zentral." + }, + { + "patent_id": "US09736309", + "title": "Real-time transcription and interaction with a caller based on the transcription", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.862, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 1.0, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 1/64 20060101AFI20170815BHUS", + "H04M 3/527 20060101ALI20170815BHUS", + "G10L 15/26 20060101ALI20170815BHUS", + "G10L 13/08 20130101ALI20170815BHUS", + "G10L 15/30 20130101ALI20170815BHUS" + ], + "cpc": [ + "H04M 3/527 20130101FI20170815BHUS", + "G10L 13/08 20130101LI20170815BHUS", + "G10L 15/26 20130101LI20170815BHUS", + "G10L 15/30 20130101LI20170815BHUS", + "H04M 2201/39 20130101LA20170815BHUS", + "H04M 2201/40 20130101LA20170815BHUS", + "H04M 2201/60 20130101LA20170815BHUS" + ], + "application_number": "15241555", + "current_rank": 8, + "grade": 2, + "notes": "Echtzeit-Transkription gesprochener Sprache ist zentral." + }, + { + "patent_id": "US12579986", + "title": "Systems and methods for distinguishing between human speech and machine generated speech", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/14 20130101AFI20260317BHUS", + "G06F 40/30 20200101ALI20260317BHUS", + "G10L 15/26 20060101ALI20260317BHUS", + "G10L 17/00 20130101ALI20260317BHUS", + "G10L 17/02 20130101ALI20260317BHUS", + "G10L 17/22 20130101ALI20260317BHUS", + "G10L 17/26 20130101ALI20260317BHUS", + "H04M 3/51 20060101ALI20260317BHUS" + ], + "cpc": [ + "G10L 17/14 20130101FI20260317BHUS", + "G06F 40/30 20200101LI20260317BHUS", + "G10L 15/26 20130101LI20260317BHUS", + "G10L 17/00 20130101LI20260317BHUS", + "G10L 17/02 20130101LI20260317BHUS", + "G10L 17/22 20130101LI20260317BHUS", + "H04M 3/5166 20130101LI20260317BHUS" + ], + "application_number": "18602835", + "current_rank": 9, + "grade": 1, + "notes": "Klassifikation menschlicher und synthetischer Sprache ist fachlich angrenzend." + }, + { + "patent_id": "US10397400", + "title": "Electronic call assistant based on a caller-status and a callee-status", + "source": "USPTO", + "publication_year": "2019", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20190827BHUS", + "G10L 17/14 20130101ALI20190827BHUS", + "A61B 5/00 20060101ALN20190827BHUS", + "G10L 15/26 20060101ALN20190827BHUS" + ], + "cpc": [ + "H04M 3/493 20130101FI20190827BHUS", + "G10L 17/14 20130101LI20190827BHUS", + "H04M 3/4936 20130101LI20190827BHUS", + "A61B 5/6802 20130101LA20190827BHUS", + "G10L 15/265 20130101LA20190827BHUS", + "H04M 2201/405 20130101LA20190827BHUS" + ], + "application_number": "15802695", + "current_rank": 10, + "grade": 0, + "notes": "Allgemeiner elektronischer Anrufassistent; Spracherkennung ist nicht zentral." + }, + { + "patent_id": "US09369577", + "title": "Transparent voice registration and verification method and system", + "source": "USPTO", + "publication_year": "2016", + "match_score": 0.8285, + "ipc_score": 0.8808, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "G10L17/14" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/493 20060101AFI20160614BHUS", + "G10L 17/14 20130101ALI20160614BHUS", + "H04M 3/42 20060101ALI20160614BHUS", + "H04M 3/51 20060101ALI20160614BHUS", + "H04M 3/38 20060101ALI20160614BHUS", + "G10L 17/04 20130101ALN20160614BHUS" + ], + "cpc": [ + "H04M 3/4936 20130101FI20160614BHUS", + "G10L 17/14 20130101LI20160614BHUS", + "H04M 3/385 20130101LI20160614BHUS", + "H04M 3/42221 20130101LI20160614BHUS", + "H04M 3/51 20130101LI20160614BHUS", + "G10L 17/04 20130101LA20160614BHUS", + "H04M 2201/36 20130101LA20160614BHUS", + "H04M 2201/41 20130101LA20160614BHUS", + "H04M 2203/6045 20130101LA20160614BHUS" + ], + "application_number": "14526933", + "current_rank": 11, + "grade": 1, + "notes": "Stimmregistrierung und Sprecherverifikation sind fachlich angrenzend." + }, + { + "patent_id": "US12615335", + "title": "Voice fingerprinting system for detecting hoax emergency reports", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/00 20130101AFI20260428BHUS", + "G10L 17/02 20130101ALI20260428BHUS", + "G10L 17/04 20130101ALI20260428BHUS", + "G10L 17/06 20130101ALI20260428BHUS", + "G10L 17/18 20130101ALI20260428BHUS", + "G10L 25/18 20130101ALI20260428BHUS", + "G10L 25/24 20130101ALI20260428BHUS", + "H04M 3/22 20060101ALI20260428BHUS", + "H04M 3/51 20060101ALI20260428BHUS", + "G06Q 50/26 20120101ALN20260428BHUS" + ], + "cpc": [ + "H04M 3/5116 20130101FI20260428BHUS", + "G10L 17/02 20130101LI20260428BHUS", + "G10L 17/04 20130101LI20260428BHUS", + "G10L 17/06 20130101LI20260428BHUS", + "G10L 17/18 20130101LI20260428BHUS", + "G10L 25/18 20130101LI20260428BHUS", + "G10L 25/24 20130101LI20260428BHUS", + "H04M 3/2281 20130101LI20260428BHUS", + "H04M 3/5175 20130101LI20260428BHUS", + "H04M 3/5191 20130101LI20260428BHUS", + "G06Q 50/265 20130101LA20260428BHUS", + "H04M 2201/405 20130101LA20260428BHUS" + ], + "application_number": "18732780", + "current_rank": 12, + "grade": 1, + "notes": "Voice-Fingerprinting und Sprechererkennung sind fachlich angrenzend." + }, + { + "patent_id": "US12592239", + "title": "Active voice liveness detection system", + "source": "USPTO", + "publication_year": "2026", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 17/26 20130101AFI20260331BHUS", + "G06F 21/32 20130101ALI20260331BHUS", + "G10L 15/02 20060101ALI20260331BHUS", + "G10L 17/00 20130101ALI20260331BHUS", + "G10L 17/02 20130101ALI20260331BHUS", + "G10L 17/04 20130101ALI20260331BHUS", + "G10L 17/08 20130101ALI20260331BHUS", + "G10L 17/18 20130101ALI20260331BHUS", + "G10L 25/30 20130101ALI20260331BHUS", + "G10L 25/51 20130101ALI20260331BHUS", + "G10L 25/60 20130101ALI20260331BHUS", + "H04M 3/22 20060101ALI20260331BHUS", + "H04M 3/42 20060101ALI20260331BHUS", + "H04M 3/51 20060101ALI20260331BHUS" + ], + "cpc": [ + "G10L 17/26 20130101FI20260331BHUS", + "G06F 21/32 20130101LI20260331BHUS", + "G10L 15/02 20130101LI20260331BHUS", + "G10L 17/00 20130101LI20260331BHUS", + "G10L 17/02 20130101LI20260331BHUS", + "G10L 17/04 20130101LI20260331BHUS", + "G10L 17/08 20130101LI20260331BHUS", + "G10L 17/18 20130101LI20260331BHUS", + "G10L 25/51 20130101LI20260331BHUS", + "G10L 25/60 20130101LI20260331BHUS", + "H04M 3/2281 20130101LI20260331BHUS", + "H04M 3/42221 20130101LI20260331BHUS", + "H04M 3/5175 20130101LI20260331BHUS", + "H04M 3/5183 20130101LI20260331BHUS", + "G10L 25/30 20130101LA20260331BHUS", + "H04M 2201/405 20130101LA20260331BHUS" + ], + "application_number": "18646310", + "current_rank": 13, + "grade": 1, + "notes": "Voice-Liveness-Erkennung ist biometrisch verwandt, aber keine klassische Spracherkennung." + }, + { + "patent_id": "US09571617", + "title": "Controlling mute function on telephone", + "source": "USPTO", + "publication_year": "2017", + "match_score": 0.8134, + "ipc_score": 0.8556, + "topic_score": 1.0, + "text_score": 0.3333333333333333, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/00 20060101AFI20170214BHUS", + "H04M 1/19 20060101ALI20170214BHUS", + "H04M 1/247 20060101ALI20170214BHUS", + "G10L 15/22 20060101ALI20170214BHUS", + "G10L 17/04 20130101ALI20170214BHUS", + "G10L 17/06 20130101ALI20170214BHUS", + "G10L 25/84 20130101ALI20170214BHUS", + "H04M 1/60 20060101ALN20170214BHUS" + ], + "cpc": [ + "H04M 1/19 20130101FI20170214BHUS", + "G10L 15/22 20130101LI20170214BHUS", + "G10L 17/04 20130101LI20170214BHUS", + "G10L 17/06 20130101LI20170214BHUS", + "G10L 25/84 20130101LI20170214BHUS", + "H04M 1/247 20130101LI20170214BHUS", + "H04M 1/6033 20130101LI20170214BHUS", + "G10L 2015/223 20130101LA20170214BHUS", + "H04M 1/6008 20130101LA20170214BHUS", + "H04M 2201/405 20130101LA20170214BHUS", + "H04M 2203/258 20130101LA20170214BHUS", + "H04M 2250/74 20130101LA20170214BHUS" + ], + "application_number": "15168757", + "current_rank": 14, + "grade": 1, + "notes": "Sprachgesteuerte Stummschaltung; Spracherkennung ist eine relevante Teilfunktion." + }, + { + "patent_id": "US12482458", + "title": "Semiautomated relay method and apparatus", + "source": "USPTO", + "publication_year": "2025", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "G10L 15/183 20130101AFI20251125BHUS", + "G10L 15/26 20060101ALI20251125BHUS", + "G10L 25/60 20130101ALI20251125BHUS", + "H04M 1/247 20210101ALI20251125BHUS", + "H04M 1/72433 20210101ALI20251125BHUS", + "H04M 1/72478 20210101ALI20251125BHUS", + "H04M 3/42 20060101ALI20251125BHUS" + ], + "cpc": [ + "G10L 15/183 20130101FI20251125BHUS", + "G10L 15/26 20130101LI20251125BHUS", + "G10L 25/60 20130101LI20251125BHUS", + "H04M 1/2475 20130101LI20251125BHUS", + "H04M 1/72433 20210101LI20251125BHUS", + "H04M 1/72478 20210101LI20251125BHUS", + "H04M 3/42391 20130101LI20251125BHUS", + "H04M 2201/40 20130101LA20251125BHUS", + "H04M 2201/60 20130101LA20251125BHUS" + ], + "application_number": "16422662", + "current_rank": 15, + "grade": 2, + "notes": "Spracherkennung und Transkription im Relay-System sind zentral." + }, + { + "patent_id": "US12132865", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20241029BHUS", + "G06F 40/205 20200101ALI20241029BHUS", + "G10L 17/04 20130101ALI20241029BHUS", + "G10L 17/08 20130101ALI20241029BHUS", + "G10L 25/51 20130101ALI20241029BHUS", + "G10L 25/63 20130101ALI20241029BHUS", + "G10L 25/87 20130101ALI20241029BHUS", + "H04M 3/42 20060101ALI20241029BHUS", + "G10L 15/26 20060101ALN20241029BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20241029BHUS", + "G06F 40/205 20200101LI20241029BHUS", + "G10L 17/04 20130101LI20241029BHUS", + "G10L 17/08 20130101LI20241029BHUS", + "G10L 25/51 20130101LI20241029BHUS", + "G10L 25/63 20130101LI20241029BHUS", + "H04M 3/42 20130101LI20241029BHUS", + "G10L 15/26 20130101LA20241029BHUS", + "G10L 25/87 20130101LA20241029BHUS", + "H04M 2201/40 20130101LA20241029BHUS", + "H04M 2201/41 20130101LA20241029BHUS", + "H04M 2203/40 20130101LA20241029BHUS", + "H04M 2203/401 20130101LA20241029BHUS" + ], + "application_number": "18376605", + "current_rank": 16, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US12088761", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2024", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20240910BHUS", + "G06F 40/205 20200101ALI20240910BHUS", + "G10L 15/26 20060101ALI20240910BHUS", + "G10L 17/04 20130101ALI20240910BHUS", + "G10L 17/08 20130101ALI20240910BHUS", + "G10L 25/51 20130101ALI20240910BHUS", + "G10L 25/63 20130101ALI20240910BHUS", + "G10L 25/87 20130101ALI20240910BHUS", + "H04M 3/42 20060101ALI20240910BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20240910BHUS", + "G06F 40/205 20200101LI20240910BHUS", + "G10L 17/04 20130101LI20240910BHUS", + "G10L 17/08 20130101LI20240910BHUS", + "G10L 25/51 20130101LI20240910BHUS", + "G10L 25/63 20130101LI20240910BHUS", + "H04M 3/42 20130101LI20240910BHUS", + "G10L 15/26 20130101LA20240910BHUS", + "G10L 25/87 20130101LA20240910BHUS", + "H04M 2201/40 20130101LA20240910BHUS", + "H04M 2201/41 20130101LA20240910BHUS", + "H04M 2203/40 20130101LA20240910BHUS", + "H04M 2203/401 20130101LA20240910BHUS" + ], + "application_number": "18203094", + "current_rank": 17, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US11811970", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20231107BHUS", + "G10L 17/04 20130101ALI20231107BHUS", + "G10L 25/51 20130101ALI20231107BHUS", + "G10L 25/63 20130101ALI20231107BHUS", + "G10L 25/87 20130101ALI20231107BHUS", + "H04M 3/42 20060101ALI20231107BHUS", + "G06F 40/205 20200101ALI20231107BHUS", + "G10L 17/08 20130101ALI20231107BHUS", + "G10L 15/26 20060101ALN20231107BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20231107BHUS", + "G06F 40/205 20200101LI20231107BHUS", + "G10L 17/04 20130101LI20231107BHUS", + "G10L 17/08 20130101LI20231107BHUS", + "G10L 25/51 20130101LI20231107BHUS", + "G10L 25/63 20130101LI20231107BHUS", + "H04M 3/42 20130101LI20231107BHUS", + "G10L 15/26 20130101LA20231107BHUS", + "G10L 25/87 20130101LA20231107BHUS", + "H04M 2201/40 20130101LA20231107BHUS", + "H04M 2201/41 20130101LA20231107BHUS", + "H04M 2203/40 20130101LA20231107BHUS", + "H04M 2203/401 20130101LA20231107BHUS" + ], + "application_number": "17690099", + "current_rank": 18, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US11706338", + "title": "Voice and speech recognition for call center feedback and quality assurance", + "source": "USPTO", + "publication_year": "2023", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 3/51 20060101AFI20230718BHUS", + "G10L 17/04 20130101ALI20230718BHUS", + "G10L 25/51 20130101ALI20230718BHUS", + "G10L 25/63 20130101ALI20230718BHUS", + "G10L 25/87 20130101ALI20230718BHUS", + "H04M 3/42 20060101ALI20230718BHUS", + "G06F 40/205 20200101ALI20230718BHUS", + "G10L 17/08 20130101ALI20230718BHUS", + "G10L 15/26 20060101ALN20230718BHUS" + ], + "cpc": [ + "H04M 3/5175 20130101FI20230718BHUS", + "G06F 40/205 20200101LI20230718BHUS", + "G10L 17/04 20130101LI20230718BHUS", + "G10L 17/08 20130101LI20230718BHUS", + "G10L 25/51 20130101LI20230718BHUS", + "G10L 25/63 20130101LI20230718BHUS", + "H04M 3/42 20130101LI20230718BHUS", + "G10L 15/26 20130101LA20230718BHUS", + "G10L 25/87 20130101LA20230718BHUS", + "H04M 2201/40 20130101LA20230718BHUS", + "H04M 2201/41 20130101LA20230718BHUS", + "H04M 2203/40 20130101LA20230718BHUS", + "H04M 2203/401 20130101LA20230718BHUS" + ], + "application_number": "17472557", + "current_rank": 19, + "grade": 2, + "notes": "Sprach- und Sprecherkennung für Callcenter-Analyse sind zentral." + }, + { + "patent_id": "US10863033", + "title": "Voice recognition system and voice recognition method", + "source": "USPTO", + "publication_year": "2020", + "match_score": 0.812, + "ipc_score": 0.77, + "topic_score": 1.0, + "text_score": 0.6666666666666666, + "topic_match_kind": "topic_id", + "matched_keywords": [ + "speech recognition" + ], + "matched_ipc_symbols": [ + "H04M2201/405" + ], + "text_retrieval": false, + "ipc": [ + "H04M 11/00 20060101AFI20201208BHUS", + "H04M 3/58 20060101ALI20201208BHUS", + "H04M 3/493 20060101ALI20201208BHUS", + "G10L 17/22 20130101ALI20201208BHUS", + "H04M 3/42 20060101ALI20201208BHUS", + "G10L 15/22 20060101ALI20201208BHUS" + ], + "cpc": [ + "H04M 3/58 20130101FI20201208BHUS", + "G10L 15/22 20130101LI20201208BHUS", + "G10L 17/22 20130101LI20201208BHUS", + "H04M 3/42221 20130101LI20201208BHUS", + "H04M 3/4931 20130101LI20201208BHUS", + "H04M 3/4936 20130101LI20201208BHUS", + "G10L 2015/223 20130101LA20201208BHUS", + "H04M 3/4933 20130101LA20201208BHUS", + "H04M 2201/18 20130101LA20201208BHUS", + "H04M 2201/39 20130101LA20201208BHUS", + "H04M 2201/40 20130101LA20201208BHUS" + ], + "application_number": "16432362", + "current_rank": 20, + "grade": 2, + "notes": "Sprach- und Stimmerkennung sind zentraler Gegenstand." + } + ] + } + ] +} \ No newline at end of file diff --git a/service/scripts/patents/evaluate_keyword_patent_search.py b/service/scripts/patents/evaluate_keyword_patent_search.py new file mode 100644 index 00000000..550876db --- /dev/null +++ b/service/scripts/patents/evaluate_keyword_patent_search.py @@ -0,0 +1,1147 @@ +#!/usr/bin/env python3 +""" +evaluate_keyword_patent_search.py — Systematic evaluation for keyword → patent search. + +Modes: + bootstrap Run live search for each gold case and write labeling candidates. + eval Score ranked results against gold labels (+ IPC proxy metrics). + ablation Re-score labeled rankings under alternate IPC/topic/text weights. + +Usage (from service/): + python scripts/patents/evaluate_keyword_patent_search.py bootstrap + python scripts/patents/evaluate_keyword_patent_search.py eval + python scripts/patents/evaluate_keyword_patent_search.py ablation + +Requires PATENT_ELASTICSEARCH credentials in src/main/inse/.env for live search. +After bootstrap, fill relevant_patent_ids / relevance_grades in the gold set +(or in the generated labeling JSON) and re-run eval. +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import sys +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +current_dir = Path(__file__).resolve().parent +sys.path.insert(0, str(current_dir.parent.parent / "src" / "main")) + +from inse.patents.keywords.eval_metrics import ( # noqa: E402 + analyze_family_duplicates_in_top_k, + average_precision, + ipc_prefix_hit_rate, + mean, + mrr, + ndcg_at_k, + normalize_patent_id, + patent_family_key, + precision_at_k, + recall_at_k, + unique_family_precision_at_k, +) +from inse.patents.keywords.logic import ( # noqa: E402 + _DEFAULT_SCORE_WEIGHTS, + _MAX_PATENTS, + _compute_final_score, + get_patents_by_keywords, +) +from inse.patents.keywords.model import ( # noqa: E402 + KeywordPatentMatch, + KeywordPatentSearchDiagnostics, + KeywordPatentSearchItem, + PatentsByKeywordsRequest, +) + +logger = logging.getLogger(__name__) + +DEFAULT_GOLDSET = current_dir / "data" / "keyword_patent_goldset_presentation.json" +DEFAULT_OUT_DIR = current_dir / "data" / "eval_runs" +LITHIUM_CASE_PREFIX = "lithium-ion-batteries" +IPC_FOCUS_CASES = {"materials-chemistry"} | { + f"{LITHIUM_CASE_PREFIX}-de", + f"{LITHIUM_CASE_PREFIX}-en", + f"{LITHIUM_CASE_PREFIX}-de-en", +} + + +def _is_lithium_case(case_id: str) -> bool: + return case_id.startswith(LITHIUM_CASE_PREFIX) + + +def _family_key_from_match(match: KeywordPatentMatch) -> str: + return patent_family_key( + patent_id=match.patent.patent_id, + application_number=match.patent.application_number, + title=match.patent.title, + ) + + +def _family_metrics( + matches: list[KeywordPatentMatch], + ks: list[int], + grades: dict[str, float] | None = None, +) -> dict[str, Any]: + ranked_ids = [match.patent.patent_id for match in matches] + family_keys = [_family_key_from_match(match) for match in matches] + duplicates = { + f"@{k}": analyze_family_duplicates_in_top_k(family_keys, k) for k in ks + } + payload: dict[str, Any] = {"family_duplicates": duplicates} + if grades: + relevant_ids = list(grades.keys()) + payload["unique_family_precision"] = { + f"@{k}": round( + unique_family_precision_at_k(ranked_ids, family_keys, relevant_ids, k), + 4, + ) + for k in ks + } + return payload + + +def _load_json(path: Path) -> dict[str, Any]: + with path.open(encoding="utf-8") as handle: + return json.load(handle) + + +def _write_json(path: Path, payload: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + json.dump(payload, handle, indent=2, ensure_ascii=False) + handle.write("\n") + + +def _keyword_items(case: dict[str, Any]) -> list[KeywordPatentSearchItem]: + return [KeywordPatentSearchItem.model_validate(item) for item in case["keywords"]] + + +def _patent_codes(match: KeywordPatentMatch) -> list[str]: + return [*match.patent.ipc, *match.patent.cpc] + + +def _match_to_dict(match: KeywordPatentMatch) -> dict[str, Any]: + payload: dict[str, Any] = { + "patent_id": match.patent.patent_id, + "title": match.patent.title, + "source": match.patent.source, + "publication_year": match.patent.publication_year, + "match_score": match.match_score, + "ipc_score": match.ipc_score, + "topic_score": match.topic_score, + "text_score": match.text_score, + "topic_match_kind": match.topic_match_kind, + "matched_keywords": match.matched_keywords, + "matched_ipc_symbols": match.matched_ipc_symbols, + "text_retrieval": match.text_retrieval, + "ipc": match.patent.ipc, + "cpc": match.patent.cpc, + "application_number": match.patent.application_number, + } + if match.keyword_evidence is not None: + payload["keyword_evidence"] = match.keyword_evidence.model_dump() + return payload + + +def _relevance_for_case(case: dict[str, Any]) -> dict[str, float]: + grades: dict[str, float] = {} + for patent_id, grade in (case.get("relevance_grades") or {}).items(): + grades[normalize_patent_id(patent_id)] = float(grade) + for patent_id in case.get("relevant_patent_ids") or []: + grades.setdefault(normalize_patent_id(patent_id), 1.0) + return {pid: grade for pid, grade in grades.items() if grade > 0} + + +def _proxy_metrics( + matches: list[KeywordPatentMatch], + case: dict[str, Any], + ks: list[int], + *, + mapping_status: str | None = None, +) -> dict[str, Any]: + ipc_lists = [_patent_codes(match) for match in matches] + prefixes = case.get("expected_ipc_prefixes") or [] + topic_rates = [] + text_rates = [] + for k in ks: + top = matches[:k] + if not top: + topic_rates.append(0.0) + text_rates.append(0.0) + continue + topic_rates.append(sum(1 for m in top if m.topic_score > 0) / len(top)) + text_rates.append(sum(1 for m in top if m.text_score > 0) / len(top)) + + text_path = mapping_status in {"uncertain", "no_mapping"} or any( + m.text_retrieval for m in matches[:10] + ) + ipc_hit = { + f"@{k}": round(ipc_prefix_hit_rate(ipc_lists, prefixes, k=k), 4) for k in ks + } + payload: dict[str, Any] = { + "retrieved": len(matches), + "ipc_prefix_hit_rate": ipc_hit, + "topic_score_rate": {f"@{k}": round(rate, 4) for k, rate in zip(ks, topic_rates)}, + "text_score_rate": {f"@{k}": round(rate, 4) for k, rate in zip(ks, text_rates)}, + "mean_match_score_at_10": round( + mean([m.match_score for m in matches[:10]]), + 4, + ), + "family_metrics": _family_metrics(matches, ks), + } + watch_prefixes = case.get("ipc_cluster_watch_prefixes") or [] + if watch_prefixes: + payload["ipc_cluster_watch_hit_rate"] = { + f"@{k}": round(ipc_prefix_hit_rate(ipc_lists, watch_prefixes, k=k), 4) + for k in ks + } + payload["ipc_cluster_watch_prefixes"] = list(watch_prefixes) + payload["ipc_cluster_watch_note"] = ( + "Separate analysis for notable mapping cluster; " + "not counted toward expected_ipc_prefixes battery proxy." + ) + if prefixes: + payload["expected_ipc_prefixes"] = list(prefixes) + if text_path: + payload["ipc_prefix_hit_rate_role"] = "post_hoc_plausibility_only" + payload["ipc_prefix_hit_rate_note"] = ( + "ipc_hit@k is a post-hoc plausibility check on patent classifications " + "after keyword text retrieval; IPC was not used to retrieve these results." + ) + else: + payload["ipc_prefix_hit_rate_role"] = "retrieval_aligned" + return payload + + +def _label_metrics( + ranked_ids: list[str], + grades: dict[str, float], + ks: list[int], +) -> dict[str, Any] | None: + if not grades: + return None + relevant_ids = list(grades.keys()) + family_keys = [ + patent_family_key(patent_id=pid, application_number=None, title=None) + for pid in ranked_ids + ] + return { + "labeled_relevant": len(relevant_ids), + "precision": {f"@{k}": round(precision_at_k(ranked_ids, relevant_ids, k), 4) for k in ks}, + "unique_family_precision": { + f"@{k}": round( + unique_family_precision_at_k(ranked_ids, family_keys, relevant_ids, k), + 4, + ) + for k in ks + }, + "recall": {f"@{k}": round(recall_at_k(ranked_ids, relevant_ids, k), 4) for k in ks}, + "ndcg": {f"@{k}": round(ndcg_at_k(ranked_ids, grades, k), 4) for k in ks}, + "map": round(average_precision(ranked_ids, relevant_ids), 4), + "mrr": round(mrr(ranked_ids, relevant_ids), 4), + } + + +def _label_metrics_for_matches( + matches: list[KeywordPatentMatch], + grades: dict[str, float], + ks: list[int], +) -> dict[str, Any] | None: + if not grades: + return None + ranked_ids = [match.patent.patent_id for match in matches] + family_keys = [_family_key_from_match(match) for match in matches] + relevant_ids = list(grades.keys()) + return { + "labeled_relevant": len(relevant_ids), + "precision": { + f"@{k}": round(precision_at_k(ranked_ids, relevant_ids, k), 4) for k in ks + }, + "unique_family_precision": { + f"@{k}": round( + unique_family_precision_at_k(ranked_ids, family_keys, relevant_ids, k), + 4, + ) + for k in ks + }, + "recall": {f"@{k}": round(recall_at_k(ranked_ids, relevant_ids, k), 4) for k in ks}, + "ndcg": {f"@{k}": round(ndcg_at_k(ranked_ids, grades, k), 4) for k in ks}, + "map": round(average_precision(ranked_ids, relevant_ids), 4), + "mrr": round(mrr(ranked_ids, relevant_ids), 4), + } + + +def _split_label_metrics( + matches: list[KeywordPatentMatch], + grades: dict[str, float], + ks: list[int], +) -> dict[str, Any]: + ipc_matches = [m for m in matches if not m.text_retrieval] + text_matches = [m for m in matches if m.text_retrieval] + return { + "overall": _label_metrics_for_matches(matches, grades, ks), + "ipc_path": { + "retrieved": len(ipc_matches), + "metrics": _label_metrics_for_matches(ipc_matches, grades, ks), + }, + "text_path": { + "retrieved": len(text_matches), + "metrics": _label_metrics_for_matches(text_matches, grades, ks), + }, + } + + +def _diagnostics_dict( + diagnostics: KeywordPatentSearchDiagnostics | None, +) -> dict[str, Any] | None: + if diagnostics is None: + return None + return diagnostics.model_dump() + + +def _aggregate(case_reports: list[dict[str, Any]], ks: list[int]) -> dict[str, Any]: + labeled = [report for report in case_reports if report.get("label_metrics")] + proxy_only = case_reports + + def avg_nested(key: str, metric: str) -> dict[str, float]: + out: dict[str, float] = {} + for k in ks: + values = [ + report[key][metric][f"@{k}"] + for report in (labeled if key == "label_metrics" else proxy_only) + if report.get(key) and f"@{k}" in report[key].get(metric, {}) + ] + out[f"@{k}"] = round(mean(values), 4) + return out + + def avg_path_metric(path_key: str, metric: str) -> dict[str, float]: + out: dict[str, float] = {} + for k in ks: + values = [] + for report in case_reports: + path = (report.get("label_metrics_split") or {}).get(path_key) or {} + metrics = path.get("metrics") or {} + if metrics and f"@{k}" in metrics.get(metric, {}): + values.append(metrics[metric][f"@{k}"]) + out[f"@{k}"] = round(mean(values), 4) if values else 0.0 + return out + + summary: dict[str, Any] = { + "cases_total": len(case_reports), + "cases_labeled": len(labeled), + "proxy": { + "ipc_prefix_hit_rate": avg_nested("proxy_metrics", "ipc_prefix_hit_rate"), + "topic_score_rate": avg_nested("proxy_metrics", "topic_score_rate"), + "text_score_rate": avg_nested("proxy_metrics", "text_score_rate"), + }, + } + if labeled: + summary["labels"] = { + "precision": avg_nested("label_metrics", "precision"), + "recall": avg_nested("label_metrics", "recall"), + "ndcg": avg_nested("label_metrics", "ndcg"), + "map": round(mean([r["label_metrics"]["map"] for r in labeled]), 4), + "mrr": round(mean([r["label_metrics"]["mrr"] for r in labeled]), 4), + "by_path": { + "ipc_path": { + "precision": avg_path_metric("ipc_path", "precision"), + "recall": avg_path_metric("ipc_path", "recall"), + "ndcg": avg_path_metric("ipc_path", "ndcg"), + }, + "text_path": { + "precision": avg_path_metric("text_path", "precision"), + "recall": avg_path_metric("text_path", "recall"), + "ndcg": avg_path_metric("text_path", "ndcg"), + }, + }, + } + return summary + + +def _ipc_clusters_for_report(diagnostics: dict[str, Any] | None) -> list[dict[str, Any]]: + return [ + { + "topic_key": selection.get("topic_key"), + "subclass": selection.get("subclass"), + "symbol": selection.get("symbol"), + "relative_mass": selection.get("relative_mass"), + } + for selection in (diagnostics or {}).get("ipc_cluster_selections") or [] + ] + + +def _top10_for_presentation(matches: list[KeywordPatentMatch]) -> list[dict[str, Any]]: + rows: list[dict[str, Any]] = [] + for match in matches[:10]: + rows.append( + { + "patent_id": match.patent.patent_id, + "title": match.patent.title, + "match_score": round(match.match_score, 4), + "ipc_score": round(match.ipc_score, 4), + "matched_ipc_symbols": list(match.matched_ipc_symbols), + } + ) + return rows + + +def _presentation_case_report( + case: dict[str, Any], + matches: list[KeywordPatentMatch], + mapping_status: str, + diagnostics: KeywordPatentSearchDiagnostics | None, + grades: dict[str, float], + ks: list[int], +) -> dict[str, Any]: + labels = _label_metrics_for_matches(matches, grades, ks) + proxy = _proxy_metrics( + matches, + case, + ks, + mapping_status=mapping_status, + ) + diagnostics_payload = _diagnostics_dict(diagnostics) + report: dict[str, Any] = { + "case_id": case["id"], + "mapping_status": mapping_status, + "search_path": (diagnostics_payload or {}).get("search_path"), + "ipc_cluster_selections": _ipc_clusters_for_report(diagnostics_payload), + "ipc_hit": proxy.get("ipc_prefix_hit_rate", {}), + "top_10": _top10_for_presentation(matches), + } + if labels: + report["precision"] = labels["precision"] + report["recall"] = labels["recall"] + report["ndcg"] = labels["ndcg"] + report["map"] = labels["map"] + report["mrr"] = labels["mrr"] + return report + + +def _presentation_aggregate( + case_reports: list[dict[str, Any]], + ks: list[int], +) -> dict[str, Any]: + labeled = [report for report in case_reports if report.get("precision")] + + def avg_at_k(metric: str) -> dict[str, float | None]: + out: dict[str, float | None] = {} + for k in ks: + values = [ + report[metric][f"@{k}"] + for report in labeled + if report.get(metric) and f"@{k}" in report[metric] + ] + out[f"@{k}"] = round(mean(values), 4) if values else None + return out + + def avg_scalar(metric: str) -> float | None: + values = [report[metric] for report in labeled if report.get(metric) is not None] + return round(mean(values), 4) if values else None + + ipc_values: dict[str, list[float]] = {f"@{k}": [] for k in ks} + for report in case_reports: + ipc_hit = report.get("ipc_hit") or {} + for k in ks: + key = f"@{k}" + if key in ipc_hit: + ipc_values[key].append(float(ipc_hit[key])) + + return { + "cases_total": len(case_reports), + "cases_labeled": len(labeled), + "precision": avg_at_k("precision"), + "recall": avg_at_k("recall"), + "ndcg": avg_at_k("ndcg"), + "map": avg_scalar("map"), + "mrr": avg_scalar("mrr"), + "ipc_hit": { + key: round(mean(values), 4) if values else None + for key, values in ipc_values.items() + }, + } + + +def _print_presentation_case(report: dict[str, Any], ks: list[int]) -> None: + print(f"\n=== {report['case_id']} ===") + print(f" mapping_status: {report.get('mapping_status')}") + print(f" search_path: {report.get('search_path')}") + print(" ipc_cluster_selections:") + for selection in report.get("ipc_cluster_selections") or []: + print( + " " + f"{selection.get('subclass')} {selection.get('symbol')} " + f"relative_mass={selection.get('relative_mass')}" + ) + ipc_hit = report.get("ipc_hit") or {} + print( + " ipc_hit: " + + " ".join(f"@{k}={ipc_hit.get(f'@{k}')}" for k in ks) + ) + if report.get("precision"): + print( + " precision: " + + " ".join(f"@{k}={report['precision'].get(f'@{k}')}" for k in ks) + ) + print( + " recall: " + + " ".join(f"@{k}={report['recall'].get(f'@{k}')}" for k in ks) + ) + print( + " ndcg: " + + " ".join(f"@{k}={report['ndcg'].get(f'@{k}')}" for k in ks) + ) + print(f" MAP: {report.get('map')} MRR: {report.get('mrr')}") + else: + print(" (no relevance labels — IPC proxy and top_10 only)") + print(" top_10:") + for rank, row in enumerate(report.get("top_10") or [], start=1): + symbols = ", ".join(row.get("matched_ipc_symbols") or []) or "(none)" + print( + f" {rank:2}. {row.get('patent_id')} " + f"match={row.get('match_score')} ipc={row.get('ipc_score')} " + f"symbols={symbols}" + ) + print(f" {row.get('title')}") + + +async def _run_case( + case: dict[str, Any], +) -> tuple[list[KeywordPatentMatch], str, KeywordPatentSearchDiagnostics | None]: + request = PatentsByKeywordsRequest(keywords=_keyword_items(case)) + response = await get_patents_by_keywords(request) + return list(response.patents), response.mapping_status, response.diagnostics + + +def _print_diagnostics(diagnostics: dict[str, Any] | None) -> None: + if not diagnostics: + print(" diagnostics: (none)") + return + print( + " diagnostics: " + f"path={diagnostics.get('search_path')} " + f"raw={diagnostics.get('raw_patents_after_dedupe')} " + f"passed_gate={diagnostics.get('passed_relevance_gate')} " + f"scored_before_cap={diagnostics.get('scored_before_cap')} " + f"returned={diagnostics.get('returned')} " + f"cap={diagnostics.get('max_patents_cap')} " + f"hit_cap={diagnostics.get('hit_return_cap')} " + f"es_size/index={diagnostics.get('es_query_size_per_index')}" + ) + print( + " filter_counts: " + f"ipc={diagnostics.get('filtered_by_ipc')} " + f"gate={diagnostics.get('filtered_by_relevance_gate')} " + f"min_score={diagnostics.get('filtered_by_min_score')}" + ) + + +def _print_ipc_clusters(case_id: str, diagnostics: dict[str, Any] | None) -> None: + if case_id not in IPC_FOCUS_CASES: + return + selections = (diagnostics or {}).get("ipc_cluster_selections") or [] + print(f" ipc_cluster_selections ({case_id}):") + if not selections: + print(" (none)") + return + for selection in selections: + print( + " " + f"topic={selection.get('topic_key')} " + f"subclass={selection.get('subclass')} " + f"symbol={selection.get('symbol')} " + f"level={selection.get('level')} " + f"relative_mass={selection.get('relative_mass')} " + f"cluster_mass={selection.get('cluster_mass')} " + f"reason={selection.get('reason')}" + ) + + +def _print_label_split(split: dict[str, Any] | None) -> None: + if not split: + return + for path_key, label in ( + ("ipc_path", "IPC-path labels"), + ("text_path", "Text-path labels"), + ): + path = split.get(path_key) or {} + metrics = path.get("metrics") + retrieved = path.get("retrieved", 0) + if retrieved == 0: + print(f" {label}: retrieved=0 (path unused for this case)") + continue + if not metrics: + print(f" {label}: retrieved={retrieved} (no labels overlapping this path)") + continue + print( + f" {label}: retrieved={retrieved} " + f"P@10={metrics['precision'].get('@10')} " + f"nDCG@10={metrics['ndcg'].get('@10')} " + f"MAP={metrics['map']} MRR={metrics['mrr']}" + ) + + +def _print_family_duplicates(proxy: dict[str, Any], ks: list[int]) -> None: + family = (proxy.get("family_metrics") or {}).get("family_duplicates") or {} + if not family: + return + print(" family_duplicates:") + for k in ks: + stats = family.get(f"@{k}") or {} + print( + f" @{k}: unique={stats.get('unique_families')} " + f"dup_entries={stats.get('duplicate_entries')} " + f"groups={len(stats.get('duplicate_groups') or [])}" + ) + for group in (stats.get("duplicate_groups") or [])[:3]: + print( + f" {group.get('family_key')} " + f"(count={group.get('count')})" + ) + + +def _print_top_candidates(top_results: list[dict[str, Any]], limit: int = 20) -> None: + print(f" top_{limit}_candidates:") + for rank, item in enumerate(top_results[:limit], start=1): + ipc = item.get("ipc") or [] + cpc = item.get("cpc") or [] + codes = ", ".join([*(ipc[:2]), *(cpc[:1])]) or "(none)" + print( + f" {rank:2}. {item.get('patent_id')} " + f"score={item.get('match_score')} " + f"text={item.get('text_retrieval')} " + f"ipc={codes}" + ) + + +def _print_lithium_case_detail(case_id: str, report: dict[str, Any], ks: list[int]) -> None: + if not _is_lithium_case(case_id): + return + proxy = report["proxy_metrics"] + diagnostics = report.get("diagnostics") or {} + print(f" search_path: {diagnostics.get('search_path')}") + print(f" passed_relevance_gate: {diagnostics.get('passed_relevance_gate')}") + prefixes = proxy.get("expected_ipc_prefixes") or ["H01M"] + print(f" battery_proxy_ipc ({', '.join(prefixes)}):") + for k in ks: + print(f" ipc_hit@{k}: {proxy['ipc_prefix_hit_rate'].get(f'@{k}')}") + watch = proxy.get("ipc_cluster_watch_hit_rate") + if watch: + watch_prefixes = proxy.get("ipc_cluster_watch_prefixes") or ["H01J"] + print(f" mapping_cluster_watch ({', '.join(watch_prefixes)}, not battery proxy):") + for k in ks: + print(f" cluster_hit@{k}: {watch.get(f'@{k}')}") + _print_ipc_clusters(case_id, diagnostics) + _print_family_duplicates(proxy, ks) + _print_top_candidates(report.get("top_results") or [], limit=20) + + +def _print_case_summary(case_id: str, report: dict[str, Any], ks: list[int] | None = None) -> None: + proxy = report["proxy_metrics"] + case_ks = ks or [5, 10, 20] + print(f"\n=== {case_id} ===") + print(f" mapping_status: {report.get('mapping_status')}") + print(f" retrieved: {proxy['retrieved']}") + ipc_role = proxy.get("ipc_prefix_hit_rate_role", "retrieval_aligned") + ipc_label = "ipc_hit@10" + if ipc_role == "post_hoc_plausibility_only": + ipc_label = "ipc_hit@10 (post-hoc plausibility only)" + print(f" {ipc_label}: {proxy['ipc_prefix_hit_rate'].get('@10')}") + print(f" topic_rate@10: {proxy['topic_score_rate'].get('@10')}") + print(f" text_rate@10: {proxy['text_score_rate'].get('@10')}") + _print_diagnostics(report.get("diagnostics")) + if _is_lithium_case(case_id): + _print_lithium_case_detail(case_id, report, case_ks) + else: + _print_ipc_clusters(case_id, report.get("diagnostics")) + _print_family_duplicates(proxy, case_ks) + labels = report.get("label_metrics") + if labels: + print(f" P@10 (overall): {labels['precision'].get('@10')}") + print(f" nDCG@10 (overall): {labels['ndcg'].get('@10')}") + print(f" MAP: {labels['map']} MRR: {labels['mrr']}") + else: + print(" (no relevance labels yet — proxy metrics only)") + _print_label_split(report.get("label_metrics_split")) + + +def _prior_labeling_paths(out_dir: Path) -> list[Path]: + return sorted(out_dir.glob("labeling_*.json")) + + +def _seed_grades_from_gold(case: dict[str, Any]) -> dict[str, dict[str, Any]]: + """patent_id -> {grade, notes} from goldset labels.""" + seeded: dict[str, dict[str, Any]] = {} + for patent_id, grade in (case.get("relevance_grades") or {}).items(): + seeded[normalize_patent_id(patent_id)] = { + "grade": float(grade), + "notes": "from goldset relevance_grades", + } + for patent_id in case.get("relevant_patent_ids") or []: + key = normalize_patent_id(patent_id) + seeded.setdefault( + key, + {"grade": 1.0, "notes": "from goldset relevant_patent_ids"}, + ) + for patent_id in case.get("irrelevant_patent_ids") or []: + key = normalize_patent_id(patent_id) + seeded.setdefault( + key, + {"grade": 0.0, "notes": "from goldset irrelevant_patent_ids"}, + ) + return seeded + + +def _load_prior_candidate_grades( + out_dir: Path, +) -> dict[str, dict[str, dict[str, Any]]]: + """case_id -> patent_id -> candidate payload (latest non-null grade wins).""" + by_case: dict[str, dict[str, dict[str, Any]]] = {} + for path in _prior_labeling_paths(out_dir): + try: + payload = _load_json(path) + except (OSError, json.JSONDecodeError) as exc: + logger.warning("Skipping prior labeling file %s: %s", path, exc) + continue + for case in payload.get("cases") or []: + case_id = case.get("id") + if not case_id: + continue + bucket = by_case.setdefault(case_id, {}) + for candidate in case.get("candidates") or []: + patent_id = normalize_patent_id(candidate.get("patent_id") or "") + if not patent_id: + continue + existing = bucket.get(patent_id) + grade = candidate.get("grade") + # Prefer entries that already have a grade; otherwise keep newest metadata. + if existing is None: + bucket[patent_id] = dict(candidate) + continue + if existing.get("grade") is None and grade is not None: + bucket[patent_id] = dict(candidate) + elif existing.get("grade") is None: + bucket[patent_id] = dict(candidate) + return by_case + + +def _merge_candidates( + *, + case: dict[str, Any], + new_ranked: list[dict[str, Any]], + prior_by_case: dict[str, dict[str, dict[str, Any]]], +) -> list[dict[str, Any]]: + """Merge new Top-N with prior pool and goldset grades for joint labeling.""" + case_id = case["id"] + prior = dict(prior_by_case.get(case_id) or {}) + gold_grades = _seed_grades_from_gold(case) + + merged: dict[str, dict[str, Any]] = {} + + # Start with prior pool (old hits stay available for labeling). + for patent_id, candidate in prior.items(): + item = dict(candidate) + item["patent_id"] = patent_id + item.setdefault("grade", None) + item.setdefault("notes", "") + item["in_prior_pool"] = True + item["in_current_top"] = False + merged[patent_id] = item + + # Overlay / add current bootstrap ranking. + for rank, item in enumerate(new_ranked, start=1): + patent_id = normalize_patent_id(item["patent_id"]) + base = dict(merged.get(patent_id) or {}) + previous_grade = base.get("grade") + previous_notes = base.get("notes") or "" + updated = { + **item, + "patent_id": patent_id, + "grade": previous_grade, + "notes": previous_notes, + "in_prior_pool": patent_id in prior, + "in_current_top": True, + "current_rank": rank, + } + merged[patent_id] = updated + + # Seed grades from goldset when still unlabeled. + for patent_id, seed in gold_grades.items(): + if patent_id in merged: + if merged[patent_id].get("grade") is None: + merged[patent_id]["grade"] = seed["grade"] + if not merged[patent_id].get("notes"): + merged[patent_id]["notes"] = seed["notes"] + continue + # Gold label for a patent not in current/prior retrieval — keep for metrics. + merged[patent_id] = { + "patent_id": patent_id, + "title": None, + "source": None, + "match_score": None, + "text_retrieval": None, + "grade": seed["grade"], + "notes": seed["notes"], + "in_prior_pool": False, + "in_current_top": False, + "from_goldset_only": True, + } + + def sort_key(candidate: dict[str, Any]) -> tuple: + current_rank = candidate.get("current_rank") + score = candidate.get("match_score") + return ( + 0 if candidate.get("in_current_top") else 1, + current_rank if isinstance(current_rank, int) else 10**9, + -(score if isinstance(score, (int, float)) else -1.0), + candidate.get("patent_id") or "", + ) + + return sorted(merged.values(), key=sort_key) + + +async def cmd_bootstrap(args: argparse.Namespace) -> int: + gold = _load_json(args.goldset) + ks = list(args.k or gold.get("ks") or [5, 10, 20]) + cases = gold["cases"] + if args.case: + cases = [case for case in cases if case["id"] == args.case] + if not cases: + logger.error("Unknown case id: %s", args.case) + return 1 + + out_dir = Path(args.out_dir) + prior_by_case = _load_prior_candidate_grades(out_dir) + prior_files = _prior_labeling_paths(out_dir) + print( + f"Merging with {len(prior_files)} prior labeling sheet(s); " + f"cases with prior candidates: {sorted(prior_by_case)}" + ) + + labeling_cases: list[dict[str, Any]] = [] + case_reports: list[dict[str, Any]] = [] + + for case in cases: + logger.info("Bootstrap case=%s", case["id"]) + matches, mapping_status, diagnostics = await _run_case(case) + ranked = [_match_to_dict(match) for match in matches] + grades = _relevance_for_case(case) + split = _split_label_metrics(matches, grades, ks) + diagnostics_payload = _diagnostics_dict(diagnostics) + report = { + "case_id": case["id"], + "mapping_status": mapping_status, + "proxy_metrics": _proxy_metrics( + matches, + case, + ks, + mapping_status=mapping_status, + ), + "label_metrics": split["overall"], + "label_metrics_split": split, + "diagnostics": diagnostics_payload, + "top_results": ranked[: args.top], + } + case_reports.append(report) + _print_case_summary(case["id"], report, ks) + + merged_candidates = _merge_candidates( + case=case, + new_ranked=ranked[: args.top], + prior_by_case=prior_by_case, + ) + labeling_cases.append( + { + "id": case["id"], + "description": case.get("description"), + "keywords": case["keywords"], + "expected_ipc_prefixes": case.get("expected_ipc_prefixes", []), + "mapping_status": mapping_status, + "diagnostics": diagnostics_payload, + "merge_stats": { + "current_top": sum( + 1 for c in merged_candidates if c.get("in_current_top") + ), + "from_prior_pool": sum( + 1 for c in merged_candidates if c.get("in_prior_pool") + ), + "total_candidates": len(merged_candidates), + "graded": sum( + 1 for c in merged_candidates if c.get("grade") is not None + ), + }, + "instructions": ( + "Set grade 0=irrelevant, 1=relevant, 2=highly relevant. " + "Pool merges current Top-N with prior labeling sheets and " + "goldset grades so old and new hits can be judged together. " + "Copy graded patent_ids into goldset relevant_patent_ids " + "and/or relevance_grades." + ), + "candidates": merged_candidates, + } + ) + + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + labeling_path = out_dir / f"labeling_{stamp}.json" + report_path = out_dir / f"bootstrap_report_{stamp}.json" + + payload = { + "created_at": stamp, + "goldset": str(args.goldset), + "merged_prior_labeling_files": [str(path) for path in prior_files], + "summary": _aggregate(case_reports, ks), + "cases": labeling_cases, + "cap_explanation": ( + f"Each EPO/USPTO query uses size={_MAX_PATENTS} and the pipeline " + f"caps returned patents at {_MAX_PATENTS}. hit_return_cap=true means " + "at least that many candidates passed scoring before the final slice." + ), + } + _write_json(labeling_path, payload) + _write_json( + report_path, + { + "created_at": stamp, + "mode": "bootstrap", + "summary": payload["summary"], + "case_reports": case_reports, + "cap_explanation": payload["cap_explanation"], + }, + ) + + print("\n--- aggregate (proxy + label split) ---") + print(json.dumps(payload["summary"], indent=2)) + print(f"\n{payload['cap_explanation']}") + print(f"\nLabeling sheet (merged): {labeling_path}") + print(f"Report: {report_path}") + print( + "Next: grade candidates (grade=0/1/2), merge into goldset, then run: " + "python scripts/patents/evaluate_keyword_patent_search.py eval" + ) + print( + "Do not retune relevance gates or score weights until after this label round." + ) + return 0 + + +async def cmd_eval(args: argparse.Namespace) -> int: + gold = _load_json(args.goldset) + ks = list(args.k or gold.get("ks") or [5, 10, 20]) + presentation = bool(gold.get("presentation")) + cases = gold["cases"] + if args.case: + cases = [case for case in cases if case["id"] == args.case] + if not cases: + logger.error("Unknown case id: %s", args.case) + return 1 + + case_reports: list[dict[str, Any]] = [] + for case in cases: + logger.info("Eval case=%s", case["id"]) + matches, mapping_status, diagnostics = await _run_case(case) + grades = _relevance_for_case(case) + if presentation: + report = _presentation_case_report( + case, + matches, + mapping_status, + diagnostics, + grades, + ks, + ) + case_reports.append(report) + _print_presentation_case(report, ks) + continue + + split = _split_label_metrics(matches, grades, ks) + report = { + "case_id": case["id"], + "mapping_status": mapping_status, + "proxy_metrics": _proxy_metrics( + matches, + case, + ks, + mapping_status=mapping_status, + ), + "label_metrics": split["overall"], + "label_metrics_split": split, + "diagnostics": _diagnostics_dict(diagnostics), + "top_results": [_match_to_dict(match) for match in matches[: args.top]], + } + case_reports.append(report) + _print_case_summary(case["id"], report, ks) + + summary = ( + _presentation_aggregate(case_reports, ks) + if presentation + else _aggregate(case_reports, ks) + ) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + report_name = "presentation_eval_report" if presentation else "eval_report" + report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json" + _write_json( + report_path, + { + "created_at": stamp, + "mode": "presentation_eval" if presentation else "eval", + "goldset": str(args.goldset), + "summary": summary, + "case_reports": case_reports, + }, + ) + + print("\n--- aggregate ---") + print(json.dumps(summary, indent=2)) + if summary.get("cases_labeled", 0) == 0: + print( + "\nNo relevance labels found. Grade candidates in labeling_presentation.json " + "or fill relevance_grades in the goldset, then re-run eval." + ) + print(f"\nReport: {report_path}") + return 0 + + +def _reweight_matches( + matches: list[KeywordPatentMatch], + weights: dict[str, float], +) -> list[KeywordPatentMatch]: + rescored = [ + match.model_copy( + update={ + "match_score": _compute_final_score( + match.ipc_score, + match.topic_score, + match.text_score, + weights=weights, + ) + } + ) + for match in matches + ] + rescored.sort( + key=lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ), + reverse=True, + ) + return rescored + + +async def cmd_ablation(args: argparse.Namespace) -> int: + gold = _load_json(args.goldset) + ks = list(args.k or gold.get("ks") or [5, 10, 20]) + weight_sets = { + "default": dict(_DEFAULT_SCORE_WEIGHTS), + "ipc_heavy": {"ipc": 0.8, "topic": 0.15, "text": 0.05}, + "topic_heavy": {"ipc": 0.4, "topic": 0.45, "text": 0.15}, + "text_heavy": {"ipc": 0.4, "topic": 0.2, "text": 0.4}, + "balanced": {"ipc": 1 / 3, "topic": 1 / 3, "text": 1 / 3}, + } + + cases = gold["cases"] + if args.case: + cases = [case for case in cases if case["id"] == args.case] + + ablation_rows: list[dict[str, Any]] = [] + for case in cases: + logger.info("Ablation case=%s", case["id"]) + base_matches, _mapping_status, _diagnostics = await _run_case(case) + grades = _relevance_for_case(case) + for name, weights in weight_sets.items(): + matches = _reweight_matches(base_matches, weights) + ranked_ids = [m.patent.patent_id for m in matches] + row = { + "case_id": case["id"], + "weights_name": name, + "weights": weights, + "proxy_metrics": _proxy_metrics(matches, case, ks), + "label_metrics": _label_metrics(ranked_ids, grades, ks), + } + ablation_rows.append(row) + label = row["label_metrics"] + p10 = label["precision"]["@10"] if label else None + print( + f"{case['id']:24} {name:12} " + f"ipc_hit@10={row['proxy_metrics']['ipc_prefix_hit_rate']['@10']} " + f"P@10={p10}" + ) + + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + report_path = Path(args.out_dir) / f"ablation_report_{stamp}.json" + _write_json( + report_path, + { + "created_at": stamp, + "mode": "ablation", + "weight_sets": weight_sets, + "rows": ablation_rows, + }, + ) + print(f"\nReport: {report_path}") + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Evaluate keyword → patent search (P@k, nDCG, IPC proxy metrics).", + ) + parser.add_argument( + "mode", + choices=["bootstrap", "eval", "ablation"], + help="bootstrap=write labeling sheet; eval=score vs gold; ablation=weight variants", + ) + parser.add_argument( + "--goldset", + type=Path, + default=DEFAULT_GOLDSET, + help=f"Gold set JSON (default: {DEFAULT_GOLDSET})", + ) + parser.add_argument( + "--out-dir", + type=Path, + default=DEFAULT_OUT_DIR, + help=f"Output directory (default: {DEFAULT_OUT_DIR})", + ) + parser.add_argument("--case", type=str, default=None, help="Run a single case id") + parser.add_argument( + "--top", + type=int, + default=20, + help="How many top results to keep for labeling/report (default: 20)", + ) + parser.add_argument( + "-k", + action="append", + type=int, + dest="k", + help="Cutoffs for @k metrics (repeatable). Default from goldset.", + ) + parser.add_argument("-v", "--verbose", action="store_true") + return parser + + +def main() -> int: + parser = build_parser() + args = parser.parse_args() + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format="%(levelname)s %(message)s", + ) + + if args.mode == "bootstrap": + return asyncio.run(cmd_bootstrap(args)) + if args.mode == "eval": + return asyncio.run(cmd_eval(args)) + if args.mode == "ablation": + return asyncio.run(cmd_ablation(args)) + parser.error(f"Unknown mode: {args.mode}") + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/service/scripts/patents/index_org_patents.py b/service/scripts/patents/index_org_patents.py index 21023ca2..f7c5b469 100644 --- a/service/scripts/patents/index_org_patents.py +++ b/service/scripts/patents/index_org_patents.py @@ -4,13 +4,9 @@ index_org_patents.py — Build the org_patents Elasticsearch index for one insti Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for patents matched via institution assignee and/or author name (match_type: "institution", -"name", or "both"), deletes existing documents for the institution, and reindexes. -Every inventor-name match counts outright only if the assignee is the institution -itself; everything else (a personal-assignee match or a third-party assignee) only -counts if the patent's primary IPC/CPC classification also maps to OpenAlex research -topics that appear on the author's own profile — applied regardless of how common the -name looks in our local OpenAlex data, since a name can appear unique there while -still being common globally in EPO/USPTO. +"name", or "both"), deletes existing documents for the institution, and reindexes. An +inventor-name match counts only if the assignee is the institution itself or the +person themselves, to avoid pulling in unrelated patents via a shared name. Usage: python scripts/patents/index_org_patents.py --institution-id diff --git a/service/src/main/inse/patents/keywords/eval_metrics.py b/service/src/main/inse/patents/keywords/eval_metrics.py new file mode 100644 index 00000000..887a713e --- /dev/null +++ b/service/src/main/inse/patents/keywords/eval_metrics.py @@ -0,0 +1,225 @@ +"""Ranking metrics for keyword → patent search evaluation.""" +from __future__ import annotations + +import math +from collections.abc import Iterable, Mapping, Sequence + + +def normalize_patent_id(patent_id: str) -> str: + return patent_id.strip().upper() + + +def precision_at_k( + ranked_ids: Sequence[str], + relevant_ids: Iterable[str], + k: int, +) -> float: + if k <= 0: + return 0.0 + relevant = {normalize_patent_id(pid) for pid in relevant_ids} + if not relevant: + return 0.0 + top = [normalize_patent_id(pid) for pid in ranked_ids[:k]] + hits = sum(1 for pid in top if pid in relevant) + return hits / k + + +def recall_at_k( + ranked_ids: Sequence[str], + relevant_ids: Iterable[str], + k: int, +) -> float: + relevant = {normalize_patent_id(pid) for pid in relevant_ids} + if not relevant or k <= 0: + return 0.0 + top = {normalize_patent_id(pid) for pid in ranked_ids[:k]} + return len(top & relevant) / len(relevant) + + +def average_precision( + ranked_ids: Sequence[str], + relevant_ids: Iterable[str], +) -> float: + relevant = {normalize_patent_id(pid) for pid in relevant_ids} + if not relevant: + return 0.0 + + hits = 0 + precision_sum = 0.0 + for idx, patent_id in enumerate(ranked_ids, start=1): + if normalize_patent_id(patent_id) not in relevant: + continue + hits += 1 + precision_sum += hits / idx + + if hits == 0: + return 0.0 + return precision_sum / len(relevant) + + +def dcg_at_k(gains: Sequence[float], k: int) -> float: + total = 0.0 + for idx, gain in enumerate(gains[:k], start=1): + total += gain / math.log2(idx + 1) + return total + + +def ndcg_at_k( + ranked_ids: Sequence[str], + relevance_grades: Mapping[str, float], + k: int, +) -> float: + if k <= 0 or not relevance_grades: + return 0.0 + + grades = { + normalize_patent_id(pid): float(grade) + for pid, grade in relevance_grades.items() + if float(grade) > 0 + } + if not grades: + return 0.0 + + gains = [ + grades.get(normalize_patent_id(pid), 0.0) for pid in ranked_ids[:k] + ] + ideal = sorted(grades.values(), reverse=True) + ideal_dcg = dcg_at_k(ideal, k) + if ideal_dcg <= 0: + return 0.0 + return dcg_at_k(gains, k) / ideal_dcg + + +def mrr( + ranked_ids: Sequence[str], + relevant_ids: Iterable[str], +) -> float: + relevant = {normalize_patent_id(pid) for pid in relevant_ids} + if not relevant: + return 0.0 + for idx, patent_id in enumerate(ranked_ids, start=1): + if normalize_patent_id(patent_id) in relevant: + return 1.0 / idx + return 0.0 + + +def ipc_prefix_hit_rate( + patent_ipc_lists: Sequence[Sequence[str]], + prefixes: Sequence[str], + *, + k: int | None = None, +) -> float: + """Share of patents whose IPC/CPC codes start with any expected prefix.""" + if not prefixes: + return 0.0 + subset = list(patent_ipc_lists[:k] if k is not None else patent_ipc_lists) + if not subset: + return 0.0 + + normalized_prefixes = [prefix.strip().upper() for prefix in prefixes if prefix.strip()] + if not normalized_prefixes: + return 0.0 + + hits = 0 + for codes in subset: + normalized_codes = [code.strip().upper().replace(" ", "") for code in codes] + if any( + code.startswith(prefix) + for code in normalized_codes + for prefix in normalized_prefixes + ): + hits += 1 + return hits / len(subset) + + +def mean(values: Sequence[float]) -> float: + if not values: + return 0.0 + return sum(values) / len(values) + + +def normalize_application_number(application_number: str | None) -> str | None: + if not application_number or not application_number.strip(): + return None + return application_number.strip().upper().replace(" ", "") + + +def normalize_title_key(title: str | None) -> str | None: + if not title or not title.strip(): + return None + return " ".join(title.lower().split()) + + +def patent_family_key( + *, + patent_id: str, + application_number: str | None = None, + title: str | None = None, +) -> str: + """Best-effort family key: application number, else normalized title, else patent id.""" + app = normalize_application_number(application_number) + if app: + return f"app:{app}" + title_key = normalize_title_key(title) + if title_key: + return f"title:{title_key}" + return f"id:{normalize_patent_id(patent_id)}" + + +def analyze_family_duplicates_in_top_k( + family_keys: Sequence[str], + k: int, +) -> dict[str, int | list[dict[str, str | int]]]: + top = list(family_keys[:k]) + counts: dict[str, int] = {} + for key in top: + counts[key] = counts.get(key, 0) + 1 + duplicate_groups = [ + {"family_key": key, "count": count} + for key, count in sorted(counts.items(), key=lambda item: -item[1]) + if count > 1 + ] + return { + "total_in_top_k": len(top), + "unique_families": len(counts), + "duplicate_entries": len(top) - len(counts), + "duplicate_groups": duplicate_groups, + } + + +def unique_family_precision_at_k( + ranked_ids: Sequence[str], + family_keys: Sequence[str], + relevant_ids: Iterable[str], + k: int, +) -> float: + """Precision@k counting at most one relevant hit per patent family in top-k.""" + if k <= 0: + return 0.0 + relevant = {normalize_patent_id(pid) for pid in relevant_ids} + if not relevant: + return 0.0 + + credited_families: set[str] = set() + hits = 0 + for patent_id, family_key in zip(ranked_ids[:k], family_keys[:k]): + if family_key in credited_families: + continue + credited_families.add(family_key) + if normalize_patent_id(patent_id) in relevant: + hits += 1 + return hits / k + + +def dedupe_ranked_ids_by_family( + ranked_ids: Sequence[str], + family_keys: Sequence[str], +) -> list[str]: + seen: set[str] = set() + deduped: list[str] = [] + for patent_id, family_key in zip(ranked_ids, family_keys): + if family_key in seen: + continue + seen.add(family_key) + deduped.append(normalize_patent_id(patent_id)) + return deduped diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py index 47e51161..1e030675 100644 --- a/service/src/main/inse/patents/keywords/logic.py +++ b/service/src/main/inse/patents/keywords/logic.py @@ -5,6 +5,7 @@ import asyncio import logging import math import re +from dataclasses import dataclass, field import httpx @@ -30,28 +31,60 @@ from inse.patents.ipc_lookup import ( ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.keywords.model import ( + KeywordEvidence, + KeywordPatentMappingStatus, KeywordPatentMatch, + KeywordPatentSearchDiagnostics, KeywordPatentSearchItem, PatentsByKeywordsRequest, PatentsByKeywordsResponse, ) -from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup -from inse.patents.keywords.search_queries import IpcPatentSearchQueries +from inse.patents.keywords.reverse_lookup import ( + IpcCodeMatch, + KeywordIpcReverseLookup, + _topic_group_key as _match_topic_group_key, +) +from inse.patents.keywords.search_queries import ( + IpcPatentSearchQueries, + _search_terms_for_symbol, +) from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver logger = logging.getLogger(__name__) _MAX_PATENTS = 100 -_MAX_IPC_CODES = 20 -_MAX_IPC_CODES_PER_KEYWORD = 2 +# Raw mapping candidates before cluster selection (avoid early truncation bias). +_MAX_IPC_LOOKUP_CANDIDATES = 200 +_MAX_IPC_CODES_PER_KEYWORD = 3 +_MAX_CLUSTERS_PER_TOPIC = 3 _MAX_PATENT_SEARCH_TERMS = 10 _MAX_SEARCH_KEYWORDS = 10 _MIN_KEYWORD_RELEVANCE = 0.0 _MIN_IPC_MATCH_SCORE = 0.65 +# Concentration gates: fragmented distributions return no IPC codes. +_MIN_CLUSTER_RELATIVE_MASS = 0.15 +_MIN_CLUSTER_TAIL_MASS = 0.10 +_MIN_LEADER_RELATIVE_MASS = 0.20 +_MIN_LEADER_MASS_RATIO = 1.5 +_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75 _MIN_PATENT_MATCH_SCORE = 0.50 +_MIN_TEXT_PATENT_MATCH_SCORE = 0.30 _DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15} +# When IPC mapping is abstained, score only topic + text evidence. +_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55} +# Also try title/abstract search when IPC mapping produced terms but scoring +# returned no patents (empty retrieval or over-filtering). +_TEXT_SEARCH_AFTER_EMPTY_IPC = True +_TOPIC_SCORE_TOPIC_ID = 1.0 +_TOPIC_SCORE_SUBFIELD = 0.7 +_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3 +# Section/class are excluded from retrieval; subclass is allowed but weaker. _SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"}) +_EXCLUDED_IPC_LEVELS = frozenset({"section", "class"}) +# Level weighting is applied once in reverse_lookup (_LEVEL_WEIGHTS). +# Cluster mass uses those scores as-is — no second level discount here. +_IPC_LEVEL_RANK = {"subgroup": 3, "group": 2, "subclass": 1} # Soft field overlap for natural-science / engineering patent domains. _SOFT_MATCH_FIELD_NAMES = frozenset( { @@ -133,100 +166,301 @@ _TEXT_STOPWORDS = frozenset( ) +@dataclass +class IpcSubclassCluster: + """Aggregated IPC evidence for one topic/keyword × subclass.""" + + topic_key: str + subclass: str + mass: float + relative_mass: float = 0.0 + members: list[IpcCodeMatch] = field(default_factory=list) + + @property + def best_match(self) -> IpcCodeMatch: + return max( + self.members, + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + ) + + +@dataclass(frozen=True) +class IpcClusterSelection: + topic_key: str + subclass: str + cluster_mass: float + relative_mass: float + match: IpcCodeMatch + reason: str + + def _ipc_section(symbol: str) -> str: normalized = normalize_symbol(symbol) return normalized[:1] if normalized else "" -def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> set[str]: - weights: dict[str, float] = {} +def _evidence_weight(match: IpcCodeMatch) -> float: + """Cluster mass uses reverse-lookup scores (already level-weighted once).""" + return match.match_score + + +def _subclass_key(symbol: str) -> str | None: + normalized = normalize_symbol(symbol) + if not normalized: + return None + return infer_subclass(normalized) + + +def _usable_ipc_matches(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: + """Keep only real subgroup/group/subclass matches above the score floor.""" + usable: list[IpcCodeMatch] = [] for match in ipc_matches: - section = _ipc_section(match.ipc_symbol) - if not section: + if match.ipc_level in _EXCLUDED_IPC_LEVELS: continue - weights[section] = weights.get(section, 0.0) + match.match_score - ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True) - return {section for section, _ in ranked[:limit]} - - -def _prefer_searchable_ipc_levels(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: - searchable = [ - match for match in ipc_matches if match.ipc_level in _SEARCHABLE_IPC_LEVELS - ] - return searchable if searchable else ipc_matches - - -def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: - if not ipc_matches: - return [] - - ipc_matches = _prefer_searchable_ipc_levels(ipc_matches) - ranked = sorted(ipc_matches, key=lambda match: match.match_score, reverse=True) - strong = [ - match - for match in ranked - if match.match_score >= _MIN_IPC_MATCH_SCORE - ] - if not strong: - return [] - - dominant_sections = _dominant_ipc_sections(strong) - filtered: list[IpcCodeMatch] = [] - seen: set[tuple[str, str]] = set() - for match in strong: - key = (match.ipc_level, match.ipc_symbol) - if key in seen: + if match.ipc_level not in _SEARCHABLE_IPC_LEVELS: continue - if match.match_score >= 0.8: - filtered.append(match) - seen.add(key) + if match.match_score < _MIN_IPC_MATCH_SCORE: continue - if _ipc_section(match.ipc_symbol) in dominant_sections: - filtered.append(match) - seen.add(key) - - return filtered + if _subclass_key(match.ipc_symbol) is None: + continue + usable.append(match) + return usable -def _limit_matches_per_keyword( +def _aggregate_subclass_clusters( + topic_key: str, matches: list[IpcCodeMatch], - limit: int = _MAX_IPC_CODES_PER_KEYWORD, -) -> list[IpcCodeMatch]: - grouped: dict[str, list[IpcCodeMatch]] = {} +) -> list[IpcSubclassCluster]: + buckets: dict[str, IpcSubclassCluster] = {} for match in matches: - grouped.setdefault(match.source_keyword.casefold(), []).append(match) + subclass = _subclass_key(match.ipc_symbol) + if not subclass: + continue + cluster = buckets.get(subclass) + if cluster is None: + cluster = IpcSubclassCluster(topic_key=topic_key, subclass=subclass, mass=0.0) + buckets[subclass] = cluster + cluster.mass += _evidence_weight(match) + cluster.members.append(match) - result: list[IpcCodeMatch] = [] - for keyword_matches in grouped.values(): - keyword_matches.sort(key=lambda match: match.match_score, reverse=True) - result.extend(keyword_matches[:limit]) + clusters = list(buckets.values()) + total_mass = sum(cluster.mass for cluster in clusters) + if total_mass <= 0: + return [] + for cluster in clusters: + cluster.relative_mass = cluster.mass / total_mass + return sorted(clusters, key=lambda item: item.mass, reverse=True) - return sorted(result, key=lambda match: match.match_score, reverse=True) + +def _select_dominant_clusters( + clusters: list[IpcSubclassCluster], +) -> list[tuple[IpcSubclassCluster, str]]: + """Pick dominant subclass clusters by relative mass / clear leadership. + + Fragmented distributions (many similarly weak clusters) return empty — + the caller should treat that as ``uncertain`` IPC evidence. + """ + if not clusters: + return [] + + if len(clusters) == 1: + return [(clusters[0], "sole_cluster_evidence")] + + selected: list[tuple[IpcSubclassCluster, str]] = [] + cumulative = 0.0 + + for cluster in clusters: + if len(selected) >= _MAX_CLUSTERS_PER_TOPIC: + break + + if cluster.relative_mass >= _MIN_CLUSTER_RELATIVE_MASS: + selected.append((cluster, "dominant_relative_mass")) + cumulative += cluster.relative_mass + continue + + if ( + selected + and cumulative < _TARGET_CUMULATIVE_CLUSTER_MASS + and cluster.relative_mass >= _MIN_CLUSTER_TAIL_MASS + ): + selected.append((cluster, "cumulative_mass_tail")) + cumulative += cluster.relative_mass + continue + + if selected: + break + + if not selected: + leader = clusters[0] + runner_up = clusters[1] + if ( + leader.relative_mass >= _MIN_LEADER_RELATIVE_MASS + and leader.mass >= runner_up.mass * _MIN_LEADER_MASS_RATIO + ): + selected.append((leader, "mass_leader_with_gap")) + + # No fragmented_top_mass fallback: weak/flat distributions stay empty. + return selected + + +def _select_ipc_matches_for_topic( + topic_key: str, + matches: list[IpcCodeMatch], +) -> list[IpcClusterSelection]: + usable = _usable_ipc_matches(matches) + clusters = _aggregate_subclass_clusters(topic_key, usable) + selected_clusters = _select_dominant_clusters(clusters) + + if not selected_clusters and clusters: + top = clusters[0] + logger.info( + "IPC cluster uncertain: topic=%s clusters=%d top_subclass=%s " + "top_relative_mass=%.4f top_cluster_mass=%.4f reason=fragmented_uncertain", + topic_key, + len(clusters), + top.subclass, + top.relative_mass, + top.mass, + ) + + selections: list[IpcClusterSelection] = [] + for cluster, reason in selected_clusters: + best = cluster.best_match + selections.append( + IpcClusterSelection( + topic_key=topic_key, + subclass=cluster.subclass, + cluster_mass=round(cluster.mass, 4), + relative_mass=round(cluster.relative_mass, 4), + match=best, + reason=reason, + ) + ) + return selections + + +def _topic_group_key(match: IpcCodeMatch) -> str: + """Group by OpenAlex topic_id when present; else fall back to keyword.""" + return _match_topic_group_key(match.topic_id, match.source_keyword) + + +def _group_matches_by_topic( + ipc_matches: list[IpcCodeMatch], +) -> dict[str, list[IpcCodeMatch]]: + grouped: dict[str, list[IpcCodeMatch]] = {} + for match in ipc_matches: + key = _topic_group_key(match) + grouped.setdefault(key, []).append(match) + return grouped + + +def select_ipc_matches_by_cluster_mass( + ipc_matches: list[IpcCodeMatch], +) -> tuple[list[IpcCodeMatch], list[IpcClusterSelection]]: + """Data-driven IPC selection from real patents_openalex_keywords matches. + + Evidence is aggregated per topic_id (or keyword) × subclass, then dominant + clusters are chosen by relative mass / leadership gap. Fragmented evidence + yields an empty selection (uncertain) — no synthetic IPC codes. + """ + selections: list[IpcClusterSelection] = [] + for topic_key, topic_matches in _group_matches_by_topic(ipc_matches).items(): + topic_selections = _select_ipc_matches_for_topic(topic_key, topic_matches) + for selection in topic_selections[:_MAX_IPC_CODES_PER_KEYWORD]: + selections.append(selection) + logger.info( + "IPC cluster selected: topic=%s subclass=%s level=%s symbol=%s " + "score=%.4f cluster_mass=%.4f relative_mass=%.4f reason=%s", + selection.topic_key, + selection.subclass, + selection.match.ipc_level, + selection.match.ipc_symbol, + selection.match.match_score, + selection.cluster_mass, + selection.relative_mass, + selection.reason, + ) + + # Merge across topics: keep best real match per symbol. + best_by_symbol: dict[str, IpcCodeMatch] = {} + for selection in selections: + symbol = normalize_symbol(selection.match.ipc_symbol) + existing = best_by_symbol.get(symbol) + if existing is None or selection.match.match_score > existing.match_score: + best_by_symbol[symbol] = selection.match + + selected_matches = sorted( + best_by_symbol.values(), + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + reverse=True, + ) + return selected_matches, selections + + +def _preferred_retrieval_symbols(match: IpcCodeMatch) -> list[str]: + """Prefer specific real symbols (subgroup/group) over broad subclass alone.""" + symbol = normalize_symbol(match.ipc_symbol) + if not symbol: + return [] + + ordered: list[str] = [] + if match.ipc_level in {"subgroup", "group"}: + # Keep the concrete matched symbol first for query expansion. + ordered.append(symbol) + parsed = parse_ipc_symbol(symbol) + if parsed is not None and parsed.main_group: + main_group = normalize_symbol(parsed.main_group) + if main_group and main_group not in ordered: + ordered.append(main_group) + + subclass = _subclass_key(symbol) + if subclass and subclass not in ordered: + ordered.append(subclass) + return ordered def _term_from_ipc_match(match: IpcCodeMatch) -> str | None: - symbol = normalize_symbol(match.ipc_symbol) - if not symbol: - return None - - return infer_subclass(symbol) + """Derive subclass prefix from a real match (used by tests / helpers).""" + return _subclass_key(match.ipc_symbol) def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]: - filtered = _filter_ipc_matches_for_search(ipc_matches) - filtered = sorted(filtered, key=lambda match: match.match_score, reverse=True) + """Build EPO/USPTO search symbols from selected real matches. + + Subgroup/group matches contribute their concrete symbols (and main-group) + before the broader subclass prefix. Nothing is injected without mapping + evidence. Query builders expand these via ``_search_terms_for_symbol``. + """ + ranked = sorted( + ipc_matches, + key=lambda match: ( + _IPC_LEVEL_RANK.get(match.ipc_level, 0), + match.match_score, + ), + reverse=True, + ) terms: list[str] = [] seen: set[str] = set() - for match in filtered: + for match in ranked: if match.ipc_level not in _SEARCHABLE_IPC_LEVELS: continue - term = _term_from_ipc_match(match) - if not term or term in seen: - continue - seen.add(term) - terms.append(term) - if len(terms) >= _MAX_PATENT_SEARCH_TERMS: - break + for symbol in _preferred_retrieval_symbols(match): + # Only keep symbols that expand to usable ES match terms. + expanded = _search_terms_for_symbol(symbol) + if not expanded: + continue + if symbol in seen: + continue + seen.add(symbol) + terms.append(symbol) + if len(terms) >= _MAX_PATENT_SEARCH_TERMS: + return terms return terms @@ -344,14 +578,6 @@ def _normalized_field_name(name: str | None) -> str: return (name or "").strip().casefold() -def _patent_has_g06_code(patent: model.PatentEntry) -> bool: - for code in (*patent.ipc, *patent.cpc): - symbol = normalize_symbol(extract_ipc_symbol(code) or code) - if symbol.startswith("G06"): - return True - return False - - def _compatible_patent_fields(keyword_field: str) -> frozenset[str]: return _COMPATIBLE_FIELDS.get(keyword_field, frozenset({keyword_field})) @@ -379,23 +605,27 @@ def _keyword_overlap_criteria( ) -def _topics_overlap_keywords( +@dataclass(frozen=True) +class TopicEvidence: + match_kind: str + score: float + + +@dataclass(frozen=True) +class TextGateDecision: + accepted: bool + reason: str + + +def _compute_topic_evidence( patent_topics: list[MappedOpenAlexTopic], keyword_topic_ids: frozenset[str], keyword_subfield_names: frozenset[str], keyword_soft_field_names: frozenset[str], - *, - patent: model.PatentEntry | None = None, -) -> bool: - if ( - not keyword_topic_ids - and not keyword_subfield_names - and not keyword_soft_field_names - ): - return True - +) -> TopicEvidence: + """Graded topic overlap used for ranking (field is weak signal only).""" if not patent_topics: - return False + return TopicEvidence(match_kind="none", score=0.0) patent_topic_ids = { topic_id @@ -403,7 +633,7 @@ def _topics_overlap_keywords( if (topic_id := normalize_openalex_id(mapped.topic_id)) } if keyword_topic_ids & patent_topic_ids: - return True + return TopicEvidence(match_kind="topic_id", score=_TOPIC_SCORE_TOPIC_ID) patent_subfield_names = { (mapped.subfield_name or "").strip().casefold() @@ -411,7 +641,7 @@ def _topics_overlap_keywords( if (mapped.subfield_name or "").strip() } if keyword_subfield_names & patent_subfield_names: - return True + return TopicEvidence(match_kind="subfield", score=_TOPIC_SCORE_SUBFIELD) if keyword_soft_field_names: patent_field_names = { @@ -421,17 +651,64 @@ def _topics_overlap_keywords( } for keyword_field in keyword_soft_field_names: if patent_field_names & _compatible_patent_fields(keyword_field): - return True - if ( - patent is not None - and _patent_has_g06_code(patent) - and keyword_soft_field_names & {"engineering", "computer science"} - ): - return True + return TopicEvidence( + match_kind="compatible_field", + score=_TOPIC_SCORE_COMPATIBLE_FIELD, + ) + return TopicEvidence(match_kind="none", score=0.0) + + +def _topics_overlap_keywords( + patent_topics: list[MappedOpenAlexTopic], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + *, + patent: model.PatentEntry | None = None, +) -> bool: + """True when any graded topic signal is present (including weak field).""" + _ = patent + if ( + not keyword_topic_ids + and not keyword_subfield_names + and not keyword_soft_field_names + ): + return True + return ( + _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + ).score + > 0.0 + ) + + +def _topic_passes_relevance_gate(topic_evidence: TopicEvidence) -> bool: + """Compatible field alone must not pass the gate — only ranking signal.""" + return topic_evidence.match_kind in {"topic_id", "subfield"} + + +def _tokenize_words(text: str) -> list[str]: + return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold()) + + +def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool: + if not needle or len(needle) > len(haystack): + return False + width = len(needle) + for index in range(len(haystack) - width + 1): + if haystack[index : index + width] == needle: + return True return False +def _token_set(tokens: list[str]) -> set[str]: + return set(tokens) + + def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: terms: list[str] = [] seen: set[str] = set() @@ -442,14 +719,8 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: item.topic_display_name, item.subfield_name, ): - normalized = (value or "").strip().casefold() - if not normalized: - continue - - words = re.findall(r"[a-zäöüß]{4,}", normalized) - - for word in words: - if word in _TEXT_STOPWORDS or word in seen: + for word in _tokenize_words(value or ""): + if len(word) < 4 or word in _TEXT_STOPWORDS or word in seen: continue seen.add(word) terms.append(word) @@ -457,23 +728,210 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]: return terms +def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]: + """Full phrases for ES title/abstract retrieval (text path).""" + phrases: list[str] = [] + seen: set[str] = set() + for item in items: + for value in (item.keyword, item.topic_display_name): + cleaned = " ".join((value or "").strip().split()) + if len(cleaned) < 3: + continue + key = cleaned.casefold() + if key in seen: + continue + seen.add(key) + phrases.append(cleaned) + return phrases + + def _text_overlap_score( patent: model.PatentEntry, search_terms: list[str], ) -> float: - text = " ".join( - part - for part in [patent.title or "", patent.abstract or ""] - if part - ).casefold() - - if not search_terms or not text.strip(): + tokens = _token_set( + _tokenize_words( + " ".join( + part + for part in [patent.title or "", patent.abstract or ""] + if part + ) + ) + ) + if not search_terms or not tokens: return 0.0 - hits = sum(1 for term in search_terms if term in text) + hits = sum(1 for term in search_terms if term in tokens) return min(hits / 3, 1.0) +def _text_match_kind( + *, + phrase_in_title: bool, + phrase_in_abstract: bool, + full_token_match: bool, + partial_token_match: bool, +) -> str: + if phrase_in_title: + return "phrase_title" + if phrase_in_abstract: + return "phrase_abstract" + if full_token_match: + return "full_token" + if partial_token_match: + return "partial_token" + return "none" + + +def _collect_keyword_text_evidence( + patent: model.PatentEntry, + phrases: list[str], + search_terms: list[str], +) -> KeywordEvidence: + """Record phrase / full-token / partial-token evidence separately.""" + title_tokens = _tokenize_words(patent.title or "") + abstract_tokens = _tokenize_words(patent.abstract or "") + combined_tokens = _token_set(title_tokens + abstract_tokens) + + phrase_in_title = False + phrase_in_abstract = False + full_token_match = False + partial_token_match = False + matched_phrases: list[str] = [] + + for phrase in phrases: + phrase_tokens = _tokenize_words(phrase) + if not phrase_tokens: + continue + if _contains_token_sequence(title_tokens, phrase_tokens): + phrase_in_title = True + matched_phrases.append(phrase) + elif _contains_token_sequence(abstract_tokens, phrase_tokens): + phrase_in_abstract = True + matched_phrases.append(phrase) + + present = [token for token in phrase_tokens if token in combined_tokens] + if present and len(present) == len(phrase_tokens): + full_token_match = True + elif present: + partial_token_match = True + + matched_words = [term for term in search_terms if term in combined_tokens] + if matched_words and not full_token_match and not partial_token_match: + # Lone search-term hits without a covering phrase count as partial. + partial_token_match = True + + word_match_score = ( + min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0 + ) + kind = _text_match_kind( + phrase_in_title=phrase_in_title, + phrase_in_abstract=phrase_in_abstract, + full_token_match=full_token_match, + partial_token_match=partial_token_match, + ) + + return KeywordEvidence( + phrase_in_title=phrase_in_title, + phrase_in_abstract=phrase_in_abstract, + full_token_match=full_token_match, + partial_token_match=partial_token_match, + word_match_score=round(word_match_score, 4), + matched_phrases=list(dict.fromkeys(matched_phrases)), + matched_words=matched_words, + text_match_kind=kind, + ) + + +def _keyword_text_score(evidence: KeywordEvidence) -> float: + if evidence.phrase_in_title: + return 1.0 + if evidence.phrase_in_abstract: + return 0.85 + if evidence.full_token_match: + return 0.55 + if evidence.partial_token_match: + return 0.25 + return 0.0 + + +def _exact_topic_or_subfield_match( + patent_topics: list[MappedOpenAlexTopic], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], +) -> bool: + evidence = _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + frozenset(), + ) + return evidence.match_kind in {"topic_id", "subfield"} + + +def _keyword_text_passes_relevance_gate( + evidence: KeywordEvidence, + *, + topic_evidence: TopicEvidence, +) -> TextGateDecision: + """Keyword text acceptance policy (no domain hardcoding). + + Accept: + - phrase in title (strong) + - phrase in abstract (medium) + - exact topic/subfield together with full token text evidence + Reject: + - partial/general words alone + - compatible field alone + - exact topic/subfield without text evidence + """ + exact = topic_evidence.match_kind in {"topic_id", "subfield"} + + if evidence.phrase_in_title: + return TextGateDecision(True, "phrase_in_title") + if evidence.phrase_in_abstract: + return TextGateDecision(True, "phrase_in_abstract") + if exact and evidence.full_token_match: + return TextGateDecision( + True, + f"{topic_evidence.match_kind}_with_full_token_match", + ) + if exact and evidence.partial_token_match: + return TextGateDecision(False, "exact_topic_with_partial_tokens_only") + if exact: + return TextGateDecision(False, "exact_topic_without_text") + if topic_evidence.match_kind == "compatible_field": + return TextGateDecision(False, "compatible_field_only") + if evidence.partial_token_match or evidence.matched_words: + return TextGateDecision(False, "partial_or_loose_words_only") + return TextGateDecision(False, "insufficient_evidence") + + +def _matched_keyword_labels_from_evidence( + items: list[KeywordPatentSearchItem], + evidence: KeywordEvidence, +) -> list[str]: + matched: list[str] = [] + seen: set[str] = set() + phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases} + word_keys = set(evidence.matched_words) + + for item in items: + for value in (item.keyword, item.topic_display_name): + label = (value or "").strip() + if not label: + continue + key = label.casefold() + if key in seen: + continue + label_tokens = _tokenize_words(label) + if key in phrase_keys or any(token in word_keys for token in label_tokens): + seen.add(key) + matched.append(label) + break + return matched + + def _patent_passes_relevance_gate( patent_topics: list[MappedOpenAlexTopic], *, @@ -483,14 +941,14 @@ def _patent_passes_relevance_gate( patent: model.PatentEntry, text_score: float, ) -> bool: - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + _ = patent + topic_evidence = _compute_topic_evidence( patent_topics, keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names, - patent=patent, ) - return has_topic_match or text_score > 0.0 + return _topic_passes_relevance_gate(topic_evidence) or text_score > 0.0 def _normalize_score_weights( @@ -599,26 +1057,407 @@ def _score_patent( _text_search_terms(search_keywords), ) - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( + topic_evidence = _compute_topic_evidence( patent_topics or [], keyword_topic_ids or frozenset(), keyword_subfield_names or frozenset(), keyword_soft_field_names or frozenset(), - patent=patent, ) - if not has_topic_match and text_score == 0.0: + if not _topic_passes_relevance_gate(topic_evidence) and text_score == 0.0: return None - topic_score = 1.0 if has_topic_match else 0.0 - return ( - _compute_final_score(ipc_score, topic_score, text_score), + _compute_final_score(ipc_score, topic_evidence.score, text_score), matched_keywords, matched_symbols, ) +async def _fetch_patents_for_queries( + client: BasePatentSearchClient, + epo_query: dict, + uspto_query: dict, +) -> list[model.PatentEntry] | None: + """Run EPO+USPTO search. Returns None on configuration/transport failure.""" + try: + epo_data, uspto_data = await asyncio.gather( + client.search_epo(epo_query), + client.search_uspto(uspto_query), + ) + except MissingApiKeyError: + logger.warning("Patent search skipped: Elasticsearch API key not configured.") + return None + except httpx.HTTPError as exc: + logger.warning("Patent search failed: %s", exc) + return None + + return deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)) + + +def _cluster_selection_dicts( + selections: list[IpcClusterSelection], +) -> list[dict]: + return [ + { + "topic_key": selection.topic_key, + "subclass": selection.subclass, + "symbol": selection.match.ipc_symbol, + "level": selection.match.ipc_level, + "match_score": selection.match.match_score, + "cluster_mass": selection.cluster_mass, + "relative_mass": selection.relative_mass, + "reason": selection.reason, + } + for selection in selections + ] + + +def _empty_diagnostics( + *, + search_path: str = "none", + ipc_cluster_selections: list[dict] | None = None, +) -> KeywordPatentSearchDiagnostics: + return KeywordPatentSearchDiagnostics( + search_path=search_path, + es_query_size_per_index=_MAX_PATENTS, + max_patents_cap=_MAX_PATENTS, + ipc_cluster_selections=list(ipc_cluster_selections or []), + ) + + +def _finalize_scored_patents( + scored: list[KeywordPatentMatch], + *, + raw_count: int, + filtered_by_ipc: int, + filtered_by_relevance_gate: int, + filtered_by_min_score: int, + passed_relevance_gate: int, + search_path: str, + ipc_cluster_selections: list[dict] | None = None, +) -> tuple[list[KeywordPatentMatch], KeywordPatentSearchDiagnostics]: + scored_before_cap = len(scored) + scored.sort( + key=lambda item: ( + item.match_score, + item.patent.publication_date or "", + item.patent.patent_id, + ), + reverse=True, + ) + returned = scored[:_MAX_PATENTS] + diagnostics = KeywordPatentSearchDiagnostics( + search_path=search_path, + es_query_size_per_index=_MAX_PATENTS, + raw_patents_after_dedupe=raw_count, + filtered_by_ipc=filtered_by_ipc, + filtered_by_relevance_gate=filtered_by_relevance_gate, + filtered_by_min_score=filtered_by_min_score, + passed_relevance_gate=passed_relevance_gate, + scored_before_cap=scored_before_cap, + returned=len(returned), + max_patents_cap=_MAX_PATENTS, + hit_return_cap=scored_before_cap >= _MAX_PATENTS, + ipc_cluster_selections=list(ipc_cluster_selections or []), + ) + return returned, diagnostics + + +async def _score_patents_with_ipc( + *, + raw_patents: list[model.PatentEntry], + ipc_matches: list[IpcCodeMatch], + text_search_terms: list[str], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + resolver: PatentOpenAlexMappingResolver, +) -> tuple[list[KeywordPatentMatch], dict[str, int]]: + patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) + scored: list[KeywordPatentMatch] = [] + filtered_by_ipc = 0 + filtered_by_relevance_gate = 0 + filtered_by_min_score = 0 + passed_relevance_gate = 0 + + for patent in raw_patents: + patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) + ipc_result = _score_ipc_match(patent, ipc_matches) + if ipc_result is None: + filtered_by_ipc += 1 + continue + ipc_score, matched_keywords, matched_symbols = ipc_result + + topic_evidence = _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + ) + text_score = _text_overlap_score(patent, text_search_terms) + if not _topic_passes_relevance_gate(topic_evidence) and text_score == 0.0: + filtered_by_relevance_gate += 1 + logger.info( + "IPC path reject: id=%s topic_kind=%s topic_score=%.2f " + "text_score=%.2f reason=field_or_none_without_text", + patent.patent_id, + topic_evidence.match_kind, + topic_evidence.score, + text_score, + ) + continue + + passed_relevance_gate += 1 + score = _compute_final_score(ipc_score, topic_evidence.score, text_score) + if score < _MIN_PATENT_MATCH_SCORE: + filtered_by_min_score += 1 + continue + + logger.info( + "IPC path accept: id=%s topic_kind=%s topic_score=%.2f " + "text_score=%.2f final_score=%.4f", + patent.patent_id, + topic_evidence.match_kind, + topic_evidence.score, + text_score, + score, + ) + scored.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + ipc_score=ipc_score, + topic_score=topic_evidence.score, + text_score=text_score, + matched_keywords=matched_keywords, + matched_ipc_symbols=matched_symbols, + text_retrieval=False, + topic_match_kind=topic_evidence.match_kind, + ) + ) + + logger.info( + "Keyword patent search: filtered_by_ipc=%d filtered_by_relevance_gate=%d " + "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", + filtered_by_ipc, + filtered_by_relevance_gate, + filtered_by_min_score, + passed_relevance_gate, + len(scored), + ) + return scored, { + "filtered_by_ipc": filtered_by_ipc, + "filtered_by_relevance_gate": filtered_by_relevance_gate, + "filtered_by_min_score": filtered_by_min_score, + "passed_relevance_gate": passed_relevance_gate, + } + + +async def _score_patents_text_search( + *, + raw_patents: list[model.PatentEntry], + search_keywords: list[KeywordPatentSearchItem], + phrases: list[str], + text_search_terms: list[str], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + resolver: PatentOpenAlexMappingResolver, +) -> tuple[list[KeywordPatentMatch], dict[str, int]]: + """Score patents without IPC using graded topic + structured text evidence.""" + patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) + scored: list[KeywordPatentMatch] = [] + filtered_by_relevance_gate = 0 + filtered_by_min_score = 0 + passed_relevance_gate = 0 + + for patent in raw_patents: + patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) + evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms) + topic_evidence = _compute_topic_evidence( + patent_topics, + keyword_topic_ids, + keyword_subfield_names, + keyword_soft_field_names, + ) + decision = _keyword_text_passes_relevance_gate( + evidence, + topic_evidence=topic_evidence, + ) + if not decision.accepted: + filtered_by_relevance_gate += 1 + logger.info( + "Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f " + "text_kind=%s phrase_title=%s phrase_abstract=%s " + "full_token=%s partial_token=%s reason=%s", + patent.patent_id, + patent.title, + topic_evidence.match_kind, + topic_evidence.score, + evidence.text_match_kind, + evidence.phrase_in_title, + evidence.phrase_in_abstract, + evidence.full_token_match, + evidence.partial_token_match, + decision.reason, + ) + continue + + passed_relevance_gate += 1 + text_score = _keyword_text_score(evidence) + # Field-only remains a weak ranking signal when already accepted via phrase. + score = _compute_final_score( + 0.0, + topic_evidence.score, + text_score, + weights=_TEXT_SCORE_WEIGHTS, + ) + if score < _MIN_TEXT_PATENT_MATCH_SCORE: + filtered_by_min_score += 1 + logger.info( + "Text reject: id=%s reason=below_min_score score=%.4f", + patent.patent_id, + score, + ) + continue + + logger.info( + "Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f " + "text_kind=%s text_score=%.2f final_score=%.4f reason=%s", + patent.patent_id, + patent.title, + topic_evidence.match_kind, + topic_evidence.score, + evidence.text_match_kind, + text_score, + score, + decision.reason, + ) + scored.append( + KeywordPatentMatch( + patent=patent, + match_score=score, + ipc_score=0.0, + topic_score=topic_evidence.score, + text_score=text_score, + matched_keywords=_matched_keyword_labels_from_evidence( + search_keywords, + evidence, + ), + matched_ipc_symbols=[], + text_retrieval=True, + keyword_evidence=evidence, + topic_match_kind=topic_evidence.match_kind, + ) + ) + + logger.info( + "Keyword patent text search: filtered_by_relevance_gate=%d " + "filtered_by_min_score=%d passed_relevance_gate=%d scored=%d", + filtered_by_relevance_gate, + filtered_by_min_score, + passed_relevance_gate, + len(scored), + ) + return scored, { + "filtered_by_relevance_gate": filtered_by_relevance_gate, + "filtered_by_min_score": filtered_by_min_score, + "passed_relevance_gate": passed_relevance_gate, + } + + +async def _search_patents_text_search( + *, + client: BasePatentSearchClient, + queries: IpcPatentSearchQueries, + ipc_search: IpcSearchClient, + resolver: PatentOpenAlexMappingResolver, + search_keywords: list[KeywordPatentSearchItem], + keyword_topic_ids: frozenset[str], + keyword_subfield_names: frozenset[str], + keyword_soft_field_names: frozenset[str], + mapping_status: KeywordPatentMappingStatus, + ipc_cluster_selections: list[dict] | None = None, +) -> PatentsByKeywordsResponse: + cluster_dicts = list(ipc_cluster_selections or []) + phrases = _text_search_phrases(search_keywords) + text_search_terms = _text_search_terms(search_keywords) + if not phrases: + logger.info( + "Keyword patent text search: no phrases for keywords %s", + [item.keyword for item in search_keywords], + ) + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=_empty_diagnostics( + search_path="text", + ipc_cluster_selections=cluster_dicts, + ), + ) + + logger.info( + "Keyword patent text search: mapping_status=%s phrases=%s", + mapping_status, + phrases, + ) + raw_patents = await _fetch_patents_for_queries( + client, + queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS), + queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS), + ) + if raw_patents is None: + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="search_error", + diagnostics=_empty_diagnostics( + search_path="text", + ipc_cluster_selections=cluster_dicts, + ), + ) + + logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents)) + scored, filter_counts = await _score_patents_text_search( + raw_patents=raw_patents, + search_keywords=search_keywords, + phrases=phrases, + text_search_terms=text_search_terms, + keyword_topic_ids=keyword_topic_ids, + keyword_subfield_names=keyword_subfield_names, + keyword_soft_field_names=keyword_soft_field_names, + resolver=resolver, + ) + scored, diagnostics = _finalize_scored_patents( + scored, + raw_count=len(raw_patents), + filtered_by_ipc=0, + filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], + filtered_by_min_score=filter_counts["filtered_by_min_score"], + passed_relevance_gate=filter_counts["passed_relevance_gate"], + search_path="text", + ipc_cluster_selections=cluster_dicts, + ) + await enrich_patents_classifications([item.patent for item in scored], ipc_search) + + if not scored: + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=diagnostics, + ) + + return PatentsByKeywordsResponse( + patent_count=len(scored), + patents=scored, + mapping_status=mapping_status, + diagnostics=diagnostics, + ) + + async def get_patents_by_keywords( request: PatentsByKeywordsRequest, *, @@ -639,7 +1478,12 @@ async def get_patents_by_keywords( "Keyword patent search: no searchable keywords in %s", [item.keyword for item in request.keywords], ) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_mapping", + diagnostics=_empty_diagnostics(search_path="none"), + ) logger.info( "Keyword patent search: using keywords=%s (from %d requested)", @@ -658,152 +1502,116 @@ async def get_patents_by_keywords( _keyword_overlap_criteria(search_keywords) ) - ipc_matches = await lookup.lookup_ipc_codes( + raw_ipc_matches = await lookup.lookup_ipc_codes( search_keywords, - max_codes=_MAX_IPC_CODES, + max_codes=_MAX_IPC_LOOKUP_CANDIDATES, ) - ipc_matches = _filter_ipc_matches_for_search(ipc_matches) - ipc_matches = _limit_matches_per_keyword(ipc_matches) + had_usable_mapping = bool(_usable_ipc_matches(raw_ipc_matches)) + ipc_matches, cluster_selections = select_ipc_matches_by_cluster_mass(raw_ipc_matches) + cluster_dicts = _cluster_selection_dicts(cluster_selections) logger.info( - "Keyword patent search: search_keywords=%s ipc_matches=%s", + "Keyword patent search: search_keywords=%s selected_ipc=%s", [item.keyword for item in search_keywords], - [ - { - "symbol": match.ipc_symbol, - "level": match.ipc_level, - "score": match.match_score, - "keyword": match.source_keyword, - } - for match in ipc_matches - ], + cluster_dicts, ) - if not ipc_matches: - logger.info( - "Keyword patent search: no IPC codes after filtering for keywords %s", - [item.keyword for item in search_keywords], - ) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - symbols = _patent_search_terms(ipc_matches) + if not symbols: + mapping_status: KeywordPatentMappingStatus = ( + "uncertain" if had_usable_mapping else "no_mapping" + ) + logger.info( + "Keyword patent search: no IPC search terms for keywords %s " + "(mapping_status=%s) — trying keyword text search", + [item.keyword for item in search_keywords], + mapping_status, + ) + return await _search_patents_text_search( + client=client, + queries=queries, + ipc_search=ipc_search, + resolver=resolver, + search_keywords=search_keywords, + keyword_topic_ids=keyword_topic_ids, + keyword_subfield_names=keyword_subfield_names, + keyword_soft_field_names=keyword_soft_field_names, + mapping_status=mapping_status, + ipc_cluster_selections=cluster_dicts, + ) + text_search_terms = _text_search_terms(search_keywords) logger.info("Keyword patent search: patent_search_terms=%s", symbols) - if not symbols: - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - try: - epo_data, uspto_data = await asyncio.gather( - client.search_epo( - queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) - ), - client.search_uspto( - queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS) - ), - ) - except MissingApiKeyError: - logger.warning("Patent search skipped: Elasticsearch API key not configured.") - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - except httpx.HTTPError as exc: - logger.warning("Patent search failed: %s", exc) - return PatentsByKeywordsResponse(patent_count=0, patents=[]) - - raw_patents = deduplicate_patents( - parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) + raw_patents = await _fetch_patents_for_queries( + client, + queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), + queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS), ) + if raw_patents is None: + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="search_error", + diagnostics=_empty_diagnostics( + search_path="ipc", + ipc_cluster_selections=cluster_dicts, + ), + ) + logger.info("Keyword patent search: raw_patents=%d", len(raw_patents)) - patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents) + scored, filter_counts = await _score_patents_with_ipc( + raw_patents=raw_patents, + ipc_matches=ipc_matches, + text_search_terms=text_search_terms, + keyword_topic_ids=keyword_topic_ids, + keyword_subfield_names=keyword_subfield_names, + keyword_soft_field_names=keyword_soft_field_names, + resolver=resolver, + ) + scored, diagnostics = _finalize_scored_patents( + scored, + raw_count=len(raw_patents), + filtered_by_ipc=filter_counts["filtered_by_ipc"], + filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"], + filtered_by_min_score=filter_counts["filtered_by_min_score"], + passed_relevance_gate=filter_counts["passed_relevance_gate"], + search_path="ipc", + ipc_cluster_selections=cluster_dicts, + ) - scored: list[KeywordPatentMatch] = [] - filtered_by_ipc = 0 - filtered_by_relevance_gate = 0 - filtered_by_min_score = 0 - for patent in raw_patents: - patent_topics = patent_topics_by_key.get(patent_map_key(patent), []) - ipc_result = _score_ipc_match(patent, ipc_matches) - if ipc_result is None: - filtered_by_ipc += 1 - continue - ipc_score, matched_keywords, matched_symbols = ipc_result - - has_topic_match = bool(patent_topics) and _topics_overlap_keywords( - patent_topics, - keyword_topic_ids, - keyword_subfield_names, - keyword_soft_field_names, - patent=patent, + if scored: + await enrich_patents_classifications([item.patent for item in scored], ipc_search) + return PatentsByKeywordsResponse( + patent_count=len(scored), + patents=scored, + mapping_status="mapped", + diagnostics=diagnostics, ) - text_score = _text_overlap_score(patent, text_search_terms) - - if not has_topic_match and text_score == 0.0: - filtered_by_relevance_gate += 1 - continue - - topic_score = 1.0 if has_topic_match else 0.0 - - score = _compute_final_score(ipc_score, topic_score, text_score) - if score < _MIN_PATENT_MATCH_SCORE: - filtered_by_min_score += 1 - continue - - hierarchy_levels = sorted( - { - level - for symbol in matched_symbols - for code in (*patent.ipc, *patent.cpc) - if (level := _ipc_hierarchy_level(code, symbol)) - } - ) - logger.info( - "Patent candidate: id=%s title=%s ipc_score=%.4f " - "topic_score=%.4f text_score=%.4f final_score=%.4f " - "hierarchy_levels=%s matched_keywords=%s matched_symbols=%s", - patent.patent_id, - patent.title, - ipc_score, - topic_score, - text_score, - score, - hierarchy_levels, - matched_keywords, - matched_symbols, - ) - scored.append( - KeywordPatentMatch( - patent=patent, - match_score=score, - ipc_score=ipc_score, - topic_score=topic_score, - text_score=text_score, - matched_keywords=matched_keywords, - matched_ipc_symbols=matched_symbols, - ) + if not _TEXT_SEARCH_AFTER_EMPTY_IPC: + return PatentsByKeywordsResponse( + patent_count=0, + patents=[], + mapping_status="no_patents_found", + diagnostics=diagnostics, ) logger.info( - "Keyword patent search: filtered_by_ipc=%d filtered_by_relevance_gate=%d " - "filtered_by_min_score=%d final_patents=%d", - filtered_by_ipc, - filtered_by_relevance_gate, - filtered_by_min_score, - len(scored), + "Keyword patent search: IPC path yielded no scored patents — " + "trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)" ) - - scored.sort( - key=lambda item: ( - item.match_score, - item.patent.publication_date or "", - item.patent.patent_id, - ), - reverse=True, - ) - scored = scored[:_MAX_PATENTS] - - patents = [item.patent for item in scored] - await enrich_patents_classifications(patents, ipc_search) - - return PatentsByKeywordsResponse( - patent_count=len(scored), - patents=scored, + return await _search_patents_text_search( + client=client, + queries=queries, + ipc_search=ipc_search, + resolver=resolver, + search_keywords=search_keywords, + keyword_topic_ids=keyword_topic_ids, + keyword_subfield_names=keyword_subfield_names, + keyword_soft_field_names=keyword_soft_field_names, + # IPC was selected but produced no usable hits; UI treats this like + # uncertain IPC evidence and labels patents via text_retrieval. + mapping_status="uncertain", + ipc_cluster_selections=cluster_dicts, ) diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py index 56423282..1a1c4b44 100644 --- a/service/src/main/inse/patents/keywords/model.py +++ b/service/src/main/inse/patents/keywords/model.py @@ -5,6 +5,13 @@ from pydantic import BaseModel, Field from inse.patents.common.model import PatentEntry KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"] +KeywordPatentMappingStatus = Literal[ + "mapped", + "uncertain", + "no_mapping", + "no_patents_found", + "search_error", +] class KeywordPatentSearchItem(BaseModel): @@ -42,16 +49,86 @@ class PatentsByKeywordsRequest(BaseModel): ) +class KeywordEvidence(BaseModel): + """Traceable title/abstract evidence for keyword text retrieval.""" + + phrase_in_title: bool = False + phrase_in_abstract: bool = False + full_token_match: bool = False + partial_token_match: bool = False + word_match_score: float = 0.0 + matched_phrases: list[str] = Field(default_factory=list) + matched_words: list[str] = Field(default_factory=list) + text_match_kind: str = Field( + default="none", + description=( + "phrase_title | phrase_abstract | full_token | partial_token | none" + ), + ) + + class KeywordPatentMatch(BaseModel): patent: PatentEntry match_score: float = Field(description="Combined match quality score.") ipc_score: float = Field(description="IPC/CPC classification match score.") - topic_score: float = Field(description="OpenAlex topic overlap score (0 or 1).") + topic_score: float = Field( + description=( + "Graded OpenAlex topic overlap: 1.0 topic_id, 0.7 subfield, " + "0.3 compatible field, 0.0 none." + ), + ) text_score: float = Field(description="Title/abstract keyword overlap score.") matched_keywords: list[str] = Field(default_factory=list) matched_ipc_symbols: list[str] = Field(default_factory=list) + text_retrieval: bool = Field( + default=False, + description=( + "True when the patent was retrieved via title/abstract keyword search " + "because IPC mapping was uncertain, missing, or yielded no hits." + ), + ) + keyword_evidence: KeywordEvidence | None = Field( + default=None, + description="Structured text evidence when text_retrieval is true.", + ) + topic_match_kind: str | None = Field( + default=None, + description="topic_id | subfield | compatible_field | none", + ) + + +class KeywordPatentSearchDiagnostics(BaseModel): + """Pipeline counters for evaluation (no effect on ranking thresholds).""" + + search_path: str = Field( + description="ipc | text | none", + ) + es_query_size_per_index: int = 0 + raw_patents_after_dedupe: int = 0 + filtered_by_ipc: int = 0 + filtered_by_relevance_gate: int = 0 + filtered_by_min_score: int = 0 + passed_relevance_gate: int = 0 + scored_before_cap: int = 0 + returned: int = 0 + max_patents_cap: int = 0 + hit_return_cap: bool = False + ipc_cluster_selections: list[dict] = Field(default_factory=list) class PatentsByKeywordsResponse(BaseModel): patent_count: int patents: list[KeywordPatentMatch] + mapping_status: KeywordPatentMappingStatus = Field( + description=( + "IPC mapping outcome: mapped (IPC used), uncertain (fragmented evidence; " + "may include text-retrieved patents), no_mapping (no usable IPC evidence; " + "may include text-retrieved patents), no_patents_found (neither IPC nor " + "keyword text search produced relevant patents), or search_error (technical " + "failure talking to the search backend)." + ), + ) + diagnostics: KeywordPatentSearchDiagnostics | None = Field( + default=None, + description="Optional search-pipeline counters for evaluation/debugging.", + ) diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py index 60806eba..5f29b445 100644 --- a/service/src/main/inse/patents/keywords/reverse_lookup.py +++ b/service/src/main/inse/patents/keywords/reverse_lookup.py @@ -24,10 +24,11 @@ logger = logging.getLogger(__name__) _LEVEL_WEIGHTS = { "subgroup": 1.0, "group": 0.92, - "subclass": 0.85, - "class": 0.75, - "section": 0.6, + # Subclass is allowed but clearly weaker than group/subgroup. + "subclass": 0.70, + # Section/class are excluded from keyword→patent retrieval. } +_EXCLUDED_IPC_LEVELS = frozenset({"section", "class"}) @dataclass(frozen=True) @@ -37,6 +38,7 @@ class IpcCodeMatch: match_score: float source_keyword: str match_type: str + topic_id: str | None = None def _keyword_variants(keyword: str) -> list[str]: @@ -83,7 +85,11 @@ def _weighted_score( relevance_score 0.0 while still mapping to valid OpenAlex topics. """ _ = relevance_score - level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7) + if ipc_level in _EXCLUDED_IPC_LEVELS: + return 0.0 + level_weight = _LEVEL_WEIGHTS.get(ipc_level) + if level_weight is None: + return 0.0 return round(base_score * level_weight, 4) @@ -138,15 +144,46 @@ def clear_reverse_lookup_caches() -> None: _build_json_inverted_index.cache_clear() +def _item_topic_id(item: KeywordPatentSearchItem) -> str | None: + variants = _topic_id_variants_for_item(item) + if not variants: + return None + for variant in variants: + short = normalize_openalex_id(variant) + if short: + return short + return variants[0] + + +def _topic_group_key(topic_id: str | None, source_keyword: str = "") -> str: + """Stable topic bucket for evidence; must stay aligned with cluster grouping.""" + if topic_id: + short = normalize_openalex_id(topic_id) + return short or topic_id.strip() + keyword = (source_keyword or "").strip() + return f"keyword:{keyword.casefold() or 'unknown'}" + + def _merge_ipc_match( - matches: dict[tuple[str, str], IpcCodeMatch], + matches: dict[tuple[str, str, str], IpcCodeMatch], level: str, symbol: str, score: float, source_keyword: str, match_type: str, + topic_id: str | None = None, ) -> None: - key = (level, normalize_symbol(symbol)) + """Merge by topic × level × symbol so evidence for distinct topics is preserved. + + Global symbol collapse happens only after per-topic cluster selection. + """ + if level in _EXCLUDED_IPC_LEVELS or score <= 0: + return + key = ( + _topic_group_key(topic_id, source_keyword), + level, + normalize_symbol(symbol), + ) existing = matches.get(key) if existing is None or score > existing.match_score: matches[key] = IpcCodeMatch( @@ -155,6 +192,7 @@ def _merge_ipc_match( match_score=score, source_keyword=source_keyword, match_type=match_type, + topic_id=topic_id, ) @@ -166,10 +204,13 @@ def _matches_from_doc( ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or "")) if not ipc_level or not ipc_symbol: return [] + if ipc_level in _EXCLUDED_IPC_LEVELS: + return [] keyword_variants = set(_keyword_variants(item.keyword)) topic_variants = set(_topic_id_variants_for_item(item)) topic_name = (item.topic_display_name or "").strip().casefold() + topic_id = _item_topic_id(item) found: list[IpcCodeMatch] = [] for match in doc.get("keyword_matches") or []: @@ -183,6 +224,8 @@ def _matches_from_doc( float(match.get("match_score") or 0.0), item.relevance_score, ) + if score <= 0: + break found.append( IpcCodeMatch( ipc_level=ipc_level, @@ -190,6 +233,7 @@ def _matches_from_doc( match_score=score, source_keyword=item.keyword, match_type="keyword", + topic_id=topic_id, ) ) break @@ -206,6 +250,8 @@ def _matches_from_doc( float(match.get("match_score") or 0.0), item.relevance_score, ) + if score <= 0: + break found.append( IpcCodeMatch( ipc_level=ipc_level, @@ -213,6 +259,7 @@ def _matches_from_doc( match_score=score, source_keyword=item.keyword, match_type="topic", + topic_id=topic_id, ) ) break @@ -222,15 +269,22 @@ def _matches_from_doc( def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: by_keyword, by_topic = _build_json_inverted_index() - merged: dict[tuple[str, str], IpcCodeMatch] = {} + merged: dict[tuple[str, str, str], IpcCodeMatch] = {} for item in items: + topic_id = _item_topic_id(item) for level, symbol, base_score, source_keyword, match_type in by_keyword.get( item.keyword.strip().casefold(), [] ): score = _weighted_score(level, base_score, item.relevance_score) _merge_ipc_match( - merged, level, symbol, score, item.keyword, match_type + merged, + level, + symbol, + score, + item.keyword, + match_type, + topic_id=topic_id, ) for variant in _topic_id_variants_for_item(item): @@ -239,14 +293,20 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]: ): score = _weighted_score(level, base_score, item.relevance_score) _merge_ipc_match( - merged, level, symbol, score, item.keyword, match_type + merged, + level, + symbol, + score, + item.keyword, + match_type, + topic_id=topic_id, ) return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: - merged: dict[tuple[str, str], IpcCodeMatch] = {} + merged: dict[tuple[str, str, str], IpcCodeMatch] = {} for match in matches: _merge_ipc_match( merged, @@ -255,6 +315,7 @@ def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]: match.match_score, match.source_keyword, match.match_type, + topic_id=match.topic_id, ) return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) @@ -336,8 +397,13 @@ class KeywordIpcReverseLookup: self, items: list[KeywordPatentSearchItem], *, - max_codes: int = 40, + max_codes: int | None = 200, ) -> list[IpcCodeMatch]: + """Return mapping candidates for downstream cluster selection. + + ``max_codes`` caps raw candidates *after* dedupe. Pass a high value (or + ``None``) so relative cluster mass is not distorted by early truncation. + """ if not items: return [] @@ -360,6 +426,8 @@ class KeywordIpcReverseLookup: ) matches = _dedupe_ipc_matches(matches) + if max_codes is None: + return matches return matches[:max_codes] async def _lookup_via_elasticsearch( @@ -394,7 +462,7 @@ class KeywordIpcReverseLookup: response.raise_for_status() data = response.json() - merged: dict[tuple[str, str], IpcCodeMatch] = {} + merged: dict[tuple[str, str, str], IpcCodeMatch] = {} for hit in data.get("hits", {}).get("hits", []): doc = hit.get("_source", {}) for item in items: @@ -406,6 +474,7 @@ class KeywordIpcReverseLookup: match.match_score, match.source_keyword, match.match_type, + topic_id=match.topic_id, ) return sorted(merged.values(), key=lambda match: match.match_score, reverse=True) diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py index 86a3ce9b..02139697 100644 --- a/service/src/main/inse/patents/keywords/search_queries.py +++ b/service/src/main/inse/patents/keywords/search_queries.py @@ -4,7 +4,7 @@ from __future__ import annotations from typing import Any from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE -from inse.patents.ipc_lookup import parse_ipc_symbol +from inse.patents.ipc_lookup import display_ipc_symbol, parse_ipc_symbol from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol _PATENT_SOURCE_FIELDS = [ @@ -43,60 +43,201 @@ _USPTO_SOURCE_FIELDS = [ ] _MIN_MATCH_TERM_LEN = 4 +_MIN_TEXT_PHRASE_LEN = 3 + +# Prefer concrete group/subgroup hits over broad subclass prefixes. +_BOOST_SUBGROUP = 4.0 +_BOOST_MAIN_GROUP = 2.5 +_BOOST_SUBCLASS = 1.0 + +# Text search: prefer exact phrases in title over abstract / loose match. +_BOOST_TEXT_PHRASE_TITLE = 5.0 +_BOOST_TEXT_PHRASE_ABSTRACT = 3.0 +_BOOST_TEXT_MATCH_TITLE = 1.5 +_BOOST_TEXT_MATCH_ABSTRACT = 1.0 -def _search_terms_for_symbol(symbol: str) -> list[str]: - """Derive EPO/USPTO `match` terms from an IPC/CPC symbol. +def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None: + cleaned = term.strip() + if len(cleaned) < _MIN_MATCH_TERM_LEN: + return + weights[cleaned] = max(weights.get(cleaned, 0.0), boost) + + +def _weighted_search_terms_for_symbol(symbol: str) -> dict[str, float]: + """Derive EPO/USPTO `match` terms with specificity boosts. Patent indices store IPC values like ``B60L 53/14 20060101AFI...``. Wildcard/prefix on normalized symbols (``B60L*``) does not match; ``match`` - on subclass codes (``B60L``) does. + on subclass / group tokens does. Concrete group/subgroup terms are boosted + above broad subclass prefixes. """ normalized = normalize_symbol(symbol) if not normalized: - return [] - - terms: list[str] = [] - subclass = infer_subclass(normalized) - if subclass and len(subclass) >= _MIN_MATCH_TERM_LEN: - terms.append(subclass) + return {} + weights: dict[str, float] = {} keys = parse_ipc_symbol(normalized) + subclass = infer_subclass(normalized) + if not subclass and keys is not None and keys.subclass: + subclass = normalize_symbol(keys.subclass) + + def add_symbol_forms(value: str | None, boost: float) -> None: + if not value: + return + norm = normalize_symbol(value) + if not norm: + return + _add_term_boost(weights, norm, boost) + display = display_ipc_symbol(norm) + if display and display != norm: + _add_term_boost(weights, display, boost) + if keys is not None: - if keys.subclass and len(keys.subclass) >= _MIN_MATCH_TERM_LEN: - terms.append(normalize_symbol(keys.subclass)) - if keys.main_group and len(normalize_symbol(keys.main_group)) >= _MIN_MATCH_TERM_LEN: - terms.append(normalize_symbol(keys.main_group)) + if keys.subgroup: + add_symbol_forms(keys.subgroup, _BOOST_SUBGROUP) + if keys.main_group: + main_group = normalize_symbol(keys.main_group) + # Short subgroup digits are folded into main_group by the parser + # (e.g. C07C243/08) — treat those leaf symbols as subgroup-level. + if keys.subgroup is None and "/" in main_group: + add_symbol_forms(main_group, _BOOST_SUBGROUP) + else: + add_symbol_forms(main_group, _BOOST_MAIN_GROUP) - if len(normalized) >= _MIN_MATCH_TERM_LEN: - prefix = normalized[:_MIN_MATCH_TERM_LEN] - if prefix not in terms: - terms.append(prefix) + if subclass: + add_symbol_forms(subclass, _BOOST_SUBCLASS) + elif len(normalized) >= _MIN_MATCH_TERM_LEN: + _add_term_boost(weights, normalized[:_MIN_MATCH_TERM_LEN], _BOOST_SUBCLASS) - return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN)) + return weights -def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]: +def _search_terms_for_symbol(symbol: str) -> list[str]: + """Derive EPO/USPTO `match` terms from an IPC/CPC symbol (boost order).""" + weights = _weighted_search_terms_for_symbol(symbol) + return [ + term + for term, _boost in sorted( + weights.items(), + key=lambda item: (-item[1], -len(item[0]), item[0]), + ) + ] + + +def _merge_term_boosts(symbols: list[str]) -> dict[str, float]: + merged: dict[str, float] = {} + for symbol in symbols: + for term, boost in _weighted_search_terms_for_symbol(symbol).items(): + merged[term] = max(merged.get(term, 0.0), boost) + return merged + + +def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[str, Any]]: clauses: list[dict[str, Any]] = [] - seen: set[tuple[str, str]] = set() - for term in terms: + for term, boost in sorted( + term_boosts.items(), + key=lambda item: (-item[1], -len(item[0]), item[0]), + ): if len(term) < _MIN_MATCH_TERM_LEN: continue - key = (field, term) + clauses.append( + { + "match": { + field: { + "query": term, + "boost": boost, + } + } + } + ) + return clauses + + +def _normalize_text_phrases(phrases: list[str]) -> list[str]: + cleaned: list[str] = [] + seen: set[str] = set() + for phrase in phrases: + value = " ".join((phrase or "").strip().split()) + if len(value) < _MIN_TEXT_PHRASE_LEN: + continue + key = value.casefold() if key in seen: continue seen.add(key) - clauses.append({"match": {field: term}}) + cleaned.append(value) + return cleaned + + +def _text_match_clauses( + phrases: list[str], + *, + title_fields: tuple[str, ...], + abstract_field: str, +) -> list[dict[str, Any]]: + """Build title/abstract should-clauses with phrase boosts over loose match.""" + clauses: list[dict[str, Any]] = [] + for phrase in _normalize_text_phrases(phrases): + for field in title_fields: + clauses.append( + { + "match_phrase": { + field: { + "query": phrase, + "boost": _BOOST_TEXT_PHRASE_TITLE, + } + } + } + ) + clauses.append( + { + "match": { + field: { + "query": phrase, + "operator": "and", + "boost": _BOOST_TEXT_MATCH_TITLE, + } + } + } + ) + clauses.append( + { + "match_phrase": { + abstract_field: { + "query": phrase, + "boost": _BOOST_TEXT_PHRASE_ABSTRACT, + } + } + } + ) + clauses.append( + { + "match": { + abstract_field: { + "query": phrase, + "operator": "and", + "boost": _BOOST_TEXT_MATCH_ABSTRACT, + } + } + } + ) return clauses class IpcPatentSearchQueries: def epo_query_by_ipc_terms( self, - terms: list[str], + terms: list[str] | dict[str, float], size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms) + term_boosts = ( + terms + if isinstance(terms, dict) + else {term: _BOOST_SUBCLASS for term in terms} + ) + should = _ipc_match_clauses("ipc", term_boosts) + _ipc_match_clauses( + "cpc", term_boosts + ) query: dict[str, Any] = ( {"match_none": {}} if not should @@ -106,8 +247,8 @@ class IpcPatentSearchQueries: "size": size, "track_total_hits": True, "sort": [ + {"_score": {"order": "desc"}}, {"date_publication": {"order": "desc", "missing": "_last"}}, - "_doc", ], "_source": _PATENT_SOURCE_FIELDS, "query": query, @@ -115,10 +256,17 @@ class IpcPatentSearchQueries: def uspto_query_by_ipc_terms( self, - terms: list[str], + terms: list[str] | dict[str, float], size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms) + term_boosts = ( + terms + if isinstance(terms, dict) + else {term: _BOOST_SUBCLASS for term in terms} + ) + should = _ipc_match_clauses("ipcr", term_boosts) + _ipc_match_clauses( + "cpc", term_boosts + ) query: dict[str, Any] = ( {"match_none": {}} if not should @@ -128,8 +276,8 @@ class IpcPatentSearchQueries: "size": size, "track_total_hits": True, "sort": [ + {"_score": {"order": "desc"}}, {"publication_date": {"order": "desc", "missing": "_last"}}, - "_doc", ], "_source": _USPTO_SOURCE_FIELDS, "query": query, @@ -140,27 +288,63 @@ class IpcPatentSearchQueries: symbols: list[str], size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - terms: list[str] = [] - seen: set[str] = set() - for symbol in symbols: - for term in _search_terms_for_symbol(symbol): - if term in seen: - continue - seen.add(term) - terms.append(term) - return self.epo_query_by_ipc_terms(terms, size=size) + return self.epo_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) def uspto_query_by_ipc_symbols( self, symbols: list[str], size: int = DEFAULT_SEARCH_SIZE, ) -> dict[str, Any]: - terms: list[str] = [] - seen: set[str] = set() - for symbol in symbols: - for term in _search_terms_for_symbol(symbol): - if term in seen: - continue - seen.add(term) - terms.append(term) - return self.uspto_query_by_ipc_terms(terms, size=size) + return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size) + + def epo_query_by_text_phrases( + self, + phrases: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _text_match_clauses( + phrases, + title_fields=("title_en", "title_de"), + abstract_field="abstract", + ) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"date_publication": {"order": "desc", "missing": "_last"}}, + ], + "_source": _PATENT_SOURCE_FIELDS, + "query": query, + } + + def uspto_query_by_text_phrases( + self, + phrases: list[str], + size: int = DEFAULT_SEARCH_SIZE, + ) -> dict[str, Any]: + should = _text_match_clauses( + phrases, + title_fields=("title",), + abstract_field="abstract", + ) + query: dict[str, Any] = ( + {"match_none": {}} + if not should + else {"bool": {"should": should, "minimum_should_match": 1}} + ) + return { + "size": size, + "track_total_hits": True, + "sort": [ + {"_score": {"order": "desc"}}, + {"publication_date": {"order": "desc", "missing": "_last"}}, + ], + "_source": _USPTO_SOURCE_FIELDS, + "query": query, + } diff --git a/service/src/main/inse/patents/keywords/test_eval_metrics.py b/service/src/main/inse/patents/keywords/test_eval_metrics.py new file mode 100644 index 00000000..c996c649 --- /dev/null +++ b/service/src/main/inse/patents/keywords/test_eval_metrics.py @@ -0,0 +1,74 @@ +"""Unit tests for keyword → patent evaluation metrics.""" +from __future__ import annotations + +from inse.patents.keywords.eval_metrics import ( + analyze_family_duplicates_in_top_k, + average_precision, + ipc_prefix_hit_rate, + mrr, + ndcg_at_k, + precision_at_k, + recall_at_k, + unique_family_precision_at_k, +) + + +def test_precision_at_k() -> None: + ranked = ["EP1", "EP2", "EP3", "EP4"] + relevant = ["EP2", "EP9"] + assert precision_at_k(ranked, relevant, 2) == 0.5 + assert precision_at_k(ranked, relevant, 4) == 0.25 + + +def test_recall_at_k() -> None: + ranked = ["EP1", "EP2", "EP3"] + relevant = ["EP2", "EP9"] + assert recall_at_k(ranked, relevant, 2) == 0.5 + assert recall_at_k(ranked, relevant, 3) == 0.5 + + +def test_average_precision() -> None: + ranked = ["EP1", "EP2", "EP3"] + relevant = ["EP2", "EP3"] + # hit@2 → 1/2, hit@3 → 2/3 → AP = (0.5 + 0.666...) / 2 + assert abs(average_precision(ranked, relevant) - ((0.5 + 2 / 3) / 2)) < 1e-9 + + +def test_ndcg_at_k() -> None: + ranked = ["EP1", "EP2", "EP3"] + grades = {"EP2": 2.0, "EP3": 1.0} + score = ndcg_at_k(ranked, grades, 3) + assert 0.0 < score < 1.0 + + +def test_mrr() -> None: + assert mrr(["EP1", "EP2", "EP3"], ["EP3"]) == 1 / 3 + assert mrr(["EP1", "EP2"], ["EP9"]) == 0.0 + + +def test_ipc_prefix_hit_rate() -> None: + ipc_lists = [ + ["C07C243/08"], + ["H01L21/02"], + ["C07D401/00", "A61K31/00"], + ] + assert ipc_prefix_hit_rate(ipc_lists, ["C07"], k=3) == 2 / 3 + assert ipc_prefix_hit_rate(ipc_lists, ["C07"], k=1) == 1.0 + + +def test_unique_family_precision_at_k() -> None: + ranked = ["EP1", "EP2", "EP3", "EP4"] + family_keys = ["app:1", "app:1", "app:2", "app:3"] + relevant = ["EP1", "EP2", "EP4"] + # top-3: EP1 relevant (family app:1), EP2 dup family skip, EP3 miss -> 1/3 + assert unique_family_precision_at_k(ranked, family_keys, relevant, 3) == 1 / 3 + # top-4: EP1 hit, EP2 skip, EP3 miss, EP4 hit -> 2/4 + assert unique_family_precision_at_k(ranked, family_keys, relevant, 4) == 0.5 + + +def test_analyze_family_duplicates_in_top_k() -> None: + keys = ["app:1", "app:1", "app:2", "title:foo"] + stats = analyze_family_duplicates_in_top_k(keys, 4) + assert stats["unique_families"] == 3 + assert stats["duplicate_entries"] == 1 + assert stats["duplicate_groups"][0]["count"] == 2 diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py index 0a6af63c..b6f14912 100644 --- a/service/src/main/inse/patents/keywords/test_logic.py +++ b/service/src/main/inse/patents/keywords/test_logic.py @@ -4,32 +4,49 @@ from __future__ import annotations import asyncio from unittest.mock import AsyncMock, patch +import httpx + from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common import model from inse.patents.keywords.logic import ( + TopicEvidence, _compute_final_score, + _compute_topic_evidence, + _collect_keyword_text_evidence, + _exact_topic_or_subfield_match, + _keyword_text_passes_relevance_gate, + _keyword_text_score, _filter_keywords_for_patent_search, _ipc_hierarchy_quality, _keyword_is_patent_searchable, - _limit_matches_per_keyword, _patent_passes_relevance_gate, _patent_search_terms, _score_ipc_match, _score_patent, + _select_dominant_clusters, + _aggregate_subclass_clusters, _term_from_ipc_match, _text_overlap_score, _text_search_terms, + _topic_passes_relevance_gate, _topics_overlap_keywords, + _usable_ipc_matches, get_patents_by_keywords, + select_ipc_matches_by_cluster_mass, ) from inse.patents.keywords.reverse_lookup import ( IpcCodeMatch, + _dedupe_ipc_matches, _json_lookup, _weighted_score, clear_reverse_lookup_caches, ) from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest -from inse.patents.keywords.search_queries import IpcPatentSearchQueries, _search_terms_for_symbol +from inse.patents.keywords.search_queries import ( + IpcPatentSearchQueries, + _search_terms_for_symbol, + _weighted_search_terms_for_symbol, +) def test_ipc_hierarchy_quality_exact_match() -> None: @@ -74,7 +91,166 @@ def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None: IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"), ] terms = _patent_search_terms(ipc_matches) - assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"] + assert "C25B3/03" in terms + assert "C07C243/08" in terms + assert "C09B68/48" in terms + assert terms.count("C09B68/48") == 1 + + +def test_usable_ipc_matches_excludes_section_and_class() -> None: + matches = [ + IpcCodeMatch("section", "C", 0.99, "Topic", "topic"), + IpcCodeMatch("class", "C07", 0.95, "Topic", "topic"), + IpcCodeMatch("subclass", "C07C", 0.80, "Topic", "topic"), + IpcCodeMatch("subgroup", "C07C243/08", 0.88, "Topic", "topic"), + ] + usable = _usable_ipc_matches(matches) + levels = {match.ipc_level for match in usable} + assert "section" not in levels + assert "class" not in levels + assert levels <= {"subclass", "group", "subgroup"} + + +def test_cluster_mass_prefers_dense_subclass_over_single_outlier() -> None: + """Many related subgroups in one subclass beat one high-score foreign outlier.""" + matches = [ + IpcCodeMatch("subgroup", "G01Q60/36", 0.95, "Robotics", "topic"), + IpcCodeMatch("subgroup", "B25J9/16", 0.78, "Robotics", "topic"), + IpcCodeMatch("subgroup", "B25J13/08", 0.76, "Robotics", "topic"), + IpcCodeMatch("subgroup", "B25J19/02", 0.74, "Robotics", "topic"), + IpcCodeMatch("group", "B25J9", 0.72, "Robotics", "topic"), + ] + selected, selections = select_ipc_matches_by_cluster_mass(matches) + by_subclass = {selection.subclass: selection for selection in selections} + assert "B25J" in by_subclass + g01q = by_subclass.get("G01Q") + assert g01q is None or by_subclass["B25J"].cluster_mass > g01q.cluster_mass + assert by_subclass["B25J"].relative_mass == max(s.relative_mass for s in selections) + assert selected + assert all(match.match_type != "domain_preference" for match in selected) + + +def test_cluster_selection_works_for_unseen_battery_topic() -> None: + matches = [ + IpcCodeMatch("subgroup", "H01M10/052", 0.88, "Battery technology", "topic", "TBAT"), + IpcCodeMatch("subgroup", "H01M4/58", 0.84, "Battery technology", "topic", "TBAT"), + IpcCodeMatch("subgroup", "H01M10/44", 0.80, "Battery technology", "topic", "TBAT"), + IpcCodeMatch("subgroup", "G01R31/36", 0.79, "Battery technology", "topic", "TBAT"), + ] + selected, selections = select_ipc_matches_by_cluster_mass(matches) + assert selections + assert {s.topic_key for s in selections} == {"TBAT"} + assert all(s.cluster_mass > 0 for s in selections) + assert all(s.reason for s in selections) + terms = _patent_search_terms(selected) + assert terms + assert any(term.startswith("H01M") for term in terms) + + +def test_cluster_selection_works_for_unseen_quantum_topic() -> None: + matches = [ + IpcCodeMatch("subgroup", "G06N10/00", 0.86, "Quantum computing", "topic", "TQ"), + IpcCodeMatch("subgroup", "G06N10/40", 0.83, "Quantum computing", "topic", "TQ"), + IpcCodeMatch("subclass", "G06N", 0.70, "Quantum computing", "topic", "TQ"), + IpcCodeMatch("subgroup", "H01L39/22", 0.75, "Quantum computing", "topic", "TQ"), + ] + selected, selections = select_ipc_matches_by_cluster_mass(matches) + assert selections + g06n = next(s for s in selections if s.subclass == "G06N") + assert g06n.relative_mass > 0 + assert all(m.ipc_level != "class" for m in selected) + assert "domain_preference" not in {m.match_type for m in selected} + + +def test_search_terms_prefer_specific_subgroup_symbol() -> None: + matches = [ + IpcCodeMatch("subgroup", "G06N3/08", 0.84, "Neural nets", "topic", "TNN"), + ] + terms = _patent_search_terms(matches) + assert terms[0] == "G06N3/08" + assert "G06N" in terms + + +def test_no_synthetic_matches_when_mapping_has_single_family() -> None: + """Sole concentrated family is accepted; nothing else is invented.""" + matches = [ + IpcCodeMatch("subgroup", "C12Q1/68", 0.92, "Unknown Topic X", "topic", "TX"), + ] + selected, selections = select_ipc_matches_by_cluster_mass(matches) + assert len(selections) == 1 + assert selections[0].subclass == "C12Q" + assert selections[0].reason == "sole_cluster_evidence" + assert selected[0].match_type == "topic" + terms = _patent_search_terms(selected) + assert terms[0] == "C12Q1/68" + + +def test_fragmented_weak_clusters_yield_no_ipc_selection() -> None: + """Many similarly weak subclasses must not force a fragmented pick.""" + matches = [ + IpcCodeMatch( + "subgroup", + f"A{index:02d}B1/00", + 0.70, + "Flat Topic", + "topic", + "TFLAT", + ) + for index in range(1, 16) + ] + selected, selections = select_ipc_matches_by_cluster_mass(matches) + assert selections == [] + assert selected == [] + assert _patent_search_terms(selected) == [] + + +def test_dedupe_preserves_same_symbol_for_distinct_topics() -> None: + """Identical IPC symbols for different topics must not collapse before clustering.""" + matches = [ + IpcCodeMatch("subgroup", "G06N3/08", 0.80, "Neural nets", "topic", "TNN"), + IpcCodeMatch("subgroup", "G06N3/08", 0.75, "Robotics", "topic", "TROB"), + IpcCodeMatch("subgroup", "G06N3/08", 0.90, "Neural nets", "topic", "TNN"), + ] + deduped = _dedupe_ipc_matches(matches) + by_topic = {match.topic_id: match for match in deduped} + assert set(by_topic) == {"TNN", "TROB"} + assert by_topic["TNN"].match_score == 0.90 + assert by_topic["TROB"].match_score == 0.75 + + selected, selections = select_ipc_matches_by_cluster_mass(deduped) + assert {selection.topic_key for selection in selections} == {"TNN", "TROB"} + assert len(selected) == 1 + assert selected[0].ipc_symbol == "G06N3/08" + assert selected[0].match_score == 0.90 + + +def test_aggregate_subclass_clusters_sums_scores_without_second_level_weight() -> None: + matches = [ + IpcCodeMatch("subgroup", "B60L50/50", 0.80, "EV", "topic", "TEV"), + IpcCodeMatch("subgroup", "B60L53/14", 0.80, "EV", "topic", "TEV"), + IpcCodeMatch("subclass", "B60L", 0.80, "EV", "topic", "TEV"), + ] + clusters = _aggregate_subclass_clusters("TEV", matches) + assert len(clusters) == 1 + assert clusters[0].subclass == "B60L" + assert abs(clusters[0].mass - 2.4) < 1e-9 + + +def test_dominant_clusters_skip_low_mass_tail() -> None: + clusters = _aggregate_subclass_clusters( + "Topic", + [ + IpcCodeMatch("subgroup", "A01B1/00", 0.90, "Topic", "topic"), + IpcCodeMatch("subgroup", "A01B3/00", 0.88, "Topic", "topic"), + IpcCodeMatch("subgroup", "A01B5/00", 0.86, "Topic", "topic"), + IpcCodeMatch("subgroup", "Z99Z1/00", 0.66, "Topic", "topic"), + ], + ) + selected = _select_dominant_clusters(clusters) + selected_subclasses = {cluster.subclass for cluster, _reason in selected} + assert "A01B" in selected_subclasses + # Tiny tail cluster should not be auto-selected. + assert "Z99Z" not in selected_subclasses def test_score_ipc_match_returns_only_best_evidence() -> None: @@ -148,6 +324,48 @@ def test_score_patent_uses_best_ipc_match() -> None: assert "G01S" in symbols +def test_compute_topic_evidence_is_graded() -> None: + topics = [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T999", + subfield_name="Organic Chemistry", + field_name="Chemistry", + ) + ] + exact = _compute_topic_evidence( + topics, + frozenset({"T999"}), + frozenset({"organic chemistry"}), + frozenset({"chemistry"}), + ) + assert exact.match_kind == "topic_id" + assert exact.score == 1.0 + + subfield = _compute_topic_evidence( + topics, + frozenset({"TOTHER"}), + frozenset({"organic chemistry"}), + frozenset({"chemistry"}), + ) + assert subfield.match_kind == "subfield" + assert subfield.score == 0.7 + + field_only = _compute_topic_evidence( + [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T1", + field_name="Materials Science", + ) + ], + frozenset({"TOTHER"}), + frozenset({"organic chemistry"}), + frozenset({"chemistry"}), + ) + assert field_only.match_kind == "compatible_field" + assert field_only.score == 0.3 + assert not _topic_passes_relevance_gate(field_only) + + def test_score_patent_requires_topic_overlap() -> None: patent = model.PatentEntry( patent_id="EP123", @@ -205,7 +423,45 @@ def test_score_patent_accepts_compatible_engineering_and_computer_science() -> N ) ], ) + # Compatible field alone is only a ranking signal; text evidence lets it pass. assert result is not None + score, _keywords, _symbols = result + assert score == _compute_final_score(0.9 * 0.75, 0.3, 2 / 3) + + +def test_score_patent_rejects_compatible_field_without_text() -> None: + patent = model.PatentEntry( + patent_id="EP456", + source="EPO", + ipc=["G06N 3/08"], + title="Unrelated apparatus", + abstract="No topical keywords here.", + ) + ipc_matches = [ + IpcCodeMatch("subclass", "G06N", 0.9, "Deep Learning", "keyword"), + ] + result = _score_patent( + patent, + ipc_matches, + patent_topics=[ + MappedOpenAlexTopic( + topic_id="https://openalex.org/T12072", + field_name="Computer Science", + ) + ], + keyword_topic_ids=frozenset({"T10653"}), + keyword_subfield_names=frozenset({"control and systems engineering"}), + keyword_soft_field_names=frozenset({"engineering"}), + search_keywords=[ + KeywordPatentSearchItem( + keyword="Deep Learning", + topic_id="https://openalex.org/T10653", + field_name="Engineering", + relevance_score=0.9, + ) + ], + ) + assert result is None def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None: @@ -346,21 +602,20 @@ def test_topics_overlap_keywords_rejects_patents_without_topics() -> None: ) -def test_limit_matches_per_keyword() -> None: +def test_selection_is_computed_per_topic_then_merged() -> None: matches = [ - IpcCodeMatch("subclass", "C07C", 0.95, "Organic Chemistry", "keyword"), - IpcCodeMatch("group", "C07C31", 0.9, "Organic Chemistry", "keyword"), - IpcCodeMatch("subclass", "C01B", 0.88, "Inorganic Chemistry", "keyword"), - IpcCodeMatch("subclass", "C01C", 0.87, "Inorganic Chemistry", "keyword"), + IpcCodeMatch("subgroup", "C07C243/08", 0.90, "Organic A", "keyword", "TORG"), + IpcCodeMatch("subgroup", "C07C31/20", 0.88, "Organic B", "keyword", "TORG"), + IpcCodeMatch("subgroup", "C01B3/00", 0.90, "Inorganic A", "keyword", "TINORG"), + IpcCodeMatch("subgroup", "C01C1/00", 0.88, "Inorganic B", "keyword", "TINORG"), ] - limited = _limit_matches_per_keyword(matches, limit=2) - assert len(limited) == 4 - organic = [match for match in limited if match.source_keyword == "Organic Chemistry"] - inorganic = [match for match in limited if match.source_keyword == "Inorganic Chemistry"] - assert len(organic) == 2 - assert len(inorganic) == 2 - assert organic[0].ipc_symbol == "C07C" - assert inorganic[0].ipc_symbol == "C01B" + selected, selections = select_ipc_matches_by_cluster_mass(matches) + topics = {selection.topic_key for selection in selections} + assert topics == {"TORG", "TINORG"} + subclasses = {selection.subclass for selection in selections} + assert "C07C" in subclasses + assert "C01B" in subclasses or "C01C" in subclasses + assert selected def test_text_overlap_score_uses_title_and_abstract() -> None: @@ -377,6 +632,143 @@ def test_text_overlap_score_uses_title_and_abstract() -> None: assert score == 1.0 +def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None: + patent = model.PatentEntry( + patent_id="EP1", + source="EPO", + title="Biochemistry overview", + abstract="Spectrochemical analysis.", + ) + # "chemistry" must not match inside "biochemistry" / "spectrochemical". + assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0 + + +def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None: + """Soft field / loose words must not accept a mechanical separator patent.""" + patent = model.PatentEntry( + patent_id="EP-MECH", + source="EPO", + title=( + "Rotating machine for separating materials in different " + "states of aggregation" + ), + abstract="Apparatus for mechanical separation of materials.", + ipc=["B01D45/12"], + ) + phrases = ["Organic Chemistry", "organische Chemie"] + terms = ["organic", "chemistry", "organische", "chemie"] + evidence = _collect_keyword_text_evidence(patent, phrases, terms) + + assert evidence.phrase_in_title is False + assert evidence.phrase_in_abstract is False + assert evidence.full_token_match is False + assert evidence.matched_phrases == [] + assert evidence.matched_words == [] + + field_only = TopicEvidence(match_kind="compatible_field", score=0.3) + assert not _keyword_text_passes_relevance_gate( + evidence, + topic_evidence=field_only, + ).accepted + exact = TopicEvidence(match_kind="topic_id", score=1.0) + assert not _keyword_text_passes_relevance_gate( + evidence, + topic_evidence=exact, + ).accepted + + +def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None: + phrase_patent = model.PatentEntry( + patent_id="EP-PHRASE", + source="EPO", + title="Process for organic chemistry synthesis", + abstract="Catalytic reactions.", + ) + phrases = ["organic chemistry"] + terms = ["organic", "chemistry"] + evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms) + assert evidence.phrase_in_title is True + assert evidence.text_match_kind == "phrase_title" + assert _keyword_text_score(evidence) == 1.0 + assert _keyword_text_passes_relevance_gate( + evidence, + topic_evidence=TopicEvidence(match_kind="none", score=0.0), + ).accepted + + full_token_patent = model.PatentEntry( + patent_id="EP-WORDS", + source="EPO", + title="Catalytic organic synthesis method", + abstract="Uses chemistry laboratory techniques.", + ) + full_evidence = _collect_keyword_text_evidence( + full_token_patent, + phrases, + terms, + ) + assert full_evidence.phrase_in_title is False + assert full_evidence.phrase_in_abstract is False + assert full_evidence.full_token_match is True + assert not _keyword_text_passes_relevance_gate( + full_evidence, + topic_evidence=TopicEvidence(match_kind="none", score=0.0), + ).accepted + assert _keyword_text_passes_relevance_gate( + full_evidence, + topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), + ).accepted + + partial_patent = model.PatentEntry( + patent_id="EP-PARTIAL", + source="EPO", + title="Organic polymer blend", + abstract="Industrial materials processing.", + ) + partial_evidence = _collect_keyword_text_evidence( + partial_patent, + phrases, + terms, + ) + assert partial_evidence.partial_token_match is True + assert partial_evidence.full_token_match is False + decision = _keyword_text_passes_relevance_gate( + partial_evidence, + topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0), + ) + assert not decision.accepted + assert decision.reason == "exact_topic_with_partial_tokens_only" + + assert _exact_topic_or_subfield_match( + [ + MappedOpenAlexTopic( + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + subfield_name="Organic Chemistry", + field_name="Chemistry", + ) + ], + frozenset({"TORG"}), + frozenset({"organic chemistry"}), + ) + + +def test_token_match_rejects_machine_inside_micromachined() -> None: + patent = model.PatentEntry( + patent_id="EP-MICRO", + source="EPO", + title="Micromachined sensor device", + abstract="Fabrication of micromachined structures.", + ) + assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0 + evidence = _collect_keyword_text_evidence( + patent, + ["Machine Learning"], + ["machine", "learning"], + ) + assert evidence.matched_words == [] + assert evidence.full_token_match is False + + def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None: patent = model.PatentEntry( patent_id="EP1", @@ -517,8 +909,10 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None: epo_symbols.assert_called_once() uspto_symbols.assert_called_once() - assert epo_symbols.call_args.args[0] == ["C07C"] - assert captured == ["epo", "uspto"] + assert epo_symbols.call_args.args[0][0] == "C07C243/08" + assert "C07C" in epo_symbols.call_args.args[0] + # IPC search returns empty → text fallback also queries EPO/USPTO. + assert captured == ["epo", "uspto", "epo", "uspto"] def test_text_search_terms_include_topic_metadata() -> None: @@ -541,8 +935,10 @@ def test_text_search_terms_include_topic_metadata() -> None: def test_weighted_score_applies_level_not_llm_relevance() -> None: score_high = _weighted_score("subclass", 0.8, 1.0) score_zero = _weighted_score("subclass", 0.8, 0.0) - assert score_high == round(0.8 * 0.85, 4) + assert score_high == round(0.8 * 0.70, 4) assert score_zero == score_high + assert _weighted_score("section", 0.9, 1.0) == 0.0 + assert _weighted_score("class", 0.9, 1.0) == 0.0 def test_search_terms_use_subclass_prefix() -> None: @@ -550,6 +946,233 @@ def test_search_terms_use_subclass_prefix() -> None: assert "G06N" in _search_terms_for_symbol("G06N") +def test_search_terms_include_concrete_subgroup_and_main_group() -> None: + terms = _search_terms_for_symbol("B60R2300/8086") + assert "B60R2300/8086" in terms + assert "B60R2300/80" in terms + assert "B60R" in terms + + weights = _weighted_search_terms_for_symbol("G06N3/08") + assert weights["G06N3/08"] > weights["G06N"] + assert weights["G06N3/08"] >= 4.0 + + +def _match_boost(clauses: list[dict], field: str, term: str) -> float | None: + for clause in clauses: + payload = clause.get("match", {}).get(field) + if isinstance(payload, dict) and payload.get("query") == term: + return float(payload.get("boost", 1.0)) + if payload == term: + return 1.0 + return None + + +def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None: + queries = IpcPatentSearchQueries() + epo = queries.epo_query_by_ipc_symbols(["G06N3/08", "G06N"]) + uspto = queries.uspto_query_by_ipc_symbols(["G06N3/08", "G06N"]) + + epo_should = epo["query"]["bool"]["should"] + uspto_should = uspto["query"]["bool"]["should"] + + epo_specific = _match_boost(epo_should, "ipc", "G06N3/08") + epo_subclass = _match_boost(epo_should, "ipc", "G06N") + uspto_specific = _match_boost(uspto_should, "ipcr", "G06N3/08") + uspto_subclass = _match_boost(uspto_should, "ipcr", "G06N") + + assert epo_specific is not None and epo_subclass is not None + assert uspto_specific is not None and uspto_subclass is not None + assert epo_specific > epo_subclass + assert uspto_specific > uspto_subclass + assert _match_boost(epo_should, "cpc", "G06N3/08") == epo_specific + assert _match_boost(uspto_should, "cpc", "G06N3/08") == uspto_specific + assert epo["sort"][0] == {"_score": {"order": "desc"}} + assert uspto["sort"][0] == {"_score": {"order": "desc"}} + + +def test_text_queries_prefer_phrase_match_in_title() -> None: + queries = IpcPatentSearchQueries() + epo = queries.epo_query_by_text_phrases(["organic chemistry"]) + uspto = queries.uspto_query_by_text_phrases(["organic chemistry"]) + + epo_should = epo["query"]["bool"]["should"] + uspto_should = uspto["query"]["bool"]["should"] + + def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None: + for clause in clauses: + payload = clause.get(kind, {}).get(field) + if isinstance(payload, dict) and payload.get("query") == "organic chemistry": + return float(payload.get("boost", 1.0)) + return None + + assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0 + assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0 + assert clause_boost(epo_should, "match", "title_en") == 1.5 + assert clause_boost(uspto_should, "match_phrase", "title") == 5.0 + assert epo["sort"][0] == {"_score": {"order": "desc"}} + + +def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None: + """Fragmented IPC abstention must fall back to title/abstract search.""" + patent = model.PatentEntry( + patent_id="EP123", + source="EPO", + title="Process for organic chemistry synthesis", + abstract="A catalytic method in organic chemistry.", + publication_date="20240101", + ipc=["C07C243/08"], + cpc=[], + ) + + async def fake_search_epo(query): + assert "match_phrase" in str(query) or "title_en" in str(query) + return { + "hits": { + "hits": [ + { + "_source": { + "doc_number": "123", + "country": "EP", + "kind": "A1", + "date_publication": "20240101", + "title_en": patent.title, + "abstract": patent.abstract, + "ipc": patent.ipc, + "cpc": [], + } + } + ] + } + } + + async def fake_search_uspto(query): + return {"hits": {"hits": []}} + + fragmented = [ + IpcCodeMatch( + "subgroup", + f"A{index:02d}B1/00", + 0.70, + "organische Chemie", + "topic", + "TORG", + ) + for index in range(1, 16) + ] + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=fragmented), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=fake_search_epo), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(side_effect=fake_search_uspto), + ), patch( + "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", + new=AsyncMock(return_value={}), + ), patch( + "inse.patents.keywords.logic.enrich_patents_classifications", + new=AsyncMock(), + ), patch.object( + IpcPatentSearchQueries, + "epo_query_by_text_phrases", + wraps=IpcPatentSearchQueries().epo_query_by_text_phrases, + ) as epo_text: + response = asyncio.run(get_patents_by_keywords(request)) + + epo_text.assert_called_once() + assert response.mapping_status == "uncertain" + assert response.patent_count == 1 + assert response.patents[0].text_retrieval is True + assert response.patents[0].ipc_score == 0.0 + assert response.patents[0].text_score > 0.0 + assert response.patents[0].matched_ipc_symbols == [] + assert response.patents[0].keyword_evidence is not None + assert response.patents[0].keyword_evidence.phrase_in_title is True + assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title" + + +def test_text_fallback_empty_yields_no_patents_found() -> None: + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=[]), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ), patch( + "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents", + new=AsyncMock(return_value={}), + ), patch( + "inse.patents.keywords.logic.enrich_patents_classifications", + new=AsyncMock(), + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "no_patents_found" + assert response.patent_count == 0 + assert response.patents == [] + + +def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None: + request = PatentsByKeywordsRequest( + keywords=[ + KeywordPatentSearchItem( + keyword="organische Chemie", + keyword_level="coarse", + topic_id="https://openalex.org/TORG", + topic_display_name="Organic Chemistry", + field_name="Chemistry", + relevance_score=1.0, + ) + ] + ) + + with patch( + "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes", + new=AsyncMock(return_value=[]), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_epo", + new=AsyncMock(side_effect=httpx.HTTPError("boom")), + ), patch( + "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto", + new=AsyncMock(return_value={"hits": {"hits": []}}), + ): + response = asyncio.run(get_patents_by_keywords(request)) + + assert response.mapping_status == "search_error" + assert response.patent_count == 0 + + def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None: clear_reverse_lookup_caches() monkeypatch.setattr( diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py index 561ae554..d0c93be7 100644 --- a/service/src/main/inse/patents/org/logic.py +++ b/service/src/main/inse/patents/org/logic.py @@ -14,8 +14,8 @@ from inse.models.openalex.author import Author from inse.patents.authors.identity import ( author_institution_names, patent_institution_match, + patent_personal_assignee_match, ) -from inse.patents.authors.ipc_openalex_mapping import normalize_openalex_id from inse.patents.authors.name_matching import filter_patents_by_author_name from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.model import PatentEntry @@ -26,12 +26,10 @@ from inse.patents.common.parsing import ( parse_epo_hits, parse_uspto_hits, patent_dedup_key, - patent_map_key, ) from inse.patents.institutions.logic import get_patents_by_institution_id from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient -from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver from inse.patents.org.elastic_search_client import ( OrgPatentsSearchClient, fetch_authors_by_institution_name, @@ -219,68 +217,6 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict: } -MIN_CORROBORATING_TOPIC_OVERLAP = 2 - - -def primary_classification_codes(patent: PatentEntry) -> list[str]: - """Returns only the patent's primary IPC/CPC code(s) (marked "AFI" in the - raw EPO/USPTO string), falling back to all codes if none are marked. - - Patents can carry dozens of secondary/incidental classification codes - (marked "ALI") alongside their real subject. Resolving OpenAlex topics - from *all* of them gives some patents a huge, unfocused topic cloud — - confirmed against a real org_patents rebuild, where a 20-code patent - picked up 70+ unrelated topics, making a coincidental two-topic overlap - with an unrelated same-named author far more likely than intended. - """ - all_codes = [*patent.ipc, *patent.cpc] - primary = [code for code in all_codes if "AFI" in code] - return primary or all_codes - - -def topic_corroborated_patents( - patents: list[PatentEntry], - author: Author, - patent_topic_map: dict[str, list], -) -> list[PatentEntry]: - """Keeps only patents whose IPC/CPC-derived OpenAlex topics share at - least MIN_CORROBORATING_TOPIC_OVERLAP exact topic IDs with the author's - own research topics — used to disambiguate common inventor names where - institution/self-assignee matching alone isn't enough. - - Requiring a single shared topic ID was still too loose: broad, - genuinely common topics (e.g. "Image Processing Techniques") show up on - many unrelated patents *and* on many unrelated researchers' profiles, so - one coincidental overlap doesn't mean much (confirmed against a real - org_patents rebuild: match_type=name patents still ballooned to ~2000). - Two independent topic overlaps happening by chance is far less likely, - while a patent genuinely invented by the author would typically share - more than one topic with their own body of work. If the author has no - topic profile at all, there is nothing to corroborate against. - """ - author_topic_ids = { - normalize_openalex_id(topic.id) - for topic in (author.topics or []) - if topic.id - } - author_topic_ids.discard(None) - if not author_topic_ids: - return [] - - kept: list[PatentEntry] = [] - for patent in patents: - mapped_topics = patent_topic_map.get(patent_map_key(patent), []) - patent_topic_ids = { - normalize_openalex_id(topic.topic_id) - for topic in mapped_topics - if topic.topic_id - } - patent_topic_ids.discard(None) - if len(patent_topic_ids & author_topic_ids) >= MIN_CORROBORATING_TOPIC_OVERLAP: - kept.append(patent) - return kept - - async def _search_patents_by_author( author: Author, institution_name: str | None, @@ -315,48 +251,18 @@ async def _search_patents_by_author( return [] # Applied to every name-based hit, not gated behind an ambiguity check: - # the institution itself being the assignee is the only unambiguous - # case — accepted outright. Everything else matched on name alone, - # including a personal-assignee match (several different same-named - # people could each be listed as their own patent's assignee) or a - # third-party assignee (e.g. an industry partner on a co-invented - # patent — the normal case for academic patents, not a red flag by - # itself), only counts if the patent's IPC/CPC-derived OpenAlex topics - # also overlap with the author's own research topics. This + # a match only counts if the assignee is the institution itself or the + # person themselves — a bare name match on inventors is too weak a + # signal on its own once several same-named people are possible. This # intentionally does not rely on is_ambiguous_name: a name can look # unique in our local OpenAlex slice while still being common globally - # in EPO/USPTO, so a bare name-on-inventor match alone is never a - # strong enough signal on its own. + # in EPO/USPTO. inst_names = [institution_name] if institution_name else [] - strong_identity_matched = [ + return [ p for p in name_matched if patent_institution_match(p, inst_names) + or patent_personal_assignee_match(p, author_name) ] - matched_keys = {patent_dedup_key(p) for p in strong_identity_matched} - remaining = [p for p in name_matched if patent_dedup_key(p) not in matched_keys] - if not remaining: - return strong_identity_matched - - topic_matched: list[PatentEntry] = [] - try: - resolver = PatentOpenAlexMappingResolver() - primary_only = [ - patent.model_copy(update={ - "ipc": primary_classification_codes(patent), - "cpc": [], - }) - for patent in remaining - ] - patent_topic_map = await resolver.resolve_topics_for_patents(primary_only) - topic_matched = topic_corroborated_patents(remaining, author, patent_topic_map) - except Exception: - logger.warning( - "OpenAlex topic corroboration failed for author %s", - author_name, - exc_info=True, - ) - - return strong_identity_matched + topic_matched async def build_org_patents_for_institution( diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py index 82a2aa21..60622812 100644 --- a/service/src/main/inse/patents/org/test_logic.py +++ b/service/src/main/inse/patents/org/test_logic.py @@ -1,14 +1,9 @@ from inse.models.openalex.author import Author -from inse.models.openalex.work_topic import WorkTopic -from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic from inse.patents.common.model import PatentEntry -from inse.patents.common.parsing import patent_map_key from inse.patents.org.logic import ( merge_org_patents, org_patent_document_id, - primary_classification_codes, resolve_match_type, - topic_corroborated_patents, ) from inse.patents.org.model import MatchedAuthor @@ -107,108 +102,3 @@ def test_org_patent_document_id_is_stable() -> None: doc_id = org_patent_document_id("I62318514", patent) assert doc_id == "I62318514_EPO_EP1234567_20240101_A1" - - -def _author_with_topics(author_id: str, name: str, topic_ids: list[str]) -> Author: - return Author( - id=f"https://openalex.org/{author_id}", - display_name=name, - topics=[WorkTopic(id=tid, display_name=f"Topic {tid}") for tid in topic_ids], - ) - - -def _mapped_topics(*topic_ids: str) -> list[MappedOpenAlexTopic]: - return [ - MappedOpenAlexTopic(topic_id=tid, topic_display_name=f"Topic {tid}") - for tid in topic_ids - ] - - -def test_topic_corroborated_patents_keeps_two_overlapping_topics() -> None: - author = _author_with_topics( - "A123", "Wei Zhang", - ["https://openalex.org/T1", "https://openalex.org/T2"], - ) - patent = _patent("EP1") - patent_topic_map = { - patent_map_key(patent): _mapped_topics( - "https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3" - ), - } - - result = topic_corroborated_patents([patent], author, patent_topic_map) - - assert result == [patent] - - -def test_topic_corroborated_patents_drops_single_coincidental_overlap() -> None: - """A single shared topic isn't enough — broad, common topics show up on - many unrelated patents and profiles by coincidence.""" - author = _author_with_topics( - "A123", "Xin Wang", - ["https://openalex.org/T1", "https://openalex.org/T9"], - ) - patent = _patent("EP2") - patent_topic_map = { - patent_map_key(patent): _mapped_topics( - "https://openalex.org/T1", "https://openalex.org/T2", "https://openalex.org/T3" - ), - } - - result = topic_corroborated_patents([patent], author, patent_topic_map) - - assert result == [] - - -def test_topic_corroborated_patents_drops_patent_without_mapped_topics() -> None: - author = _author_with_topics("A123", "Wei Zhang", ["https://openalex.org/T1"]) - patent = _patent("EP3") - - result = topic_corroborated_patents([patent], author, {}) - - assert result == [] - - -def test_topic_corroborated_patents_rejects_everything_without_author_topic_profile() -> None: - author = Author(id="https://openalex.org/A999", display_name="Wei Zhang") - patent = _patent("EP4") - patent_topic_map = { - patent_map_key(patent): _mapped_topics( - "https://openalex.org/T1", "https://openalex.org/T2" - ), - } - - result = topic_corroborated_patents([patent], author, patent_topic_map) - - assert result == [] - - -def test_primary_classification_codes_keeps_only_afi_marked_codes() -> None: - """A patent with many secondary ("ALI") codes alongside its one primary - ("AFI") code must only contribute the primary one — otherwise a large - secondary-code topic cloud makes coincidental multi-topic overlaps with - an unrelated same-named author far too easy (confirmed against a real - org_patents rebuild: a 20-code patent picked up 70+ topics).""" - patent = _patent("EP1") - patent.ipc = [ - "G06V 10/776 20220101AFI20250422BHUS", - "G01N 33/569 20060101ALI20250422BHUS", - "G06T 5/20 20060101ALI20250422BHUS", - ] - patent.cpc = ["G16H 30/40 20180101ALI20250422BHUS"] - - result = primary_classification_codes(patent) - - assert result == ["G06V 10/776 20220101AFI20250422BHUS"] - - -def test_primary_classification_codes_falls_back_to_all_codes_without_afi_marker() -> None: - patent = _patent("EP2") - patent.ipc = ["G06V 10/776 20220101ALI20250422BHUS"] - patent.cpc = ["G01N 33/569 20060101ALI20250422BHUS"] - - result = primary_classification_codes(patent) - - assert result == patent.ipc + patent.cpc - - diff --git a/webapp/src/app/api/model/keywordEvidence.ts b/webapp/src/app/api/model/keywordEvidence.ts new file mode 100644 index 00000000..5df71c34 --- /dev/null +++ b/webapp/src/app/api/model/keywordEvidence.ts @@ -0,0 +1,10 @@ +export interface KeywordEvidence { + phrase_in_title?: boolean; + phrase_in_abstract?: boolean; + full_token_match?: boolean; + partial_token_match?: boolean; + word_match_score?: number; + matched_phrases?: Array; + matched_words?: Array; + text_match_kind?: string; +} diff --git a/webapp/src/app/api/model/keywordPatentMatch.ts b/webapp/src/app/api/model/keywordPatentMatch.ts index 59dfeaae..60aa48d1 100644 --- a/webapp/src/app/api/model/keywordPatentMatch.ts +++ b/webapp/src/app/api/model/keywordPatentMatch.ts @@ -8,6 +8,7 @@ * Do not edit the class manually. */ import { PatentEntry } from './patentEntry'; +import { KeywordEvidence } from './keywordEvidence'; export interface KeywordPatentMatch { patent: PatentEntry; @@ -29,4 +30,10 @@ export interface KeywordPatentMatch { text_score: number; matched_keywords?: Array; matched_ipc_symbols?: Array; + /** + * True when retrieved via title/abstract text search because IPC mapping was uncertain, missing, or yielded no hits. + */ + text_retrieval?: boolean; + keyword_evidence?: KeywordEvidence | null; + topic_match_kind?: string | null; } diff --git a/webapp/src/app/api/model/patentsByKeywordsResponse.ts b/webapp/src/app/api/model/patentsByKeywordsResponse.ts index fe9bec64..ee762c7c 100644 --- a/webapp/src/app/api/model/patentsByKeywordsResponse.ts +++ b/webapp/src/app/api/model/patentsByKeywordsResponse.ts @@ -9,7 +9,15 @@ */ import { KeywordPatentMatch } from './keywordPatentMatch'; +export type KeywordPatentMappingStatus = + | 'mapped' + | 'uncertain' + | 'no_mapping' + | 'no_patents_found' + | 'search_error'; + export interface PatentsByKeywordsResponse { patent_count: number; patents: Array; + mapping_status: KeywordPatentMappingStatus; } diff --git a/webapp/src/app/modules/institution/institution.component.ts b/webapp/src/app/modules/institution/institution.component.ts index 61d0d938..3bc06ee1 100644 --- a/webapp/src/app/modules/institution/institution.component.ts +++ b/webapp/src/app/modules/institution/institution.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, inject } from '@angular/core'; import { ActivatedRoute, RouterLink, @@ -6,9 +6,12 @@ import { RouterLinkActive, } from '@angular/router'; import { Institution } from '../../api'; +import { PatentsService } from '../../api/api/patents.service'; import { MatCardModule } from '@angular/material/card'; import { MatTabsModule } from '@angular/material/tabs'; +const PATENTS_LINK = { label: 'Patente', path: 'patents', disabled: false }; + @Component({ selector: 'app-institution', imports: [ @@ -22,6 +25,8 @@ import { MatTabsModule } from '@angular/material/tabs'; styleUrl: './institution.component.scss', }) export class InstitutionComponent implements OnInit { + private readonly patentsApi = inject(PatentsService); + institution!: Institution; links = [ @@ -40,7 +45,6 @@ export class InstitutionComponent implements OnInit { sort_direction: 'asc', }, }, - { label: 'Patente', path: 'patents', disabled: false }, ]; constructor(private readonly activatedRoute: ActivatedRoute) {} @@ -49,5 +53,19 @@ export class InstitutionComponent implements OnInit { this.activatedRoute.data.subscribe(({ institution }) => { this.institution = institution; }); + + const institutionId = this.activatedRoute.snapshot.paramMap.get('institutionId'); + if (!institutionId) return; + + // The "Patente" tab only makes sense once org_patents has been indexed for + // this institution (currently a manual, ~30-40 min-per-institution process), + // so only show it once we know there is actually data behind it. + this.patentsApi.getOrgPatentsByInstitution(institutionId, undefined, 0, 0).subscribe({ + next: (result) => { + if ((result.patent_count ?? 0) > 0) { + this.links = [...this.links, PATENTS_LINK]; + } + }, + }); } } diff --git a/webapp/src/app/modules/institutions/institutions.component.html b/webapp/src/app/modules/institutions/institutions.component.html index 26fe07c3..42df50d1 100644 --- a/webapp/src/app/modules/institutions/institutions.component.html +++ b/webapp/src/app/modules/institutions/institutions.component.html @@ -75,17 +75,19 @@ work Projekte - - verified - Patente - + @if (hasPatents(institution)) { + + verified + Patente + + } diff --git a/webapp/src/app/modules/institutions/institutions.component.ts b/webapp/src/app/modules/institutions/institutions.component.ts index 57c734df..a8735d33 100644 --- a/webapp/src/app/modules/institutions/institutions.component.ts +++ b/webapp/src/app/modules/institutions/institutions.component.ts @@ -1,5 +1,6 @@ -import { Component, computed, input } from '@angular/core'; +import { Component, computed, effect, inject, input } from '@angular/core'; import { Institution, InstitutionPage } from '../../api'; +import { PatentsService } from '../../api/api/patents.service'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { RouterModule } from '@angular/router'; @@ -27,6 +28,8 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter styleUrl: './institutions.component.scss', }) export class InstitutionsComponent { + private readonly patentsApi = inject(PatentsService); + institutionPage = input.required(); observers: FilterObserver[] = [ @@ -44,6 +47,31 @@ export class InstitutionsComponent { elements: this.institutionPage().elements || [], })); + // The "Patente" action only makes sense once org_patents has been indexed + // for that institution (currently a manual, per-institution process), so + // it's hidden by default and only shown once a cheap count check confirms + // there is actually data behind it. + private readonly patentsAvailable = new Map(); + + constructor() { + effect(() => { + for (const institution of this.page().elements) { + const id = this.extractInstitutionId(institution); + if (!id || this.patentsAvailable.has(id)) continue; + this.patentsAvailable.set(id, false); + this.patentsApi.getOrgPatentsByInstitution(id, undefined, 0, 0).subscribe({ + next: (result) => { + this.patentsAvailable.set(id, (result.patent_count ?? 0) > 0); + }, + }); + } + }); + } + + hasPatents(institution: Institution): boolean { + return this.patentsAvailable.get(this.extractInstitutionId(institution)) ?? false; + } + sortingOptions: SelectorOption[] = [ { value: 'relevance', display_name: 'Relevanz' }, { value: 'name', display_name: 'Name' }, diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html index e9fecdf1..7f3312ef 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.html @@ -1,7 +1,11 @@ @if (loading()) {
-

Lade passende Patente...

+
} @else if (error()) {
@@ -11,7 +15,7 @@ } @else if (matches().length === 0) {
-

Keine passenden Patente gefunden.

+

{{ emptyMessage() }}

} @else {
diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss index ae2481f3..18059791 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.scss @@ -3,6 +3,15 @@ color: #666; } +.fallback-notice { + margin: 0 0 12px; + padding: 10px 12px; + border-radius: 8px; + background: #f4f7fb; + color: #3d4f63; + font-size: 0.9rem; +} + .section-title { margin: 0; font-size: 1.25rem; diff --git a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts index 1fe27272..e1c00415 100644 --- a/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts +++ b/webapp/src/app/modules/keywords-search/keywords-patents/keywords-patents.component.ts @@ -5,6 +5,8 @@ import { MatIconModule } from '@angular/material/icon'; import { Router } from '@angular/router'; import { PatentEntry } from '../../../api/model/patentEntry'; import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch'; +import { KeywordPatentMappingStatus } from '../../../api/model/patentsByKeywordsResponse'; +import { LoadingComponent } from '../../../shared/ui/loading/loading.component'; import { formatPatentDate, getPublicationStageLabel, @@ -14,12 +16,13 @@ type SourceFilter = 'all' | 'EPO' | 'USPTO'; @Component({ selector: 'app-keywords-patents', - imports: [NgTemplateOutlet, MatButtonModule, MatIconModule], + imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent], templateUrl: './keywords-patents.component.html', styleUrl: './keywords-patents.component.scss', }) export class KeywordsPatentsComponent { readonly matches = input([]); + readonly mappingStatus = input(null); readonly loading = input(false); readonly error = input(false); readonly showReload = input(false); @@ -33,6 +36,15 @@ export class KeywordsPatentsComponent { constructor(private readonly router: Router) {} + emptyMessage(): string { + switch (this.mappingStatus()) { + case 'search_error': + return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.'; + default: + return 'Keine passenden Patente gefunden'; + } + } + filteredMatches(): KeywordPatentMatch[] { const filter = this.activeFilter(); const items = this.matches(); diff --git a/webapp/src/app/modules/keywords-search/patent-search.utils.ts b/webapp/src/app/modules/keywords-search/patent-search.utils.ts index 25496431..9a77b9c9 100644 --- a/webapp/src/app/modules/keywords-search/patent-search.utils.ts +++ b/webapp/src/app/modules/keywords-search/patent-search.utils.ts @@ -1,6 +1,9 @@ import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic'; import { KeywordPatentMatch } from '../../api/model/keywordPatentMatch'; import { KeywordPatentSearchItem } from '../../api/model/keywordPatentSearchItem'; +import { + KeywordPatentMappingStatus, +} from '../../api/model/patentsByKeywordsResponse'; import { PatentKeywordEntry, SearchResultsPayload, @@ -8,9 +11,17 @@ import { export const PATENTS_CACHE_KEY = 'keywords-patents-cache'; +export type { KeywordPatentMappingStatus }; + export interface PatentsCache { keywords: string[]; matches: KeywordPatentMatch[]; + mappingStatus?: KeywordPatentMappingStatus | null; +} + +export interface PatentsCacheResult { + matches: KeywordPatentMatch[]; + mappingStatus: KeywordPatentMappingStatus | null; } export function buildPatentSearchItems( @@ -58,14 +69,17 @@ export function buildPatentSearchItemsFromPayload( export function readPatentsCache( keywords: string[], -): KeywordPatentMatch[] | null { +): PatentsCacheResult | null { const raw = sessionStorage.getItem(PATENTS_CACHE_KEY); if (!raw) return null; try { const cache = JSON.parse(raw) as PatentsCache; if (!sameKeywordSet(cache.keywords, keywords)) return null; - return cache.matches ?? []; + return { + matches: cache.matches ?? [], + mappingStatus: cache.mappingStatus ?? null, + }; } catch { sessionStorage.removeItem(PATENTS_CACHE_KEY); return null; @@ -75,9 +89,10 @@ export function readPatentsCache( export function writePatentsCache( keywords: string[], matches: KeywordPatentMatch[], + mappingStatus: KeywordPatentMappingStatus | null = null, ): void { try { - const cache: PatentsCache = { keywords, matches }; + const cache: PatentsCache = { keywords, matches, mappingStatus }; sessionStorage.setItem(PATENTS_CACHE_KEY, JSON.stringify(cache)); } catch (error) { console.error('Failed to cache patent results:', error); diff --git a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html index 87d668f6..3e0cb344 100644 --- a/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/patents-results/patents-results.component.html @@ -22,6 +22,7 @@
([]); + readonly mappingStatus = signal(null); readonly loadingPatents = signal(false); readonly patentsError = signal(false); @@ -91,7 +95,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit { ngOnInit(): void { const cached = readPatentsCache(this.state.keywords()); if (cached) { - this.setPatentMatches(cached); + this.setPatentMatches(cached.matches, cached.mappingStatus); return; } @@ -119,7 +123,7 @@ export class KeywordsToPatentsResultsComponent implements OnInit { private loadMatchingPatents(): void { const keywords = buildPatentSearchItemsFromPayload(this.state.payload()); if (keywords.length === 0) { - this.setPatentMatches([]); + this.setPatentMatches([], 'no_mapping'); return; } @@ -128,22 +132,33 @@ export class KeywordsToPatentsResultsComponent implements OnInit { this.keywordsService.getPatentsByKeywords({ keywords }).subscribe({ next: (response: PatentsByKeywordsResponse) => { - this.setPatentMatches(response.patents ?? []); + this.setPatentMatches( + response.patents ?? [], + response.mapping_status ?? null, + ); this.loadingPatents.set(false); }, error: (error: unknown) => { console.error('Patent search failed:', error); - this.setPatentMatches([]); + this.setPatentMatches([], null); this.patentsError.set(true); this.loadingPatents.set(false); }, }); } - private setPatentMatches(matches: KeywordPatentMatch[]): void { + private setPatentMatches( + matches: KeywordPatentMatch[], + mappingStatus: KeywordPatentMappingStatus | null = null, + ): void { this.patentMatchesBase.set(matches); + this.mappingStatus.set(mappingStatus); this.updateDisplayedMatches(); - writePatentsCache(this.state.keywords(), this.patentMatchesBase()); + writePatentsCache( + this.state.keywords(), + this.patentMatchesBase(), + mappingStatus, + ); } private updateDisplayedMatches(): void { diff --git a/webapp/src/app/modules/patent-detail/patent-detail.component.ts b/webapp/src/app/modules/patent-detail/patent-detail.component.ts index 013f39a4..fb314d3a 100644 --- a/webapp/src/app/modules/patent-detail/patent-detail.component.ts +++ b/webapp/src/app/modules/patent-detail/patent-detail.component.ts @@ -11,7 +11,10 @@ import { PatentsService } from '../../api/api/patents.service'; import { PatentEntry } from '../../api/model/patentEntry'; import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; -import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { + classificationSectionColor, + topicHierarchyColor, +} from '../../resolvers/utils/topic-colors'; import { ClassificationCard, ClassificationSystem, @@ -107,7 +110,7 @@ export class PatentDetailComponent implements OnInit { } sectionColor(card: ClassificationCard): string { - return topicHierarchyColor({ field_name: card.sectionName }); + return classificationSectionColor(card.sectionName ?? card.symbols[0]); } toggleClassificationExpanded(key: string): void { diff --git a/webapp/src/app/modules/patents/patents.component.ts b/webapp/src/app/modules/patents/patents.component.ts index d1c99016..bbf90d41 100644 --- a/webapp/src/app/modules/patents/patents.component.ts +++ b/webapp/src/app/modules/patents/patents.component.ts @@ -17,7 +17,10 @@ import { IpcClassification } from '../../api'; import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { LoadingComponent } from '../../shared/ui/loading/loading.component'; -import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; +import { + classificationSectionColor, + topicHierarchyColor, +} from '../../resolvers/utils/topic-colors'; type SourceFilter = 'all' | 'EPO' | 'USPTO'; @@ -404,7 +407,7 @@ export class PatentsComponent implements OnInit { } sectionColor(card: ClassificationCard): string { - return topicHierarchyColor({ field_name: card.sectionName }); + return classificationSectionColor(card.sectionName ?? card.symbols[0]); } private getClassificationLevel(entry: IpcClassification): { diff --git a/webapp/src/app/resolvers/utils/topic-colors.ts b/webapp/src/app/resolvers/utils/topic-colors.ts index 1d2b69d9..eb9b97bb 100644 --- a/webapp/src/app/resolvers/utils/topic-colors.ts +++ b/webapp/src/app/resolvers/utils/topic-colors.ts @@ -53,6 +53,29 @@ const DOMAIN_FALLBACK_HUES: Record = { const FIELD_COLOR_SATURATION = 86; const FIELD_COLOR_LIGHTNESS = 36; +// IPC/CPC section titles (e.g. "F - Mechanical engineering; Lighting; ...") +// never match the academic FIELD_HUES keys above, so they need their own +// fixed hue per section letter to avoid an effectively random hash color. +const IPC_SECTION_HUES: Record = { + A: 342, // Human Necessities (agriculture, foodstuffs, health) + B: 204, // Performing Operations; Transporting + C: 184, // Chemistry; Metallurgy + D: 262, // Textiles; Paper + E: 96, // Fixed Constructions + F: 88, // Mechanical Engineering; Lighting; Heating; Weapons; Blasting + G: 250, // Physics + H: 222, // Electricity +}; + +export function classificationSectionColor( + section: string | null | undefined, +): string { + const letter = section?.trim().charAt(0).toUpperCase(); + const hue = (letter ? IPC_SECTION_HUES[letter] : undefined) ?? stableHue(section ?? 'section'); + + return `hsl(${normalizeHue(hue)} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`; +} + export function topicHierarchyColor( topic: TopicHierarchyColorInput | undefined | null, ): string {