feat(keywords): show patents for extracted keywords
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
This commit is contained in:
@@ -1,280 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
build_ipc_openalex_mapping.py — Build a 1:1 IPC/CPC → OpenAlex topic mapping file.
|
||||
|
||||
Scans the `ipc` Elasticsearch index, matches each hierarchy level (section, class,
|
||||
subclass, group, subgroup) to the closest OpenAlex topic from topic_hierarchy_cache.json,
|
||||
and writes service/src/data/ipc_openalex_topic_mapping.json.
|
||||
|
||||
Usage:
|
||||
python scripts/build_ipc_openalex_mapping.py
|
||||
python scripts/build_ipc_openalex_mapping.py --output ../src/data/ipc_openalex_topic_mapping.json
|
||||
python scripts/build_ipc_openalex_mapping.py --min-score 0.35
|
||||
|
||||
Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials for the ipc index.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from inse.integrations import elasticsearch # noqa: E402
|
||||
from inse.model import ESCluster # noqa: E402
|
||||
from inse.patents.ipc_search_client import IPC_INDEX # noqa: E402
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = (
|
||||
("section", "cpc_section_number", "cpc_section_name"),
|
||||
("class", "cpc_class_number", "cpc_class_name"),
|
||||
("group", "cpc_group_number", "cpc_group_name"),
|
||||
("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"),
|
||||
)
|
||||
BUILD_LEVELS = ("section", "class", "subclass")
|
||||
|
||||
|
||||
def _normalize_symbol(symbol: str | None) -> str:
|
||||
if not symbol:
|
||||
return ""
|
||||
return symbol.strip().upper().replace(" ", "")
|
||||
|
||||
|
||||
def _infer_subclass(symbol: str | None) -> str | None:
|
||||
if not symbol:
|
||||
return None
|
||||
cleaned = _normalize_symbol(symbol)
|
||||
match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned)
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def _load_topic_cache() -> list[dict]:
|
||||
cache_path = current_dir.parent / "src" / "data" / "topic_hierarchy_cache.json"
|
||||
with cache_path.open(encoding="utf-8") as handle:
|
||||
raw = json.load(handle)
|
||||
topics = []
|
||||
for display_name, info in raw.items():
|
||||
topics.append(
|
||||
{
|
||||
"display_name": display_name,
|
||||
"topic_id": info.get("topic_id"),
|
||||
"subfield": info.get("subfield"),
|
||||
"field": info.get("field"),
|
||||
"domain": info.get("domain"),
|
||||
}
|
||||
)
|
||||
return topics
|
||||
|
||||
|
||||
def _tokenize(text: str) -> set[str]:
|
||||
return {token for token in re.findall(r"[a-z0-9]+", text.casefold()) if len(token) > 2}
|
||||
|
||||
|
||||
def _prepare_topics(topics: list[dict]) -> tuple[list[dict], dict[str, set[int]]]:
|
||||
prepared: list[dict] = []
|
||||
index: dict[str, set[int]] = defaultdict(set)
|
||||
for idx, topic in enumerate(topics):
|
||||
labels = [
|
||||
topic["display_name"],
|
||||
topic.get("subfield"),
|
||||
topic.get("field"),
|
||||
topic.get("domain"),
|
||||
]
|
||||
tokens: set[str] = set()
|
||||
for label in labels:
|
||||
if label:
|
||||
tokens |= _tokenize(label)
|
||||
prepared.append({**topic, "_tokens": tokens, "_labels": [l for l in labels if l]})
|
||||
for token in tokens:
|
||||
index[token].add(idx)
|
||||
return prepared, index
|
||||
|
||||
|
||||
def _score_label(ipc_label: str, topic: dict) -> float:
|
||||
ipc_text = ipc_label.casefold()
|
||||
ipc_tokens = _tokenize(ipc_label)
|
||||
best = 0.0
|
||||
for candidate in topic["_labels"]:
|
||||
candidate_text = candidate.casefold()
|
||||
ratio = SequenceMatcher(None, ipc_text, candidate_text).ratio()
|
||||
token_overlap = len(ipc_tokens & topic["_tokens"])
|
||||
token_score = token_overlap / max(len(ipc_tokens), 1)
|
||||
best = max(best, ratio, token_score)
|
||||
return best
|
||||
|
||||
|
||||
def _best_topic_match(
|
||||
ipc_label: str,
|
||||
topics: list[dict],
|
||||
topic_index: dict[str, set[int]],
|
||||
min_score: float,
|
||||
) -> dict | None:
|
||||
ipc_tokens = _tokenize(ipc_label)
|
||||
candidate_indices: set[int] = set()
|
||||
for token in ipc_tokens:
|
||||
candidate_indices |= topic_index.get(token, set())
|
||||
if not candidate_indices:
|
||||
return None
|
||||
|
||||
best_topic = None
|
||||
best_score = 0.0
|
||||
for idx in list(candidate_indices)[:100]:
|
||||
topic = topics[idx]
|
||||
score = _score_label(ipc_label, topic)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_topic = topic
|
||||
if best_topic is None or best_score < min_score:
|
||||
return None
|
||||
return {
|
||||
"topic_id": best_topic["topic_id"],
|
||||
"topic_display_name": best_topic["display_name"],
|
||||
"subfield": best_topic.get("subfield"),
|
||||
"field": best_topic.get("field"),
|
||||
"domain": best_topic.get("domain"),
|
||||
"match_score": round(best_score, 3),
|
||||
}
|
||||
|
||||
|
||||
async def _fetch_unique_ipc_entries() -> dict[str, dict[str, str]]:
|
||||
entries: dict[str, dict[str, str]] = defaultdict(dict)
|
||||
|
||||
async def _terms_with_label(
|
||||
level: str,
|
||||
number_field: str,
|
||||
name_field: str,
|
||||
size: int,
|
||||
) -> None:
|
||||
for field_name in (number_field, f"{number_field}.keyword"):
|
||||
payload = {
|
||||
"size": 0,
|
||||
"aggs": {
|
||||
"items": {
|
||||
"terms": {"field": field_name, "size": size},
|
||||
"aggs": {
|
||||
"sample": {
|
||||
"top_hits": {"size": 1, "_source": [name_field]},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
try:
|
||||
data = await elasticsearch.search(
|
||||
index=IPC_INDEX,
|
||||
body=payload,
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
buckets = data.get("aggregations", {}).get("items", {}).get("buckets", [])
|
||||
if buckets:
|
||||
break
|
||||
else:
|
||||
return
|
||||
for bucket in buckets:
|
||||
symbol = bucket.get("key")
|
||||
hits = bucket.get("sample", {}).get("hits", {}).get("hits", [])
|
||||
if not symbol or not hits:
|
||||
continue
|
||||
name = hits[0].get("_source", {}).get(name_field)
|
||||
if not name:
|
||||
continue
|
||||
normalized = _normalize_symbol(str(symbol))
|
||||
if level == "class" and len(normalized) != 3:
|
||||
continue
|
||||
if level == "subclass":
|
||||
if len(normalized) <= 3:
|
||||
continue
|
||||
normalized = _infer_subclass(str(symbol)) or normalized
|
||||
entries[level][normalized] = str(name).strip()
|
||||
|
||||
if "section" in BUILD_LEVELS:
|
||||
await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30)
|
||||
if "class" in BUILD_LEVELS:
|
||||
await _terms_with_label("class", "cpc_class_number", "cpc_class_name", 500)
|
||||
if "subclass" in BUILD_LEVELS:
|
||||
await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000)
|
||||
if "group" in BUILD_LEVELS:
|
||||
await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000)
|
||||
if "subgroup" in BUILD_LEVELS:
|
||||
await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000)
|
||||
return entries
|
||||
|
||||
|
||||
def build_mapping(ipc_entries: dict[str, dict[str, str]], topics: list[dict], min_score: float) -> dict:
|
||||
prepared_topics, topic_index = _prepare_topics(topics)
|
||||
mapping = {level: {} for level in ("section", "class", "subclass", "group", "subgroup")}
|
||||
label_cache: dict[tuple[str, str], dict | None] = {}
|
||||
total = sum(len(symbols) for level, symbols in ipc_entries.items() if level in BUILD_LEVELS)
|
||||
processed = 0
|
||||
|
||||
for level in BUILD_LEVELS:
|
||||
symbols = ipc_entries.get(level, {})
|
||||
for symbol, label in symbols.items():
|
||||
processed += 1
|
||||
if processed % 500 == 0:
|
||||
logger.info("Mapped %d / %d ipc symbols", processed, total)
|
||||
cache_key = (level, label.casefold())
|
||||
if cache_key not in label_cache:
|
||||
label_cache[cache_key] = _best_topic_match(
|
||||
label, prepared_topics, topic_index, min_score
|
||||
)
|
||||
match = label_cache[cache_key]
|
||||
if match is None:
|
||||
continue
|
||||
mapping[level][symbol] = {
|
||||
"topic_id": match["topic_id"],
|
||||
"topic_display_name": match["topic_display_name"],
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"ipc_label": label,
|
||||
"match_score": match["match_score"],
|
||||
}
|
||||
return mapping
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build IPC/CPC → OpenAlex topic mapping JSON.")
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=str(current_dir.parent / "src" / "data" / "ipc_openalex_topic_mapping.json"),
|
||||
help="Output JSON path",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--min-score",
|
||||
type=float,
|
||||
default=0.35,
|
||||
help="Minimum label similarity score for a 1:1 assignment",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
topics = _load_topic_cache()
|
||||
logger.info("Loaded %d OpenAlex topics from cache", len(topics))
|
||||
|
||||
ipc_entries = await _fetch_unique_ipc_entries()
|
||||
counts = {level: len(ipc_entries.get(level, {})) for level in BUILD_LEVELS}
|
||||
logger.info("Fetched unique ipc symbols: %s", counts)
|
||||
|
||||
mapping = build_mapping(ipc_entries, topics, args.min_score)
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(json.dumps(mapping, indent=2, ensure_ascii=True), encoding="utf-8")
|
||||
|
||||
counts = {level: len(mapping[level]) for level in mapping}
|
||||
logger.info("Wrote mapping to %s: %s", output_path, counts)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,78 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Quick check of patent counts for specific authors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import clear_mapping_cache
|
||||
from inse.patents.authors.logic import get_patents_by_author_id
|
||||
from inse.patents.authors.name_matching import filter_patents_by_author_name
|
||||
from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
|
||||
from inse.patents.authors.identity import is_ambiguous_name
|
||||
from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
from inse.persons import logic as person_logic
|
||||
|
||||
|
||||
AUTHORS = [
|
||||
("Dirk Schadendorf", "A5034365278", 8),
|
||||
("Christian Weber", "A5100603203", 14),
|
||||
]
|
||||
|
||||
|
||||
async def _counts(author_id: str) -> dict:
|
||||
search_client = PatentSearchClient()
|
||||
ipc_client = IpcSearchClient()
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
person = await person_logic.search_persons(author_id=short_id)
|
||||
author = person.results[0] if person.results else None
|
||||
if not author or not author.display_name:
|
||||
return {"error": "author not found"}
|
||||
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)),
|
||||
search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)),
|
||||
)
|
||||
all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data))
|
||||
name_matched = filter_patents_by_author_name(all_patents, author.display_name)
|
||||
await enrich_patents_classifications(name_matched, ipc_client)
|
||||
full_name_count = await person_logic.count_authors_by_display_name(author.display_name)
|
||||
ambiguous = is_ambiguous_name(
|
||||
author.display_name,
|
||||
patent_hit_count=len(all_patents),
|
||||
openalex_full_name_count=full_name_count,
|
||||
)
|
||||
filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous)
|
||||
return {
|
||||
"author_name": author.display_name,
|
||||
"es_hits": len(all_patents),
|
||||
"name_matched": len(name_matched),
|
||||
"after_topic_filter": len(filtered),
|
||||
"ambiguous": ambiguous,
|
||||
"openalex_same_name": full_name_count,
|
||||
"titles": [item.patent.title for item in filtered],
|
||||
}
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
clear_mapping_cache()
|
||||
for label, author_id, expected in AUTHORS:
|
||||
result = await _counts(author_id)
|
||||
print(f"\n=== {label} ({author_id}) expected={expected} ===")
|
||||
for key, value in result.items():
|
||||
if key == "titles":
|
||||
print(f"{key}:")
|
||||
for title in value:
|
||||
print(f" - {title}")
|
||||
else:
|
||||
print(f"{key}: {value}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Per-patent breakdown of topic-filter decisions for test authors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import (
|
||||
clear_mapping_cache,
|
||||
load_ipc_openalex_mapping,
|
||||
patent_topics_match_author,
|
||||
resolve_mapped_topics_for_patent,
|
||||
)
|
||||
from inse.patents.authors.name_matching import filter_patents_by_author_name
|
||||
from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
|
||||
from inse.patents.authors.identity import is_ambiguous_name, patent_institution_match, patent_personal_assignee_match
|
||||
from inse.patents.common.parsing import deduplicate_patents, enrich_patents_classifications, parse_epo_hits, parse_uspto_hits
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
from inse.persons import logic as person_logic
|
||||
|
||||
AUTHORS = [
|
||||
("Dirk Schadendorf", "A5034365278"),
|
||||
("Christian Weber", "A5100603203"),
|
||||
]
|
||||
|
||||
|
||||
async def diagnose(author_id: str) -> None:
|
||||
search_client = PatentSearchClient()
|
||||
ipc_client = IpcSearchClient()
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
person = await person_logic.search_persons(author_id=short_id)
|
||||
author = person.results[0]
|
||||
mapping = load_ipc_openalex_mapping()
|
||||
|
||||
print(f"\n{'='*70}")
|
||||
print(f"{author.display_name} ({author_id})")
|
||||
print("Author topics:")
|
||||
for t in author.topics or []:
|
||||
print(f" - {t.display_name} ({t.id})")
|
||||
|
||||
institutions = []
|
||||
for inst in author.last_known_institutions or []:
|
||||
institutions.append(inst.display_name)
|
||||
for aff in author.affiliations or []:
|
||||
if aff.institution:
|
||||
institutions.append(aff.institution.display_name)
|
||||
print("Institutions:", institutions)
|
||||
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
search_client.search_epo(search_client.epo_query_by_inventor(author.display_name)),
|
||||
search_client.search_uspto(search_client.uspto_query_by_inventor(author.display_name)),
|
||||
)
|
||||
all_patents = deduplicate_patents(parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data))
|
||||
name_matched = filter_patents_by_author_name(all_patents, author.display_name)
|
||||
await enrich_patents_classifications(name_matched, ipc_client)
|
||||
full_name_count = await person_logic.count_authors_by_display_name(author.display_name)
|
||||
ambiguous = is_ambiguous_name(
|
||||
author.display_name,
|
||||
patent_hit_count=len(all_patents),
|
||||
openalex_full_name_count=full_name_count,
|
||||
)
|
||||
print(f"ambiguous={ambiguous}, name_matched={len(name_matched)}")
|
||||
|
||||
filtered = filter_patents_by_ipc_topic_mapping(name_matched, author, is_ambiguous=ambiguous)
|
||||
kept_ids = {item.patent.patent_id for item in filtered}
|
||||
|
||||
for i, patent in enumerate(name_matched, 1):
|
||||
mapped = resolve_mapped_topics_for_patent(patent, mapping)
|
||||
topic_match = patent_topics_match_author(patent, author, mapping)
|
||||
inst_match = patent_institution_match(patent, institutions)
|
||||
pers_match = patent_personal_assignee_match(patent, author.display_name or "")
|
||||
kept = patent.patent_id in kept_ids
|
||||
mapped_labels = [m.topic_display_name or m.topic_id for m in mapped]
|
||||
ipc = patent.ipc[:3] if patent.ipc else []
|
||||
cpc = patent.cpc[:2] if patent.cpc else []
|
||||
print(f"\n[{i}] {'KEEP' if kept else 'DROP'} | {patent.title[:70] if patent.title else '?'}")
|
||||
print(f" ipc={ipc} cpc={cpc}")
|
||||
print(f" mapped={mapped_labels or 'NONE'}")
|
||||
print(f" topic_match={topic_match} inst={inst_match} personal={pers_match}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
clear_mapping_cache()
|
||||
for label, author_id in AUTHORS:
|
||||
await diagnose(author_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Diagnose keyword → patent search for a given keyword."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import _load_topic_cache
|
||||
from inse.patents.keywords.logic import _patent_search_terms, get_patents_by_keywords
|
||||
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
|
||||
from inse.patents.keywords.reverse_lookup import KeywordIpcReverseLookup
|
||||
|
||||
|
||||
def _find_topic(keyword: str) -> tuple[str, dict]:
|
||||
cache = _load_topic_cache()
|
||||
keyword_lower = keyword.casefold()
|
||||
for name, info in cache.items():
|
||||
if keyword_lower in name.casefold():
|
||||
return name, info
|
||||
for name, info in cache.items():
|
||||
if info.get("subfield", "").casefold() == keyword_lower:
|
||||
return name, info
|
||||
return keyword, {}
|
||||
|
||||
|
||||
async def diagnose(keyword: str, topic_name: str | None, topic_id: str | None) -> None:
|
||||
if topic_name and topic_id:
|
||||
display_name = topic_name
|
||||
tid = topic_id
|
||||
info = _load_topic_cache().get(topic_name, {})
|
||||
else:
|
||||
display_name, info = _find_topic(keyword)
|
||||
tid = info.get("topic_id")
|
||||
|
||||
item = KeywordPatentSearchItem(
|
||||
keyword=keyword,
|
||||
topic_id=tid,
|
||||
topic_display_name=display_name,
|
||||
subfield_name=info.get("subfield"),
|
||||
field_name=info.get("field"),
|
||||
relevance_score=1.0,
|
||||
)
|
||||
print(f"Keyword: {keyword}")
|
||||
print(f"Topic: {display_name} ({tid})")
|
||||
print(f"Subfield: {info.get('subfield')} | Field: {info.get('field')}")
|
||||
|
||||
lookup = KeywordIpcReverseLookup()
|
||||
ipc = await lookup.lookup_ipc_codes([item])
|
||||
print(f"\nIPC matches ({len(ipc)}):")
|
||||
for match in ipc[:20]:
|
||||
print(
|
||||
f" {match.ipc_symbol:14} score={match.match_score:.3f} "
|
||||
f"type={match.match_type}"
|
||||
)
|
||||
|
||||
terms = _patent_search_terms(ipc)
|
||||
print(f"\nPatent search terms ({len(terms)}): {terms}")
|
||||
|
||||
response = await get_patents_by_keywords(PatentsByKeywordsRequest(keywords=[item]))
|
||||
print(f"\nPatents returned: {response.patent_count}")
|
||||
for entry in response.patents[:10]:
|
||||
patent = entry.patent
|
||||
title = (patent.title or "")[:60]
|
||||
print(
|
||||
f" score={entry.match_score:.3f} {patent.patent_id} "
|
||||
f"ipc={entry.matched_ipc_symbols} | {title}"
|
||||
)
|
||||
if patent.ipc:
|
||||
print(f" raw ipc: {patent.ipc[:2]}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("keyword", default="Medizin", nargs="?")
|
||||
parser.add_argument("--topic-name", default=None)
|
||||
parser.add_argument("--topic-id", default=None)
|
||||
args = parser.parse_args()
|
||||
asyncio.run(diagnose(args.keyword, args.topic_name, args.topic_id))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print IPC/CPC → OpenAlex topic/keyword matches from patents_openalex_keywords."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
|
||||
|
||||
DEFAULT_SYMBOLS = ("A", "A61", "A61B", "G01N", "C12N", "H04L")
|
||||
|
||||
|
||||
def _print_match_block(title: str, matches: list[dict]) -> None:
|
||||
print(f" {title}:")
|
||||
if not matches:
|
||||
print(" (none)")
|
||||
return
|
||||
for item in matches:
|
||||
if "keyword" in item:
|
||||
label = item.get("keyword")
|
||||
topic = item.get("topic_display_name") or item.get("topic_id")
|
||||
print(
|
||||
f" #{item.get('rank')} {label} "
|
||||
f"[topic={topic}, score={item.get('match_score')}]"
|
||||
)
|
||||
else:
|
||||
label = item.get("topic_display_name") or item.get("topic_id")
|
||||
print(f" #{item.get('rank')} {label} (score={item.get('match_score')})")
|
||||
|
||||
|
||||
async def diagnose_symbol(client: PatentsOpenAlexKeywordsClient, symbol: str) -> None:
|
||||
normalized = normalize_symbol(symbol)
|
||||
print(f"\n{'=' * 70}")
|
||||
print(f"IPC/CPC symbol: {normalized}")
|
||||
|
||||
doc = await client.lookup_symbol(normalized)
|
||||
if doc:
|
||||
print(f"Matched level: {doc.get('ipc_level')}")
|
||||
print(f"IPC label: {doc.get('ipc_label')}")
|
||||
_print_match_block("Topic matches", doc.get("topic_matches") or [])
|
||||
_print_match_block("Keyword matches", doc.get("keyword_matches") or [])
|
||||
return
|
||||
|
||||
subclass = infer_subclass(normalized)
|
||||
for level, candidate in (
|
||||
("subgroup", normalized),
|
||||
("group", normalized),
|
||||
("subclass", subclass),
|
||||
("class", normalized[:3] if len(normalized) >= 3 else None),
|
||||
("section", normalized[:1] if normalized else None),
|
||||
):
|
||||
if not candidate:
|
||||
continue
|
||||
doc = await client.lookup(level, candidate)
|
||||
if doc:
|
||||
print(f"Matched level: {doc.get('ipc_level')} (via fallback lookup)")
|
||||
print(f"IPC label: {doc.get('ipc_label')}")
|
||||
_print_match_block("Topic matches", doc.get("topic_matches") or [])
|
||||
_print_match_block("Keyword matches", doc.get("keyword_matches") or [])
|
||||
return
|
||||
|
||||
print(" No mapping found in patents_openalex_keywords.")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Diagnose IPC/CPC matches in patents_openalex_keywords.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"symbols",
|
||||
nargs="*",
|
||||
default=list(DEFAULT_SYMBOLS),
|
||||
help="IPC/CPC symbols to inspect",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = PatentsOpenAlexKeywordsClient()
|
||||
for symbol in args.symbols:
|
||||
await diagnose_symbol(client, symbol)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,7 @@ from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.service import router as university_ranking_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
from inse.patents.keywords.service import router as keywords_patents_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
@@ -90,6 +91,7 @@ app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
app.include_router(keywords_service_router)
|
||||
app.include_router(keywords_patents_router)
|
||||
|
||||
app.include_router(service_router)
|
||||
|
||||
|
||||
@@ -3,9 +3,15 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import (
|
||||
MappedOpenAlexTopic,
|
||||
normalize_openalex_id,
|
||||
)
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import (
|
||||
BasePatentSearchClient,
|
||||
@@ -16,8 +22,12 @@ from inse.patents.common.parsing import (
|
||||
enrich_patents_classifications,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
patent_map_key,
|
||||
)
|
||||
from inse.patents.ipc_lookup import (
|
||||
extract_ipc_symbol,
|
||||
parse_ipc_symbol,
|
||||
)
|
||||
from inse.patents.ipc_lookup import extract_ipc_symbol
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.keywords.model import (
|
||||
KeywordPatentMatch,
|
||||
@@ -26,19 +36,100 @@ from inse.patents.keywords.model import (
|
||||
PatentsByKeywordsResponse,
|
||||
)
|
||||
from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup
|
||||
from inse.patents.keywords.search_queries import (
|
||||
IpcPatentSearchQueries,
|
||||
_search_terms_for_symbol,
|
||||
)
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol
|
||||
from inse.patents.keywords.search_queries import IpcPatentSearchQueries
|
||||
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 = 40
|
||||
_MAX_PATENT_SEARCH_TERMS = 12
|
||||
_MIN_IPC_MATCH_SCORE = 0.45
|
||||
_MIN_PATENT_MATCH_SCORE = 0.35
|
||||
_MAX_IPC_CODES = 20
|
||||
_MAX_IPC_CODES_PER_KEYWORD = 2
|
||||
_MAX_PATENT_SEARCH_TERMS = 10
|
||||
_MAX_SEARCH_KEYWORDS = 10
|
||||
_MIN_KEYWORD_RELEVANCE = 0.0
|
||||
_MIN_IPC_MATCH_SCORE = 0.65
|
||||
_MIN_PATENT_MATCH_SCORE = 0.50
|
||||
_SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"})
|
||||
# Soft field overlap for natural-science / engineering patent domains.
|
||||
_SOFT_MATCH_FIELD_NAMES = frozenset(
|
||||
{
|
||||
"engineering",
|
||||
"computer science",
|
||||
"physical sciences",
|
||||
"physics and astronomy",
|
||||
"materials science",
|
||||
"environmental science",
|
||||
"chemical engineering",
|
||||
"chemistry",
|
||||
"earth and planetary sciences",
|
||||
"medicine",
|
||||
"biochemistry, genetics and molecular biology",
|
||||
"immunology and microbiology",
|
||||
}
|
||||
)
|
||||
_PREFERRED_KEYWORD_LEVELS = frozenset({"coarse", "fine", "custom"})
|
||||
_NON_TECHNICAL_FIELD_NAMES = frozenset(
|
||||
{
|
||||
"social sciences",
|
||||
"arts and humanities",
|
||||
"law",
|
||||
"business, management and accounting",
|
||||
}
|
||||
)
|
||||
_COMPATIBLE_FIELDS: dict[str, frozenset[str]] = {
|
||||
"chemistry": frozenset(
|
||||
{"chemistry", "chemical engineering", "materials science"}
|
||||
),
|
||||
"chemical engineering": frozenset(
|
||||
{"chemical engineering", "chemistry", "materials science"}
|
||||
),
|
||||
"materials science": frozenset(
|
||||
{"materials science", "chemistry", "chemical engineering", "engineering"}
|
||||
),
|
||||
"computer science": frozenset({"computer science", "engineering"}),
|
||||
"engineering": frozenset(
|
||||
{"engineering", "computer science", "materials science"}
|
||||
),
|
||||
"physical sciences": frozenset(
|
||||
{"physical sciences", "physics and astronomy", "chemistry", "materials science"}
|
||||
),
|
||||
"physics and astronomy": frozenset(
|
||||
{"physics and astronomy", "physical sciences", "materials science"}
|
||||
),
|
||||
"biochemistry, genetics and molecular biology": frozenset(
|
||||
{
|
||||
"biochemistry, genetics and molecular biology",
|
||||
"chemistry",
|
||||
"medicine",
|
||||
}
|
||||
),
|
||||
"medicine": frozenset(
|
||||
{
|
||||
"medicine",
|
||||
"biochemistry, genetics and molecular biology",
|
||||
"immunology and microbiology",
|
||||
}
|
||||
),
|
||||
}
|
||||
_TEXT_STOPWORDS = frozenset(
|
||||
{
|
||||
"and",
|
||||
"the",
|
||||
"of",
|
||||
"in",
|
||||
"for",
|
||||
"und",
|
||||
"der",
|
||||
"die",
|
||||
"das",
|
||||
"von",
|
||||
"medicine",
|
||||
"medical",
|
||||
"science",
|
||||
"sciences",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _ipc_section(symbol: str) -> str:
|
||||
@@ -57,18 +148,26 @@ def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> s
|
||||
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 or match.match_type == "heuristic"
|
||||
if match.match_score >= _MIN_IPC_MATCH_SCORE
|
||||
]
|
||||
if not strong:
|
||||
strong = ranked[:8]
|
||||
return []
|
||||
|
||||
dominant_sections = _dominant_ipc_sections(strong)
|
||||
filtered: list[IpcCodeMatch] = []
|
||||
@@ -77,10 +176,6 @@ def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcC
|
||||
key = (match.ipc_level, match.ipc_symbol)
|
||||
if key in seen:
|
||||
continue
|
||||
if match.match_type == "heuristic":
|
||||
filtered.append(match)
|
||||
seen.add(key)
|
||||
continue
|
||||
if match.match_score >= 0.8:
|
||||
filtered.append(match)
|
||||
seen.add(key)
|
||||
@@ -89,215 +184,420 @@ def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcC
|
||||
filtered.append(match)
|
||||
seen.add(key)
|
||||
|
||||
return filtered or strong[:12]
|
||||
return filtered
|
||||
|
||||
|
||||
def _active_heuristic_prefixes(ipc_matches: list[IpcCodeMatch]) -> set[str]:
|
||||
prefixes: set[str] = set()
|
||||
for match in ipc_matches:
|
||||
if match.match_type != "heuristic":
|
||||
continue
|
||||
symbol = normalize_symbol(match.ipc_symbol)
|
||||
if not symbol:
|
||||
continue
|
||||
for prefix in (
|
||||
"A61",
|
||||
"B01",
|
||||
"C01",
|
||||
"C07",
|
||||
"C08",
|
||||
"C09",
|
||||
"C10",
|
||||
"C12",
|
||||
"G01N",
|
||||
"G06",
|
||||
"B60",
|
||||
"F02",
|
||||
):
|
||||
if symbol.startswith(prefix):
|
||||
prefixes.add(prefix)
|
||||
return prefixes
|
||||
def _limit_matches_per_keyword(
|
||||
matches: list[IpcCodeMatch],
|
||||
limit: int = _MAX_IPC_CODES_PER_KEYWORD,
|
||||
) -> list[IpcCodeMatch]:
|
||||
grouped: dict[str, list[IpcCodeMatch]] = {}
|
||||
for match in matches:
|
||||
grouped.setdefault(match.source_keyword.casefold(), []).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])
|
||||
|
||||
def _symbol_matches_heuristic_prefixes(symbol: str, prefixes: set[str]) -> bool:
|
||||
normalized = normalize_symbol(symbol)
|
||||
return any(normalized.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
def _ipc_search_domain(symbol: str) -> str:
|
||||
normalized = normalize_symbol(symbol)
|
||||
if normalized.startswith("A61"):
|
||||
return "medicine"
|
||||
if (
|
||||
normalized.startswith("C")
|
||||
or normalized.startswith("B01")
|
||||
or normalized.startswith("G01N")
|
||||
):
|
||||
return "chemistry"
|
||||
if normalized.startswith("B60") or normalized.startswith("F02"):
|
||||
return "automotive"
|
||||
if normalized.startswith("G06"):
|
||||
return "cs_ai"
|
||||
return "other"
|
||||
return sorted(result, key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
|
||||
def _term_from_ipc_match(match: IpcCodeMatch) -> str | None:
|
||||
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass
|
||||
symbol = normalize_symbol(match.ipc_symbol)
|
||||
if not symbol:
|
||||
return None
|
||||
|
||||
return infer_subclass(normalize_symbol(match.ipc_symbol))
|
||||
|
||||
|
||||
def _interleave_ipc_matches(
|
||||
matches: list[IpcCodeMatch],
|
||||
*,
|
||||
limit: int,
|
||||
) -> list[IpcCodeMatch]:
|
||||
from collections import defaultdict
|
||||
|
||||
by_domain: dict[str, list[IpcCodeMatch]] = defaultdict(list)
|
||||
for match in matches:
|
||||
by_domain[_ipc_search_domain(match.ipc_symbol)].append(match)
|
||||
|
||||
if len(by_domain) <= 1:
|
||||
return matches[:limit]
|
||||
|
||||
ordered: list[IpcCodeMatch] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
queues = list(by_domain.values())
|
||||
while len(ordered) < limit and queues:
|
||||
progressed = False
|
||||
for queue in list(queues):
|
||||
if len(ordered) >= limit:
|
||||
break
|
||||
while queue:
|
||||
match = queue.pop(0)
|
||||
key = (match.ipc_level, match.ipc_symbol)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
ordered.append(match)
|
||||
progressed = True
|
||||
break
|
||||
queues = [queue for queue in queues if queue]
|
||||
if not progressed:
|
||||
break
|
||||
return ordered
|
||||
|
||||
|
||||
def _balanced_patent_matches(
|
||||
scored: list[KeywordPatentMatch],
|
||||
limit: int,
|
||||
) -> list[KeywordPatentMatch]:
|
||||
from collections import defaultdict
|
||||
|
||||
by_domain: dict[str, list[KeywordPatentMatch]] = defaultdict(list)
|
||||
for item in scored:
|
||||
domain = (
|
||||
_ipc_search_domain(item.matched_ipc_symbols[0])
|
||||
if item.matched_ipc_symbols
|
||||
else "other"
|
||||
)
|
||||
by_domain[domain].append(item)
|
||||
|
||||
if len(by_domain) <= 1:
|
||||
return scored[:limit]
|
||||
|
||||
ordered: list[KeywordPatentMatch] = []
|
||||
seen_ids: set[str] = set()
|
||||
queues = list(by_domain.values())
|
||||
while len(ordered) < limit and queues:
|
||||
progressed = False
|
||||
for queue in list(queues):
|
||||
if len(ordered) >= limit:
|
||||
break
|
||||
while queue:
|
||||
item = queue.pop(0)
|
||||
if item.patent.patent_id in seen_ids:
|
||||
continue
|
||||
seen_ids.add(item.patent.patent_id)
|
||||
ordered.append(item)
|
||||
progressed = True
|
||||
break
|
||||
queues = [queue for queue in queues if queue]
|
||||
if not progressed:
|
||||
break
|
||||
return ordered
|
||||
return infer_subclass(symbol)
|
||||
|
||||
|
||||
def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]:
|
||||
filtered = _filter_ipc_matches_for_search(ipc_matches)
|
||||
active_prefixes = _active_heuristic_prefixes(ipc_matches)
|
||||
if active_prefixes:
|
||||
filtered = [
|
||||
match
|
||||
for match in filtered
|
||||
if _symbol_matches_heuristic_prefixes(match.ipc_symbol, active_prefixes)
|
||||
]
|
||||
|
||||
filtered = _interleave_ipc_matches(filtered, limit=_MAX_PATENT_SEARCH_TERMS)
|
||||
filtered = sorted(filtered, key=lambda match: match.match_score, reverse=True)
|
||||
terms: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for match in filtered:
|
||||
subclass = _term_from_ipc_match(match)
|
||||
if not subclass or subclass in seen:
|
||||
if match.ipc_level not in _SEARCHABLE_IPC_LEVELS:
|
||||
continue
|
||||
seen.add(subclass)
|
||||
terms.append(subclass)
|
||||
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
|
||||
return terms
|
||||
|
||||
|
||||
def _ipc_terms_overlap(patent_code: str, mapped_symbol: str) -> bool:
|
||||
patent_terms = set(
|
||||
_search_terms_for_symbol(extract_ipc_symbol(patent_code) or patent_code)
|
||||
)
|
||||
mapped_terms = set(_search_terms_for_symbol(mapped_symbol))
|
||||
return bool(patent_terms & mapped_terms)
|
||||
def _normalize_ipc_code(code: str) -> str:
|
||||
extracted = extract_ipc_symbol(code) or code
|
||||
return normalize_symbol(extracted)
|
||||
|
||||
|
||||
def _patent_code_matches_symbol(patent_code: str, mapped_symbol: str) -> bool:
|
||||
if _ipc_terms_overlap(patent_code, mapped_symbol):
|
||||
return True
|
||||
normalized_patent = normalize_symbol(extract_ipc_symbol(patent_code))
|
||||
normalized_mapped = normalize_symbol(mapped_symbol)
|
||||
def _ipc_main_group(symbol: str) -> str | None:
|
||||
parsed = parse_ipc_symbol(symbol)
|
||||
if parsed is None or not parsed.main_group:
|
||||
return None
|
||||
|
||||
return normalize_symbol(parsed.main_group)
|
||||
|
||||
|
||||
def _ipc_hierarchy_quality(
|
||||
patent_code: str,
|
||||
mapped_symbol: str,
|
||||
) -> float:
|
||||
normalized_patent = _normalize_ipc_code(patent_code)
|
||||
normalized_mapped = _normalize_ipc_code(mapped_symbol)
|
||||
|
||||
if not normalized_patent or not normalized_mapped:
|
||||
return 0.0
|
||||
|
||||
if normalized_patent == normalized_mapped:
|
||||
return 1.0
|
||||
|
||||
patent_group = _ipc_main_group(normalized_patent)
|
||||
mapped_group = _ipc_main_group(normalized_mapped)
|
||||
|
||||
if patent_group and mapped_group and patent_group == mapped_group:
|
||||
return 0.90
|
||||
|
||||
patent_subclass = infer_subclass(normalized_patent)
|
||||
mapped_subclass = infer_subclass(normalized_mapped)
|
||||
|
||||
if (
|
||||
patent_subclass
|
||||
and mapped_subclass
|
||||
and patent_subclass == mapped_subclass
|
||||
):
|
||||
return 0.75
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
def _ipc_hierarchy_level(
|
||||
patent_code: str,
|
||||
mapped_symbol: str,
|
||||
) -> str | None:
|
||||
quality = _ipc_hierarchy_quality(patent_code, mapped_symbol)
|
||||
if quality >= 1.0:
|
||||
return "exact"
|
||||
if quality >= 0.90:
|
||||
return "main_group"
|
||||
if quality >= 0.75:
|
||||
return "subclass"
|
||||
return None
|
||||
|
||||
|
||||
def _keyword_level(item: KeywordPatentSearchItem) -> str:
|
||||
return (item.keyword_level or "").strip().casefold()
|
||||
|
||||
|
||||
def _keyword_is_patent_searchable(item: KeywordPatentSearchItem) -> bool:
|
||||
if not item.keyword.strip():
|
||||
return False
|
||||
|
||||
topic_id = normalize_openalex_id(item.topic_id)
|
||||
if not topic_id:
|
||||
return False
|
||||
|
||||
field_name = _normalized_field_name(item.field_name)
|
||||
if field_name in _NON_TECHNICAL_FIELD_NAMES:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _sort_and_limit_keywords(
|
||||
items: list[KeywordPatentSearchItem],
|
||||
) -> list[KeywordPatentSearchItem]:
|
||||
ranked = sorted(items, key=lambda item: item.relevance_score, reverse=True)
|
||||
return ranked[:_MAX_SEARCH_KEYWORDS]
|
||||
|
||||
|
||||
def _filter_keywords_for_patent_search(
|
||||
items: list[KeywordPatentSearchItem],
|
||||
) -> list[KeywordPatentSearchItem]:
|
||||
"""Prefer coarse/fine/custom keywords; ignore broad when specifics exist."""
|
||||
searchable = [item for item in items if _keyword_is_patent_searchable(item)]
|
||||
if not searchable:
|
||||
return []
|
||||
|
||||
preferred = [
|
||||
item
|
||||
for item in searchable
|
||||
if _keyword_level(item) in _PREFERRED_KEYWORD_LEVELS
|
||||
]
|
||||
if preferred:
|
||||
return _sort_and_limit_keywords(preferred)
|
||||
|
||||
non_broad = [
|
||||
item for item in searchable if _keyword_level(item) != "broad"
|
||||
]
|
||||
if non_broad:
|
||||
return _sort_and_limit_keywords(non_broad)
|
||||
|
||||
return _sort_and_limit_keywords(searchable)
|
||||
|
||||
|
||||
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}))
|
||||
|
||||
|
||||
def _keyword_overlap_criteria(
|
||||
items: list[KeywordPatentSearchItem],
|
||||
) -> tuple[frozenset[str], frozenset[str], frozenset[str]]:
|
||||
topic_ids: set[str] = set()
|
||||
subfield_names: set[str] = set()
|
||||
soft_field_names: set[str] = set()
|
||||
for item in items:
|
||||
topic_id = normalize_openalex_id(item.topic_id)
|
||||
if topic_id:
|
||||
topic_ids.add(topic_id)
|
||||
subfield_name = (item.subfield_name or "").strip()
|
||||
if subfield_name:
|
||||
subfield_names.add(subfield_name.casefold())
|
||||
field_name = _normalized_field_name(item.field_name)
|
||||
if field_name in _SOFT_MATCH_FIELD_NAMES:
|
||||
soft_field_names.add(field_name)
|
||||
return (
|
||||
normalized_patent.startswith(normalized_mapped)
|
||||
or normalized_mapped.startswith(normalized_patent)
|
||||
frozenset(topic_ids),
|
||||
frozenset(subfield_names),
|
||||
frozenset(soft_field_names),
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
if (
|
||||
not keyword_topic_ids
|
||||
and not keyword_subfield_names
|
||||
and not keyword_soft_field_names
|
||||
):
|
||||
return True
|
||||
|
||||
if not patent_topics:
|
||||
return False
|
||||
|
||||
patent_topic_ids = {
|
||||
topic_id
|
||||
for mapped in patent_topics
|
||||
if (topic_id := normalize_openalex_id(mapped.topic_id))
|
||||
}
|
||||
if keyword_topic_ids & patent_topic_ids:
|
||||
return True
|
||||
|
||||
patent_subfield_names = {
|
||||
(mapped.subfield_name or "").strip().casefold()
|
||||
for mapped in patent_topics
|
||||
if (mapped.subfield_name or "").strip()
|
||||
}
|
||||
if keyword_subfield_names & patent_subfield_names:
|
||||
return True
|
||||
|
||||
if keyword_soft_field_names:
|
||||
patent_field_names = {
|
||||
_normalized_field_name(mapped.field_name)
|
||||
for mapped in patent_topics
|
||||
if mapped.field_name
|
||||
}
|
||||
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 False
|
||||
|
||||
|
||||
def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]:
|
||||
terms: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for item in items:
|
||||
for value in (
|
||||
item.keyword,
|
||||
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:
|
||||
continue
|
||||
seen.add(word)
|
||||
terms.append(word)
|
||||
|
||||
return terms
|
||||
|
||||
|
||||
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():
|
||||
return 0.0
|
||||
|
||||
hits = sum(1 for term in search_terms if term in text)
|
||||
return min(hits / 3, 1.0)
|
||||
|
||||
|
||||
def _patent_passes_relevance_gate(
|
||||
patent_topics: list[MappedOpenAlexTopic],
|
||||
*,
|
||||
keyword_topic_ids: frozenset[str],
|
||||
keyword_subfield_names: frozenset[str],
|
||||
keyword_soft_field_names: frozenset[str],
|
||||
patent: model.PatentEntry,
|
||||
text_score: float,
|
||||
) -> bool:
|
||||
has_topic_match = bool(patent_topics) and _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
keyword_topic_ids,
|
||||
keyword_subfield_names,
|
||||
keyword_soft_field_names,
|
||||
patent=patent,
|
||||
)
|
||||
return has_topic_match or text_score > 0.0
|
||||
|
||||
|
||||
def _compute_final_score(
|
||||
ipc_score: float,
|
||||
topic_score: float,
|
||||
text_score: float,
|
||||
) -> float:
|
||||
return round(
|
||||
0.60 * ipc_score
|
||||
+ 0.25 * topic_score
|
||||
+ 0.15 * text_score,
|
||||
4,
|
||||
)
|
||||
|
||||
|
||||
def _score_ipc_match(
|
||||
patent: model.PatentEntry,
|
||||
ipc_matches: list[IpcCodeMatch],
|
||||
) -> tuple[float, list[str], list[str]] | None:
|
||||
searchable_matches = [
|
||||
match
|
||||
for match in ipc_matches
|
||||
if match.ipc_level in _SEARCHABLE_IPC_LEVELS
|
||||
] or ipc_matches
|
||||
|
||||
best_score = 0.0
|
||||
best_keywords: set[str] = set()
|
||||
best_symbols: set[str] = set()
|
||||
|
||||
patent_codes = [
|
||||
normalized
|
||||
for code in (*patent.ipc, *patent.cpc)
|
||||
if (normalized := _normalize_ipc_code(code))
|
||||
]
|
||||
|
||||
for ipc_match in searchable_matches:
|
||||
for patent_code in patent_codes:
|
||||
hierarchy_quality = _ipc_hierarchy_quality(
|
||||
patent_code,
|
||||
ipc_match.ipc_symbol,
|
||||
)
|
||||
if hierarchy_quality <= 0:
|
||||
continue
|
||||
|
||||
candidate_score = ipc_match.match_score * hierarchy_quality
|
||||
|
||||
if candidate_score > best_score:
|
||||
best_score = candidate_score
|
||||
best_keywords = {ipc_match.source_keyword}
|
||||
best_symbols = {ipc_match.ipc_symbol}
|
||||
elif math.isclose(
|
||||
candidate_score,
|
||||
best_score,
|
||||
rel_tol=1e-9,
|
||||
abs_tol=1e-9,
|
||||
):
|
||||
best_keywords.add(ipc_match.source_keyword)
|
||||
best_symbols.add(ipc_match.ipc_symbol)
|
||||
|
||||
if best_score <= 0:
|
||||
return None
|
||||
|
||||
return (
|
||||
round(best_score, 4),
|
||||
sorted(best_keywords),
|
||||
sorted(best_symbols),
|
||||
)
|
||||
|
||||
|
||||
def _score_patent(
|
||||
patent: model.PatentEntry,
|
||||
ipc_matches: list[IpcCodeMatch],
|
||||
*,
|
||||
patent_topics: list[MappedOpenAlexTopic] | None = None,
|
||||
keyword_topic_ids: frozenset[str] | None = None,
|
||||
keyword_subfield_names: frozenset[str] | None = None,
|
||||
keyword_soft_field_names: frozenset[str] | None = None,
|
||||
search_keywords: list[KeywordPatentSearchItem] | None = None,
|
||||
) -> tuple[float, list[str], list[str]] | None:
|
||||
best_score = 0.0
|
||||
matched_keywords: set[str] = set()
|
||||
matched_symbols: set[str] = set()
|
||||
ipc_result = _score_ipc_match(patent, ipc_matches)
|
||||
if ipc_result is None:
|
||||
return None
|
||||
ipc_score, matched_keywords, matched_symbols = ipc_result
|
||||
|
||||
patent_codes = [
|
||||
normalize_symbol(extract_ipc_symbol(code))
|
||||
for code in (*patent.ipc, *patent.cpc)
|
||||
if extract_ipc_symbol(code)
|
||||
]
|
||||
text_score = 0.0
|
||||
if search_keywords is not None:
|
||||
text_score = _text_overlap_score(
|
||||
patent,
|
||||
_text_search_terms(search_keywords),
|
||||
)
|
||||
|
||||
for ipc_match in ipc_matches:
|
||||
for patent_code in patent_codes:
|
||||
if _patent_code_matches_symbol(patent_code, ipc_match.ipc_symbol):
|
||||
if ipc_match.match_score > best_score:
|
||||
best_score = ipc_match.match_score
|
||||
matched_keywords.add(ipc_match.source_keyword)
|
||||
matched_symbols.add(ipc_match.ipc_symbol)
|
||||
has_topic_match = bool(patent_topics) and _topics_overlap_keywords(
|
||||
patent_topics or [],
|
||||
keyword_topic_ids or frozenset(),
|
||||
keyword_subfield_names or frozenset(),
|
||||
keyword_soft_field_names or frozenset(),
|
||||
patent=patent,
|
||||
)
|
||||
|
||||
if best_score <= 0:
|
||||
if not has_topic_match and text_score == 0.0:
|
||||
return None
|
||||
|
||||
topic_score = 1.0 if has_topic_match else 0.0
|
||||
|
||||
return (
|
||||
best_score,
|
||||
sorted(matched_keywords),
|
||||
sorted(matched_symbols),
|
||||
_compute_final_score(ipc_score, topic_score, text_score),
|
||||
matched_keywords,
|
||||
matched_symbols,
|
||||
)
|
||||
|
||||
|
||||
@@ -307,33 +607,78 @@ async def get_patents_by_keywords(
|
||||
reverse_lookup: KeywordIpcReverseLookup | None = None,
|
||||
search_client: BasePatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
mapping_resolver: PatentOpenAlexMappingResolver | None = None,
|
||||
) -> PatentsByKeywordsResponse:
|
||||
lookup = reverse_lookup or KeywordIpcReverseLookup()
|
||||
client = search_client or BasePatentSearchClient()
|
||||
ipc_search = ipc_client or IpcSearchClient()
|
||||
resolver = mapping_resolver or PatentOpenAlexMappingResolver()
|
||||
queries = IpcPatentSearchQueries()
|
||||
|
||||
ipc_matches = await lookup.lookup_ipc_codes(
|
||||
request.keywords,
|
||||
max_codes=_MAX_IPC_CODES,
|
||||
)
|
||||
ipc_matches = _filter_ipc_matches_for_search(ipc_matches)
|
||||
if not ipc_matches:
|
||||
search_keywords = _filter_keywords_for_patent_search(request.keywords)
|
||||
if not search_keywords:
|
||||
logger.info(
|
||||
"Keyword patent search: no IPC codes for keywords %s",
|
||||
"Keyword patent search: no searchable keywords in %s",
|
||||
[item.keyword for item in request.keywords],
|
||||
)
|
||||
return PatentsByKeywordsResponse(patent_count=0, patents=[])
|
||||
|
||||
logger.info(
|
||||
"Keyword patent search: using keywords=%s (from %d requested)",
|
||||
[
|
||||
{
|
||||
"keyword": item.keyword,
|
||||
"level": item.keyword_level,
|
||||
"relevance_score": item.relevance_score,
|
||||
"field_name": item.field_name,
|
||||
}
|
||||
for item in search_keywords
|
||||
],
|
||||
len(request.keywords),
|
||||
)
|
||||
keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names = (
|
||||
_keyword_overlap_criteria(search_keywords)
|
||||
)
|
||||
|
||||
ipc_matches = await lookup.lookup_ipc_codes(
|
||||
search_keywords,
|
||||
max_codes=_MAX_IPC_CODES,
|
||||
)
|
||||
ipc_matches = _filter_ipc_matches_for_search(ipc_matches)
|
||||
ipc_matches = _limit_matches_per_keyword(ipc_matches)
|
||||
logger.info(
|
||||
"Keyword patent search: search_keywords=%s ipc_matches=%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
|
||||
],
|
||||
)
|
||||
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)
|
||||
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_terms(symbols, size=_MAX_PATENTS)),
|
||||
client.search_epo(
|
||||
queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS)
|
||||
),
|
||||
client.search_uspto(
|
||||
queries.uspto_query_by_ipc_terms(symbols, size=_MAX_PATENTS)
|
||||
queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS)
|
||||
),
|
||||
)
|
||||
except MissingApiKeyError:
|
||||
@@ -346,15 +691,64 @@ async def get_patents_by_keywords(
|
||||
raw_patents = deduplicate_patents(
|
||||
parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
)
|
||||
logger.info("Keyword patent search: raw_patents=%d", len(raw_patents))
|
||||
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
|
||||
for patent in raw_patents:
|
||||
result = _score_patent(patent, ipc_matches)
|
||||
if result is None:
|
||||
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
|
||||
score, matched_keywords, matched_symbols = result
|
||||
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,
|
||||
)
|
||||
|
||||
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,
|
||||
@@ -364,6 +758,15 @@ async def get_patents_by_keywords(
|
||||
)
|
||||
)
|
||||
|
||||
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),
|
||||
)
|
||||
|
||||
scored.sort(
|
||||
key=lambda item: (
|
||||
item.match_score,
|
||||
@@ -372,7 +775,7 @@ async def get_patents_by_keywords(
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
scored = _balanced_patent_matches(scored, _MAX_PATENTS)
|
||||
scored = scored[:_MAX_PATENTS]
|
||||
|
||||
patents = [item.patent for item in scored]
|
||||
await enrich_patents_classifications(patents, ipc_search)
|
||||
@@ -395,6 +798,7 @@ def keyword_items_from_entries(
|
||||
items.append(
|
||||
KeywordPatentSearchItem(
|
||||
keyword=str(llm.get("keyword") or "").strip(),
|
||||
keyword_level=entry.get("keyword_level"),
|
||||
topic_id=topic.get("id"),
|
||||
topic_display_name=topic.get("display_name"),
|
||||
subfield_name=(topic.get("subfield") or {}).get("display_name"),
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.patents.common.model import PatentEntry
|
||||
|
||||
KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"]
|
||||
|
||||
|
||||
class KeywordPatentSearchItem(BaseModel):
|
||||
keyword: str = Field(description="Extracted keyword text.")
|
||||
keyword_level: KeywordPatentLevel | None = Field(
|
||||
default=None,
|
||||
description="Keyword granularity from extraction UI: broad, coarse, fine, or custom.",
|
||||
)
|
||||
topic_id: str | None = Field(
|
||||
default=None,
|
||||
description="OpenAlex topic id from keyword enrichment, if available.",
|
||||
|
||||
@@ -10,7 +10,6 @@ import httpx
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import (
|
||||
_load_topic_cache,
|
||||
load_ipc_openalex_mapping,
|
||||
normalize_openalex_id,
|
||||
)
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
@@ -22,82 +21,6 @@ from inse.patents.patents_openalex_keywords.resolver import load_patents_openale
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CS_AI_IPC_SUBCLASSES = ("G06N", "G06F", "G06T", "G06V", "G06K", "G06Q")
|
||||
_AUTOMOTIVE_IPC_SUBCLASSES = (
|
||||
"B60L",
|
||||
"B60K",
|
||||
"B60W",
|
||||
"B60R",
|
||||
"B60H",
|
||||
"B60Q",
|
||||
"B60M",
|
||||
"F02M",
|
||||
"F02D",
|
||||
)
|
||||
_MEDICINE_IPC_SUBCLASSES = ("A61B", "A61K", "A61M", "A61P", "A61N", "A61F")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_GENERAL = ("C07C", "C01B", "C08L", "G01N")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_ORGANIC = ("C07C", "C07D")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_INORGANIC = ("C01B", "C01G")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_POLYMER = ("C08L", "C08G")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM = ("C12N", "C12Q")
|
||||
_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL = ("G01N",)
|
||||
_CHEMISTRY_IPC_SUBCLASSES_PROCESS = ("B01J", "B01D")
|
||||
_CHEMISTRY_RELATED_SUBFIELDS = frozenset(
|
||||
{
|
||||
"organic chemistry",
|
||||
"inorganic chemistry",
|
||||
"physical and theoretical chemistry",
|
||||
"analytical chemistry",
|
||||
"materials chemistry",
|
||||
"environmental chemistry",
|
||||
"biochemistry",
|
||||
"process chemistry and technology",
|
||||
"spectroscopy",
|
||||
"clinical biochemistry",
|
||||
"geochemistry and petrology",
|
||||
"pharmaceutical science",
|
||||
}
|
||||
)
|
||||
_CHEMISTRY_RELATED_FIELDS = frozenset(
|
||||
{
|
||||
"chemistry",
|
||||
"chemical engineering",
|
||||
}
|
||||
)
|
||||
_MEDICINE_RELATED_SUBFIELDS = frozenset(
|
||||
{
|
||||
"medicine",
|
||||
"public health",
|
||||
"health professions",
|
||||
"pharmacology",
|
||||
"surgery",
|
||||
"oncology",
|
||||
"radiology, nuclear medicine and imaging",
|
||||
"cardiology and cardiovascular medicine",
|
||||
"epidemiology",
|
||||
"immunology",
|
||||
}
|
||||
)
|
||||
_MEDICINE_RELATED_FIELDS = frozenset(
|
||||
{
|
||||
"medicine",
|
||||
"health professions",
|
||||
"nursing",
|
||||
"pharmacology, toxicology and pharmaceutics",
|
||||
"biochemistry, genetics and molecular biology",
|
||||
}
|
||||
)
|
||||
_AI_RELATED_SUBFIELDS = frozenset(
|
||||
{
|
||||
"artificial intelligence",
|
||||
"computer vision and pattern recognition",
|
||||
"signal processing",
|
||||
"information systems and management",
|
||||
"human-computer interaction",
|
||||
"software",
|
||||
}
|
||||
)
|
||||
|
||||
_LEVEL_WEIGHTS = {
|
||||
"subgroup": 1.0,
|
||||
"group": 0.92,
|
||||
@@ -135,14 +58,33 @@ def _topic_id_variants(topic_id: str | None) -> list[str]:
|
||||
return list(dict.fromkeys(variants))
|
||||
|
||||
|
||||
def _topic_id_variants_for_item(item: KeywordPatentSearchItem) -> list[str]:
|
||||
variants = _topic_id_variants(item.topic_id)
|
||||
if variants:
|
||||
return variants
|
||||
|
||||
display_name = (item.topic_display_name or "").strip()
|
||||
if display_name:
|
||||
info = _load_topic_cache().get(display_name)
|
||||
if info and info.get("topic_id"):
|
||||
return _topic_id_variants(str(info["topic_id"]))
|
||||
|
||||
return []
|
||||
|
||||
|
||||
def _weighted_score(
|
||||
ipc_level: str,
|
||||
base_score: float,
|
||||
relevance_score: float,
|
||||
) -> float:
|
||||
"""Combine IPC mapping confidence with IPC hierarchy level.
|
||||
|
||||
LLM keyword relevance is not applied here: broad keywords often carry
|
||||
relevance_score 0.0 while still mapping to valid OpenAlex topics.
|
||||
"""
|
||||
_ = relevance_score
|
||||
level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7)
|
||||
relevance = max(relevance_score, 0.1)
|
||||
return round(base_score * level_weight * relevance, 4)
|
||||
return round(base_score * level_weight, 4)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
@@ -194,8 +136,6 @@ def _build_json_inverted_index() -> tuple[
|
||||
|
||||
def clear_reverse_lookup_caches() -> None:
|
||||
_build_json_inverted_index.cache_clear()
|
||||
_topic_id_to_hierarchy.cache_clear()
|
||||
_legacy_indices.cache_clear()
|
||||
|
||||
|
||||
def _merge_ipc_match(
|
||||
@@ -228,7 +168,7 @@ def _matches_from_doc(
|
||||
return []
|
||||
|
||||
keyword_variants = set(_keyword_variants(item.keyword))
|
||||
topic_variants = set(_topic_id_variants(item.topic_id))
|
||||
topic_variants = set(_topic_id_variants_for_item(item))
|
||||
topic_name = (item.topic_display_name or "").strip().casefold()
|
||||
found: list[IpcCodeMatch] = []
|
||||
|
||||
@@ -293,7 +233,7 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
|
||||
merged, level, symbol, score, item.keyword, match_type
|
||||
)
|
||||
|
||||
for variant in _topic_id_variants(item.topic_id):
|
||||
for variant in _topic_id_variants_for_item(item):
|
||||
for level, symbol, base_score, source_keyword, match_type in by_topic.get(
|
||||
variant, []
|
||||
):
|
||||
@@ -305,285 +245,7 @@ def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
|
||||
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _topic_id_to_hierarchy() -> dict[str, dict[str, str]]:
|
||||
result: dict[str, dict[str, str]] = {}
|
||||
for info in _load_topic_cache().values():
|
||||
topic_id = info.get("topic_id")
|
||||
if not topic_id:
|
||||
continue
|
||||
for variant in _topic_id_variants(str(topic_id)):
|
||||
result[variant] = info
|
||||
return result
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _legacy_indices() -> tuple[
|
||||
dict[str, list[tuple[str, str, float]]],
|
||||
dict[str, list[tuple[str, str, float]]],
|
||||
dict[str, list[tuple[str, str, float]]],
|
||||
dict[str, list[tuple[str, str, float]]],
|
||||
]:
|
||||
"""topic_id / topic_name / subfield / field -> (level, symbol, score)."""
|
||||
by_topic_id: dict[str, list[tuple[str, str, float]]] = {}
|
||||
by_topic_name: dict[str, list[tuple[str, str, float]]] = {}
|
||||
by_subfield: dict[str, list[tuple[str, str, float]]] = {}
|
||||
by_field: dict[str, list[tuple[str, str, float]]] = {}
|
||||
cache = _load_topic_cache()
|
||||
|
||||
mapping = load_ipc_openalex_mapping()
|
||||
for level, entries in mapping.items():
|
||||
for symbol, mapped in entries.items():
|
||||
score = 0.55
|
||||
record = (level, normalize_symbol(symbol), score)
|
||||
for variant in _topic_id_variants(mapped.topic_id):
|
||||
by_topic_id.setdefault(variant, []).append(record)
|
||||
if mapped.topic_display_name:
|
||||
by_topic_name.setdefault(
|
||||
mapped.topic_display_name.casefold(), []
|
||||
).append(record)
|
||||
|
||||
info = cache.get(mapped.topic_display_name or "")
|
||||
if info:
|
||||
subfield = str(info.get("subfield") or "").casefold()
|
||||
field = str(info.get("field") or "").casefold()
|
||||
if subfield:
|
||||
by_subfield.setdefault(subfield, []).append(record)
|
||||
if field:
|
||||
by_field.setdefault(field, []).append(record)
|
||||
|
||||
return by_topic_id, by_topic_name, by_subfield, by_field
|
||||
|
||||
|
||||
def _hierarchy_for_item(item: KeywordPatentSearchItem) -> dict[str, str]:
|
||||
for variant in _topic_id_variants(item.topic_id):
|
||||
info = _topic_id_to_hierarchy().get(variant)
|
||||
if info:
|
||||
return info
|
||||
if item.topic_display_name:
|
||||
info = _load_topic_cache().get(item.topic_display_name)
|
||||
if info:
|
||||
return info
|
||||
return {
|
||||
"subfield": item.subfield_name or "",
|
||||
"field": item.field_name or "",
|
||||
}
|
||||
|
||||
|
||||
def _apply_cs_ai_heuristics(
|
||||
merged: dict[tuple[str, str], IpcCodeMatch],
|
||||
item: KeywordPatentSearchItem,
|
||||
) -> None:
|
||||
hierarchy = _hierarchy_for_item(item)
|
||||
subfield = str(hierarchy.get("subfield") or "").casefold()
|
||||
field = str(hierarchy.get("field") or "").casefold()
|
||||
if field != "computer science" and subfield not in _AI_RELATED_SUBFIELDS:
|
||||
return
|
||||
|
||||
for symbol in _CS_AI_IPC_SUBCLASSES:
|
||||
score = _weighted_score("subclass", 0.62, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged,
|
||||
"subclass",
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
"heuristic",
|
||||
)
|
||||
|
||||
|
||||
def _apply_automotive_heuristics(
|
||||
merged: dict[tuple[str, str], IpcCodeMatch],
|
||||
item: KeywordPatentSearchItem,
|
||||
) -> None:
|
||||
hierarchy = _hierarchy_for_item(item)
|
||||
subfield = str(hierarchy.get("subfield") or "").casefold()
|
||||
field = str(hierarchy.get("field") or "").casefold()
|
||||
keyword = item.keyword.casefold()
|
||||
automotive_keyword = any(
|
||||
token in keyword
|
||||
for token in (
|
||||
"automobil",
|
||||
"fahrzeug",
|
||||
"kraftfahr",
|
||||
"elektromob",
|
||||
"verkehr",
|
||||
"mobil",
|
||||
)
|
||||
)
|
||||
if (
|
||||
subfield != "automotive engineering"
|
||||
and field != "engineering"
|
||||
and not automotive_keyword
|
||||
):
|
||||
return
|
||||
|
||||
for symbol in _AUTOMOTIVE_IPC_SUBCLASSES:
|
||||
score = _weighted_score("subclass", 0.6, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged,
|
||||
"subclass",
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
"heuristic",
|
||||
)
|
||||
|
||||
|
||||
def _chemistry_subclasses_for_keyword(keyword: str) -> tuple[str, ...]:
|
||||
normalized = keyword.casefold()
|
||||
subclasses: list[str] = []
|
||||
if any(token in normalized for token in ("anorganisch", "inorganic")):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_INORGANIC)
|
||||
elif any(token in normalized for token in ("organisch", "organic")):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC)
|
||||
if any(token in normalized for token in ("polymer", "makromolek")):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_POLYMER)
|
||||
if any(token in normalized for token in ("biochem", "enzym", "ferment")):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_BIOCHEM)
|
||||
if any(
|
||||
token in normalized
|
||||
for token in ("analyt", "spektroskop", "chromatograph", "spektromet")
|
||||
):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ANALYTICAL)
|
||||
if any(
|
||||
token in normalized
|
||||
for token in ("verfahren", "reaktion", "katalys", "synthese", "technische chemie")
|
||||
):
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_PROCESS)
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_ORGANIC)
|
||||
if any(
|
||||
token in normalized
|
||||
for token in ("chemie", "chemisch", "molekül", "molekul", "stoff")
|
||||
):
|
||||
if not subclasses:
|
||||
subclasses.extend(_CHEMISTRY_IPC_SUBCLASSES_GENERAL)
|
||||
return tuple(dict.fromkeys(subclasses))
|
||||
|
||||
|
||||
def _apply_chemistry_heuristics(
|
||||
merged: dict[tuple[str, str], IpcCodeMatch],
|
||||
item: KeywordPatentSearchItem,
|
||||
) -> None:
|
||||
hierarchy = _hierarchy_for_item(item)
|
||||
subfield = str(hierarchy.get("subfield") or "").casefold()
|
||||
field = str(hierarchy.get("field") or "").casefold()
|
||||
subclasses = _chemistry_subclasses_for_keyword(item.keyword)
|
||||
if (
|
||||
subfield not in _CHEMISTRY_RELATED_SUBFIELDS
|
||||
and field not in _CHEMISTRY_RELATED_FIELDS
|
||||
and not subclasses
|
||||
):
|
||||
return
|
||||
|
||||
if not subclasses:
|
||||
subclasses = _CHEMISTRY_IPC_SUBCLASSES_GENERAL
|
||||
|
||||
for symbol in subclasses:
|
||||
score = _weighted_score("subclass", 0.68, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged,
|
||||
"subclass",
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
"heuristic",
|
||||
)
|
||||
|
||||
|
||||
def _apply_medicine_heuristics(
|
||||
merged: dict[tuple[str, str], IpcCodeMatch],
|
||||
item: KeywordPatentSearchItem,
|
||||
) -> None:
|
||||
hierarchy = _hierarchy_for_item(item)
|
||||
subfield = str(hierarchy.get("subfield") or "").casefold()
|
||||
field = str(hierarchy.get("field") or "").casefold()
|
||||
keyword = item.keyword.casefold()
|
||||
medicine_keyword = any(
|
||||
token in keyword
|
||||
for token in (
|
||||
"medizin",
|
||||
"krankheit",
|
||||
"therap",
|
||||
"diagnos",
|
||||
"patient",
|
||||
"klinik",
|
||||
"arzt",
|
||||
"heilkund",
|
||||
"pharma",
|
||||
"immun",
|
||||
"patholog",
|
||||
)
|
||||
)
|
||||
if (
|
||||
subfield not in _MEDICINE_RELATED_SUBFIELDS
|
||||
and field not in _MEDICINE_RELATED_FIELDS
|
||||
and not medicine_keyword
|
||||
):
|
||||
return
|
||||
|
||||
for symbol in _MEDICINE_IPC_SUBCLASSES:
|
||||
score = _weighted_score("subclass", 0.72, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged,
|
||||
"subclass",
|
||||
symbol,
|
||||
score,
|
||||
item.keyword,
|
||||
"heuristic",
|
||||
)
|
||||
|
||||
|
||||
def _legacy_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
|
||||
by_topic_id, by_topic_name, by_subfield, by_field = _legacy_indices()
|
||||
merged: dict[tuple[str, str], IpcCodeMatch] = {}
|
||||
|
||||
for item in items:
|
||||
for variant in _topic_id_variants(item.topic_id):
|
||||
for level, symbol, base_score in by_topic_id.get(variant, []):
|
||||
score = _weighted_score(level, base_score, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, "topic"
|
||||
)
|
||||
|
||||
topic_name = (item.topic_display_name or "").strip().casefold()
|
||||
if topic_name:
|
||||
for level, symbol, base_score in by_topic_name.get(topic_name, []):
|
||||
score = _weighted_score(level, base_score, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, "topic"
|
||||
)
|
||||
|
||||
hierarchy = _hierarchy_for_item(item)
|
||||
subfield = str(hierarchy.get("subfield") or "").casefold()
|
||||
field = str(hierarchy.get("field") or "").casefold()
|
||||
if subfield:
|
||||
for level, symbol, base_score in by_subfield.get(subfield, []):
|
||||
score = _weighted_score(level, base_score * 0.85, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, "subfield"
|
||||
)
|
||||
if field:
|
||||
for level, symbol, base_score in by_field.get(field, []):
|
||||
score = _weighted_score(level, base_score * 0.7, item.relevance_score)
|
||||
_merge_ipc_match(
|
||||
merged, level, symbol, score, item.keyword, "field"
|
||||
)
|
||||
|
||||
results = sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
if not results:
|
||||
logger.info(
|
||||
"Legacy IPC lookup found no codes for %d keyword(s); "
|
||||
"build patents_openalex_keywords for better coverage.",
|
||||
len(items),
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def _finalize_ipc_matches(
|
||||
items: list[KeywordPatentSearchItem],
|
||||
matches: list[IpcCodeMatch],
|
||||
) -> list[IpcCodeMatch]:
|
||||
def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
|
||||
merged: dict[tuple[str, str], IpcCodeMatch] = {}
|
||||
for match in matches:
|
||||
_merge_ipc_match(
|
||||
@@ -594,11 +256,6 @@ def _finalize_ipc_matches(
|
||||
match.source_keyword,
|
||||
match.match_type,
|
||||
)
|
||||
for item in items:
|
||||
_apply_cs_ai_heuristics(merged, item)
|
||||
_apply_automotive_heuristics(merged, item)
|
||||
_apply_chemistry_heuristics(merged, item)
|
||||
_apply_medicine_heuristics(merged, item)
|
||||
return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
|
||||
|
||||
|
||||
@@ -620,7 +277,7 @@ def _build_es_should_clauses(items: list[KeywordPatentSearchItem]) -> list[dict[
|
||||
}
|
||||
)
|
||||
|
||||
for topic_id in _topic_id_variants(item.topic_id):
|
||||
for topic_id in _topic_id_variants_for_item(item):
|
||||
if topic_id in seen:
|
||||
continue
|
||||
seen.add(topic_id)
|
||||
@@ -695,21 +352,15 @@ class KeywordIpcReverseLookup:
|
||||
if not matches:
|
||||
matches = _json_lookup(items)
|
||||
|
||||
if not matches:
|
||||
matches = _legacy_lookup(items)
|
||||
|
||||
if not matches:
|
||||
logger.info(
|
||||
"No IPC codes resolved for keywords: %s",
|
||||
"No IPC codes resolved for keywords: %s; "
|
||||
"build patents_openalex_keywords for better coverage.",
|
||||
[item.keyword for item in items],
|
||||
)
|
||||
|
||||
matches = _finalize_ipc_matches(items, matches)
|
||||
heuristics = [match for match in matches if match.match_type == "heuristic"]
|
||||
regular = [match for match in matches if match.match_type != "heuristic"]
|
||||
regular = sorted(regular, key=lambda match: match.match_score, reverse=True)
|
||||
remaining = max(0, max_codes - len(heuristics))
|
||||
return heuristics + regular[:remaining]
|
||||
matches = _dedupe_ipc_matches(matches)
|
||||
return matches[:max_codes]
|
||||
|
||||
async def _lookup_via_elasticsearch(
|
||||
self,
|
||||
|
||||
@@ -1,24 +1,115 @@
|
||||
"""Tests for keyword-based patent search."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
||||
from inse.patents.common import model
|
||||
from inse.patents.keywords.logic import _patent_code_matches_symbol, _score_patent
|
||||
from inse.patents.keywords.logic import (
|
||||
_compute_final_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,
|
||||
_term_from_ipc_match,
|
||||
_text_overlap_score,
|
||||
_text_search_terms,
|
||||
_topics_overlap_keywords,
|
||||
get_patents_by_keywords,
|
||||
)
|
||||
from inse.patents.keywords.reverse_lookup import (
|
||||
IpcCodeMatch,
|
||||
_finalize_ipc_matches,
|
||||
_json_lookup,
|
||||
_legacy_lookup,
|
||||
_weighted_score,
|
||||
clear_reverse_lookup_caches,
|
||||
)
|
||||
from inse.patents.keywords.model import KeywordPatentSearchItem
|
||||
from inse.patents.keywords.search_queries import _search_terms_for_symbol
|
||||
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
|
||||
from inse.patents.keywords.search_queries import IpcPatentSearchQueries, _search_terms_for_symbol
|
||||
|
||||
|
||||
def test_patent_code_matches_symbol_prefix() -> None:
|
||||
assert _patent_code_matches_symbol("G01S 5/02", "G01S")
|
||||
assert _patent_code_matches_symbol("G01S5/02", "G01S")
|
||||
assert not _patent_code_matches_symbol("H01L 21/02", "G01S")
|
||||
def test_ipc_hierarchy_quality_exact_match() -> None:
|
||||
assert _ipc_hierarchy_quality("C07C243/08", "C07C243/08") == 1.0
|
||||
|
||||
|
||||
def test_ipc_hierarchy_quality_same_main_group() -> None:
|
||||
assert _ipc_hierarchy_quality("C07C243/086", "C07C243/088") == 0.90
|
||||
|
||||
|
||||
def test_ipc_hierarchy_quality_same_subclass() -> None:
|
||||
assert _ipc_hierarchy_quality("C07C243/08", "C07C31/20") == 0.75
|
||||
|
||||
|
||||
def test_ipc_hierarchy_quality_no_match() -> None:
|
||||
assert _ipc_hierarchy_quality("C07C243/08", "C08F110/10") == 0.0
|
||||
|
||||
|
||||
def test_ipc_hierarchy_quality_invalid_code() -> None:
|
||||
assert _ipc_hierarchy_quality("", "C07C243/08") == 0.0
|
||||
assert _ipc_hierarchy_quality("C07", "C07C243/08") == 0.0
|
||||
|
||||
|
||||
def test_term_from_ipc_match_returns_subclass() -> None:
|
||||
match = IpcCodeMatch("subgroup", "C07C243/08", 0.9, "Organic Chemistry", "keyword")
|
||||
assert _term_from_ipc_match(match) == "C07C"
|
||||
|
||||
|
||||
def test_term_from_ipc_match_skips_class_level() -> None:
|
||||
match = IpcCodeMatch("class", "C07", 0.7, "Chemistry", "topic")
|
||||
assert _term_from_ipc_match(match) is None
|
||||
|
||||
|
||||
def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None:
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subgroup", "C25B3/03", 0.9037, "Anorganische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"),
|
||||
IpcCodeMatch("subgroup", "D06L4/17", 0.8745, "Technische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C09B43/34", 0.8738, "Chemische Reaktionen", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C02F1/285", 0.8698, "Organische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"),
|
||||
]
|
||||
terms = _patent_search_terms(ipc_matches)
|
||||
assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"]
|
||||
|
||||
|
||||
def test_score_ipc_match_returns_only_best_evidence() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
ipc=["C07C243/08"],
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"),
|
||||
]
|
||||
result = _score_ipc_match(patent, ipc_matches)
|
||||
assert result is not None
|
||||
score, keywords, symbols = result
|
||||
assert score == 0.8989
|
||||
assert keywords == ["Anorganische Chemie"]
|
||||
assert symbols == ["C07C243/08"]
|
||||
|
||||
|
||||
def test_score_ipc_match_keeps_equal_best_matches() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
ipc=["C07C243/08"],
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"),
|
||||
]
|
||||
result = _score_ipc_match(patent, ipc_matches)
|
||||
assert result is not None
|
||||
_, keywords, symbols = result
|
||||
assert keywords == ["Anorganische Chemie", "Organische Chemie"]
|
||||
assert symbols == ["C07C243/08"]
|
||||
|
||||
|
||||
def test_score_patent_uses_best_ipc_match() -> None:
|
||||
@@ -26,22 +117,426 @@ def test_score_patent_uses_best_ipc_match() -> None:
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
ipc=["G01S 5/02"],
|
||||
title="Wireless localization system",
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
|
||||
IpcCodeMatch("class", "G01", 0.5, "wireless", "topic"),
|
||||
]
|
||||
result = _score_patent(patent, ipc_matches)
|
||||
result = _score_patent(
|
||||
patent,
|
||||
ipc_matches,
|
||||
patent_topics=[
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T12345",
|
||||
subfield_name="Remote Sensing",
|
||||
)
|
||||
],
|
||||
keyword_topic_ids=frozenset({"T12345"}),
|
||||
search_keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="wireless localization",
|
||||
topic_id="https://openalex.org/T12345",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
],
|
||||
)
|
||||
assert result is not None
|
||||
score, keywords, symbols = result
|
||||
assert score == 0.9
|
||||
assert score == _compute_final_score(0.675, 1.0, 2 / 3)
|
||||
assert "localization" in keywords
|
||||
assert "G01S" in symbols
|
||||
|
||||
|
||||
def test_weighted_score_applies_level_and_relevance() -> None:
|
||||
score = _weighted_score("subclass", 0.8, 0.5)
|
||||
assert score == round(0.8 * 0.85 * 0.5, 4)
|
||||
def test_score_patent_requires_topic_overlap() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
ipc=["G01S 5/02"],
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
|
||||
]
|
||||
patent_topics = [
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T99999",
|
||||
subfield_name="Oncology",
|
||||
)
|
||||
]
|
||||
result = _score_patent(
|
||||
patent,
|
||||
ipc_matches,
|
||||
patent_topics=patent_topics,
|
||||
keyword_topic_ids=frozenset({"T12345"}),
|
||||
keyword_subfield_names=frozenset({"law"}),
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_score_patent_accepts_compatible_engineering_and_computer_science() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP456",
|
||||
source="EPO",
|
||||
ipc=["G06N 3/08"],
|
||||
title="Deep learning classifier",
|
||||
abstract="A neural network for classification tasks.",
|
||||
)
|
||||
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 not None
|
||||
|
||||
|
||||
def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None:
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Naturwissenschaft",
|
||||
keyword_level="broad",
|
||||
relevance_score=1.0,
|
||||
topic_id="https://openalex.org/T14329",
|
||||
field_name="Environmental Science",
|
||||
),
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Thermodynamik",
|
||||
keyword_level="coarse",
|
||||
relevance_score=0.8,
|
||||
topic_id="https://openalex.org/T12345",
|
||||
field_name="Physics and Astronomy",
|
||||
subfield_name="Statistical and Nonlinear Physics",
|
||||
),
|
||||
KeywordPatentSearchItem(
|
||||
keyword="noise",
|
||||
keyword_level="coarse",
|
||||
relevance_score=0.0,
|
||||
),
|
||||
]
|
||||
filtered = _filter_keywords_for_patent_search(items)
|
||||
assert [item.keyword for item in filtered] == ["Thermodynamik"]
|
||||
|
||||
|
||||
def test_filter_keywords_for_patent_search_allows_zero_relevance_with_topic() -> None:
|
||||
item = KeywordPatentSearchItem(
|
||||
keyword="Deep Learning",
|
||||
keyword_level="fine",
|
||||
relevance_score=0.0,
|
||||
topic_id="https://openalex.org/T12072",
|
||||
field_name="Computer Science",
|
||||
subfield_name="Artificial Intelligence",
|
||||
)
|
||||
assert _keyword_is_patent_searchable(item)
|
||||
|
||||
|
||||
def test_filter_keywords_for_patent_search_allows_high_relevance_with_technical_topic() -> None:
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Deep Learning",
|
||||
keyword_level="fine",
|
||||
relevance_score=0.9,
|
||||
topic_id="https://openalex.org/T12072",
|
||||
field_name="Computer Science",
|
||||
subfield_name="Artificial Intelligence",
|
||||
),
|
||||
]
|
||||
filtered = _filter_keywords_for_patent_search(items)
|
||||
assert [item.keyword for item in filtered] == ["Deep Learning"]
|
||||
|
||||
|
||||
def test_topics_overlap_keywords_soft_match_engineering_and_computer_science() -> None:
|
||||
patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["G06N 3/08"])
|
||||
patent_topics = [
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T12072",
|
||||
field_name="Computer Science",
|
||||
)
|
||||
]
|
||||
assert _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
frozenset({"T10653"}),
|
||||
frozenset({"control and systems engineering"}),
|
||||
frozenset({"engineering"}),
|
||||
patent=patent,
|
||||
)
|
||||
|
||||
|
||||
def test_score_patent_accepts_matching_topic_id() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
ipc=["G01S 5/02"],
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
|
||||
]
|
||||
patent_topics = [
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T12345",
|
||||
subfield_name="Remote Sensing",
|
||||
)
|
||||
]
|
||||
result = _score_patent(
|
||||
patent,
|
||||
ipc_matches,
|
||||
patent_topics=patent_topics,
|
||||
keyword_topic_ids=frozenset({"T12345"}),
|
||||
)
|
||||
assert result is not None
|
||||
|
||||
|
||||
def test_topics_overlap_keywords_uses_subfield_name_not_field() -> None:
|
||||
patent_topics = [
|
||||
MappedOpenAlexTopic(
|
||||
topic_id="https://openalex.org/T99999",
|
||||
subfield_name="Chemistry",
|
||||
field_name="Physical Sciences",
|
||||
)
|
||||
]
|
||||
assert not _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
frozenset(),
|
||||
frozenset({"law"}),
|
||||
frozenset(),
|
||||
)
|
||||
assert _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
frozenset(),
|
||||
frozenset({"chemistry"}),
|
||||
frozenset(),
|
||||
)
|
||||
assert _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
frozenset(),
|
||||
frozenset(),
|
||||
frozenset({"physical sciences"}),
|
||||
)
|
||||
assert not _topics_overlap_keywords(
|
||||
patent_topics,
|
||||
frozenset(),
|
||||
frozenset(),
|
||||
frozenset({"engineering"}),
|
||||
)
|
||||
|
||||
|
||||
def test_topics_overlap_keywords_rejects_patents_without_topics() -> None:
|
||||
assert not _topics_overlap_keywords(
|
||||
[],
|
||||
frozenset({"T12345"}),
|
||||
frozenset(),
|
||||
frozenset({"chemistry"}),
|
||||
)
|
||||
|
||||
|
||||
def test_limit_matches_per_keyword() -> 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"),
|
||||
]
|
||||
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"
|
||||
|
||||
|
||||
def test_text_overlap_score_uses_title_and_abstract() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
title="Organic chemistry synthesis",
|
||||
abstract="A method for catalytic reactions.",
|
||||
)
|
||||
score = _text_overlap_score(
|
||||
patent,
|
||||
["organic", "chemistry", "catalytic", "reactions", "unrelated"],
|
||||
)
|
||||
assert score == 1.0
|
||||
|
||||
|
||||
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
title="Diagnostic imaging device",
|
||||
abstract="Medical diagnosis using imaging.",
|
||||
)
|
||||
assert _patent_passes_relevance_gate(
|
||||
[],
|
||||
keyword_topic_ids=frozenset({"T99999"}),
|
||||
keyword_subfield_names=frozenset(),
|
||||
keyword_soft_field_names=frozenset({"medicine"}),
|
||||
patent=patent,
|
||||
text_score=_text_overlap_score(patent, ["diagnostic", "imaging", "diagnosis"]),
|
||||
)
|
||||
|
||||
|
||||
def test_patent_passes_relevance_gate_rejects_ipc_only() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
title="Humidifier system",
|
||||
abstract="Water exchange membrane.",
|
||||
)
|
||||
assert not _patent_passes_relevance_gate(
|
||||
[],
|
||||
keyword_topic_ids=frozenset({"T99999"}),
|
||||
keyword_subfield_names=frozenset(),
|
||||
keyword_soft_field_names=frozenset({"medicine"}),
|
||||
patent=patent,
|
||||
text_score=0.0,
|
||||
)
|
||||
|
||||
|
||||
def test_compute_final_score_weights_ipc_topic_and_text() -> None:
|
||||
assert _compute_final_score(0.9, 1.0, 1.0) == round(
|
||||
0.60 * 0.9 + 0.25 * 1.0 + 0.15 * 1.0,
|
||||
4,
|
||||
)
|
||||
assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4)
|
||||
|
||||
|
||||
def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None:
|
||||
patent = model.PatentEntry(
|
||||
patent_id="EP1",
|
||||
source="EPO",
|
||||
ipc=["C07C31/20"],
|
||||
title="Humidifier system",
|
||||
abstract="Water exchange membrane.",
|
||||
)
|
||||
ipc_matches = [
|
||||
IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"),
|
||||
]
|
||||
result = _score_patent(
|
||||
patent,
|
||||
ipc_matches,
|
||||
patent_topics=[],
|
||||
keyword_topic_ids=frozenset({"T99999"}),
|
||||
keyword_soft_field_names=frozenset({"chemistry"}),
|
||||
search_keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Organische Chemie",
|
||||
topic_id="https://openalex.org/T99999",
|
||||
field_name="Chemistry",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
],
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_get_patents_by_keywords_uses_symbol_queries() -> None:
|
||||
queries = IpcPatentSearchQueries()
|
||||
captured: list[str] = []
|
||||
|
||||
async def fake_search_epo(query):
|
||||
captured.append("epo")
|
||||
assert "query" in query
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
async def fake_search_uspto(query):
|
||||
captured.append("uspto")
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
request = PatentsByKeywordsRequest(
|
||||
keywords=[
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Organische Chemie",
|
||||
keyword_level="coarse",
|
||||
topic_id="https://openalex.org/T13859",
|
||||
field_name="Chemistry",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
IpcCodeMatch(
|
||||
"subgroup",
|
||||
"C07C243/08",
|
||||
0.8989,
|
||||
"Organische Chemie",
|
||||
"keyword",
|
||||
)
|
||||
]
|
||||
),
|
||||
), 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_ipc_symbols",
|
||||
wraps=queries.epo_query_by_ipc_symbols,
|
||||
) as epo_symbols, patch.object(
|
||||
IpcPatentSearchQueries,
|
||||
"uspto_query_by_ipc_symbols",
|
||||
wraps=queries.uspto_query_by_ipc_symbols,
|
||||
) as uspto_symbols:
|
||||
asyncio.run(get_patents_by_keywords(request))
|
||||
|
||||
epo_symbols.assert_called_once()
|
||||
uspto_symbols.assert_called_once()
|
||||
assert epo_symbols.call_args.args[0] == ["C07C"]
|
||||
assert captured == ["epo", "uspto"]
|
||||
|
||||
|
||||
def test_text_search_terms_include_topic_metadata() -> None:
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Organische Chemie",
|
||||
topic_display_name="Organic Chemistry",
|
||||
subfield_name="Organic Chemistry",
|
||||
field_name="Chemistry",
|
||||
relevance_score=0.9,
|
||||
topic_id="https://openalex.org/T1",
|
||||
)
|
||||
]
|
||||
terms = _text_search_terms(items)
|
||||
assert "organische" in terms
|
||||
assert "organic" in terms
|
||||
assert "chemistry" in terms
|
||||
|
||||
|
||||
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_zero == score_high
|
||||
|
||||
|
||||
def test_search_terms_use_subclass_prefix() -> None:
|
||||
@@ -49,47 +544,16 @@ def test_search_terms_use_subclass_prefix() -> None:
|
||||
assert "G06N" in _search_terms_for_symbol("G06N")
|
||||
|
||||
|
||||
def test_legacy_lookup_uses_chemistry_heuristics() -> None:
|
||||
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
||||
clear_reverse_lookup_caches()
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Organische Chemie",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
matches = _finalize_ipc_matches(items, _legacy_lookup(items))
|
||||
symbols = {match.ipc_symbol for match in matches}
|
||||
assert "C07C" in symbols
|
||||
|
||||
|
||||
def test_legacy_lookup_uses_medicine_heuristics() -> None:
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
||||
lambda: {},
|
||||
)
|
||||
clear_reverse_lookup_caches()
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Medizin",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
matches = _finalize_ipc_matches(items, _legacy_lookup(items))
|
||||
symbols = {match.ipc_symbol for match in matches}
|
||||
assert "A61B" in symbols
|
||||
|
||||
|
||||
def test_legacy_lookup_uses_cs_ai_heuristics() -> None:
|
||||
clear_reverse_lookup_caches()
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Klassifikation",
|
||||
topic_id="https://openalex.org/T12072",
|
||||
topic_display_name="Machine Learning and Algorithms",
|
||||
subfield_name="Artificial Intelligence",
|
||||
field_name="Computer Science",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
matches = _finalize_ipc_matches(items, _legacy_lookup(items))
|
||||
symbols = {match.ipc_symbol for match in matches}
|
||||
assert "G06N" in symbols
|
||||
items = [KeywordPatentSearchItem(keyword="Medizin", relevance_score=1.0)]
|
||||
assert _json_lookup(items) == []
|
||||
|
||||
|
||||
def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None:
|
||||
@@ -126,3 +590,83 @@ def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None:
|
||||
assert len(matches) == 1
|
||||
assert matches[0].ipc_symbol == "G01S"
|
||||
assert matches[0].match_score > 0
|
||||
|
||||
|
||||
def test_json_lookup_finds_ipc_for_topic_id(monkeypatch) -> None:
|
||||
clear_reverse_lookup_caches()
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
||||
lambda: {
|
||||
"subclass": {
|
||||
"G06N": {
|
||||
"ipc_level": "subclass",
|
||||
"ipc_symbol": "G06N",
|
||||
"keyword_matches": [],
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T12072",
|
||||
"topic_display_name": "Machine Learning and Algorithms",
|
||||
"match_score": 0.88,
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
clear_reverse_lookup_caches()
|
||||
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Klassifikation",
|
||||
topic_id="https://openalex.org/T12072",
|
||||
topic_display_name="Machine Learning and Algorithms",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
matches = _json_lookup(items)
|
||||
assert len(matches) == 1
|
||||
assert matches[0].ipc_symbol == "G06N"
|
||||
assert matches[0].match_type == "topic"
|
||||
|
||||
|
||||
def test_json_lookup_resolves_topic_id_from_display_name(monkeypatch) -> None:
|
||||
clear_reverse_lookup_caches()
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
||||
lambda: {
|
||||
"subclass": {
|
||||
"G01N": {
|
||||
"ipc_level": "subclass",
|
||||
"ipc_symbol": "G01N",
|
||||
"keyword_matches": [],
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T14329",
|
||||
"topic_display_name": "Science and Climate Studies",
|
||||
"match_score": 0.9,
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"inse.patents.keywords.reverse_lookup._load_topic_cache",
|
||||
lambda: {
|
||||
"Science and Climate Studies": {
|
||||
"topic_id": "https://openalex.org/T14329",
|
||||
}
|
||||
},
|
||||
)
|
||||
clear_reverse_lookup_caches()
|
||||
|
||||
items = [
|
||||
KeywordPatentSearchItem(
|
||||
keyword="Science and Climate Studies",
|
||||
topic_display_name="Science and Climate Studies",
|
||||
relevance_score=1.0,
|
||||
)
|
||||
]
|
||||
matches = _json_lookup(items)
|
||||
assert len(matches) == 1
|
||||
assert matches[0].ipc_symbol == "G01N"
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { PatentEntry } from './patentEntry';
|
||||
|
||||
export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
|
||||
|
||||
export interface KeywordPatentSearchItem {
|
||||
keyword: string;
|
||||
keyword_level?: KeywordPatentLevel | null;
|
||||
topic_id?: string | null;
|
||||
topic_display_name?: string | null;
|
||||
subfield_name?: string | null;
|
||||
|
||||
+132
-114
@@ -1,114 +1,132 @@
|
||||
@if (loading()) {
|
||||
<p class="message">Lade passende Patente...</p>
|
||||
} @else if (error()) {
|
||||
<p class="message">Fehler beim Laden der Patente.</p>
|
||||
} @else if (matches().length === 0) {
|
||||
<p class="message">Keine passenden Patente gefunden.</p>
|
||||
} @else {
|
||||
<div class="patents-container">
|
||||
<h2 class="section-title">Passende Patente</h2>
|
||||
|
||||
<div class="patents-content">
|
||||
<div class="patents-list">
|
||||
<div class="patents-list-toolbar">
|
||||
<label class="sort-control">
|
||||
<span>Filter nach Quelle:</span>
|
||||
<select
|
||||
[value]="activeFilter()"
|
||||
(change)="setFilter($any($event.target).value)">
|
||||
<option value="all">Alle</option>
|
||||
<option value="EPO">EPO</option>
|
||||
<option value="USPTO">USPTO</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Patent</th>
|
||||
<th>Quelle</th>
|
||||
<th>Jahr</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (item of pagedMatches(); track trackMatch($index, item)) {
|
||||
<tr
|
||||
[class.selected]="selectedPatent() === item.patent"
|
||||
(click)="selectPatent(item.patent)">
|
||||
<td class="patent-title">
|
||||
{{ item.patent.title ?? item.patent.patent_id }}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
class="source-badge source-badge--{{
|
||||
item.patent.source.toLowerCase()
|
||||
}}">
|
||||
{{ item.patent.source }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ item.patent.publication_year ?? '-' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@if (hasPagination()) {
|
||||
<div class="pagination">
|
||||
<button
|
||||
[disabled]="selectedPage() === 1"
|
||||
(click)="setPage(selectedPage() - 1)">
|
||||
Zurück
|
||||
</button>
|
||||
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>
|
||||
<button
|
||||
[disabled]="selectedPage() === pageCount()"
|
||||
(click)="setPage(selectedPage() + 1)">
|
||||
Weiter
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (selectedPatent(); as patent) {
|
||||
<div class="patent-detail">
|
||||
<h3>{{ patent.title ?? patent.patent_id }}</h3>
|
||||
<div class="detail-stats">
|
||||
<div class="stat">
|
||||
<span class="stat-label">Quelle</span>
|
||||
<span class="stat-value">
|
||||
<span
|
||||
class="source-badge source-badge--{{
|
||||
patent.source.toLowerCase()
|
||||
}}">
|
||||
{{ patent.source }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Patent-Nr.</span>
|
||||
<span class="stat-value">{{ patent.patent_id }}</span>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<span class="stat-label">Datum</span>
|
||||
<span class="stat-value">{{
|
||||
formatDate(patent.publication_date)
|
||||
}}</span>
|
||||
</div>
|
||||
@if (getPublicationStageLabel(patent); as stageLabel) {
|
||||
<div class="stat">
|
||||
<span class="stat-label">Publikationsstufe</span>
|
||||
<span class="stat-value">{{ stageLabel }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<button type="button" class="patent-detail-action" (click)="openDetail()">
|
||||
<span class="patent-detail-action__label">Patentdetails anzeigen</span>
|
||||
<span class="material-icons" aria-hidden="true">chevron_right</span>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (loading()) {␍
|
||||
<p class="message">Lade passende Patente...</p>␍
|
||||
} @else if (error()) {␍
|
||||
<p class="message">Fehler beim Laden der Patente.</p>␍
|
||||
} @else if (matches().length === 0) {␍
|
||||
<p class="message">Keine passenden Patente gefunden.</p>␍
|
||||
} @else {␍
|
||||
<div class="patents-container">␍
|
||||
<h2 class="section-title">Passende Patente</h2>␍
|
||||
␍
|
||||
<div class="patents-content">␍
|
||||
<div class="patents-list">␍
|
||||
<div class="patents-list-toolbar">␍
|
||||
<label class="sort-control">␍
|
||||
<span>Filter nach Quelle:</span>␍
|
||||
<select␍
|
||||
[value]="activeFilter()"␍
|
||||
(change)="setFilter($any($event.target).value)">␍
|
||||
<option value="all">Alle</option>␍
|
||||
<option value="EPO">EPO</option>␍
|
||||
<option value="USPTO">USPTO</option>␍
|
||||
</select>␍
|
||||
</label>␍
|
||||
</div>␍
|
||||
␍
|
||||
<table>␍
|
||||
<thead>␍
|
||||
<tr>␍
|
||||
<th>Patent</th>␍
|
||||
<th>Score</th>␍
|
||||
<th>Quelle</th>␍
|
||||
<th>Jahr</th>␍
|
||||
</tr>␍
|
||||
</thead>␍
|
||||
<tbody>␍
|
||||
@for (item of pagedMatches(); track trackMatch($index, item)) {␍
|
||||
<tr␍
|
||||
[class.selected]="selectedMatch() === item"␍
|
||||
(click)="selectMatch(item)">␍
|
||||
<td class="patent-title">␍
|
||||
{{ item.patent.title ?? item.patent.patent_id }}␍
|
||||
</td>␍
|
||||
<td class="match-score">{{ formatScore(item.match_score) }}</td>␍
|
||||
<td>␍
|
||||
<span␍
|
||||
class="source-badge source-badge--{{␍
|
||||
item.patent.source.toLowerCase()␍
|
||||
}}">␍
|
||||
{{ item.patent.source }}␍
|
||||
</span>␍
|
||||
</td>␍
|
||||
<td>{{ item.patent.publication_year ?? '-' }}</td>␍
|
||||
</tr>␍
|
||||
}␍
|
||||
</tbody>␍
|
||||
</table>␍
|
||||
␍
|
||||
@if (hasPagination()) {␍
|
||||
<div class="pagination">␍
|
||||
<button␍
|
||||
[disabled]="selectedPage() === 1"␍
|
||||
(click)="setPage(selectedPage() - 1)">␍
|
||||
Zurück␍
|
||||
</button>␍
|
||||
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>␍
|
||||
<button␍
|
||||
[disabled]="selectedPage() === pageCount()"␍
|
||||
(click)="setPage(selectedPage() + 1)">␍
|
||||
Weiter␍
|
||||
</button>␍
|
||||
</div>␍
|
||||
}␍
|
||||
</div>␍
|
||||
␍
|
||||
@if (selectedMatch(); as match) {␍
|
||||
<div class="patent-detail">␍
|
||||
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>␍
|
||||
<div class="detail-stats">␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Match-Score</span>␍
|
||||
<span class="stat-value">{{ formatScore(match.match_score) }}</span>␍
|
||||
</div>␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Gematchte Keywords</span>␍
|
||||
<span class="stat-value">{{␍
|
||||
formatMatchList(match.matched_keywords)␍
|
||||
}}</span>␍
|
||||
</div>␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Gematchte IPC/CPC</span>␍
|
||||
<span class="stat-value">{{␍
|
||||
formatMatchList(match.matched_ipc_symbols)␍
|
||||
}}</span>␍
|
||||
</div>␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Quelle</span>␍
|
||||
<span class="stat-value">␍
|
||||
<span␍
|
||||
class="source-badge source-badge--{{␍
|
||||
match.patent.source.toLowerCase()␍
|
||||
}}">␍
|
||||
{{ match.patent.source }}␍
|
||||
</span>␍
|
||||
</span>␍
|
||||
</div>␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Patent-Nr.</span>␍
|
||||
<span class="stat-value">{{ match.patent.patent_id }}</span>␍
|
||||
</div>␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Datum</span>␍
|
||||
<span class="stat-value">{{␍
|
||||
formatDate(match.patent.publication_date)␍
|
||||
}}</span>␍
|
||||
</div>␍
|
||||
@if (getPublicationStageLabel(match.patent); as stageLabel) {␍
|
||||
<div class="stat">␍
|
||||
<span class="stat-label">Publikationsstufe</span>␍
|
||||
<span class="stat-value">{{ stageLabel }}</span>␍
|
||||
</div>␍
|
||||
}␍
|
||||
</div>␍
|
||||
␍
|
||||
<button type="button" class="patent-detail-action" (click)="openDetail()">␍
|
||||
<span class="patent-detail-action__label">Patentdetails anzeigen</span>␍
|
||||
<span class="material-icons" aria-hidden="true">chevron_right</span>␍
|
||||
</button>␍
|
||||
</div>␍
|
||||
}␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
}␍
|
||||
|
||||
+11
@@ -113,12 +113,23 @@
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
.match-score {
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #374151;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
display: block;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.patent-detail-action {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+103
-88
@@ -1,88 +1,103 @@
|
||||
import { Component, input, signal } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { PatentEntry } from '../../../api/model/patentEntry';
|
||||
import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse';
|
||||
import {
|
||||
formatPatentDate,
|
||||
getPublicationStageLabel,
|
||||
} from '../../patent-detail/patent-detail.utils';
|
||||
|
||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||
|
||||
@Component({
|
||||
selector: 'app-keywords-patents',
|
||||
templateUrl: './keywords-patents.component.html',
|
||||
styleUrl: './keywords-patents.component.scss',
|
||||
})
|
||||
export class KeywordsPatentsComponent {
|
||||
readonly matches = input<KeywordPatentMatch[]>([]);
|
||||
readonly loading = input(false);
|
||||
readonly error = input(false);
|
||||
|
||||
activeFilter = signal<SourceFilter>('all');
|
||||
selectedPatent = signal<PatentEntry | null>(null);
|
||||
selectedPage = signal(1);
|
||||
readonly pageSize = 10;
|
||||
|
||||
constructor(private readonly router: Router) {}
|
||||
|
||||
filteredMatches(): KeywordPatentMatch[] {
|
||||
const filter = this.activeFilter();
|
||||
const items = this.matches();
|
||||
if (filter === 'all') {
|
||||
return items;
|
||||
}
|
||||
return items.filter((item) => item.patent.source === filter);
|
||||
}
|
||||
|
||||
pagedMatches(): KeywordPatentMatch[] {
|
||||
const start = (this.selectedPage() - 1) * this.pageSize;
|
||||
return this.filteredMatches().slice(start, start + this.pageSize);
|
||||
}
|
||||
|
||||
pageCount(): number {
|
||||
return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize));
|
||||
}
|
||||
|
||||
hasPagination(): boolean {
|
||||
return this.pageCount() > 1;
|
||||
}
|
||||
|
||||
setFilter(filter: SourceFilter): void {
|
||||
this.activeFilter.set(filter);
|
||||
this.selectedPage.set(1);
|
||||
this.selectedPatent.set(null);
|
||||
}
|
||||
|
||||
setPage(page: number): void {
|
||||
this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount()));
|
||||
}
|
||||
|
||||
selectPatent(patent: PatentEntry): void {
|
||||
this.selectedPatent.set(patent);
|
||||
}
|
||||
|
||||
openDetail(): void {
|
||||
const patent = this.selectedPatent();
|
||||
if (!patent) return;
|
||||
void this.router.navigate(['/patent', patent.patent_id]);
|
||||
}
|
||||
|
||||
formatDate(date: string | null | undefined): string {
|
||||
return formatPatentDate(date);
|
||||
}
|
||||
|
||||
getPublicationStageLabel(patent: PatentEntry): string | null {
|
||||
return getPublicationStageLabel(patent);
|
||||
}
|
||||
|
||||
trackMatch(_index: number, item: KeywordPatentMatch): string {
|
||||
const patent = item.patent;
|
||||
return [
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date ?? '',
|
||||
patent.kind ?? patent.application_type ?? '',
|
||||
].join('|');
|
||||
}
|
||||
}
|
||||
import { Component, input, signal } from '@angular/core';␍
|
||||
import { Router } from '@angular/router';␍
|
||||
import { PatentEntry } from '../../../api/model/patentEntry';␍
|
||||
import { KeywordPatentMatch } from '../../../api/model/patentsByKeywordsResponse';␍
|
||||
import {␍
|
||||
formatPatentDate,␍
|
||||
getPublicationStageLabel,␍
|
||||
} from '../../patent-detail/patent-detail.utils';␍
|
||||
␍
|
||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';␍
|
||||
␍
|
||||
@Component({␍
|
||||
selector: 'app-keywords-patents',␍
|
||||
templateUrl: './keywords-patents.component.html',␍
|
||||
styleUrl: './keywords-patents.component.scss',␍
|
||||
})␍
|
||||
export class KeywordsPatentsComponent {␍
|
||||
readonly matches = input<KeywordPatentMatch[]>([]);␍
|
||||
readonly loading = input(false);␍
|
||||
readonly error = input(false);␍
|
||||
␍
|
||||
activeFilter = signal<SourceFilter>('all');␍
|
||||
selectedMatch = signal<KeywordPatentMatch | null>(null);␍
|
||||
selectedPage = signal(1);␍
|
||||
readonly pageSize = 10;␍
|
||||
␍
|
||||
constructor(private readonly router: Router) {}␍
|
||||
␍
|
||||
filteredMatches(): KeywordPatentMatch[] {␍
|
||||
const filter = this.activeFilter();␍
|
||||
const items = this.matches();␍
|
||||
if (filter === 'all') {␍
|
||||
return items;␍
|
||||
}␍
|
||||
return items.filter((item) => item.patent.source === filter);␍
|
||||
}␍
|
||||
␍
|
||||
pagedMatches(): KeywordPatentMatch[] {␍
|
||||
const start = (this.selectedPage() - 1) * this.pageSize;␍
|
||||
return this.filteredMatches().slice(start, start + this.pageSize);␍
|
||||
}␍
|
||||
␍
|
||||
pageCount(): number {␍
|
||||
return Math.max(1, Math.ceil(this.filteredMatches().length / this.pageSize));␍
|
||||
}␍
|
||||
␍
|
||||
hasPagination(): boolean {␍
|
||||
return this.pageCount() > 1;␍
|
||||
}␍
|
||||
␍
|
||||
setFilter(filter: SourceFilter): void {␍
|
||||
this.activeFilter.set(filter);␍
|
||||
this.selectedPage.set(1);␍
|
||||
this.selectedMatch.set(null);␍
|
||||
}␍
|
||||
␍
|
||||
setPage(page: number): void {␍
|
||||
this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount()));␍
|
||||
}␍
|
||||
␍
|
||||
selectMatch(item: KeywordPatentMatch): void {␍
|
||||
this.selectedMatch.set(item);␍
|
||||
}␍
|
||||
␍
|
||||
openDetail(): void {␍
|
||||
const match = this.selectedMatch();␍
|
||||
if (!match) return;␍
|
||||
void this.router.navigate(['/patent', match.patent.patent_id]);␍
|
||||
}␍
|
||||
␍
|
||||
formatDate(date: string | null | undefined): string {␍
|
||||
return formatPatentDate(date);␍
|
||||
}␍
|
||||
␍
|
||||
getPublicationStageLabel(patent: PatentEntry): string | null {␍
|
||||
return getPublicationStageLabel(patent);␍
|
||||
}␍
|
||||
␍
|
||||
formatScore(score: number | null | undefined): string {␍
|
||||
if (score == null || Number.isNaN(score)) {␍
|
||||
return '-';␍
|
||||
}␍
|
||||
return score.toFixed(2);␍
|
||||
}␍
|
||||
␍
|
||||
formatMatchList(values: string[] | null | undefined): string {␍
|
||||
if (!values || values.length === 0) {␍
|
||||
return '-';␍
|
||||
}␍
|
||||
return values.join(', ');␍
|
||||
}␍
|
||||
␍
|
||||
trackMatch(_index: number, item: KeywordPatentMatch): string {␍
|
||||
const patent = item.patent;␍
|
||||
return [␍
|
||||
patent.source,␍
|
||||
patent.patent_id,␍
|
||||
patent.publication_date ?? '',␍
|
||||
patent.kind ?? patent.application_type ?? '',␍
|
||||
item.match_score,␍
|
||||
].join('|');␍
|
||||
}␍
|
||||
}␍
|
||||
|
||||
@@ -58,6 +58,7 @@ import { SearchResultsPayload } from './search-results/search-results-state.serv
|
||||
type InputMode = 'url' | 'text';
|
||||
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
||||
type KeywordView = 'llm' | 'topic';
|
||||
type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
|
||||
@Component({
|
||||
selector: 'app-keywords-search',
|
||||
imports: [
|
||||
@@ -1109,11 +1110,9 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
private loadMatchingPatents(): void {
|
||||
const entries = [
|
||||
...this.getSelectedExtractedKeywordEntries(),
|
||||
...this.getSelectedManualKeywordEntries(),
|
||||
];
|
||||
const keywords = this.buildPatentSearchItems(entries);
|
||||
const keywords = this.buildPatentSearchItems(
|
||||
this.getSelectedPatentKeywordEntries(),
|
||||
);
|
||||
if (keywords.length === 0) {
|
||||
this.patentMatches.set([]);
|
||||
this.patentsLoaded.set(true);
|
||||
@@ -1139,12 +1138,39 @@ export class KeywordsSearchComponent {
|
||||
});
|
||||
}
|
||||
|
||||
private getSelectedPatentKeywordEntries(): Array<{
|
||||
entry: KeywordEntryWithTopic;
|
||||
level: KeywordPatentLevel;
|
||||
}> {
|
||||
const selected = new Set(
|
||||
this.selectedKeywords().map((k) => this.normalizeKeyword(k)),
|
||||
);
|
||||
const isSelected = (item: KeywordEntryWithTopic) =>
|
||||
selected.has(this.normalizeKeyword(this.getKeywordLabel(item)));
|
||||
|
||||
return [
|
||||
...this.broadKeywordEntries()
|
||||
.filter(isSelected)
|
||||
.map((entry) => ({ entry, level: 'broad' as const })),
|
||||
...this.coarseKeywordEntries()
|
||||
.filter(isSelected)
|
||||
.map((entry) => ({ entry, level: 'coarse' as const })),
|
||||
...this.fineKeywordEntries()
|
||||
.filter(isSelected)
|
||||
.map((entry) => ({ entry, level: 'fine' as const })),
|
||||
...this.manualKeywordEntries()
|
||||
.filter(isSelected)
|
||||
.map((entry) => ({ entry, level: 'custom' as const })),
|
||||
];
|
||||
}
|
||||
|
||||
private buildPatentSearchItems(
|
||||
entries: KeywordEntryWithTopic[],
|
||||
items: Array<{ entry: KeywordEntryWithTopic; level: KeywordPatentLevel }>,
|
||||
): KeywordPatentSearchItem[] {
|
||||
return entries
|
||||
.map((entry) => ({
|
||||
return items
|
||||
.map(({ entry, level }) => ({
|
||||
keyword: entry.llm_keyword.keyword,
|
||||
keyword_level: level,
|
||||
topic_id: entry.topic_mapping?.topic?.id ?? null,
|
||||
topic_display_name: entry.topic_mapping?.topic?.display_name ?? null,
|
||||
subfield_name: entry.topic_mapping?.topic?.subfield?.display_name ?? null,
|
||||
|
||||
Reference in New Issue
Block a user