propper implementation of trend_patents using existing patent api

This commit is contained in:
Kazgatari
2026-07-16 19:04:48 +02:00
parent 63865efe84
commit ab14d3e9ae
3 changed files with 133 additions and 257 deletions
@@ -184,21 +184,29 @@ class PatentsOpenAlexKeywordsClient:
if not unique_ids:
return {}
batch_size = 1000
results = {}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
headers=self._headers(),
json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}},
)
if response.status_code == 404:
return {}
response.raise_for_status()
hits = response.json().get("hits", {}).get("hits", [])
return {hit["_id"]: hit.get("_source", {}) for hit in hits}
for i in range(0, len(unique_ids), batch_size):
batch = unique_ids[i : i + batch_size]
response = await client.post(
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
headers=self._headers(),
json={"size": len(batch), "query": {"ids": {"values": batch}}},
)
if response.status_code == 404:
continue
response.raise_for_status()
hits = response.json().get("hits", {}).get("hits", [])
for hit in hits:
results[hit["_id"]] = hit.get("_source", {})
return results
async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
ordered_ids = candidate_doc_ids(symbol)
@@ -752,6 +752,41 @@ async def get_top_topics_for_entity(
end_year: int,
search_type: str
) -> Dict[str, Any]:
if search_type == "patents" and entity_type == "institution":
from inse.patents.org.logic import get_org_patents_by_institution_id
try:
res = await get_org_patents_by_institution_id(
institution_id=entity_id,
match_type="all",
page=0,
size=10000
)
topic_counts = {}
for p in res.patents:
try:
yr = int(p.publication_year) if p.publication_year else None
if yr and start_year <= yr <= end_year:
for ot in p.openalex_topics:
if ot.topic_display_name:
topic_counts[ot.topic_display_name] = topic_counts.get(ot.topic_display_name, 0) + 1
except Exception:
pass
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_10 = sorted_topics[:10]
items = [{"name": name, "count": count} for name, count in top_10]
sum_top_10 = sum(count for name, count in top_10)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top_10)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top patent topics for institution: %s", e)
return {"items": []}
# 1. Normalize ID and prepare filter clause
if entity_type == "institution":
entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}"
@@ -571,7 +571,6 @@ class AuthorsTrendStrategy(TrendStrategy):
return TrendResponse(series=series_list, years=years_range)
### index was not ready yet, change!
class PatentsTrendStrategy(TrendStrategy):
async def get_trend(
self,
@@ -596,264 +595,98 @@ class PatentsTrendStrategy(TrendStrategy):
if primary_inst_id not in query_institutions:
query_institutions.insert(0, primary_inst_id)
query_countries = countries or []
query_regions = regions or []
# 1. Resolve institution names from openalex-institutions index
resolved_names = {primary_inst_id: primary_inst_name}
try:
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_INSTITUTIONS),
query={"terms": {"id": query_institutions}},
size=len(query_institutions),
source=["id", "display_name"],
cluster="nes"
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
resolved_names[source["id"]] = source.get("display_name", source["id"])
except Exception as e:
logger.warning("Failed to resolve institution details from ES: %s", e)
clean_countries = [c.strip().upper() for c in query_countries]
clean_regions = [r.strip() for r in query_regions]
ids_to_resolve = list(set(query_institutions))
# 2. Fetch patents using the existing API endpoint / logic
from inse.patents.org.logic import get_org_patents_by_institution_id
# 1. Resolve institution names & variants, country names, and regions
async def fetch_institutions():
names = {primary_inst_id: primary_inst_name}
codes = {}
variants_map = {}
if not ids_to_resolve:
return names, codes, variants_map
async def fetch_patents(inst_id: str):
try:
from inse.patents.institutions.name_matching import institution_search_variants
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_INSTITUTIONS),
query={"terms": {"id": ids_to_resolve}},
size=len(ids_to_resolve),
source=["id", "display_name", "display_name_alternatives", "acronyms", "country_code"],
cluster="nes"
res = await get_org_patents_by_institution_id(
institution_id=inst_id,
match_type="all",
page=0,
size=10000
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
inst_id = source["id"]
names[inst_id] = source.get("display_name", inst_id)
codes[inst_id] = source.get("country_code", "")
variants = set()
for name in [source.get("display_name")] + source.get("display_name_alternatives", []) + source.get("acronyms", []):
if name:
for var in institution_search_variants(name):
variants.add(var)
variants_map[inst_id] = list(variants)
return inst_id, res.patents, res.institution_name
except Exception as e:
logger.warning("Failed to resolve institution details from ES: %s", e)
return names, codes, variants_map
logger.error("Failed to fetch org-patents for institution %s: %s", inst_id, e)
return inst_id, [], None
async def fetch_countries():
names = {}
if not clean_countries:
return names
try:
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_COUNTRIES),
query={"terms": {"country_code": clean_countries}},
size=len(clean_countries),
source=["country_code", "display_name"],
cluster="nes"
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
names[source["country_code"]] = source["display_name"]
except Exception as e:
logger.warning("Failed to resolve country names from ES: %s", e)
return names
fetched = await asyncio.gather(*(fetch_patents(inst_id) for inst_id in query_institutions))
async def fetch_continents():
names = {}
ccodes = {}
if not clean_regions:
return names, ccodes
try:
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_CONTINENTS),
query={
"bool": {
"should": [
{"terms": {"wikidata_id.keyword": clean_regions}},
{"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}}
]
}
},
size=len(clean_regions),
source=["id", "display_name", "wikidata_id", "countries"],
cluster="nes"
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
c_code = source.get("wikidata_id") or source["id"].split("/")[-1]
names[c_code] = source["display_name"]
ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])]
except Exception as e:
logger.warning("Failed to resolve continent names from ES: %s", e)
return names, ccodes
# Helper matching functions (case-insensitive substring topic and keyword matching)
def matches_topic(patent, topic: str) -> bool:
if not patent.openalex_topics:
return False
t_lower = topic.lower()
for ot in patent.openalex_topics:
if ot.topic_display_name:
ot_display_lower = ot.topic_display_name.lower()
if t_lower in ot_display_lower or ot_display_lower in t_lower:
return True
if ot.topic_id and ot.topic_id.lower() == t_lower:
return True
return False
(
(resolved_names, resolved_country_codes, resolved_variants),
resolved_country_names,
(resolved_continent_names, continent_country_codes)
) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents())
def matches_patent(patent, topic: str, keyword: Optional[str], fuzzy: bool) -> bool:
if matches_topic(patent, topic):
return True
if not fuzzy and keyword:
kw_lower = keyword.lower()
if patent.title and kw_lower in patent.title.lower():
return True
if patent.abstract and kw_lower in patent.abstract.lower():
return True
if patent.openalex_topics:
for ot in patent.openalex_topics:
if ot.topic_display_name and kw_lower in ot.topic_display_name.lower():
return True
return False
location_mappings = continent_country_codes.copy()
# Build list of entities
filters_map = {}
for inst_id in query_institutions:
filters_map[f"inst_{inst_id}"] = ("institution", inst_id)
for cc in clean_countries:
filters_map[f"country_{cc}"] = ("country", cc)
for r_code, member_ccs in continent_country_codes.items():
if member_ccs:
filters_map[f"region_{r_code}"] = ("region", member_ccs)
if not filters_map:
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
# 2. Query IPC symbols for each topic
from inse.patents.search_client import PatentSearchClient
patent_client = PatentSearchClient()
topic_symbols = {}
for idx, t in enumerate(topics):
if not fuzzy and keywords and idx < len(keywords):
kw_val = keywords[idx]
query = {
"query": {
"bool": {
"should": [
{"match": {"ipc_label": kw_val}},
{"nested": {"path": "topic_matches", "query": {"match": {"topic_matches.topic_display_name": kw_val}}}},
{"nested": {"path": "topic_matches", "query": {"match": {"topic_matches.subfield": kw_val}}}},
{"nested": {"path": "keyword_matches", "query": {"match": {"keyword_matches.keyword": kw_val}}}},
{"nested": {"path": "keyword_matches", "query": {"match": {"keyword_matches.topic_display_name": kw_val}}}}
],
"minimum_should_match": 1
}
},
"size": 10000
}
else:
query = {
"query": {
"nested": {
"path": "topic_matches",
"query": {
"term": {
"topic_matches.topic_display_name": t
}
}
}
},
"size": 10000
}
try:
res = await patent_client._search(index="patents_openalex_keywords", payload=query)
hits = res.get("hits", {}).get("hits", [])
symbols = [hit["_source"]["ipc_symbol"] for hit in hits if hit.get("_source", {}).get("ipc_symbol")]
topic_symbols[t] = list(set(symbols))
except Exception as e:
logger.error("Failed to query patents_openalex_keywords for topic %s: %s", t, e)
topic_symbols[t] = []
# 3. For each entity & topic, build queries and fetch timeseries data
# 3. For each institution & topic, filter patents and group by year
accumulated_data = {
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
for key in filters_map
f"inst_{inst_id}": {t: {yr: (0, 1) for yr in years_range} for t in topics}
for inst_id in query_institutions
}
async def query_patents_trends(entity_key, entity_type, entity_val, topic, symbols):
if not symbols:
return
epo_ipc_filter = {"bool": {"should": [{"match_phrase_prefix": {"ipc": sym}} for sym in symbols], "minimum_should_match": 1}}
uspto_ipcr_filter = {"bool": {"should": [{"match_phrase_prefix": {"ipcr": sym}} for sym in symbols], "minimum_should_match": 1}}
epo_must = [epo_ipc_filter]
uspto_must = [uspto_ipcr_filter]
if entity_type == "institution":
vars = resolved_variants.get(entity_val, [entity_val])
epo_must.append(patent_client._match_organization_names("applicants_name", vars))
uspto_must.append(patent_client._match_organization_names("assignees_orgs", vars))
elif entity_type == "country":
epo_must.append({"match": {"applicants_adr": entity_val}})
uspto_must.append({"match": {"assignees_addresses": entity_val}})
elif entity_type == "region":
epo_must.append({"bool": {"should": [{"match": {"applicants_adr": cc}} for cc in entity_val], "minimum_should_match": 1}})
uspto_must.append({"bool": {"should": [{"match": {"assignees_addresses": cc}} for cc in entity_val], "minimum_should_match": 1}})
epo_query = {
"query": {"bool": {"must": epo_must}},
"size": 0,
"aggs": {
"by_year": {
"terms": {
"field": "date_publication_year",
"size": 100
}
}
}
}
uspto_query = {
"query": {"bool": {"must": uspto_must}},
"size": 0,
"aggs": {
"by_year": {
"terms": {
"field": "publication_year",
"size": 100
}
}
}
}
try:
res_epo, res_us = await asyncio.gather(
patent_client.search_epo(epo_query),
patent_client.search_uspto(uspto_query)
)
buckets_epo = res_epo.get("aggregations", {}).get("by_year", {}).get("buckets", [])
buckets_us = res_us.get("aggregations", {}).get("by_year", {}).get("buckets", [])
year_counts = {}
for b in buckets_epo:
try:
yr = int(b["key"])
year_counts[yr] = year_counts.get(yr, 0) + int(b["doc_count"])
except Exception:
pass
for b in buckets_us:
try:
yr = int(b["key"])
year_counts[yr] = year_counts.get(yr, 0) + int(b["doc_count"])
except Exception:
pass
for yr, count in year_counts.items():
if yr in years_range:
accumulated_data[entity_key][topic][yr] = (count, 1)
except Exception as e:
logger.error("Failed to query patent trends for %s / %s: %s", entity_key, topic, e)
tasks = []
for entity_key, (entity_type, entity_val) in filters_map.items():
for topic in topics:
symbols = topic_symbols.get(topic, [])
tasks.append(query_patents_trends(entity_key, entity_type, entity_val, topic, symbols))
await asyncio.gather(*tasks)
for inst_id, patents, name in fetched:
if name:
resolved_names[inst_id] = name
for idx, t in enumerate(topics):
keyword = keywords[idx] if keywords and idx < len(keywords) else None
for p in patents:
if matches_patent(p, t, keyword, fuzzy):
try:
yr_val = int(p.publication_year) if p.publication_year else None
if yr_val in years_range:
count, _ = accumulated_data[f"inst_{inst_id}"][t][yr_val]
accumulated_data[f"inst_{inst_id}"][t][yr_val] = (count + 1, 1)
except Exception:
pass
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
series_list = []
for entity_key, topic_dict in accumulated_data.items():
entity_type, entity_val = filters_map[entity_key]
if entity_type == "institution":
entity_id = entity_val
entity_name = resolved_names.get(entity_id, entity_id).split("/")[-1]
elif entity_type == "country":
entity_id = entity_val
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
elif entity_type == "region":
entity_id = entity_key[len("region_"):]
entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}")
for inst_id in query_institutions:
entity_key = f"inst_{inst_id}"
topic_dict = accumulated_data[entity_key]
entity_name = resolved_names.get(inst_id, inst_id).split("/")[-1]
topic_data_map = {}
for topic, year_dict in topic_dict.items():
@@ -874,14 +707,14 @@ class PatentsTrendStrategy(TrendStrategy):
topic_data_map[topic] = yearly_data_items
series_list.append(TrendSeries(
entity_id=entity_id,
entity_id=inst_id,
entity_name=entity_name,
entity_type=entity_type,
country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None,
entity_type="institution",
country_code=None,
topic_data=topic_data_map
))
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
return TrendResponse(series=series_list, years=years_range, location_mappings={})
class ProjectsTrendStrategy(TrendStrategy):