Compare commits
206
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f71a4b56c | ||
|
|
77c7eeef8b | ||
|
|
5b894d8927 | ||
|
|
b352e5288a | ||
|
|
7bbfe1761d | ||
|
|
09cb54109a | ||
|
|
010e1c7f21 | ||
|
|
d1802fa1f8 | ||
|
|
4d0a6db3c3 | ||
|
|
db604feb37 | ||
|
|
cd0e98ec5f | ||
|
|
42685ae44f | ||
|
|
9be024bb13 | ||
|
|
87b7e207e3 | ||
|
|
8eaa9c2420 | ||
|
|
87b02ed0a4 | ||
|
|
a6d30dd897 | ||
|
|
134055b8b9 | ||
|
|
be72d28bda | ||
|
|
2bfb877e77 | ||
|
|
48e33e7fe5 | ||
|
|
f469594c17 | ||
|
|
3e115619a6 | ||
|
|
13b2fb3350 | ||
|
|
d26ddb8cb4 | ||
|
|
a8e582cf23 | ||
|
|
940c050cd7 | ||
|
|
e470b65b5a | ||
|
|
383c77134a | ||
|
|
bb941361a1 | ||
|
|
5d22b201e9 | ||
|
|
1c6dbb540f | ||
|
|
cf9a5df4e9 | ||
|
|
213edf8a5f | ||
|
|
c277fcfece | ||
|
|
8efbbf1f1a | ||
|
|
9ad6d5cd8c | ||
|
|
77540e4002 | ||
|
|
fd3ceb54aa | ||
|
|
7baeab92c2 | ||
|
|
0c526be983 | ||
|
|
53f5440d01 | ||
|
|
e86a19f800 | ||
|
|
61fd920a9f | ||
|
|
7eed7e6614 | ||
|
|
e34e1fe3d5 | ||
|
|
2418821691 | ||
|
|
058c92227a | ||
|
|
bf38147acc | ||
|
|
3f23845c89 | ||
|
|
52e70a5b24 | ||
|
|
d502431102 | ||
|
|
3533b994d0 | ||
|
|
5d22f4831a | ||
|
|
8130192a44 | ||
|
|
bda7aff447 | ||
|
|
82421c1040 | ||
|
|
0723bb5c5b | ||
|
|
e4dbe07436 | ||
|
|
19c6574945 | ||
|
|
0b750d27e7 | ||
|
|
398ea7b56c | ||
|
|
0176eea873 | ||
|
|
b0e8c86743 | ||
|
|
03a2954c72 | ||
|
|
b9d382c78a | ||
|
|
78a8e5d919 | ||
|
|
f9f6a58ad5 | ||
|
|
5cc110174a | ||
|
|
c3ec93fba1 | ||
|
|
169b825195 | ||
|
|
0a3bf72e14 | ||
|
|
eb94fc5942 | ||
|
|
e868c4a47e | ||
|
|
1cf80ae074 | ||
|
|
c74d0b5b87 | ||
|
|
a69f014413 | ||
|
|
cabf819e94 | ||
|
|
c243088752 | ||
|
|
1dd032a66c | ||
|
|
9f03c92bc1 | ||
|
|
86bced4940 | ||
|
|
4461b26270 | ||
|
|
19fd2ac86d | ||
|
|
e9ba874103 | ||
|
|
dfb1413b05 | ||
|
|
b5d03c84c4 | ||
|
|
ef41c0ad96 | ||
|
|
a07fadc30e | ||
|
|
4bf351cf66 | ||
|
|
f55a37867c | ||
|
|
ae42bc46ed | ||
|
|
c38355c817 | ||
|
|
0c004f0cdf | ||
|
|
16c0b399c8 | ||
|
|
3867540a4c | ||
|
|
32cab01a8b | ||
|
|
2b606b8473 | ||
|
|
e0ac41da91 | ||
|
|
86bed62ac0 | ||
|
|
1eaf8f8c8f | ||
|
|
0c3db967b0 | ||
|
|
04eb0f0185 | ||
|
|
b2d965d604 | ||
|
|
0e80cc3fc3 | ||
|
|
92c4edfb4f | ||
|
|
79f2aa0263 | ||
|
|
5878edc4cd | ||
|
|
f4122263dd | ||
|
|
20faff13ec | ||
|
|
73315457a6 | ||
|
|
a464a95c4e | ||
|
|
2264582d1e | ||
|
|
2703f46575 | ||
|
|
e648ea1ec4 | ||
|
|
261f97eee0 | ||
|
|
f4b8d0884c | ||
|
|
1ddc5c42c5 | ||
|
|
47fb41105a | ||
|
|
4394ced772 | ||
|
|
15fc57da51 | ||
|
|
3c910fa0e4 | ||
|
|
8805ec9e57 | ||
|
|
6f498bb754 | ||
|
|
0ea7713f05 | ||
|
|
7b4c459fd8 | ||
|
|
08824bd7ba | ||
|
|
1297f85124 | ||
|
|
7613569711 | ||
|
|
c1cba4bd4c | ||
|
|
d43c406820 | ||
|
|
63db1c9564 | ||
|
|
398df55f50 | ||
|
|
5888a71b36 | ||
|
|
c707064dfb | ||
|
|
8e56b59122 | ||
|
|
cac2d81b5c | ||
|
|
0b9f325045 | ||
|
|
6fa5792e5e | ||
|
|
116492baca | ||
|
|
b1fee136ce | ||
|
|
95ce3a47fc | ||
|
|
d1255deaec | ||
|
|
6dd57bfe2b | ||
|
|
25988d6c46 | ||
|
|
f8228c5ea7 | ||
|
|
f19059164e | ||
|
|
aaab04596d | ||
|
|
6c4688185f | ||
|
|
647eb55a88 | ||
|
|
2603580587 | ||
|
|
42ecebb27f | ||
|
|
f383952547 | ||
|
|
6db4c80258 | ||
|
|
f0173cbf8a | ||
|
|
7bd8659638 | ||
|
|
074e237c84 | ||
|
|
7e8a796623 | ||
|
|
5432d814c6 | ||
|
|
9e5b2c1a21 | ||
|
|
1fa755769b | ||
|
|
cfac12e218 | ||
|
|
2ec9047565 | ||
|
|
b499fd2877 | ||
|
|
e5599845ba | ||
|
|
249fb080e9 | ||
|
|
050c68ea5e | ||
|
|
67d5306c6e | ||
|
|
64ab9325a0 | ||
|
|
1113a6a2be | ||
|
|
3702b216a0 | ||
|
|
dbaabeb9a5 | ||
|
|
195fd2d55b | ||
|
|
5d13b07c73 | ||
|
|
d8aca8ee3e | ||
|
|
495c7d34e5 | ||
|
|
677ef59440 | ||
|
|
c259635bdf | ||
|
|
39fdb23942 | ||
|
|
0d2c7f93be | ||
|
|
7c68a5cd71 | ||
|
|
17931a82b0 | ||
|
|
0502a9a553 | ||
|
|
4b8256b56e | ||
|
|
095a4c8bac | ||
|
|
473bc96e90 | ||
|
|
642fda7542 | ||
|
|
1fdd5339fa | ||
|
|
b69fe4e15c | ||
|
|
873e4bbbec | ||
|
|
0817640449 | ||
|
|
569d73aa9f | ||
|
|
0873d25345 | ||
|
|
6c13415b1e | ||
|
|
56015846b0 | ||
|
|
7602fef243 | ||
|
|
81539d5dbd | ||
|
|
f5991ef660 | ||
|
|
6fc491fd87 | ||
|
|
f2cf83f63b | ||
|
|
512356e106 | ||
|
|
309fecf008 | ||
|
|
163fdfaa39 | ||
|
|
29c954227f | ||
|
|
1f70f9fe2d | ||
|
|
e37de88cc8 |
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
|
|||||||
"news_id": entry["news_id"],
|
"news_id": entry["news_id"],
|
||||||
"relevant": int(entry["relevant"]),
|
"relevant": int(entry["relevant"]),
|
||||||
"authors": entry["authors"],
|
"authors": entry["authors"],
|
||||||
|
"keywords": entry.get("keywords", []),
|
||||||
}
|
}
|
||||||
|
|
||||||
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
response_data = _send_es_request("POST", endpoint, payload=document_body)
|
||||||
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
|
|||||||
|
|
||||||
return created_id
|
return created_id
|
||||||
|
|
||||||
|
def update_entry(index: str, document_id: str, partial_doc: dict):
|
||||||
|
|
||||||
|
encoded_document_id = quote(document_id, safe="")
|
||||||
|
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
|
||||||
|
|
||||||
|
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
|
||||||
|
|
||||||
def get_entry(index: str, document_id: str) -> dict:
|
def get_entry(index: str, document_id: str) -> dict:
|
||||||
|
|
||||||
encoded_document_id = quote(document_id, safe="")
|
encoded_document_id = quote(document_id, safe="")
|
||||||
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
|
|||||||
"query": {"match_all": {}}
|
"query": {"match_all": {}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return _send_es_request("POST", endpoint, payload=payload)
|
||||||
|
|
||||||
|
def remove_field_all(index: str, field: str):
|
||||||
|
|
||||||
|
endpoint = f"{INSE_URL}/{index}/_update_by_query"
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"query": {"exists": {"field": field}},
|
||||||
|
"script": {
|
||||||
|
"source": f"ctx._source.remove('{field}')",
|
||||||
|
"lang": "painless",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
return _send_es_request("POST", endpoint, payload=payload)
|
return _send_es_request("POST", endpoint, payload=payload)
|
||||||
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
|
|||||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||||
|
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||||
|
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||||
|
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||||
|
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||||
|
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||||
|
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||||
|
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||||
|
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||||
|
""")
|
||||||
|
|
||||||
_client = OpenAI(
|
_client = OpenAI(
|
||||||
base_url=LLM_BASE_URL,
|
base_url=LLM_BASE_URL,
|
||||||
api_key=LLM_API_KEY,
|
api_key=LLM_API_KEY,
|
||||||
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
|
|||||||
return data.get("person", [])
|
return data.get("person", [])
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
def extract_keywords(text: str) -> list[str]:
|
||||||
|
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||||
|
if result is None:
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
data = json.loads(result)
|
||||||
|
return data.get("keywords", [])
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return []
|
||||||
|
|||||||
@@ -16,10 +16,12 @@ def sync_single_news(news_id, max_retries=3):
|
|||||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||||
authors = llm_client.extract_names(news_text)
|
authors = llm_client.extract_names(news_text)
|
||||||
|
keywords = llm_client.extract_keywords(news_text)
|
||||||
new_entry = {
|
new_entry = {
|
||||||
"news_id": news_id,
|
"news_id": news_id,
|
||||||
"relevant": is_news_relevant,
|
"relevant": is_news_relevant,
|
||||||
"authors": authors,
|
"authors": authors,
|
||||||
|
"keywords": keywords,
|
||||||
}
|
}
|
||||||
es_client.add_entry("aktuell_postproc", new_entry)
|
es_client.add_entry("aktuell_postproc", new_entry)
|
||||||
return True
|
return True
|
||||||
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
|
|||||||
print(f"Error: {news_id} - {error}")
|
print(f"Error: {news_id} - {error}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def update_keywords_single(postproc_entry, max_retries=3):
|
||||||
|
doc_id = postproc_entry["_id"]
|
||||||
|
news_id = postproc_entry["_source"]["news_id"]
|
||||||
|
attempt = 0
|
||||||
|
while attempt < max_retries:
|
||||||
|
try:
|
||||||
|
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||||
|
keywords = llm_client.extract_keywords(news_text)
|
||||||
|
es_client.update_entry("aktuell_postproc", doc_id, {"keywords": keywords})
|
||||||
|
return True
|
||||||
|
except Exception as error:
|
||||||
|
attempt += 1
|
||||||
|
print(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
|
||||||
|
if attempt < max_retries:
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
print(f"Error: {news_id} - {error}")
|
||||||
|
return False
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
|
||||||
|
|
||||||
@@ -47,6 +68,18 @@ def main():
|
|||||||
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--update-keywords",
|
||||||
|
action="store_true",
|
||||||
|
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--reset-keywords",
|
||||||
|
action="store_true",
|
||||||
|
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
|
||||||
|
)
|
||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--stats",
|
"--stats",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -60,11 +93,22 @@ def main():
|
|||||||
help="Number of threads for --sync-delta (Default: 4).",
|
help="Number of threads for --sync-delta (Default: 4).",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--limit",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.delete_all:
|
if args.delete_all:
|
||||||
es_client.delete_all_entries("aktuell_postproc")
|
es_client.delete_all_entries("aktuell_postproc")
|
||||||
|
|
||||||
|
if args.reset_keywords:
|
||||||
|
result = es_client.remove_field_all("aktuell_postproc", "keywords")
|
||||||
|
print(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
|
||||||
|
|
||||||
if args.sync_delta:
|
if args.sync_delta:
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||||
@@ -96,23 +140,58 @@ def main():
|
|||||||
end_time = time.time()
|
end_time = time.time()
|
||||||
print(f"Sync DONE: {succeeded} entries synced.")
|
print(f"Sync DONE: {succeeded} entries synced.")
|
||||||
print(f"Time taken: {end_time - start_time} seconds.")
|
print(f"Time taken: {end_time - start_time} seconds.")
|
||||||
|
|
||||||
|
if args.update_keywords:
|
||||||
|
start_time = time.time()
|
||||||
|
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["news_id", "keywords"])
|
||||||
|
|
||||||
|
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
|
||||||
|
print(f"Number of entries without keywords: {len(pending)}")
|
||||||
|
|
||||||
|
if args.limit is not None:
|
||||||
|
pending = pending[:args.limit]
|
||||||
|
|
||||||
|
total = len(pending)
|
||||||
|
print(f"Processing {total} entries.")
|
||||||
|
|
||||||
|
processed = 0
|
||||||
|
succeeded = 0
|
||||||
|
progress_lock = threading.Lock()
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||||
|
futures = [executor.submit(update_keywords_single, entry) for entry in pending]
|
||||||
|
for future in as_completed(futures):
|
||||||
|
was_successful = future.result()
|
||||||
|
with progress_lock:
|
||||||
|
processed += 1
|
||||||
|
if was_successful:
|
||||||
|
succeeded += 1
|
||||||
|
print(f"Update keywords: {processed} / {total}")
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
print(f"Update keywords DONE: {succeeded} entries updated.")
|
||||||
|
print(f"Time taken: {end_time - start_time} seconds.")
|
||||||
|
|
||||||
if args.stats:
|
if args.stats:
|
||||||
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
|
||||||
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
print(f"Total entries in 'aktuell': {len(aktuell_entries)}")
|
||||||
|
|
||||||
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors"])
|
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
|
||||||
total_entries = len(postproc_entries)
|
total_entries = len(postproc_entries)
|
||||||
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
|
||||||
irrelevant_count = total_entries - relevant_count
|
irrelevant_count = total_entries - relevant_count
|
||||||
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
|
||||||
news_without_extracted_names = total_entries - news_with_extracted_names
|
news_without_extracted_names = total_entries - news_with_extracted_names
|
||||||
|
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
|
||||||
|
news_without_keywords = total_entries - news_with_keywords
|
||||||
|
|
||||||
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
print(f"Total entries in 'aktuell_postproc': {total_entries}")
|
||||||
print(f"Relevant entries: {relevant_count}")
|
print(f"Relevant entries: {relevant_count}")
|
||||||
print(f"Irrelevant entries: {irrelevant_count}")
|
print(f"Irrelevant entries: {irrelevant_count}")
|
||||||
print(f"Entries with extracted names: {news_with_extracted_names}")
|
print(f"Entries with extracted names: {news_with_extracted_names}")
|
||||||
print(f"Entries without extracted names: {news_without_extracted_names}")
|
print(f"Entries without extracted names: {news_without_extracted_names}")
|
||||||
|
print(f"Entries with keywords: {news_with_keywords}")
|
||||||
|
print(f"Entries without keywords: {news_without_keywords}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
File diff suppressed because one or more lines are too long
+4
-1
@@ -12,8 +12,11 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
|||||||
"uvicorn~=0.29.0" \
|
"uvicorn~=0.29.0" \
|
||||||
"pytest~=8.1.0" \
|
"pytest~=8.1.0" \
|
||||||
"httpx~=0.27.0" \
|
"httpx~=0.27.0" \
|
||||||
"python-multipart~=0.0.19"\
|
"python-multipart~=0.0.19" \
|
||||||
|
"beautifulsoup4==4.12.3" \
|
||||||
"openai~=2.41.0" \
|
"openai~=2.41.0" \
|
||||||
|
"websockets==12.0" \
|
||||||
|
"partial-json-parser==0.2.1.1.post7" \
|
||||||
"sqlmodel~=0.0.33" \
|
"sqlmodel~=0.0.33" \
|
||||||
"argon2-cffi~=25.1.0"
|
"argon2-cffi~=25.1.0"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Index org_patents for an institution."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
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(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||||
|
|
||||||
|
from inse.patents.org.logic import index_org_patents_for_institution
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Index org_patents for an institution.")
|
||||||
|
parser.add_argument(
|
||||||
|
"--institution-id",
|
||||||
|
required=True,
|
||||||
|
help="OpenAlex institution ID, e.g. I62318514",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
count = await index_org_patents_for_institution(args.institution_id)
|
||||||
|
logger.info("Finished indexing %d patents for institution %s", count, args.institution_id)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -20,6 +20,7 @@ class AccountProfile(BaseModel):
|
|||||||
organization_id: uuid.UUID
|
organization_id: uuid.UUID
|
||||||
organization_name: str
|
organization_name: str
|
||||||
deleted: bool
|
deleted: bool
|
||||||
|
activated: bool
|
||||||
is_current: bool = False
|
is_current: bool = False
|
||||||
is_real_account: bool = False
|
is_real_account: bool = False
|
||||||
is_impersonating: bool = False
|
is_impersonating: bool = False
|
||||||
@@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel):
|
|||||||
password: Optional[str] = Field(default=None, min_length=8)
|
password: Optional[str] = Field(default=None, min_length=8)
|
||||||
openalex_person_id: Optional[str] = None
|
openalex_person_id: Optional[str] = None
|
||||||
deleted: Optional[bool] = None
|
deleted: Optional[bool] = None
|
||||||
|
activated: Optional[bool] = None
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from typing import Optional
|
from typing import Annotated, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Query, Response, status
|
from fastapi import APIRouter, Query, Response, status
|
||||||
from sqlmodel import Session
|
|
||||||
|
|
||||||
from inse.auth import service as auth_service
|
from inse.auth import service as auth_service
|
||||||
from inse.auth.model import AccessToken
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.database import get_session
|
from inse.database import SessionDep
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
|
|
||||||
from . import service
|
from . import service
|
||||||
@@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
|
|||||||
@router.get(
|
@router.get(
|
||||||
"/me",
|
"/me",
|
||||||
operation_id="getCurrentAccount",
|
operation_id="getCurrentAccount",
|
||||||
response_model=AccountProfile,
|
|
||||||
)
|
)
|
||||||
async def get_current_account(
|
async def get_current_account(
|
||||||
session: Session = Depends(get_session),
|
session: SessionDep,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> AccountProfile:
|
) -> AccountProfile:
|
||||||
return service.get_current_account(session=session, access_token=access_token)
|
return service.get_current_account(session=session, access_token=access_token)
|
||||||
|
|
||||||
@@ -36,16 +34,15 @@ async def get_current_account(
|
|||||||
@router.get(
|
@router.get(
|
||||||
"",
|
"",
|
||||||
operation_id="listAccounts",
|
operation_id="listAccounts",
|
||||||
response_model=AccountPage,
|
|
||||||
)
|
)
|
||||||
async def list_accounts(
|
async def list_accounts(
|
||||||
page: int = Query(default=0, ge=0),
|
session: SessionDep,
|
||||||
page_size: int = Query(default=25, ge=1, le=100),
|
page: Annotated[int, Query(ge=0)] = 0,
|
||||||
offset: Optional[int] = Query(default=None, ge=0),
|
page_size: Annotated[int, Query(ge=1, le=100)] = 10,
|
||||||
search: Optional[str] = Query(default=None),
|
offset: Annotated[int, Query(ge=0)] = 0,
|
||||||
organization_id: Optional[uuid.UUID] = Query(default=None),
|
search: Annotated[Optional[str], Query()] = None,
|
||||||
session: Session = Depends(get_session),
|
organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> AccountPage:
|
) -> AccountPage:
|
||||||
return service.list_accounts(
|
return service.list_accounts(
|
||||||
session=session,
|
session=session,
|
||||||
@@ -61,13 +58,12 @@ async def list_accounts(
|
|||||||
@router.post(
|
@router.post(
|
||||||
"",
|
"",
|
||||||
operation_id="createAccount",
|
operation_id="createAccount",
|
||||||
response_model=AccountProfile,
|
|
||||||
status_code=status.HTTP_201_CREATED,
|
status_code=status.HTTP_201_CREATED,
|
||||||
)
|
)
|
||||||
async def create_account(
|
async def create_account(
|
||||||
payload: CreateAccountRequest,
|
payload: CreateAccountRequest,
|
||||||
session: Session = Depends(get_session),
|
session: SessionDep,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> AccountProfile:
|
) -> AccountProfile:
|
||||||
return service.create_account(
|
return service.create_account(
|
||||||
session=session,
|
session=session,
|
||||||
@@ -79,11 +75,10 @@ async def create_account(
|
|||||||
@router.get(
|
@router.get(
|
||||||
"/organizations",
|
"/organizations",
|
||||||
operation_id="listAccountOrganizations",
|
operation_id="listAccountOrganizations",
|
||||||
response_model=list[OrganizationProfile],
|
|
||||||
)
|
)
|
||||||
async def list_organizations(
|
async def list_organizations(
|
||||||
session: Session = Depends(get_session),
|
session: SessionDep,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> list[OrganizationProfile]:
|
) -> list[OrganizationProfile]:
|
||||||
return service.list_organizations(session=session, access_token=access_token)
|
return service.list_organizations(session=session, access_token=access_token)
|
||||||
|
|
||||||
@@ -91,13 +86,12 @@ async def list_organizations(
|
|||||||
@router.put(
|
@router.put(
|
||||||
"/{account_id}",
|
"/{account_id}",
|
||||||
operation_id="updateAccount",
|
operation_id="updateAccount",
|
||||||
response_model=AccountProfile,
|
|
||||||
)
|
)
|
||||||
async def update_account(
|
async def update_account(
|
||||||
account_id: uuid.UUID,
|
account_id: uuid.UUID,
|
||||||
payload: UpdateAccountRequest,
|
payload: UpdateAccountRequest,
|
||||||
session: Session = Depends(get_session),
|
session: SessionDep,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> AccountProfile:
|
) -> AccountProfile:
|
||||||
return service.update_account(
|
return service.update_account(
|
||||||
session=session,
|
session=session,
|
||||||
@@ -114,8 +108,8 @@ async def update_account(
|
|||||||
)
|
)
|
||||||
async def delete_account(
|
async def delete_account(
|
||||||
account_id: uuid.UUID,
|
account_id: uuid.UUID,
|
||||||
session: Session = Depends(get_session),
|
session: SessionDep,
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> Response:
|
) -> Response:
|
||||||
service.delete_account(
|
service.delete_account(
|
||||||
session=session,
|
session=session,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from fastapi import HTTPException, status
|
|||||||
from sqlmodel import Session, func, or_, select
|
from sqlmodel import Session, func, or_, select
|
||||||
|
|
||||||
from inse.auth import service as auth_service
|
from inse.auth import service as auth_service
|
||||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||||
|
|
||||||
from .model import (
|
from .model import (
|
||||||
AccountPage,
|
AccountPage,
|
||||||
@@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
|
||||||
organization_name = account.organization.name if account.organization else ""
|
organization_name = account.organization.name if account.organization else ""
|
||||||
return AccountProfile(
|
return AccountProfile(
|
||||||
id=account.id,
|
id=account.id,
|
||||||
@@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
|||||||
organization_id=account.organization_id,
|
organization_id=account.organization_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
deleted=account.deleted,
|
deleted=account.deleted,
|
||||||
|
activated=account.activated,
|
||||||
is_current=account.id == token.effective_account_id,
|
is_current=account.id == token.effective_account_id,
|
||||||
is_real_account=account.id == token.real_account_id,
|
is_real_account=account.id == token.real_account_id,
|
||||||
is_impersonating=token.is_impersonating(),
|
is_impersonating=token.is_impersonating(),
|
||||||
@@ -54,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
|
|||||||
return account
|
return account
|
||||||
|
|
||||||
|
|
||||||
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
|
def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata) -> None:
|
||||||
if token.effective_role == UserRole.SUPER_ADMIN:
|
if token.effective_role == UserRole.SUPER_ADMIN:
|
||||||
return
|
return
|
||||||
if (
|
if (
|
||||||
@@ -94,31 +95,35 @@ def _ensure_email_available(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile:
|
def get_current_account(session: Session, access_token: AccessTokenMetadata) -> AccountProfile:
|
||||||
account = _get_account_or_404(session, access_token.effective_account_id)
|
account = _get_account_or_404(session, access_token.effective_account_id)
|
||||||
return _account_to_profile(account, access_token)
|
return _account_to_profile(account, access_token)
|
||||||
|
|
||||||
|
|
||||||
def list_accounts(
|
def list_accounts(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
page: int,
|
page: int,
|
||||||
page_size: int,
|
page_size: int,
|
||||||
offset: Optional[int] = None,
|
offset: Optional[int] = None,
|
||||||
search: Optional[str] = None,
|
search: Optional[str] = None,
|
||||||
organization_id: Optional[uuid.UUID] = None,
|
organization_id: Optional[uuid.UUID] = None,
|
||||||
) -> AccountPage:
|
) -> AccountPage:
|
||||||
if not _is_admin(access_token.effective_role):
|
if access_token.effective_role not in {
|
||||||
|
UserRole.SUPER_ADMIN,
|
||||||
|
UserRole.ADMIN,
|
||||||
|
UserRole.MANAGER,
|
||||||
|
}:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
detail="Only admins can list accounts.",
|
detail="Only managers and admins can list accounts.",
|
||||||
)
|
)
|
||||||
|
|
||||||
statement = select(Account)
|
statement = select(Account)
|
||||||
count_statement = select(func.count()).select_from(Account)
|
count_statement = select(func.count()).select_from(Account)
|
||||||
|
|
||||||
filters = []
|
filters = []
|
||||||
if access_token.effective_role == UserRole.ADMIN:
|
if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}:
|
||||||
filters.append(Account.organization_id == access_token.effective_organization_id)
|
filters.append(Account.organization_id == access_token.effective_organization_id)
|
||||||
elif organization_id is not None:
|
elif organization_id is not None:
|
||||||
filters.append(Account.organization_id == organization_id)
|
filters.append(Account.organization_id == organization_id)
|
||||||
@@ -152,7 +157,7 @@ def list_accounts(
|
|||||||
|
|
||||||
def create_account(
|
def create_account(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
payload: CreateAccountRequest,
|
payload: CreateAccountRequest,
|
||||||
) -> AccountProfile:
|
) -> AccountProfile:
|
||||||
if not _is_admin(access_token.effective_role):
|
if not _is_admin(access_token.effective_role):
|
||||||
@@ -202,12 +207,12 @@ def create_account(
|
|||||||
|
|
||||||
def list_organizations(
|
def list_organizations(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
) -> list[OrganizationProfile]:
|
) -> list[OrganizationProfile]:
|
||||||
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
||||||
organizations = session.exec(
|
organizations = session.exec(
|
||||||
select(Organization)
|
select(Organization)
|
||||||
.where(Organization.deleted == False) # noqa: E712
|
.where(Organization.deleted.is_not(True))
|
||||||
.order_by(Organization.name)
|
.order_by(Organization.name)
|
||||||
).all()
|
).all()
|
||||||
elif access_token.effective_role == UserRole.ADMIN:
|
elif access_token.effective_role == UserRole.ADMIN:
|
||||||
@@ -228,7 +233,7 @@ def list_organizations(
|
|||||||
|
|
||||||
def update_account(
|
def update_account(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
account_id: uuid.UUID,
|
account_id: uuid.UUID,
|
||||||
payload: UpdateAccountRequest,
|
payload: UpdateAccountRequest,
|
||||||
) -> AccountProfile:
|
) -> AccountProfile:
|
||||||
@@ -285,6 +290,15 @@ def update_account(
|
|||||||
account.deleted = payload.deleted
|
account.deleted = payload.deleted
|
||||||
account.epoch += 1
|
account.epoch += 1
|
||||||
|
|
||||||
|
if payload.activated is not None and payload.activated != account.activated:
|
||||||
|
if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Only super admins can activate or deactivate other accounts.",
|
||||||
|
)
|
||||||
|
account.activated = payload.activated
|
||||||
|
account.epoch += 1
|
||||||
|
|
||||||
session.add(account)
|
session.add(account)
|
||||||
session.commit()
|
session.commit()
|
||||||
session.refresh(account)
|
session.refresh(account)
|
||||||
@@ -293,7 +307,7 @@ def update_account(
|
|||||||
|
|
||||||
def delete_account(
|
def delete_account(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
account_id: uuid.UUID,
|
account_id: uuid.UUID,
|
||||||
) -> None:
|
) -> None:
|
||||||
account = _get_account_or_404(session, account_id)
|
account = _get_account_or_404(session, account_id)
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from sqlmodel import Session, SQLModel, create_engine
|
||||||
|
|
||||||
|
from inse.account_management import service
|
||||||
|
from inse.account_management.model import UpdateAccountRequest
|
||||||
|
from inse.auth.model import Account, Organization, UserRole
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def session():
|
||||||
|
engine = create_engine(
|
||||||
|
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
SQLModel.metadata.create_all(engine)
|
||||||
|
with Session(engine) as database_session:
|
||||||
|
yield database_session
|
||||||
|
|
||||||
|
|
||||||
|
def access_token(role, account_id, organization_id):
|
||||||
|
return SimpleNamespace(
|
||||||
|
effective_role=role,
|
||||||
|
effective_account_id=account_id,
|
||||||
|
real_account_id=account_id,
|
||||||
|
effective_organization_id=organization_id,
|
||||||
|
is_impersonating=lambda: False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_accounts(session):
|
||||||
|
organization = Organization(name="Test organization")
|
||||||
|
session.add(organization)
|
||||||
|
session.flush()
|
||||||
|
superadmin = Account(
|
||||||
|
email="superadmin@example.org",
|
||||||
|
name="Superadmin",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
role=UserRole.SUPER_ADMIN,
|
||||||
|
)
|
||||||
|
user = Account(
|
||||||
|
email="user@example.org",
|
||||||
|
name="User",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
)
|
||||||
|
session.add(superadmin)
|
||||||
|
session.add(user)
|
||||||
|
session.commit()
|
||||||
|
return organization, superadmin, user
|
||||||
|
|
||||||
|
|
||||||
|
def test_accounts_are_activated_by_default(session):
|
||||||
|
_, _, user = create_accounts(session)
|
||||||
|
assert user.activated is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_superadmin_can_deactivate_and_reactivate_account(session):
|
||||||
|
organization, superadmin, user = create_accounts(session)
|
||||||
|
token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id)
|
||||||
|
|
||||||
|
profile = service.update_account(
|
||||||
|
session, token, user.id, UpdateAccountRequest(activated=False)
|
||||||
|
)
|
||||||
|
assert profile.activated is False
|
||||||
|
assert user.epoch == 1
|
||||||
|
|
||||||
|
profile = service.update_account(
|
||||||
|
session, token, user.id, UpdateAccountRequest(activated=True)
|
||||||
|
)
|
||||||
|
assert profile.activated is True
|
||||||
|
assert user.epoch == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_non_superadmin_cannot_change_activation(session):
|
||||||
|
organization, superadmin, user = create_accounts(session)
|
||||||
|
admin = Account(
|
||||||
|
email="admin@example.org",
|
||||||
|
name="Admin",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
role=UserRole.ADMIN,
|
||||||
|
)
|
||||||
|
session.add(admin)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
service.update_account(
|
||||||
|
session,
|
||||||
|
access_token(UserRole.ADMIN, admin.id, organization.id),
|
||||||
|
user.id,
|
||||||
|
UpdateAccountRequest(activated=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert error.value.status_code == 403
|
||||||
|
assert user.activated is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_superadmin_cannot_deactivate_own_account(session):
|
||||||
|
organization, superadmin, _ = create_accounts(session)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
service.update_account(
|
||||||
|
session,
|
||||||
|
access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id),
|
||||||
|
superadmin.id,
|
||||||
|
UpdateAccountRequest(activated=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert error.value.status_code == 403
|
||||||
|
assert superadmin.activated is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_manager_only_lists_accounts_from_own_organization(session):
|
||||||
|
organization, superadmin, user = create_accounts(session)
|
||||||
|
manager = Account(
|
||||||
|
email="manager@example.org",
|
||||||
|
name="Manager",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
role=UserRole.MANAGER,
|
||||||
|
)
|
||||||
|
other_organization = Organization(name="Other organization")
|
||||||
|
session.add(other_organization)
|
||||||
|
session.flush()
|
||||||
|
other_user = Account(
|
||||||
|
email="other@example.org",
|
||||||
|
name="Other User",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=other_organization.id,
|
||||||
|
)
|
||||||
|
session.add(manager)
|
||||||
|
session.add(other_user)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
result = service.list_accounts(
|
||||||
|
session,
|
||||||
|
access_token(UserRole.MANAGER, manager.id, organization.id),
|
||||||
|
page=0,
|
||||||
|
page_size=25,
|
||||||
|
organization_id=other_organization.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert {profile.id for profile in result.items} == {
|
||||||
|
account.id for account in [superadmin, user, manager]
|
||||||
|
}
|
||||||
|
assert other_user.id not in {profile.id for profile in result.items}
|
||||||
|
|
||||||
|
|
||||||
|
def test_user_cannot_list_accounts(session):
|
||||||
|
organization, _, user = create_accounts(session)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
service.list_accounts(
|
||||||
|
session,
|
||||||
|
access_token(UserRole.USER, user.id, organization.id),
|
||||||
|
page=0,
|
||||||
|
page_size=25,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert error.value.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_superadmin_lists_all_active_organizations_for_selectbox(session):
|
||||||
|
first = Organization(name="Alpha")
|
||||||
|
second = Organization(name="Beta")
|
||||||
|
deleted = Organization(name="Deleted", deleted=True)
|
||||||
|
session.add(first)
|
||||||
|
session.add(second)
|
||||||
|
session.add(deleted)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
organizations = service.list_organizations(
|
||||||
|
session,
|
||||||
|
access_token(UserRole.SUPER_ADMIN, first.id, first.id),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert [organization.name for organization in organizations] == ["Alpha", "Beta"]
|
||||||
@@ -4,6 +4,7 @@ from enum import StrEnum
|
|||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy import UniqueConstraint
|
||||||
from sqlmodel import Field, Relationship, SQLModel
|
from sqlmodel import Field, Relationship, SQLModel
|
||||||
|
|
||||||
|
|
||||||
@@ -15,9 +16,14 @@ class UserRole(StrEnum):
|
|||||||
|
|
||||||
|
|
||||||
class TokenType(StrEnum):
|
class TokenType(StrEnum):
|
||||||
ID_TOKEN = "ID"
|
ID_TOKEN = "ID_TOKEN"
|
||||||
REFRESH_TOKEN = "REFRESH"
|
REFRESH_TOKEN = "REFRESH_TOKEN"
|
||||||
ACCESS_TOKEN = "ACCESS"
|
ACCESS_TOKEN = "ACCESS_TOKEN"
|
||||||
|
|
||||||
|
|
||||||
|
class SecretPurpose(StrEnum):
|
||||||
|
LOGIN_OTK = "LOGIN_OTK"
|
||||||
|
PASSWORD_RESET = "PASSWORD_RESET"
|
||||||
|
|
||||||
|
|
||||||
class Durable(SQLModel):
|
class Durable(SQLModel):
|
||||||
@@ -77,6 +83,12 @@ class Account(Durable, table=True):
|
|||||||
nullable=False,
|
nullable=False,
|
||||||
description="The epoch value for the account. Used for versioning of tokens.",
|
description="The epoch value for the account. Used for versioning of tokens.",
|
||||||
)
|
)
|
||||||
|
activated: bool = Field(
|
||||||
|
default=True,
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
description="Indicates whether the account is allowed to authenticate.",
|
||||||
|
)
|
||||||
password_hash: str = Field(
|
password_hash: str = Field(
|
||||||
index=False,
|
index=False,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
@@ -100,6 +112,9 @@ class Account(Durable, table=True):
|
|||||||
|
|
||||||
|
|
||||||
class Secret(SQLModel, table=True):
|
class Secret(SQLModel, table=True):
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
|
||||||
|
)
|
||||||
id: uuid.UUID | None = Field(
|
id: uuid.UUID | None = Field(
|
||||||
default_factory=uuid.uuid4,
|
default_factory=uuid.uuid4,
|
||||||
primary_key=True,
|
primary_key=True,
|
||||||
@@ -107,10 +122,16 @@ class Secret(SQLModel, table=True):
|
|||||||
)
|
)
|
||||||
account_id: uuid.UUID = Field(
|
account_id: uuid.UUID = Field(
|
||||||
foreign_key="account.id",
|
foreign_key="account.id",
|
||||||
unique=True, # Ensure that each account can have only one associated secret
|
index=True,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
description="The unique identifier of the account associated with this secret.",
|
description="The unique identifier of the account associated with this secret.",
|
||||||
)
|
)
|
||||||
|
purpose: SecretPurpose = Field(
|
||||||
|
default=SecretPurpose.LOGIN_OTK,
|
||||||
|
index=True,
|
||||||
|
nullable=False,
|
||||||
|
description="The purpose of the secret, such as login OTK or password reset.",
|
||||||
|
)
|
||||||
secret_value: str = Field(
|
secret_value: str = Field(
|
||||||
index=False,
|
index=False,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
@@ -121,39 +142,32 @@ class Secret(SQLModel, table=True):
|
|||||||
nullable=False,
|
nullable=False,
|
||||||
description="The timestamp indicating when the secret will expire.",
|
description="The timestamp indicating when the secret will expire.",
|
||||||
)
|
)
|
||||||
|
request_count: int = Field(
|
||||||
|
default=0,
|
||||||
class Token(BaseModel):
|
|
||||||
token_type: TokenType = Field(
|
|
||||||
description="The type of the token (ID, Refresh, or Access).",
|
|
||||||
)
|
|
||||||
real_account_id: uuid.UUID = Field(
|
|
||||||
nullable=False,
|
nullable=False,
|
||||||
|
description="The number of password reset requests in the current rate-limit window.",
|
||||||
|
)
|
||||||
|
request_window_started_at: datetime | None = Field(
|
||||||
|
default=None,
|
||||||
|
index=True,
|
||||||
|
description="The start timestamp of the current password reset request window.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class BaseTokenData(BaseModel):
|
||||||
|
real_account_id: uuid.UUID = Field(
|
||||||
description="The unique identifier of the real account associated with this token.",
|
description="The unique identifier of the real account associated with this token.",
|
||||||
)
|
)
|
||||||
expires_at: datetime = Field(
|
expires_at: datetime = Field(
|
||||||
index=True,
|
|
||||||
nullable=False,
|
|
||||||
description="The timestamp indicating when the token will expire.",
|
description="The timestamp indicating when the token will expire.",
|
||||||
)
|
)
|
||||||
epoch: int = Field(
|
epoch: int = Field(
|
||||||
default=0,
|
default=0,
|
||||||
nullable=False,
|
|
||||||
description="The epoch value for the token. Used for versioning of tokens.",
|
description="The epoch value for the token. Used for versioning of tokens.",
|
||||||
)
|
)
|
||||||
user_fingerprint_hash: str = Field(
|
|
||||||
index=True,
|
|
||||||
nullable=False,
|
|
||||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
|
||||||
)
|
|
||||||
raw_token: str = Field(
|
|
||||||
index=False,
|
|
||||||
nullable=False,
|
|
||||||
description="The raw token string.",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class IdToken(Token):
|
class IdTokenMetadata(BaseTokenData):
|
||||||
token_type: TokenType = Field(
|
token_type: TokenType = Field(
|
||||||
default=TokenType.ID_TOKEN,
|
default=TokenType.ID_TOKEN,
|
||||||
const=True,
|
const=True,
|
||||||
@@ -161,24 +175,23 @@ class IdToken(Token):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class AccessToken(Token):
|
class AccessTokenMetadata(BaseTokenData):
|
||||||
token_type: TokenType = Field(
|
token_type: TokenType = Field(
|
||||||
default=TokenType.ACCESS_TOKEN,
|
default=TokenType.ACCESS_TOKEN,
|
||||||
const=True,
|
const=True,
|
||||||
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||||
)
|
)
|
||||||
|
user_fingerprint_hash: str = Field(
|
||||||
|
description="A unique fingerprint of the user, used for additional security checks.",
|
||||||
|
)
|
||||||
effective_account_id: uuid.UUID = Field(
|
effective_account_id: uuid.UUID = Field(
|
||||||
nullable=False,
|
|
||||||
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||||
)
|
)
|
||||||
effective_role: UserRole = Field(
|
effective_role: UserRole = Field(
|
||||||
default=UserRole.USER,
|
default=UserRole.USER,
|
||||||
index=True,
|
|
||||||
nullable=False,
|
|
||||||
description="The specific role this access token grants within its organization.",
|
description="The specific role this access token grants within its organization.",
|
||||||
)
|
)
|
||||||
effective_organization_id: uuid.UUID = Field(
|
effective_organization_id: uuid.UUID = Field(
|
||||||
nullable=False,
|
|
||||||
description="The unique identifier of the organization associated with this access token.",
|
description="The unique identifier of the organization associated with this access token.",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -191,22 +204,50 @@ class AccessToken(Token):
|
|||||||
return self.effective_account_id != self.real_account_id
|
return self.effective_account_id != self.real_account_id
|
||||||
|
|
||||||
|
|
||||||
class RefreshToken(AccessToken):
|
class AccessToken(AccessTokenMetadata):
|
||||||
|
raw_token: str = Field(
|
||||||
|
description="The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshTokenMetadata(BaseTokenData):
|
||||||
token_type: TokenType = Field(
|
token_type: TokenType = Field(
|
||||||
default=TokenType.REFRESH_TOKEN,
|
default=TokenType.REFRESH_TOKEN,
|
||||||
const=True,
|
const=True,
|
||||||
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||||
)
|
)
|
||||||
|
effective_account_id: uuid.UUID = Field(
|
||||||
|
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||||
|
)
|
||||||
|
effective_role: UserRole = Field(
|
||||||
|
default=UserRole.USER,
|
||||||
|
description="The specific role this access token grants within its organization.",
|
||||||
|
)
|
||||||
|
effective_organization_id: uuid.UUID = Field(
|
||||||
|
description="The unique identifier of the organization associated with this access token.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshToken(RefreshTokenMetadata):
|
||||||
|
raw_token: str = Field(
|
||||||
|
description="The raw string representation of the refresh token. This is the actual token that can be used to obtain new access tokens.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class LoginResponse(BaseModel):
|
class LoginResponse(BaseModel):
|
||||||
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
id_token: IdTokenMetadata = Field(
|
||||||
|
description="The ID token issued upon successful login."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class AccessResponse(BaseModel):
|
class AccessResponse(BaseModel):
|
||||||
access_token: AccessToken = Field(
|
access_token: AccessToken = Field(
|
||||||
description="The access token issued upon successful authentication."
|
description="The access token issued upon successful authentication."
|
||||||
)
|
)
|
||||||
refresh_token: RefreshToken = Field(
|
|
||||||
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
|
||||||
|
class OtkResponse(BaseModel):
|
||||||
|
status: str = Field(description="The status of the one-time code (OTC) request.")
|
||||||
|
account_id: uuid.UUID = Field(
|
||||||
|
description="The unique identifier of the account for which the OTC was requested."
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,9 +12,11 @@ from inse.database import SessionDep, get_session
|
|||||||
from inse.auth.model import (
|
from inse.auth.model import (
|
||||||
AccessResponse,
|
AccessResponse,
|
||||||
AccessToken,
|
AccessToken,
|
||||||
IdToken,
|
AccessTokenMetadata,
|
||||||
|
IdTokenMetadata,
|
||||||
LoginResponse,
|
LoginResponse,
|
||||||
RefreshToken,
|
OtkResponse,
|
||||||
|
RefreshTokenMetadata,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -40,10 +42,50 @@ async def request_otk(
|
|||||||
session: SessionDep,
|
session: SessionDep,
|
||||||
email: Annotated[str, Body(description="User's email address")],
|
email: Annotated[str, Body(description="User's email address")],
|
||||||
password: Annotated[str, Body(description="User's password")],
|
password: Annotated[str, Body(description="User's password")],
|
||||||
):
|
) -> OtkResponse:
|
||||||
return auth_service.request_otk(session=session, email=email, password=password)
|
return auth_service.request_otk(session=session, email=email, password=password)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/request-password-reset",
|
||||||
|
summary="Request Password Reset",
|
||||||
|
description="Request a one-time password reset link for the given email address.",
|
||||||
|
operation_id="requestPasswordReset",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {"description": "Password reset requested successfully."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
async def request_password_reset(
|
||||||
|
session: SessionDep,
|
||||||
|
email: Annotated[str, Body(embed=True, description="User's email address")],
|
||||||
|
):
|
||||||
|
return auth_service.request_password_reset(session=session, email=email)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/reset-password",
|
||||||
|
summary="Reset Password",
|
||||||
|
description="Reset the user's password using a one-time password reset token.",
|
||||||
|
operation_id="resetPassword",
|
||||||
|
responses={status.HTTP_200_OK: {"description": "Password reset successfully."}},
|
||||||
|
)
|
||||||
|
async def reset_password(
|
||||||
|
session: SessionDep,
|
||||||
|
reset_token: Annotated[
|
||||||
|
str, Body(description="Password reset token from the reset link")
|
||||||
|
],
|
||||||
|
new_password: Annotated[
|
||||||
|
str,
|
||||||
|
Body(description="New password", min_length=8, example="NewPassword123"),
|
||||||
|
],
|
||||||
|
):
|
||||||
|
return auth_service.reset_password(
|
||||||
|
session=session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/login",
|
"/login",
|
||||||
summary="Login with One-Time Key",
|
summary="Login with One-Time Key",
|
||||||
@@ -80,7 +122,7 @@ async def get_action_tokens(
|
|||||||
effective_account_id: Annotated[
|
effective_account_id: Annotated[
|
||||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||||
],
|
],
|
||||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
id_token: Annotated[IdTokenMetadata, auth_service.CurrentUserIdTokenPayloadDep],
|
||||||
) -> AccessResponse:
|
) -> AccessResponse:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||||
@@ -108,11 +150,14 @@ async def get_action_tokens(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
async def refresh_access_token(
|
async def refresh_access_token(
|
||||||
|
response: Response,
|
||||||
refresh_token: Annotated[
|
refresh_token: Annotated[
|
||||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||||
],
|
],
|
||||||
) -> AccessToken:
|
) -> AccessToken:
|
||||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
return auth_service.refresh_access_token(
|
||||||
|
response=response, refresh_token=refresh_token
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
@@ -125,7 +170,7 @@ async def refresh_access_token(
|
|||||||
async def logout(
|
async def logout(
|
||||||
session: Annotated[Session, Depends(get_session)],
|
session: Annotated[Session, Depends(get_session)],
|
||||||
access_token: Annotated[
|
access_token: Annotated[
|
||||||
AccessToken,
|
AccessTokenMetadata,
|
||||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
],
|
],
|
||||||
):
|
):
|
||||||
@@ -150,7 +195,7 @@ async def change_password(
|
|||||||
Body(description="New password", min_length=8),
|
Body(description="New password", min_length=8),
|
||||||
],
|
],
|
||||||
access_token: Annotated[
|
access_token: Annotated[
|
||||||
AccessToken,
|
AccessTokenMetadata,
|
||||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
],
|
],
|
||||||
):
|
):
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -14,9 +14,11 @@ from inse.auth.model import (
|
|||||||
Account,
|
Account,
|
||||||
Organization,
|
Organization,
|
||||||
Secret,
|
Secret,
|
||||||
IdToken,
|
SecretPurpose,
|
||||||
AccessToken,
|
AccessToken,
|
||||||
RefreshToken,
|
IdTokenMetadata,
|
||||||
|
AccessTokenMetadata,
|
||||||
|
RefreshTokenMetadata,
|
||||||
UserRole,
|
UserRole,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -61,6 +63,19 @@ def create_org_and_account(
|
|||||||
return org, acc
|
return org, acc
|
||||||
|
|
||||||
|
|
||||||
|
def _get_cookie_value(response: Response, cookie_name: str) -> str:
|
||||||
|
for header_name, header_value in getattr(response, "raw_headers", []):
|
||||||
|
if header_name.lower() == b"set-cookie":
|
||||||
|
cookie_header = header_value.decode("latin-1")
|
||||||
|
if cookie_header.startswith(f"{cookie_name}="):
|
||||||
|
return cookie_header.split(";", 1)[0].split("=", 1)[1]
|
||||||
|
|
||||||
|
header = response.headers.get("set-cookie")
|
||||||
|
assert header is not None
|
||||||
|
assert header.startswith(f"{cookie_name}=")
|
||||||
|
return header.split(";", 1)[0].split("=", 1)[1]
|
||||||
|
|
||||||
|
|
||||||
def test_hash_and_verify_password():
|
def test_hash_and_verify_password():
|
||||||
pw = "s3cret-password"
|
pw = "s3cret-password"
|
||||||
h = auth_service._hash_password(pw)
|
h = auth_service._hash_password(pw)
|
||||||
@@ -80,11 +95,14 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
resp = auth_service.request_otk(in_memory_session, email, password)
|
resp = auth_service.request_otk(in_memory_session, email, password)
|
||||||
assert resp["status"] == "ok"
|
assert resp.status == "success"
|
||||||
assert resp["account_id"] == str(acc.id)
|
assert resp.account_id == acc.id
|
||||||
|
|
||||||
secret = in_memory_session.exec(
|
secret = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret is not None
|
assert secret is not None
|
||||||
|
|
||||||
@@ -93,9 +111,12 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
|||||||
login_result = auth_service.login(
|
login_result = auth_service.login(
|
||||||
in_memory_session, response, acc.id, secret.secret_value
|
in_memory_session, response, acc.id, secret.secret_value
|
||||||
)
|
)
|
||||||
assert isinstance(login_result.id_token, IdToken)
|
assert isinstance(login_result.id_token, IdTokenMetadata)
|
||||||
assert login_result.id_token.real_account_id == acc.id
|
assert login_result.id_token.real_account_id == acc.id
|
||||||
assert login_result.id_token.user_fingerprint_hash is not None
|
|
||||||
|
raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY)
|
||||||
|
payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session)
|
||||||
|
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||||
|
|
||||||
|
|
||||||
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
||||||
@@ -108,35 +129,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
secure_fgp_hash = auth_service._set_access_fp_cookie(response)
|
||||||
assert isinstance(id_token, IdToken)
|
secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY)
|
||||||
|
access_token = auth_service._build_access_token(
|
||||||
|
real_account_id=acc.id,
|
||||||
|
effective_account_id=acc.id,
|
||||||
|
effective_role=acc.role,
|
||||||
|
effective_organization_id=acc.organization_id,
|
||||||
|
epoch=acc.epoch,
|
||||||
|
user_fingerprint_hash=secure_fgp_hash,
|
||||||
|
)
|
||||||
|
assert isinstance(access_token, AccessToken)
|
||||||
|
|
||||||
cookie_header = None
|
payload = auth_service._verify_access_token_fp(
|
||||||
for header, value in response.headers.items():
|
secure_fgp=secure_fgp,
|
||||||
if header.lower() == "set-cookie":
|
raw_access_token=access_token.raw_token,
|
||||||
cookie_header = value
|
|
||||||
break
|
|
||||||
assert cookie_header is not None
|
|
||||||
cookie_value = cookie_header.split("=")[1].split(";")[0]
|
|
||||||
|
|
||||||
class DummyReq:
|
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
|
|
||||||
payload = auth_service._verify_fp_token(
|
|
||||||
request=req,
|
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
|
||||||
token=id_token.raw_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||||
|
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq({}),
|
secure_fgp="bad-fingerprint",
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
raw_access_token=access_token.raw_token,
|
||||||
token=id_token.raw_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -158,11 +173,30 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
|||||||
access_response = auth_service.get_access_token(
|
access_response = auth_service.get_access_token(
|
||||||
response, in_memory_session, id_token, acc.id
|
response, in_memory_session, id_token, acc.id
|
||||||
)
|
)
|
||||||
assert isinstance(access_response.access_token, AccessToken)
|
assert isinstance(access_response.access_token, AccessTokenMetadata)
|
||||||
assert isinstance(access_response.refresh_token, RefreshToken)
|
|
||||||
|
|
||||||
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
|
raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
|
||||||
assert isinstance(refreshed, AccessToken)
|
refresh_payload = auth_service._verify_refresh_token(
|
||||||
|
raw_refresh_token=raw_refresh_token,
|
||||||
|
session=in_memory_session,
|
||||||
|
)
|
||||||
|
refresh_token = RefreshTokenMetadata(
|
||||||
|
real_account_id=uuid.UUID(refresh_payload[auth_service.REAL_ACCOUNT_ID_KEY]),
|
||||||
|
effective_account_id=uuid.UUID(
|
||||||
|
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
|
||||||
|
),
|
||||||
|
expires_at=_dt.datetime.fromtimestamp(
|
||||||
|
refresh_payload["exp"], tz=_dt.timezone.utc
|
||||||
|
),
|
||||||
|
epoch=refresh_payload[auth_service.EPOCH_KEY],
|
||||||
|
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
|
||||||
|
effective_organization_id=uuid.UUID(
|
||||||
|
refresh_payload[auth_service.EFFECTIVE_ORGANIZATION_ID_KEY]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
refreshed = auth_service.refresh_access_token(Response(), refresh_token)
|
||||||
|
assert isinstance(refreshed, AccessTokenMetadata)
|
||||||
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
||||||
|
|
||||||
|
|
||||||
@@ -210,6 +244,36 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
|||||||
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||||
|
|
||||||
|
|
||||||
|
def test_deactivated_account_cannot_request_otk(in_memory_session):
|
||||||
|
email = "inactive@example.com"
|
||||||
|
password = "rightpw"
|
||||||
|
_, account = create_org_and_account(in_memory_session, email, password)
|
||||||
|
account.activated = False
|
||||||
|
in_memory_session.add(account)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
|
|
||||||
|
assert error.value.status_code == 403
|
||||||
|
assert error.value.detail == "Account is deactivated and cannot log in."
|
||||||
|
|
||||||
|
|
||||||
|
def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session):
|
||||||
|
_, account = create_org_and_account(
|
||||||
|
in_memory_session, "inactive-lookup@example.com", "password"
|
||||||
|
)
|
||||||
|
account.activated = False
|
||||||
|
in_memory_session.add(account)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
assert account.id is not None
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
auth_service._get_active_account(in_memory_session, account.id)
|
||||||
|
|
||||||
|
assert error.value.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||||
config_module.settings.token_hmac_key = "expired-key"
|
config_module.settings.token_hmac_key = "expired-key"
|
||||||
config_module.settings.token_issuer_id = "expired-issuer"
|
config_module.settings.token_issuer_id = "expired-issuer"
|
||||||
@@ -221,7 +285,12 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.LOGIN_OTK,
|
||||||
|
secret_value="000000",
|
||||||
|
expires_at=expired_at,
|
||||||
|
)
|
||||||
in_memory_session.add(secret)
|
in_memory_session.add(secret)
|
||||||
in_memory_session.commit()
|
in_memory_session.commit()
|
||||||
|
|
||||||
@@ -239,24 +308,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
secure_fgp_hash = auth_service._set_access_fp_cookie(response)
|
||||||
|
access_token = auth_service._build_access_token(
|
||||||
cookie_header = None
|
real_account_id=acc.id,
|
||||||
for header, value in response.headers.items():
|
effective_account_id=acc.id,
|
||||||
if header.lower() == "set-cookie":
|
effective_role=acc.role,
|
||||||
cookie_header = value
|
effective_organization_id=acc.organization_id,
|
||||||
break
|
epoch=acc.epoch,
|
||||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
user_fingerprint_hash=secure_fgp_hash,
|
||||||
|
)
|
||||||
class DummyReq:
|
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
|
secure_fgp="badcookie",
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
raw_access_token=access_token.raw_token,
|
||||||
token=id_token.raw_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -271,28 +336,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
secure_fgp_hash = auth_service._set_access_fp_cookie(response)
|
||||||
|
secure_fgp = _get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY)
|
||||||
cookie_header = None
|
access_token = auth_service._build_access_token(
|
||||||
for header, value in response.headers.items():
|
real_account_id=acc.id,
|
||||||
if header.lower() == "set-cookie":
|
effective_account_id=acc.id,
|
||||||
cookie_header = value
|
effective_role=acc.role,
|
||||||
break
|
effective_organization_id=acc.organization_id,
|
||||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
epoch=acc.epoch,
|
||||||
|
user_fingerprint_hash=secure_fgp_hash,
|
||||||
class DummyReq:
|
)
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
acc.epoch += 1
|
acc.epoch += 1
|
||||||
in_memory_session.add(acc)
|
in_memory_session.add(acc)
|
||||||
in_memory_session.commit()
|
in_memory_session.commit()
|
||||||
|
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
secure_fgp=secure_fgp,
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
raw_access_token=access_token.raw_token,
|
||||||
token=id_token.raw_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -307,25 +369,21 @@ def test_invalid_token_signature_raises(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
secure_fgp = auth_service._set_access_fp_cookie(response)
|
||||||
|
access_token = auth_service._build_access_token(
|
||||||
|
real_account_id=acc.id,
|
||||||
|
effective_account_id=acc.id,
|
||||||
|
effective_role=acc.role,
|
||||||
|
effective_organization_id=acc.organization_id,
|
||||||
|
epoch=acc.epoch,
|
||||||
|
user_fingerprint_hash=secure_fgp,
|
||||||
|
)
|
||||||
|
|
||||||
cookie_header = None
|
bad_token = access_token.raw_token + "x"
|
||||||
for header, value in response.headers.items():
|
|
||||||
if header.lower() == "set-cookie":
|
|
||||||
cookie_header = value
|
|
||||||
break
|
|
||||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
|
||||||
|
|
||||||
class DummyReq:
|
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
bad_token = id_token.raw_token + "x"
|
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
secure_fgp=secure_fgp,
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
raw_access_token=bad_token,
|
||||||
token=bad_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -362,7 +420,7 @@ def test_impersonation_rules(in_memory_session, settings_backup):
|
|||||||
real_acc.id,
|
real_acc.id,
|
||||||
effective_account_id=eff_acc.id,
|
effective_account_id=eff_acc.id,
|
||||||
)
|
)
|
||||||
assert isinstance(access_resp.access_token, AccessToken)
|
assert isinstance(access_resp.access_token, AccessTokenMetadata)
|
||||||
|
|
||||||
|
|
||||||
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||||
@@ -377,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
|||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret1 = in_memory_session.exec(
|
secret1 = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret1 is not None
|
assert secret1 is not None
|
||||||
first_value = secret1.secret_value
|
first_value = secret1.secret_value
|
||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret2 = in_memory_session.exec(
|
secret2 = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
|
|
||||||
assert secret2 is not None
|
assert secret2 is not None
|
||||||
@@ -396,7 +460,7 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
|||||||
login_res = auth_service.login(
|
login_res = auth_service.login(
|
||||||
in_memory_session, Response(), acc.id, secret2.secret_value
|
in_memory_session, Response(), acc.id, secret2.secret_value
|
||||||
)
|
)
|
||||||
assert isinstance(login_res.id_token, IdToken)
|
assert isinstance(login_res.id_token, IdTokenMetadata)
|
||||||
|
|
||||||
|
|
||||||
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||||
@@ -411,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
|||||||
|
|
||||||
auth_service.request_otk(in_memory_session, email, password)
|
auth_service.request_otk(in_memory_session, email, password)
|
||||||
secret = in_memory_session.exec(
|
secret = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert secret is not None
|
assert secret is not None
|
||||||
|
|
||||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||||
post = in_memory_session.exec(
|
post = in_memory_session.exec(
|
||||||
select(Secret).where(Secret.account_id == acc.id)
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.LOGIN_OTK,
|
||||||
|
)
|
||||||
).first()
|
).first()
|
||||||
assert post is None
|
assert post is None
|
||||||
|
|
||||||
@@ -432,7 +502,7 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
raw = auth_service._set_act_fp_cookie(response)
|
raw_hash = auth_service._set_access_fp_cookie(response)
|
||||||
|
|
||||||
access_token = auth_service._build_access_token(
|
access_token = auth_service._build_access_token(
|
||||||
real_account_id=acc.id,
|
real_account_id=acc.id,
|
||||||
@@ -440,18 +510,13 @@ def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
|||||||
effective_role=acc.role,
|
effective_role=acc.role,
|
||||||
effective_organization_id=acc.organization_id,
|
effective_organization_id=acc.organization_id,
|
||||||
epoch=acc.epoch,
|
epoch=acc.epoch,
|
||||||
user_fingerprint_hash=raw,
|
user_fingerprint_hash=raw_hash,
|
||||||
)
|
)
|
||||||
|
|
||||||
class DummyReq:
|
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
|
secure_fgp="wrongcookie",
|
||||||
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
|
raw_access_token=access_token.raw_token,
|
||||||
token=access_token.raw_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -466,34 +531,26 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
|||||||
assert acc.id is not None
|
assert acc.id is not None
|
||||||
|
|
||||||
response = Response()
|
response = Response()
|
||||||
cookie_raw = auth_service._set_id_fp_cookie(response)
|
|
||||||
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||||
|
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
|
||||||
payload = {
|
payload = {
|
||||||
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||||
|
auth_service.EFFECTIVE_ACCOUNT_ID_KEY: str(acc.id),
|
||||||
|
auth_service.EFFECTIVE_ROLE_KEY: acc.role.value,
|
||||||
|
auth_service.EFFECTIVE_ORGANIZATION_ID_KEY: str(acc.organization_id),
|
||||||
auth_service.EPOCH_KEY: acc.epoch,
|
auth_service.EPOCH_KEY: acc.epoch,
|
||||||
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
|
auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash,
|
||||||
}
|
}
|
||||||
bad_token = auth_service._build_token(
|
bad_token = auth_service._build_token(
|
||||||
payload=payload,
|
payload=payload,
|
||||||
expiration_datetime=past,
|
expiration_datetime=past,
|
||||||
token_type=auth_service.TokenType.ID_TOKEN,
|
token_type=auth_service.TokenType.ACCESS_TOKEN,
|
||||||
)
|
)
|
||||||
|
|
||||||
class DummyReq:
|
|
||||||
def __init__(self, cookies):
|
|
||||||
self.cookies = cookies
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
auth_service._verify_fp_token(
|
auth_service._verify_access_token_fp(
|
||||||
request=DummyReq(
|
secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY),
|
||||||
{
|
raw_access_token=bad_token,
|
||||||
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
|
|
||||||
.split("=")[1]
|
|
||||||
.split(";")[0]
|
|
||||||
}
|
|
||||||
), # type: ignore
|
|
||||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
|
||||||
token=bad_token,
|
|
||||||
session=in_memory_session,
|
session=in_memory_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -515,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
|
|||||||
random_id = uuid.uuid4()
|
random_id = uuid.uuid4()
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(Exception):
|
||||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_creates_secret(in_memory_session, settings_backup):
|
||||||
|
email = "reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(in_memory_session, email)
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
|
||||||
|
secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
|
||||||
|
assert secret is not None
|
||||||
|
assert secret.secret_value is not None
|
||||||
|
assert secret.secret_value != ""
|
||||||
|
assert secret.secret_value != password
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_unknown_email_is_safe(
|
||||||
|
in_memory_session, settings_backup, monkeypatch
|
||||||
|
):
|
||||||
|
sent_emails = []
|
||||||
|
|
||||||
|
def fake_send_email(**kwargs):
|
||||||
|
sent_emails.append(kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||||
|
config_module.settings.send_password_reset_email = True
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(
|
||||||
|
in_memory_session, "missing@example.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
assert sent_emails == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_password_reset_sends_email(
|
||||||
|
in_memory_session, settings_backup, monkeypatch
|
||||||
|
):
|
||||||
|
email = "mail-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
sent_emails = []
|
||||||
|
|
||||||
|
def fake_send_email(**kwargs):
|
||||||
|
sent_emails.append(kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(auth_service, "send_email", fake_send_email)
|
||||||
|
config_module.settings.send_password_reset_email = True
|
||||||
|
config_module.settings.password_reset_url = "http://localhost/reset-password"
|
||||||
|
|
||||||
|
result = auth_service.request_password_reset(in_memory_session, email)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
assert len(sent_emails) == 1
|
||||||
|
assert sent_emails[0]["recipient"] == email
|
||||||
|
assert "token=" in sent_emails[0]["body"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_changes_password_and_increments_epoch(in_memory_session):
|
||||||
|
email = "do-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
new_password = "NewPassword123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "valid-reset-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
old_epoch = acc.epoch
|
||||||
|
|
||||||
|
result = auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password=new_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "ok"
|
||||||
|
in_memory_session.refresh(acc)
|
||||||
|
assert auth_service._verify_password(new_password, acc.password_hash)
|
||||||
|
assert acc.epoch == old_epoch + 1
|
||||||
|
|
||||||
|
deleted_secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
assert deleted_secret is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_reused_token(in_memory_session):
|
||||||
|
email = "reuse-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "single-use-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="AnotherPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_invalid_token(in_memory_session):
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token="invalid-token",
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_password_rejects_expired_token(in_memory_session):
|
||||||
|
email = "expired-reset@example.com"
|
||||||
|
password = "oldpw123"
|
||||||
|
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||||
|
assert acc.id is not None
|
||||||
|
|
||||||
|
reset_token = "expired-token"
|
||||||
|
secret = Secret(
|
||||||
|
account_id=acc.id,
|
||||||
|
purpose=SecretPurpose.PASSWORD_RESET,
|
||||||
|
secret_value=auth_service._hash_reset_token(reset_token),
|
||||||
|
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
|
||||||
|
)
|
||||||
|
in_memory_session.add(secret)
|
||||||
|
in_memory_session.commit()
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
auth_service.reset_password(
|
||||||
|
in_memory_session,
|
||||||
|
reset_token=reset_token,
|
||||||
|
new_password="NewPassword123",
|
||||||
|
)
|
||||||
|
|
||||||
|
deleted_secret = in_memory_session.exec(
|
||||||
|
select(Secret).where(
|
||||||
|
Secret.account_id == acc.id,
|
||||||
|
Secret.purpose == SecretPurpose.PASSWORD_RESET,
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
assert deleted_secret is None
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
|
|||||||
skip_otk_validation: bool = True
|
skip_otk_validation: bool = True
|
||||||
# SMTP / email config
|
# SMTP / email config
|
||||||
send_otk_email: bool = False
|
send_otk_email: bool = False
|
||||||
|
send_password_reset_email: bool = True
|
||||||
|
password_reset_url: str = "http://localhost:4200/inse-webapp/reset-password"
|
||||||
smtp_server: str = "localhost"
|
smtp_server: str = "localhost"
|
||||||
smtp_port: int = 25
|
smtp_port: int = 25
|
||||||
smtp_sender: str = "no-reply@smartguide.local"
|
smtp_sender: str = "no-reply@smartguide.local"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import Depends
|
from fastapi import Depends
|
||||||
|
from sqlalchemy import inspect, text
|
||||||
from sqlmodel import SQLModel, Session, create_engine
|
from sqlmodel import SQLModel, Session, create_engine
|
||||||
|
|
||||||
from inse import config
|
from inse import config
|
||||||
@@ -18,6 +19,15 @@ engine = create_engine(
|
|||||||
def create_db_and_tables():
|
def create_db_and_tables():
|
||||||
"""Creates the database and tables based on the SQLModel metadata."""
|
"""Creates the database and tables based on the SQLModel metadata."""
|
||||||
SQLModel.metadata.create_all(engine)
|
SQLModel.metadata.create_all(engine)
|
||||||
|
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||||
|
if "activated" not in columns:
|
||||||
|
with engine.begin() as connection:
|
||||||
|
connection.execute(
|
||||||
|
text(
|
||||||
|
"ALTER TABLE account ADD COLUMN activated "
|
||||||
|
"BOOLEAN NOT NULL DEFAULT TRUE"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_session():
|
def get_session():
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ def get_client() -> httpx.AsyncClient:
|
|||||||
global _client, _loop
|
global _client, _loop
|
||||||
try:
|
try:
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
current_loop = asyncio.get_running_loop()
|
current_loop = asyncio.get_running_loop()
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
current_loop = None
|
current_loop = None
|
||||||
@@ -45,7 +46,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
|||||||
Returns:
|
Returns:
|
||||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if cluster == ESCluster.NES:
|
if cluster == ESCluster.NES:
|
||||||
if (
|
if (
|
||||||
not config.settings.elasticsearch_url
|
not config.settings.elasticsearch_url
|
||||||
@@ -54,7 +55,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
|||||||
raise MissingApiKeyError(
|
raise MissingApiKeyError(
|
||||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||||
)
|
)
|
||||||
|
|
||||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||||
elif cluster == ESCluster.INSE:
|
elif cluster == ESCluster.INSE:
|
||||||
if (
|
if (
|
||||||
@@ -108,8 +109,12 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
|||||||
def _wrap_exception(e: Exception) -> Exception:
|
def _wrap_exception(e: Exception) -> Exception:
|
||||||
if isinstance(e, httpx.HTTPStatusError):
|
if isinstance(e, httpx.HTTPStatusError):
|
||||||
if e.response.status_code == 404:
|
if e.response.status_code == 404:
|
||||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
return ElasticsearchNotFoundException(
|
||||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
f"Elasticsearch resource not found: {e}"
|
||||||
|
)
|
||||||
|
return ElasticsearchException(
|
||||||
|
f"Elasticsearch returned status {e.response.status_code}: {e}"
|
||||||
|
)
|
||||||
elif isinstance(e, httpx.RequestError):
|
elif isinstance(e, httpx.RequestError):
|
||||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||||
@@ -211,7 +216,9 @@ async def search(
|
|||||||
raise _wrap_exception(exc) from exc
|
raise _wrap_exception(exc) from exc
|
||||||
|
|
||||||
|
|
||||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
async def open_point_in_time(
|
||||||
|
index: str, keep_alive: str = "1m", cluster: str = "nes"
|
||||||
|
) -> str:
|
||||||
"""Opens a point-in-time on the given index and returns its id."""
|
"""Opens a point-in-time on the given index and returns its id."""
|
||||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||||
@@ -256,7 +263,7 @@ async def scan(
|
|||||||
cluster: str = "nes",
|
cluster: str = "nes",
|
||||||
) -> AsyncIterator[Dict[str, Any]]:
|
) -> AsyncIterator[Dict[str, Any]]:
|
||||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||||
|
|
||||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||||
"""
|
"""
|
||||||
@@ -316,6 +323,9 @@ async def get(
|
|||||||
cluster: ESCluster = ESCluster.NES,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
|
|
||||||
|
if isinstance(index, ESIndex):
|
||||||
|
cluster = _index_to_cluster(index) or cluster
|
||||||
|
|
||||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||||
|
|
||||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||||
|
|||||||
@@ -1,25 +1,31 @@
|
|||||||
from openai import OpenAI, APIConnectionError
|
from openai import OpenAI, APIConnectionError
|
||||||
|
from openai import AsyncOpenAI
|
||||||
from .. import config
|
from .. import config
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
import asyncio
|
||||||
def call(
|
def call(
|
||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
user_prompt: str,
|
user_prompt: str,
|
||||||
model: str = None,
|
model: str = None,
|
||||||
timeout: int = 30,
|
json_schema = None,
|
||||||
|
schema_name = None,
|
||||||
|
timeout: int = 120,
|
||||||
temperature: float = 1.0,
|
temperature: float = 1.0,
|
||||||
top_p: float = 0.95,
|
top_p: float = 0.95,
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
||||||
if model is None:
|
if model is None:
|
||||||
model = config.settings.llm_model
|
model = config.settings.llm_model
|
||||||
|
|
||||||
|
response_format = None
|
||||||
|
if json_schema is not None:
|
||||||
|
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
|
||||||
|
|
||||||
client = OpenAI(
|
client = OpenAI(
|
||||||
base_url=config.settings.llm_api_url,
|
base_url=config.settings.llm_api_url,
|
||||||
api_key=config.settings.llm_api_key,
|
api_key=config.settings.llm_api_key,
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = client.chat.completions.create(
|
response = client.chat.completions.create(
|
||||||
model=model,
|
model=model,
|
||||||
@@ -27,10 +33,10 @@ def call(
|
|||||||
{"role": "system", "content": system_prompt},
|
{"role": "system", "content": system_prompt},
|
||||||
{"role": "user", "content": user_prompt},
|
{"role": "user", "content": user_prompt},
|
||||||
],
|
],
|
||||||
|
|
||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
top_p=top_p,
|
top_p=top_p,
|
||||||
extra_body={"top_k": 64},
|
extra_body={"top_k": 64},
|
||||||
|
response_format=response_format
|
||||||
)
|
)
|
||||||
except APIConnectionError:
|
except APIConnectionError:
|
||||||
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
|
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
|
||||||
@@ -38,3 +44,84 @@ def call(
|
|||||||
return response.choices[0].message.content or (
|
return response.choices[0].message.content or (
|
||||||
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
|
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]:
|
||||||
|
response_format = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": schema_name or "response",
|
||||||
|
"strict": True,
|
||||||
|
"schema": schema,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return response_format
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def call_stream(
|
||||||
|
system_prompt: str,
|
||||||
|
user_prompt: str,
|
||||||
|
emit,
|
||||||
|
model: str = None,
|
||||||
|
json_schema=None,
|
||||||
|
schema_name=None,
|
||||||
|
timeout: int = 120,
|
||||||
|
temperature: float = 1.0,
|
||||||
|
top_p: float = 0.95,
|
||||||
|
) -> str:
|
||||||
|
if model is None:
|
||||||
|
model = config.settings.llm_model
|
||||||
|
|
||||||
|
response_format = None
|
||||||
|
if json_schema is not None:
|
||||||
|
response_format = _get_response_format(schema=json_schema, schema_name=schema_name)
|
||||||
|
|
||||||
|
client = AsyncOpenAI(
|
||||||
|
base_url=config.settings.llm_api_url,
|
||||||
|
api_key=config.settings.llm_api_key,
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
full_content = ""
|
||||||
|
try:
|
||||||
|
stream = await client.chat.completions.create(
|
||||||
|
model=model,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": user_prompt},
|
||||||
|
],
|
||||||
|
temperature=temperature,
|
||||||
|
top_p=top_p,
|
||||||
|
extra_body={"top_k": 64},
|
||||||
|
response_format=response_format,
|
||||||
|
stream=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async for chunk in stream:
|
||||||
|
delta = chunk.choices[0].delta.content
|
||||||
|
if delta:
|
||||||
|
full_content += delta
|
||||||
|
await emit({"type": "llm_chunk", "content": delta})
|
||||||
|
finally:
|
||||||
|
# Always release the underlying HTTP connection, whether we
|
||||||
|
# finished normally, timed out, were cancelled, or emit()
|
||||||
|
# failed because the client disconnected. This is what
|
||||||
|
# actually tells the backend to stop generating.
|
||||||
|
await stream.close()
|
||||||
|
|
||||||
|
except APIConnectionError as e:
|
||||||
|
print(f"Connection error: {e}")
|
||||||
|
return ""
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
|
||||||
|
# from the router)
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
return full_content
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Business logic for persons / authors.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
import partial_json_parser
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import httpx
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from typing import Awaitable, Callable
|
||||||
|
from inse.keywords.prompts import KeywordsPrompt
|
||||||
|
from inse.integrations import llm
|
||||||
|
from inse.keywords.model import (
|
||||||
|
ExtractedKeywords,
|
||||||
|
ExtractedKeywordsLLM,
|
||||||
|
ExtractedKeywordsResponse,
|
||||||
|
KeywordEntry,
|
||||||
|
KeywordEntryWithTopic,
|
||||||
|
KeywordsWsEvent,
|
||||||
|
)
|
||||||
|
from inse.topics.logic import vector_search_topics_batch
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
EventCallback = Callable[[dict], Awaitable[None]]
|
||||||
|
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||||
|
|
||||||
|
|
||||||
|
def _build_enriched_snapshot(
|
||||||
|
confirmed: Dict[str, List[KeywordEntryWithTopic]],
|
||||||
|
) -> ExtractedKeywords:
|
||||||
|
return ExtractedKeywords.model_validate(
|
||||||
|
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords:
|
||||||
|
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {
|
||||||
|
level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)]
|
||||||
|
for level in LEVELS
|
||||||
|
}
|
||||||
|
|
||||||
|
keywords: List[str] = []
|
||||||
|
positions: List[tuple[str, int]] = []
|
||||||
|
for level in LEVELS:
|
||||||
|
for idx, entry in enumerate(getattr(results, level)):
|
||||||
|
keywords.append(entry.keyword)
|
||||||
|
positions.append((level, idx))
|
||||||
|
|
||||||
|
if keywords:
|
||||||
|
matches = await vector_search_topics_batch(keywords=keywords, search_type="hybrid")
|
||||||
|
for (level, idx), match in zip(positions, matches.results):
|
||||||
|
confirmed[level][idx].topic_mapping = match
|
||||||
|
|
||||||
|
return _build_enriched_snapshot(confirmed)
|
||||||
|
|
||||||
|
async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse:
|
||||||
|
"""
|
||||||
|
Extracts keywords from the given text or URL using a language model.
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
if mode == "url":
|
||||||
|
text = await _get_text_content(query)
|
||||||
|
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||||
|
|
||||||
|
else:
|
||||||
|
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||||
|
text = query
|
||||||
|
|
||||||
|
|
||||||
|
user_prompt = f"""
|
||||||
|
Now analyze the following text and return ONLY the JSON object.\n"""
|
||||||
|
|
||||||
|
if limit:
|
||||||
|
user_prompt +=f"Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n"
|
||||||
|
|
||||||
|
user_prompt += f"""Input:{text}"""
|
||||||
|
|
||||||
|
keywords = llm.call(
|
||||||
|
system_prompt=system_prompt,
|
||||||
|
user_prompt=user_prompt,
|
||||||
|
json_schema = ExtractedKeywordsLLM.model_json_schema(),
|
||||||
|
schema_name = "extracted_keywords",
|
||||||
|
temperature=0.8,
|
||||||
|
top_p=0.95,
|
||||||
|
)
|
||||||
|
keywords_json = json.loads(keywords)
|
||||||
|
validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||||
|
enriched = await _enrich_llm_keywords(validated)
|
||||||
|
|
||||||
|
elapsed_time = time.time() - start_time
|
||||||
|
logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds")
|
||||||
|
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_text_content(url: str) -> str:
|
||||||
|
"""
|
||||||
|
Fetches the HTML content from the given URL using httpx and extracts visible text.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
headers = {
|
||||||
|
"User-Agent": (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||||
|
"Chrome/91.0.4472.124 Safari/537.36"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
response = await client.get(url, headers=headers)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
soup = BeautifulSoup(response.text, "html.parser")
|
||||||
|
for element in soup(["script", "style"]):
|
||||||
|
element.decompose()
|
||||||
|
text = soup.get_text(separator=" ", strip=True)
|
||||||
|
text = " ".join(text.split())
|
||||||
|
return text
|
||||||
|
|
||||||
|
except httpx.HTTPError as e:
|
||||||
|
logger.error(f"HTTP error for {url}: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error processing {url}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def extract_keywords_stream_enriched(
|
||||||
|
query: str,
|
||||||
|
mode: str,
|
||||||
|
limit: int,
|
||||||
|
emit: EventCallback,
|
||||||
|
) -> ExtractedKeywordsResponse:
|
||||||
|
start_time = time.time()
|
||||||
|
timeout_seconds = 120
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||||
|
|
||||||
|
if mode == "url":
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||||
|
text = await _get_text_content(query)
|
||||||
|
if text:
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||||
|
else:
|
||||||
|
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
|
||||||
|
raise RuntimeError(f"Failed to fetch content from {query}")
|
||||||
|
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||||
|
else:
|
||||||
|
text = query
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||||
|
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||||
|
|
||||||
|
user_prompt = "\nNow analyze the following text.\n"
|
||||||
|
if limit:
|
||||||
|
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
|
||||||
|
user_prompt += f"\nInput:\n{text}"
|
||||||
|
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||||
|
|
||||||
|
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||||
|
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||||
|
enrichment_tasks: List[asyncio.Task] = []
|
||||||
|
|
||||||
|
async def emit_full_results() -> None:
|
||||||
|
try:
|
||||||
|
validated = _build_enriched_snapshot(confirmed)
|
||||||
|
except ValidationError:
|
||||||
|
return
|
||||||
|
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||||
|
|
||||||
|
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||||
|
try:
|
||||||
|
topic = await vector_search_topics_batch(
|
||||||
|
keywords=[item.keyword],
|
||||||
|
search_type="hybrid",
|
||||||
|
)
|
||||||
|
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||||
|
await emit_full_results()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||||
|
await emit_full_results()
|
||||||
|
|
||||||
|
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||||
|
if event["type"] != "llm_chunk":
|
||||||
|
await emit(event)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
if not isinstance(partial, dict):
|
||||||
|
return
|
||||||
|
|
||||||
|
grew = False
|
||||||
|
|
||||||
|
for level in LEVELS:
|
||||||
|
current = partial.get(level) or []
|
||||||
|
start_idx = len(confirmed[level])
|
||||||
|
|
||||||
|
while len(confirmed[level]) < len(current):
|
||||||
|
raw_item = current[len(confirmed[level])]
|
||||||
|
try:
|
||||||
|
validated_item = KeywordEntry.model_validate(raw_item)
|
||||||
|
except ValidationError:
|
||||||
|
break
|
||||||
|
|
||||||
|
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||||
|
grew = True
|
||||||
|
|
||||||
|
for idx in range(start_idx, len(confirmed[level])):
|
||||||
|
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||||
|
await emit(
|
||||||
|
KeywordsWsEvent(
|
||||||
|
type="status",
|
||||||
|
step="enriching",
|
||||||
|
message=f"Extracting topic for keyword '{keyword_text}'",
|
||||||
|
).model_dump()
|
||||||
|
)
|
||||||
|
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
|
||||||
|
enrichment_tasks.append(task)
|
||||||
|
|
||||||
|
if grew:
|
||||||
|
await emit_full_results()
|
||||||
|
|
||||||
|
full_content_holder = {"value": ""}
|
||||||
|
|
||||||
|
async def emit_wrapper(event: Dict[str, Any]) -> None:
|
||||||
|
if event["type"] == "llm_chunk":
|
||||||
|
full_content_holder["value"] += event["content"]
|
||||||
|
event = {**event, "_full_content": full_content_holder["value"]}
|
||||||
|
await on_chunk(event)
|
||||||
|
|
||||||
|
# ---------- Call the LLM ----------
|
||||||
|
keywords = ""
|
||||||
|
try:
|
||||||
|
keywords = await asyncio.wait_for(
|
||||||
|
llm.call_stream(
|
||||||
|
system_prompt=system_prompt,
|
||||||
|
user_prompt=user_prompt,
|
||||||
|
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||||
|
schema_name="extracted_keywords",
|
||||||
|
temperature=0.0,
|
||||||
|
top_p=0.95,
|
||||||
|
emit=emit_wrapper,
|
||||||
|
),
|
||||||
|
timeout=timeout_seconds,
|
||||||
|
)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||||
|
raise RuntimeError("LLM streaming call timed out")
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||||
|
raise
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if enrichment_tasks:
|
||||||
|
done, pending = await asyncio.wait(enrichment_tasks, timeout=10)
|
||||||
|
for task in pending:
|
||||||
|
task.cancel()
|
||||||
|
if pending:
|
||||||
|
await asyncio.gather(*pending, return_exceptions=True)
|
||||||
|
|
||||||
|
if not keywords:
|
||||||
|
# Empty string covers: real empty completion, APIConnectionError,
|
||||||
|
# and disconnect-during-emit (call_stream currently swallows all
|
||||||
|
# three the same way). Treat as a failed extraction.
|
||||||
|
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||||
|
raise RuntimeError("LLM streaming call returned empty content")
|
||||||
|
|
||||||
|
# ---------- Finalize ----------
|
||||||
|
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||||
|
|
||||||
|
try:
|
||||||
|
keywords_json = json.loads(keywords)
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||||
|
raise RuntimeError("LLM response is not valid JSON")
|
||||||
|
|
||||||
|
await emit_full_results()
|
||||||
|
|
||||||
|
try:
|
||||||
|
final_validated = _build_enriched_snapshot(confirmed)
|
||||||
|
except ValidationError:
|
||||||
|
final_validated = ExtractedKeywords.model_validate(
|
||||||
|
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||||
|
)
|
||||||
|
|
||||||
|
elapsed_time = time.time() - start_time
|
||||||
|
result = ExtractedKeywordsResponse(
|
||||||
|
results=final_validated,
|
||||||
|
source=mode,
|
||||||
|
source_url=query if mode == "url" else None,
|
||||||
|
source_content=text,
|
||||||
|
duration=elapsed_time,
|
||||||
|
)
|
||||||
|
|
||||||
|
return result
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Data models for persons / authors.
|
||||||
|
"""
|
||||||
|
from typing import List, Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from inse.topics.model import KeywordTopicMatch
|
||||||
|
class KeywordsRequest(BaseModel):
|
||||||
|
query: str = Field(description="The input text from which to extract keywords.")
|
||||||
|
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||||
|
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||||
|
|
||||||
|
class KeywordEntry(BaseModel):
|
||||||
|
keyword: str = Field(description="The extracted keyword.")
|
||||||
|
relevance_score: float = Field(description="The relevance score of the keyword.")
|
||||||
|
|
||||||
|
class KeywordEntryWithTopic(BaseModel):
|
||||||
|
llm_keyword: KeywordEntry = Field(description="The keyword extracted by the LLM.")
|
||||||
|
topic_mapping: KeywordTopicMatch | None = Field(
|
||||||
|
default=None,
|
||||||
|
description="The corresponding OpenAlex topic match for the keyword, if any.",
|
||||||
|
)
|
||||||
|
|
||||||
|
class ExtractedKeywords(BaseModel):
|
||||||
|
broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
|
||||||
|
coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
|
||||||
|
fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
|
||||||
|
|
||||||
|
class ExtractedKeywordsLLM(BaseModel):
|
||||||
|
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.")
|
||||||
|
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
|
||||||
|
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
|
||||||
|
|
||||||
|
class ExtractedKeywordsResponse(BaseModel):
|
||||||
|
results_llm: ExtractedKeywordsLLM | None = None
|
||||||
|
results: ExtractedKeywords | None = None
|
||||||
|
source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.")
|
||||||
|
source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.")
|
||||||
|
source_content: str = Field(description="The actual content from which keywords were extracted.")
|
||||||
|
duration: float | None = Field(default=None, description="The time taken to extract keywords, in seconds.")
|
||||||
|
|
||||||
|
class KeywordsWsEvent(BaseModel):
|
||||||
|
type: str
|
||||||
|
step: str | None = None
|
||||||
|
message: str | None = None
|
||||||
|
result: ExtractedKeywordsResponse | None = None
|
||||||
|
keywords: ExtractedKeywords | ExtractedKeywordsLLM | None = None
|
||||||
|
duration: float | None = None
|
||||||
|
completed: str | None = None
|
||||||
|
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
from enum import StrEnum
|
||||||
|
class KeywordsPrompt(StrEnum):
|
||||||
|
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
|
||||||
|
|
||||||
|
Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval.
|
||||||
|
|
||||||
|
The extracted keywords should prioritize:
|
||||||
|
|
||||||
|
* Scientific domains
|
||||||
|
* Technologies
|
||||||
|
* Research fields
|
||||||
|
* Methods
|
||||||
|
* Applications
|
||||||
|
* Materials
|
||||||
|
* Standards
|
||||||
|
* Diseases
|
||||||
|
* Industrial sectors
|
||||||
|
* Technical concepts
|
||||||
|
|
||||||
|
Avoid generic business terms unless they are core topics of the text.
|
||||||
|
|
||||||
|
Examples of terms to avoid:
|
||||||
|
|
||||||
|
* Solution
|
||||||
|
* Platform
|
||||||
|
* Improvement
|
||||||
|
* Capability
|
||||||
|
* Innovation
|
||||||
|
* Process
|
||||||
|
* Service
|
||||||
|
* Performance
|
||||||
|
* Efficiency
|
||||||
|
|
||||||
|
unless they represent an actual searchable concept.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||||
|
|
||||||
|
The output must be strictly extractive and grounded in the input text.
|
||||||
|
|
||||||
|
## Mandatory Rules
|
||||||
|
|
||||||
|
1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text.
|
||||||
|
|
||||||
|
2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text.
|
||||||
|
|
||||||
|
3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input contains:
|
||||||
|
|
||||||
|
"transformer-based machine learning framework"
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* transformer-based machine learning framework
|
||||||
|
* machine learning
|
||||||
|
* transformer
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* Artificial Intelligence
|
||||||
|
* Deep Learning
|
||||||
|
* Neural Networks
|
||||||
|
|
||||||
|
unless those exact terms appear in the text.
|
||||||
|
|
||||||
|
4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"large language models"
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* large language models
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* LLMs
|
||||||
|
* Generative AI
|
||||||
|
* Artificial Intelligence
|
||||||
|
|
||||||
|
unless explicitly present.
|
||||||
|
|
||||||
|
5. Do NOT generate implied concepts.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"patient records"
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* Healthcare
|
||||||
|
* Medical Informatics
|
||||||
|
* Clinical Documentation
|
||||||
|
|
||||||
|
unless explicitly mentioned.
|
||||||
|
|
||||||
|
6. Every keyword must have direct textual evidence in the input.
|
||||||
|
|
||||||
|
7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output.
|
||||||
|
|
||||||
|
8. Prefer exact surface forms from the text.
|
||||||
|
|
||||||
|
9. Preserve original capitalization when possible.
|
||||||
|
|
||||||
|
10. Do not invent keywords to satisfy target counts.
|
||||||
|
|
||||||
|
11. When insufficient keywords exist for a level, return fewer keywords.
|
||||||
|
|
||||||
|
12. Grounding accuracy is more important than completeness.
|
||||||
|
|
||||||
|
13. Any keyword not directly supported by the text is considered an extraction error.
|
||||||
|
|
||||||
|
## Hierarchy Assignment Rules
|
||||||
|
|
||||||
|
The hierarchy is only an organizational grouping.
|
||||||
|
|
||||||
|
Do NOT create broader concepts to populate broad_keywords.
|
||||||
|
|
||||||
|
If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text.
|
||||||
|
|
||||||
|
Do not create abstraction layers that are not explicitly present in the document.
|
||||||
|
|
||||||
|
## Self-Validation Before Output
|
||||||
|
|
||||||
|
Before returning the final JSON, verify every keyword:
|
||||||
|
|
||||||
|
* Can this exact phrase be found in the input text?
|
||||||
|
* Can a user highlight the phrase directly in the source text?
|
||||||
|
|
||||||
|
If the answer is NO, remove the keyword.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Keyword Hierarchy
|
||||||
|
|
||||||
|
## 1. broad_keywords
|
||||||
|
|
||||||
|
High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
|
||||||
|
|
||||||
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
|
* Artificial Intelligence
|
||||||
|
* Healthcare
|
||||||
|
* Biotechnology
|
||||||
|
* Renewable Energy
|
||||||
|
* Materials Science
|
||||||
|
* Robotics
|
||||||
|
|
||||||
|
These should represent the major themes of the document when those themes are explicitly stated.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. coarse_grained
|
||||||
|
|
||||||
|
Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
|
||||||
|
|
||||||
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
|
* Machine Learning
|
||||||
|
* Drug Discovery
|
||||||
|
* Computer Vision
|
||||||
|
* Predictive Maintenance
|
||||||
|
* Smart Manufacturing
|
||||||
|
* Gene Editing
|
||||||
|
|
||||||
|
These should provide more specific context within the broad domains.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. fine_grained
|
||||||
|
|
||||||
|
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
|
||||||
|
|
||||||
|
Examples (only if explicitly mentioned):
|
||||||
|
|
||||||
|
* Transformer Architecture
|
||||||
|
* CRISPR-Cas9
|
||||||
|
* Retrieval-Augmented Generation
|
||||||
|
* Lithium Iron Phosphate
|
||||||
|
* YOLOv8
|
||||||
|
* OPC UA
|
||||||
|
|
||||||
|
These should be the most specific and actionable concepts for literature retrieval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Relevance Score
|
||||||
|
|
||||||
|
Each keyword must include a relevance score.
|
||||||
|
|
||||||
|
Definition:
|
||||||
|
|
||||||
|
* 1.0 = central concept of the text
|
||||||
|
* 0.9 = extremely important concept
|
||||||
|
* 0.8 = highly relevant concept
|
||||||
|
* 0.7 = important supporting concept
|
||||||
|
* 0.6 = relevant secondary concept
|
||||||
|
* below 0.6 = use sparingly
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
|
||||||
|
* Scores must be between 0.0 and 1.0.
|
||||||
|
* Use decimal precision up to 3 digits.
|
||||||
|
* Rank keywords by importance.
|
||||||
|
* The most important keywords should appear first.
|
||||||
|
* Broad keywords generally receive higher scores than secondary topics.
|
||||||
|
* Only include keywords with meaningful relevance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Extraction Rules
|
||||||
|
|
||||||
|
* Extract only concepts explicitly mentioned in the text.
|
||||||
|
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||||
|
* Every keyword must be directly traceable to text spans in the input.
|
||||||
|
* Prefer noun phrases.
|
||||||
|
* Avoid complete sentences.
|
||||||
|
* Avoid duplicates across levels whenever possible.
|
||||||
|
* Do not invent technologies not supported by the text.
|
||||||
|
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||||
|
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||||
|
* If fewer valid keywords exist, return fewer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Output Schema
|
||||||
|
|
||||||
|
Return ONLY valid JSON using the following structure:
|
||||||
|
|
||||||
|
{
|
||||||
|
"broad_keywords": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"coarse_grained": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fine_grained": [
|
||||||
|
{
|
||||||
|
"keyword": "string",
|
||||||
|
"relevance_score": 0.0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
|
||||||
|
* Return ONLY valid JSON.
|
||||||
|
* Do not include explanations.
|
||||||
|
* Do not include markdown.
|
||||||
|
* Do not include comments.
|
||||||
|
* Do not include reasoning.
|
||||||
|
* Do not include any text outside the JSON object.
|
||||||
|
* Every keyword must be directly supported by the input text.
|
||||||
|
* Any keyword not explicitly present in the source text must be excluded.
|
||||||
|
|
||||||
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Example 1
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||||
|
Output:
|
||||||
|
|
||||||
|
broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]}
|
||||||
|
---
|
||||||
|
|
||||||
|
# Example 2
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||||
|
Output:
|
||||||
|
|
||||||
|
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]}
|
||||||
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||||
|
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||||
|
|
||||||
|
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||||
|
|
||||||
|
The extracted text may contain:
|
||||||
|
|
||||||
|
* Navigation menus
|
||||||
|
* Headers and footers
|
||||||
|
* Cookie notices
|
||||||
|
* Marketing language
|
||||||
|
* Contact information
|
||||||
|
* Repeated sections
|
||||||
|
* Calls to action
|
||||||
|
* Legal disclaimers
|
||||||
|
* Product pages
|
||||||
|
* Blog articles
|
||||||
|
* News articles
|
||||||
|
* Landing pages
|
||||||
|
|
||||||
|
Your first task is to identify the actual content and purpose of the webpage.
|
||||||
|
|
||||||
|
Ignore:
|
||||||
|
|
||||||
|
* Navigation elements
|
||||||
|
* Cookie banners
|
||||||
|
* Legal notices
|
||||||
|
* Copyright text
|
||||||
|
* Generic marketing statements
|
||||||
|
* Contact information
|
||||||
|
* Login/signup content
|
||||||
|
* Careers pages unless they contain relevant technical information
|
||||||
|
* Repeated website boilerplate
|
||||||
|
|
||||||
|
Focus only on the primary informational content of the webpage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
|
||||||
|
|
||||||
|
The output must be strictly extractive and grounded in the webpage text.
|
||||||
|
|
||||||
|
## Mandatory Rules
|
||||||
|
|
||||||
|
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
|
||||||
|
|
||||||
|
2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
|
||||||
|
|
||||||
|
3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"The platform uses large language models and retrieval-augmented generation."
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* large language models
|
||||||
|
* retrieval-augmented generation
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* Artificial Intelligence
|
||||||
|
* Generative AI
|
||||||
|
* Natural Language Processing
|
||||||
|
|
||||||
|
unless explicitly present.
|
||||||
|
|
||||||
|
4. Do NOT generate synonyms.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
"AI assistant"
|
||||||
|
|
||||||
|
Allowed:
|
||||||
|
|
||||||
|
* AI assistant
|
||||||
|
|
||||||
|
Not allowed:
|
||||||
|
|
||||||
|
* large language models
|
||||||
|
* conversational AI
|
||||||
|
* generative AI
|
||||||
|
|
||||||
|
unless those exact terms appear.
|
||||||
|
|
||||||
|
5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
|
||||||
|
|
||||||
|
6. Do NOT rewrite marketing terms into technical terms.
|
||||||
|
|
||||||
|
7. Every keyword must have direct textual evidence in the webpage content.
|
||||||
|
|
||||||
|
8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
|
||||||
|
|
||||||
|
9. Preserve original wording whenever possible.
|
||||||
|
|
||||||
|
10. Do not invent keywords to satisfy target counts.
|
||||||
|
|
||||||
|
11. When insufficient keywords exist, return fewer keywords.
|
||||||
|
|
||||||
|
12. Grounding accuracy is more important than completeness.
|
||||||
|
|
||||||
|
13. Any keyword not directly supported by the webpage text is considered an extraction error.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Step 1: Determine Page Type
|
||||||
|
|
||||||
|
Determine internally whether the page is:
|
||||||
|
|
||||||
|
* Technology/Product Page
|
||||||
|
* Company Page
|
||||||
|
* Research Article
|
||||||
|
* Scientific Blog Post
|
||||||
|
* News Article
|
||||||
|
* Technical Documentation
|
||||||
|
* White Paper
|
||||||
|
* Industry Report
|
||||||
|
* Other
|
||||||
|
|
||||||
|
Use this classification only to identify the relevant content and remove boilerplate.
|
||||||
|
|
||||||
|
Do NOT include the classification in the output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Step 2: Extract Searchable Concepts
|
||||||
|
|
||||||
|
Extract concepts directly present in the page that are useful for:
|
||||||
|
|
||||||
|
* OpenAlex retrieval
|
||||||
|
* Scientific literature discovery
|
||||||
|
* Patent scouting
|
||||||
|
* Technology scouting
|
||||||
|
* Innovation monitoring
|
||||||
|
|
||||||
|
The extracted concepts must remain faithful to the wording used in the webpage.
|
||||||
|
|
||||||
|
Do NOT replace webpage terminology with your own preferred terminology.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Keyword Hierarchy
|
||||||
|
|
||||||
|
## broad_keywords
|
||||||
|
|
||||||
|
High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
|
||||||
|
|
||||||
|
Only use this level when such broad concepts are explicitly present.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
* Healthcare
|
||||||
|
* Biotechnology
|
||||||
|
* Manufacturing
|
||||||
|
* Robotics
|
||||||
|
* Financial Technology
|
||||||
|
|
||||||
|
only if those exact concepts appear in the webpage.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## coarse_grained
|
||||||
|
|
||||||
|
Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
* Machine Learning
|
||||||
|
* Predictive Maintenance
|
||||||
|
* Drug Discovery
|
||||||
|
* Smart Manufacturing
|
||||||
|
* Clinical Decision Support
|
||||||
|
|
||||||
|
only if explicitly present.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## fine_grained
|
||||||
|
|
||||||
|
Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
* FastAPI
|
||||||
|
* OpenAPI
|
||||||
|
* Pydantic
|
||||||
|
* CRISPR-Cas9
|
||||||
|
* Retrieval-Augmented Generation
|
||||||
|
* OPC UA
|
||||||
|
|
||||||
|
only if explicitly present.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Relevance Score
|
||||||
|
|
||||||
|
Assign a relevance score between 0.0 and 1.0.
|
||||||
|
|
||||||
|
Guidelines:
|
||||||
|
|
||||||
|
* 1.00 = central topic of the webpage
|
||||||
|
* 0.90 = major topic
|
||||||
|
* 0.80 = highly relevant
|
||||||
|
* 0.70 = supporting concept
|
||||||
|
* 0.60 = secondary concept
|
||||||
|
|
||||||
|
Avoid scores below 0.60 unless necessary.
|
||||||
|
|
||||||
|
Rank keywords by importance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Extraction Rules
|
||||||
|
|
||||||
|
* Extract only concepts explicitly mentioned in the webpage text.
|
||||||
|
* Do not use concepts that are merely implied, inferred, generalized, or derived.
|
||||||
|
* Every keyword must be directly traceable to text spans in the webpage.
|
||||||
|
* Prefer noun phrases.
|
||||||
|
* Avoid complete sentences.
|
||||||
|
* Avoid duplicates across hierarchy levels whenever possible.
|
||||||
|
* Preserve original wording.
|
||||||
|
* Rank keywords by importance.
|
||||||
|
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||||
|
* If fewer valid keywords exist, return fewer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Self-Validation Before Output
|
||||||
|
|
||||||
|
For every keyword, verify:
|
||||||
|
|
||||||
|
* Can this exact phrase be found in the webpage text?
|
||||||
|
* Can a user highlight the phrase directly in the extracted content?
|
||||||
|
|
||||||
|
If the answer is NO, remove the keyword.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Example — Technical Documentation
|
||||||
|
|
||||||
|
Input:
|
||||||
|
|
||||||
|
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||||
|
|
||||||
|
Output:
|
||||||
|
|
||||||
|
{"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]}
|
||||||
|
|
||||||
|
Return ONLY valid JSON matching the schema provided by the API.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
SIMPLE_TEXT_PROMPT = """
|
||||||
|
You are a scientific and technology intelligence expert. Extract keywords from the given text into three hierarchical levels. Each keyword must include a relevance_score (0.0–1.0) indicating centrality.
|
||||||
|
|
||||||
|
**Levels:**
|
||||||
|
- **broad_keywords** – high‑level domains/industries (e.g., Artificial Intelligence, Healthcare, Renewable Energy).
|
||||||
|
- **coarse_grained** – mid‑level technologies/methods/applications (e.g., Machine Learning, Drug Discovery, Smart Manufacturing).
|
||||||
|
- **fine_grained** – specific technical concepts, algorithms, materials, protocols (e.g., Transformer Architecture, CRISPR‑Cas9, Retrieval‑Augmented Generation).
|
||||||
|
|
||||||
|
**Guidelines:**
|
||||||
|
- Prioritize scientific, technical, and research‑oriented terminology.
|
||||||
|
- Avoid generic business fluff: "solution", "platform", "improvement", "service", "performance" – unless they are explicit searchable concepts.
|
||||||
|
- Prefer noun phrases; avoid complete sentences.
|
||||||
|
- Extract 5–15 keywords per level when possible.
|
||||||
|
- Rank by importance (higher scores first).
|
||||||
|
|
||||||
|
**Relevance scores:**
|
||||||
|
- 1.0 = central topic
|
||||||
|
- 0.9 = extremely important
|
||||||
|
- 0.8 = highly relevant
|
||||||
|
- 0.7 = supporting concept
|
||||||
|
- 0.6 = secondary
|
||||||
|
- Below 0.6 – use sparingly.
|
||||||
|
|
||||||
|
**Output schema (JSON only):**
|
||||||
|
{
|
||||||
|
"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],
|
||||||
|
"coarse_grained": [...],
|
||||||
|
"fine_grained": [...]
|
||||||
|
}
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
Input: Researchers developed a transformer-based ML framework for predictive maintenance in smart factories using sensor fusion and anomaly detection.
|
||||||
|
Output:
|
||||||
|
{
|
||||||
|
"broad_keywords": [{"keyword": "Artificial Intelligence", "relevance_score": 0.98}, {"keyword": "Manufacturing", "relevance_score": 0.94}],
|
||||||
|
"coarse_grained": [{"keyword": "Predictive Maintenance", "relevance_score": 0.95}, {"keyword": "Anomaly Detection", "relevance_score": 0.85}],
|
||||||
|
"fine_grained": [{"keyword": "Transformer Architecture", "relevance_score": 0.95}, {"keyword": "Sensor Fusion", "relevance_score": 0.82}]
|
||||||
|
}
|
||||||
|
|
||||||
|
Return ONLY the JSON object, nothing else.
|
||||||
|
"""
|
||||||
|
SIMPLE_WEBSITE_PROMPT = """
|
||||||
|
You are a technology scout and scientific analyst. The input is text scraped from a webpage (using BeautifulSoup or similar). Your goal: extract keywords into three hierarchical levels, just like the text prompt, but with extra care to ignore website boilerplate.
|
||||||
|
|
||||||
|
**Ignore:**
|
||||||
|
- Navigation menus, headers/footers, cookie banners, legal disclaimers, copyright notices.
|
||||||
|
- Generic marketing language, calls-to-action, contact details, login/signup content.
|
||||||
|
- Repeated site templates or boilerplate.
|
||||||
|
|
||||||
|
**Focus only on:**
|
||||||
|
- Technologies, research areas, scientific methods, products, applications, industrial sectors, materials, standards, diseases, engineering disciplines, innovation domains.
|
||||||
|
- Prefer canonical scientific terms over marketing buzzwords (e.g., "Large Language Models" instead of "AI Assistant").
|
||||||
|
|
||||||
|
**Hierarchy and relevance scores** are the same as in the text prompt (broad → coarse → fine, scores 0.0–1.0).
|
||||||
|
|
||||||
|
**Output schema (JSON only):**
|
||||||
|
'''{"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],"coarse_grained": [...],"fine_grained": [...]}'''
|
||||||
|
|
||||||
|
**Example (company website):**
|
||||||
|
Input: Stripe provides payment infrastructure for businesses, supporting processing, billing, fraud prevention, and global commerce.
|
||||||
|
Output:
|
||||||
|
{"broad_keywords": [{"keyword": "Financial Technology", "relevance_score": 0.98}, {"keyword": "Business Services", "relevance_score": 0.91}],"coarse_grained": [{"keyword": "Payment Processing", "relevance_score": 0.97}, {"keyword": "Digital Payments", "relevance_score": 0.95}],"fine_grained": [{"keyword": "Stripe Platform", "relevance_score": 0.99}, {"keyword": "Fraud Prevention", "relevance_score": 0.91}]}
|
||||||
|
|
||||||
|
**Return ONLY the JSON object, nothing else.**
|
||||||
|
- Nno leading/trailing spaces, newlines, or any text before or after. NO IDENTATION, justa stringified JSON
|
||||||
|
"""
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
REST API for persons / authors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||||
|
from uvicorn.protocols.utils import ClientDisconnected
|
||||||
|
|
||||||
|
from . import logic
|
||||||
|
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
prefix="/api/inse-service",
|
||||||
|
tags=["Keywords"],
|
||||||
|
responses={404: {"description": "Not found"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@router.websocket("/keywords/extract/ws")
|
||||||
|
async def extract_keywords_ws(websocket: WebSocket):
|
||||||
|
await websocket.accept()
|
||||||
|
|
||||||
|
disconnected = asyncio.Event()
|
||||||
|
extraction_task: asyncio.Task | None = None
|
||||||
|
|
||||||
|
async def emit(event: dict):
|
||||||
|
if disconnected.is_set():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await websocket.send_json(event)
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
|
||||||
|
async def safe_send(payload: dict):
|
||||||
|
if disconnected.is_set():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await websocket.send_json(payload)
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw = await websocket.receive_json()
|
||||||
|
request = KeywordsRequest(**raw)
|
||||||
|
|
||||||
|
extraction_task = asyncio.create_task(
|
||||||
|
logic.extract_keywords_stream_enriched(
|
||||||
|
query=request.query,
|
||||||
|
mode=request.mode,
|
||||||
|
limit=request.limit,
|
||||||
|
emit=emit,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await extraction_task
|
||||||
|
|
||||||
|
await safe_send({
|
||||||
|
"type": "completed",
|
||||||
|
"result": result.model_dump(),
|
||||||
|
})
|
||||||
|
|
||||||
|
except (WebSocketDisconnect, ClientDisconnected):
|
||||||
|
disconnected.set()
|
||||||
|
logger.info("Client disconnected from keyword extraction ws")
|
||||||
|
print("Client disconnected from keyword extraction ws")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
disconnected.set()
|
||||||
|
logger.exception("Error in keyword extraction ws")
|
||||||
|
await safe_send({
|
||||||
|
"type": "error",
|
||||||
|
"message": str(e),
|
||||||
|
})
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if extraction_task is not None and not extraction_task.done():
|
||||||
|
extraction_task.cancel()
|
||||||
|
try:
|
||||||
|
await extraction_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
if websocket.application_state.name != "DISCONNECTED":
|
||||||
|
await websocket.close()
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/keywords/extract",
|
||||||
|
operation_id="extractKeywords",
|
||||||
|
response_model=ExtractedKeywordsResponse,
|
||||||
|
summary="Extracts keywords from text.",
|
||||||
|
response_model_exclude_none=True,
|
||||||
|
)
|
||||||
|
async def extract_keywords(
|
||||||
|
request: Annotated[
|
||||||
|
KeywordsRequest,
|
||||||
|
Body(description="Input text for keyword extraction")
|
||||||
|
],
|
||||||
|
|
||||||
|
):
|
||||||
|
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
|
||||||
@@ -24,7 +24,7 @@ from inse.exceptions import (
|
|||||||
)
|
)
|
||||||
from inse.funders.service import router as funders_service_router
|
from inse.funders.service import router as funders_service_router
|
||||||
from inse.projects.router import router as projects_router
|
from inse.projects.router import router as projects_router
|
||||||
from inse.university_ranking.router import router as university_ranking_router
|
from inse.university_ranking.service import router as university_ranking_router
|
||||||
|
|
||||||
# caching
|
# caching
|
||||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||||
@@ -33,6 +33,7 @@ from inse.topics.service import router as topics_service_router
|
|||||||
from inse.works.service import router as works_service_router
|
from inse.works.service import router as works_service_router
|
||||||
from inse.news.service import router as news_service_router
|
from inse.news.service import router as news_service_router
|
||||||
from inse.patents.service import router as patents_service_router
|
from inse.patents.service import router as patents_service_router
|
||||||
|
from inse.keywords.service import router as keywords_service_router
|
||||||
|
|
||||||
from inse.auth.router import router as auth_router
|
from inse.auth.router import router as auth_router
|
||||||
from inse.account_management.router import router as account_management_router
|
from inse.account_management.router import router as account_management_router
|
||||||
@@ -45,7 +46,14 @@ from inse.auth.service import create_predefined_accounts
|
|||||||
from . import config
|
from . import config
|
||||||
|
|
||||||
from .service import router as service_router
|
from .service import router as service_router
|
||||||
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
|
from inse.patents.org.service import router as org_patents_router
|
||||||
|
from inse.patents.service import (
|
||||||
|
institution_patents_router,
|
||||||
|
patents_router as patents_all_router,
|
||||||
|
router as patents_service_router,
|
||||||
|
)
|
||||||
|
|
||||||
|
from inse.works.purpose_router import router as works_purpose_router
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -73,8 +81,11 @@ app = FastAPI(
|
|||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
)
|
)
|
||||||
app.include_router(collaboration_network_router)
|
app.include_router(collaboration_network_router)
|
||||||
|
app.include_router(institution_patents_router)
|
||||||
|
app.include_router(org_patents_router)
|
||||||
app.include_router(institutions_router)
|
app.include_router(institutions_router)
|
||||||
app.include_router(topics_service_router)
|
app.include_router(topics_service_router)
|
||||||
|
app.include_router(works_purpose_router)
|
||||||
app.include_router(works_service_router)
|
app.include_router(works_service_router)
|
||||||
app.include_router(persons_service_router)
|
app.include_router(persons_service_router)
|
||||||
app.include_router(funders_service_router)
|
app.include_router(funders_service_router)
|
||||||
@@ -84,6 +95,7 @@ app.include_router(patents_service_router)
|
|||||||
app.include_router(university_ranking_router)
|
app.include_router(university_ranking_router)
|
||||||
app.include_router(projects_router)
|
app.include_router(projects_router)
|
||||||
app.include_router(patents_all_router)
|
app.include_router(patents_all_router)
|
||||||
|
app.include_router(keywords_service_router)
|
||||||
|
|
||||||
app.include_router(service_router)
|
app.include_router(service_router)
|
||||||
|
|
||||||
@@ -91,6 +103,7 @@ app.include_router(auth_router)
|
|||||||
app.include_router(account_management_router)
|
app.include_router(account_management_router)
|
||||||
app.include_router(organization_management_router)
|
app.include_router(organization_management_router)
|
||||||
|
|
||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
ETagCacheMiddleware,
|
ETagCacheMiddleware,
|
||||||
ttl=300, # 5 minutes expiration time
|
ttl=300, # 5 minutes expiration time
|
||||||
@@ -107,6 +120,7 @@ app.add_middleware(
|
|||||||
|
|
||||||
# exception handlers
|
# exception handlers
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(NotFoundException)
|
@app.exception_handler(NotFoundException)
|
||||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||||
@@ -115,13 +129,18 @@ async def handle_not_found(request: Request, exc: NotFoundException):
|
|||||||
@app.exception_handler(ElasticsearchException)
|
@app.exception_handler(ElasticsearchException)
|
||||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
return JSONResponse(
|
||||||
|
status_code=502, content={"message": "Search service temporarily unavailable"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(MissingApiKeyError)
|
@app.exception_handler(MissingApiKeyError)
|
||||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||||
logger.error("Configuration error: %s", str(exc))
|
logger.error("Configuration error: %s", str(exc))
|
||||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
return JSONResponse(
|
||||||
|
status_code=503,
|
||||||
|
content={"message": str(exc) or "Search service is not configured"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(UpstreamAPIException)
|
@app.exception_handler(UpstreamAPIException)
|
||||||
|
|||||||
@@ -34,9 +34,14 @@ class ESIndex(StrEnum):
|
|||||||
OPENALEX_AUTHORS = "openalex-authors"
|
OPENALEX_AUTHORS = "openalex-authors"
|
||||||
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
OPENALEX_INSTITUTIONS = "openalex-institutions"
|
||||||
OPENALEX_PUBLICATIONS = "openalex-publications"
|
OPENALEX_PUBLICATIONS = "openalex-publications"
|
||||||
|
OPENALEX_COUNTRIES = "openalex-countries"
|
||||||
|
OPENALEX_CONTINENTS = "openalex-continents"
|
||||||
|
OPENALEX_TOPICS = "openalex-topics"
|
||||||
|
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||||
|
|
||||||
EPO_INDEX = "epo_index_1.0"
|
EPO_INDEX = "epo_index_1.0"
|
||||||
USPTO_INDEX = "uspto_patents_3.0"
|
USPTO_INDEX = "uspto_patents_3.0"
|
||||||
|
ORG_PATENTS = "org_patents"
|
||||||
|
|
||||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||||
|
|||||||
Binary file not shown.
@@ -39,6 +39,7 @@ class Topic(BaseModel):
|
|||||||
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
|
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
|
||||||
subfield: Optional[TopicSubfield] = None
|
subfield: Optional[TopicSubfield] = None
|
||||||
var_field: Optional[TopicField] = Field(default=None, alias="field")
|
var_field: Optional[TopicField] = Field(default=None, alias="field")
|
||||||
|
field: Optional[TopicField] = Field(default=None)
|
||||||
domain: Optional[TopicDomain] = None
|
domain: Optional[TopicDomain] = None
|
||||||
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
|
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
|
||||||
cited_by_count: Optional[StrictInt] = None
|
cited_by_count: Optional[StrictInt] = None
|
||||||
|
|||||||
@@ -33,11 +33,12 @@ class WorkTopic(BaseModel):
|
|||||||
""" # noqa: E501
|
""" # noqa: E501
|
||||||
id: Optional[StrictStr] = None
|
id: Optional[StrictStr] = None
|
||||||
display_name: Optional[StrictStr] = None
|
display_name: Optional[StrictStr] = None
|
||||||
|
description: Optional[StrictStr] = None
|
||||||
score: Optional[Union[StrictFloat, StrictInt]] = None
|
score: Optional[Union[StrictFloat, StrictInt]] = None
|
||||||
subfield: Optional[WorkTopicSubfield] = None
|
subfield: Optional[WorkTopicSubfield] = None
|
||||||
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
|
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
|
||||||
domain: Optional[WorkTopicDomain] = None
|
domain: Optional[WorkTopicDomain] = None
|
||||||
__properties: ClassVar[List[str]] = ["id", "display_name", "score", "subfield", "field", "domain"]
|
__properties: ClassVar[List[str]] = ["id", "display_name", "description", "score", "subfield", "field", "domain"]
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
validate_by_name=True,
|
validate_by_name=True,
|
||||||
@@ -101,6 +102,7 @@ class WorkTopic(BaseModel):
|
|||||||
_obj = cls.model_validate({
|
_obj = cls.model_validate({
|
||||||
"id": obj.get("id"),
|
"id": obj.get("id"),
|
||||||
"display_name": obj.get("display_name"),
|
"display_name": obj.get("display_name"),
|
||||||
|
"description": obj.get("description"),
|
||||||
"score": obj.get("score"),
|
"score": obj.get("score"),
|
||||||
"subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None,
|
"subfield": WorkTopicSubfield.from_dict(obj["subfield"]) if obj.get("subfield") is not None else None,
|
||||||
"field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None,
|
"field": WorkTopicField.from_dict(obj["field"]) if obj.get("field") is not None else None,
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
|
|||||||
|
|
||||||
from ..integrations import elasticsearch, llm
|
from ..integrations import elasticsearch, llm
|
||||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
from ..topics.logic import vector_search_topics
|
||||||
|
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
|
|||||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||||
TOPIC_NUM_CANDIDATES = 100
|
TOPIC_NUM_CANDIDATES = 100
|
||||||
TOPIC_SIMILARITY = 0.5
|
TOPIC_SIMILARITY = 0.5
|
||||||
|
TOPIC_MATCHES_PER_KEYWORD = 1
|
||||||
|
|
||||||
KEYWORD_LIMIT = 6
|
KEYWORD_LIMIT = 6
|
||||||
KEYWORD_CONTENT_CHARS = 4000
|
KEYWORD_CONTENT_CHARS = 4000
|
||||||
KEYWORD_SYSTEM_PROMPT = """\
|
KEYWORD_SYSTEM_PROMPT = """\
|
||||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||||
|
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||||
|
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||||
|
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||||
|
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
RELATED_BLOCK_SIZE = 5
|
RELATED_BLOCK_SIZE = 5
|
||||||
@@ -80,7 +86,14 @@ async def search_news(
|
|||||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||||
exact_query = {
|
exact_query = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": [{"match": {"full_content": query_text}}],
|
"must": [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": query_text,
|
||||||
|
"fields": ["maintitle^2", "full_content"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
"filter": clauses,
|
"filter": clauses,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -240,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
source = response.get("_source", {})
|
source = response.get("_source", {})
|
||||||
|
|
||||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
|
||||||
keywords = await _get_article_keywords(
|
keywords = await _get_article_keywords(
|
||||||
news_id,
|
news_id,
|
||||||
postproc_id,
|
postproc_id,
|
||||||
@@ -248,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
source.get("maintitle"),
|
source.get("maintitle"),
|
||||||
source.get("full_content"),
|
source.get("full_content"),
|
||||||
)
|
)
|
||||||
|
topics = await _match_topics_for_keywords(keywords)
|
||||||
|
|
||||||
return NewsArticleDetail(
|
return NewsArticleDetail(
|
||||||
id=response.get("_id"),
|
id=response.get("_id"),
|
||||||
@@ -258,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
|||||||
full_content=source.get("full_content"),
|
full_content=source.get("full_content"),
|
||||||
relevant=relevant,
|
relevant=relevant,
|
||||||
authors=await _build_mentioned_persons(authors),
|
authors=await _build_mentioned_persons(authors),
|
||||||
topics=topics,
|
|
||||||
keywords=keywords,
|
keywords=keywords,
|
||||||
|
topics=topics,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
|
||||||
query = " ".join(
|
|
||||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
|
||||||
).strip()
|
|
||||||
if not query:
|
|
||||||
return []
|
|
||||||
|
|
||||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
|
||||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
|
||||||
|
|
||||||
|
|
||||||
async def _get_article_keywords(
|
async def _get_article_keywords(
|
||||||
news_id: str,
|
news_id: str,
|
||||||
postproc_id: str | None,
|
postproc_id: str | None,
|
||||||
@@ -308,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(raw)
|
parsed = json.loads(raw)
|
||||||
candidates = parsed if isinstance(parsed, list) else []
|
if isinstance(parsed, list):
|
||||||
|
candidates = parsed
|
||||||
|
elif isinstance(parsed, dict):
|
||||||
|
candidates = parsed.get("keywords", [])
|
||||||
|
else:
|
||||||
|
candidates = []
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
candidates = re.split(r"[,\n]", raw)
|
candidates = re.split(r"[,\n]", raw)
|
||||||
|
|
||||||
@@ -343,6 +350,35 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
|
|||||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||||
|
|
||||||
|
|
||||||
|
async def _match_topics_for_keywords(keywords: list) -> list:
|
||||||
|
matched = []
|
||||||
|
seen_ids = set()
|
||||||
|
|
||||||
|
for keyword in keywords:
|
||||||
|
try:
|
||||||
|
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD)
|
||||||
|
except Exception:
|
||||||
|
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
|
||||||
|
continue
|
||||||
|
|
||||||
|
for topic in response.results or []:
|
||||||
|
if not topic.id or topic.id in seen_ids:
|
||||||
|
continue
|
||||||
|
seen_ids.add(topic.id)
|
||||||
|
matched.append(
|
||||||
|
MatchedTopic(
|
||||||
|
id=topic.id,
|
||||||
|
display_name=topic.display_name,
|
||||||
|
subfield_name=topic.subfield.display_name if topic.subfield else None,
|
||||||
|
field_name=topic.var_field.display_name if topic.var_field else None,
|
||||||
|
domain_name=topic.domain.display_name if topic.domain else None,
|
||||||
|
source_keyword=keyword,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return matched
|
||||||
|
|
||||||
|
|
||||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||||
try:
|
try:
|
||||||
from ..util import get_model
|
from ..util import get_model
|
||||||
|
|||||||
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
|
|||||||
person_id: Optional[str] = None
|
person_id: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class MatchedTopic(BaseModel):
|
||||||
|
id: Optional[str] = None
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
subfield_name: Optional[str] = None
|
||||||
|
field_name: Optional[str] = None
|
||||||
|
domain_name: Optional[str] = None
|
||||||
|
source_keyword: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class NewsArticleDetail(NewsArticle):
|
class NewsArticleDetail(NewsArticle):
|
||||||
full_content: Optional[str] = None
|
full_content: Optional[str] = None
|
||||||
relevant: Optional[bool] = None
|
relevant: Optional[bool] = None
|
||||||
authors: List[MentionedPerson] = []
|
authors: List[MentionedPerson] = []
|
||||||
topics: List[str] = []
|
|
||||||
keywords: List[str] = []
|
keywords: List[str] = []
|
||||||
|
topics: List[MatchedTopic] = []
|
||||||
|
|
||||||
|
|
||||||
class NewsPage(BaseModel):
|
class NewsPage(BaseModel):
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status
|
|||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
from inse.auth import service as auth_service
|
from inse.auth import service as auth_service
|
||||||
from inse.auth.model import AccessToken
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.database import get_session
|
from inse.database import get_session
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ async def get_organizations(
|
|||||||
page_size: int = Query(default=25, ge=1, le=100),
|
page_size: int = Query(default=25, ge=1, le=100),
|
||||||
offset: Optional[int] = Query(default=None, ge=0),
|
offset: Optional[int] = Query(default=None, ge=0),
|
||||||
session: Session = Depends(get_session),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> OrganizationPage:
|
) -> OrganizationPage:
|
||||||
return service.get_organizations(
|
return service.get_organizations(
|
||||||
session=session,
|
session=session,
|
||||||
@@ -46,7 +46,7 @@ async def get_organizations(
|
|||||||
async def create_organization(
|
async def create_organization(
|
||||||
payload: CreateOrganizationRequest,
|
payload: CreateOrganizationRequest,
|
||||||
session: Session = Depends(get_session),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> OrganizationProfile:
|
) -> OrganizationProfile:
|
||||||
return service.create_organization(session, access_token, payload)
|
return service.create_organization(session, access_token, payload)
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ async def update_organization(
|
|||||||
organization_id: uuid.UUID,
|
organization_id: uuid.UUID,
|
||||||
payload: UpdateOrganizationRequest,
|
payload: UpdateOrganizationRequest,
|
||||||
session: Session = Depends(get_session),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> OrganizationProfile:
|
) -> OrganizationProfile:
|
||||||
return service.update_organization(
|
return service.update_organization(
|
||||||
session, access_token, organization_id, payload
|
session, access_token, organization_id, payload
|
||||||
@@ -75,7 +75,7 @@ async def update_organization(
|
|||||||
async def delete_organization(
|
async def delete_organization(
|
||||||
organization_id: uuid.UUID,
|
organization_id: uuid.UUID,
|
||||||
session: Session = Depends(get_session),
|
session: Session = Depends(get_session),
|
||||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
) -> Response:
|
) -> Response:
|
||||||
service.delete_organization(session, access_token, organization_id)
|
service.delete_organization(session, access_token, organization_id)
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Optional
|
|||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
from sqlmodel import Session, func, select
|
from sqlmodel import Session, func, select
|
||||||
|
|
||||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
|
||||||
|
|
||||||
from .model import (
|
from .model import (
|
||||||
CreateOrganizationRequest,
|
CreateOrganizationRequest,
|
||||||
@@ -14,7 +14,7 @@ from .model import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _require_super_admin(access_token: AccessToken) -> None:
|
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
|
||||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
@@ -73,6 +73,7 @@ def _member_counts(
|
|||||||
.where(
|
.where(
|
||||||
Account.organization_id.in_(organization_ids),
|
Account.organization_id.in_(organization_ids),
|
||||||
Account.deleted == False, # noqa: E712
|
Account.deleted == False, # noqa: E712
|
||||||
|
Account.activated == True, # noqa: E712
|
||||||
)
|
)
|
||||||
.group_by(Account.organization_id)
|
.group_by(Account.organization_id)
|
||||||
).all()
|
).all()
|
||||||
@@ -91,9 +92,24 @@ def _to_profile(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _deactivate_organization_accounts(
|
||||||
|
session: Session, organization_id: uuid.UUID
|
||||||
|
) -> None:
|
||||||
|
accounts = session.exec(
|
||||||
|
select(Account).where(
|
||||||
|
Account.organization_id == organization_id,
|
||||||
|
Account.activated == True, # noqa: E712
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
for account in accounts:
|
||||||
|
account.activated = False
|
||||||
|
account.epoch += 1
|
||||||
|
session.add(account)
|
||||||
|
|
||||||
|
|
||||||
def get_organizations(
|
def get_organizations(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
page: int,
|
page: int,
|
||||||
page_size: int,
|
page_size: int,
|
||||||
offset: Optional[int] = None,
|
offset: Optional[int] = None,
|
||||||
@@ -129,7 +145,7 @@ def get_organizations(
|
|||||||
|
|
||||||
def create_organization(
|
def create_organization(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
payload: CreateOrganizationRequest,
|
payload: CreateOrganizationRequest,
|
||||||
) -> OrganizationProfile:
|
) -> OrganizationProfile:
|
||||||
_require_super_admin(access_token)
|
_require_super_admin(access_token)
|
||||||
@@ -148,7 +164,7 @@ def create_organization(
|
|||||||
|
|
||||||
def update_organization(
|
def update_organization(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
organization_id: uuid.UUID,
|
organization_id: uuid.UUID,
|
||||||
payload: UpdateOrganizationRequest,
|
payload: UpdateOrganizationRequest,
|
||||||
) -> OrganizationProfile:
|
) -> OrganizationProfile:
|
||||||
@@ -162,6 +178,8 @@ def update_organization(
|
|||||||
if payload.other_inst_id is not None:
|
if payload.other_inst_id is not None:
|
||||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||||
if payload.deleted is not None:
|
if payload.deleted is not None:
|
||||||
|
if payload.deleted and not organization.deleted:
|
||||||
|
_deactivate_organization_accounts(session, organization.id)
|
||||||
organization.deleted = payload.deleted
|
organization.deleted = payload.deleted
|
||||||
|
|
||||||
session.add(organization)
|
session.add(organization)
|
||||||
@@ -173,11 +191,13 @@ def update_organization(
|
|||||||
|
|
||||||
def delete_organization(
|
def delete_organization(
|
||||||
session: Session,
|
session: Session,
|
||||||
access_token: AccessToken,
|
access_token: AccessTokenMetadata,
|
||||||
organization_id: uuid.UUID,
|
organization_id: uuid.UUID,
|
||||||
) -> None:
|
) -> None:
|
||||||
_require_super_admin(access_token)
|
_require_super_admin(access_token)
|
||||||
organization = _get_organization_or_404(session, organization_id)
|
organization = _get_organization_or_404(session, organization_id)
|
||||||
|
if not organization.deleted:
|
||||||
|
_deactivate_organization_accounts(session, organization.id)
|
||||||
organization.deleted = True
|
organization.deleted = True
|
||||||
session.add(organization)
|
session.add(organization)
|
||||||
session.commit()
|
session.commit()
|
||||||
|
|||||||
@@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session):
|
|||||||
assert session.get(Organization, created.id).deleted is True
|
assert session.get(Organization, created.id).deleted is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||||
|
organization = Organization(name="Organization to delete")
|
||||||
|
session.add(organization)
|
||||||
|
session.flush()
|
||||||
|
active_account = Account(
|
||||||
|
email="active-delete@example.org",
|
||||||
|
name="Active",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
epoch=3,
|
||||||
|
)
|
||||||
|
inactive_account = Account(
|
||||||
|
email="inactive-delete@example.org",
|
||||||
|
name="Inactive",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
activated=False,
|
||||||
|
epoch=5,
|
||||||
|
)
|
||||||
|
session.add(active_account)
|
||||||
|
session.add(inactive_account)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
service.delete_organization(
|
||||||
|
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
|
||||||
|
)
|
||||||
|
|
||||||
|
session.refresh(active_account)
|
||||||
|
session.refresh(inactive_account)
|
||||||
|
assert active_account.activated is False
|
||||||
|
assert active_account.epoch == 4
|
||||||
|
assert inactive_account.activated is False
|
||||||
|
assert inactive_account.epoch == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||||
|
organization = Organization(name="Organization to update")
|
||||||
|
session.add(organization)
|
||||||
|
session.flush()
|
||||||
|
account = Account(
|
||||||
|
email="active-update@example.org",
|
||||||
|
name="Active",
|
||||||
|
password_hash="hash",
|
||||||
|
organization_id=organization.id,
|
||||||
|
)
|
||||||
|
session.add(account)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
service.update_organization(
|
||||||
|
session,
|
||||||
|
token(UserRole.SUPER_ADMIN, organization.id),
|
||||||
|
organization.id,
|
||||||
|
UpdateOrganizationRequest(deleted=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
session.refresh(account)
|
||||||
|
assert account.activated is False
|
||||||
|
assert account.epoch == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||||
def test_only_superadmin_can_create_organizations(session, role):
|
def test_only_superadmin_can_create_organizations(session, role):
|
||||||
organization = Organization(name="Scope")
|
organization = Organization(name="Scope")
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Global patent listing."""
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Business logic for global patent listing."""
|
||||||
|
import asyncio
|
||||||
|
from datetime import datetime
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from starlette.status import HTTP_404_NOT_FOUND
|
||||||
|
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||||
|
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
|
||||||
|
from inse.patents.common import model
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
from inse.patents.common.parsing import (
|
||||||
|
enrich_patents_classifications,
|
||||||
|
parse_epo_hits,
|
||||||
|
parse_uspto_hits,
|
||||||
|
)
|
||||||
|
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
|
||||||
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
|
from inse.patents.search_client import PatentSearchClient
|
||||||
|
|
||||||
|
async def get_all_patents(
|
||||||
|
page: int = 0,
|
||||||
|
size: int = 10,
|
||||||
|
search: str | None = None,
|
||||||
|
source: str | None = None,
|
||||||
|
sort_by: str = "date",
|
||||||
|
sort_direction: str = "desc",
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
|
client: PatentSearchClient | None = None,
|
||||||
|
ipc_client: IpcSearchClient | None = None,
|
||||||
|
) -> model.AllPatentsResponse:
|
||||||
|
all_patents_client = AllPatentsSearchClient()
|
||||||
|
ipc_search_client = ipc_client or IpcSearchClient()
|
||||||
|
|
||||||
|
try:
|
||||||
|
if source == "EPO":
|
||||||
|
epo_data = await all_patents_client.search_epo(
|
||||||
|
all_patents_client.epo_query(page, size, search, sort_direction, year_from, year_to)
|
||||||
|
)
|
||||||
|
patents = parse_epo_hits(epo_data)
|
||||||
|
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
|
||||||
|
elif source == "USPTO":
|
||||||
|
uspto_data = await all_patents_client.search_uspto(
|
||||||
|
all_patents_client.uspto_query(page, size, search, sort_direction, year_from, year_to)
|
||||||
|
)
|
||||||
|
patents = parse_uspto_hits(uspto_data)
|
||||||
|
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
|
||||||
|
else:
|
||||||
|
half = size // 2
|
||||||
|
epo_data, uspto_data = await asyncio.gather(
|
||||||
|
all_patents_client.search_epo(
|
||||||
|
all_patents_client.epo_query(page, half, search, sort_direction, year_from, year_to)
|
||||||
|
),
|
||||||
|
all_patents_client.search_uspto(
|
||||||
|
all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||||
|
total = (
|
||||||
|
epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
+ uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
except MissingApiKeyError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Patent search is not configured.",
|
||||||
|
) from exc
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_502_BAD_GATEWAY,
|
||||||
|
detail="Patent search request failed.",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
await enrich_patents_classifications(patents, ipc_search_client)
|
||||||
|
|
||||||
|
return model.AllPatentsResponse(
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
patents=patents,
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Business logic for global patent listing."""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from inse.patents.all import logic
|
||||||
|
from inse.patents.common import model
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/patents",
|
||||||
|
operation_id="getAllPatents",
|
||||||
|
response_model=model.AllPatentsResponse,
|
||||||
|
summary="Get all patents with pagination and search.",
|
||||||
|
)
|
||||||
|
async def get_all_patents(
|
||||||
|
page: int = 0,
|
||||||
|
size: int = 10,
|
||||||
|
search: str | None = None,
|
||||||
|
source: str | None = None,
|
||||||
|
sort_by: str = "date",
|
||||||
|
sort_direction: str = "desc",
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
|
):
|
||||||
|
return await logic.get_all_patents(
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
search=search,
|
||||||
|
source=source,
|
||||||
|
sort_by=sort_by,
|
||||||
|
sort_direction=sort_direction,
|
||||||
|
year_from=year_from,
|
||||||
|
year_to=year_to,
|
||||||
|
)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Patent lookup by inventor."""
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
"""Business logic for patent lookup by inventor."""
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||||
|
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
|
||||||
|
from inse.patents.authors.name_matching import name_matches
|
||||||
|
from inse.patents.common import model
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
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
|
||||||
|
from inse.models.openalex.author import Author
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_patents_by_author_id(
|
||||||
|
author_id: str,
|
||||||
|
client: PatentSearchClient | None = None,
|
||||||
|
ipc_client: IpcSearchClient | None = None,
|
||||||
|
) -> model.PatentsByAuthorResponse:
|
||||||
|
search_client = client or PatentSearchClient()
|
||||||
|
ipc_search_client = ipc_client or IpcSearchClient()
|
||||||
|
|
||||||
|
author = _get_author(author_id)
|
||||||
|
if not author:
|
||||||
|
return model.PatentsByAuthorResponse(
|
||||||
|
author_id=author_id,
|
||||||
|
author_name=None,
|
||||||
|
patent_count=0,
|
||||||
|
patents=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
author_name = author.display_name
|
||||||
|
last_name = _extract_last_name(author_name)
|
||||||
|
first_name = _extract_first_name(author_name)
|
||||||
|
|
||||||
|
if not last_name:
|
||||||
|
return model.PatentsByAuthorResponse(
|
||||||
|
author_id=author_id,
|
||||||
|
author_name=author_name,
|
||||||
|
patent_count=0,
|
||||||
|
patents=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
epo_data, uspto_data = await _search_both_indices(
|
||||||
|
search_client, last_name, first_name
|
||||||
|
)
|
||||||
|
except MissingApiKeyError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Patent search is not configured.",
|
||||||
|
) from exc
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_502_BAD_GATEWAY,
|
||||||
|
detail="Patent search request failed.",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||||
|
|
||||||
|
if first_name and last_name:
|
||||||
|
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||||
|
|
||||||
|
all_patents = deduplicate_patents(all_patents)
|
||||||
|
await enrich_patents_classifications(all_patents, ipc_search_client)
|
||||||
|
|
||||||
|
return model.PatentsByAuthorResponse(
|
||||||
|
author_id=author_id,
|
||||||
|
author_name=author_name,
|
||||||
|
patent_count=len(all_patents),
|
||||||
|
patents=all_patents,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _search_both_indices(client, last_name, first_name):
|
||||||
|
return await asyncio.gather(
|
||||||
|
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||||
|
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _filter_patents_by_name(
|
||||||
|
patents: list[model.PatentEntry],
|
||||||
|
first_name: str,
|
||||||
|
last_name: str,
|
||||||
|
) -> list[model.PatentEntry]:
|
||||||
|
return [
|
||||||
|
patent for patent in patents
|
||||||
|
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _get_author(author_id: str) -> Author | None:
|
||||||
|
short_id = author_id.replace("https://openalex.org/", "")
|
||||||
|
result = person_logic.search_persons(author_id=short_id)
|
||||||
|
return result.results[0] if result.results else None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_last_name(name: str | None) -> str | None:
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
parts = name.strip().split()
|
||||||
|
return parts[-1] if parts else None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_first_name(name: str | None) -> str | None:
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
parts = name.strip().split()
|
||||||
|
return parts[0] if len(parts) > 1 else None
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""Inventor name normalization and matching."""
|
||||||
|
import re
|
||||||
|
|
||||||
|
from inse.patents.common.text_normalization import (
|
||||||
|
name_token_variants,
|
||||||
|
normalize_name_part,
|
||||||
|
patent_transliteration_expansions,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def tokens_equal(
|
||||||
|
left: str | None,
|
||||||
|
right: str | None,
|
||||||
|
*,
|
||||||
|
allow_initial: bool = True,
|
||||||
|
) -> bool:
|
||||||
|
left_variants = name_token_variants(left)
|
||||||
|
right_variants = name_token_variants(right)
|
||||||
|
if not left_variants or not right_variants:
|
||||||
|
return False
|
||||||
|
if left_variants & right_variants:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if not allow_initial:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return _initial_tokens_match(left, right)
|
||||||
|
|
||||||
|
|
||||||
|
def _initial_letter(token: str | None) -> str | None:
|
||||||
|
normalized = normalize_name_part(token)
|
||||||
|
if len(normalized) == 1 and normalized.isalpha():
|
||||||
|
return normalized
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
|
||||||
|
left_initial = _initial_letter(left)
|
||||||
|
right_initial = _initial_letter(right)
|
||||||
|
left_full = normalize_name_part(left)
|
||||||
|
right_full = normalize_name_part(right)
|
||||||
|
|
||||||
|
if left_initial and right_full and len(right_full) > 1:
|
||||||
|
return right_full.startswith(left_initial)
|
||||||
|
if right_initial and left_full and len(left_full) > 1:
|
||||||
|
return left_full.startswith(right_initial)
|
||||||
|
if left_initial and right_initial:
|
||||||
|
return left_initial == right_initial
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _inventor_first_token(inventor_name: str) -> str:
|
||||||
|
if "," in inventor_name:
|
||||||
|
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
|
||||||
|
return first_part.split()[0] if first_part else ""
|
||||||
|
parts = inventor_name.split()
|
||||||
|
return parts[0] if parts else ""
|
||||||
|
|
||||||
|
|
||||||
|
def first_name_match_kind(
|
||||||
|
inventor_name: str,
|
||||||
|
first_name: str,
|
||||||
|
last_name: str,
|
||||||
|
) -> str:
|
||||||
|
if not name_matches(inventor_name, first_name, last_name):
|
||||||
|
return "none"
|
||||||
|
|
||||||
|
inventor_first = _inventor_first_token(inventor_name)
|
||||||
|
if tokens_equal(inventor_first, first_name, allow_initial=False):
|
||||||
|
return "full"
|
||||||
|
return "initial"
|
||||||
|
|
||||||
|
|
||||||
|
def search_name_variants(value: str | None) -> list[str]:
|
||||||
|
if not value or not value.strip():
|
||||||
|
return []
|
||||||
|
|
||||||
|
seen: set[str] = set()
|
||||||
|
ordered: list[str] = []
|
||||||
|
|
||||||
|
def _add(candidate: str) -> None:
|
||||||
|
key = candidate.casefold()
|
||||||
|
if candidate.strip() and key not in seen:
|
||||||
|
seen.add(key)
|
||||||
|
ordered.append(candidate.strip())
|
||||||
|
|
||||||
|
_add(value.strip())
|
||||||
|
|
||||||
|
normalized = normalize_name_part(value)
|
||||||
|
if normalized:
|
||||||
|
_add(normalized.title())
|
||||||
|
|
||||||
|
for variant in name_token_variants(value):
|
||||||
|
_add(variant.title())
|
||||||
|
|
||||||
|
for variant in patent_transliteration_expansions(normalized):
|
||||||
|
_add(variant.title())
|
||||||
|
|
||||||
|
if normalized and len(normalized) > 1:
|
||||||
|
_add(normalized[0].upper())
|
||||||
|
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
|
||||||
|
if not inventor_name or not last_name:
|
||||||
|
return False
|
||||||
|
|
||||||
|
name = inventor_name.strip()
|
||||||
|
|
||||||
|
if "," in name:
|
||||||
|
last_part, first_part = [p.strip() for p in name.split(",", 1)]
|
||||||
|
first_token = first_part.split()[0] if first_part else ""
|
||||||
|
return (
|
||||||
|
tokens_equal(last_part, last_name, allow_initial=False)
|
||||||
|
and bool(first_name)
|
||||||
|
and tokens_equal(first_token, first_name)
|
||||||
|
)
|
||||||
|
|
||||||
|
parts = name.split()
|
||||||
|
if len(parts) < 2:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return (
|
||||||
|
tokens_equal(parts[-1], last_name, allow_initial=False)
|
||||||
|
and bool(first_name)
|
||||||
|
and tokens_equal(parts[0], first_name)
|
||||||
|
)
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Elasticsearch query builders for inventor-based patent search."""
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from inse.patents.authors.name_matching import search_name_variants
|
||||||
|
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
|
||||||
|
|
||||||
|
|
||||||
|
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||||
|
variants = search_name_variants(name)
|
||||||
|
if len(variants) <= 1:
|
||||||
|
return {"match": {field: variants[0] if variants else name}}
|
||||||
|
return {
|
||||||
|
"bool": {
|
||||||
|
"should": [{"match": {field: variant}} for variant in variants],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class InventorSearchQueries:
|
||||||
|
def epo_query_by_inventor(
|
||||||
|
self,
|
||||||
|
last_name: str,
|
||||||
|
first_name: str | None = None,
|
||||||
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if first_name:
|
||||||
|
query = {
|
||||||
|
"nested": {
|
||||||
|
"path": "inventors_name_nested",
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"must": [
|
||||||
|
_match_name_field("inventors_name_nested.inventor", last_name),
|
||||||
|
_match_name_field("inventors_name_nested.inventor", first_name),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = {
|
||||||
|
"nested": {
|
||||||
|
"path": "inventors_name_nested",
|
||||||
|
"query": _match_name_field("inventors_name_nested.inventor", last_name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"sort": [
|
||||||
|
{"_score": {"order": "desc"}},
|
||||||
|
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||||
|
"_doc",
|
||||||
|
],
|
||||||
|
"_source": [
|
||||||
|
"doc_number",
|
||||||
|
"country",
|
||||||
|
"kind",
|
||||||
|
"date_publication",
|
||||||
|
"date_publication_year",
|
||||||
|
"application_number",
|
||||||
|
"application_filing_date",
|
||||||
|
"title_en",
|
||||||
|
"title_de",
|
||||||
|
"abstract",
|
||||||
|
"inventors_name",
|
||||||
|
"applicants_name",
|
||||||
|
"ipc",
|
||||||
|
"cpc",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
|
|
||||||
|
def uspto_query_by_inventor(
|
||||||
|
self,
|
||||||
|
last_name: str,
|
||||||
|
first_name: str | None = None,
|
||||||
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if first_name:
|
||||||
|
query = {
|
||||||
|
"nested": {
|
||||||
|
"path": "inventors",
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"must": [
|
||||||
|
_match_name_field("inventors.name", last_name),
|
||||||
|
_match_name_field("inventors.name", first_name),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = {
|
||||||
|
"nested": {
|
||||||
|
"path": "inventors",
|
||||||
|
"query": _match_name_field("inventors.name", last_name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"sort": [
|
||||||
|
{"_score": {"order": "desc"}},
|
||||||
|
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||||
|
"_doc",
|
||||||
|
],
|
||||||
|
"_source": [
|
||||||
|
"publication_number",
|
||||||
|
"country",
|
||||||
|
"publication_date",
|
||||||
|
"publication_year",
|
||||||
|
"application_number",
|
||||||
|
"application_date",
|
||||||
|
"application_type",
|
||||||
|
"title",
|
||||||
|
"abstract",
|
||||||
|
"inventors_names",
|
||||||
|
"assignees_orgs",
|
||||||
|
"ipcr",
|
||||||
|
"cpc",
|
||||||
|
"number_of_claims",
|
||||||
|
"status",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from inse.patents.authors import logic
|
||||||
|
from inse.patents.common import model
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{author_id}/patents",
|
||||||
|
operation_id="getPatentsByAuthor",
|
||||||
|
response_model=model.PatentsByAuthorResponse,
|
||||||
|
summary="Get patents matched to an author by name.",
|
||||||
|
)
|
||||||
|
async def get_patents_by_author(author_id: str):
|
||||||
|
return await logic.get_patents_by_author_id(author_id)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Shared patent infrastructure."""
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Base HTTP client for patent Elasticsearch indices."""
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from ... import config
|
||||||
|
|
||||||
|
EPO_INDEX = "epo_index_1.0"
|
||||||
|
USPTO_INDEX = "uspto_patents_3.0"
|
||||||
|
DEFAULT_SEARCH_SIZE = 100
|
||||||
|
|
||||||
|
|
||||||
|
class MissingApiKeyError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class BasePatentSearchClient:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str | None = None,
|
||||||
|
api_key: str | None = None,
|
||||||
|
timeout: float = 30.0,
|
||||||
|
transport: httpx.AsyncBaseTransport | None = None,
|
||||||
|
):
|
||||||
|
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||||
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
|
self.timeout = timeout
|
||||||
|
self.transport = transport
|
||||||
|
|
||||||
|
def _headers(self) -> dict[str, str]:
|
||||||
|
if not self.api_key:
|
||||||
|
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||||
|
return {
|
||||||
|
"Authorization": f"ApiKey {self.api_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return await self._search(EPO_INDEX, payload)
|
||||||
|
|
||||||
|
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return await self._search(USPTO_INDEX, payload)
|
||||||
|
|
||||||
|
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=self.timeout,
|
||||||
|
transport=self.transport,
|
||||||
|
) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"/{index}/_search",
|
||||||
|
headers=self._headers(),
|
||||||
|
json=payload,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class IpcClassification(BaseModel):
|
||||||
|
symbol: str
|
||||||
|
section: str | None = None
|
||||||
|
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
||||||
|
subclass: str | None = None
|
||||||
|
main_group: str | None = None
|
||||||
|
subgroup: str | None = None
|
||||||
|
|
||||||
|
model_config = ConfigDict(populate_by_name=True)
|
||||||
|
|
||||||
|
|
||||||
|
class PatentEntry(BaseModel):
|
||||||
|
patent_id: str
|
||||||
|
source: str
|
||||||
|
title: str | None = None
|
||||||
|
abstract: str | None = None
|
||||||
|
publication_date: str | None = None
|
||||||
|
publication_year: str | None = None
|
||||||
|
application_number: str | None = None
|
||||||
|
application_date: str | None = None
|
||||||
|
kind: str | None = None
|
||||||
|
application_type: str | None = None
|
||||||
|
number_of_claims: int | None = None
|
||||||
|
status: str | None = None
|
||||||
|
inventors: list[str] = Field(default_factory=list)
|
||||||
|
assignees: list[str] = Field(default_factory=list)
|
||||||
|
ipc: list[str] = Field(default_factory=list)
|
||||||
|
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||||
|
cpc: list[str] = Field(default_factory=list)
|
||||||
|
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||||
|
country: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class PatentsByAuthorResponse(BaseModel):
|
||||||
|
author_id: str
|
||||||
|
author_name: str | None = None
|
||||||
|
patent_count: int
|
||||||
|
patents: list[PatentEntry]
|
||||||
|
|
||||||
|
|
||||||
|
class PatentsByInstitutionResponse(BaseModel):
|
||||||
|
institution_id: str
|
||||||
|
institution_name: str | None = None
|
||||||
|
patent_count: int
|
||||||
|
patents: list[PatentEntry]
|
||||||
|
|
||||||
|
|
||||||
|
class AllPatentsResponse(BaseModel):
|
||||||
|
total: int
|
||||||
|
page: int
|
||||||
|
size: int
|
||||||
|
patents: list[PatentEntry]
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""Shared patent hit parsing, deduplication, and classification enrichment."""
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from inse.patents.common import model
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
from inse.patents.ipc_lookup import extract_ipc_symbol
|
||||||
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||||
|
patents = []
|
||||||
|
for hit in data.get("hits", {}).get("hits", []):
|
||||||
|
src = hit.get("_source", {})
|
||||||
|
inventors = src.get("inventors_name") or []
|
||||||
|
applicants = src.get("applicants_name") or []
|
||||||
|
ipc = src.get("ipc") or []
|
||||||
|
cpc = src.get("cpc") or []
|
||||||
|
patents.append(model.PatentEntry(
|
||||||
|
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||||
|
source="EPO",
|
||||||
|
title=src.get("title_en") or src.get("title_de"),
|
||||||
|
abstract=src.get("abstract"),
|
||||||
|
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||||
|
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||||
|
application_number=src.get("application_number"),
|
||||||
|
application_date=src.get("application_filing_date"),
|
||||||
|
kind=src.get("kind"),
|
||||||
|
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||||
|
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
|
||||||
|
ipc=_to_classification_strings(ipc),
|
||||||
|
cpc=_to_classification_strings(cpc),
|
||||||
|
country=src.get("country", "EP"),
|
||||||
|
))
|
||||||
|
return patents
|
||||||
|
|
||||||
|
|
||||||
|
def parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||||
|
patents = []
|
||||||
|
for hit in data.get("hits", {}).get("hits", []):
|
||||||
|
src = hit.get("_source", {})
|
||||||
|
inventors = src.get("inventors_names") or []
|
||||||
|
assignees = src.get("assignees_orgs") or []
|
||||||
|
ipc = src.get("ipcr") or []
|
||||||
|
cpc = src.get("cpc") or []
|
||||||
|
patents.append(model.PatentEntry(
|
||||||
|
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||||
|
source="USPTO",
|
||||||
|
title=src.get("title"),
|
||||||
|
abstract=src.get("abstract"),
|
||||||
|
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||||
|
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||||
|
application_number=src.get("application_number"),
|
||||||
|
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||||
|
application_type=src.get("application_type"),
|
||||||
|
number_of_claims=src.get("number_of_claims"),
|
||||||
|
status=src.get("status"),
|
||||||
|
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||||
|
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
|
||||||
|
ipc=_to_classification_strings(ipc),
|
||||||
|
cpc=_to_classification_strings(cpc),
|
||||||
|
country=src.get("country", "US"),
|
||||||
|
))
|
||||||
|
return patents
|
||||||
|
|
||||||
|
|
||||||
|
def deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||||
|
seen: set[tuple[str, str, str, str]] = set()
|
||||||
|
deduplicated: list[model.PatentEntry] = []
|
||||||
|
|
||||||
|
for patent in patents:
|
||||||
|
key = patent_dedup_key(patent)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
deduplicated.append(patent)
|
||||||
|
|
||||||
|
return deduplicated
|
||||||
|
|
||||||
|
|
||||||
|
def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||||
|
stage = patent.kind or patent.application_type or ""
|
||||||
|
return (
|
||||||
|
patent.source,
|
||||||
|
patent.patent_id,
|
||||||
|
patent.publication_date or "",
|
||||||
|
stage,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def enrich_patents_classifications(
|
||||||
|
patents: list[model.PatentEntry],
|
||||||
|
ipc_client: IpcSearchClient,
|
||||||
|
) -> None:
|
||||||
|
symbols = list(dict.fromkeys(
|
||||||
|
extract_ipc_symbol(raw)
|
||||||
|
for patent in patents
|
||||||
|
for raw in (*patent.ipc, *patent.cpc)
|
||||||
|
))
|
||||||
|
if not symbols:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
resolved = await ipc_client.resolve_symbols(symbols)
|
||||||
|
except MissingApiKeyError:
|
||||||
|
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||||
|
return
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
logger.warning("Classification enrichment failed: %s", exc)
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||||
|
return
|
||||||
|
|
||||||
|
for patent in patents:
|
||||||
|
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||||
|
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_classification_strings(value) -> list[str]:
|
||||||
|
if not value:
|
||||||
|
return []
|
||||||
|
items = value if isinstance(value, list) else [value]
|
||||||
|
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _descriptions_for_raw_codes(
|
||||||
|
raw_codes: list[str],
|
||||||
|
resolved: dict[str, model.IpcClassification],
|
||||||
|
) -> list[model.IpcClassification]:
|
||||||
|
return [
|
||||||
|
resolved[extract_ipc_symbol(raw)]
|
||||||
|
for raw in raw_codes
|
||||||
|
if extract_ipc_symbol(raw) in resolved
|
||||||
|
]
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Shared text normalization for patent name matching."""
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
|
||||||
|
_CHAR_REPLACEMENTS: dict[str, str] = {
|
||||||
|
"ß": "ss",
|
||||||
|
"ẞ": "ss",
|
||||||
|
"æ": "ae",
|
||||||
|
"Æ": "ae",
|
||||||
|
"œ": "oe",
|
||||||
|
"Œ": "oe",
|
||||||
|
"ø": "o",
|
||||||
|
"Ø": "o",
|
||||||
|
"đ": "d",
|
||||||
|
"Đ": "d",
|
||||||
|
"ð": "d",
|
||||||
|
"Ð": "d",
|
||||||
|
"þ": "th",
|
||||||
|
"Þ": "th",
|
||||||
|
"ł": "l",
|
||||||
|
"Ł": "l",
|
||||||
|
"ı": "i",
|
||||||
|
"ſ": "s",
|
||||||
|
}
|
||||||
|
|
||||||
|
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
|
||||||
|
("ae", "a"),
|
||||||
|
("oe", "o"),
|
||||||
|
("ue", "u"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
|
||||||
|
(r"u([lmnrt])", r"ue\1"),
|
||||||
|
(r"o([lmnrt])", r"oe\1"),
|
||||||
|
(r"a([lmnrt])", r"ae\1"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_name_part(value: str | None) -> str:
|
||||||
|
if not value:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
text = value.strip()
|
||||||
|
for src, dst in _CHAR_REPLACEMENTS.items():
|
||||||
|
text = text.replace(src, dst)
|
||||||
|
|
||||||
|
text = unicodedata.normalize("NFKD", text)
|
||||||
|
text = "".join(c for c in text if not unicodedata.combining(c))
|
||||||
|
text = text.lower()
|
||||||
|
text = re.sub(r"[''`´]", "", text)
|
||||||
|
text = re.sub(r"[^\w\s-]", "", text)
|
||||||
|
text = re.sub(r"\s+", " ", text).strip()
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def name_token_variants(value: str | None) -> set[str]:
|
||||||
|
base = normalize_name_part(value)
|
||||||
|
if not base:
|
||||||
|
return set()
|
||||||
|
|
||||||
|
variants = {base}
|
||||||
|
|
||||||
|
for src, dst in _DIGRAPH_COLLAPSES:
|
||||||
|
if src in base:
|
||||||
|
variants.add(base.replace(src, dst))
|
||||||
|
|
||||||
|
if "-" in base:
|
||||||
|
variants.add(base.replace("-", ""))
|
||||||
|
variants.add(base.replace("-", " "))
|
||||||
|
|
||||||
|
return {v for v in variants if v}
|
||||||
|
|
||||||
|
|
||||||
|
def patent_transliteration_expansions(normalized: str) -> set[str]:
|
||||||
|
expanded = {normalized}
|
||||||
|
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
|
||||||
|
if re.search(pattern, normalized):
|
||||||
|
expanded.add(re.sub(pattern, repl, normalized))
|
||||||
|
return expanded
|
||||||
@@ -36,24 +36,45 @@ class AllPatentsSearchClient:
|
|||||||
size: int = 10,
|
size: int = 10,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
sort_direction: str = "desc",
|
sort_direction: str = "desc",
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||||
|
|
||||||
if search and search.strip():
|
if search and search.strip():
|
||||||
term = search.strip()
|
term = search.strip()
|
||||||
doc_number = term.upper().removeprefix("EP")
|
doc_number = term.upper().removeprefix("EP")
|
||||||
query: dict[str, Any] = {
|
search_query: dict[str, Any] = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"should": [
|
"should": [
|
||||||
{"match_phrase": {"title_en": {"query": term}}},
|
{"match": {"title_en": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||||
{"match_phrase": {"title_de": {"query": term}}},
|
{"match": {"title_de": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||||
{"term": {"doc_number": doc_number}},
|
{"term": {"doc_number": doc_number}},
|
||||||
],
|
],
|
||||||
"minimum_should_match": 1,
|
"minimum_should_match": 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
query = {"match_all": {}}
|
search_query = {"match_all": {}}
|
||||||
|
|
||||||
|
filters = []
|
||||||
|
if year_from or year_to:
|
||||||
|
date_range: dict[str, Any] = {}
|
||||||
|
if year_from:
|
||||||
|
date_range["gte"] = year_from * 10000
|
||||||
|
if year_to:
|
||||||
|
date_range["lte"] = (year_to * 10000) + 9999
|
||||||
|
filters.append({"range": {"date_publication": date_range}})
|
||||||
|
|
||||||
|
if filters:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": search_query,
|
||||||
|
"filter": filters,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = search_query
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"from": page * size,
|
"from": page * size,
|
||||||
@@ -68,30 +89,54 @@ class AllPatentsSearchClient:
|
|||||||
],
|
],
|
||||||
"query": query,
|
"query": query,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def remove_year(self, patent_id: str) -> str:
|
||||||
|
return patent_id[4:].strip()
|
||||||
def uspto_query(
|
def uspto_query(
|
||||||
self,
|
self,
|
||||||
page: int = 0,
|
page: int = 0,
|
||||||
size: int = 10,
|
size: int = 10,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
sort_direction: str = "desc",
|
sort_direction: str = "desc",
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||||
|
|
||||||
if search and search.strip():
|
if search and search.strip():
|
||||||
term = search.strip()
|
term = search.strip()
|
||||||
pub_number = term.upper().removeprefix("US")
|
pub_number = term.upper().removeprefix("US")
|
||||||
query: dict[str, Any] = {
|
search_query: dict[str, Any] = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"should": [
|
"should": [
|
||||||
{"match_phrase": {"title": {"query": term}}},
|
{"match": {"title": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||||
{"term": {"publication_number": pub_number}},
|
{"term": {"publication_number": pub_number}},
|
||||||
],
|
],
|
||||||
"minimum_should_match": 1,
|
"minimum_should_match": 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
query = {"match_all": {}}
|
search_query = {"match_all": {}}
|
||||||
|
|
||||||
|
filters = []
|
||||||
|
if year_from or year_to:
|
||||||
|
date_range: dict[str, Any] = {}
|
||||||
|
if year_from:
|
||||||
|
date_range["gte"] = year_from * 10000
|
||||||
|
if year_to:
|
||||||
|
date_range["lte"] = (year_to * 10000) + 9999
|
||||||
|
filters.append({"range": {"publication_date": date_range}})
|
||||||
|
|
||||||
|
if filters:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": search_query,
|
||||||
|
"filter": filters,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = search_query
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"from": page * size,
|
"from": page * size,
|
||||||
@@ -107,6 +152,103 @@ class AllPatentsSearchClient:
|
|||||||
"query": query,
|
"query": query,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"doc_number": doc_number}},
|
||||||
|
{"term": {"doc_number": self.remove_year(doc_number)}},
|
||||||
|
{"term": {"application_number": self.remove_year(doc_number)}},
|
||||||
|
{"term": {"application_number": doc_number}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": 1,
|
||||||
|
"_source": [
|
||||||
|
"doc_number", "country", "kind", "date_publication",
|
||||||
|
"date_publication_year", "application_number",
|
||||||
|
"application_filing_date", "title_en", "title_de",
|
||||||
|
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
|
|
||||||
|
def uspto_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"publication_number": number}},
|
||||||
|
{"term": {"publication_number": self.remove_year(number)}},
|
||||||
|
{"term": {"application_number": number}},
|
||||||
|
{"term": {"application_number": self.remove_year(number)}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": 1,
|
||||||
|
"_source": [
|
||||||
|
"publication_number", "country", "publication_date",
|
||||||
|
"publication_year", "application_number", "application_date",
|
||||||
|
"application_type", "title", "abstract", "inventors_names",
|
||||||
|
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
|
|
||||||
|
def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"match_phrase": {"title_en": title}},
|
||||||
|
{"match_phrase": {"title_de": title}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": 1,
|
||||||
|
"_source": [
|
||||||
|
"doc_number", "country", "kind", "date_publication",
|
||||||
|
"date_publication_year", "application_number",
|
||||||
|
"application_filing_date", "title_en", "title_de",
|
||||||
|
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
|
|
||||||
|
def uspto_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [{"match_phrase": {"title": title}}],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"size": 1,
|
||||||
|
"_source": [
|
||||||
|
"publication_number", "country", "publication_date",
|
||||||
|
"publication_year", "application_number", "application_date",
|
||||||
|
"application_type", "title", "abstract", "inventors_names",
|
||||||
|
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||||
|
],
|
||||||
|
"query": query,
|
||||||
|
}
|
||||||
|
|
||||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
return await self._search(EPO_INDEX, payload)
|
return await self._search(EPO_INDEX, payload)
|
||||||
|
|
||||||
|
|||||||
@@ -6,21 +6,27 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
|
import httpx
|
||||||
import asyncio
|
import asyncio
|
||||||
from .. import config
|
from .. import config
|
||||||
from .name_matching import search_name_variants
|
from .name_matching import search_name_variants
|
||||||
|
|
||||||
DEFAULT_SEARCH_SIZE = 100
|
DEFAULT_SEARCH_SIZE = 100
|
||||||
|
|
||||||
|
def remove_year(patent_number: str) -> str:
|
||||||
|
"""Remove a 4-digit year from the end of a patent number, if present."""
|
||||||
|
if len(patent_number) > 4 and patent_number[-4:].isdigit():
|
||||||
|
return patent_number[:-4]
|
||||||
|
return patent_number
|
||||||
|
|
||||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||||
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
||||||
variants = search_name_variants(name)
|
variants = search_name_variants(name)
|
||||||
if len(variants) <= 1:
|
if len(variants) <= 1:
|
||||||
return {"match": {field: variants[0] if variants else name}}
|
return {"match_phrase": {field: variants[0] if variants else name}}
|
||||||
return {
|
return {
|
||||||
"bool": {
|
"bool": {
|
||||||
"should": [{"match": {field: variant}} for variant in variants],
|
"should": [{"match_phrase": {field: variant}} for variant in variants],
|
||||||
"minimum_should_match": 1,
|
"minimum_should_match": 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,9 +38,15 @@ from inse.exceptions import MissingApiKeyError
|
|||||||
class PatentSearchClient:
|
class PatentSearchClient:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
|
base_url: str | None = None,
|
||||||
api_key: str | None = None,
|
api_key: str | None = None,
|
||||||
|
timeout: float = 30.0,
|
||||||
|
transport: httpx.AsyncBaseTransport | None = None,
|
||||||
):
|
):
|
||||||
|
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
|
self.timeout = timeout
|
||||||
|
self.transport = transport
|
||||||
|
|
||||||
def _headers(self) -> dict[str, str]:
|
def _headers(self) -> dict[str, str]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
@@ -158,9 +170,11 @@ class PatentSearchClient:
|
|||||||
}
|
}
|
||||||
|
|
||||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
print("Searching EPO with payload:", payload)
|
||||||
return await self._search(ESIndex.EPO_INDEX, payload)
|
return await self._search(ESIndex.EPO_INDEX, payload)
|
||||||
|
|
||||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
print("Searching USPTO with payload:", payload)
|
||||||
return await self._search(ESIndex.USPTO_INDEX, payload)
|
return await self._search(ESIndex.USPTO_INDEX, payload)
|
||||||
|
|
||||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
@@ -172,9 +186,10 @@ class PatentSearchClient:
|
|||||||
patent_id: str,
|
patent_id: str,
|
||||||
prefix: str,
|
prefix: str,
|
||||||
title: str,
|
title: str,
|
||||||
|
filling_date: str | None = None,
|
||||||
size: int = 1,
|
size: int = 1,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
|
"""Search EPO and USPTO by ID; fall back to match on title if no hits.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
||||||
@@ -202,16 +217,28 @@ class PatentSearchClient:
|
|||||||
return epo_result if epo_hits > 0 else uspto_result
|
return epo_result if epo_hits > 0 else uspto_result
|
||||||
|
|
||||||
if prefix.upper() == "US":
|
if prefix.upper() == "US":
|
||||||
payload = self._uspto_query_by_title(title, size)
|
payload = self._uspto_query_by_title(title, filling_date, size)
|
||||||
return await self.search_uspto(payload)
|
return await self.search_uspto(payload)
|
||||||
|
|
||||||
payload = self._epo_query_by_title(title, size)
|
payload = self._epo_query_by_title(title,filling_date, size)
|
||||||
return await self.search_epo(payload)
|
return await self.search_epo(payload)
|
||||||
|
|
||||||
#query builders
|
#query builders
|
||||||
|
|
||||||
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||||
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
||||||
raw_id = patent_id.upper().removeprefix("EP")
|
raw_id = patent_id.upper().removeprefix("EP")
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"doc_number": raw_id}},
|
||||||
|
{"term": {"doc_number": remove_year(raw_id)}},
|
||||||
|
{"term": {"application_number": remove_year(raw_id)}},
|
||||||
|
{"term": {"application_number": raw_id}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
"size": size,
|
"size": size,
|
||||||
"_source": [
|
"_source": [
|
||||||
@@ -220,11 +247,23 @@ class PatentSearchClient:
|
|||||||
"application_filing_date", "title_en", "title_de", "abstract",
|
"application_filing_date", "title_en", "title_de", "abstract",
|
||||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||||
],
|
],
|
||||||
"query": {"term": {"doc_number": raw_id}},
|
"query": query,
|
||||||
}
|
}
|
||||||
|
|
||||||
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||||
"""Term query against publication_number; tries the ID as-is."""
|
"""Term query against publication_number; tries the ID as-is."""
|
||||||
|
raw_id = patent_id.upper().removeprefix("US")
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"publication_number": raw_id}},
|
||||||
|
{"term": {"publication_number": remove_year(raw_id)}},
|
||||||
|
{"term": {"application_number": raw_id}},
|
||||||
|
{"term": {"application_number": remove_year(raw_id)}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
"size": size,
|
"size": size,
|
||||||
"track_total_hits": True,
|
"track_total_hits": True,
|
||||||
@@ -235,11 +274,24 @@ class PatentSearchClient:
|
|||||||
"application_type", "title", "abstract", "inventors_names",
|
"application_type", "title", "abstract", "inventors_names",
|
||||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||||
],
|
],
|
||||||
"query": {"term": {"publication_number": patent_id}},
|
"query": query,
|
||||||
}
|
}
|
||||||
|
|
||||||
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||||
"""match_phrase fallback on title_en (and title_de as a should clause)."""
|
"""match fallback on title_en (and title_de as a should clause)."""
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"match_phrase": {"title_en": title}},
|
||||||
|
{"match_phrase": {"title_de": title}},
|
||||||
|
{"match_phrase": {"title_fr": title}},
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"size": size,
|
"size": size,
|
||||||
"_source": [
|
"_source": [
|
||||||
@@ -248,20 +300,19 @@ class PatentSearchClient:
|
|||||||
"application_filing_date", "title_en", "title_de", "abstract",
|
"application_filing_date", "title_en", "title_de", "abstract",
|
||||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||||
],
|
],
|
||||||
"query": {
|
"query": query
|
||||||
"bool": {
|
|
||||||
"should": [
|
|
||||||
{"match_phrase": {"title_en": title}},
|
|
||||||
{"match_phrase": {"title_de": title}},
|
|
||||||
{"match_phrase": {"title_fr": title}},
|
|
||||||
],
|
|
||||||
"minimum_should_match": 1,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
def _uspto_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||||
"""match_phrase fallback on title."""
|
"""match fallback on title."""
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"should": [{"match_phrase": {"title": title}}],
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if filling_date:
|
||||||
|
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||||
return {
|
return {
|
||||||
"size": size,
|
"size": size,
|
||||||
"_source": [
|
"_source": [
|
||||||
@@ -270,5 +321,5 @@ class PatentSearchClient:
|
|||||||
"application_type", "title", "abstract", "inventors_names",
|
"application_type", "title", "abstract", "inventors_names",
|
||||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||||
],
|
],
|
||||||
"query": {"match_phrase": {"title": title}},
|
"query": query,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Patent lookup by institution assignee."""
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"""Business logic for patent lookup by institution assignee."""
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||||
|
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
|
||||||
|
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||||
|
from inse.models.openalex.institution import Institution
|
||||||
|
from inse.patents.common import model
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
from inse.patents.common.parsing import (
|
||||||
|
deduplicate_patents,
|
||||||
|
enrich_patents_classifications,
|
||||||
|
parse_epo_hits,
|
||||||
|
parse_uspto_hits,
|
||||||
|
)
|
||||||
|
from inse.patents.institutions.name_matching import (
|
||||||
|
MIN_INSTITUTION_ACRONYM_LEN,
|
||||||
|
assignee_matches_institution_name,
|
||||||
|
institution_search_variants,
|
||||||
|
)
|
||||||
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
|
from inse.patents.search_client import PatentSearchClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_patents_by_institution_id(
|
||||||
|
institution_id: str,
|
||||||
|
client: PatentSearchClient | None = None,
|
||||||
|
ipc_client: IpcSearchClient | None = None,
|
||||||
|
institutions_client: InstitutionsSearchClient | None = None,
|
||||||
|
) -> model.PatentsByInstitutionResponse:
|
||||||
|
search_client = client or PatentSearchClient()
|
||||||
|
ipc_search_client = ipc_client or IpcSearchClient()
|
||||||
|
institution_client = institutions_client or InstitutionsSearchClient()
|
||||||
|
|
||||||
|
short_id = institution_id.replace("https://openalex.org/", "")
|
||||||
|
institution = institution_client.get_institution_by_id(short_id)
|
||||||
|
search_names = _institution_search_names(institution)
|
||||||
|
|
||||||
|
if not search_names:
|
||||||
|
return model.PatentsByInstitutionResponse(
|
||||||
|
institution_id=short_id,
|
||||||
|
institution_name=institution.display_name,
|
||||||
|
patent_count=0,
|
||||||
|
patents=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
epo_data, uspto_data = await asyncio.gather(
|
||||||
|
search_client.search_epo(
|
||||||
|
search_client.epo_query_by_applicant(search_names)
|
||||||
|
),
|
||||||
|
search_client.search_uspto(
|
||||||
|
search_client.uspto_query_by_assignee(search_names)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
except MissingApiKeyError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Patent search is not configured.",
|
||||||
|
) from exc
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_502_BAD_GATEWAY,
|
||||||
|
detail="Patent search request failed.",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||||
|
all_patents = filter_patents_by_institution(all_patents, institution)
|
||||||
|
all_patents = deduplicate_patents(all_patents)
|
||||||
|
|
||||||
|
await enrich_patents_classifications(all_patents, ipc_search_client)
|
||||||
|
|
||||||
|
return model.PatentsByInstitutionResponse(
|
||||||
|
institution_id=short_id,
|
||||||
|
institution_name=institution.display_name,
|
||||||
|
patent_count=len(all_patents),
|
||||||
|
patents=all_patents,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _institution_search_names(institution: Institution) -> list[str]:
|
||||||
|
names: list[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
def _add(name: str | None) -> None:
|
||||||
|
if not name or not name.strip():
|
||||||
|
return
|
||||||
|
for variant in institution_search_variants(name.strip()):
|
||||||
|
key = variant.casefold()
|
||||||
|
if key not in seen:
|
||||||
|
seen.add(key)
|
||||||
|
names.append(variant)
|
||||||
|
|
||||||
|
_add(institution.display_name)
|
||||||
|
for alternative in institution.display_name_alternatives or []:
|
||||||
|
_add(alternative)
|
||||||
|
for acronym in institution.display_name_acronyms or []:
|
||||||
|
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
|
||||||
|
_add(acronym)
|
||||||
|
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
|
def _institution_canonical_names(institution: Institution) -> list[str]:
|
||||||
|
names: list[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
def _add(name: str | None) -> None:
|
||||||
|
if not name or not name.strip():
|
||||||
|
return
|
||||||
|
key = name.strip().casefold()
|
||||||
|
if key not in seen:
|
||||||
|
seen.add(key)
|
||||||
|
names.append(name.strip())
|
||||||
|
|
||||||
|
_add(institution.display_name)
|
||||||
|
for alternative in institution.display_name_alternatives or []:
|
||||||
|
_add(alternative)
|
||||||
|
for acronym in institution.display_name_acronyms or []:
|
||||||
|
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
|
||||||
|
_add(acronym)
|
||||||
|
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
|
def filter_patents_by_institution(
|
||||||
|
patents: list[model.PatentEntry],
|
||||||
|
institution: Institution,
|
||||||
|
) -> list[model.PatentEntry]:
|
||||||
|
canonical_names = _institution_canonical_names(institution)
|
||||||
|
return [
|
||||||
|
patent for patent in patents
|
||||||
|
if any(
|
||||||
|
assignee_matches_institution_name(assignee, name)
|
||||||
|
for assignee in patent.assignees
|
||||||
|
for name in canonical_names
|
||||||
|
)
|
||||||
|
]
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""Institution assignee name normalization and matching."""
|
||||||
|
from inse.patents.common.text_normalization import (
|
||||||
|
name_token_variants,
|
||||||
|
normalize_name_part,
|
||||||
|
patent_transliteration_expansions,
|
||||||
|
)
|
||||||
|
|
||||||
|
_INSTITUTION_GENERIC_TOKENS = frozenset({
|
||||||
|
"university", "universitat", "universitaet", "universiteit", "college",
|
||||||
|
"institute", "institut", "institution", "national", "sciences", "science",
|
||||||
|
"school", "center", "centre", "laboratory", "department", "academy",
|
||||||
|
"the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und",
|
||||||
|
"fur", "von",
|
||||||
|
})
|
||||||
|
|
||||||
|
MIN_INSTITUTION_SUBSTRING_LEN = 6
|
||||||
|
MIN_INSTITUTION_VARIANT_LEN = 4
|
||||||
|
MIN_INSTITUTION_ACRONYM_LEN = 3
|
||||||
|
|
||||||
|
|
||||||
|
def institution_search_variants(value: str | None) -> list[str]:
|
||||||
|
if not value or not value.strip():
|
||||||
|
return []
|
||||||
|
|
||||||
|
stripped = value.strip()
|
||||||
|
min_len = (
|
||||||
|
MIN_INSTITUTION_ACRONYM_LEN
|
||||||
|
if stripped.isupper() and " " not in stripped
|
||||||
|
else MIN_INSTITUTION_VARIANT_LEN
|
||||||
|
)
|
||||||
|
|
||||||
|
seen: set[str] = set()
|
||||||
|
ordered: list[str] = []
|
||||||
|
|
||||||
|
def _add(candidate: str) -> None:
|
||||||
|
candidate = candidate.strip()
|
||||||
|
if len(candidate) < min_len:
|
||||||
|
return
|
||||||
|
key = candidate.casefold()
|
||||||
|
if key not in seen:
|
||||||
|
seen.add(key)
|
||||||
|
ordered.append(candidate)
|
||||||
|
|
||||||
|
_add(stripped)
|
||||||
|
|
||||||
|
normalized = normalize_name_part(value)
|
||||||
|
if normalized:
|
||||||
|
_add(normalized.title())
|
||||||
|
|
||||||
|
for variant in name_token_variants(value):
|
||||||
|
_add(variant.title())
|
||||||
|
|
||||||
|
for variant in patent_transliteration_expansions(normalized):
|
||||||
|
_add(variant.title())
|
||||||
|
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
def _significant_institution_tokens(text: str) -> set[str]:
|
||||||
|
return {
|
||||||
|
token
|
||||||
|
for token in normalize_name_part(text).split()
|
||||||
|
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
|
||||||
|
and token not in _INSTITUTION_GENERIC_TOKENS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool:
|
||||||
|
norm_assignee = normalize_name_part(assignee)
|
||||||
|
norm_name = normalize_name_part(institution_name)
|
||||||
|
if not norm_assignee or not norm_name:
|
||||||
|
return False
|
||||||
|
|
||||||
|
original = institution_name.strip()
|
||||||
|
assignee_tokens = set(norm_assignee.split())
|
||||||
|
|
||||||
|
if len(original) <= 6 and " " not in original:
|
||||||
|
return norm_name in assignee_tokens
|
||||||
|
|
||||||
|
if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN:
|
||||||
|
if norm_name in norm_assignee or norm_assignee in norm_name:
|
||||||
|
return True
|
||||||
|
|
||||||
|
significant = _significant_institution_tokens(institution_name)
|
||||||
|
if not significant:
|
||||||
|
return False
|
||||||
|
|
||||||
|
matched = significant & assignee_tokens
|
||||||
|
if len(significant) >= 2:
|
||||||
|
return len(matched) >= 2
|
||||||
|
return bool(matched)
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""Elasticsearch query builders for institution assignee patent search."""
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
|
||||||
|
from inse.patents.institutions.name_matching import institution_search_variants
|
||||||
|
|
||||||
|
|
||||||
|
class AssigneeSearchQueries:
|
||||||
|
def _match_organization_names(self, field: str, names: list[str]) -> dict[str, Any]:
|
||||||
|
clauses: list[dict[str, Any]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
for name in names:
|
||||||
|
for variant in institution_search_variants(name):
|
||||||
|
key = variant.casefold()
|
||||||
|
if not variant or key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
clauses.append({"match_phrase": {field: {"query": variant}}})
|
||||||
|
|
||||||
|
if not clauses:
|
||||||
|
return {"match_none": {}}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"bool": {
|
||||||
|
"should": clauses,
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def epo_query_by_applicant(
|
||||||
|
self,
|
||||||
|
institution_names: list[str],
|
||||||
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"sort": [
|
||||||
|
{"_score": {"order": "desc"}},
|
||||||
|
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||||
|
"_doc",
|
||||||
|
],
|
||||||
|
"_source": [
|
||||||
|
"doc_number",
|
||||||
|
"country",
|
||||||
|
"kind",
|
||||||
|
"date_publication",
|
||||||
|
"date_publication_year",
|
||||||
|
"application_number",
|
||||||
|
"application_filing_date",
|
||||||
|
"title_en",
|
||||||
|
"title_de",
|
||||||
|
"abstract",
|
||||||
|
"inventors_name",
|
||||||
|
"applicants_name",
|
||||||
|
"ipc",
|
||||||
|
"cpc",
|
||||||
|
],
|
||||||
|
"query": self._match_organization_names("applicants_name", institution_names),
|
||||||
|
}
|
||||||
|
|
||||||
|
def uspto_query_by_assignee(
|
||||||
|
self,
|
||||||
|
institution_names: list[str],
|
||||||
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"sort": [
|
||||||
|
{"_score": {"order": "desc"}},
|
||||||
|
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||||
|
"_doc",
|
||||||
|
],
|
||||||
|
"_source": [
|
||||||
|
"publication_number",
|
||||||
|
"country",
|
||||||
|
"publication_date",
|
||||||
|
"publication_year",
|
||||||
|
"application_number",
|
||||||
|
"application_date",
|
||||||
|
"application_type",
|
||||||
|
"title",
|
||||||
|
"abstract",
|
||||||
|
"inventors_names",
|
||||||
|
"assignees_orgs",
|
||||||
|
"ipcr",
|
||||||
|
"cpc",
|
||||||
|
"number_of_claims",
|
||||||
|
"status",
|
||||||
|
],
|
||||||
|
"query": self._match_organization_names("assignees_orgs", institution_names),
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||||
|
from inse.patents.common import model
|
||||||
|
from inse.patents.institutions import logic
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||||
|
return InstitutionsSearchClient()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{id}/patents",
|
||||||
|
operation_id="getPatentsByInstitution",
|
||||||
|
response_model=model.PatentsByInstitutionResponse,
|
||||||
|
summary="Get patents matched to an institution by assignee name.",
|
||||||
|
)
|
||||||
|
async def get_patents_by_institution(
|
||||||
|
id: str,
|
||||||
|
client: Annotated[
|
||||||
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
|
],
|
||||||
|
) -> model.PatentsByInstitutionResponse:
|
||||||
|
return await logic.get_patents_by_institution_id(
|
||||||
|
institution_id=id,
|
||||||
|
institutions_client=client,
|
||||||
|
)
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
#!/usr/bin/env python
|
"""Backward-compatible re-exports."""
|
||||||
# -*- coding: utf-8 -*-
|
from inse.patents.all.logic import get_all_patents
|
||||||
"""
|
from inse.patents.authors.logic import get_patents_by_author_id
|
||||||
Business logic for patent matching by author name.
|
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
|
||||||
"""
|
from inse.patents.institutions.logic import (
|
||||||
|
filter_patents_by_institution as _filter_patents_by_institution,
|
||||||
|
get_patents_by_institution_id,
|
||||||
|
)
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
@@ -16,22 +20,28 @@ from .elastic_search_all_patents_client import AllPatentsSearchClient
|
|||||||
from .ipc_search_client import IpcSearchClient
|
from .ipc_search_client import IpcSearchClient
|
||||||
from .ipc_lookup import extract_ipc_symbol
|
from .ipc_lookup import extract_ipc_symbol
|
||||||
from .name_matching import name_matches
|
from .name_matching import name_matches
|
||||||
|
from datetime import datetime
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def normalize_patent_date(date_str: str) -> str:
|
||||||
|
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
|
||||||
|
|
||||||
async def get_patent(
|
async def get_patent(
|
||||||
patent_id: str,
|
patent_id: str,
|
||||||
title: str,
|
title: str,
|
||||||
prefix: str,
|
prefix: str,
|
||||||
|
filling_date: str | None = None,
|
||||||
client: PatentSearchClient | None = None,
|
client: PatentSearchClient | None = None,
|
||||||
) -> model.PatentEntry:
|
) -> model.PatentEntry:
|
||||||
search_client = client or PatentSearchClient()
|
search_client = client or PatentSearchClient()
|
||||||
|
|
||||||
|
if filling_date:
|
||||||
|
filling_date = normalize_patent_date(filling_date)
|
||||||
data = await search_client.get_by_id_or_title(
|
data = await search_client.get_by_id_or_title(
|
||||||
patent_id=patent_id,
|
patent_id=patent_id,
|
||||||
prefix=prefix,
|
prefix=prefix,
|
||||||
title=title,
|
title=title,
|
||||||
|
filling_date=filling_date,
|
||||||
)
|
)
|
||||||
|
|
||||||
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
||||||
@@ -309,4 +319,4 @@ async def get_all_patents(
|
|||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
patents=patents,
|
patents=patents,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,47 +1,2 @@
|
|||||||
from pydantic import BaseModel, ConfigDict, Field
|
"""Backward-compatible re-exports."""
|
||||||
|
from inse.patents.common.model import * # noqa: F403
|
||||||
|
|
||||||
class IpcClassification(BaseModel):
|
|
||||||
symbol: str
|
|
||||||
section: str | None = None
|
|
||||||
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
|
||||||
subclass: str | None = None
|
|
||||||
main_group: str | None = None
|
|
||||||
subgroup: str | None = None
|
|
||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True)
|
|
||||||
|
|
||||||
|
|
||||||
class PatentEntry(BaseModel):
|
|
||||||
patent_id: str
|
|
||||||
source: str # "EPO" or "USPTO"
|
|
||||||
title: str | None = None
|
|
||||||
abstract: str | None = None
|
|
||||||
publication_date: str | None = None
|
|
||||||
publication_year: str | None = None
|
|
||||||
application_number: str | None = None
|
|
||||||
application_date: str | None = None
|
|
||||||
kind: str | None = None # EPO only
|
|
||||||
application_type: str | None = None # USPTO only
|
|
||||||
number_of_claims: int | None = None # USPTO only
|
|
||||||
status: str | None = None # USPTO only
|
|
||||||
inventors: list[str] = Field(default_factory=list)
|
|
||||||
assignees: list[str] = Field(default_factory=list)
|
|
||||||
ipc: list[str] = Field(default_factory=list)
|
|
||||||
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
|
||||||
cpc: list[str] = Field(default_factory=list)
|
|
||||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
|
||||||
country: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class PatentsByAuthorResponse(BaseModel):
|
|
||||||
author_id: str
|
|
||||||
author_name: str | None = None
|
|
||||||
patent_count: int
|
|
||||||
patents: list[PatentEntry]
|
|
||||||
|
|
||||||
class AllPatentsResponse(BaseModel):
|
|
||||||
total: int
|
|
||||||
page: int
|
|
||||||
size: int
|
|
||||||
patents: list[PatentEntry]
|
|
||||||
|
|||||||
@@ -1,242 +1,18 @@
|
|||||||
#!/usr/bin/env python
|
"""Backward-compatible re-exports."""
|
||||||
# -*- coding: utf-8 -*-
|
from inse.patents.authors.name_matching import ( # noqa: F401
|
||||||
"""
|
first_name_match_kind,
|
||||||
Name normalization and matching for patent inventor lookup.
|
name_matches,
|
||||||
|
search_name_variants,
|
||||||
Handles umlauts, diacritics, and common Latin transliterations so that
|
tokens_equal,
|
||||||
e.g. 'Müller' matches 'Mueller' and 'Muller'.
|
|
||||||
"""
|
|
||||||
import re
|
|
||||||
import unicodedata
|
|
||||||
|
|
||||||
# Characters that NFKD does not map to ASCII-friendly forms.
|
|
||||||
_CHAR_REPLACEMENTS: dict[str, str] = {
|
|
||||||
"ß": "ss",
|
|
||||||
"ẞ": "ss",
|
|
||||||
"æ": "ae",
|
|
||||||
"Æ": "ae",
|
|
||||||
"œ": "oe",
|
|
||||||
"Œ": "oe",
|
|
||||||
"ø": "o",
|
|
||||||
"Ø": "o",
|
|
||||||
"đ": "d",
|
|
||||||
"Đ": "d",
|
|
||||||
"ð": "d",
|
|
||||||
"Ð": "d",
|
|
||||||
"þ": "th",
|
|
||||||
"Þ": "th",
|
|
||||||
"ł": "l",
|
|
||||||
"Ł": "l",
|
|
||||||
"ı": "i",
|
|
||||||
"ſ": "s",
|
|
||||||
}
|
|
||||||
|
|
||||||
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
|
|
||||||
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
|
|
||||||
("ae", "a"),
|
|
||||||
("oe", "o"),
|
|
||||||
("ue", "u"),
|
|
||||||
)
|
)
|
||||||
|
from inse.patents.common.text_normalization import ( # noqa: F401
|
||||||
# Common ASCII spellings in patent records for umlaut-derived vowels.
|
name_token_variants,
|
||||||
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
|
normalize_name_part,
|
||||||
(r"u([lmnrt])", r"ue\1"),
|
)
|
||||||
(r"o([lmnrt])", r"oe\1"),
|
from inse.patents.institutions.name_matching import ( # noqa: F401
|
||||||
(r"a([lmnrt])", r"ae\1"),
|
MIN_INSTITUTION_ACRONYM_LEN,
|
||||||
|
MIN_INSTITUTION_SUBSTRING_LEN,
|
||||||
|
MIN_INSTITUTION_VARIANT_LEN,
|
||||||
|
assignee_matches_institution_name,
|
||||||
|
institution_search_variants,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def normalize_name_part(value: str | None) -> str:
|
|
||||||
"""
|
|
||||||
Normalize a single name token for comparison.
|
|
||||||
|
|
||||||
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
|
|
||||||
-> remove apostrophes/punctuation -> collapse whitespace.
|
|
||||||
"""
|
|
||||||
if not value:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
text = value.strip()
|
|
||||||
for src, dst in _CHAR_REPLACEMENTS.items():
|
|
||||||
text = text.replace(src, dst)
|
|
||||||
|
|
||||||
text = unicodedata.normalize("NFKD", text)
|
|
||||||
text = "".join(c for c in text if not unicodedata.combining(c))
|
|
||||||
text = text.lower()
|
|
||||||
text = re.sub(r"[''`´]", "", text)
|
|
||||||
text = re.sub(r"[^\w\s-]", "", text)
|
|
||||||
text = re.sub(r"\s+", " ", text).strip()
|
|
||||||
return text
|
|
||||||
|
|
||||||
|
|
||||||
def name_token_variants(value: str | None) -> set[str]:
|
|
||||||
"""
|
|
||||||
Return equivalent forms of a name token.
|
|
||||||
|
|
||||||
Includes the normalized base plus German digraph collapses
|
|
||||||
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
|
|
||||||
"""
|
|
||||||
base = normalize_name_part(value)
|
|
||||||
if not base:
|
|
||||||
return set()
|
|
||||||
|
|
||||||
variants = {base}
|
|
||||||
|
|
||||||
for src, dst in _DIGRAPH_COLLAPSES:
|
|
||||||
if src in base:
|
|
||||||
variants.add(base.replace(src, dst))
|
|
||||||
|
|
||||||
if "-" in base:
|
|
||||||
variants.add(base.replace("-", ""))
|
|
||||||
variants.add(base.replace("-", " "))
|
|
||||||
|
|
||||||
return {v for v in variants if v}
|
|
||||||
|
|
||||||
|
|
||||||
def _patent_transliteration_expansions(normalized: str) -> set[str]:
|
|
||||||
"""
|
|
||||||
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
|
|
||||||
|
|
||||||
Used for Elasticsearch recall only; post-filter applies stricter matching.
|
|
||||||
"""
|
|
||||||
expanded = {normalized}
|
|
||||||
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
|
|
||||||
if re.search(pattern, normalized):
|
|
||||||
expanded.add(re.sub(pattern, repl, normalized))
|
|
||||||
return expanded
|
|
||||||
|
|
||||||
|
|
||||||
def tokens_equal(
|
|
||||||
left: str | None,
|
|
||||||
right: str | None,
|
|
||||||
*,
|
|
||||||
allow_initial: bool = True,
|
|
||||||
) -> bool:
|
|
||||||
"""True when two name tokens are equivalent after normalization."""
|
|
||||||
left_variants = name_token_variants(left)
|
|
||||||
right_variants = name_token_variants(right)
|
|
||||||
if not left_variants or not right_variants:
|
|
||||||
return False
|
|
||||||
if left_variants & right_variants:
|
|
||||||
return True
|
|
||||||
|
|
||||||
if not allow_initial:
|
|
||||||
return False
|
|
||||||
|
|
||||||
return _initial_tokens_match(left, right)
|
|
||||||
|
|
||||||
|
|
||||||
def _initial_letter(token: str | None) -> str | None:
|
|
||||||
normalized = normalize_name_part(token)
|
|
||||||
if len(normalized) == 1 and normalized.isalpha():
|
|
||||||
return normalized
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
|
|
||||||
"""True when one token is a single-letter initial matching the other token."""
|
|
||||||
left_initial = _initial_letter(left)
|
|
||||||
right_initial = _initial_letter(right)
|
|
||||||
left_full = normalize_name_part(left)
|
|
||||||
right_full = normalize_name_part(right)
|
|
||||||
|
|
||||||
if left_initial and right_full and len(right_full) > 1:
|
|
||||||
return right_full.startswith(left_initial)
|
|
||||||
if right_initial and left_full and len(left_full) > 1:
|
|
||||||
return left_full.startswith(right_initial)
|
|
||||||
if left_initial and right_initial:
|
|
||||||
return left_initial == right_initial
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _inventor_first_token(inventor_name: str) -> str:
|
|
||||||
if "," in inventor_name:
|
|
||||||
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
|
|
||||||
return first_part.split()[0] if first_part else ""
|
|
||||||
parts = inventor_name.split()
|
|
||||||
return parts[0] if parts else ""
|
|
||||||
|
|
||||||
|
|
||||||
def first_name_match_kind(
|
|
||||||
inventor_name: str,
|
|
||||||
first_name: str,
|
|
||||||
last_name: str,
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
Match quality for the inventor first name: 'full', 'initial', or 'none'.
|
|
||||||
"""
|
|
||||||
if not name_matches(inventor_name, first_name, last_name):
|
|
||||||
return "none"
|
|
||||||
|
|
||||||
inventor_first = _inventor_first_token(inventor_name)
|
|
||||||
if tokens_equal(inventor_first, first_name, allow_initial=False):
|
|
||||||
return "full"
|
|
||||||
return "initial"
|
|
||||||
|
|
||||||
|
|
||||||
def search_name_variants(value: str | None) -> list[str]:
|
|
||||||
"""
|
|
||||||
Distinct search strings for Elasticsearch, preserving original casing
|
|
||||||
where useful but including normalized and transliterated forms.
|
|
||||||
"""
|
|
||||||
if not value or not value.strip():
|
|
||||||
return []
|
|
||||||
|
|
||||||
seen: set[str] = set()
|
|
||||||
ordered: list[str] = []
|
|
||||||
|
|
||||||
def _add(candidate: str) -> None:
|
|
||||||
key = candidate.casefold()
|
|
||||||
if candidate.strip() and key not in seen:
|
|
||||||
seen.add(key)
|
|
||||||
ordered.append(candidate.strip())
|
|
||||||
|
|
||||||
_add(value.strip())
|
|
||||||
|
|
||||||
normalized = normalize_name_part(value)
|
|
||||||
if normalized:
|
|
||||||
_add(normalized.title())
|
|
||||||
|
|
||||||
for variant in name_token_variants(value):
|
|
||||||
_add(variant.title())
|
|
||||||
|
|
||||||
for variant in _patent_transliteration_expansions(normalized):
|
|
||||||
_add(variant.title())
|
|
||||||
|
|
||||||
if normalized and len(normalized) > 1:
|
|
||||||
_add(normalized[0].upper())
|
|
||||||
|
|
||||||
return ordered
|
|
||||||
|
|
||||||
|
|
||||||
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
|
|
||||||
"""
|
|
||||||
True when an inventor entry matches first_name + last_name.
|
|
||||||
|
|
||||||
Supports:
|
|
||||||
- USPTO: 'Christian Weber', 'Christian Hans Weber'
|
|
||||||
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
|
|
||||||
"""
|
|
||||||
if not inventor_name or not last_name:
|
|
||||||
return False
|
|
||||||
|
|
||||||
name = inventor_name.strip()
|
|
||||||
|
|
||||||
if "," in name:
|
|
||||||
last_part, first_part = [p.strip() for p in name.split(",", 1)]
|
|
||||||
first_token = first_part.split()[0] if first_part else ""
|
|
||||||
return (
|
|
||||||
tokens_equal(last_part, last_name, allow_initial=False)
|
|
||||||
and bool(first_name)
|
|
||||||
and tokens_equal(first_token, first_name)
|
|
||||||
)
|
|
||||||
|
|
||||||
parts = name.split()
|
|
||||||
if len(parts) < 2:
|
|
||||||
return False
|
|
||||||
|
|
||||||
return (
|
|
||||||
tokens_equal(parts[-1], last_name, allow_initial=False)
|
|
||||||
and bool(first_name)
|
|
||||||
and tokens_equal(parts[0], first_name)
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Org patents index: institution-scoped patent aggregation."""
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
"""HTTP client for the org_patents Elasticsearch index."""
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING
|
||||||
|
from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry
|
||||||
|
from inse import config
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
DEFAULT_PAGE_SIZE = 20
|
||||||
|
|
||||||
|
|
||||||
|
class OrgPatentsSearchClient:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: str | None = None,
|
||||||
|
api_key: str | None = None,
|
||||||
|
timeout: float = 60.0,
|
||||||
|
transport: httpx.AsyncBaseTransport | None = None,
|
||||||
|
):
|
||||||
|
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||||
|
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||||
|
self.timeout = timeout
|
||||||
|
self.transport = transport
|
||||||
|
|
||||||
|
def _headers(self, content_type: str = "application/json") -> dict[str, str]:
|
||||||
|
if not self.api_key:
|
||||||
|
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||||
|
return {
|
||||||
|
"Authorization": f"ApiKey {self.api_key}",
|
||||||
|
"Content-Type": content_type,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def ensure_index(self) -> None:
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=self.timeout,
|
||||||
|
transport=self.transport,
|
||||||
|
) as client:
|
||||||
|
response = await client.head(
|
||||||
|
f"/{ORG_PATENTS_INDEX}",
|
||||||
|
headers=self._headers(),
|
||||||
|
)
|
||||||
|
if response.status_code == 404:
|
||||||
|
create_response = await client.put(
|
||||||
|
f"/{ORG_PATENTS_INDEX}",
|
||||||
|
headers=self._headers(),
|
||||||
|
json={"mappings": ORG_PATENTS_MAPPING},
|
||||||
|
)
|
||||||
|
create_response.raise_for_status()
|
||||||
|
logger.info("Created index %s", ORG_PATENTS_INDEX)
|
||||||
|
return
|
||||||
|
|
||||||
|
response.raise_for_status()
|
||||||
|
mapping_response = await client.put(
|
||||||
|
f"/{ORG_PATENTS_INDEX}/_mapping",
|
||||||
|
headers=self._headers(),
|
||||||
|
json=ORG_PATENTS_MAPPING,
|
||||||
|
)
|
||||||
|
mapping_response.raise_for_status()
|
||||||
|
|
||||||
|
async def delete_by_institution(self, institution_id: str) -> int:
|
||||||
|
payload = {
|
||||||
|
"query": {"term": {"institution_id": institution_id.upper()}},
|
||||||
|
}
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=self.timeout,
|
||||||
|
transport=self.transport,
|
||||||
|
) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"/{ORG_PATENTS_INDEX}/_delete_by_query",
|
||||||
|
headers=self._headers(),
|
||||||
|
json=payload,
|
||||||
|
params={"refresh": "true"},
|
||||||
|
)
|
||||||
|
if response.status_code == 404:
|
||||||
|
return 0
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json().get("deleted", 0)
|
||||||
|
|
||||||
|
async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None:
|
||||||
|
if not documents:
|
||||||
|
return
|
||||||
|
|
||||||
|
batch_size = 500
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=self.timeout,
|
||||||
|
transport=self.transport,
|
||||||
|
) as client:
|
||||||
|
for start in range(0, len(documents), batch_size):
|
||||||
|
batch = documents[start : start + batch_size]
|
||||||
|
bulk_lines: list[str] = []
|
||||||
|
for doc_id, source in batch:
|
||||||
|
bulk_lines.append(json.dumps({"index": {"_index": ORG_PATENTS_INDEX, "_id": doc_id}}))
|
||||||
|
bulk_lines.append(json.dumps(source))
|
||||||
|
|
||||||
|
payload = "\n".join(bulk_lines) + "\n"
|
||||||
|
response = await client.post(
|
||||||
|
"/_bulk",
|
||||||
|
content=payload,
|
||||||
|
headers=self._headers("application/x-ndjson"),
|
||||||
|
params={"refresh": "true"},
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
result = response.json()
|
||||||
|
if result.get("errors"):
|
||||||
|
failed = [
|
||||||
|
item
|
||||||
|
for item in result.get("items", [])
|
||||||
|
if item.get("index", {}).get("status", 200) >= 400
|
||||||
|
]
|
||||||
|
logger.error("Bulk index errors: %s", failed[:3])
|
||||||
|
raise RuntimeError("Bulk indexing into org_patents failed.")
|
||||||
|
|
||||||
|
async def search_by_institution(
|
||||||
|
self,
|
||||||
|
institution_id: str,
|
||||||
|
match_type: MatchTypeFilter = "all",
|
||||||
|
page: int = 0,
|
||||||
|
size: int = DEFAULT_PAGE_SIZE,
|
||||||
|
source: str | None = None,
|
||||||
|
) -> tuple[list[OrgPatentEntry], int]:
|
||||||
|
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
||||||
|
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
|
||||||
|
|
||||||
|
if match_type == "institution":
|
||||||
|
filters.append({"terms": {"match_type": ["institution", "both"]}})
|
||||||
|
elif match_type == "name":
|
||||||
|
filters.append({"terms": {"match_type": ["name", "both"]}})
|
||||||
|
elif match_type == "both":
|
||||||
|
filters.append({"term": {"match_type": "both"}})
|
||||||
|
|
||||||
|
if source in ("EPO", "USPTO"):
|
||||||
|
filters.append({"term": {"source": source}})
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"from": page * size,
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
"query": {"bool": {"filter": filters}},
|
||||||
|
"sort": [
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"patent_id": {"order": "asc"}},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
timeout=self.timeout,
|
||||||
|
transport=self.transport,
|
||||||
|
) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"/{ORG_PATENTS_INDEX}/_search",
|
||||||
|
headers=self._headers(),
|
||||||
|
json=payload,
|
||||||
|
)
|
||||||
|
if response.status_code == 404:
|
||||||
|
return [], 0
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
|
||||||
|
total = data.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])]
|
||||||
|
return patents, total
|
||||||
|
|
||||||
|
|
||||||
|
def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
publication_year = source.get("publication_year")
|
||||||
|
return OrgPatentEntry(
|
||||||
|
institution_id=source.get("institution_id", ""),
|
||||||
|
institution_name=source.get("institution_name"),
|
||||||
|
patent_id=source.get("patent_id", ""),
|
||||||
|
source=source.get("source", ""),
|
||||||
|
match_type=source.get("match_type", "institution"),
|
||||||
|
title=source.get("title"),
|
||||||
|
abstract=source.get("abstract"),
|
||||||
|
publication_date=source.get("publication_date"),
|
||||||
|
publication_year=str(publication_year) if publication_year is not None else None,
|
||||||
|
application_number=source.get("application_number"),
|
||||||
|
application_date=source.get("application_date"),
|
||||||
|
kind=source.get("kind"),
|
||||||
|
application_type=source.get("application_type"),
|
||||||
|
number_of_claims=source.get("number_of_claims"),
|
||||||
|
status=source.get("status"),
|
||||||
|
inventors=source.get("inventors") or [],
|
||||||
|
assignees=source.get("assignees") or [],
|
||||||
|
ipc=source.get("ipc") or [],
|
||||||
|
cpc=source.get("cpc") or [],
|
||||||
|
country=source.get("country"),
|
||||||
|
matched_authors=source.get("matched_authors") or [],
|
||||||
|
)
|
||||||
@@ -0,0 +1,429 @@
|
|||||||
|
"""Business logic for org_patents index build and retrieval."""
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||||
|
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
|
||||||
|
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.models.openalex.author import Author
|
||||||
|
from inse.patents.authors.name_matching import name_matches
|
||||||
|
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||||
|
from inse.patents.common.model import PatentEntry
|
||||||
|
from inse.patents.common.parsing import (
|
||||||
|
deduplicate_patents,
|
||||||
|
enrich_patents_classifications,
|
||||||
|
parse_epo_hits,
|
||||||
|
parse_uspto_hits,
|
||||||
|
patent_dedup_key,
|
||||||
|
)
|
||||||
|
from inse.patents.institutions.logic import get_patents_by_institution_id
|
||||||
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
|
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||||
|
from inse.patents.org.model import (
|
||||||
|
MatchType,
|
||||||
|
MatchTypeFilter,
|
||||||
|
MatchedAuthor,
|
||||||
|
OrgPatentEntry,
|
||||||
|
OrgPatentsResponse,
|
||||||
|
)
|
||||||
|
from inse.patents.search_client import PatentSearchClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
AUTHOR_PAGE_SIZE = 500
|
||||||
|
ORG_PATENT_SEARCH_SIZE = 500
|
||||||
|
AUTHOR_SEARCH_CONCURRENCY = 8
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_last_name(name: str | None) -> str | None:
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
parts = name.strip().split()
|
||||||
|
return parts[-1] if parts else None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_first_name(name: str | None) -> str | None:
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
parts = name.strip().split()
|
||||||
|
return parts[0] if len(parts) > 1 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _filter_patents_by_name(
|
||||||
|
patents: list[PatentEntry],
|
||||||
|
first_name: str,
|
||||||
|
last_name: str,
|
||||||
|
) -> list[PatentEntry]:
|
||||||
|
return [
|
||||||
|
patent
|
||||||
|
for patent in patents
|
||||||
|
if any(
|
||||||
|
name_matches(inventor, first_name, last_name)
|
||||||
|
for inventor in patent.inventors
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _AccumulatedPatent:
|
||||||
|
patent: PatentEntry
|
||||||
|
institution_match: bool = False
|
||||||
|
matched_authors: dict[str, MatchedAuthor] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_institution_id(institution_id: str) -> str:
|
||||||
|
return institution_id.replace("https://openalex.org/", "").upper()
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_author_id(author_id: str | None) -> str:
|
||||||
|
if not author_id:
|
||||||
|
return ""
|
||||||
|
return author_id.replace("https://openalex.org/", "").upper()
|
||||||
|
|
||||||
|
|
||||||
|
def org_patent_document_id(institution_id: str, patent: PatentEntry) -> str:
|
||||||
|
stage = patent.kind or patent.application_type or "none"
|
||||||
|
safe_patent_id = re.sub(r"[^A-Za-z0-9_-]", "_", patent.patent_id)
|
||||||
|
safe_date = patent.publication_date or "none"
|
||||||
|
safe_stage = re.sub(r"[^A-Za-z0-9_-]", "_", stage)
|
||||||
|
return f"{normalize_institution_id(institution_id)}_{patent.source}_{safe_patent_id}_{safe_date}_{safe_stage}"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchType:
|
||||||
|
if institution_match and has_name_match:
|
||||||
|
return "both"
|
||||||
|
if institution_match:
|
||||||
|
return "institution"
|
||||||
|
return "name"
|
||||||
|
|
||||||
|
|
||||||
|
def merge_org_patents(
|
||||||
|
institution_id: str,
|
||||||
|
institution_name: str | None,
|
||||||
|
institution_patents: list[PatentEntry],
|
||||||
|
author_patents: list[tuple[Author, list[PatentEntry]]],
|
||||||
|
) -> list[OrgPatentEntry]:
|
||||||
|
accumulated: dict[tuple[str, str, str, str], _AccumulatedPatent] = {}
|
||||||
|
|
||||||
|
for patent in institution_patents:
|
||||||
|
key = patent_dedup_key(patent)
|
||||||
|
entry = accumulated.get(key)
|
||||||
|
if entry is None:
|
||||||
|
accumulated[key] = _AccumulatedPatent(patent=patent, institution_match=True)
|
||||||
|
else:
|
||||||
|
entry.institution_match = True
|
||||||
|
|
||||||
|
for author, patents in author_patents:
|
||||||
|
author_id = normalize_author_id(author.id)
|
||||||
|
author_name = author.display_name or ""
|
||||||
|
if not author_id or not author_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
matched_author = MatchedAuthor(
|
||||||
|
openalex_author_id=author_id,
|
||||||
|
author_name=author_name,
|
||||||
|
)
|
||||||
|
for patent in patents:
|
||||||
|
key = patent_dedup_key(patent)
|
||||||
|
entry = accumulated.get(key)
|
||||||
|
if entry is None:
|
||||||
|
accumulated[key] = _AccumulatedPatent(
|
||||||
|
patent=patent,
|
||||||
|
matched_authors={author_id: matched_author},
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
entry.matched_authors[author_id] = matched_author
|
||||||
|
|
||||||
|
org_patents: list[OrgPatentEntry] = []
|
||||||
|
short_institution_id = normalize_institution_id(institution_id)
|
||||||
|
|
||||||
|
for entry in accumulated.values():
|
||||||
|
has_name_match = bool(entry.matched_authors)
|
||||||
|
match_type = resolve_match_type(entry.institution_match, has_name_match)
|
||||||
|
org_patents.append(
|
||||||
|
OrgPatentEntry(
|
||||||
|
institution_id=short_institution_id,
|
||||||
|
institution_name=institution_name,
|
||||||
|
match_type=match_type,
|
||||||
|
matched_authors=list(entry.matched_authors.values()),
|
||||||
|
**entry.patent.model_dump(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
org_patents.sort(
|
||||||
|
key=lambda patent: (
|
||||||
|
patent.publication_year or "",
|
||||||
|
patent.patent_id,
|
||||||
|
),
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
return org_patents
|
||||||
|
|
||||||
|
|
||||||
|
def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
|
||||||
|
publication_year = None
|
||||||
|
if patent.publication_year:
|
||||||
|
try:
|
||||||
|
publication_year = int(patent.publication_year)
|
||||||
|
except ValueError:
|
||||||
|
publication_year = None
|
||||||
|
|
||||||
|
return {
|
||||||
|
"institution_id": patent.institution_id,
|
||||||
|
"institution_name": patent.institution_name,
|
||||||
|
"patent_id": patent.patent_id,
|
||||||
|
"source": patent.source,
|
||||||
|
"match_type": patent.match_type,
|
||||||
|
"title": patent.title,
|
||||||
|
"abstract": patent.abstract,
|
||||||
|
"publication_date": patent.publication_date,
|
||||||
|
"publication_year": publication_year,
|
||||||
|
"application_number": patent.application_number,
|
||||||
|
"application_date": patent.application_date,
|
||||||
|
"kind": patent.kind,
|
||||||
|
"application_type": patent.application_type,
|
||||||
|
"number_of_claims": patent.number_of_claims,
|
||||||
|
"status": patent.status,
|
||||||
|
"inventors": patent.inventors,
|
||||||
|
"assignees": patent.assignees,
|
||||||
|
"ipc": patent.ipc,
|
||||||
|
"cpc": patent.cpc,
|
||||||
|
"country": patent.country,
|
||||||
|
"matched_authors": [
|
||||||
|
author.model_dump() for author in patent.matched_authors
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_authors_for_institution(institution_id: str) -> list[Author]:
|
||||||
|
short_id = normalize_institution_id(institution_id)
|
||||||
|
query = {
|
||||||
|
"nested": {
|
||||||
|
"path": "last_known_institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"last_known_institutions.id": f"https://openalex.org/{short_id}",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
authors: list[Author] = []
|
||||||
|
search_after: list | None = None
|
||||||
|
sort = [
|
||||||
|
{"works_count": {"order": "desc"}},
|
||||||
|
{"id": {"order": "asc"}},
|
||||||
|
]
|
||||||
|
|
||||||
|
while True:
|
||||||
|
body: dict = {
|
||||||
|
"size": AUTHOR_PAGE_SIZE,
|
||||||
|
"query": query,
|
||||||
|
"sort": sort,
|
||||||
|
}
|
||||||
|
if search_after:
|
||||||
|
body["search_after"] = search_after
|
||||||
|
|
||||||
|
response = elasticsearch.search(index="openalex-authors", body=body)
|
||||||
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
if not hits:
|
||||||
|
break
|
||||||
|
|
||||||
|
for hit in hits:
|
||||||
|
source = dict(hit.get("_source", {}))
|
||||||
|
source["id"] = source.get("id") or hit.get("_id", "")
|
||||||
|
author = Author.from_dict(source)
|
||||||
|
if author:
|
||||||
|
authors.append(author)
|
||||||
|
|
||||||
|
if len(hits) < AUTHOR_PAGE_SIZE:
|
||||||
|
break
|
||||||
|
search_after = hits[-1].get("sort")
|
||||||
|
if not search_after:
|
||||||
|
break
|
||||||
|
|
||||||
|
return authors
|
||||||
|
|
||||||
|
|
||||||
|
async def _search_patents_by_author(
|
||||||
|
author: Author,
|
||||||
|
search_client: PatentSearchClient,
|
||||||
|
) -> list[PatentEntry]:
|
||||||
|
author_name = author.display_name
|
||||||
|
last_name = _extract_last_name(author_name)
|
||||||
|
first_name = _extract_first_name(author_name)
|
||||||
|
if not last_name:
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
epo_data, uspto_data = await asyncio.gather(
|
||||||
|
search_client.search_epo(
|
||||||
|
search_client.epo_query_by_inventor(
|
||||||
|
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
|
||||||
|
)
|
||||||
|
),
|
||||||
|
search_client.search_uspto(
|
||||||
|
search_client.uspto_query_by_inventor(
|
||||||
|
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
|
||||||
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
except (MissingApiKeyError, httpx.HTTPError):
|
||||||
|
raise
|
||||||
|
|
||||||
|
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||||
|
if first_name and last_name:
|
||||||
|
patents = _filter_patents_by_name(patents, first_name, last_name)
|
||||||
|
return deduplicate_patents(patents)
|
||||||
|
|
||||||
|
|
||||||
|
async def build_org_patents_for_institution(
|
||||||
|
institution_id: str,
|
||||||
|
search_client: PatentSearchClient | None = None,
|
||||||
|
ipc_client: IpcSearchClient | None = None,
|
||||||
|
institutions_client: InstitutionsSearchClient | None = None,
|
||||||
|
) -> list[OrgPatentEntry]:
|
||||||
|
patent_client = search_client or PatentSearchClient()
|
||||||
|
ipc_search_client = ipc_client or IpcSearchClient()
|
||||||
|
institution_client = institutions_client or InstitutionsSearchClient()
|
||||||
|
|
||||||
|
short_id = normalize_institution_id(institution_id)
|
||||||
|
institution = institution_client.get_institution_by_id(short_id)
|
||||||
|
institution_name = institution.display_name
|
||||||
|
|
||||||
|
institution_response = await get_patents_by_institution_id(
|
||||||
|
institution_id=short_id,
|
||||||
|
client=patent_client,
|
||||||
|
ipc_client=ipc_search_client,
|
||||||
|
institutions_client=institution_client,
|
||||||
|
)
|
||||||
|
institution_patents = institution_response.patents
|
||||||
|
|
||||||
|
authors = fetch_authors_for_institution(short_id)
|
||||||
|
logger.info(
|
||||||
|
"Building org_patents for %s (%s): %d authors, %d institution patents",
|
||||||
|
institution_name,
|
||||||
|
short_id,
|
||||||
|
len(authors),
|
||||||
|
len(institution_patents),
|
||||||
|
)
|
||||||
|
|
||||||
|
semaphore = asyncio.Semaphore(AUTHOR_SEARCH_CONCURRENCY)
|
||||||
|
|
||||||
|
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
|
||||||
|
async with semaphore:
|
||||||
|
patents = await _search_patents_by_author(author, patent_client)
|
||||||
|
return author, patents
|
||||||
|
|
||||||
|
author_results = await asyncio.gather(
|
||||||
|
*[_fetch_for_author(author) for author in authors],
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
author_patents: list[tuple[Author, list[PatentEntry]]] = []
|
||||||
|
for result in author_results:
|
||||||
|
if isinstance(result, Exception):
|
||||||
|
logger.warning("Author patent search failed: %s", result)
|
||||||
|
continue
|
||||||
|
author_patents.append(result)
|
||||||
|
|
||||||
|
org_patents = merge_org_patents(
|
||||||
|
institution_id=short_id,
|
||||||
|
institution_name=institution_name,
|
||||||
|
institution_patents=institution_patents,
|
||||||
|
author_patents=author_patents,
|
||||||
|
)
|
||||||
|
|
||||||
|
await enrich_patents_classifications(
|
||||||
|
[patent for patent in org_patents],
|
||||||
|
ipc_search_client,
|
||||||
|
)
|
||||||
|
return org_patents
|
||||||
|
|
||||||
|
|
||||||
|
async def index_org_patents_for_institution(
|
||||||
|
institution_id: str,
|
||||||
|
search_client: PatentSearchClient | None = None,
|
||||||
|
ipc_client: IpcSearchClient | None = None,
|
||||||
|
institutions_client: InstitutionsSearchClient | None = None,
|
||||||
|
org_client: OrgPatentsSearchClient | None = None,
|
||||||
|
) -> int:
|
||||||
|
short_id = normalize_institution_id(institution_id)
|
||||||
|
org_patents_client = org_client or OrgPatentsSearchClient()
|
||||||
|
|
||||||
|
org_patents = await build_org_patents_for_institution(
|
||||||
|
institution_id=short_id,
|
||||||
|
search_client=search_client,
|
||||||
|
ipc_client=ipc_client,
|
||||||
|
institutions_client=institutions_client,
|
||||||
|
)
|
||||||
|
|
||||||
|
await org_patents_client.ensure_index()
|
||||||
|
deleted = await org_patents_client.delete_by_institution(short_id)
|
||||||
|
logger.info("Deleted %d existing org_patents documents for %s", deleted, short_id)
|
||||||
|
|
||||||
|
documents = [
|
||||||
|
(
|
||||||
|
org_patent_document_id(short_id, patent),
|
||||||
|
org_patent_to_es_document(patent),
|
||||||
|
)
|
||||||
|
for patent in org_patents
|
||||||
|
]
|
||||||
|
await org_patents_client.bulk_index(documents)
|
||||||
|
logger.info("Indexed %d org_patents documents for %s", len(documents), short_id)
|
||||||
|
return len(documents)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_org_patents_by_institution_id(
|
||||||
|
institution_id: str,
|
||||||
|
match_type: MatchTypeFilter = "all",
|
||||||
|
page: int = 0,
|
||||||
|
size: int = 20,
|
||||||
|
source: str | None = None,
|
||||||
|
org_client: OrgPatentsSearchClient | None = None,
|
||||||
|
institutions_client: InstitutionsSearchClient | None = None,
|
||||||
|
) -> OrgPatentsResponse:
|
||||||
|
short_id = normalize_institution_id(institution_id)
|
||||||
|
org_patents_client = org_client or OrgPatentsSearchClient()
|
||||||
|
institution_client = institutions_client or InstitutionsSearchClient()
|
||||||
|
|
||||||
|
try:
|
||||||
|
institution = institution_client.get_institution_by_id(short_id)
|
||||||
|
institution_name = institution.display_name
|
||||||
|
except Exception:
|
||||||
|
institution_name = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
await org_patents_client.ensure_index()
|
||||||
|
patents, total = await org_patents_client.search_by_institution(
|
||||||
|
institution_id=short_id,
|
||||||
|
match_type=match_type,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
source=source,
|
||||||
|
)
|
||||||
|
except MissingApiKeyError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Patent search is not configured.",
|
||||||
|
) from exc
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=HTTP_502_BAD_GATEWAY,
|
||||||
|
detail="org_patents search request failed.",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
return OrgPatentsResponse(
|
||||||
|
institution_id=short_id,
|
||||||
|
institution_name=institution_name,
|
||||||
|
patent_count=total,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
patents=patents,
|
||||||
|
)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
ORG_PATENTS_INDEX = "org_patents"
|
||||||
|
|
||||||
|
ORG_PATENTS_MAPPING = {
|
||||||
|
"properties": {
|
||||||
|
"institution_id": {"type": "keyword"},
|
||||||
|
"institution_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||||
|
"patent_id": {"type": "keyword"},
|
||||||
|
"source": {"type": "keyword"},
|
||||||
|
"match_type": {"type": "keyword"},
|
||||||
|
"title": {"type": "text"},
|
||||||
|
"abstract": {"type": "text"},
|
||||||
|
"publication_date": {"type": "keyword"},
|
||||||
|
"publication_year": {"type": "integer"},
|
||||||
|
"application_number": {"type": "keyword"},
|
||||||
|
"application_date": {"type": "keyword"},
|
||||||
|
"kind": {"type": "keyword"},
|
||||||
|
"application_type": {"type": "keyword"},
|
||||||
|
"number_of_claims": {"type": "integer"},
|
||||||
|
"status": {"type": "keyword"},
|
||||||
|
"inventors": {"type": "keyword"},
|
||||||
|
"assignees": {"type": "keyword"},
|
||||||
|
"ipc": {"type": "keyword"},
|
||||||
|
"cpc": {"type": "keyword"},
|
||||||
|
"country": {"type": "keyword"},
|
||||||
|
"matched_authors": {
|
||||||
|
"type": "nested",
|
||||||
|
"properties": {
|
||||||
|
"openalex_author_id": {"type": "keyword"},
|
||||||
|
"author_name": {"type": "keyword"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from inse.patents.common.model import PatentEntry
|
||||||
|
|
||||||
|
MatchType = Literal["institution", "name", "both"]
|
||||||
|
MatchTypeFilter = Literal["institution", "name", "both", "all"]
|
||||||
|
|
||||||
|
|
||||||
|
class MatchedAuthor(BaseModel):
|
||||||
|
openalex_author_id: str
|
||||||
|
author_name: str
|
||||||
|
|
||||||
|
|
||||||
|
class OrgPatentEntry(PatentEntry):
|
||||||
|
institution_id: str
|
||||||
|
institution_name: str | None = None
|
||||||
|
match_type: MatchType
|
||||||
|
matched_authors: list[MatchedAuthor] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class OrgPatentsResponse(BaseModel):
|
||||||
|
institution_id: str
|
||||||
|
institution_name: str | None = None
|
||||||
|
patent_count: int
|
||||||
|
page: int = 0
|
||||||
|
size: int = 20
|
||||||
|
patents: list[OrgPatentEntry]
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
|
||||||
|
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||||
|
from inse.patents.org import logic
|
||||||
|
from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||||
|
return InstitutionsSearchClient()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{id}/org-patents",
|
||||||
|
operation_id="getOrgPatentsByInstitution",
|
||||||
|
response_model=OrgPatentsResponse,
|
||||||
|
summary="Get pre-indexed org patents for an institution.",
|
||||||
|
)
|
||||||
|
async def get_org_patents_by_institution(
|
||||||
|
id: str,
|
||||||
|
client: Annotated[
|
||||||
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
|
],
|
||||||
|
match_type: Annotated[
|
||||||
|
MatchTypeFilter,
|
||||||
|
Query(description="Filter patents by match type."),
|
||||||
|
] = "all",
|
||||||
|
page: int = 0,
|
||||||
|
size: int = 20,
|
||||||
|
source: str | None = None,
|
||||||
|
) -> OrgPatentsResponse:
|
||||||
|
return await logic.get_org_patents_by_institution_id(
|
||||||
|
institution_id=id,
|
||||||
|
match_type=match_type,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
source=source,
|
||||||
|
institutions_client=client,
|
||||||
|
)
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
from inse.patents.common.model import PatentEntry
|
||||||
|
from inse.patents.org.logic import merge_org_patents, org_patent_document_id, resolve_match_type
|
||||||
|
from inse.patents.org.model import MatchedAuthor
|
||||||
|
from inse.models.openalex.author import Author
|
||||||
|
|
||||||
|
|
||||||
|
def _patent(
|
||||||
|
patent_id: str = "EP1234567",
|
||||||
|
source: str = "EPO",
|
||||||
|
) -> PatentEntry:
|
||||||
|
return PatentEntry(
|
||||||
|
patent_id=patent_id,
|
||||||
|
source=source,
|
||||||
|
title="Example patent",
|
||||||
|
publication_year="2024",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _author(author_id: str, name: str) -> Author:
|
||||||
|
return Author(
|
||||||
|
id=f"https://openalex.org/{author_id}",
|
||||||
|
display_name=name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_match_type() -> None:
|
||||||
|
assert resolve_match_type(True, True) == "both"
|
||||||
|
assert resolve_match_type(True, False) == "institution"
|
||||||
|
assert resolve_match_type(False, True) == "name"
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_org_patents_keeps_institution_only_patents() -> None:
|
||||||
|
result = merge_org_patents(
|
||||||
|
institution_id="I62318514",
|
||||||
|
institution_name="University of Duisburg-Essen",
|
||||||
|
institution_patents=[_patent("EP111")],
|
||||||
|
author_patents=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].match_type == "institution"
|
||||||
|
assert result[0].matched_authors == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_org_patents_keeps_name_only_patents() -> None:
|
||||||
|
author = _author("A123", "Max Mustermann")
|
||||||
|
result = merge_org_patents(
|
||||||
|
institution_id="I62318514",
|
||||||
|
institution_name="University of Duisburg-Essen",
|
||||||
|
institution_patents=[],
|
||||||
|
author_patents=[(author, [_patent("EP222")])],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].match_type == "name"
|
||||||
|
assert result[0].matched_authors[0].openalex_author_id == "A123"
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_org_patents_marks_both_when_same_patent_found_twice() -> None:
|
||||||
|
author = _author("A123", "Max Mustermann")
|
||||||
|
patent = _patent("EP333")
|
||||||
|
result = merge_org_patents(
|
||||||
|
institution_id="I62318514",
|
||||||
|
institution_name="University of Duisburg-Essen",
|
||||||
|
institution_patents=[patent],
|
||||||
|
author_patents=[(author, [patent])],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].match_type == "both"
|
||||||
|
assert len(result[0].matched_authors) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_org_patents_deduplicates_and_collects_multiple_authors() -> None:
|
||||||
|
author_one = _author("A111", "Max Mustermann")
|
||||||
|
author_two = _author("A222", "Maria Muster")
|
||||||
|
patent = _patent("EP444")
|
||||||
|
result = merge_org_patents(
|
||||||
|
institution_id="I62318514",
|
||||||
|
institution_name="University of Duisburg-Essen",
|
||||||
|
institution_patents=[],
|
||||||
|
author_patents=[
|
||||||
|
(author_one, [patent]),
|
||||||
|
(author_two, [patent]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].match_type == "name"
|
||||||
|
assert {author.openalex_author_id for author in result[0].matched_authors} == {"A111", "A222"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_org_patent_document_id_is_stable() -> None:
|
||||||
|
patent = _patent("EP1234567")
|
||||||
|
patent.kind = "A1"
|
||||||
|
patent.publication_date = "20240101"
|
||||||
|
|
||||||
|
doc_id = org_patent_document_id("I62318514", patent)
|
||||||
|
|
||||||
|
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Combined patent Elasticsearch client."""
|
||||||
|
from inse.patents.authors.search_queries import InventorSearchQueries
|
||||||
|
from inse.patents.common.elastic_search_client import (
|
||||||
|
DEFAULT_SEARCH_SIZE,
|
||||||
|
EPO_INDEX,
|
||||||
|
USPTO_INDEX,
|
||||||
|
BasePatentSearchClient,
|
||||||
|
MissingApiKeyError,
|
||||||
|
)
|
||||||
|
from inse.patents.institutions.search_queries import AssigneeSearchQueries
|
||||||
|
|
||||||
|
|
||||||
|
class PatentSearchClient(
|
||||||
|
InventorSearchQueries,
|
||||||
|
AssigneeSearchQueries,
|
||||||
|
BasePatentSearchClient,
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"DEFAULT_SEARCH_SIZE",
|
||||||
|
"EPO_INDEX",
|
||||||
|
"MissingApiKeyError",
|
||||||
|
"PatentSearchClient",
|
||||||
|
"USPTO_INDEX",
|
||||||
|
]
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
#!/usr/bin/env python
|
"""Aggregates patent API routers."""
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
from . import logic
|
from . import logic
|
||||||
from . import model
|
from . import model
|
||||||
@@ -11,6 +10,10 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
|||||||
|
|
||||||
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||||
|
|
||||||
|
from inse.patents.all.service import router as all_patents_router
|
||||||
|
from inse.patents.authors.service import router as author_patents_router
|
||||||
|
from inse.patents.institutions.service import router as institution_patents_router
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/{author_id}/patents",
|
"/{author_id}/patents",
|
||||||
@@ -37,8 +40,11 @@ async def get_patent_by_identifier(
|
|||||||
description="Do we want to fallback to title search if ID and DOI dont work?"
|
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||||
),
|
),
|
||||||
] = "",
|
] = "",
|
||||||
|
filling_date: Annotated[
|
||||||
|
Optional[str], Query(description="Filling date in YYYY-MM-DD format")
|
||||||
|
] = "",
|
||||||
) -> model.PatentEntry | None:
|
) -> model.PatentEntry | None:
|
||||||
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title)
|
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date)
|
||||||
|
|
||||||
|
|
||||||
@patents_router.get(
|
@patents_router.get(
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
from inse.patents import model
|
||||||
|
from inse.patents.institutions.logic import filter_patents_by_institution
|
||||||
|
from inse.patents.institutions.name_matching import (
|
||||||
|
assignee_matches_institution_name,
|
||||||
|
institution_search_variants,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_institution_search_variants_exclude_single_letter_initials() -> None:
|
||||||
|
variants = institution_search_variants("Harvard University")
|
||||||
|
|
||||||
|
assert "H" not in variants
|
||||||
|
assert "U" not in variants
|
||||||
|
assert any("Harvard" in variant for variant in variants)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignee_matches_institution_name_accepts_valid_university() -> None:
|
||||||
|
assert assignee_matches_institution_name(
|
||||||
|
"Universitaet Duisburg-Essen",
|
||||||
|
"University of Duisburg-Essen",
|
||||||
|
)
|
||||||
|
assert assignee_matches_institution_name(
|
||||||
|
"President and Fellows of Harvard College",
|
||||||
|
"Harvard University",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignee_matches_institution_name_rejects_false_positives() -> None:
|
||||||
|
assert not assignee_matches_institution_name("u-blox AG", "Harvard University")
|
||||||
|
assert not assignee_matches_institution_name(
|
||||||
|
"LG H&H CO., LTD.",
|
||||||
|
"Harvard University",
|
||||||
|
)
|
||||||
|
assert not assignee_matches_institution_name(
|
||||||
|
"K & N Engineering, Inc.",
|
||||||
|
"National Institute for Fusion Science",
|
||||||
|
)
|
||||||
|
assert not assignee_matches_institution_name(
|
||||||
|
"K&K INC.",
|
||||||
|
"National Institute for Fusion Science",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_patents_by_institution_removes_unrelated_assignees() -> None:
|
||||||
|
institution = _institution(
|
||||||
|
display_name="Harvard University",
|
||||||
|
alternatives=["Universidad de Harvard"],
|
||||||
|
)
|
||||||
|
patents = [
|
||||||
|
model.PatentEntry(
|
||||||
|
patent_id="US1",
|
||||||
|
source="USPTO",
|
||||||
|
assignees=["President and Fellows of Harvard College"],
|
||||||
|
),
|
||||||
|
model.PatentEntry(
|
||||||
|
patent_id="US2",
|
||||||
|
source="USPTO",
|
||||||
|
assignees=["u-blox AG"],
|
||||||
|
),
|
||||||
|
model.PatentEntry(
|
||||||
|
patent_id="US3",
|
||||||
|
source="USPTO",
|
||||||
|
assignees=["LG H&H CO., LTD."],
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
result = filter_patents_by_institution(patents, institution)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].patent_id == "US1"
|
||||||
|
|
||||||
|
|
||||||
|
def _institution(
|
||||||
|
display_name: str,
|
||||||
|
alternatives: list[str] | None = None,
|
||||||
|
):
|
||||||
|
from inse.models.openalex.institution import Institution
|
||||||
|
|
||||||
|
return Institution(
|
||||||
|
id="https://openalex.org/I123",
|
||||||
|
display_name=display_name,
|
||||||
|
display_name_alternatives=alternatives,
|
||||||
|
)
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
from inse.patents import logic, model
|
from inse.patents import model
|
||||||
|
from inse.patents.common.parsing import deduplicate_patents
|
||||||
|
from inse.patents.institutions.logic import filter_patents_by_institution
|
||||||
|
|
||||||
|
|
||||||
def _uspto_patent(
|
def _uspto_patent(
|
||||||
@@ -34,7 +36,7 @@ def _epo_patent(
|
|||||||
def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
||||||
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
|
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
|
||||||
|
|
||||||
result = logic._deduplicate_patents(patents)
|
result = deduplicate_patents(patents)
|
||||||
|
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result[0].patent_id == "US12508845"
|
assert result[0].patent_id == "US12508845"
|
||||||
@@ -43,7 +45,7 @@ def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
|||||||
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
|
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
|
||||||
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
|
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
|
||||||
|
|
||||||
result = logic._deduplicate_patents(patents)
|
result = deduplicate_patents(patents)
|
||||||
|
|
||||||
assert len(result) == 2
|
assert len(result) == 2
|
||||||
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
|
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
|
||||||
@@ -55,7 +57,7 @@ def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None
|
|||||||
duplicate = _uspto_patent()
|
duplicate = _uspto_patent()
|
||||||
duplicate.abstract = "Second abstract"
|
duplicate.abstract = "Second abstract"
|
||||||
|
|
||||||
result = logic._deduplicate_patents([first, duplicate])
|
result = deduplicate_patents([first, duplicate])
|
||||||
|
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result[0].abstract == "First abstract"
|
assert result[0].abstract == "First abstract"
|
||||||
@@ -65,7 +67,7 @@ def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
|
|||||||
application = _epo_patent(publication_date="20161005", kind="A1")
|
application = _epo_patent(publication_date="20161005", kind="A1")
|
||||||
grant = _epo_patent(publication_date="20180411", kind="B1")
|
grant = _epo_patent(publication_date="20180411", kind="B1")
|
||||||
|
|
||||||
result = logic._deduplicate_patents([application, grant])
|
result = deduplicate_patents([application, grant])
|
||||||
|
|
||||||
assert len(result) == 2
|
assert len(result) == 2
|
||||||
assert [patent.kind for patent in result] == ["A1", "B1"]
|
assert [patent.kind for patent in result] == ["A1", "B1"]
|
||||||
@@ -75,7 +77,7 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() ->
|
|||||||
earlier = _uspto_patent(publication_date="20241230")
|
earlier = _uspto_patent(publication_date="20241230")
|
||||||
later = _uspto_patent(publication_date="20251230")
|
later = _uspto_patent(publication_date="20251230")
|
||||||
|
|
||||||
result = logic._deduplicate_patents([earlier, later])
|
result = deduplicate_patents([earlier, later])
|
||||||
|
|
||||||
assert len(result) == 2
|
assert len(result) == 2
|
||||||
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
|
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
|
||||||
@@ -85,7 +87,58 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types
|
|||||||
utility = _uspto_patent(application_type="utility")
|
utility = _uspto_patent(application_type="utility")
|
||||||
reissue = _uspto_patent(application_type="reissue")
|
reissue = _uspto_patent(application_type="reissue")
|
||||||
|
|
||||||
result = logic._deduplicate_patents([utility, reissue])
|
result = deduplicate_patents([utility, reissue])
|
||||||
|
|
||||||
assert len(result) == 2
|
assert len(result) == 2
|
||||||
assert [patent.application_type for patent in result] == ["utility", "reissue"]
|
assert [patent.application_type for patent in result] == ["utility", "reissue"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignee_matches_institution_name_accepts_alternative_names() -> None:
|
||||||
|
from inse.patents.name_matching import assignee_matches_institution_name
|
||||||
|
|
||||||
|
assert assignee_matches_institution_name(
|
||||||
|
"Universitaet Duisburg-Essen",
|
||||||
|
"University of Duisburg-Essen",
|
||||||
|
)
|
||||||
|
assert not assignee_matches_institution_name(
|
||||||
|
"Harvard University",
|
||||||
|
"University of Duisburg-Essen",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_patents_by_institution_keeps_matching_assignees() -> None:
|
||||||
|
institution = _institution(
|
||||||
|
display_name="University of Duisburg-Essen",
|
||||||
|
alternatives=["Universität Duisburg-Essen"],
|
||||||
|
)
|
||||||
|
matching = model.PatentEntry(
|
||||||
|
patent_id="EP123",
|
||||||
|
source="EPO",
|
||||||
|
assignees=["University of Duisburg-Essen"],
|
||||||
|
)
|
||||||
|
other = model.PatentEntry(
|
||||||
|
patent_id="EP456",
|
||||||
|
source="EPO",
|
||||||
|
assignees=["Harvard University"],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = filter_patents_by_institution(
|
||||||
|
[matching, other],
|
||||||
|
institution,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0].patent_id == "EP123"
|
||||||
|
|
||||||
|
|
||||||
|
def _institution(
|
||||||
|
display_name: str,
|
||||||
|
alternatives: list[str] | None = None,
|
||||||
|
):
|
||||||
|
from inse.models.openalex.institution import Institution
|
||||||
|
|
||||||
|
return Institution(
|
||||||
|
id="https://openalex.org/I123",
|
||||||
|
display_name=display_name,
|
||||||
|
display_name_alternatives=alternatives,
|
||||||
|
)
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ from inse.persons.model import (
|
|||||||
CustomAuthorsListResponse,
|
CustomAuthorsListResponse,
|
||||||
CareerMetrics,
|
CareerMetrics,
|
||||||
)
|
)
|
||||||
|
from inse.works.logic import enrich_topic_descriptions
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
INDEX_NAME = "openalex-authors"
|
INDEX_NAME = "openalex-authors"
|
||||||
@@ -728,6 +729,10 @@ async def advanced_search_persons(
|
|||||||
)
|
)
|
||||||
results.append(custom_author)
|
results.append(custom_author)
|
||||||
|
|
||||||
|
await enrich_topic_descriptions(
|
||||||
|
[topic for author in results for topic in author.topics or []]
|
||||||
|
)
|
||||||
|
|
||||||
return CustomAuthorsListResponse(
|
return CustomAuthorsListResponse(
|
||||||
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,3 +12,4 @@ class Tags(StrEnum):
|
|||||||
AUTH = "Auth"
|
AUTH = "Auth"
|
||||||
ACCOUNT = "Account"
|
ACCOUNT = "Account"
|
||||||
ORGANIZATION = "Organization"
|
ORGANIZATION = "Organization"
|
||||||
|
UNIVERSITY_RANKINGS = "University Rankings"
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ Business logic for OpenAlex topics.
|
|||||||
import logging
|
import logging
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
import asyncio
|
||||||
import httpx
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from inse.exceptions import (
|
from inse.exceptions import (
|
||||||
UpstreamAPIException,
|
UpstreamAPIException,
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
@@ -22,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
|
|||||||
AutocompleteResponseResultsInner,
|
AutocompleteResponseResultsInner,
|
||||||
)
|
)
|
||||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||||
from inse.model import ESCluster
|
from inse.model import ESCluster, ESIndex
|
||||||
from .search_client import OpenAlexTopicsClient
|
from .search_client import TopicsSearchClient
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -39,15 +39,15 @@ async def list_topics(
|
|||||||
cursor: str | None = None,
|
cursor: str | None = None,
|
||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
client: OpenAlexTopicsClient | None = None,
|
client: TopicsSearchClient | None = None,
|
||||||
) -> TopicsListResponse:
|
) -> TopicsListResponse:
|
||||||
if sample is not None and (sort or page not in (None, 1)):
|
if sample is not None and (sort or page not in (None, 1)):
|
||||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||||
|
|
||||||
openalex_client = client or OpenAlexTopicsClient()
|
topics_client = client or TopicsSearchClient()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = await openalex_client.list_topics(
|
data = await topics_client.list_topics(
|
||||||
search=search,
|
search=search,
|
||||||
filter=filter,
|
filter=filter,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
@@ -58,25 +58,24 @@ async def list_topics(
|
|||||||
sample=sample,
|
sample=sample,
|
||||||
select=select,
|
select=select,
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc:
|
except ValueError as exc:
|
||||||
status_code = exc.response.status_code
|
raise BadRequestException(str(exc)) from exc
|
||||||
detail = "OpenAlex topics request failed."
|
except ElasticsearchException as exc:
|
||||||
try:
|
logger.exception("OpenAlex topics Elasticsearch request failed.")
|
||||||
error_body = exc.response.json()
|
|
||||||
detail = error_body.get("message") or error_body.get("error") or detail
|
|
||||||
except ValueError:
|
|
||||||
if exc.response.text:
|
|
||||||
detail = exc.response.text
|
|
||||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
|
||||||
except httpx.HTTPError as exc:
|
|
||||||
logger.exception("OpenAlex topics request failed.")
|
|
||||||
raise UpstreamAPIException(
|
raise UpstreamAPIException(
|
||||||
message="OpenAlex topics request failed.",
|
message="OpenAlex topics Elasticsearch request failed.",
|
||||||
status_code=502,
|
status_code=502,
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
try:
|
try:
|
||||||
normalized_data = _normalize_topics_response(data)
|
openalex_style_data = _elasticsearch_to_topics_response(
|
||||||
|
data,
|
||||||
|
per_page=per_page,
|
||||||
|
page=page,
|
||||||
|
cursor=cursor,
|
||||||
|
group_by=group_by,
|
||||||
|
)
|
||||||
|
normalized_data = _normalize_topics_response(openalex_style_data)
|
||||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||||
except ValidationError as exc:
|
except ValidationError as exc:
|
||||||
logger.exception("OpenAlex topics response could not be parsed.")
|
logger.exception("OpenAlex topics response could not be parsed.")
|
||||||
@@ -93,7 +92,7 @@ async def autocomplete_topics(
|
|||||||
field_id: str | None = None,
|
field_id: str | None = None,
|
||||||
subfield_id: str | None = None,
|
subfield_id: str | None = None,
|
||||||
limit: int = 10,
|
limit: int = 10,
|
||||||
client: OpenAlexTopicsClient | None = None,
|
client: TopicsSearchClient | None = None,
|
||||||
) -> AutocompleteResponse:
|
) -> AutocompleteResponse:
|
||||||
filters = []
|
filters = []
|
||||||
if domain_id:
|
if domain_id:
|
||||||
@@ -152,6 +151,99 @@ async def autocomplete_topics(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _elasticsearch_to_topics_response(
|
||||||
|
data: dict[str, Any],
|
||||||
|
*,
|
||||||
|
per_page: int,
|
||||||
|
page: int | None,
|
||||||
|
cursor: str | None,
|
||||||
|
group_by: str | None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Converts an Elasticsearch search response into the OpenAlex-style topics
|
||||||
|
response expected by TopicsListResponse.
|
||||||
|
|
||||||
|
Elasticsearch response shape:
|
||||||
|
|
||||||
|
{
|
||||||
|
"took": 12,
|
||||||
|
"hits": {
|
||||||
|
"total": {"value": 123},
|
||||||
|
"hits": [
|
||||||
|
{"_source": {...}, "sort": [...]}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"aggregations": {...}
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenAlex-style response shape:
|
||||||
|
|
||||||
|
{
|
||||||
|
"meta": {...},
|
||||||
|
"results": [...],
|
||||||
|
"group_by": [...]
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
hits_root = data.get("hits") or {}
|
||||||
|
raw_hits = hits_root.get("hits") or []
|
||||||
|
|
||||||
|
total = hits_root.get("total")
|
||||||
|
if isinstance(total, dict):
|
||||||
|
count = total.get("value")
|
||||||
|
else:
|
||||||
|
count = total
|
||||||
|
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
for hit in raw_hits:
|
||||||
|
if not isinstance(hit, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
source = hit.get("_source")
|
||||||
|
if isinstance(source, dict):
|
||||||
|
results.append(source)
|
||||||
|
|
||||||
|
groups = _extract_group_by_results(data) if group_by else []
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
"count": count,
|
||||||
|
"db_response_time_ms": data.get("took"),
|
||||||
|
"page": page if cursor is None else None,
|
||||||
|
"per_page": per_page,
|
||||||
|
"groups_count": len(groups) if group_by else None,
|
||||||
|
"next_cursor": (data.get("meta") or {}).get("next_cursor"),
|
||||||
|
"cost_usd": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"meta": meta,
|
||||||
|
"results": results,
|
||||||
|
"group_by": groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_group_by_results(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
aggregations = data.get("aggregations") or {}
|
||||||
|
group_by_agg = aggregations.get("group_by") or {}
|
||||||
|
buckets = group_by_agg.get("buckets") or []
|
||||||
|
|
||||||
|
groups: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for bucket in buckets:
|
||||||
|
if not isinstance(bucket, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
key = bucket.get("key")
|
||||||
|
groups.append(
|
||||||
|
{
|
||||||
|
"key": key,
|
||||||
|
"key_display_name": bucket.get("key_as_string") or key,
|
||||||
|
"count": bucket.get("doc_count"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return groups
|
||||||
|
|
||||||
|
|
||||||
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||||
normalized = deepcopy(data)
|
normalized = deepcopy(data)
|
||||||
|
|
||||||
@@ -263,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
|
|||||||
return f"{text}T00:00:00Z"
|
return f"{text}T00:00:00Z"
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
# Configuration for vector search similarity thresholds and boosts
|
# Configuration for vector search similarity thresholds and boosts
|
||||||
SIMILARITY_THRESHOLD = (
|
SIMILARITY_THRESHOLD = (
|
||||||
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
|
||||||
@@ -278,34 +369,16 @@ K = 500
|
|||||||
NUM_CANDIDATES = 500
|
NUM_CANDIDATES = 500
|
||||||
|
|
||||||
|
|
||||||
async def vector_search_topics(
|
def _build_vector_search_body(
|
||||||
*,
|
*,
|
||||||
query: str,
|
query: str,
|
||||||
limit: int = 25,
|
query_vector: list[float],
|
||||||
search_type: str = "hybrid",
|
search_type: str = "hybrid",
|
||||||
) -> TopicsListResponse:
|
limit: int = 25,
|
||||||
|
) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
Perform a semantic similarity search on the topicvectors index.
|
Construct the Elasticsearch request body for topic vector/hybrid search.
|
||||||
"""
|
"""
|
||||||
try:
|
|
||||||
from inse.integrations import elasticsearch
|
|
||||||
from inse.util import get_model
|
|
||||||
|
|
||||||
except Exception as exc:
|
|
||||||
logger.exception("Failed to load elasticsearch integration.")
|
|
||||||
raise ElasticsearchException(
|
|
||||||
f"Failed to load elasticsearch integration: {exc}"
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
# 1. Vectorize query
|
|
||||||
try:
|
|
||||||
model = get_model()
|
|
||||||
query_vector = model.encode(query).tolist()
|
|
||||||
except Exception as exc:
|
|
||||||
logger.exception("Failed to encode query text.")
|
|
||||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
|
||||||
|
|
||||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
|
||||||
should_clauses = []
|
should_clauses = []
|
||||||
|
|
||||||
# Lexical multi_match search (only in hybrid mode)
|
# Lexical multi_match search (only in hybrid mode)
|
||||||
@@ -352,7 +425,7 @@ async def vector_search_topics(
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
body = {
|
return {
|
||||||
"query": {"bool": {"should": should_clauses}},
|
"query": {"bool": {"should": should_clauses}},
|
||||||
"_source": {
|
"_source": {
|
||||||
"excludes": [
|
"excludes": [
|
||||||
@@ -367,9 +440,45 @@ async def vector_search_topics(
|
|||||||
"size": limit,
|
"size": limit,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def vector_search_topics(
|
||||||
|
*,
|
||||||
|
query: str,
|
||||||
|
limit: int = 25,
|
||||||
|
search_type: str = "hybrid",
|
||||||
|
) -> TopicsListResponse:
|
||||||
|
"""
|
||||||
|
Perform a semantic similarity search on the topicvectors index.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.util import get_model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Failed to load elasticsearch integration.")
|
||||||
|
raise ElasticsearchException(
|
||||||
|
f"Failed to load elasticsearch integration: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
# 1. Vectorize query
|
||||||
|
try:
|
||||||
|
model = get_model()
|
||||||
|
query_vector = model.encode(query).tolist()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Failed to encode query text.")
|
||||||
|
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||||
|
|
||||||
|
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||||
|
body = _build_vector_search_body(
|
||||||
|
query=query,
|
||||||
|
query_vector=query_vector,
|
||||||
|
search_type=search_type,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
raw_results = await elasticsearch.search(
|
raw_results = await elasticsearch.search(
|
||||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||||
@@ -393,3 +502,97 @@ async def vector_search_topics(
|
|||||||
raise ElasticsearchException(
|
raise ElasticsearchException(
|
||||||
f"Vector search response could not be parsed: {exc}"
|
f"Vector search response could not be parsed: {exc}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
async def vector_search_topics_batch(
|
||||||
|
*,
|
||||||
|
keywords: list[str],
|
||||||
|
search_type: str = "hybrid",
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Perform concurrent semantic/hybrid search for a list of keywords.
|
||||||
|
"""
|
||||||
|
from inse.topics.model import KeywordsTopicsResponse, KeywordTopicMatch
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
|
if not keywords:
|
||||||
|
return KeywordsTopicsResponse(results=[])
|
||||||
|
|
||||||
|
try:
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.util import get_model
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Failed to load elasticsearch integration.")
|
||||||
|
raise ElasticsearchException(
|
||||||
|
f"Failed to load elasticsearch integration: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
# 1. Vectorize queries on CPU in batch
|
||||||
|
try:
|
||||||
|
model = get_model()
|
||||||
|
vectors = model.encode(keywords)
|
||||||
|
query_vectors = [v.tolist() for v in vectors]
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Failed to encode batch queries.")
|
||||||
|
raise ElasticsearchException(f"Failed to encode batch queries: {exc}") from exc
|
||||||
|
|
||||||
|
# 2. Construct search bodies and query Elasticsearch concurrently
|
||||||
|
tasks = []
|
||||||
|
for kw, qv in zip(keywords, query_vectors):
|
||||||
|
body = _build_vector_search_body(
|
||||||
|
query=kw,
|
||||||
|
query_vector=qv,
|
||||||
|
search_type=search_type,
|
||||||
|
limit=1,
|
||||||
|
)
|
||||||
|
tasks.append(
|
||||||
|
elasticsearch.search(
|
||||||
|
index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_results_list = await asyncio.gather(*tasks)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Batch Elasticsearch vector search failed with unexpected error.")
|
||||||
|
raise ElasticsearchException(
|
||||||
|
f"Unexpected batch vector search failure: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
# 3. Align and map raw results to KeywordTopicMatch objects
|
||||||
|
results_by_index = [None] * len(keywords)
|
||||||
|
keywords_with_topics = []
|
||||||
|
topics_to_normalize = []
|
||||||
|
index_mapping = []
|
||||||
|
|
||||||
|
for i, (keyword, raw_res) in enumerate(zip(keywords, raw_results_list)):
|
||||||
|
hits = raw_res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
topic_dict = hits[0].get("_source", {})
|
||||||
|
keywords_with_topics.append(keyword)
|
||||||
|
topics_to_normalize.append(topic_dict)
|
||||||
|
index_mapping.append(i)
|
||||||
|
else:
|
||||||
|
results_by_index[i] = KeywordTopicMatch(keyword=keyword, topic=None)
|
||||||
|
|
||||||
|
if topics_to_normalize:
|
||||||
|
data = {"results": topics_to_normalize}
|
||||||
|
normalized_data = _normalize_topics_response(data)
|
||||||
|
normalized_topics = normalized_data.get("results", [])
|
||||||
|
|
||||||
|
for keyword, topic_dict, orig_idx in zip(keywords_with_topics, normalized_topics, index_mapping):
|
||||||
|
try:
|
||||||
|
topic = Topic.from_dict(topic_dict)
|
||||||
|
except Exception as e:
|
||||||
|
logger.exception(f"Failed to parse normalized topic dictionary for keyword '{keyword}': {e}")
|
||||||
|
topic = None
|
||||||
|
results_by_index[orig_idx] = KeywordTopicMatch(keyword=keyword, topic=topic)
|
||||||
|
|
||||||
|
# Fallback to fill any unfilled slots
|
||||||
|
for i, res in enumerate(results_by_index):
|
||||||
|
if res is None:
|
||||||
|
results_by_index[i] = KeywordTopicMatch(keyword=keywords[i], topic=None)
|
||||||
|
|
||||||
|
return KeywordsTopicsResponse(results=results_by_index)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
from typing import List, Optional
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
|
# Vector search for Keyword list
|
||||||
|
class KeywordsTopicsRequest(BaseModel):
|
||||||
|
keywords: List[str] = Field(..., description="List of keywords/sentences to query by similarity.")
|
||||||
|
|
||||||
|
|
||||||
|
class KeywordTopicMatch(BaseModel):
|
||||||
|
keyword: str
|
||||||
|
topic: Optional[Topic] = Field(None, description="The top matching topic from OpenAlex, or None if no match is found.")
|
||||||
|
|
||||||
|
|
||||||
|
class KeywordsTopicsResponse(BaseModel):
|
||||||
|
results: List[KeywordTopicMatch] = Field(..., description="Top matching topics for each keyword in the requested list.")
|
||||||
@@ -1,33 +1,200 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
HTTP client for OpenAlex topics.
|
Elasticsearch search client for OpenAlex topics.
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
from inse.model import ESCluster, ESIndex
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
|
from inse.integrations.elasticsearch import search as elasticsearch_search
|
||||||
|
|
||||||
|
|
||||||
class OpenAlexTopicsClient:
|
class TopicsSearchClient:
|
||||||
|
"""
|
||||||
|
Search client for OpenAlex topics backed by Elasticsearch.
|
||||||
|
|
||||||
|
This replaces the old OpenAlex HTTP API client and uses the internal
|
||||||
|
Elasticsearch wrapper instead.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_SEARCH_FIELDS = [
|
||||||
|
"display_name^5",
|
||||||
|
"description^3",
|
||||||
|
"keywords",
|
||||||
|
"domain.display_name^2",
|
||||||
|
"field.display_name^2",
|
||||||
|
"subfield.display_name^2",
|
||||||
|
]
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
base_url: str | None = None,
|
*,
|
||||||
api_key: str | None = None,
|
index: ESIndex | str | None = None,
|
||||||
timeout: float | None = None,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
transport: httpx.AsyncBaseTransport | None = None,
|
|
||||||
):
|
):
|
||||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
self.index = index or self._default_index()
|
||||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
self.cluster = cluster
|
||||||
self.timeout = (
|
|
||||||
timeout
|
|
||||||
if timeout is not None
|
|
||||||
else config.settings.openalex_api_timeout_seconds
|
|
||||||
)
|
|
||||||
self.transport = transport
|
|
||||||
|
|
||||||
def list_topics_params(
|
@staticmethod
|
||||||
|
def _default_index() -> str:
|
||||||
|
"""
|
||||||
|
Resolve the OpenAlex topics index name.
|
||||||
|
|
||||||
|
Prefer a configured value if present, otherwise fall back to a sensible
|
||||||
|
default string index name.
|
||||||
|
"""
|
||||||
|
return (
|
||||||
|
ESIndex.OPENALEX_TOPICS.value
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _split_csv(value: str | None) -> list[str]:
|
||||||
|
if not value:
|
||||||
|
return []
|
||||||
|
return [part.strip() for part in value.split(",") if part.strip()]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _encode_cursor(sort_values: list[Any]) -> str:
|
||||||
|
raw = json.dumps(sort_values).encode("utf-8")
|
||||||
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _decode_cursor(cursor: str | None) -> list[Any] | None:
|
||||||
|
if not cursor or cursor == "*":
|
||||||
|
return None
|
||||||
|
|
||||||
|
padding = "=" * (-len(cursor) % 4)
|
||||||
|
raw = base64.urlsafe_b64decode(cursor + padding)
|
||||||
|
return json.loads(raw.decode("utf-8"))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_select(select: str | None) -> list[str] | None:
|
||||||
|
fields = TopicsSearchClient._split_csv(select)
|
||||||
|
return fields or None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_sort(sort: str | None) -> list[dict[str, Any]] | None:
|
||||||
|
"""
|
||||||
|
Parses OpenAlex-style sort syntax into Elasticsearch sort syntax.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
"works_count:desc"
|
||||||
|
"cited_by_count:desc,display_name:asc"
|
||||||
|
"-works_count"
|
||||||
|
"""
|
||||||
|
parts = TopicsSearchClient._split_csv(sort)
|
||||||
|
if not parts:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parsed: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for part in parts:
|
||||||
|
direction = "asc"
|
||||||
|
field = part
|
||||||
|
|
||||||
|
if part.startswith("-"):
|
||||||
|
direction = "desc"
|
||||||
|
field = part[1:]
|
||||||
|
elif ":" in part:
|
||||||
|
field, direction = part.split(":", 1)
|
||||||
|
field = field.strip()
|
||||||
|
direction = direction.strip().lower()
|
||||||
|
|
||||||
|
if direction not in {"asc", "desc"}:
|
||||||
|
direction = "asc"
|
||||||
|
|
||||||
|
if field in {"score", "_score", "relevance_score"}:
|
||||||
|
parsed.append({"_score": {"order": direction}})
|
||||||
|
else:
|
||||||
|
parsed.append({field: {"order": direction, "missing": "_last"}})
|
||||||
|
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_filter_clause(expression: str) -> tuple[dict[str, Any] | None, bool]:
|
||||||
|
"""
|
||||||
|
Parses a single simple OpenAlex-style filter expression.
|
||||||
|
|
||||||
|
Supported examples:
|
||||||
|
"works_count:>100"
|
||||||
|
"works_count:>=100"
|
||||||
|
"display_name:Physics"
|
||||||
|
"ids.openalex:T123"
|
||||||
|
"field.id:F1|F2"
|
||||||
|
"is_active:true"
|
||||||
|
"is_active:!true"
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[clause, is_negative]
|
||||||
|
"""
|
||||||
|
if ":" not in expression:
|
||||||
|
return None, False
|
||||||
|
|
||||||
|
field, value = expression.split(":", 1)
|
||||||
|
field = field.strip()
|
||||||
|
value = value.strip()
|
||||||
|
|
||||||
|
if not field or not value:
|
||||||
|
return None, False
|
||||||
|
|
||||||
|
is_negative = False
|
||||||
|
if value.startswith("!"):
|
||||||
|
is_negative = True
|
||||||
|
value = value[1:].strip()
|
||||||
|
|
||||||
|
range_ops = {
|
||||||
|
">=": "gte",
|
||||||
|
"<=": "lte",
|
||||||
|
">": "gt",
|
||||||
|
"<": "lt",
|
||||||
|
}
|
||||||
|
|
||||||
|
for prefix, op in range_ops.items():
|
||||||
|
if value.startswith(prefix):
|
||||||
|
range_value = value[len(prefix):].strip()
|
||||||
|
return {"range": {field: {op: range_value}}}, is_negative
|
||||||
|
|
||||||
|
if "|" in value:
|
||||||
|
values = [v.strip() for v in value.split("|") if v.strip()]
|
||||||
|
return {"terms": {field: values}}, is_negative
|
||||||
|
|
||||||
|
lowered = value.lower()
|
||||||
|
if lowered == "true":
|
||||||
|
typed_value: Any = True
|
||||||
|
elif lowered == "false":
|
||||||
|
typed_value = False
|
||||||
|
else:
|
||||||
|
typed_value = value
|
||||||
|
|
||||||
|
return {"term": {field: typed_value}}, is_negative
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _parse_filters(
|
||||||
|
cls,
|
||||||
|
filter: str | None,
|
||||||
|
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||||
|
filter_clauses: list[dict[str, Any]] = []
|
||||||
|
must_not_clauses: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for expression in cls._split_csv(filter):
|
||||||
|
clause, is_negative = cls._parse_filter_clause(expression)
|
||||||
|
if clause is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if is_negative:
|
||||||
|
must_not_clauses.append(clause)
|
||||||
|
else:
|
||||||
|
filter_clauses.append(clause)
|
||||||
|
|
||||||
|
return filter_clauses, must_not_clauses
|
||||||
|
|
||||||
|
def build_search_body(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
search: str | None = None,
|
search: str | None = None,
|
||||||
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
params: dict[str, Any] = {"per_page": per_page}
|
"""
|
||||||
|
Build the Elasticsearch search body from the previous OpenAlex-style API
|
||||||
|
parameters.
|
||||||
|
"""
|
||||||
|
filter_clauses, must_not_clauses = self._parse_filters(filter)
|
||||||
|
|
||||||
|
must_clauses: list[dict[str, Any]] = []
|
||||||
|
|
||||||
if search:
|
if search:
|
||||||
params["search"] = search
|
must_clauses.append(
|
||||||
if filter:
|
{
|
||||||
params["filter"] = filter
|
"multi_match": {
|
||||||
if sort:
|
"query": search,
|
||||||
params["sort"] = sort
|
"fields": self.DEFAULT_SEARCH_FIELDS,
|
||||||
if group_by:
|
"type": "best_fields",
|
||||||
params["group_by"] = group_by
|
"operator": "and",
|
||||||
if cursor:
|
}
|
||||||
params["cursor"] = cursor
|
}
|
||||||
elif page is not None:
|
)
|
||||||
params["page"] = page
|
|
||||||
if sample is not None:
|
|
||||||
params["sample"] = sample
|
|
||||||
if select:
|
|
||||||
params["select"] = select
|
|
||||||
if self.api_key:
|
|
||||||
params["api_key"] = self.api_key
|
|
||||||
|
|
||||||
return params
|
if must_clauses or filter_clauses or must_not_clauses:
|
||||||
|
query: dict[str, Any] = {
|
||||||
|
"bool": {
|
||||||
|
"must": must_clauses or [{"match_all": {}}],
|
||||||
|
"filter": filter_clauses,
|
||||||
|
"must_not": must_not_clauses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
query = {"match_all": {}}
|
||||||
|
|
||||||
|
if sample is not None:
|
||||||
|
query = {
|
||||||
|
"function_score": {
|
||||||
|
"query": query,
|
||||||
|
"random_score": {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size = sample if sample is not None else per_page
|
||||||
|
|
||||||
|
body: dict[str, Any] = {
|
||||||
|
"query": query,
|
||||||
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
source = self._parse_select(select)
|
||||||
|
if source is not None:
|
||||||
|
body["_source"] = source
|
||||||
|
|
||||||
|
sort_clause = self._parse_sort(sort)
|
||||||
|
if sort_clause is not None:
|
||||||
|
body["sort"] = sort_clause
|
||||||
|
|
||||||
|
search_after = self._decode_cursor(cursor)
|
||||||
|
if search_after is not None:
|
||||||
|
body["search_after"] = search_after
|
||||||
|
elif cursor is None and page is not None:
|
||||||
|
body["from"] = max(page - 1, 0) * per_page
|
||||||
|
|
||||||
|
if group_by:
|
||||||
|
body["size"] = 0
|
||||||
|
body["aggs"] = {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {
|
||||||
|
"field": group_by,
|
||||||
|
"size": per_page,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return body
|
||||||
|
|
||||||
|
async def search_topics(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
search: str | None = None,
|
||||||
|
filter: str | None = None,
|
||||||
|
sort: str | None = None,
|
||||||
|
group_by: str | None = None,
|
||||||
|
per_page: int = 25,
|
||||||
|
page: int | None = 1,
|
||||||
|
cursor: str | None = None,
|
||||||
|
sample: int | None = None,
|
||||||
|
select: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
body = self.build_search_body(
|
||||||
|
search=search,
|
||||||
|
filter=filter,
|
||||||
|
sort=sort,
|
||||||
|
group_by=group_by,
|
||||||
|
per_page=per_page,
|
||||||
|
page=page,
|
||||||
|
cursor=cursor,
|
||||||
|
sample=sample,
|
||||||
|
select=select,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await elasticsearch_search(
|
||||||
|
index=self.index,
|
||||||
|
body=body,
|
||||||
|
cluster=self.cluster,
|
||||||
|
)
|
||||||
|
|
||||||
|
hits = result.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
last_sort = hits[-1].get("sort")
|
||||||
|
if last_sort is not None:
|
||||||
|
result.setdefault("meta", {})["next_cursor"] = self._encode_cursor(last_sort)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
async def list_topics(
|
async def list_topics(
|
||||||
self,
|
self,
|
||||||
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
|
|||||||
sample: int | None = None,
|
sample: int | None = None,
|
||||||
select: str | None = None,
|
select: str | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
async with httpx.AsyncClient(
|
"""
|
||||||
base_url=self.base_url,
|
Backwards-compatible alias for the old OpenAlex client method name.
|
||||||
timeout=self.timeout,
|
"""
|
||||||
transport=self.transport,
|
return await self.search_topics(
|
||||||
) as client:
|
search=search,
|
||||||
response = await client.get(
|
filter=filter,
|
||||||
"/topics",
|
sort=sort,
|
||||||
params=self.list_topics_params(
|
group_by=group_by,
|
||||||
search=search,
|
per_page=per_page,
|
||||||
filter=filter,
|
page=page,
|
||||||
sort=sort,
|
cursor=cursor,
|
||||||
group_by=group_by,
|
sample=sample,
|
||||||
per_page=per_page,
|
select=select,
|
||||||
page=page,
|
)
|
||||||
cursor=cursor,
|
|
||||||
sample=sample,
|
|
||||||
select=select,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
@@ -12,6 +12,7 @@ from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
|||||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
from . import logic
|
from . import logic
|
||||||
|
from .model import KeywordsTopicsRequest, KeywordsTopicsResponse
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
|
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
|
||||||
@@ -140,3 +141,22 @@ async def vector_search_topics(
|
|||||||
search_type=search_type,
|
search_type=search_type,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/vector-search/batch",
|
||||||
|
operation_id="vectorSearchTopicsBatch",
|
||||||
|
response_model=KeywordsTopicsResponse,
|
||||||
|
response_model_exclude_none=True,
|
||||||
|
summary="Batch semantic / vector search for multiple keywords.",
|
||||||
|
)
|
||||||
|
async def vector_search_topics_batch(
|
||||||
|
request_body: KeywordsTopicsRequest,
|
||||||
|
search_type: Annotated[
|
||||||
|
str,
|
||||||
|
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
|
||||||
|
] = "hybrid",
|
||||||
|
):
|
||||||
|
return await logic.vector_search_topics_batch(
|
||||||
|
keywords=request_body.keywords,
|
||||||
|
search_type=search_type,
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
from inse.exceptions import BadRequestException
|
|
||||||
|
|
||||||
|
from inse.exceptions import BadRequestException
|
||||||
from inse.topics import logic
|
from inse.topics import logic
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -11,108 +9,144 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeTopicsSearchClient:
|
||||||
|
def __init__(self, response: dict):
|
||||||
|
self.response = response
|
||||||
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
|
async def list_topics(self, **kwargs):
|
||||||
|
self.calls.append(kwargs)
|
||||||
|
return self.response
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_maps_openalex_response_to_model():
|
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
return httpx.Response(
|
{
|
||||||
200,
|
"took": 12,
|
||||||
json={
|
"hits": {
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
"total": {"value": 1, "relation": "eq"},
|
||||||
"results": [
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
"description": "Methods that learn from data.",
|
"id": "https://openalex.org/T12419",
|
||||||
"keywords": ["machine learning", "classification"],
|
"display_name": "Machine learning",
|
||||||
"subfield": {
|
"description": "Methods that learn from data.",
|
||||||
"id": "https://openalex.org/subfields/1702",
|
"keywords": ["machine learning", "classification"],
|
||||||
"display_name": "Artificial Intelligence",
|
"subfield": {
|
||||||
|
"id": "https://openalex.org/subfields/1702",
|
||||||
|
"display_name": "Artificial Intelligence",
|
||||||
|
},
|
||||||
|
"field": {
|
||||||
|
"id": "https://openalex.org/fields/17",
|
||||||
|
"display_name": "Computer Science",
|
||||||
|
},
|
||||||
|
"domain": {
|
||||||
|
"id": "https://openalex.org/domains/4",
|
||||||
|
"display_name": "Physical Sciences",
|
||||||
|
},
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"ids": {
|
||||||
|
"openalex": "https://openalex.org/T12419",
|
||||||
|
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||||
|
},
|
||||||
|
"works_api_url": (
|
||||||
|
"https://api.openalex.org/works?"
|
||||||
|
"filter=topics.id:T12419"
|
||||||
|
),
|
||||||
|
"created_date": "2023-12-25",
|
||||||
|
"updated_date": "2023-11-07T05:31:56Z",
|
||||||
},
|
},
|
||||||
"field": {
|
|
||||||
"id": "https://openalex.org/fields/17",
|
|
||||||
"display_name": "Computer Science",
|
|
||||||
},
|
|
||||||
"domain": {
|
|
||||||
"id": "https://openalex.org/domains/4",
|
|
||||||
"display_name": "Physical Sciences",
|
|
||||||
},
|
|
||||||
"works_count": 123,
|
|
||||||
"cited_by_count": 456,
|
|
||||||
"ids": {
|
|
||||||
"openalex": "https://openalex.org/T12419",
|
|
||||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
|
||||||
},
|
|
||||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
|
||||||
"created_date": "2023-12-25",
|
|
||||||
"updated_date": "2023-11-07T05:31:56Z",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"group_by": [
|
|
||||||
{
|
|
||||||
"key": "https://openalex.org/domains/4",
|
|
||||||
"key_display_name": "Physical Sciences",
|
|
||||||
"count": 1,
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
"aggregations": {
|
||||||
|
"group_by": {
|
||||||
client = OpenAlexTopicsClient(
|
"buckets": [
|
||||||
api_key="test-key",
|
{
|
||||||
transport=httpx.MockTransport(handler),
|
"key": "https://openalex.org/domains/4",
|
||||||
|
"key_as_string": "Physical Sciences",
|
||||||
|
"doc_count": 1,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_topics(search="machine learning", client=client)
|
result = await logic.list_topics(
|
||||||
|
search="machine learning",
|
||||||
|
group_by="domain.id",
|
||||||
|
client=client,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.calls[0]["search"] == "machine learning"
|
||||||
|
assert client.calls[0]["group_by"] == "domain.id"
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
|
assert result.meta.db_response_time_ms == 12
|
||||||
|
|
||||||
topic = result.results[0]
|
topic = result.results[0]
|
||||||
assert topic.display_name == "Machine learning"
|
assert topic.display_name == "Machine learning"
|
||||||
assert topic.var_field.display_name == "Computer Science"
|
assert topic.var_field.display_name == "Computer Science"
|
||||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||||
assert topic.domain.display_name == "Physical Sciences"
|
assert topic.domain.display_name == "Physical Sciences"
|
||||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||||
|
|
||||||
|
assert result.group_by[0].key == "https://openalex.org/domains/4"
|
||||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||||
|
assert result.group_by[0].count == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_rejects_sample_with_sort():
|
async def test_list_topics_rejects_sample_with_sort():
|
||||||
with pytest.raises(BadRequestException) as exc_info:
|
with pytest.raises(BadRequestException):
|
||||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||||
def handler(_: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
return httpx.Response(
|
{
|
||||||
200,
|
"took": "10",
|
||||||
json={
|
"hits": {
|
||||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
"total": {"value": "1", "relation": "eq"},
|
||||||
"results": [
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": 123,
|
"_id": "123",
|
||||||
"display_name": 456,
|
"_source": {
|
||||||
"description": True,
|
"id": 123,
|
||||||
"keywords": ["topic", 123],
|
"display_name": 456,
|
||||||
"subfield": {"id": 1, "display_name": 2},
|
"description": True,
|
||||||
"field": {"id": 3, "display_name": 4},
|
"keywords": ["topic", 123],
|
||||||
"domain": {"id": 5, "display_name": 6},
|
"subfield": {"id": 1, "display_name": 2},
|
||||||
"works_count": "12.0",
|
"field": {"id": 3, "display_name": 4},
|
||||||
"cited_by_count": False,
|
"domain": {"id": 5, "display_name": 6},
|
||||||
"ids": {"openalex": 123, "wikipedia": 456},
|
"works_count": "12.0",
|
||||||
"created_date": "2023-12-25T10:11:12Z",
|
"cited_by_count": False,
|
||||||
"updated_date": "2023-12-25",
|
"ids": {"openalex": 123, "wikipedia": 456},
|
||||||
|
"created_date": "2023-12-25T10:11:12Z",
|
||||||
|
"updated_date": "2023-12-25",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"group_by": [{"key": True, "count": "1"}],
|
|
||||||
},
|
},
|
||||||
)
|
"aggregations": {
|
||||||
|
"group_by": {
|
||||||
client = OpenAlexTopicsClient(
|
"buckets": [
|
||||||
api_key="test-key",
|
{
|
||||||
transport=httpx.MockTransport(handler),
|
"key": True,
|
||||||
|
"doc_count": "1",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.list_topics(client=client)
|
result = await logic.list_topics(group_by="domain.id", client=client)
|
||||||
|
|
||||||
topic = result.results[0]
|
topic = result.results[0]
|
||||||
assert topic.id == "123"
|
assert topic.id == "123"
|
||||||
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_autocomplete_topics_returns_frontend_options():
|
async def test_autocomplete_topics_returns_frontend_options():
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
client = FakeTopicsSearchClient(
|
||||||
assert request.url.params["search"] == "machine learning"
|
{
|
||||||
assert request.url.params["filter"] == (
|
"took": 12,
|
||||||
"domain.id:https://openalex.org/domains/4,"
|
"hits": {
|
||||||
"field.id:https://openalex.org/fields/17,"
|
"total": {"value": 1, "relation": "eq"},
|
||||||
"subfield.id:https://openalex.org/subfields/1702"
|
"hits": [
|
||||||
)
|
|
||||||
assert request.url.params["sort"] == "works_count:desc"
|
|
||||||
assert request.url.params["per_page"] == "5"
|
|
||||||
assert request.url.params["select"] == (
|
|
||||||
"id,display_name,description,keywords,subfield,field,domain,"
|
|
||||||
"works_count,cited_by_count,ids"
|
|
||||||
)
|
|
||||||
return httpx.Response(
|
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
|
||||||
"results": [
|
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
"description": "Methods that learn from data.",
|
"id": "https://openalex.org/T12419",
|
||||||
"field": {"display_name": "Computer Science"},
|
"display_name": "Machine learning",
|
||||||
"subfield": {"display_name": "Artificial Intelligence"},
|
"description": "Methods that learn from data.",
|
||||||
"domain": {"display_name": "Physical Sciences"},
|
"field": {"display_name": "Computer Science"},
|
||||||
"works_count": 123,
|
"subfield": {
|
||||||
"cited_by_count": 456,
|
"display_name": "Artificial Intelligence",
|
||||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
},
|
||||||
|
"domain": {"display_name": "Physical Sciences"},
|
||||||
|
"works_count": 123,
|
||||||
|
"cited_by_count": 456,
|
||||||
|
"ids": {
|
||||||
|
"openalex": "https://openalex.org/T12419",
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
}
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
|
||||||
api_key="test-key",
|
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
result = await logic.autocomplete_topics(
|
result = await logic.autocomplete_topics(
|
||||||
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
|
|||||||
client=client,
|
client=client,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
assert client.calls[0]["search"] == "machine learning"
|
||||||
|
assert client.calls[0]["filter"] == (
|
||||||
|
"domain.id:https://openalex.org/domains/4,"
|
||||||
|
"field.id:https://openalex.org/fields/17,"
|
||||||
|
"subfield.id:https://openalex.org/subfields/1702"
|
||||||
|
)
|
||||||
|
assert client.calls[0]["sort"] == "works_count:desc"
|
||||||
|
assert client.calls[0]["per_page"] == 5
|
||||||
|
assert client.calls[0]["page"] == 1
|
||||||
|
assert client.calls[0]["select"] == (
|
||||||
|
"id,display_name,description,keywords,subfield,field,domain,"
|
||||||
|
"works_count,cited_by_count,ids"
|
||||||
|
)
|
||||||
|
|
||||||
assert result.meta.count == 1
|
assert result.meta.count == 1
|
||||||
assert result.meta.db_response_time_ms == 12
|
assert result.meta.db_response_time_ms == 12
|
||||||
assert len(result.results) == 1
|
assert len(result.results) == 1
|
||||||
|
|
||||||
option = result.results[0]
|
option = result.results[0]
|
||||||
assert option.id == "https://openalex.org/T12419"
|
assert option.id == "https://openalex.org/T12419"
|
||||||
assert option.display_name == "Machine learning"
|
assert option.display_name == "Machine learning"
|
||||||
@@ -190,4 +230,4 @@ async def test_autocomplete_topics_returns_frontend_options():
|
|||||||
assert option.works_count == 123
|
assert option.works_count == 123
|
||||||
assert option.cited_by_count == 456
|
assert option.cited_by_count == 456
|
||||||
assert option.entity_type == "topic"
|
assert option.entity_type == "topic"
|
||||||
assert option.external_id == "https://openalex.org/T12419"
|
assert option.external_id == "https://openalex.org/T12419"
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import httpx
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from inse.topics.search_client import OpenAlexTopicsClient
|
from inse.model import ESCluster, ESIndex
|
||||||
|
from inse.topics.search_client import TopicsSearchClient
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -9,10 +9,10 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_include_openalex_query_parameters():
|
def test_build_search_body_includes_openalex_query_parameters():
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
params = client.list_topics_params(
|
body = client.build_search_body(
|
||||||
search="machine learning",
|
search="machine learning",
|
||||||
filter="domain.id:4,works_count:>1000",
|
filter="domain.id:4,works_count:>1000",
|
||||||
sort="works_count:desc",
|
sort="works_count:desc",
|
||||||
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
|
|||||||
select="id,display_name",
|
select="id,display_name",
|
||||||
)
|
)
|
||||||
|
|
||||||
assert params == {
|
assert body["query"] == {
|
||||||
"search": "machine learning",
|
"bool": {
|
||||||
"filter": "domain.id:4,works_count:>1000",
|
"must": [
|
||||||
"sort": "works_count:desc",
|
{
|
||||||
"group_by": "domain.id",
|
"multi_match": {
|
||||||
"per_page": 10,
|
"query": "machine learning",
|
||||||
"page": 2,
|
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||||
"select": "id,display_name",
|
"type": "best_fields",
|
||||||
"api_key": "test-key",
|
"operator": "and",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"filter": [
|
||||||
|
{"term": {"domain.id": "4"}},
|
||||||
|
{"range": {"works_count": {"gt": "1000"}}},
|
||||||
|
],
|
||||||
|
"must_not": [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert body["_source"] == ["id", "display_name"]
|
||||||
|
assert body["sort"] == [
|
||||||
|
{"works_count": {"order": "desc", "missing": "_last"}}
|
||||||
|
]
|
||||||
|
|
||||||
|
# group_by queries use aggregations and no regular hits
|
||||||
|
assert body["size"] == 0
|
||||||
|
assert body["from"] == 10
|
||||||
|
assert body["track_total_hits"] is True
|
||||||
|
assert body["aggs"] == {
|
||||||
|
"group_by": {
|
||||||
|
"terms": {
|
||||||
|
"field": "domain.id",
|
||||||
|
"size": 10,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def test_list_topics_params_prefers_cursor_over_page():
|
def test_build_search_body_prefers_cursor_over_page():
|
||||||
client = OpenAlexTopicsClient(api_key="test-key")
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
params = client.list_topics_params(cursor="*", page=3)
|
cursor = client._encode_cursor(["Machine learning", "https://openalex.org/T12419"])
|
||||||
|
|
||||||
assert params["cursor"] == "*"
|
body = client.build_search_body(
|
||||||
assert "page" not in params
|
cursor=cursor,
|
||||||
|
page=3,
|
||||||
|
per_page=25,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert body["search_after"] == [
|
||||||
|
"Machine learning",
|
||||||
|
"https://openalex.org/T12419",
|
||||||
|
]
|
||||||
|
assert "from" not in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_search_body_with_plain_cursor_star_does_not_use_page_offset():
|
||||||
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
|
body = client.build_search_body(
|
||||||
|
cursor="*",
|
||||||
|
page=3,
|
||||||
|
per_page=25,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "search_after" not in body
|
||||||
|
assert "from" not in body
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
|
||||||
def handler(request: httpx.Request) -> httpx.Response:
|
captured = {}
|
||||||
assert request.method == "GET"
|
|
||||||
assert request.url.path == "/topics"
|
async def fake_elasticsearch_search(*, index, body, cluster):
|
||||||
assert request.url.params["search"] == "machine learning"
|
captured["index"] = index
|
||||||
assert request.url.params["api_key"] == "test-key"
|
captured["body"] = body
|
||||||
return httpx.Response(
|
captured["cluster"] = cluster
|
||||||
200,
|
|
||||||
json={
|
return {
|
||||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
"took": 3,
|
||||||
"results": [
|
"hits": {
|
||||||
|
"total": {"value": 1, "relation": "eq"},
|
||||||
|
"hits": [
|
||||||
{
|
{
|
||||||
"id": "https://openalex.org/T12419",
|
"_id": "https://openalex.org/T12419",
|
||||||
"display_name": "Machine learning",
|
"_source": {
|
||||||
|
"id": "https://openalex.org/T12419",
|
||||||
|
"display_name": "Machine learning",
|
||||||
|
},
|
||||||
|
"sort": [1000, "https://openalex.org/T12419"],
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
)
|
}
|
||||||
|
|
||||||
client = OpenAlexTopicsClient(
|
monkeypatch.setattr(
|
||||||
base_url="https://api.openalex.org",
|
"inse.topics.search_client.elasticsearch_search",
|
||||||
api_key="test-key",
|
fake_elasticsearch_search,
|
||||||
transport=httpx.MockTransport(handler),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
|
||||||
|
|
||||||
result = await client.list_topics(search="machine learning")
|
result = await client.list_topics(search="machine learning")
|
||||||
|
|
||||||
assert result["meta"]["count"] == 1
|
assert captured["index"] == ESIndex.OPENALEX_TOPICS
|
||||||
assert result["results"][0]["display_name"] == "Machine learning"
|
assert captured["cluster"] == ESCluster.NES
|
||||||
|
|
||||||
|
assert captured["body"]["query"]["bool"]["must"] == [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": "machine learning",
|
||||||
|
"fields": client.DEFAULT_SEARCH_FIELDS,
|
||||||
|
"type": "best_fields",
|
||||||
|
"operator": "and",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
assert captured["body"]["size"] == 25
|
||||||
|
assert captured["body"]["from"] == 0
|
||||||
|
assert captured["body"]["track_total_hits"] is True
|
||||||
|
|
||||||
|
assert result["hits"]["total"]["value"] == 1
|
||||||
|
assert result["hits"]["hits"][0]["_source"]["display_name"] == "Machine learning"
|
||||||
|
assert result["meta"]["next_cursor"] is not None
|
||||||
@@ -1,65 +1,228 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import datetime
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse
|
from .model import UniversityTopicData, YearlyData, UniversityRanking, DashboardMetric, RankingResponse
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
START_YEAR = 2015
|
START_YEAR = 2000
|
||||||
END_YEAR = 2026
|
END_YEAR = datetime.datetime.now().year - 1
|
||||||
|
|
||||||
async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
async def resolve_topic(topic_query: str) -> Topic:
|
||||||
|
"""Resolves a topic display name or ID using Elasticsearch with source whitelisting."""
|
||||||
|
if topic_query.startswith("https://openalex.org/"):
|
||||||
|
query = {"term": {"id": topic_query}}
|
||||||
|
else:
|
||||||
|
query = {"match_phrase": {"display_name": topic_query}}
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query=query,
|
||||||
|
size=1,
|
||||||
|
source=["id", "display_name", "description", "works_count", "cited_by_count"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
return Topic.from_dict(hits[0]["_source"])
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic in ES: %s", e)
|
||||||
|
|
||||||
|
return Topic(display_name=topic_query)
|
||||||
|
|
||||||
|
async def get_ranking_data(topic_query: str, metric: DashboardMetric) -> RankingResponse:
|
||||||
"""
|
"""
|
||||||
Fetches real data from Elasticsearch and computes metrics for the dashboard.
|
Fetches real data from Elasticsearch and computes metrics for the dashboard.
|
||||||
"""
|
"""
|
||||||
|
topic_obj = await resolve_topic(topic_query)
|
||||||
|
topic_name = topic_obj.display_name or topic_query
|
||||||
|
|
||||||
|
if topic_obj.id:
|
||||||
|
topic_filter = {"term": {"topics.id.keyword": topic_obj.id}}
|
||||||
|
else:
|
||||||
|
topic_filter = {"match_phrase": {"topics.display_name": topic_name}}
|
||||||
|
|
||||||
query = {
|
query = {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": [
|
"filter": [
|
||||||
{
|
{"term": {"type": "education"}},
|
||||||
"match_phrase": {
|
{"term": {"geo.country_code": "DE"}},
|
||||||
"topics.display_name": topic
|
topic_filter
|
||||||
}
|
]
|
||||||
},
|
|
||||||
{
|
|
||||||
"term": {
|
|
||||||
"geo.country_code": "DE"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# Fetch top institutions for the topic by works_count
|
|
||||||
res = await elasticsearch.search(
|
res = await elasticsearch.search(
|
||||||
index="openalex-institutions",
|
index="openalex-institutions",
|
||||||
query=query,
|
query=query,
|
||||||
size=10,
|
size=50,
|
||||||
sort=[{"works_count": "desc"}],
|
source=["id", "display_name", "topics"],
|
||||||
cluster="nes"
|
cluster="nes"
|
||||||
)
|
)
|
||||||
|
|
||||||
hits = res.get("hits", {}).get("hits", [])
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
timeseries: List[UniversityTopicData] = []
|
candidates = []
|
||||||
|
|
||||||
for hit in hits:
|
for hit in hits:
|
||||||
source = hit["_source"]
|
source = hit["_source"]
|
||||||
# Map the counts_by_year from ES to our model
|
inst_id = source.get("id")
|
||||||
# We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
|
display_name = source.get("display_name", "Unknown")
|
||||||
es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
|
|
||||||
|
|
||||||
|
# Extract topic-specific works count
|
||||||
|
exact_topic_count = 0
|
||||||
|
for t in source.get("topics", []):
|
||||||
|
if t.get("display_name", "").lower() == topic_name.lower():
|
||||||
|
exact_topic_count = t.get("count", 0)
|
||||||
|
break
|
||||||
|
|
||||||
|
candidates.append({
|
||||||
|
"id": inst_id,
|
||||||
|
"display_name": display_name,
|
||||||
|
"exact_topic_count": exact_topic_count
|
||||||
|
})
|
||||||
|
|
||||||
|
# Sort in Python by exact topic count descending and take the top 10
|
||||||
|
candidates.sort(key=lambda x: x["exact_topic_count"], reverse=True)
|
||||||
|
top_10 = candidates[:10]
|
||||||
|
|
||||||
|
# Initialize timeseries map: inst_id -> year -> (publications, citations)
|
||||||
|
years_range = list(range(START_YEAR, END_YEAR + 1))
|
||||||
|
accumulated_data = {
|
||||||
|
inst["id"]: {yr: (0, 0) for yr in years_range}
|
||||||
|
for inst in top_10
|
||||||
|
}
|
||||||
|
|
||||||
|
if top_10:
|
||||||
|
# Build filter map for the single-pass aggregation query
|
||||||
|
filters_map = {}
|
||||||
|
for inst in top_10:
|
||||||
|
inst_id = inst["id"]
|
||||||
|
filters_map[inst_id] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.id": inst_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Topic filter clause (using topic ID if resolved, otherwise matching display name keyword)
|
||||||
|
topic_id = topic_obj.id
|
||||||
|
if topic_id:
|
||||||
|
topic_clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"term": {"topics.id": topic_id}}}},
|
||||||
|
{"term": {"primary_topic.id": topic_id}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
topic_clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": topic_name}}}},
|
||||||
|
{"match_phrase": {"primary_topic.display_name": topic_name}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Construct single-pass ES query on openalex-works in Filter Context
|
||||||
|
works_query = {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"publication_year": {
|
||||||
|
"gte": START_YEAR,
|
||||||
|
"lte": END_YEAR
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
topic_clause,
|
||||||
|
{
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.id": [inst["id"] for inst in top_10]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
aggregations = {
|
||||||
|
"institutions_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": filters_map
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"terms": {
|
||||||
|
"field": "publication_year",
|
||||||
|
"size": len(years_range) * 2
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"citations_sum": {
|
||||||
|
"sum": {
|
||||||
|
"field": "cited_by_count"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
works_res = await elasticsearch.search(
|
||||||
|
index="openalex-works*",
|
||||||
|
query=works_query,
|
||||||
|
body={"aggs": aggregations},
|
||||||
|
size=0,
|
||||||
|
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
inst_buckets = works_res.get("aggregations", {}).get("institutions_agg", {}).get("buckets", {})
|
||||||
|
for inst_id, inst_bucket in inst_buckets.items():
|
||||||
|
year_buckets = inst_bucket.get("by_year", {}).get("buckets", [])
|
||||||
|
for yr_bucket in year_buckets:
|
||||||
|
yr = int(yr_bucket.get("key"))
|
||||||
|
pubs = int(yr_bucket.get("doc_count", 0))
|
||||||
|
cits = int(yr_bucket.get("citations_sum", {}).get("value", 0))
|
||||||
|
if yr in years_range:
|
||||||
|
accumulated_data[inst_id][yr] = (pubs, cits)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error executing ranking aggregations on openalex-works: %s", e)
|
||||||
|
|
||||||
|
# Map the accumulated results back into the timeseries response model
|
||||||
|
timeseries: List[UniversityTopicData] = []
|
||||||
|
inst_name_map = {inst["id"]: inst["display_name"] for inst in top_10}
|
||||||
|
|
||||||
|
for inst_id, year_dict in accumulated_data.items():
|
||||||
yearly_data = []
|
yearly_data = []
|
||||||
for year in range(START_YEAR, END_YEAR + 1):
|
for yr in years_range:
|
||||||
count_item = es_counts.get(year, {})
|
pubs, cits = year_dict[yr]
|
||||||
yearly_data.append(YearlyData(
|
yearly_data.append(YearlyData(
|
||||||
year=year,
|
year=yr,
|
||||||
publications=count_item.get("works_count", 0),
|
publications=pubs,
|
||||||
citations=count_item.get("cited_by_count", 0)
|
citations=cits
|
||||||
))
|
))
|
||||||
|
|
||||||
timeseries.append(UniversityTopicData(
|
timeseries.append(UniversityTopicData(
|
||||||
university=source.get("display_name", "Unknown"),
|
university=inst_name_map[inst_id],
|
||||||
topic=topic,
|
topic=topic_obj,
|
||||||
yearly_data=yearly_data
|
yearly_data=yearly_data
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import List, Literal
|
from typing import List, Literal, Dict, Optional
|
||||||
|
from inse.models.openalex.topic import Topic
|
||||||
|
|
||||||
ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology']
|
|
||||||
DashboardMetric = Literal['publications', 'citations']
|
DashboardMetric = Literal['publications', 'citations']
|
||||||
|
|
||||||
class YearlyData(BaseModel):
|
class YearlyData(BaseModel):
|
||||||
@@ -11,7 +11,7 @@ class YearlyData(BaseModel):
|
|||||||
|
|
||||||
class UniversityTopicData(BaseModel):
|
class UniversityTopicData(BaseModel):
|
||||||
university: str
|
university: str
|
||||||
topic: ResearchTopic
|
topic: Topic
|
||||||
yearly_data: List[YearlyData]
|
yearly_data: List[YearlyData]
|
||||||
|
|
||||||
class UniversityRanking(BaseModel):
|
class UniversityRanking(BaseModel):
|
||||||
@@ -27,4 +27,37 @@ class RankingResponse(BaseModel):
|
|||||||
# Raw timeseries data for the ECharts line race
|
# Raw timeseries data for the ECharts line race
|
||||||
timeseries: List[UniversityTopicData]
|
timeseries: List[UniversityTopicData]
|
||||||
# Computed metrics for the ranking table
|
# Computed metrics for the ranking table
|
||||||
rankings: List[UniversityRanking]
|
rankings: List[UniversityRanking]
|
||||||
|
|
||||||
|
# Trend Analysis Models
|
||||||
|
class TopicYearlyData(BaseModel):
|
||||||
|
year: int
|
||||||
|
raw: int
|
||||||
|
normalized: float
|
||||||
|
cumulative: float
|
||||||
|
institutions_count: int
|
||||||
|
|
||||||
|
class TrendSeries(BaseModel):
|
||||||
|
entity_id: str
|
||||||
|
entity_name: str
|
||||||
|
entity_type: Literal['institution', 'country', 'region']
|
||||||
|
country_code: Optional[str] = None
|
||||||
|
# Map topic display name to its yearly data
|
||||||
|
topic_data: Dict[str, List[TopicYearlyData]]
|
||||||
|
|
||||||
|
class TrendResponse(BaseModel):
|
||||||
|
series: List[TrendSeries]
|
||||||
|
years: List[int]
|
||||||
|
location_mappings: Optional[Dict[str, List[str]]] = None
|
||||||
|
|
||||||
|
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||||
|
|
||||||
|
class TopInstitutionItem(DehydratedInstitution):
|
||||||
|
works_count: Optional[int] = None
|
||||||
|
exact_topic_count: Optional[int] = None
|
||||||
|
|
||||||
|
class AutocompleteLocationItem(BaseModel):
|
||||||
|
id: str
|
||||||
|
display_name: str
|
||||||
|
code: str
|
||||||
|
type: Literal['country', 'continent']
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
from fastapi import APIRouter, Query
|
|
||||||
from . import service
|
|
||||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
|
||||||
from inse.tags import Tags
|
|
||||||
|
|
||||||
router = APIRouter(
|
|
||||||
prefix="/api/inse-service/university-rankings",
|
|
||||||
tags=[Tags.INSTITUTIONS]
|
|
||||||
)
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"",
|
|
||||||
response_model=RankingResponse,
|
|
||||||
summary="Returns data for the University Ranking Dashboard."
|
|
||||||
)
|
|
||||||
async def get_rankings(
|
|
||||||
topic: ResearchTopic = Query(
|
|
||||||
...,
|
|
||||||
description="Research topic (e.g., 'Artificial Intelligence')"
|
|
||||||
),
|
|
||||||
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
|
||||||
):
|
|
||||||
return await service.get_university_dashboard_data(topic, metric)
|
|
||||||
@@ -1,6 +1,80 @@
|
|||||||
from . import logic
|
import logging
|
||||||
from .model import RankingResponse, ResearchTopic, DashboardMetric
|
from typing import List, Optional
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
|
from inse.tags import Tags
|
||||||
"""Orchestrates data retrieval and computation for the dashboard."""
|
from . import logic, trend_logic
|
||||||
return await logic.get_ranking_data(topic, metric)
|
from .model import (
|
||||||
|
RankingResponse,
|
||||||
|
DashboardMetric,
|
||||||
|
TrendResponse,
|
||||||
|
TopInstitutionItem,
|
||||||
|
AutocompleteLocationItem
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
prefix="/api/inse-service/university-rankings",
|
||||||
|
tags=[Tags.UNIVERSITY_RANKINGS]
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"",
|
||||||
|
response_model=RankingResponse,
|
||||||
|
summary="Returns data for the University Ranking Dashboard."
|
||||||
|
)
|
||||||
|
async def get_rankings(
|
||||||
|
topic: str = Query(
|
||||||
|
...,
|
||||||
|
description="Research topic display name or OpenAlex ID (e.g., 'Artificial Intelligence')"
|
||||||
|
),
|
||||||
|
metric: DashboardMetric = Query("publications", description="Metric to rank by")
|
||||||
|
):
|
||||||
|
return await logic.get_ranking_data(topic, metric)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/trend",
|
||||||
|
response_model=TrendResponse,
|
||||||
|
summary="Returns timeseries publication data for compared institutions, countries and regions."
|
||||||
|
)
|
||||||
|
async def get_trend(
|
||||||
|
topics: List[str] = Query(..., description="List of topics to analyze"),
|
||||||
|
institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"),
|
||||||
|
countries: Optional[List[str]] = Query(None, description="List of country codes"),
|
||||||
|
regions: Optional[List[str]] = Query(None, description="List of region identifiers")
|
||||||
|
):
|
||||||
|
return await trend_logic.get_trend_data(
|
||||||
|
topics=topics,
|
||||||
|
institutions=institutions,
|
||||||
|
countries=countries,
|
||||||
|
regions=regions
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/top-institutions",
|
||||||
|
response_model=List[TopInstitutionItem],
|
||||||
|
summary="Returns top institutions filtered by country/region and sorted by topic-level publications count."
|
||||||
|
)
|
||||||
|
async def get_top_institutions(
|
||||||
|
topic: str = Query(..., description="Research topic"),
|
||||||
|
region: Optional[str] = Query(None, description="Region identifier (e.g. EU)"),
|
||||||
|
country: Optional[str] = Query(None, description="Country code (e.g. DE)"),
|
||||||
|
limit: int = Query(10, description="Max suggestions to return")
|
||||||
|
):
|
||||||
|
return await trend_logic.get_top_institutions_by_region(
|
||||||
|
topic=topic,
|
||||||
|
region=region,
|
||||||
|
country=country,
|
||||||
|
limit=limit
|
||||||
|
)
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/autocomplete-locations",
|
||||||
|
response_model=List[AutocompleteLocationItem],
|
||||||
|
summary="Returns country and continent options for autocomplete inputs."
|
||||||
|
)
|
||||||
|
async def get_autocomplete_locations(
|
||||||
|
query: str = Query(..., description="Query text to search for countries/continents")
|
||||||
|
):
|
||||||
|
return await trend_logic.autocomplete_locations(query)
|
||||||
@@ -0,0 +1,656 @@
|
|||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
import datetime
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.preprocessing import MinMaxScaler
|
||||||
|
|
||||||
|
from sqlmodel import Session
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESIndex
|
||||||
|
from inse.auth.model import AccessToken, Organization
|
||||||
|
from .model import (
|
||||||
|
TrendResponse,
|
||||||
|
TrendSeries,
|
||||||
|
TopicYearlyData,
|
||||||
|
TopInstitutionItem,
|
||||||
|
AutocompleteLocationItem
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Default fallback institution: University of Duisburg-Essen
|
||||||
|
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
||||||
|
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
||||||
|
|
||||||
|
async def autocomplete_locations(query: str) -> List[AutocompleteLocationItem]:
|
||||||
|
stripped = query.strip()
|
||||||
|
if not stripped:
|
||||||
|
return []
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
# Query countries index (Idea: Instead of wildcard: use alternative names?)
|
||||||
|
country_query = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{
|
||||||
|
"wildcard": {
|
||||||
|
"display_name.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": {
|
||||||
|
"country_code": {
|
||||||
|
"query": stripped.upper(),
|
||||||
|
"boost": 5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Query continents index
|
||||||
|
continent_query = {
|
||||||
|
"wildcard": {
|
||||||
|
"display_name.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
countries_res, continents_res = await asyncio.gather(
|
||||||
|
elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||||
|
query=country_query,
|
||||||
|
size=10,
|
||||||
|
source=["id", "display_name", "country_code", "wikidata_id"],
|
||||||
|
cluster="nes"
|
||||||
|
),
|
||||||
|
elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||||
|
query=continent_query,
|
||||||
|
size=5,
|
||||||
|
source=["id", "display_name", "wikidata_id"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to autocomplete locations in ES: %s", e)
|
||||||
|
return []
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
# Process continents
|
||||||
|
for hit in continents_res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
code_val = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||||
|
results.append(AutocompleteLocationItem(
|
||||||
|
id=code_val,
|
||||||
|
display_name=source["display_name"],
|
||||||
|
code=code_val,
|
||||||
|
type="continent"
|
||||||
|
))
|
||||||
|
|
||||||
|
# Process countries
|
||||||
|
for hit in countries_res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
results.append(AutocompleteLocationItem(
|
||||||
|
id=source["country_code"],
|
||||||
|
display_name=source["display_name"],
|
||||||
|
code=source["country_code"],
|
||||||
|
type="country"
|
||||||
|
))
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def get_top_institutions_by_region(
|
||||||
|
topic: str,
|
||||||
|
region: Optional[str] = None,
|
||||||
|
country: Optional[str] = None,
|
||||||
|
limit: int = 10
|
||||||
|
) -> List[TopInstitutionItem]:
|
||||||
|
"""
|
||||||
|
Search top educational institutions by region or country based on publication counts
|
||||||
|
for the specific topic, using a two-step Python-based sorting approach.
|
||||||
|
"""
|
||||||
|
country_codes = []
|
||||||
|
if country:
|
||||||
|
country_codes = [country.upper()]
|
||||||
|
elif region:
|
||||||
|
try:
|
||||||
|
# Query openalex-continents index to resolve continent country codes dynamically
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||||
|
query={
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"wikidata_id.keyword": region}},
|
||||||
|
{"term": {"id": f"https://openalex.org/continents/{region}"}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
size=1,
|
||||||
|
source=["countries"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
source = hits[0]["_source"]
|
||||||
|
country_codes = [
|
||||||
|
c["id"].split("/")[-1].upper() for c in source.get("countries", [])
|
||||||
|
]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve continent countries in get_top_institutions_by_region: %s", e)
|
||||||
|
|
||||||
|
# Resolve the topic to get the exact ID/display name
|
||||||
|
topic_filter = {"match_phrase": {"topics.display_name": topic}}
|
||||||
|
try:
|
||||||
|
topic_res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query={"match_phrase": {"display_name": topic}},
|
||||||
|
size=1,
|
||||||
|
source=["id", "display_name"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
hits = topic_res.get("hits", {}).get("hits", [])
|
||||||
|
if hits:
|
||||||
|
source = hits[0]["_source"]
|
||||||
|
topic_id = source["id"]
|
||||||
|
topic_filter = {"term": {"topics.id.keyword": topic_id}}
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic in get_top_institutions_by_region: %s", e)
|
||||||
|
|
||||||
|
# Query openalex-institutions for educational entities matching country and topic
|
||||||
|
must_clauses: List[Dict[str, Any]] = [
|
||||||
|
{"term": {"type": "education"}},
|
||||||
|
topic_filter
|
||||||
|
]
|
||||||
|
|
||||||
|
if country_codes:
|
||||||
|
must_clauses.append({"terms": {"geo.country_code": country_codes}})
|
||||||
|
|
||||||
|
query = {"bool": {"filter": must_clauses}}
|
||||||
|
|
||||||
|
# Fetch top 50 by overall works count to cover a good pool of institutions
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||||
|
query=query,
|
||||||
|
size=50,
|
||||||
|
source=["id", "display_name", "country_code", "works_count", "topics"],
|
||||||
|
sort=[{"works_count": "desc"}],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
hits = res.get("hits", {}).get("hits", [])
|
||||||
|
candidates = []
|
||||||
|
|
||||||
|
for hit in hits:
|
||||||
|
source = hit["_source"]
|
||||||
|
inst_id = source.get("id")
|
||||||
|
display_name = source.get("display_name", "Unknown")
|
||||||
|
country_code = source.get("country_code")
|
||||||
|
works_count = source.get("works_count")
|
||||||
|
|
||||||
|
# Extract exact count for the selected topic
|
||||||
|
exact_topic_count = 0
|
||||||
|
for t in source.get("topics", []):
|
||||||
|
if t.get("display_name", "").lower() == topic.lower():
|
||||||
|
exact_topic_count = t.get("count", 0)
|
||||||
|
break
|
||||||
|
|
||||||
|
candidates.append(TopInstitutionItem(
|
||||||
|
id=inst_id,
|
||||||
|
display_name=display_name,
|
||||||
|
country_code=country_code,
|
||||||
|
works_count=works_count,
|
||||||
|
exact_topic_count=exact_topic_count
|
||||||
|
))
|
||||||
|
|
||||||
|
# Sort candidates by exact_topic_count descending
|
||||||
|
candidates.sort(key=lambda x: x.exact_topic_count or 0, reverse=True)
|
||||||
|
|
||||||
|
return candidates[:limit]
|
||||||
|
|
||||||
|
async def get_trend_data(
|
||||||
|
topics: List[str],
|
||||||
|
institutions: Optional[List[str]] = None,
|
||||||
|
countries: Optional[List[str]] = None,
|
||||||
|
regions: Optional[List[str]] = None
|
||||||
|
) -> TrendResponse:
|
||||||
|
"""
|
||||||
|
Traverses the openalex-works index to retrieve yearly contributions of selected/top
|
||||||
|
institutions, countries, and regions across multiple topics.
|
||||||
|
"""
|
||||||
|
if not topics:
|
||||||
|
return TrendResponse(series=[], years=[])
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
start_year = 2000
|
||||||
|
end_year = datetime.datetime.now().year - 1
|
||||||
|
years_range = list(range(start_year, end_year + 1))
|
||||||
|
|
||||||
|
# Resolve primary institution (default University of Duisburg-Essen for everyone)
|
||||||
|
primary_inst_id = DEFAULT_INSTITUTION_ID
|
||||||
|
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||||
|
|
||||||
|
# Initialize institutions list and ensure primary is included
|
||||||
|
query_institutions = []
|
||||||
|
if institutions:
|
||||||
|
query_institutions = [i.strip() for i in institutions]
|
||||||
|
if primary_inst_id not in query_institutions:
|
||||||
|
query_institutions.insert(0, primary_inst_id)
|
||||||
|
|
||||||
|
# Prepare lists of countries and regions dynamically
|
||||||
|
query_countries = countries or []
|
||||||
|
query_regions = regions or []
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
# Define concurrent metadata lookups
|
||||||
|
async def fetch_institutions():
|
||||||
|
names = {primary_inst_id: primary_inst_name}
|
||||||
|
codes = {}
|
||||||
|
if not ids_to_resolve:
|
||||||
|
return names, codes
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||||
|
query={"terms": {"id": ids_to_resolve}},
|
||||||
|
size=len(ids_to_resolve),
|
||||||
|
source=["id", "display_name", "country_code"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
names[source["id"]] = source.get("display_name", source["id"])
|
||||||
|
codes[source["id"]] = source.get("country_code", "")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve institution details from ES: %s", e)
|
||||||
|
return names, codes
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
async def fetch_topics():
|
||||||
|
t_ids = {}
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index="openalex-topics",
|
||||||
|
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}},
|
||||||
|
size=len(topics) * 2,
|
||||||
|
source=["id", "display_name"],
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
for hit in res.get("hits", {}).get("hits", []):
|
||||||
|
source = hit["_source"]
|
||||||
|
for t in topics:
|
||||||
|
if t.lower() in source["display_name"].lower():
|
||||||
|
t_ids[t] = source["id"]
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to resolve topic IDs from ES: %s", e)
|
||||||
|
return t_ids
|
||||||
|
|
||||||
|
# Execute all 4 queries concurrently
|
||||||
|
(
|
||||||
|
(resolved_names, resolved_country_codes),
|
||||||
|
resolved_country_names,
|
||||||
|
(resolved_continent_names, continent_country_codes),
|
||||||
|
resolved_topic_ids
|
||||||
|
) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics())
|
||||||
|
|
||||||
|
location_mappings = continent_country_codes.copy()
|
||||||
|
|
||||||
|
# Map of filters inside our Elasticsearch aggregation
|
||||||
|
filters_map: Dict[str, Dict[str, Any]] = {}
|
||||||
|
|
||||||
|
# 1. Institution Filters
|
||||||
|
for inst_id in query_institutions:
|
||||||
|
filters_map[f"inst_{inst_id}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.id": inst_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Country Filters
|
||||||
|
for cc in clean_countries:
|
||||||
|
filters_map[f"country_{cc}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"term": {
|
||||||
|
"authorships.institutions.country_code": cc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3. Continent/Region Filters
|
||||||
|
for r_code, member_ccs in continent_country_codes.items():
|
||||||
|
if member_ccs:
|
||||||
|
filters_map[f"region_{r_code}"] = {
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": member_ccs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# If no entities specified, return empty
|
||||||
|
if not filters_map:
|
||||||
|
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||||
|
|
||||||
|
# We will accumulate results in a nested structure: entity_key -> topic -> year -> (count, inst_count)
|
||||||
|
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
|
||||||
|
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
|
||||||
|
for key in filters_map
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build topic matching clauses and filters
|
||||||
|
topic_clauses = []
|
||||||
|
topic_filters = {}
|
||||||
|
for t in topics:
|
||||||
|
tid = resolved_topic_ids.get(t)
|
||||||
|
if tid:
|
||||||
|
clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}},
|
||||||
|
{"term": {"primary_topic.id": tid}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
clause = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}},
|
||||||
|
{"match_phrase": {"primary_topic.display_name": t}}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
topic_clauses.append(clause)
|
||||||
|
topic_filters[t] = clause
|
||||||
|
|
||||||
|
# Build query-level entity filters to optimize search performance
|
||||||
|
entity_should_clauses = []
|
||||||
|
if query_institutions:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.id": query_institutions
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if clean_countries:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": clean_countries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
all_continent_countries = []
|
||||||
|
for member_ccs in continent_country_codes.values():
|
||||||
|
all_continent_countries.extend(member_ccs)
|
||||||
|
if all_continent_countries:
|
||||||
|
entity_should_clauses.append({
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships.institutions",
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"authorships.institutions.country_code": list(set(all_continent_countries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
# Construct the single-pass Elasticsearch query
|
||||||
|
filter_clauses = [
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"publication_year": {
|
||||||
|
"gte": start_year,
|
||||||
|
"lte": end_year
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"bool": {
|
||||||
|
"should": topic_clauses,
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
if entity_should_clauses:
|
||||||
|
filter_clauses.append({
|
||||||
|
"bool": {
|
||||||
|
"should": entity_should_clauses,
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
query = {
|
||||||
|
"bool": {
|
||||||
|
"filter": filter_clauses
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build two-layer nested aggregations (topics -> entities -> publication_year)
|
||||||
|
aggregations = {
|
||||||
|
"topics_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": topic_filters
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"entities_agg": {
|
||||||
|
"filters": {
|
||||||
|
"filters": filters_map
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"terms": {
|
||||||
|
"field": "publication_year",
|
||||||
|
"size": len(years_range) * 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = await elasticsearch.search(
|
||||||
|
index=f"{str(ESIndex.OPENALEX_WORKS)}*",
|
||||||
|
query=query,
|
||||||
|
body={"aggs": aggregations},
|
||||||
|
size=0,
|
||||||
|
cluster="nes"
|
||||||
|
)
|
||||||
|
|
||||||
|
topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {})
|
||||||
|
for t_name, t_bucket in topics_buckets.items():
|
||||||
|
entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {})
|
||||||
|
for entity_key, e_bucket in entities_buckets.items():
|
||||||
|
year_buckets = e_bucket.get("by_year", {}).get("buckets", [])
|
||||||
|
for yr_bucket in year_buckets:
|
||||||
|
yr = int(yr_bucket.get("key"))
|
||||||
|
count = int(yr_bucket.get("doc_count", 0))
|
||||||
|
inst_count = 1
|
||||||
|
if yr in years_range:
|
||||||
|
accumulated_data[entity_key][t_name][yr] = (count, inst_count)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error executing single-pass Elasticsearch query: %s", e)
|
||||||
|
|
||||||
|
# Construct lists of raw counts and S-Curves for all series to normalize in parallel
|
||||||
|
series_keys = []
|
||||||
|
raw_lists = []
|
||||||
|
cumsum_lists = []
|
||||||
|
inst_counts_map = {}
|
||||||
|
|
||||||
|
for entity_key, topic_dict in accumulated_data.items():
|
||||||
|
for topic, year_dict in topic_dict.items():
|
||||||
|
raw_counts = []
|
||||||
|
inst_counts = []
|
||||||
|
for yr in years_range:
|
||||||
|
count, inst_count = year_dict[yr]
|
||||||
|
raw_counts.append(count)
|
||||||
|
inst_counts.append(inst_count)
|
||||||
|
|
||||||
|
cumulative_counts = list(np.cumsum(raw_counts))
|
||||||
|
|
||||||
|
series_keys.append((entity_key, topic))
|
||||||
|
raw_lists.append(raw_counts)
|
||||||
|
cumsum_lists.append(cumulative_counts)
|
||||||
|
inst_counts_map[(entity_key, topic)] = inst_counts
|
||||||
|
|
||||||
|
normalized_lookup = {}
|
||||||
|
if raw_lists:
|
||||||
|
# Construct matrices of shape (n_years, n_series)
|
||||||
|
raw_matrix = np.array(raw_lists, dtype=float).T
|
||||||
|
cumsum_matrix = np.array(cumsum_lists, dtype=float).T
|
||||||
|
|
||||||
|
# Batch normalize columns in parallel using MinMaxScaler
|
||||||
|
scaler_raw = MinMaxScaler()
|
||||||
|
normalized_matrix = scaler_raw.fit_transform(raw_matrix)
|
||||||
|
|
||||||
|
scaler_cumsum = MinMaxScaler()
|
||||||
|
normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix)
|
||||||
|
|
||||||
|
# Transpose back to lists of shape (n_series, n_years)
|
||||||
|
normalized_lists = normalized_matrix.T.tolist()
|
||||||
|
normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist()
|
||||||
|
|
||||||
|
for idx, (entity_key, topic) in enumerate(series_keys):
|
||||||
|
normalized_lookup[(entity_key, topic)] = {
|
||||||
|
"normalized": normalized_lists[idx],
|
||||||
|
"cumulative": normalized_cumsum_lists[idx]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Process and build TrendSeries list
|
||||||
|
series_list: List[TrendSeries] = []
|
||||||
|
|
||||||
|
for entity_key, topic_dict in accumulated_data.items():
|
||||||
|
# Resolve details for this entity
|
||||||
|
if entity_key.startswith("inst_"):
|
||||||
|
entity_id = entity_key[len("inst_"):]
|
||||||
|
entity_name = resolved_names.get(entity_id, entity_id)
|
||||||
|
entity_type = "institution"
|
||||||
|
elif entity_key.startswith("country_"):
|
||||||
|
entity_id = entity_key[len("country_"):]
|
||||||
|
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
|
||||||
|
entity_type = "country"
|
||||||
|
elif entity_key.startswith("region_"):
|
||||||
|
entity_id = entity_key[len("region_"):]
|
||||||
|
entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}")
|
||||||
|
entity_type = "region"
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
topic_data_map: Dict[str, List[TopicYearlyData]] = {}
|
||||||
|
|
||||||
|
for topic, year_dict in topic_dict.items():
|
||||||
|
yearly_data_items: List[TopicYearlyData] = []
|
||||||
|
|
||||||
|
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||||
|
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||||
|
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||||
|
inst_counts = inst_counts_map.get((entity_key, topic), [1] * len(years_range))
|
||||||
|
|
||||||
|
for idx, yr in enumerate(years_range):
|
||||||
|
count, _ = year_dict[yr]
|
||||||
|
yearly_data_items.append(TopicYearlyData(
|
||||||
|
year=yr,
|
||||||
|
raw=count,
|
||||||
|
normalized=norm_vals[idx],
|
||||||
|
cumulative=cum_vals[idx],
|
||||||
|
institutions_count=inst_counts[idx]
|
||||||
|
))
|
||||||
|
|
||||||
|
topic_data_map[topic] = yearly_data_items
|
||||||
|
|
||||||
|
series_list.append(TrendSeries(
|
||||||
|
entity_id=entity_id,
|
||||||
|
entity_name=entity_name,
|
||||||
|
entity_type=entity_type,
|
||||||
|
country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None,
|
||||||
|
topic_data=topic_data_map
|
||||||
|
))
|
||||||
|
|
||||||
|
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
|
||||||
|
|
||||||
@@ -55,6 +55,7 @@ async def get_author_works(
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
client: OpenAlexWorksSearchClient | None = None,
|
client: OpenAlexWorksSearchClient | None = None,
|
||||||
) -> WorkPage:
|
) -> WorkPage:
|
||||||
search_client = client or OpenAlexWorksSearchClient()
|
search_client = client or OpenAlexWorksSearchClient()
|
||||||
@@ -68,9 +69,11 @@ async def get_author_works(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
elements, total = _parse_full_work_search_response(data)
|
elements, total = _parse_full_work_search_response(data)
|
||||||
|
await _enrich_work_topic_descriptions(elements)
|
||||||
offset = (page - 1) * size
|
offset = (page - 1) * size
|
||||||
last_page = offset + len(elements) >= total
|
last_page = offset + len(elements) >= total
|
||||||
|
|
||||||
@@ -166,6 +169,15 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
|||||||
"primary_topics": {
|
"primary_topics": {
|
||||||
"terms": {"field": "primary_topic.id", "size": 1000},
|
"terms": {"field": "primary_topic.id", "size": 1000},
|
||||||
},
|
},
|
||||||
|
"all_topics": {
|
||||||
|
"nested": {"path": "topics"},
|
||||||
|
"aggs": {
|
||||||
|
"topic_ids": {
|
||||||
|
"terms": {"field": "topics.id", "size": 1000},
|
||||||
|
"aggs": {"works": {"reverse_nested": {}}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,10 +192,25 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
|||||||
|
|
||||||
aggregations = response.get("aggregations", {})
|
aggregations = response.get("aggregations", {})
|
||||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||||
|
topic_buckets = (
|
||||||
|
aggregations.get("all_topics", {}).get("topic_ids", {}).get("buckets", [])
|
||||||
|
)
|
||||||
|
|
||||||
|
broad_counts = {
|
||||||
|
bucket["key"]: bucket.get("works", {}).get("doc_count", bucket["doc_count"])
|
||||||
|
for bucket in topic_buckets
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
counts = []
|
counts = []
|
||||||
for bucket in buckets:
|
for bucket in buckets:
|
||||||
counts.append({"id": bucket["key"], "count": bucket["doc_count"]})
|
topic_id = bucket["key"]
|
||||||
|
counts.append(
|
||||||
|
{
|
||||||
|
"id": topic_id,
|
||||||
|
"count": max(broad_counts.get(topic_id, 0), bucket["doc_count"]),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
@@ -202,9 +229,44 @@ async def get_work(
|
|||||||
elements, _ = _parse_full_work_search_response(response_by_title)
|
elements, _ = _parse_full_work_search_response(response_by_title)
|
||||||
if not elements:
|
if not elements:
|
||||||
return None
|
return None
|
||||||
|
await _enrich_work_topic_descriptions(elements[:1])
|
||||||
return elements[0]
|
return elements[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def enrich_topic_descriptions(topics: List) -> None:
|
||||||
|
"""Batch-fill missing descriptions on dehydrated topics.
|
||||||
|
|
||||||
|
OpenAlex work and author documents carry dehydrated topics without a
|
||||||
|
description, so we batch-load the details from the openalex-topics index.
|
||||||
|
"""
|
||||||
|
pending = [topic for topic in topics if topic.id and not topic.description]
|
||||||
|
|
||||||
|
if not pending:
|
||||||
|
return
|
||||||
|
|
||||||
|
details = await _get_topic_details(list({topic.id for topic in pending}))
|
||||||
|
|
||||||
|
if not details:
|
||||||
|
return
|
||||||
|
|
||||||
|
for topic in pending:
|
||||||
|
info = details.get(topic.id)
|
||||||
|
if info:
|
||||||
|
topic.description = info.get("description")
|
||||||
|
|
||||||
|
|
||||||
|
async def _enrich_work_topic_descriptions(works: List[Work]) -> None:
|
||||||
|
topics = []
|
||||||
|
|
||||||
|
for work in works:
|
||||||
|
topics.extend(work.topics or [])
|
||||||
|
|
||||||
|
if work.primary_topic:
|
||||||
|
topics.append(work.primary_topic)
|
||||||
|
|
||||||
|
await enrich_topic_descriptions(topics)
|
||||||
|
|
||||||
|
|
||||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||||
if not topic_ids:
|
if not topic_ids:
|
||||||
return {}
|
return {}
|
||||||
@@ -869,6 +931,7 @@ async def _search_author_works_data(
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
return await search_client.search_author_works(
|
return await search_client.search_author_works(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -879,6 +942,7 @@ async def _search_author_works_data(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
Pydantic models for publication works.
|
Pydantic models for publication works.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from enum import StrEnum
|
||||||
from typing import List
|
from typing import List
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
@@ -41,3 +42,35 @@ class WorkPage(BaseModel):
|
|||||||
class WorkList(BaseModel):
|
class WorkList(BaseModel):
|
||||||
elements: List[Work] = Field(default_factory=list, description="All works.")
|
elements: List[Work] = Field(default_factory=list, description="All works.")
|
||||||
total: int = Field(default=0, description="The total number of works.")
|
total: int = Field(default=0, description="The total number of works.")
|
||||||
|
|
||||||
|
|
||||||
|
class WorkPurpose(StrEnum):
|
||||||
|
"""Represents the purpose of a work. Either a foundation work or an application work."""
|
||||||
|
|
||||||
|
FOUNDATION = "Foundation"
|
||||||
|
APPLICATION = "Application"
|
||||||
|
|
||||||
|
|
||||||
|
class SpecificWorkPurpose(BaseModel):
|
||||||
|
"""Represents the purpose of a specific work, including its ID, purpose, and optional reasoning."""
|
||||||
|
|
||||||
|
raw_oa_work_id: str = Field(description="The raw OpenAlex work id.")
|
||||||
|
publication_year: Optional[int] = Field(
|
||||||
|
default=None, description="The publication year of the work."
|
||||||
|
)
|
||||||
|
purpose: WorkPurpose = Field(description="The purpose of the work.")
|
||||||
|
reasoning: Optional[str] = Field(
|
||||||
|
default=None, description="The reasoning behind the purpose determination."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorWorkPurposes(BaseModel):
|
||||||
|
"""Represents the purposes of an author, including their ID and a list of specific work purposes."""
|
||||||
|
|
||||||
|
raw_oa_author_id: str = Field(description="The raw OpenAlex author id.")
|
||||||
|
total: int = Field(
|
||||||
|
default=0, description="The total number of works for the author."
|
||||||
|
)
|
||||||
|
purposes: List[SpecificWorkPurpose] = Field(
|
||||||
|
default_factory=list, description="The list of specific work purposes."
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Path
|
||||||
|
|
||||||
|
from inse.tags import Tags
|
||||||
|
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose
|
||||||
|
|
||||||
|
from inse.works import purpose_service
|
||||||
|
|
||||||
|
WORKS_PREFIX = "/api/purpose"
|
||||||
|
|
||||||
|
router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{raw_oa_work_id}/purpose",
|
||||||
|
operation_id="getWorkPurpose",
|
||||||
|
summary="Returns the purpose of a work based on its ID.",
|
||||||
|
)
|
||||||
|
async def get_work_purpose(
|
||||||
|
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
|
||||||
|
) -> SpecificWorkPurpose:
|
||||||
|
return await purpose_service.get_work_purpose(raw_oa_work_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/{raw_oa_author_id}/purposes",
|
||||||
|
operation_id="getAuthorWorkPurposes",
|
||||||
|
summary="Returns the purposes of an author based on their ID.",
|
||||||
|
)
|
||||||
|
async def get_author_work_purposes(
|
||||||
|
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
|
||||||
|
) -> AuthorWorkPurposes:
|
||||||
|
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import logging
|
||||||
|
import random
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
|
||||||
|
from inse.exceptions import NotFoundException
|
||||||
|
from inse.integrations import elasticsearch
|
||||||
|
from inse.model import ESIndex
|
||||||
|
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
|
||||||
|
raw_oa_work_id = raw_oa_work_id.strip().upper()
|
||||||
|
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_WORKS,
|
||||||
|
doc_id=raw_oa_work_id,
|
||||||
|
source=["title", "abstract"],
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(f"Elasticsearch response for work id {raw_oa_work_id}: {response}")
|
||||||
|
|
||||||
|
source = response.get("_source", {})
|
||||||
|
if not source:
|
||||||
|
raise NotFoundException(f"Work with id {raw_oa_work_id} not found.")
|
||||||
|
|
||||||
|
logger.debug(f"Found work source for id {raw_oa_work_id}: {source}")
|
||||||
|
|
||||||
|
return SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=raw_oa_work_id,
|
||||||
|
publication_year=source.get("publication_year"),
|
||||||
|
purpose=WorkPurpose.FOUNDATION, # TODO: Replace with actual purpose determination logic
|
||||||
|
reasoning="This is a placeholder reasoning for the purpose determination.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
|
||||||
|
raw_oa_author_id = raw_oa_author_id.strip().upper()
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.OPENALEX_WORKS,
|
||||||
|
source=["id", "publication_year"],
|
||||||
|
query={
|
||||||
|
"nested": {
|
||||||
|
"path": "authorships",
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"term": {
|
||||||
|
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
size=10000,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug(f"Elasticsearch response for author id {raw_oa_author_id}: {response}")
|
||||||
|
|
||||||
|
purposes: List[SpecificWorkPurpose] = []
|
||||||
|
|
||||||
|
# TODO: implement actual retrieval of previously determined purposes for the author's works
|
||||||
|
|
||||||
|
hits_block = response.get("hits", {})
|
||||||
|
hits = hits_block.get("hits", [])
|
||||||
|
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||||
|
for hit in hits:
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
work_id = source.get("id")
|
||||||
|
publication_year = source.get("publication_year")
|
||||||
|
if work_id:
|
||||||
|
# TODO: Remove random based purpose assignment
|
||||||
|
if random.choice([True, False]):
|
||||||
|
purpose = SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=work_id,
|
||||||
|
publication_year=publication_year,
|
||||||
|
purpose=WorkPurpose.FOUNDATION,
|
||||||
|
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
purpose = SpecificWorkPurpose(
|
||||||
|
raw_oa_work_id=work_id,
|
||||||
|
publication_year=publication_year,
|
||||||
|
purpose=WorkPurpose.APPLICATION,
|
||||||
|
reasoning=f"Placeholder reasoning for work {work_id}.",
|
||||||
|
)
|
||||||
|
|
||||||
|
purposes.append(purpose)
|
||||||
|
else:
|
||||||
|
logger.warning(f"Work hit without id for author {raw_oa_author_id}: {hit}")
|
||||||
|
|
||||||
|
return AuthorWorkPurposes(
|
||||||
|
raw_oa_author_id=raw_oa_author_id, total=total_hits, purposes=purposes
|
||||||
|
)
|
||||||
@@ -35,6 +35,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||||
filters = self._work_filters(
|
filters = self._work_filters(
|
||||||
@@ -73,19 +74,27 @@ class OpenAlexWorksSearchClient:
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
if sort == "citations":
|
||||||
|
sort_clauses = [
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
sort_clauses = [
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
return {
|
return {
|
||||||
"from": (page - 1) * size,
|
"from": (page - 1) * size,
|
||||||
"size": size,
|
"size": size,
|
||||||
|
"track_total_hits": True,
|
||||||
"query": {
|
"query": {
|
||||||
"bool": {
|
"bool": {
|
||||||
"must": must_clauses,
|
"must": must_clauses,
|
||||||
"filter": filters,
|
"filter": filters,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"sort": [
|
"sort": sort_clauses,
|
||||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
|
||||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _work_filters(
|
def _work_filters(
|
||||||
@@ -129,6 +138,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language: list[str] | None = None,
|
language: list[str] | None = None,
|
||||||
institution_id: list[str] | None = None,
|
institution_id: list[str] | None = None,
|
||||||
topic_id: list[str] | None = None,
|
topic_id: list[str] | None = None,
|
||||||
|
sort: str = "year",
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
if not self.api_key:
|
if not self.api_key:
|
||||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||||
@@ -142,6 +152,7 @@ class OpenAlexWorksSearchClient:
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
REST API for publication works.
|
REST API for publication works.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Annotated, Optional
|
from typing import Annotated, Literal, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
from fastapi import Path
|
from fastapi import Path
|
||||||
@@ -54,6 +54,10 @@ async def get_author_works(
|
|||||||
list[str] | None,
|
list[str] | None,
|
||||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||||
] = None,
|
] = None,
|
||||||
|
sort: Annotated[
|
||||||
|
Literal["year", "citations"],
|
||||||
|
Query(description="Sort order: by publication year or by citation count."),
|
||||||
|
] = "year",
|
||||||
):
|
):
|
||||||
return await logic.get_author_works(
|
return await logic.get_author_works(
|
||||||
author_id,
|
author_id,
|
||||||
@@ -64,6 +68,7 @@ async def get_author_works(
|
|||||||
language=language,
|
language=language,
|
||||||
institution_id=institution_id,
|
institution_id=institution_id,
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
|
sort=sort,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,28 @@ def test_author_works_query_searches_authorship_author_id():
|
|||||||
assert query["query"]["bool"]["filter"] == []
|
assert query["query"]["bool"]["filter"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_author_works_query_sorts_by_year_by_default():
|
||||||
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
query = client.author_works_query("A5023888391", page=1, size=20)
|
||||||
|
|
||||||
|
assert query["sort"] == [
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_author_works_query_sorts_by_citations():
|
||||||
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
query = client.author_works_query("A5023888391", page=1, size=20, sort="citations")
|
||||||
|
|
||||||
|
assert query["sort"] == [
|
||||||
|
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||||
|
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def test_author_works_query_adds_publication_filters():
|
def test_author_works_query_adds_publication_filters():
|
||||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||||
|
|
||||||
|
|||||||
@@ -1195,6 +1195,11 @@ Content-Type: application/json
|
|||||||
|
|
||||||
###
|
###
|
||||||
|
|
||||||
|
GET https://project.nes.uni-due.de/elastic/openalex-works/_mapping
|
||||||
|
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||||
|
|
||||||
|
###
|
||||||
|
|
||||||
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
GET https://project.nes.uni-due.de/elastic/openalex-works/_search
|
||||||
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
|
|||||||
@@ -12,9 +12,9 @@
|
|||||||
"ngVersion": "21.2.14",
|
"ngVersion": "21.2.14",
|
||||||
"providedInRoot": true,
|
"providedInRoot": true,
|
||||||
"serviceSuffix": "Service",
|
"serviceSuffix": "Service",
|
||||||
"withInterfaces": true,
|
"withInterfaces": false,
|
||||||
"enumPropertyNaming": "original",
|
"enumPropertyNaming": "original",
|
||||||
"fileNaming": "kebab-case"
|
"fileNaming": "camelCase"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ api/companyConnections.service.ts
|
|||||||
api/funding.service.ts
|
api/funding.service.ts
|
||||||
api/iNSEService.service.ts
|
api/iNSEService.service.ts
|
||||||
api/institutions.service.ts
|
api/institutions.service.ts
|
||||||
|
api/keywords.service.ts
|
||||||
api/news.service.ts
|
api/news.service.ts
|
||||||
api/organization.service.ts
|
api/organization.service.ts
|
||||||
api/patents.service.ts
|
api/patents.service.ts
|
||||||
@@ -16,6 +17,7 @@ api/personNetwork.service.ts
|
|||||||
api/persons.service.ts
|
api/persons.service.ts
|
||||||
api/projects.service.ts
|
api/projects.service.ts
|
||||||
api/topics.service.ts
|
api/topics.service.ts
|
||||||
|
api/universityRankings.service.ts
|
||||||
api/works.service.ts
|
api/works.service.ts
|
||||||
configuration.ts
|
configuration.ts
|
||||||
encoder.ts
|
encoder.ts
|
||||||
@@ -34,9 +36,11 @@ model/authorNetworkNode.ts
|
|||||||
model/authorParsedLongestName.ts
|
model/authorParsedLongestName.ts
|
||||||
model/authorPositionCount.ts
|
model/authorPositionCount.ts
|
||||||
model/authorSummaryStats.ts
|
model/authorSummaryStats.ts
|
||||||
|
model/authorWorkPurposes.ts
|
||||||
model/authorsFilterProperties.ts
|
model/authorsFilterProperties.ts
|
||||||
model/authorsListResponse.ts
|
model/authorsListResponse.ts
|
||||||
model/authorship.ts
|
model/authorship.ts
|
||||||
|
model/autocompleteLocationItem.ts
|
||||||
model/autocompleteResponse.ts
|
model/autocompleteResponse.ts
|
||||||
model/autocompleteResponseMeta.ts
|
model/autocompleteResponseMeta.ts
|
||||||
model/autocompleteResponseResultsInner.ts
|
model/autocompleteResponseResultsInner.ts
|
||||||
@@ -45,6 +49,8 @@ model/bodyChangePassword.ts
|
|||||||
model/bodyGetAccessToken.ts
|
model/bodyGetAccessToken.ts
|
||||||
model/bodyLogin.ts
|
model/bodyLogin.ts
|
||||||
model/bodyRequestOtk.ts
|
model/bodyRequestOtk.ts
|
||||||
|
model/bodyRequestPasswordReset.ts
|
||||||
|
model/bodyResetPassword.ts
|
||||||
model/bundProject.ts
|
model/bundProject.ts
|
||||||
model/bundProjectDetails.ts
|
model/bundProjectDetails.ts
|
||||||
model/bundProjectPage.ts
|
model/bundProjectPage.ts
|
||||||
@@ -72,6 +78,9 @@ model/euCordisProjectResponse.ts
|
|||||||
model/euOrganizationProjectSummary.ts
|
model/euOrganizationProjectSummary.ts
|
||||||
model/euOrganizationProjectSummaryPage.ts
|
model/euOrganizationProjectSummaryPage.ts
|
||||||
model/euProjectData.ts
|
model/euProjectData.ts
|
||||||
|
model/extractedKeywords.ts
|
||||||
|
model/extractedKeywordsLLM.ts
|
||||||
|
model/extractedKeywordsResponse.ts
|
||||||
model/filterInformation.ts
|
model/filterInformation.ts
|
||||||
model/filterProperties.ts
|
model/filterProperties.ts
|
||||||
model/fp7EurosciVoc.ts
|
model/fp7EurosciVoc.ts
|
||||||
@@ -109,7 +118,7 @@ model/hEUReportSummary.ts
|
|||||||
model/hEUTopic.ts
|
model/hEUTopic.ts
|
||||||
model/hEUWebLink.ts
|
model/hEUWebLink.ts
|
||||||
model/hTTPValidationError.ts
|
model/hTTPValidationError.ts
|
||||||
model/idToken.ts
|
model/idTokenMetadata.ts
|
||||||
model/inseAccountManagementModelOrganizationProfile.ts
|
model/inseAccountManagementModelOrganizationProfile.ts
|
||||||
model/inseOrganizationManagementModelOrganizationProfile.ts
|
model/inseOrganizationManagementModelOrganizationProfile.ts
|
||||||
model/institution.ts
|
model/institution.ts
|
||||||
@@ -121,12 +130,20 @@ model/institutionNetworkNode.ts
|
|||||||
model/institutionPage.ts
|
model/institutionPage.ts
|
||||||
model/institutionsListResponse.ts
|
model/institutionsListResponse.ts
|
||||||
model/ipcClassification.ts
|
model/ipcClassification.ts
|
||||||
|
model/keywordEntry.ts
|
||||||
|
model/keywordEntryWithTopic.ts
|
||||||
|
model/keywordTopicMatch.ts
|
||||||
model/keywords.ts
|
model/keywords.ts
|
||||||
|
model/keywordsRequest.ts
|
||||||
|
model/keywordsTopicsRequest.ts
|
||||||
|
model/keywordsTopicsResponse.ts
|
||||||
model/latitude.ts
|
model/latitude.ts
|
||||||
model/location.ts
|
model/location.ts
|
||||||
model/loginResponse.ts
|
model/loginResponse.ts
|
||||||
model/longitude.ts
|
model/longitude.ts
|
||||||
|
model/matchedAuthor.ts
|
||||||
model/matchedOfficer.ts
|
model/matchedOfficer.ts
|
||||||
|
model/matchedTopic.ts
|
||||||
model/mentionedPerson.ts
|
model/mentionedPerson.ts
|
||||||
model/meta.ts
|
model/meta.ts
|
||||||
model/model2YrMeanCitedness.ts
|
model/model2YrMeanCitedness.ts
|
||||||
@@ -135,9 +152,13 @@ model/newsArticle.ts
|
|||||||
model/newsArticleDetail.ts
|
model/newsArticleDetail.ts
|
||||||
model/newsPage.ts
|
model/newsPage.ts
|
||||||
model/openAccess.ts
|
model/openAccess.ts
|
||||||
|
model/orgPatentEntry.ts
|
||||||
|
model/orgPatentsResponse.ts
|
||||||
model/organizationPage.ts
|
model/organizationPage.ts
|
||||||
|
model/otkResponse.ts
|
||||||
model/patentEntry.ts
|
model/patentEntry.ts
|
||||||
model/patentsByAuthorResponse.ts
|
model/patentsByAuthorResponse.ts
|
||||||
|
model/patentsByInstitutionResponse.ts
|
||||||
model/personBio.ts
|
model/personBio.ts
|
||||||
model/projectType.ts
|
model/projectType.ts
|
||||||
model/projectsFilteringProperties.ts
|
model/projectsFilteringProperties.ts
|
||||||
@@ -146,20 +167,24 @@ model/publicationDetailByFunder.ts
|
|||||||
model/publicationIdsByAuthorPosition.ts
|
model/publicationIdsByAuthorPosition.ts
|
||||||
model/publicationsByAuthorResponse.ts
|
model/publicationsByAuthorResponse.ts
|
||||||
model/rankingResponse.ts
|
model/rankingResponse.ts
|
||||||
model/refreshToken.ts
|
|
||||||
model/score.ts
|
model/score.ts
|
||||||
model/sortDirection.ts
|
model/sortDirection.ts
|
||||||
|
model/specificWorkPurpose.ts
|
||||||
model/tokenType.ts
|
model/tokenType.ts
|
||||||
|
model/topInstitutionItem.ts
|
||||||
model/topic.ts
|
model/topic.ts
|
||||||
model/topicCount.ts
|
model/topicCount.ts
|
||||||
model/topicDomain.ts
|
model/topicDomain.ts
|
||||||
model/topicField.ts
|
model/topicField.ts
|
||||||
model/topicIds.ts
|
model/topicIds.ts
|
||||||
model/topicSubfield.ts
|
model/topicSubfield.ts
|
||||||
|
model/topicYearlyData.ts
|
||||||
model/topics.ts
|
model/topics.ts
|
||||||
model/topicsByTime.ts
|
model/topicsByTime.ts
|
||||||
model/topicsByYear.ts
|
model/topicsByYear.ts
|
||||||
model/topicsListResponse.ts
|
model/topicsListResponse.ts
|
||||||
|
model/trendResponse.ts
|
||||||
|
model/trendSeries.ts
|
||||||
model/universityRanking.ts
|
model/universityRanking.ts
|
||||||
model/universityTopicData.ts
|
model/universityTopicData.ts
|
||||||
model/updateAccountRequest.ts
|
model/updateAccountRequest.ts
|
||||||
@@ -179,6 +204,7 @@ model/workKeyword.ts
|
|||||||
model/workMeshInner.ts
|
model/workMeshInner.ts
|
||||||
model/workNetworkNode.ts
|
model/workNetworkNode.ts
|
||||||
model/workPage.ts
|
model/workPage.ts
|
||||||
|
model/workPurpose.ts
|
||||||
model/workSustainableDevelopmentGoalsInner.ts
|
model/workSustainableDevelopmentGoalsInner.ts
|
||||||
model/workTopic.ts
|
model/workTopic.ts
|
||||||
model/workTopicDomain.ts
|
model/workTopicDomain.ts
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ export * from './iNSEService.service';
|
|||||||
import { INSEServiceService } from './iNSEService.service';
|
import { INSEServiceService } from './iNSEService.service';
|
||||||
export * from './institutions.service';
|
export * from './institutions.service';
|
||||||
import { InstitutionsService } from './institutions.service';
|
import { InstitutionsService } from './institutions.service';
|
||||||
|
export * from './keywords.service';
|
||||||
|
import { KeywordsService } from './keywords.service';
|
||||||
export * from './news.service';
|
export * from './news.service';
|
||||||
import { NewsService } from './news.service';
|
import { NewsService } from './news.service';
|
||||||
export * from './organization.service';
|
export * from './organization.service';
|
||||||
@@ -22,6 +24,8 @@ export * from './projects.service';
|
|||||||
import { ProjectsService } from './projects.service';
|
import { ProjectsService } from './projects.service';
|
||||||
export * from './topics.service';
|
export * from './topics.service';
|
||||||
import { TopicsService } from './topics.service';
|
import { TopicsService } from './topics.service';
|
||||||
|
export * from './universityRankings.service';
|
||||||
|
import { UniversityRankingsService } from './universityRankings.service';
|
||||||
export * from './works.service';
|
export * from './works.service';
|
||||||
import { WorksService } from './works.service';
|
import { WorksService } from './works.service';
|
||||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService];
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ import { BodyLogin } from '../model/bodyLogin';
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset';
|
||||||
|
// @ts-ignore
|
||||||
|
import { BodyResetPassword } from '../model/bodyResetPassword';
|
||||||
|
// @ts-ignore
|
||||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
@@ -41,6 +45,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { LoginResponse } from '../model/loginResponse';
|
import { LoginResponse } from '../model/loginResponse';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { OtkResponse } from '../model/otkResponse';
|
||||||
|
// @ts-ignore
|
||||||
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -64,13 +70,14 @@ export class AuthService extends BaseService {
|
|||||||
* Change the user\'s password and invalidate existing tokens.
|
* Change the user\'s password and invalidate existing tokens.
|
||||||
* @endpoint post /api/auth/v2/change-password
|
* @endpoint post /api/auth/v2/change-password
|
||||||
* @param bodyChangePassword
|
* @param bodyChangePassword
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
||||||
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
||||||
}
|
}
|
||||||
@@ -132,13 +139,14 @@ export class AuthService extends BaseService {
|
|||||||
* Create Account
|
* Create Account
|
||||||
* @endpoint post /api/accounts
|
* @endpoint post /api/accounts
|
||||||
* @param createAccountRequest
|
* @param createAccountRequest
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (createAccountRequest === null || createAccountRequest === undefined) {
|
if (createAccountRequest === null || createAccountRequest === undefined) {
|
||||||
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
|
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
|
||||||
}
|
}
|
||||||
@@ -200,13 +208,14 @@ export class AuthService extends BaseService {
|
|||||||
* Delete Account
|
* Delete Account
|
||||||
* @endpoint delete /api/accounts/{account_id}
|
* @endpoint delete /api/accounts/{account_id}
|
||||||
* @param accountId
|
* @param accountId
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (accountId === null || accountId === undefined) {
|
if (accountId === null || accountId === undefined) {
|
||||||
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
|
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
|
||||||
}
|
}
|
||||||
@@ -259,22 +268,20 @@ export class AuthService extends BaseService {
|
|||||||
* Retrieve an access token for the authenticated user.
|
* Retrieve an access token for the authenticated user.
|
||||||
* @endpoint post /api/auth/v2/access
|
* @endpoint post /api/auth/v2/access
|
||||||
* @param bodyGetAccessToken
|
* @param bodyGetAccessToken
|
||||||
|
* @param idToken
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||||
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
// authentication (HTTPBearer) required
|
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -326,13 +333,14 @@ export class AuthService extends BaseService {
|
|||||||
/**
|
/**
|
||||||
* Get Current Account
|
* Get Current Account
|
||||||
* @endpoint get /api/accounts/me
|
* @endpoint get /api/accounts/me
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -431,13 +439,14 @@ export class AuthService extends BaseService {
|
|||||||
/**
|
/**
|
||||||
* List Organizations
|
* List Organizations
|
||||||
* @endpoint get /api/accounts/organizations
|
* @endpoint get /api/accounts/organizations
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<InseAccountManagementModelOrganizationProfile>>;
|
||||||
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||||
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<InseAccountManagementModelOrganizationProfile>>>;
|
||||||
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -490,13 +499,14 @@ export class AuthService extends BaseService {
|
|||||||
* @param offset
|
* @param offset
|
||||||
* @param search
|
* @param search
|
||||||
* @param organizationId
|
* @param organizationId
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
||||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -624,13 +634,14 @@ export class AuthService extends BaseService {
|
|||||||
* Logout
|
* Logout
|
||||||
* Logout the authenticated user.
|
* Logout the authenticated user.
|
||||||
* @endpoint post /api/auth/v2/logout
|
* @endpoint post /api/auth/v2/logout
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -679,19 +690,17 @@ export class AuthService extends BaseService {
|
|||||||
* Refresh Access Token
|
* Refresh Access Token
|
||||||
* Refresh the access token using a valid refresh token.
|
* Refresh the access token using a valid refresh token.
|
||||||
* @endpoint post /api/auth/v2/refresh
|
* @endpoint post /api/auth/v2/refresh
|
||||||
|
* @param refreshToken
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
||||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||||
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
// authentication (HTTPBearer) required
|
|
||||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -738,9 +747,9 @@ export class AuthService extends BaseService {
|
|||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OtkResponse>;
|
||||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OtkResponse>>;
|
||||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OtkResponse>>;
|
||||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||||
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||||
@@ -782,7 +791,7 @@ export class AuthService extends BaseService {
|
|||||||
|
|
||||||
let localVarPath = `/api/auth/v2/request-otk`;
|
let localVarPath = `/api/auth/v2/request-otk`;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
return this.httpClient.request<OtkResponse>('post', `${basePath}${localVarPath}`,
|
||||||
{
|
{
|
||||||
context: localVarHttpContext,
|
context: localVarHttpContext,
|
||||||
body: bodyRequestOtk,
|
body: bodyRequestOtk,
|
||||||
@@ -796,18 +805,151 @@ export class AuthService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request Password Reset
|
||||||
|
* Request a one-time password reset link for the given email address.
|
||||||
|
* @endpoint post /api/auth/v2/request-password-reset
|
||||||
|
* @param bodyRequestPasswordReset
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyRequestPasswordReset === null || bodyRequestPasswordReset === undefined) {
|
||||||
|
throw new Error('Required parameter bodyRequestPasswordReset was null or undefined when calling requestPasswordReset.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/request-password-reset`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyRequestPasswordReset,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset Password
|
||||||
|
* Reset the user\'s password using a one-time password reset token.
|
||||||
|
* @endpoint post /api/auth/v2/reset-password
|
||||||
|
* @param bodyResetPassword
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
|
public resetPassword(bodyResetPassword: BodyResetPassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (bodyResetPassword === null || bodyResetPassword === undefined) {
|
||||||
|
throw new Error('Required parameter bodyResetPassword was null or undefined when calling resetPassword.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/auth/v2/reset-password`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: bodyResetPassword,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update Account
|
* Update Account
|
||||||
* @endpoint put /api/accounts/{account_id}
|
* @endpoint put /api/accounts/{account_id}
|
||||||
* @param accountId
|
* @param accountId
|
||||||
* @param updateAccountRequest
|
* @param updateAccountRequest
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (accountId === null || accountId === undefined) {
|
if (accountId === null || accountId === undefined) {
|
||||||
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
|
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,8 +26,6 @@ import { Institution } from '../model/institution';
|
|||||||
import { InstitutionPage } from '../model/institutionPage';
|
import { InstitutionPage } from '../model/institutionPage';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
||||||
// @ts-ignore
|
|
||||||
import { RankingResponse } from '../model/rankingResponse';
|
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
@@ -170,69 +168,6 @@ export class InstitutionsService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns data for the University Ranking Dashboard.
|
|
||||||
* @endpoint get /api/inse-service/university-rankings
|
|
||||||
* @param topic Research topic (e.g., \'Artificial Intelligence\')
|
|
||||||
* @param metric Metric to rank by
|
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
|
||||||
* @param reportProgress flag to report request and response progress.
|
|
||||||
*/
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
|
||||||
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
|
||||||
if (topic === null || topic === undefined) {
|
|
||||||
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
|
||||||
<any>topic, 'topic');
|
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
|
||||||
<any>metric, 'metric');
|
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
|
||||||
'application/json'
|
|
||||||
]);
|
|
||||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
|
||||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
|
||||||
}
|
|
||||||
|
|
||||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
|
||||||
|
|
||||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
|
||||||
|
|
||||||
|
|
||||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
|
||||||
if (localVarHttpHeaderAcceptSelected) {
|
|
||||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
|
||||||
responseType_ = 'text';
|
|
||||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
|
||||||
responseType_ = 'json';
|
|
||||||
} else {
|
|
||||||
responseType_ = 'blob';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let localVarPath = `/api/inse-service/university-rankings`;
|
|
||||||
const { basePath, withCredentials } = this.configuration;
|
|
||||||
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
|
||||||
{
|
|
||||||
context: localVarHttpContext,
|
|
||||||
params: localVarQueryParameters,
|
|
||||||
responseType: <any>responseType_,
|
|
||||||
...(withCredentials ? { withCredentials } : {}),
|
|
||||||
headers: localVarHeaders,
|
|
||||||
observe: observe,
|
|
||||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
|
||||||
reportProgress: reportProgress
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a list of OpenAlex institutions.
|
* Returns a list of OpenAlex institutions.
|
||||||
* @endpoint get /api/inse-service/institutions
|
* @endpoint get /api/inse-service/institutions
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
/**
|
||||||
|
* Innovation Search Engine API
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||||
|
* https://openapi-generator.tech
|
||||||
|
* Do not edit the class manually.
|
||||||
|
*/
|
||||||
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
// @ts-ignore
|
||||||
|
import { KeywordsRequest } from '../model/keywordsRequest';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
|
import { Configuration } from '../configuration';
|
||||||
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class KeywordsService extends BaseService {
|
||||||
|
|
||||||
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
|
super(basePath, configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extracts keywords from text.
|
||||||
|
* @endpoint post /api/inse-service/keywords/extract
|
||||||
|
* @param keywordsRequest
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ExtractedKeywordsResponse>;
|
||||||
|
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ExtractedKeywordsResponse>>;
|
||||||
|
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ExtractedKeywordsResponse>>;
|
||||||
|
public extractKeywords(keywordsRequest: KeywordsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (keywordsRequest === null || keywordsRequest === undefined) {
|
||||||
|
throw new Error('Required parameter keywordsRequest was null or undefined when calling extractKeywords.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/keywords/extract`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<ExtractedKeywordsResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: keywordsRequest,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -47,13 +47,14 @@ export class OrganizationService extends BaseService {
|
|||||||
* Create Organization
|
* Create Organization
|
||||||
* @endpoint post /api/organizations
|
* @endpoint post /api/organizations
|
||||||
* @param createOrganizationRequest
|
* @param createOrganizationRequest
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
|
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
|
||||||
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
|
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
|
||||||
}
|
}
|
||||||
@@ -115,13 +116,14 @@ export class OrganizationService extends BaseService {
|
|||||||
* Delete Organization
|
* Delete Organization
|
||||||
* @endpoint delete /api/organizations/{organization_id}
|
* @endpoint delete /api/organizations/{organization_id}
|
||||||
* @param organizationId
|
* @param organizationId
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public deleteOrganisation(organizationId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||||
public deleteOrganisation(organizationId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||||
public deleteOrganisation(organizationId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||||
public deleteOrganisation(organizationId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (organizationId === null || organizationId === undefined) {
|
if (organizationId === null || organizationId === undefined) {
|
||||||
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
|
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
|
||||||
}
|
}
|
||||||
@@ -175,13 +177,14 @@ export class OrganizationService extends BaseService {
|
|||||||
* @param page
|
* @param page
|
||||||
* @param pageSize
|
* @param pageSize
|
||||||
* @param offset
|
* @param offset
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>;
|
||||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
|
||||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
|
||||||
public getOrganisations(page?: number, pageSize?: number, offset?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -240,13 +243,14 @@ export class OrganizationService extends BaseService {
|
|||||||
* @endpoint put /api/organizations/{organization_id}
|
* @endpoint put /api/organizations/{organization_id}
|
||||||
* @param organizationId
|
* @param organizationId
|
||||||
* @param updateOrganizationRequest
|
* @param updateOrganizationRequest
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
|
||||||
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (organizationId === null || organizationId === undefined) {
|
if (organizationId === null || organizationId === undefined) {
|
||||||
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,9 +21,13 @@ import { AllPatentsResponse } from '../model/allPatentsResponse';
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { OrgPatentsResponse } from '../model/orgPatentsResponse';
|
||||||
|
// @ts-ignore
|
||||||
import { PatentEntry } from '../model/patentEntry';
|
import { PatentEntry } from '../model/patentEntry';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
@@ -113,19 +117,90 @@ export class PatentsService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get pre-indexed org patents for an institution.
|
||||||
|
* @endpoint get /api/inse-service/institutions/{id}/org-patents
|
||||||
|
* @param id
|
||||||
|
* @param matchType Filter patents by match type.
|
||||||
|
* @param page
|
||||||
|
* @param size
|
||||||
|
* @param source
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrgPatentsResponse>;
|
||||||
|
public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrgPatentsResponse>>;
|
||||||
|
public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrgPatentsResponse>>;
|
||||||
|
public getOrgPatentsByInstitution(id: string, matchType?: 'institution' | 'name' | 'both' | 'all', page?: number, size?: number, source?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (id === null || id === undefined) {
|
||||||
|
throw new Error('Required parameter id was null or undefined when calling getOrgPatentsByInstitution.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>matchType, 'match_type');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>page, 'page');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>size, 'size');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>source, 'source');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/org-patents`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<OrgPatentsResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns one publication by OpenAlex ID or DOI.
|
* Returns one publication by OpenAlex ID or DOI.
|
||||||
* @endpoint get /api/inse-service/patents/{identifier}
|
* @endpoint get /api/inse-service/patents/{identifier}
|
||||||
* @param identifier
|
* @param identifier
|
||||||
* @param prefix Application Prefix (EP or US)
|
* @param prefix Application Prefix (EP or US)
|
||||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||||
|
* @param fillingDate Filling date in YYYY-MM-DD format
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
|
||||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
|
||||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
|
||||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, fillingDate?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (identifier === null || identifier === undefined) {
|
if (identifier === null || identifier === undefined) {
|
||||||
throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
|
throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
|
||||||
}
|
}
|
||||||
@@ -135,6 +210,8 @@ export class PatentsService extends BaseService {
|
|||||||
<any>prefix, 'prefix');
|
<any>prefix, 'prefix');
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
<any>title, 'title');
|
<any>title, 'title');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>fillingDate, 'filling_date');
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -232,4 +309,59 @@ export class PatentsService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get patents matched to an institution by assignee name.
|
||||||
|
* @endpoint get /api/inse-service/institutions/{id}/patents
|
||||||
|
* @param id
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getPatentsByInstitution(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByInstitutionResponse>;
|
||||||
|
public getPatentsByInstitution(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByInstitutionResponse>>;
|
||||||
|
public getPatentsByInstitution(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByInstitutionResponse>>;
|
||||||
|
public getPatentsByInstitution(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (id === null || id === undefined) {
|
||||||
|
throw new Error('Required parameter id was null or undefined when calling getPatentsByInstitution.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<PatentsByInstitutionResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,10 @@ import { AutocompleteResponse } from '../model/autocompleteResponse';
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { KeywordsTopicsRequest } from '../model/keywordsTopicsRequest';
|
||||||
|
// @ts-ignore
|
||||||
|
import { KeywordsTopicsResponse } from '../model/keywordsTopicsResponse';
|
||||||
|
// @ts-ignore
|
||||||
import { TopicsListResponse } from '../model/topicsListResponse';
|
import { TopicsListResponse } from '../model/topicsListResponse';
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -433,4 +437,75 @@ export class TopicsService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch semantic / vector search for multiple keywords.
|
||||||
|
* @endpoint post /api/topics/vector-search/batch
|
||||||
|
* @param keywordsTopicsRequest
|
||||||
|
* @param searchType Search approach: \'hybrid\' or \'semantic\'.
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<KeywordsTopicsResponse>;
|
||||||
|
public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<KeywordsTopicsResponse>>;
|
||||||
|
public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<KeywordsTopicsResponse>>;
|
||||||
|
public vectorSearchTopicsBatch(keywordsTopicsRequest: KeywordsTopicsRequest, searchType?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (keywordsTopicsRequest === null || keywordsTopicsRequest === undefined) {
|
||||||
|
throw new Error('Required parameter keywordsTopicsRequest was null or undefined when calling vectorSearchTopicsBatch.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>searchType, 'searchType');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
// to determine the Content-Type header
|
||||||
|
const consumes: string[] = [
|
||||||
|
'application/json'
|
||||||
|
];
|
||||||
|
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||||
|
if (httpContentTypeSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/topics/vector-search/batch`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<KeywordsTopicsResponse>('post', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
body: keywordsTopicsRequest,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,323 @@
|
|||||||
|
/**
|
||||||
|
* Innovation Search Engine API
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||||
|
* https://openapi-generator.tech
|
||||||
|
* Do not edit the class manually.
|
||||||
|
*/
|
||||||
|
/* tslint:disable:no-unused-variable member-ordering */
|
||||||
|
|
||||||
|
import { Inject, Injectable, Optional } from '@angular/core';
|
||||||
|
import { HttpClient, HttpHeaders, HttpParams,
|
||||||
|
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||||
|
} from '@angular/common/http';
|
||||||
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AutocompleteLocationItem } from '../model/autocompleteLocationItem';
|
||||||
|
// @ts-ignore
|
||||||
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
|
// @ts-ignore
|
||||||
|
import { RankingResponse } from '../model/rankingResponse';
|
||||||
|
// @ts-ignore
|
||||||
|
import { TopInstitutionItem } from '../model/topInstitutionItem';
|
||||||
|
// @ts-ignore
|
||||||
|
import { TrendResponse } from '../model/trendResponse';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||||
|
import { Configuration } from '../configuration';
|
||||||
|
import { BaseService } from '../api.base.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class UniversityRankingsService extends BaseService {
|
||||||
|
|
||||||
|
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||||
|
super(basePath, configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns country and continent options for autocomplete inputs.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/autocomplete-locations
|
||||||
|
* @param query Query text to search for countries/continents
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AutocompleteLocationItem>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AutocompleteLocationItem>>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AutocompleteLocationItem>>>;
|
||||||
|
public getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet(query: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (query === null || query === undefined) {
|
||||||
|
throw new Error('Required parameter query was null or undefined when calling getAutocompleteLocationsApiInseServiceUniversityRankingsAutocompleteLocationsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>query, 'query');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/autocomplete-locations`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<Array<AutocompleteLocationItem>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns data for the University Ranking Dashboard.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings
|
||||||
|
* @param topic Research topic display name or OpenAlex ID (e.g., \'Artificial Intelligence\')
|
||||||
|
* @param metric Metric to rank by
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
|
||||||
|
public getRankingsApiInseServiceUniversityRankingsGet(topic: string, metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topic === null || topic === undefined) {
|
||||||
|
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>topic, 'topic');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>metric, 'metric');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns top institutions filtered by country/region and sorted by topic-level publications count.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/top-institutions
|
||||||
|
* @param topic Research topic
|
||||||
|
* @param region Region identifier (e.g. EU)
|
||||||
|
* @param country Country code (e.g. DE)
|
||||||
|
* @param limit Max suggestions to return
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<TopInstitutionItem>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<TopInstitutionItem>>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<TopInstitutionItem>>>;
|
||||||
|
public getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet(topic: string, region?: string, country?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topic === null || topic === undefined) {
|
||||||
|
throw new Error('Required parameter topic was null or undefined when calling getTopInstitutionsApiInseServiceUniversityRankingsTopInstitutionsGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>topic, 'topic');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>region, 'region');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>country, 'country');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>limit, 'limit');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/top-institutions`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<Array<TopInstitutionItem>>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns timeseries publication data for compared institutions, countries and regions.
|
||||||
|
* @endpoint get /api/inse-service/university-rankings/trend
|
||||||
|
* @param topics List of topics to analyze
|
||||||
|
* @param institutions List of OpenAlex Institution IDs
|
||||||
|
* @param countries List of country codes
|
||||||
|
* @param regions List of region identifiers
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TrendResponse>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TrendResponse>>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TrendResponse>>;
|
||||||
|
public getTrendApiInseServiceUniversityRankingsTrendGet(topics: Array<string>, institutions?: Array<string>, countries?: Array<string>, regions?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (topics === null || topics === undefined) {
|
||||||
|
throw new Error('Required parameter topics was null or undefined when calling getTrendApiInseServiceUniversityRankingsTrendGet.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
if (topics) {
|
||||||
|
topics.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'topics');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (institutions) {
|
||||||
|
institutions.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'institutions');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (countries) {
|
||||||
|
countries.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'countries');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (regions) {
|
||||||
|
regions.forEach((element) => {
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>element, 'regions');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/inse-service/university-rankings/trend`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<TrendResponse>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -16,9 +16,13 @@ import { HttpClient, HttpHeaders, HttpParams,
|
|||||||
import { CustomHttpParameterCodec } from '../encoder';
|
import { CustomHttpParameterCodec } from '../encoder';
|
||||||
import { Observable } from 'rxjs';
|
import { Observable } from 'rxjs';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { AuthorWorkPurposes } from '../model/authorWorkPurposes';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
|
import { SpecificWorkPurpose } from '../model/specificWorkPurpose';
|
||||||
|
// @ts-ignore
|
||||||
import { TopicCount } from '../model/topicCount';
|
import { TopicCount } from '../model/topicCount';
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
import { TopicsByTime } from '../model/topicsByTime';
|
import { TopicsByTime } from '../model/topicsByTime';
|
||||||
@@ -100,6 +104,61 @@ export class WorksService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the purposes of an author based on their ID.
|
||||||
|
* @endpoint get /api/purpose/{raw_oa_author_id}/purposes
|
||||||
|
* @param rawOaAuthorId The raw OpenAlex author id.
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorWorkPurposes>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorWorkPurposes>>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorWorkPurposes>>;
|
||||||
|
public getAuthorWorkPurposes(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||||
|
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPurposes.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/purpose/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/purposes`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<AuthorWorkPurposes>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a page of works for an author.
|
* Returns a page of works for an author.
|
||||||
* @endpoint get /api/works/{author_id}
|
* @endpoint get /api/works/{author_id}
|
||||||
@@ -111,13 +170,14 @@ export class WorksService extends BaseService {
|
|||||||
* @param language Filter by language code. Can be repeated.
|
* @param language Filter by language code. Can be repeated.
|
||||||
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
|
* @param institutionId Filter by OpenAlex institution id. Can be repeated.
|
||||||
* @param topicId Filter by OpenAlex topic id. Can be repeated.
|
* @param topicId Filter by OpenAlex topic id. Can be repeated.
|
||||||
|
* @param sort Sort order: by publication year or by citation count.
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
* @param reportProgress flag to report request and response progress.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPage>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPage>>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPage>>;
|
||||||
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getAuthorWorks(authorId: string, page?: number, size?: number, publicationYear?: Array<number>, type?: Array<string>, language?: Array<string>, institutionId?: Array<string>, topicId?: Array<string>, sort?: 'year' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
if (authorId === null || authorId === undefined) {
|
if (authorId === null || authorId === undefined) {
|
||||||
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
|
throw new Error('Required parameter authorId was null or undefined when calling getAuthorWorks.');
|
||||||
}
|
}
|
||||||
@@ -157,6 +217,8 @@ export class WorksService extends BaseService {
|
|||||||
<any>element, 'topic_id');
|
<any>element, 'topic_id');
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>sort, 'sort');
|
||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
@@ -382,4 +444,59 @@ export class WorksService extends BaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the purpose of a work based on its ID.
|
||||||
|
* @endpoint get /api/purpose/{raw_oa_work_id}/purpose
|
||||||
|
* @param rawOaWorkId The raw OpenAlex work id.
|
||||||
|
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||||
|
* @param reportProgress flag to report request and response progress.
|
||||||
|
*/
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<SpecificWorkPurpose>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<SpecificWorkPurpose>>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<SpecificWorkPurpose>>;
|
||||||
|
public getWorkPurpose(rawOaWorkId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
if (rawOaWorkId === null || rawOaWorkId === undefined) {
|
||||||
|
throw new Error('Required parameter rawOaWorkId was null or undefined when calling getWorkPurpose.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
|
'application/json'
|
||||||
|
]);
|
||||||
|
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||||
|
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||||
|
|
||||||
|
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||||
|
|
||||||
|
|
||||||
|
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||||
|
if (localVarHttpHeaderAcceptSelected) {
|
||||||
|
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||||
|
responseType_ = 'text';
|
||||||
|
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||||
|
responseType_ = 'json';
|
||||||
|
} else {
|
||||||
|
responseType_ = 'blob';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let localVarPath = `/api/purpose/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/purpose`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<SpecificWorkPurpose>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
import { RefreshToken } from './refreshToken';
|
|
||||||
import { AccessToken } from './accessToken';
|
import { AccessToken } from './accessToken';
|
||||||
|
|
||||||
|
|
||||||
@@ -16,9 +15,5 @@ export interface AccessResponse {
|
|||||||
* The access token issued upon successful authentication.
|
* The access token issued upon successful authentication.
|
||||||
*/
|
*/
|
||||||
access_token: AccessToken;
|
access_token: AccessToken;
|
||||||
/**
|
|
||||||
* The refresh token issued alongside the access token for obtaining new access tokens.
|
|
||||||
*/
|
|
||||||
refresh_token: RefreshToken;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user