diff --git a/llm_evaluations/news_ident_person/sync/elastic/client.py b/llm_evaluations/news_ident_person/sync/elastic/client.py
index 20f59651..aaf72bf4 100644
--- a/llm_evaluations/news_ident_person/sync/elastic/client.py
+++ b/llm_evaluations/news_ident_person/sync/elastic/client.py
@@ -38,6 +38,7 @@ def add_entry(index: str, entry: dict):
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
+ "keywords": entry.get("keywords", []),
}
response_data = _send_es_request("POST", endpoint, payload=document_body)
@@ -47,6 +48,13 @@ def add_entry(index: str, entry: dict):
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:
encoded_document_id = quote(document_id, safe="")
@@ -103,4 +111,18 @@ def delete_all_entries(index: str):
"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)
\ No newline at end of file
diff --git a/llm_evaluations/news_ident_person/sync/llm/client.py b/llm_evaluations/news_ident_person/sync/llm/client.py
index 429bf658..ea4a4453 100644
--- a/llm_evaluations/news_ident_person/sync/llm/client.py
+++ b/llm_evaluations/news_ident_person/sync/llm/client.py
@@ -23,6 +23,17 @@ SYSTEM_PROMPT_NAMES = ("""
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(
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
@@ -62,3 +73,14 @@ def extract_names(text: str) -> list[str]:
return data.get("person", [])
except json.JSONDecodeError:
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 []
diff --git a/llm_evaluations/news_ident_person/sync/sync.py b/llm_evaluations/news_ident_person/sync/sync.py
index b9ff298c..17a8ded5 100644
--- a/llm_evaluations/news_ident_person/sync/sync.py
+++ b/llm_evaluations/news_ident_person/sync/sync.py
@@ -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"]
is_news_relevant = llm_client.is_news_relevant(news_text)
authors = llm_client.extract_names(news_text)
+ keywords = llm_client.extract_keywords(news_text)
new_entry = {
"news_id": news_id,
"relevant": is_news_relevant,
"authors": authors,
+ "keywords": keywords,
}
es_client.add_entry("aktuell_postproc", new_entry)
return True
@@ -32,6 +34,25 @@ def sync_single_news(news_id, max_retries=3):
print(f"Error: {news_id} - {error}")
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():
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'.",
)
+ 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(
"--stats",
action="store_true",
@@ -60,11 +93,22 @@ def main():
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()
if args.delete_all:
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:
start_time = time.time()
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
@@ -96,23 +140,58 @@ def main():
end_time = time.time()
print(f"Sync DONE: {succeeded} entries synced.")
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:
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
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)
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
irrelevant_count = total_entries - relevant_count
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_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"Relevant entries: {relevant_count}")
print(f"Irrelevant entries: {irrelevant_count}")
print(f"Entries with extracted names: {news_with_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__":
main()
\ No newline at end of file
diff --git a/llm_evaluations/news_ident_person/viewer.html b/llm_evaluations/news_ident_person/viewer.html
index 6d534848..cb8d4baf 100644
--- a/llm_evaluations/news_ident_person/viewer.html
+++ b/llm_evaluations/news_ident_person/viewer.html
@@ -32,14 +32,37 @@
#persons {
color: #333;
}
- #checklist {
+ #checklist,
+ #keyword-checklist {
display: inline-block;
text-align: left;
margin-top: 8px;
}
- #checklist div {
+ #checklist div,
+ #keyword-checklist div {
margin: 2px 0;
}
+ #keywords-heading {
+ margin-top: 14px;
+ font-weight: bold;
+ color: #333;
+ }
+ #keyword-chips {
+ margin: 6px 0;
+ }
+ .kw-chip {
+ display: inline-block;
+ background: #e3ecff;
+ color: #1a3a8f;
+ border-radius: 12px;
+ padding: 3px 10px;
+ margin: 2px;
+ font-size: 0.9em;
+ }
+ .kw-empty {
+ color: #b00;
+ font-style: italic;
+ }
#content {
width: 70%;
margin: 0 auto;
@@ -72,6 +95,9 @@
+ Vorhergesagte Keywords:
+
+
@@ -85,12 +111,15 @@
const NEWS = [
{
_id: '01102012_CarmenTomlik_PopstarsmitLauteundLeier_archiv',
- llm_label: 1,
- llm_persons: [
- 'Andrea Sieber',
- 'Oswald von Wolkenstein',
- 'Walther von der Vogelweide',
- 'Holger Schäfer',
+ llm_label: 0,
+ llm_persons: [],
+ pred_keywords: [
+ 'Mittelalterliche Lyrik',
+ 'Deutschunterricht',
+ 'Didaktische Ansätze',
+ 'Verbindung zu Popsongs',
+ 'Minnesänger',
+ 'Nachwuchsforschung',
],
full_content:
'[01.10.2012] Auch das Mittelalter hatte seine Idole: Ihre Auftritte waren umjubelt und die Songs von Walther von der Vogelweide & Co klangen nach Popmusik. Kurze Reime, virtuose Rhythmen und die brisanten Themen passen noch immer auf die Bühne und sprechen vor allem Jugendliche an. Diese Parallelen will die Nachwuchsforschergruppe „mittelneu“ der UDE nutzen, um den Schülern von heute die Dichtkunst von gestern näherzubringen. Unter dem Motto „Oswald und Walther reloaded“ kommen am 6. Oktober Lehrer und Wissenschaftler auf der Zeche Zollverein zusammen, um eine Brücke zwischen mittelalterlicher und moderner Lyrik im Deutschunterricht zu schlagen.\n\nEs wird immer noch auswendig gelernt – doch obwohl lyrische Texte fest im Lehrplan verankert sind, finden Gedichte und Lieder des Mittelalters kaum noch Raum. Das muss sich ändern, fordert Dr. Andrea Sieber. An Beispielen der Minnesänger Oswald von Wolkenstein und Walther von der Vogelweide sollen deshalb Gemeinsamkeiten mit modernen Popsongs aufgezeigt werden. Und das sind nicht wenige: „In den Texten geht es um Liebe, Enttäuschung und Trennungsschmerz, aber auch um Erotik“, sagt Sieber.\n\nIn Vorträgen und Workshops werden die didaktischen Möglichkeiten ausgelotet und Methoden diskutiert, wie sie am besten umgesetzt werden können. Daraus sollen konkrete Ideen für den Unterricht entstehen. Passend zum Thema tritt der bekannte Minnesänger Holger Schäfer auf und zeigt mit seiner Live-Performance, wie eine praxisnahe Vermittlung aussehen kann.\n\nDas Kolloquium wird vom NRW-Wissenschaftsministerium gefördert und findet am 6. Oktober von 10 bis 18 Uhr im Kokskohlenbunker A16 auf dem Gelände der Zeche Zollverein statt.\n\nWeitere Informationen und Anmeldung:\nhttp://www.uni-due.de/mittelneu\nDr. Andrea Sieber, Tel. 0201/183-7215, andrea.sieber@uni-due.de',
@@ -99,47 +128,70 @@
_id: '02042014__berzeugendeVorteile_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Elektrotechnik und Informationstechnik',
+ 'Online-Master',
+ 'Fernstudium',
+ 'Berufsbegleitendes Studium',
+ 'Automatisierungstechnik',
+ 'Intelligente Energienetze',
+ ],
full_content:
'[02.04.2014] Der Bedarf für dieses berufsbegleitende Angebot ist da – das hat jetzt die Akkreditierungsagentur bestätigt. Der neue Master-Fernstudiengang Elektrotechnik und Informationstechnik der Universität Duisburg-Essen (UDE) erfüllt alle Qualitätsstandards. Noch kann man sich für das kommende Sommersemester kurzfristig einschreiben.\n\nMit dem Online-Master EIT können sich Ingenieure in der Elektrotechnik und Informationstechnik weiterentwickeln. Sie haben vier Vertiefungsrichtungen zur Auswahl: Automatisierungstechnik, Digitale Kommunikationssysteme, Hochfrequenzsysteme und Intelligente Energienetze.\n\nEine Umfrage unter Personalern und Entscheidern großer Ingenieursbetriebe untermauert, dass sich eine solche Qualifizierung lohnt: Das Aufbaustudium vermittelt den aktuellen Stand von Forschung und Entwicklung; diese Expertise bringen die Studierenden ins Unternehmen ein, was sich für beide Seiten lohnt. Die flexible Zeiteinteilung, den fairen Preis und vor allem den praktischen Bezug sehen sie als große Vorteile für eigene und potenzielle Mitarbeiter.\n\nInsbesondere in der Automatisierungstechnik und den Energienetzen erwarten die meisten Unternehmen in den folgenden zwei Jahren steigende fachliche Ansprüche und suchen entsprechend qualifiziertes Personal. Unter allen Befragten kam eine Weiterbildung der Mitarbeiter durch ein Fernstudium in Betracht. Sechs Teilzeit-Semester seien nicht zu lang. Die Mehrheit würde Ingenieure, die berufsbegleitend studieren, in Teilzeit beschäftigen.\n\nZum Studienstart werden keine Gebühren für die einzelnen Kurse erhoben, lediglich eine Anmeldungspauschale von einem Euro.\n\nWeitere Informationen: http://www.online-master-eit.de\nProf. Dr. Daniel Erni, Tel. 0203/379-4212, online-master-eit@uni-due.de\n\n\nRedaktion: Katrin Koster, Tel. 0203/379-1488',
},
{
_id: '02072004_MonikaRgge_ErstesForumzurBaukommunikation_archiv',
- llm_label: 0,
- llm_persons: [],
+ llm_label: 1,
+ llm_persons: [
+ 'Dirk Baecker',
+ 'Birger Priddat',
+ 'Manfred Schedlowski',
+ 'Bernd Kniess',
+ 'Gernot Böhme',
+ 'Oliver Scheytt',
+ 'Harald Gatermann',
+ 'Peter Zec',
+ 'Heinrich Kraft',
+ 'Ulrich Hatzfeld',
+ 'Olaf Kaltenborn',
+ ],
+ pred_keywords: [
+ 'Baukommunikation',
+ 'Gebaute Umwelt',
+ 'Atmosphäre',
+ 'Städtebau',
+ 'Architektur',
+ 'Interdisziplinarität',
+ ],
full_content:
'[02.07.2004] Wer baut, greift in das Leben der Menschen und der Gesellschaft ein. Die Kunst der Architekten und Ingenieure genügt deshalb nicht; Vertreter vieler Disziplinen müssen gefragt werden. Davon gehen die Wissenschaftler im Essener Uni-Fachbereich Bauwesen aus und regten deshalb die Gründung des „Essener Forum Baukommunikation“ an. Am Donnerstag, 15. Juli, findet ab 9.30 Uhr das erste Forum in der Galerie „stadt.bau.raum“ im Haus Boniverstraße 30 in Gelsenkirchen statt.\n\n„Atmosphäre – Kommuniktionsmedium der gebauten Umwelt“ heißt das Thema der Tagung. Wodurch wirken eine Stadt, ein Gebäude, eine Landschaft auf den Menschen. Kann man Atmosphäre planen, gestalten, manipulieren oder verändern? Was sind die Folgen der Planungen von Architekten, Bauingenieure, Städte- und Verkehrsplanern für Menschen, Gesellschaft und Umwelt? Das sind die Fragen, die zur Diskussion stehen sollen. Kurzreferate dazu halten der Soziologe Dirk Baecker von der Universität Witten-Herdecke, der Ökonom und Philosoph Birger Priddat von der Zeppelin-University in Friedrichshafen, der Medizin-Psychologe Manfred Schedlowski von der ETH Zürich, der Architekt und Stadtplaner Bernd Kniess aus Köln und der Philosoph Gernot Böhme von der Universität Darmstadt. Er hat sich mit dem Tagungsthema in seinem Werk eingehend beschäftigt, zuletzt mit der Frage der gezielten Schaffung von Atmosphäre durch die Architektur und den Städtebau der Nationalsozialisten.\n\nAbschließend diskutieren unter Leitung des Essener Kulturdezernenten Dr. Oliver Scheytt Architekturprofessor Harald Gatermann von der Fachhochschule Bochum, Peter Zec vom Design Zentrum Nordrhein-Westfalen, Dr. Heinrich Kraft von der ECE Projektmanagement GmbH & Co, KG, Hamburg, Dr. Ulrich Hatzfeld vom Landes-Bauministerium und Dr. Olaf Kaltenborn von der Universität Witten-Herdecke.\n\nSoziologen, Psychologen, Kriminologen, Philosophen und Ökonomen – alle haben Erkenntnisse über die Auswirkung der Tätigkeit des Bauens von Städten und Gebäuden auf den Menschen und die Gesellschaft. Doch einen Dialog darüber mit den Baufachleuten gibt es bisher nicht. Das wollen die Essener Ingenieure des Bauwesens mit der Gründung des „Essener Forum Baukommunikation“ ändern. Künftig soll jährlich ein Forum mit Wissenschaftlern der verschiedenen Fachrichtungen zu einem bestimmten Thema stattfinden. Zwischen den einzelnen Foren werden sich Studenten verschiedener Fachbereiche und Universitäten in Seminaren und Projektarbeiten mit diesen oder auch anderen aktuellen Themen befassen. Ihre Arbeitsergebnisse werden zur Information und Diskussion im Internet veröffentlicht. Ziel ist es, den künftigen Bauingenieuren zu verdeutlichen, welche Dimensionen sie in ihrem künftigen Beruf über Technik und Gestaltung hinaus zu bedenken haben. Auf der anderen Seite will das Essener Forum Baukommunikation aber auch die Erkenntnisse anderer Wissenschaften für die Praxis des Städtebaus und der Architektur nutzbar machen.\n\nEingeladen zum ersten Forum sind neben den Vertretern der am Forum beteiligten Disziplinen auch alle diejenigen, die sich für das Thema interessieren. Eine Teilnehmergebühr wird nicht erhoben. Anmeldungen sind aber notwendig bei Reinhard Jammers per Fax unter (0 21 91) 69 09 68 oder per E-Mail: reinhard@jammers.de',
},
{
_id: '02112007_BeateHKostka_Innovationalleinreichtnicht_archiv',
- llm_label: 0,
- llm_persons: [],
+ llm_label: 1,
+ llm_persons: ['Volker Breithecker'],
+ pred_keywords: [
+ 'Existenzgründung',
+ 'Small Business Management',
+ 'Unternehmertum',
+ 'Businessplanwettbewerb',
+ 'Betriebliches Rechnungswesen',
+ 'Selbstständigkeit',
+ ],
full_content:
'[02.11.2007] Praxisorientiertes Wissen rund um die Unternehmensgründung vermittelt der neue Durchgang des zweisemestrigen Existenzgründungslehrgangs „small business management“ an der Universität Duisburg-Essen, der am 9. November beginnt.\n\nsbm ist ein studien- oder berufsbegleitendes Programm für Interessierte aller Alters- und Berufsgruppen. Bei der Auftaktveranstaltung am 9.11. (Campus Duisburg, Gebäude MC, Raum 122, Mülheimer Str./Ecke Lotharstraße) informiert Projektleiter Prof. Dr. Volker Breithecker ab 15 Uhr über die Lehrgangsinhalte und ehemalige sbm-Teilnehmer berichten von ihren Erfahrungen und Erfolgen.\n\nVorgestellt wird auch der Businessplanwettbewerb „StartUp ? Duisburg“ und regionale Institutionen informieren über Aktuelles rund um das Thema Existenzgründung. Im Anschluss an die Info-Veranstaltung haben Interessierte die Möglichkeit, sich für den Lehrgang, der am 14. November startet, anzumelden.\n\nSbm ist ein Erfolgsmodell: ab November 2007 läuft es zum neunten Mal an. Das Besondere daran ist nicht nur die Kombination verschiedener Vortragsreihen zum Unternehmertum, Betriebliches Rechnungswesen und Unternehmensnachfolge, sondern auch das hohe Niveau, auf dem die Veranstaltungen durchgeführt werden. Die Teilnehmer werden angeregt, sich mit Fragen des Unternehmertums und der beruflichen Selbstständigkeit zu beschäftigen und persönliche Vor- und Nachteile abzuwägen.\n\nDer Projektleiter, Prof. Dr. Volker Breithecker, der an der UDE den Lehrstuhl für Betriebswirtschaftliche Steuerlehre leitet, sieht darin die Hauptaufgabe von sbm: „Die eigene Unternehmensidee mit einem Businessplan zu präsentieren und von erfahrenen Fachkräften und Coaches analysieren zu lassen ist oft von der Erkenntnis begleitet, dass Innovation allein für unternehmerischen Erfolg nicht ausreichend ist. Die Teilnehmer, die ihre Unternehmensidee in einem Startup-Unternehmen umsetzen wollen, erhalten umfangreiche Hilfe und auch weiterführende Unterstützung.“\n\nAbsolventen des Lehrgangs werden außerdem qualifiziert, am Existenzgründerwettbewerb StartUp Duisburg teilzunehmen. Unter der Schirmherrschaft der Stadt Duisburg, der Sparkasse Duisburg, des Immobilien-Management Duisburg, der Gesellschaft für Wirtschaftsförderung Duisburg mbH und der Universität Duisburg-Essen wird damit der Technologienachwuchs am Standort gefördert.',
},
{
_id: '02122015_AlexandraNießen_WasistanderUnilos_archiv',
- llm_label: 1,
- llm_persons: [
- 'Ingrid Schöll',
- 'Matthias Gunzer',
- 'André Niemann',
- 'Ramona Gläser',
- 'Michael Brauer',
- 'Astrid Windus',
- 'Olaf Hartung',
- 'Eberhard Passarge',
- 'James Franco',
- 'Seth Rogen',
- 'Kim Jong-un',
- 'Norbert Linke',
- 'Jürgen W. Einax',
- 'Janina Söhn',
- 'Joachim Renn',
- 'Thomas Uhlendahl',
- 'Sonja Heldt',
- 'Martina Herrmann',
- 'Johannes Pfeiffer',
- 'Joachim Dorfmüller',
+ llm_label: 0,
+ llm_persons: [],
+ pred_keywords: [
+ 'Lebenslanges Lernen',
+ 'Nachhaltigkeit',
+ 'Geschichte',
+ 'Medizin',
+ 'Chemie',
+ 'Soziologie',
],
full_content:
'[02.12.2015] Montag, 7. Dezember, 10 bis 12 Uhr\nWieso Führen und Leiten eine Lern-Herausforderung im Lebenslauf darstellt, erläutert Dr. Ingrid Schöll, Direktorin der VHS Bonn, in der Veranstaltung „Bildung in der Lebenszeit“. Campus Essen, S03 V00 E33, Universitätsstraße 3.\n\nMontag, 7. Dezember, 14 bis 16 Uhr\nImmunität ist nicht nur etwas für Politiker, weiß der Mediziner Prof. Dr. Matthias Gunzer. Was das genau bedeutet, verrät er im Verein Lebenslanges Lernen. Campus Essen, R12 S00 H12, Glaspavillon, Universitätsstraße 12.\n\nMontag, 7. Dezember, 16.15 Uhr\nDer Nachhaltigkeitsbeauftragte der UDE, Prof. Dr. André Niemann, hält in der Ringvorlesung „Urban Sustainability“ einen Vortrag über „Sustainable Higher Education Units – State of the Art, Strategies and Pathways“. Campus Essen, R11 T00 D05, Universitätsstraße 12.\n\nMontag, 7. Dezember, 18 bis 20 Uhr\nWelche Bedeutung das Reichsbanner Schwarz-Rot-Gold nach dem Ersten Weltkrieg hatte, als Deutschland und Frankreich miteinander kommunizierten, berichtet Ramona Gläser. Sie spricht im Kolloquium zur Neueren und Neuesten Geschichte/Sozial- und Wirtschaftsgeschichte. Campus Essen, R12 V05 D81, Universitätsstraße 12.\n\nDienstag, 8. Dezember, 16 bis 18 Uhr\nWie Karl V., König von Frankreich, im 14. Jahrhundert seine Politik als Handeln der Verwaltung gestaltete, erfährt man im Mediävistischen Kolloquium von Dr. Michael Brauer (Salzburg). Campus Essen, R12 S05 H81, Universitätsstraße 12.\n\nDienstag, 8. Dezember, 18 bis 20 Uhr\nÜber die religiöse Kommunikation im bolivianischen Carabucos im 17. Jahrhundert informiert Dr. Astrid Windus (Hamburg). Sie kommt ins Kolloquium „Forschungsprobleme der außereuropäischen und der frühneuzeitlichen Geschichte“. Campus Essen, R12 V05 D81, Universitätsstraße 12.\n\nDienstag, 8. Dezember, 18 bis 20 Uhr\nPrivatdozent Dr. Olaf Hartung (Gießen) denkt darüber nach, wie Forschung zu einem schreiborientierten Geschichtsunterricht aussieht. Er ist Gast im Geschichtsdidaktischen Forschungskolloquium. Campus Essen, R12 S05 H81, Universitätsstraße 12.\n\nDienstag, 8. Dezember, 18.15 bis 19.30 Uhr\nWo Wissenschaftler mit genetischen Erkenntnissen an ihre Grenzen stoßen, zeigt Prof. Dr. Eberhard Passarge im medizinisch-philosophischen Kolloquium. Universitätsklinikum Essen, Institutsgruppe I, Hörsaal 1, Virchowstraße 171.\n\nDienstag, 8. Dezember, 18.30 Uhr\nDer Essener Filmclub zeigt den Film „The Interview“. Er handelt von einem Journalisten (James Franco) und seinem Produzenten (Seth Rogen), die den Diktator Nordkoreas Kim Jong-un im Namen der CIA umbringen sollen. Das ist jedoch schwieriger als gedacht. Campus Essen, S05 T00 B71, Universitätsstraße 5.\n\nMittwoch, 9. Dezember, 14 bis 16 Uhr\nWer noch mehr über die Musik der Strauß-Komponisten des 19. Jahrhunderts erfahren möchte, ist bei Prof. Dr. Norbert Linke in den besten Händen. Campus Duisburg, LC 126, Kammermusiksaal, Lotharstraße 65.\n\nMittwoch, 9. Dezember, 17 Uhr\nWie die Chemometrik als analytisches Werkzeug in der Chemie zum Einsatz kommt, thematisiert Prof. Dr. Jürgen W. Einax (Jena) in der Fresenius Lecture. Campus Essen, S07 S00 D07, Universitätsstraße 7.\n\nMittwoch, 9. Dezember, 18 bis 20 Uhr\nWelche Bedeutung Bildung unter erwachsenen Migranten hat, erläutert Dr. Janina Söhn (SOFI Göttingen). Sie kommt ins Soziologische Kolloquium. Campus Duisburg, LK 061, Lotharstraße 65.\n\nMittwoch, 9. Dezember, 18 bis 20 Uhr\nIn der Ringvorlesung „Wagnisse“ widmet sich Prof. Dr. Joachim Renn (Münster) dem Thema Kontingenzverteilungen. Campus Essen, R12 S00 H12, Glaspavillon, Universitätsstraße 12.\n\nDonnerstag, 10. Dezember, 15 bis 18 Uhr\nWann Mediation und Moderation in Wasserinfrastruktur-Fragen etwas bewirken, weiß Dr. Thomas Uhlendahl (Freiburg). Sonja Heldt zeigt am Beispiel der Emscher- und Lippemündung, wie man sich bei Renaturierungs-Projekten um Akzeptanz bemüht. Beide kommen ins Future Water Kolloquium. Campus Essen, S03 V00 E59, Universitätsstraße 2.\n\nDonnerstag, 10. Dezember, 18 bis 20 Uhr\nMit dem Wert von Vertrauen beschäftigt sich Dr. Martina Herrmann (TU Dortmund) im Philosophischen Kolloquium. Campus Essen, R12 S05 H81, Universitätsstraße 12.\n\nDonnerstag, 10. Dezember, 20 Uhr\nDer Uni-Filmclub zeigt „Die Feuerzangenbowle“. Der Schwarzweiß-Streifen erzählt die Geschichte vom legendären Johannes Pfeiffer (Heinz Rühmann), der als Erwachsener noch einmal die Schulbank drückt. Universitätsklinikum Essen, Audimax, Hufelandstraße 55.\n\nFreitag, 11. Dezember, 19.30 Uhr\nÜber Leben und Werk von George Gershwin informieren die Professoren Dr. Joachim Dorfmüller und Dr. Norbert Linke beim 216. Akademischen Konzert. Campus Duisburg, LC 126, Kammermusiksaal, Lotharstraße 65.',
@@ -148,6 +200,14 @@
_id: '03012017_UlrikeEichweber_ErfreulicheBilanz',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Universitätsallianz Ruhr',
+ 'Ostasienforschung',
+ 'Wissenschaftliche Forschung',
+ 'Ruhr Astroparticle and Plasma Physics Center (RAPP)',
+ 'DFG Sonderforschungsbereiche',
+ 'EU-Förderungen',
+ ],
full_content:
' Einen erfolgreichen Blick zurück ins Jahr 2016 kann die Universitätsallianz (UA) Ruhr tun: Im AREA Ruhr bündelt sie ihre Expertise in der Ostasienforschung, die Profilschwerpunkte konnten sich über Auszeichnungen und EU-Förderungen freuen, am Ruhr Astroparticle and Plasma Physics Center (RAPP) forschen rund 100 Wissenschaftler/innen und die DFG genehmigte zwei neue gemeinsame Sonderforschungsbereiche. Der Jahrsrückblick als PDF:\r\nhttp://www.uamr.de/fileadmin/downloads/Jahresrueckblick_2016.pdf ',
},
@@ -155,13 +215,28 @@
_id: '03062019_UlrikeEichweber_ZumAbschlusseinFest',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Ingenieurwissenschaften',
+ 'Abschlussfeier',
+ 'Absolventen',
+ 'Fakultäts-Sommerfest',
+ 'Campus Duisburg-Essen',
+ ],
full_content:
' Feierlich verabschieden die Ingenieurwissenschaften am 12. Juli ihre Absolvent*innen. Los geht es um 15 Uhr im Hörsaalzentrum LX (Campus Duisburg). Im Anschluss steigt ab 17 Uhr das traditionelle Fakultäts-Sommerfest auf den ZHO-Wiesn. ',
},
{
_id: '05032025_UlrikeEichweber_UNIonTOPInfoveranstaltung',
- llm_label: 1,
- llm_persons: ['Wanja von der Goltz', 'Max Briesemeister'],
+ llm_label: 0,
+ llm_persons: [],
+ pred_keywords: [
+ 'UNI on TOP',
+ 'Kaufmännische Ausbildung',
+ 'Studium parallel',
+ 'Betriebswirtschaftslehre (BWL)',
+ 'Duales Lernen',
+ 'Berufskollegs',
+ ],
full_content:
'Lehre und Studium gleichzeitig – geht das? Ja! Für Azubis in kaufmännischen Berufen ist das Dank des Projekts "UNI on TOP" der Mercator School of Management (MSM) der UDE möglich. Interessierte können sich jetzt darüber informieren: am 19. März bei einer Veranstaltung am Campus Duisburg. Nach dem Abi stellt sich vielen die Frage: Berufsausbildung oder Studium? Wer an "UNI on TOP" teilnimmt, muss sich nicht zwischen beiden Optionen entscheiden. Wenn der Arbeitgeber mitspielt, können die Azubis gleichzeitig im Betrieb, in der Berufsschule und an der Uni lernen. So können sie parallel zu ihrer kaufmännischen Lehre auch einen Bachelorstudiengang in Betriebswirtschaftslehre absolvieren. Rund zehn Berufskollegs in NRW bieten ihre Schüler:innen mittlerweile diese Möglichkeit. Eine Win-Win-Situation für alle Beteiligten sei das, meint MSM-Studiendekan Dr. Wanja von der Goltz: "Die Azubis bekommen die Gelegenheit, in ein Uni-Studium flexibel hineinzuschnuppern, ohne sich wie beim dualen Studium langfristig zu binden. Die Universität erschließt sich einen neuen Pool von Studieninteressierten, die in der Regel mit deutlich größerer Wahrscheinlichkeit erfolgreich studieren werden. Die Berufskollegs können leistungsstarke Schüler:innen gewinnen. Und die Betriebe können um gute Auszubildende werben und beweisen, dass eine kaufmännische Ausbildung nicht unbedingt eine Entscheidung gegen ein Studium ist.“ Interessierte Unternehmen und Azubis können sich nun bei einer Veranstaltung am 19. März ab 15 Uhr im Gebäude LX (Campus Duisburg) näher über das Projekt informieren. Organisiert wird sie von der MSM gemeinsam mit dem Kooperationspartner, der Niederrheinischen IHK. Im Bild: Teilnehmer:innen am Prorgamm "UNI on TOP" im Jahr 2022 vorne. Hinten: Studiendekan Dr. Wanja von der Goltz an der Mercator School of Management (l.) und Dr. Max Briesemeister, Lehrer am KBM und (Mit-)Initiator des Projekts. ',
},
@@ -169,6 +244,14 @@
_id: '05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Tsunami',
+ 'Japan',
+ 'Katastrophe',
+ 'Spendenaktion',
+ 'Fukushima',
+ 'Ostasienwissenschaften',
+ ],
full_content:
'[05.04.2011] Ein großes Erdbeben erschütterte am 11. März den Norden Japans. Der darauf folgende Tsunami tötete Zehntausende von Menschen und raubte Hunderttausenden ihr Heim. Die Folgen der dritten Katastrophe, des Reaktorunglücks von Fukushima, sind noch nicht absehbar. „Japan braucht unser Mitgefühl und unsere Hilfe“, appelliert Helmut Demes, Geschäftsführer des Instituts für Ostasienwissenschaften IN-EAST der Universität Duisburg-Essen (UDE), an alle, die angesichts des großen Leids nicht tatenlos zusehen wollen.\n\nEine Möglichkeit sich einzusetzen ist, sich an der Spendensammelaktion zu beteiligen, zu der das IN-EAST und die japanische Elterninitiative Dendenmushi öffentlich aufrufen. Am kommenden Freitag, 8.4., können Geldgaben von 14 bis 19 Uhr am Forum auf der Königstraße in Duisburg abgegeben werden. Als kleines Dankeschön erhalten die Spender Origami-Kraniche, die Kinder zuvor aus Papier gefaltet haben. Das gesammelte Geld wird dem Roten Kreuz in Japan überwiesen, damit es für die Opfer vor Ort eingesetzt werden kann. Auch Direktspenden sind möglich auf das Spendenkonto 41 41 41, Bank für Sozialwirtschaft, BLZ 370 205 00, Stichwort: Tsunami 2011.\n\nWeitere Informationen: Helmut Demes, Tel. 0203/379-4191, helmut.demes@uni-due.de',
},
@@ -176,6 +259,14 @@
_id: '06052015_KatrinKoster_WasunserenGewssernhilft_archiv',
llm_label: 1,
llm_persons: ['Daniel Hering'],
+ pred_keywords: [
+ 'Aquatische Ökologie',
+ 'Süßwassersysteme',
+ 'Gewässerschutz',
+ 'Biodiversität',
+ 'Wasserwirtschaft',
+ 'Nachhaltiges Management',
+ ],
full_content:
'[06.05.2015] Intensive Nutzung, Düngemittel und die stetig steigenden Temperaturen machen den europäischen Süßwassersystemen zu schaffen. Länderübergreifend untersuchen viele Forschungsprojekte die Auswirkungen auf Flüsse, Seen und Feuchtgebiete, um Sanierungsstrategien zu finden. Damit Wasserwirtschaftler, Politiker, Wissenschaftler und interessierte Laien ihre Daten leichter nutzen können, haben vier europäische Einrichtungen eine Online-Plattform geschaffen, auf der zahlreiche Ergebnisse anschaulich dargestellt werden. Sie enthält beispielsweise eine Datenbank zur Ökologie von 20.000 Süßwasserorganismen. Dafür ist die Aquatische Ökologie der Universität Duisburg-Essen (UDE) mitverantwortlich, ebenso wie für die Konzeption und technische Umsetzung des neuen Angebots.\n\nDie Webseite ist verständlich gestaltet: Sie richtet sich auch an Bürger, die mehr über Wasserwirtschaft, Gewässerschutz und Naturschutz erfahren wollen. So gibt es Karten zur weltweiten Biodiversität der Fische, Insekten und Algen, zu ihrer Verbreitung und zu Belastungsfaktoren. Faszinierende Arten werden in Bild, Text und Video vorgestellt; ein lesenswertes Blog informiert über Themen wie Antibiotika in Gewässern oder Nährstoffbelastungen.\n\nDer Mensch ist von diesen Ökosystemen abhängig, und Umweltveränderungen haben weitreichende Konsequenzen. Prof. Dr. Daniel Hering betont, wie wichtig die globale Veröffentlichung der bisherigen Schritte und Ergebnisse ist: „Nur mit hochwertigen Daten wird es uns gelingen, die komplexen wissenschaftlichen und praktischen Fragen zu lösen. Unsere Plattform hilft dabei, ein erfolgreiches und nachhaltiges Management von Süßwasserökosystemen besser zu planen und umzusetzen.“ Außerdem wollen die vier Einrichtungen aus Deutschland, Österreich und Belgien die Vielzahl an Forschungsprojekten stärker vernetzen.\n\nWeitere Informationen: http://www.freshwaterplatform.eu/\nProf. Dr. Daniel Hering, Tel. 0201/183-3084, daniel.hering@uni-due.de',
},
@@ -183,13 +274,29 @@
_id: '07102019__Stipendium–auchohneEinser-Abi',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Stipendienwesen',
+ 'RuhrFutur',
+ 'Studienförderung',
+ 'Bildungsinitiative',
+ 'Studienhürden',
+ 'Akademische Beratung',
+ ],
full_content:
' Die Bildungsinitiative RuhrFutur und ihre sieben Partnerhochschulen, zu denen auch die UDE zählt, forcieren ihr Engagement für das Stipendienwesen im Revier. Mit dem neuen Projekt Stipendienkultur Ruhr soll langfristig die Quote der Geförderten erhöht werden. Viele Studierende im Ruhrgebiet sind die ersten in ihrer Familie, die eine akademische Ausbildung machen. Für sie stellt die Finanzierung des Studiums eine große Hürde dar. Oft wissen sie nicht, dass sie für eine Förderung bewerben können – auch ohne Einser-Abi. Die neue Website stipendienkultur.de bündelt alle wichtigen Informationen zu Förderwerken, Voraussetzungen, Bewerbungen, Fristen und Worskhops. Auch das Akademische BeratungsZentrum ABZ sorgt mit verschiedenen Veranstaltungen für mehr Durchblick:\r\nhttps://www.uni-due.de/offene-hochschule/stipendienkultur-ruhr\r\nhttps://www.uni-due.de/de/studium/foerderwerke/ ',
},
{
_id: '08072015_KatrinKoster_beralleGrenzenhinweg_archiv',
llm_label: 1,
- llm_persons: ['Volker Buck', 'Andreas Reichert'],
+ llm_persons: ['Volker Buck'],
+ pred_keywords: [
+ 'Technische Physik',
+ 'Internationale Kooperationen',
+ 'Wissenschaftsausbildung',
+ 'Universität Duisburg-Essen',
+ 'Weißrussland',
+ 'Ehrendoktorwürde',
+ ],
full_content:
'[08.07.2015] Er hat schon früh sinnstiftende Netzwerke aufgebaut: Prof. Dr. Volker Buck von der Universität Duisburg-Essen (UDE) ist nun für sein Engagement in Weißrussland ausgezeichnet worden. Der Professor für Technische Physik erhielt von der Francisk Skorina Gomel State University die Ehrendoktorwürde. Mit diesem Titel wurde er für die Ausbildung von Wissenschaftlern und für den Aufbau von internationalen Kooperationen geehrt.\n\nVolker Buck hat bereits in den Neunzigerjahren – also kurz nach der Unabhängigkeit von Weißrussland – einen regen Austausch mit der dortigen Hochschule begonnen. Die Ehrendoktorwürde wurde ihm bei der 85-Jahrfeier der Universität verliehen.\n\nWeitere Informationen:\nDr. Andreas Reichert, Tel. 0203/379-2032, andreas.reichert@uni-due.de',
},
@@ -197,6 +304,14 @@
_id: '08092015__WiefindeichdaspassendeFach_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Studienwahl',
+ 'Studienberatung',
+ 'Probestudium',
+ 'Frühstudium',
+ 'Studienorientierung',
+ 'Fachschaft',
+ ],
full_content:
'[08.09.2015] Was sie studieren sollen, beschäftigt viele Schüler nicht erst zum Abitur. Die Universität Duisburg-Essen (UDE) hilft mit verschiedenen Angeboten, sich richtig zu entscheiden.\n\nWer noch völlig unentschlossen ist, dem rät das Akademische Beratungs-Zentrum ABZ zum Workshop „Deine Studienwahl – schon klar?" An einem Nachmittag gibt es Hilfe zur Selbsthilfe, das Passende für sich zu finden. https://www.uni-due.de/abz/studieninteressierte/schuelerseminare.shtml\n\nWer schon weiß, was er studieren will, dem rät Dr. Verena Wockenfuß vom ABZ seine Vorstellungen zu überprüfen: „Im Schülervorlesungsverzeichnis sind quer durch alle Fächer Vorlesungen, Übungen und Seminare der ersten beiden Semester aufgelistet. Am besten schnuppert man einmalig in eine der Veranstaltungen hinein, lässt sich dann im ABZ beraten und spricht außerdem mit der jeweiligen Fachschaft. Das hilft den meisten sehr viel weiter.“\n\nOrientierung bieten auch das Probestudium (Chemie, Physik, E-Technik, Nano Engineering, Informatik) sowie das Frühstudium. An letzterem beteiligen sich alle Fakultäten. Viele Schüler nutzen es, um Fächer zu testen; sie kommen regelmäßig an die Uni, schreiben Klausuren oder Hausarbeiten und halten Referate. Wer mehr wissen möchte: Am 10. September um 16 Uhr in Essen und am 15. September um 15 Uhr in Duisburg finden Infotreffen statt. https://www.uni-due.de/abz/studieninteressierte/fruehstudium.php\nhttps://www.uni-due.de/abz/studieninteressierte/probestudium.shtml\n\nAuch für besorgte Mütter und Väter hat die Studienberatung wieder ein Ohr. Sie veranstaltet in den kommenden Wochen die beliebte Elternsprechstunde: am 29. September um 16 Uhr im Bildungspunkt in der Essener Innenstadt sowie am 21.Oktober um 14 Uhr im Uni-Office in der Duisburger City. Eine Anmeldung ist nicht erforderlich.\n\n\nWeitere Informationen: http://www.uni-due.de/abz/studieninteressierte.shtml\nDr. Verena Wockenfuß, Tel. 0201/183 4995, verena.wockenfuss@uni-due.de\n\nRedaktion: Ulrike Bohnsack, Tel. 0203/379-2429',
},
@@ -204,16 +319,28 @@
_id: '08102019_UlrikeEichweber_KIinderFinanzwelt',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Digitalisierung',
+ 'Künstliche Intelligenz',
+ 'Bankwesen',
+ 'Versicherungsbranche',
+ 'Finanzdienstleistungen',
+ 'Workshops',
+ ],
full_content:
' Banken und Versicherung müssen sich fit machen für die Digitalisierung. Wie Künstliche Intelligenz sinnvoll eingesetzt werden kann und welche Projekte es dazu schon gibt, darüber informieren Fachleute beim future lab des european center for financial services (ecfs) an der UDE. In vier Workshops, die auch als Vorbereitung des Banken-Symposiums 2020 dienen, können Interessierte aktuelle Fragen mit den Expert*innen diskutieren. Der erste Workshop findet am 14. November ab 18 Uhr am Campus Duisburg (Mercator School of Management) statt.\r\n Das Programm im Überblick und Anmeldung:\r\nhttp://www.ecfs.de/future-lab-2020/ ',
},
{
_id: '09082022_JenniferMeina_ZwischendenZeilen',
- llm_label: 1,
- llm_persons: [
- 'Mariya Shymchyshyn',
- 'Jens Martin Gurr',
- 'Jennifer Meina',
+ llm_label: 0,
+ llm_persons: [],
+ pred_keywords: [
+ 'Literaturtheorie',
+ 'Flucht und Migration',
+ 'Kriegserfahrung',
+ 'Weltliteratur',
+ 'Geokritik',
+ 'Feminismus',
],
full_content:
'Über Sprache und Literatur schreiben, wenn einem die Worte fehlen. So erging es der ukrainischen Anglistin Prof. Dr. Mariya Shymchyshyn durch den Krieg in ihrem Heimatland. Mittlerweile ist sie durch ein Stipendium der VolkswagenStiftung an der UDE, wird hier für mindestens ein Jahr bleiben – und hat ihre Sprache wiedergefunden. Geboren in Ternopil im Westen der Ukraine, erfuhr Shymchyshyn schon als Kind durch die Fluchterfahrungen der Großeltern aus Polen, was Entwurzelung bedeutet. In der Öffentlichkeit und in der Schule durfte zudem nicht alles ausgesprochen werden, in der Familie schon. Heute ist sie Lehrstuhlinhaberin für Theorie und Geschichte der Weltliteratur Nationalen Linguistischen Universität Kiew. „Literatur ist immer auch etwas Ideologisches. Es steht zwischen den Zeilen viel mehr als es scheint.“ Ihre Forschung ist dabei breit gefächert: Von Feminismus und der Harlem Renaissance bis zur Geokritik und Migration. Sie beschäftigte sich gerade mit dem Thema Flucht in der zeitgenössischen Belletristik – als der Krieg ausbrach. „Es hat alles verändert, es ist eine Tragödie – nicht nur für uns Ukrainer:innen, sondern für die ganze Welt“, sagt Shymchyshyn. Sie erinnert sich daran, als sie die erste Bombe sah, als sie den Knall hörte, da konnte sie nicht glauben, was passiert. Gleichzeitig fehlt den Menschen das Vokabular, um ihre Emotionen und Gefühle auszudrücken. „Am ersten Tag hofften wir alle, dass es ein Irrtum sein könnte, dass es bald vorbei ist. Niemand verstand, was geschah, obwohl wir alle die Trümmer und den Tod sahen. Wir konnten nicht glauben, dass ein solch barbarischer Krieg im 21. Jahrhundert möglich ist.“ Es dauerte etwa einen Monat, bis die Universitätsprofessoren den Online-Unterricht wieder aufnehmen konnten. „Die Studierenden wollten erzählen, was sie durchgemacht hatten. Viele begannen selbst zu schreiben." Und auch sie selbst wollte wieder lehren und forschen. „Als Akademikerin muss man klar denken, man muss arbeiten. Aber das konnte ich nicht. Ich zweifelte an meiner Arbeit: Welche Bedeutung hat meine Forschung, wenn in der Nähe Menschen sterben?" Erst durch ihre Flucht, die sie und ihren 13-jährigen Sohn über die Niederlande nach Essen führte, konnte sie wieder schreiben. Gemeinsam mit Prof. Dr. Jens Martin Gurr vom Institut für Anglistik der UDE bewarb sie sich bei der VolkswagenStiftung: Shymchyshyns Forschung wird für mindestens ein Jahr gefördert. Sie ist dankbar, weil sie nicht nur als Flüchtling gesehen wird, sondern als Wissenschaftlerin, die weiterarbeiten will. Doch so produktiv und glücklich, wie sie derzeit in Essen ist, Shymchyshyn will nach dem Krieg in ihre Heimat zurückkehren. „Das intellektuelle Kapital des Landes darf nicht verschwinden. Wir werden unser Land wiederaufbauen und stärker werden als zuvor." Für die Redaktion:\r\nEin Foto von Prof. Dr. Mariya Shymchyshyn (Fotonachweis: Jennifer Meina/UDE) für die Berichterstattung stellen wir Ihnen unter folgendem Link zur Verfügung: http://www.uni-due.de/de/presse/pi_fotos.php ',
@@ -222,6 +349,14 @@
_id: '10072014_AlexandraNießen_Zell-WanderungimVisier_archiv',
llm_label: 1,
llm_persons: ['Daniel Robert Engel'],
+ pred_keywords: [
+ 'Immundynamik',
+ 'Zellmigration',
+ 'Immunsystem',
+ 'Leukozyten',
+ 'angeborene Immunantwort',
+ 'Entzündungsprozesse',
+ ],
full_content:
'[10.07.2014] Wandern, das machen nicht nur Menschen, Zellen tun es auch. Wie sie sich als Bestandteile des Immunsystems fortbewegen, untersucht Prof. Dr. Daniel Robert Engel. Er hat die Professur für Immundynamik an der Medizinischen Fakultät der Universität Duisburg-Essen (UDE) übernommen.\n\nEngel studierte Biologie an der Universität Bonn (1998-2003) und arbeitete ab 2003 am Institut für Experimentelle Immunologie des dortigen Uniklinikums, wo er auch promoviert wurde (2007). Von 2010 bis 2012 leitete er eine Gruppe von Nachwuchsforschern, die sich mit zellulären- und molekularen Mechanismen der angeborenen Immunantwort beschäftigt. Seine Arbeiten wurden von verschiedenen Seiten gefördert – u.a. von der Deutschen Forschungsgemeinschaft – und auch ausgezeichnet. So erhielt er 2011 den Fritz und Ursula Melcher-Award der Deutschen Gesellschaft für Immunologie.\n\nWie die lebenden Zellen wandern, studiert der heute 37-Jährige etwa an weißen Blutkörperchen (Leukozyten), den Immunzellen also, die Gefahren vom Organismus abwehren. Mit Kollegen hat er das Konzept entwickelt, dass die Zellen auch eng miteinander kommunizieren. Ziel der Forscher ist es zu verstehen, wie sie dies am Entzündungsort tun.\n\nAn der UDE will der Professor die Erkenntnisse zur Zellmigration in internationale Projekte einbringen und neue Therapien gegen Krankheiten entwickeln.\n\nWeitere Informationen:\nProf. Dr. rer. nat. Daniel Robert Engel, Tel. 0201/723-6072, danielrobert.engel@uk-essen.de',
},
@@ -229,6 +364,14 @@
_id: '10102003_UlrikeBohnsack_StudienstartinDuisburg-Essen_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Erstsemesterbegrüßung',
+ 'Hochschulorientierung',
+ 'Studienberatung',
+ 'Serviceangebote',
+ 'Studentenleben',
+ 'Campus-Leben',
+ ],
full_content:
'[10.10.2003] Über 5 000 Studierende starten an der Uni Duisburg-Essen am kommenden Montag in ihr erstes Semester. Damit aller Anfang nicht schwer wird, heißt die Hochschule ihre „Erstis“ am Donnerstag, 16. Oktober, besonders willkommen: Rektor Professor Dr. Zechlin nimmt die StudienanfängerInnen um 10 Uhr im Essener Audimax und um 12 Uhr im Duisburger Audimax in Empfang und stellt ihnen die Hochschule vor.\n\nAuf beiden Campi werden die Oberbürgermeister Dr. Wolfgang Reiniger, Essen, und Bärbel Zieling, Duisburg, die neuen Uni-Mitglieder begrüßen. An beiden Standorten wird dann die Geschäftsführerin des Studentenwerks, Katja Linder, per Bild und Text den Service ihrer Einrichtung vorstellen.\n\nPer Bild und Text ist in Essen auch das Medienzentrum mit von der Partie: Dr. Thomas Strauch lädt zu einem virtuellen Rundgang durch die Hochschule ein, bevor ein Sprecher der AStA das vorletzte Wort hat – das letzte hat vor seinem Aufbruch nach Duisburg der Rektor. Musik am Anfang, in der Mitte und am Ende gehört natürlich auch dazu – genauso wie die „student bags“ die im Foyer des Audimax verteilt werden.\n\nIn Duisburg feiern die „Erstis“ ihren Studienstart nach der offiziellen Begrüßung bei Fruchtcocktails im Foyer des Audimax. Dabei lassen sich nicht nur erste Kontakte knüpfen, sondern auch etliche Informationen einholen. Denn die Beratungseinrichtungen der Uni sind mit Ständen vertreten und machen mit ihren Angeboten vertraut: Dazu gehören neben generellen Studieninformationen, Sozial- und Bafög-Beratung, Verpflegungseinrichtungen, Wohnmöglichkeiten, Job-Service, Praktikumsvermittlung oder auch Kontakte zu studentischen Gruppen. Mit dabei ist auch Fußballzweitligist MSV Duisburg. Er schickt nicht nur sein Infomobil, sondern spendiert den Erstsemestern 90 Minuten Kurzweil: Die Duisburger „student bags“ enthalten unter anderem einen kostenlosen Gutschein für ein MSV-Heimspiel.\n\nHinweis für die en: Zur Berichterstattung über die Erstsemesterbegrüßung an beiden Uni-Standorten sind sie herzlich eingeladen. Wir würden uns freuen, Vertreter Ihrer en am kommenden Donnerstag in Essen und Duisburg begrüßen zu können.',
},
@@ -236,6 +379,14 @@
_id: '10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Sozialmedizinische Genderforschung',
+ 'Kardiovaskuläre Erkrankungen',
+ 'Philosophie und Medizin',
+ 'Naturwissenschaften',
+ 'Geschichte',
+ 'Französische Poesie',
+ ],
full_content:
'[10.11.2004] Die Dimensionen sozialmedizinischer Genderforschung stehen im Mittelpunkt einer Ringvorlesung, die das Essener Kolleg für Geschlechterforschung im Wintersemester auf dem Essener Uni-Campus anbietet. Die Reihe wird am Montag, 15. November, 17 Uhr, im Hörsaal des Zentrums für Innere Medizin auf dem Universitätsgelände, Hufelandstraße 55, fortgesetzt. Privatdozent Dr. Thomas Wichter spricht über das Thema „Frauen und Männer in Diagnose und Therapie kardiovaskulärer Erkrankungen“.\n\nWas ist sonst noch an der Uni los?\n\nDienstag, 16. November, 18.15 Uhr: Philosophisch-medizinisches Seminar im Großen Hörsaal der Institutsgruppe I des Universitätsklinikums, Virchowstraße 171. Professor Dr. Georg Scherer, Essen, über das Thema „Sinnerfahrung und Unsterblichkeit“.\n\nMittwoch, 17. November, 14 Uhr: Literaturcafe des Vereins Lebens Langes Lernen (LLL) e. V. im Clubraum der BRÜCKE. Essen. „Wenn die Romantik zur Klassik wird. Ungebrochener Charme in der französischen romantischen Poesie“ mit Gerasimos Romanos.\n\nMittwoch, 17. November, 16.15 Uhr: Antrittsvorlesung im Rahmen des Chemischen Kolloquiums in Essen, S03 V00 E59. Professor Dr. Matthias Epple, Essen, über das Thema „Von Zähnen, Muschelschalen, Knochen und Tiefseequallen“.\n\nMittwoch, 17. November, 17.15 Uhr: Physikalisches Kolloquium auf dem Campus Duisburg, Saal MC 122. Professor Dr. Dieter Meschede, Bonn, über das Thema „Alles unter Kontrolle: Einzelne Atome und einzelne Photone“.\n\nMittwoch, 17. November, 18.15 Uhr: Ringvorlesung der Fachgruppe Geschichte im Glaspavillon, Universitäts-, Ecke Gladbecker Straße in Essen. Dr. Walter Kettemann über das Thema „Tyrannenmord? Zur Ermordung Herzog Ludwigs von Orléans (1407)“.',
},
@@ -243,6 +394,13 @@
_id: '11072024_ManuelaMnch_Jubilum',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Nanointegration',
+ 'Biologie',
+ 'Physik',
+ 'Forschung',
+ 'Universität Duisburg-Essen',
+ ],
full_content:
' KAY EIBL,\r\nFakultät für Biologie. DR. MARION FRANKE,\r\nCenter for Nanointegration Duisburg-Essen. DR. MARKUS ERNST GRUNER,\r\nFakultät für Physik. GISELA MÜLLER,\r\nUniversitätsbibliothek. ',
},
@@ -253,15 +411,34 @@
'Dirk Schadendorf',
'Levi A. Garraway',
'Bastian Schilling',
- 'Christine Harrell',
+ ],
+ pred_keywords: [
+ 'Immuntherapien',
+ 'Krebsforschung',
+ 'Schwarzer Hautkrebs',
+ 'Tumormutationen',
+ 'Wirkmechanismen',
+ 'Personalisierte Therapie',
],
full_content:
'[11.09.2015] Selbst fortgeschrittene Tumore können immer besser behandelt werden dank moderner Immuntherapien. Doch warum wirken bestimmte Medikamente bei einzelnen Patienten und bei anderen nicht? Dieser Frage ging ein internationales Forscherteam der Universitäten Duisburg-Essen und Harvard (USA) nach. Die Federführung lag beim Westdeutschen Tumorzentrum am Universitätsklinikum Essen. Im Mittelpunkt stand der Wirkstoff Ipilimumab, der bereits erfolgreich beim schwarzen Hautkrebs eingesetzt wird. Hierüber berichtet das renommierte Wissenschaftsmagazin Science in seiner aktuellen Ausgabe.\n\nJedes Jahr erkranken rund 500.000 Menschen alleine in Deutschland neu an Krebs, davon bis zu 20.000 am schwarzen Hautkrebs, Tendenz weiter steigend. Schätzungsweise 3.500 dieser Patienten sterben jährlich an dieser Erkrankung, die jede Altersgruppe betreffen kann. Seit 2011 wird in Deutschland Ipilimumab eingesetzt, um den fortgeschrittenen schwarzen Hautkrebs zu behandeln. Bei rund 20 Prozent der Patienten kann der Tumor so über mehrere Jahre unter Kontrolle gehalten werden. Aber warum der Wirkstoff bei einigen Patienten hilft, bei anderen aber nicht, war bislang nicht klar.\n\nDieser Frage sind die Wissenschaftler unter der Leitung von Prof. Dr. Dirk Schadendorf, Direktor der Hautklinik am UK Essen, und Levi A. Garraway M.D, Ph.D. von der Harvard University, USA, nun nachgegangen. Bei der Untersuchung von 110 Patienten entdeckten sie einen interessanten Zusammenhang: Je mehr Mutationen es im Tumor gab, desto wirksamer war das Medikament. Begünstigt wird diese Wirkung noch durch eine verstärkte Produktion bestimmter Moleküle (Granzyme A und Perforin), die das menschliche Immunsystem zur Zerstörung von Tumorzellen einsetzt.\n\n„Unsere Beobachtungen lassen bislang aber noch keine präzise Aussagen darüber zu, wie auf den Wirkstoff angesprochen wird“, erläutert Dr. Bastian Schilling, einer der Autoren der Studie. Die neuen Erkenntnisse zeigen aber, dass sich dahinter komplexe Mechanismen mit vielen Faktoren verbergen müssen. „Deshalb wollen wir im nächsten Schritt weitere Patienten untersuchen, um die genauen Wirkmechanismen zu entschlüsseln. So können wir dann auch die Immuntherapie noch individueller zuschneiden“, ergänzt Professor Dirk Schadendorf.\n\nDas UK Essen ist zusammen mit dem UK Düsseldorf einziger Partnerstandort des Deutschen Konsortiums für Translationale Krebsforschung (DKTK) in Nordrhein-Westfalen. Das DKTK ist eines der vom Bundesministerium für Bildung und Forschung und den Bundesländern eingerichteten Deutschen Zentren für Gesundheitsforschung.\n\nWeitere Informationen:\nVan Allan E, Miao D, Schilling B et al. Science express 10.Sept 2015\nChristine Harrell, Tel. 0201/723 1615, christine.harrell@uk-essen.de',
},
{
_id: '13072020_ClaudiaBraczko_Selbstverpflichtunggescheitert',
- llm_label: 0,
- llm_persons: [],
+ llm_label: 1,
+ llm_persons: [
+ 'Gerhard Bosch',
+ 'Frederic Hüttenhoff',
+ 'Claudia Weinkopf',
+ ],
+ pred_keywords: [
+ 'Fleischindustrie',
+ 'Arbeitsbedingungen',
+ 'Gesetzliche Regelungen',
+ 'Mindestlohn',
+ 'Werkvertragsstrukturen',
+ 'Arbeitsschutz',
+ ],
full_content:
'Gesetzliche Regelungen und keine Werkverträge: Um die Arbeitsbedingungen in der Fleischindustrie zu verbessern, kommt es auf den Staat an. „Der Kontrolldruck auf die Branche muss nachhaltig erhöht werden“, fordert das Institut Arbeit und Qualifikation (IAQ) der UDE in seinem aktuellen Report. Dazu braucht es neue Kontrollstrategien zwischen den Arbeitsschutzbehörden, der Unfallgenossenschaft, den Sozialversicherungen, den Finanzbehörden und der Finanzkontrolle Schwarzarbeit. „Die neuesten Versprechungen der Branche sind Folge des politischen Drucks, nicht aber eines Umdenkens“, kritisiert das IAQ-Team mit Prof. Dr. Gerhard Bosch, Frederic Hüttenhoff und Dr. Claudia Weinkopf. Für die Mindestlohnforschung verfolgt das IAQ seit Jahren die Entwicklungen in der deutschen Fleischwirtschaft. Sie ist inzwischen zum Synonym für Ausbeutung, Lohndumping und soziale Verantwortungslosigkeit der Arbeitgeber geworden. Gesetzliche Vorgaben, Mindestlohn und „freiwillige Selbstverpflichtungen“ wurden immer wieder umgangen, scheiterten am Widerstand der Branche und ihrer Lobby oder einfach mangels wirksamer Sanktionen. Statt vieler Kleinbetriebe gibt es heute einen industrialisierten Wirtschaftszweig mit wenigen Marktführern, die die meisten Tätigkeiten ausgelagert haben, um so den durch die EU-Osterweiterung verfügbaren Pool billiger Arbeitskräfte besser auszuschöpfen. Die skandalösen Arbeitsbedingungen ließen sich in undurchsichtigen Subunternehmerstrukturen verschleiern. Der Branchenmindestlohn ab August 2014 führte immerhin dazu, dass die zuvor von Werkvertragsunternehmen entsandten Beschäftigten jetzt meist Arbeitsverträge nach deutschem Arbeitsrecht haben und damit in das hiesige Sozialversicherungssystem einbezogen sind, was ihnen insbesondere Zugang zu einer Krankenversicherung verschafft hat. Gesetzliche Lücken Das „Gesetz zur Sicherung von Arbeitnehmerrechten in der Fleischwirtschaft“ (GSA Fleisch) von 2017 wirkt nur begrenzt: Zwar hat sich laut Berufsgenossenschaft die Zahlungsmoral bei den Sozialbeiträgen verbessert, eine große Kontrollaktion der Arbeitsschutzbehörden in NRW deckte aber im Spätsommer 2019 weiterhin massive Verstöße bei den Arbeitszeit- und Hygienestandards auf. Zudem müssen die Beschäftigten ihre Lohnansprüche weiterhin über ein zivilgerichtliches Verfahren einfordern und vor Gericht die Beweislast tragen. „Um zumindest Mindestlohnverstöße wirksamer aufzudecken und Lohnansprüche durchzusetzen, müssen Arbeitszeiten manipulationssicher erfasst werden. De Beschäftigten brauchen das gesetzliche Recht zur Einsicht der Angaben,“ fordert das IAQ-Team. ',
},
@@ -269,6 +446,14 @@
_id: '13092018_UlrikeEichweber_PrventivgegensexuellenMissbrauch',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Sexueller Missbrauch',
+ 'Präventionsarbeit',
+ 'Lehrerbildung',
+ 'Lehrkräfte',
+ 'Kinderschutz',
+ 'UDE',
+ ],
full_content:
' Wie können Lehrkräfte Präventionsarbeit gegen sexuellem Missbrauch an Kindern leisten – mit dieser Frage befasste sich das Projekt "Echt Klasse" der Stiftung Hänsel + Gretel. An ihm beteilgte sich auch das Zentrum für Lehrerbildung (ZLB) mit Fortbildungen für die UDE-Lehramtsstudierenden. Die Abschlussveranstaltung des Projektes findet am 18. September im Glaspavillon (Campus Essen) statt. Beginn: 15 Uhr Weitere Infos:\r\nhttp://udue.de/echtklasse2018 (PDF) ',
},
@@ -276,6 +461,14 @@
_id: '14022003_MonikaRgge_KonzertinderKreuzeskirche_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Studentenorchester',
+ 'Klassische Musik',
+ 'Universität Duisburg-Essen',
+ 'Folkwang-Hochschule',
+ 'Abschlusskonzert',
+ 'Orchester-Dirigieren',
+ ],
full_content:
'[14.02.2003] Mit Sergej Prokofjews „Peter und der Wolf“ sowie mit Ausschnitten aus Gioacchino Rossinis „Barbier von Sevilla“ bestreitet das „Essener Studentenorchester“ am Sonntag, 16. Februar, sein Abschlusskonzert zum Ende des Wintersemesters. Eingeladen wird für 17 Uhr in die Kreuzeskirche am Essener Weberplatz. Karten gibt es zu Preisen von 7,50, 5,– und 2,50 Euro an der Abendkasse.\n\nMitglieder des 1996 entstandenen Orchester sind zur Zeit 42 Studenten, die an der Universität Duisburg-Essen sowie an der Folkwang-Hochschule Essen eingeschrieben sind und die Freude am gemeinsamen Musizieren haben. Zum Repertoire des Orchesters gehören Kompositionen aus dem 18., 19. und 20. Jahrhundert. Dirigentin des Orchesters ist seit dem Sommersemester vorigen Jahres Chenghua Jin (32), die ihre musikalische Ausbildung in China begonnen hat. Seit Oktober 2000 studiert sie Chorleitung und Orchester-Dirigieren an der Folkwang-Hochschule.',
},
@@ -283,6 +476,14 @@
_id: '14122023_AstridBergmeister_WiekannEuropaseineNaturwiederherstellen',
llm_label: 1,
llm_persons: ['Daniel Hering', 'Josef Settele', "Guy Pe'er"],
+ pred_keywords: [
+ 'Gesetz zur Wiederherstellung der Natur',
+ 'Biologische Vielfalt',
+ 'Renaturierung',
+ 'EU-Umweltpolitik',
+ 'Landnutzung',
+ 'Ökosystemwiederherstellung',
+ ],
full_content:
'Anfang 2024 wird das Europäische Parlament endgültig über das „Gesetz zur Wiederherstellung der Natur“ abstimmen. Die international einzigartige und heiß diskutierte Verordnung hat das Ziel, den Verlust der biologischen Vielfalt in Europa aufzuhalten und umzukehren. Ein internationales Team von Wissenschaftler:innen unter Leitung der UDE hat untersucht, wie erfolgsversprechend dieses Gesetz ist. Der Artikel wird am 14. Dezember in der Fachzeitschrift Science veröffentlicht. Das „Gesetz zur Wiederherstellung der Natur“ (Nature Restoration Law, NRL) verpflichtet die EU-Mitgliedstaaten, bis 2030 wirkungsvolle Renaturierungsmaßnahmen zu ergreifen: bis 2030 auf mindestens 20 Prozent der Land- und Meeresflächen und bis 2050 in allen Ökosystemen, die einer Wiederherstellung bedürfen. Zentrale Punkte betreffen die Wiedervernässung entwässerter Moore sowie die Erholung von Bestäuberpopulationen. Das NRL hat im EU-Parlament bereits mehrere Hürden genommen: Zuletzt wurde es vom Umweltausschuss des EU-Parlaments gebilligt, nachdem Delegationen des Parlaments und des Rates den endgültigen Text verhandelt hatten. Für Anfang 2024 ist nun die Abstimmung des Europäischen Parlaments über das NRL geplant. Aber wird die Verordnung ihre Ziele wirklich erreichen? Die Autor:innen der Studie sind ausgewiesene Expert:innen, die große europäische Projekte zur Renaturierung und zur biologischen Vielfalt leiten. Sie haben die Erfahrungen mit anderen europäischen Umweltrichtlinien und -strategien analysiert und darauf aufbauend die Erfolgsaussichten der NRL bewertet. „Das NRL verfolgt viele erfolgsversprechende Ansätze und verdeutlicht, dass die EU Kommission von Erfahrungen mit ähnlichen Rechtsvorschriften gelernt hat. Ein zentraler Aspekt dabei: Mit der Konstruktion des NRL umgeht die EU-Kommission mehrere Fallstricke, die die Umsetzung europäischer Politiken und Verordnungen oft behindern", sagt Prof. Dr. Daniel Hering von der Universität Duisburg-Essen, Erstautor der Studie. „Die Verordnung definiert klare Ziele und Zeitpläne und legt die Umsetzungsschritte fest. Sie muss zudem nicht, wie eine Richtlinie, formal in nationales Recht umgesetzt werden und spart damit Zeit.“ Dennoch wird die konkrete Umsetzung auf der Ebene der Mitgliedsstaaten für den Erfolg des NRL entscheidend sein. „Während die Ziele des EU-Gesetzes genau definiert und verbindlich sind, müssen die Schritte zu ihrer Erreichung im Detail von den europäischen Ländern entschieden und durchgeführt werden, und die meisten von ihnen sind freiwillig“, erläutert Prof. Dr. Josef Settele vom Helmholtz-Zentrum für Umweltforschung (UFZ), einer der Autoren der Studie. Ein weiterer erfolgsentscheidender Aspekt: Die Zusammenarbeit der Politik mit den Landnutzer:innen, insbesondere mit der Landwirtschaft. „Die intensive Landwirtschaft ist nach wie vor eine der Hauptursachen für den Verlust der biologischen Vielfalt in Europa", ordnet der Senior-Autor Guy Pe\'er ein. „Aber die Ziele der Landwirtschaft und der Renaturierung könnten miteinander verknüpft werden, so dass beide Seiten davon profitieren können. Die Landwirtschaft profitiert direkt von gesunden Böden und sich erholenden Bestäuberpopulationen sowie von einem verbesserten Landschaftswasserhaushalt – das zeigt, wie sich die Ziele des NRL mit einem Nutzen für die Landwirtschaft verbinden lassen.“ Die Autor:innen kommen zu dem Schluss, dass ein Einsatz von Fördermitteln der Gemeinsamen Agrarpolitik der EU auch zur Zielerreichung des NRL entscheidend sein wird: eine in Fachwelt und Anwendung kontrovers diskutierte These. Insgesamt bewerten die Autor:innen das NRL positiv. Sie machen jedoch deutlich, dass eine ehrgeizige nationale Umsetzung und die Zusammenarbeit mit Wirtschaftssektoren wie der Landwirtschaft letztlich über den Erfolg der Renaturierung in Europa entscheiden werden. Im Bild: Die Vernetzung von Flüssen und ihren Auen, ein wichtiges Ziel des Gesetzes zur Wiederherstellung der Natur, reduziert das Risiko von Überschwemmungen und steigert die Biodiversität. ',
},
@@ -290,6 +491,14 @@
_id: '16012006_ChristophLindemann_EinForumzurKontaktaufnahme_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Firmenkontaktmesse',
+ 'Berufseinstieg',
+ 'Wirtschaftswissenschaften',
+ 'Studierende',
+ 'Karrierechancen',
+ 'Praktika',
+ ],
full_content:
'[16.01.2006] Kontakte knüpfen für den Berufseinstieg - diese Möglichkeit bietet die Firmenkontaktmesse „ConPract“, die der Fachbereich Wirtschaftswissenschaften der Universität Duisburg-Essen am Donnerstag, 19. Januar, veranstaltet. Studierende aller Fachbereiche haben zwischen 10 und 16 Uhr die Gelegenheit, ihre Berufschancen bei elf großen Unternehmen zu prüfen. Veranstaltungsort ist der Glaspavillon des Campus Essen, Gebäude R12, Universitäts-/Ecke Gladbecker Straße. Bereits jetzt können sich Interessierte durch eine Online-Anmeldung einen individuellen Beratungstermin bei ihren potenziellen Arbeitgebern sichern. Nähere Informationen zur Anmeldung und zur Messe gibt es im Internet unter www.conpract.de">http://www.conpract.de\'>www.conpract.de.\n\nDie Veranstaltung ist als Forum zur ersten Kontaktaufnahme gedacht und richtet sich sowohl an Absolventen mit konkreten Berufsvorstellungen, als auch an Studierende, die kurz vor ihrem Studienabschluss stehen. Die Besucher können Informationen über mögliche Berufsfelder und Berufschancen, den Berufseinstieg, Einstellungskriterien, Rekrutierungspraktiken, Unternehmensphilosophien, offene Stellen, mögliche Praktika oder auch Möglichkeiten für Diplomarbeiten in Kooperation mit Unternehmen sammeln.\n\nDie beteiligten Unternehmen sind Deloitte, RWE, Walmart, klickTel, MLP, PriceWaterhouseCoopers, die Santander Consumer CC-Bank, Procter&Gamble, ifb, DextraData und Atena. An den Info-Ständen stehen Mitarbeiter aus Personal- oder Fachabteilungen zu Gesprächen zur Verfügung.',
},
@@ -297,6 +506,14 @@
_id: '16102006_UlrikeBohnsack_…esblitzt,knalltundraucht_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Ingenieurtage',
+ 'Hochtechnologie',
+ 'Robotik',
+ 'Nanopartikel',
+ 'Weltraumforschung',
+ 'Alltagstechnologie',
+ ],
full_content:
"[16.10.2006] Sie beginnt und endet mit einer Lasershow: Die „Engineer's Night“ am kommenden Freitag ist zweifelsohne der Höhepunkt der Ingenieurtage am Duisburger Uni-Campus (19. bis 21. Oktober). Eine Nacht, in der den Zuschauern die Haare zu Berge stehen, in der Gegenstände schweben, durch die Luft fliegen oder Funken sprühen und ein Lichtbogen zum Lautsprecher wird. Eine Nacht, die verspricht, keine Minute langweilig zu werden.\n\nZum Auftakt um 19.15 Uhr wirbeln Laserstrahlen durch den Hörsaal BA 026 an der Bismarckstraße. Dann führt Prof. Dr. Eberhardt 12 spektakuläre Experimente mitelektrischen Strömen durch. Anschließend nehmen die Wissenschaftler die Besucher mit in die Labore. Im Hochspannungslabor simulieren sie Blitzeinschläge und ihre Folgen, sie zündeln im Brandentdeckungslabor und testen Feuermelder. In den Maschinenbau-Laboren treffen die Besucher auf Roboter, sie können ihre Gehbewegungen analysieren lassen und virtuell, aber mit nicht minder großem Vergnügen am Computer Achterbahn fahren. Im Nanopartikellabor erfahren sie alles über die winzigen Teilchen und ihre Herstellung.\n\nUm den Warp-Antrieb geht es beim Vortrag um 22 Uhr: Nicht nur Star-Trek-Fans kommen auf ihre Kosten, wenn Dr. Georg Herdrich von der Universität Stuttgart erklärt, warum der Warp-Antrieb nicht funktioniert und welche Alternativen es für das interplanetare Reisen gibt. Herdrich ist ein echter Weltall-Experte: Er gehört der Forschergruppe um den Astronauten Ernst W. Messerschmid an.\n\nDie Forscher der Uni Duisburg-Essen stillen bei der Ingenieursnacht ? Ende gegen 24 Uhr\n\nübrigens nicht nur den Wissensdurst, sondern sorgen auch fürs leibliche Wohl.\n\nAm Samstag öffnen sich erneut die Labore bei den Daniel Düsentriebs: Ab 12 Uhr laden sie zum „Gucken und Anfassen“ der Hochtechnologie in den Uni-Bereich Bismarckstraße und in die Keksdosen, Mülheimer Straße, ein. Viele Entwicklungen, die die Besucher zu Gesicht bekommen, betreffen unseren Alltag: denkende Autos, Hochleistungs-Chips, Flughafen-Logistik, Mobilfunk, Energieversorgung, Trinkwasser oder Müllentsorgung. Auch die Labore des Vorabends sind erneut geöffnet.\n\nZum Auftakt der Ingenieurstage gibt es am Donnerstag einen Innovationsmarkt für Unternehmen (ab 14 Uhr). Die Berufskontaktmesse, eigentlich für den Vormittag des 19. Oktober geplant, wurde auf Januar verschoben.\n\nEine Anmeldung ist an keinem Tag erforderlich.\n\nDas komplette Programm der Ingenieurtage steht im Netz unter www.uni-due.de/ingenieurtage",
},
@@ -304,6 +521,14 @@
_id: '16112017_UlrikeEichweber_WiewarendieerstenWochen',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Erstsemesterstudierende',
+ 'Studieneingangsbefragung',
+ 'Studienbedingungen',
+ 'Studierenden-Erwartungen',
+ 'Studienalltag',
+ 'UDE-Panel',
+ ],
full_content:
' Wie waren die ersten Wochen an der UDE? Welche Erwartungen haben Erstsemesterstudierende an ihr Studium? Wie organisieren sie ihren Studienalltag? Mit der jährlichen Studieneingangsbefragung im Rahmen des UDE-Panels möchte die UDE mehr über die Bedarfe und Erwartungen der Erstsemesterstudierenden erfahren, um so die Studienbedingungen an der UDE zu verbessern. Die Einladungen zur Teilnahme werden Ende November verschickt. Weitere Infos:\r\nhttps://panel.uni-due.de ',
},
@@ -311,6 +536,14 @@
_id: '17082022_MartinRolshoven_ImmunzellehemmtTumorwachstum',
llm_label: 1,
llm_persons: ['Jadwiga Jablonska', 'Ekaterina Pylaeva'],
+ pred_keywords: [
+ 'Neutrophile Granulozyten',
+ 'Tumorwachstum',
+ 'Krebsimmunantwort',
+ 'Frühe Krebsstadien',
+ 'Tumor-Antigene',
+ 'Therapeutische Intervention',
+ ],
full_content:
'Forscher:innen der Medizinischen Fakultät unter der Leitung von Privatdozentin Dr. Jadwiga Jablonska haben zum ersten Mal zeigen können, dass eine häufig vorkommende Immunzelle das Wachstum von Tumoren in frühen Stadien signifikant bremsen kann. Die als neutrophile Granulozyten bekannten Abwehrzellen des Körpers können unter bestimmten Bedingungen die Überlebenschancen von Krebspatient:innen verbessern. Die Ergebnisse sind jetzt in der renommierten Fachzeitschrift Cell Reports* publiziert. Bisher hatten neutrophile Granulozyten, kurz Neutrophile, einen eher schlechten Ruf. Zirkulieren sie bei Krebskranken verstärkt als sogenannte tumorassoziierte Neutrophile, kann dies zum Beispiel bei Kopf-Hals-Krebs dazu führen, dass sich der Krebs weiter ausbreitet. Leider gibt es bislang nur wenige Möglichkeiten, die tumorfördernden Eigenschaften dieser Zellen zu blockieren. Die neuen Erkenntnisse von PD Dr. Jablonska und ihrem Team von der Klinik für Hals-, Nasen- und Ohrenheilkunde des Universitätsklinikums Essen (UK Essen) zeigen jedoch, dass neutrophile Granulozyten nicht immer die Bösen sind, sondern bei der Krebsabwehr unterstützen können. „Neutrophile Granulozyten sind in der Lage, Tumor-Antigene aufzunehmen, im frühen Krebsstadium in die Lymphknoten zu wandern und Abwehrzellen zu aktivieren“, sagt Dr. Ekaterina Pylaeva, Erstautorin der Studie. „Bisher ging man davon aus, dass Neutrophile die Anti-Krebs-Immunantwort hemmen; jetzt wissen wir, dass sie auch stark stimulierend wirken können“, ergänzt Studienleiterin Jablonska. „Daher führt eine Ansammlung dieser Zellen im Krebsfrühstadium zu einer positiven Prognose für Patient:innen.“ Allerdings fördert in späteren Krebsstadien eine Ansammlung dieser Immunzellen das Tumorwachstum, beobachteten die Forschenden. Die Neutrophilen verändern dann ihre Gestalt: von einem Anti-Tumor-Phänotyp zu einem tumorfördernden. Mit diesem Wissen kann man nun versuchen, den Mechanismus therapeutisch zu adressieren und so die Überlebenschancen der Betroffenen zu erhöhen. * "During early stages of cancer, neutrophils initiate anti-tumor immune responses in tumor-draining lymph nodes“: Cell Reports,https://doi.org/10.1016/j.celrep.2022.111171 Im Bild: Dr. Ekaterina Pylaeva (links) und PD Dr. Jadwiga Jablonska bei der finalen Bearbeitung des Bildmaterials für ihre jüngst publizierte Studie. ',
},
@@ -318,6 +551,14 @@
_id: '18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Industrial Design',
+ 'IMM Cologne',
+ 'Möbelentwurf',
+ 'Operationen am offenen Würfel',
+ 'Design-Ausstellung',
+ 'Kunst und Design',
+ ],
full_content:
'[18.01.2005] Der Studiengang Industrial Design des Fachbereichs Kunst und Design der Universität Duisburg-Essen beteiligt sich an der Internationalen Möbelmesse „IMM Cologne“ in Köln. Bis zum 23. Januar, jeweils von 9 bis 18 Uhr, betreiben die Designer in der Halle „Future Point“, in der sich Design-Schulen aus der ganzen Welt präsentieren, einen eigenen Messestand. Dort werden allerdings nicht einfach Arbeitsergebnisse ausgestellt, sondern es wird live unterrichtet. Die Industrial-Design-Studenten beschäftigen sich mit „Operationen am offenen Würfel“.\n\nSeit Anfang des Semesters ist die geometrische Grundform „Würfel“ das Thema für die Studierenden des ersten Semesters. Zunächst wurden Übungen zum Volumen von Würfeln gemacht, dann erprobten die Studenten die Wirkung unterschiedlicher Farben. Schließlich sollen sie nun Möbel entwerfen, die durch Drehen, Klappen, Falten, Schieben oder anderem mehr aus einem Würfel entstehen können. Betreut werden die Studenten bei den gestellten Aufgaben durch Lutz Köbele, Fachvertreter im Studiengang Industrial Design.\n\nNeben der „IMM Cologne“ gibt es traditionell unter dem Titel „Passagen“ ein begleitendes Ausstellungsprogramm. Der Studiengang Industrial Design beteiligt sich daran mit „Wohnobjekten aus Edelstahl“, die Essener Studenten für die Firma Stålform entworfen haben. Die Ausstellung ist bis zum 23. Januar, jeweils von 12 bis 21 Uhr, an der Antwerpenerstraße 55, 50672 Köln, geöffnet.',
},
@@ -325,18 +566,28 @@
_id: '18122024_KerstinMork_LandsichertFinanzierungderResearchAllianceRuhr',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Research Alliance Ruhr',
+ 'Spitzenforschung',
+ 'Universitätsallianz Ruhr',
+ 'Zukunftsfragen',
+ 'Naturwissenschaftlich-technische Forschung',
+ 'Nachhaltigkeit und Umwelt',
+ ],
full_content:
'Der Landtag Nordrhein-Westfalen hat mit der Verabschiedung des Haushalts 2025 auch der dauerhaften Finanzierung der Spitzenforschung in der Research Alliance Ruhr zugestimmt. Ab dem Jahr 2025 erhalten die drei Universitäten in Bochum, Dortmund und Duisburg-Essen zusätzliche Mittel in Höhe von jeweils 16 Millionen Euro für ihre innovative Kooperation in der Research Alliance Ruhr unter dem Dach der Universitätsallianz Ruhr. Insgesamt stehen damit zukünftig 48 Millionen Euro pro Jahr für die Fortführung und den weiteren Ausbau der vier Research Center und des Colleges zur Verfügung. In der Research Alliance Ruhr baut die UA Ruhr seit 2022 ihre internationale Spitzenforschung weiter aus. Dafür wurden vier neue, universitätsübergreifende naturwissenschaftlich-technische Research Center und ein geistes- und sozialwissenschaftliches College gegründet: das Research Center One Health Ruhr - from Molecules to Systems, das Research Center Chemical Sciences and Sustainability, das Research Center Trustworthy Data Science and Security, das Research Center Future Energy Materials and Systems und das College for Social Sciences and Humanities. Die Center forschen zu drängenden Zukunftsfragen wie Gesundheit und Umwelt, nachhaltige Chemie, neue Energiesysteme sowie Datensicherheit. Das College fördert insbesondere den themenoffenen internationalen wissenschaftlichen Austausch. Ina Brandes, Ministerin für Kultur und Wissenschaft des Landes Nordrhein-Westfalen: „Im Verbund der Universitätsallianz Ruhr schöpfen die Universitäten ihr Potenzial noch besser aus und leisten einen wertvollen Beitrag für den Wissenschaftsstandort Nordrhein-Westfalen mit Strahlkraft weit über Deutschland hinaus. Die Research Alliance Ruhr steht für internationale Spitzenforschung ,made in NRW‘ und hat damit Modellcharakter für das deutsche Hochschul- und Wissenschaftssystem.“ Die Rektor:innen der drei Universitäten – Professor Dr. Martin Paul (Ruhr-Universität Bochum), Professor Dr. Manfred Bayer (TU Dortmund) und Professorin Dr. Barbara Albert (Universität Duisburg-Essen) – erklärten gemeinsam: „Wir begrüßen die Entscheidung, die Research Alliance Ruhr dauerhaft zu finanzieren. Damit wird die internationale Spitzenforschung der Universitätsallianz Ruhr nachhaltig ausgebaut und langfristig gesichert. Unsere Wissenschaftler:innen können so gezielt an Lösungen für zentrale Zukunftsfragen arbeiten. Diese Entscheidung ist ein wichtiger Schritt für das Ruhrgebiet als Wissenschaftsstandort und ein klares Bekenntnis zur Förderung exzellenter Forschung in Nordrhein-Westfalen.“\r\n\r\nSeit ihrer Gründung haben sich bereits 27 Spitzenwissenschaftler*innen für eine Zukunft in der Research Alliance entschieden. Insgesamt werden mehr als 50 neue Professuren an der Ruhr-Universität Bochum, der Technischen Universität Dortmund und der Universität Duisburg-Essen geschaffen.\r\n\r\nDie Landesregierung Nordrhein-Westfalen finanzierte bereits die Aufbauphase von 2022 bis 2024 mit rund 75 Millionen Euro. Die Research Alliance Ruhr ist aus einem Ideenwettbewerb, den die Landesregierung 2019 in der Ruhr-Konferenz ausgerufen hatte, hervorgegangen. ',
},
{
_id: '19052009__InallenStudienphasengutberaten_archiv',
llm_label: 1,
- llm_persons: [
- 'Franz Bosbach',
- 'Ingeborg Stahr',
- 'Nicole Auferkorte-Michaelis',
- 'Kirsten Weihofen',
- 'Beate H. Kostka',
+ llm_persons: ['Franz Bosbach'],
+ pred_keywords: [
+ 'Mentoring-System',
+ 'Studierendenbetreuung',
+ 'Studienabbrechprävention',
+ 'Fachliche Beratung',
+ 'Hochschulqualität',
+ 'Kompetenzentwicklung',
],
full_content:
'[19.05.2009] Erstmals wird jetzt in den elf Fachbereichen der Universität Duisburg-Essen (UDE) ein flächendeckendes Mentoring-System eingeführt, so dass die Studierenden ab dem kommenden Wintersemester in allen Phasen ihres Studiums von ihren Professoren fachlich beraten und gefördert werden. Damit übernimmt die UDE bundesweit eine Vorreiterrolle bei der Wahrnehmung ihrer Verantwortung für die Studierendenbetreuung.\n\nProfessor Dr. Franz Bosbach, Prorektor für Studium und Lehre: „Wir möchten, dass unsere Studierenden erfolgreich sind. Ein wesentlicher Faktor dafür ist die persönliche Beratung vom ersten Semester an, gerade auch in den Massenfächern.“ Verankert ist das neue Mentoringsystem in den Ziel- und Leistungsvereinbarungen, die das Rektorat jetzt mit allen Fachbereichen abgeschlossen hat. Auf diese Weise wird sich die Qualität und Intensität der Studierendenbetreuung an der UDE erheblich verbessern.\n\nEntscheidende Phasen im Studienverlauf sind erfahrungsgemäß die ersten Fachsemester und die Examenszeit, in denen eine effiziente Hilfestellung benötigt wird. Um Studienabbrüche zu vermeiden, wird künftig jeder Studierende gezielt und individuell begleitet und unterstützt. Geplant ist, dass der Mentor, ein Professor oder hauptamtlicher Wissenschaftler, jedem Studierenden mindestens zwei Mal pro Semester für ein persönliches Gespräch zur Verfügung steht. Schon vor dem Semester werden maximal 15-köpfige Studierendengruppen gebildet, die sich mehrfach im Semester treffen und von einem Mentor betreut werden.\n\nMentoring bietet die Chance, persönliche, strategische und fachliche Kompetenzen weiterzuentwickeln und selbst gesteckte Ziele tatsächlich zu erreichen. Das besondere Beratungs- und Unterstützungsangebot soll die Interaktion und den Kontakt zwischen den Studierenden und Dozenten fördern, um die Anonymität des Studiums auch in Massenfächern aufzubrechen. Als begleitende, qualitätsbezogene Maßnahme wird das Zentrum für Hochschul- und Qualitätsentwicklung (ZfH) ein Handbuch für Mentoren, ein Schulungsangebot für Mentoren und Mentees sowie eine Begleitstudie erarbeiten.\n\nWeitere Informationen: Zentrum für Hochschul- und Qualitätsentwicklung (ZfH), http://zfh.uni-duisburg-essen.de/mentoring-system, Dr. Ingeborg Stahr, Tel. 0203/379-2435, ingeborg.stahr@uni-due.de, Dr. Nicole Auferkorte-Michaelis, Tel. 0203/379-1366, nicole.auferkorte-michaelis@uni-due.de, Dipl.-Päd. Kirsten Weihofen, Tel. 0203/379-1412, kirsten.weihofen@uni-due.de\n\nRedaktion: Beate H. Kostka, Tel. 0203/379-2430',
@@ -345,6 +596,14 @@
_id: '19092006__ZweiFliegenmiteinerKlappeschlagen_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Online-Studium',
+ 'Wirtschaftsinformatik',
+ 'Virtueller Weiterbildungsstudiengang',
+ 'Beruf und Studium',
+ 'Flexibilität',
+ 'Hochschulabsolventen',
+ ],
full_content:
'[19.09.2006] Beruf und Studium? Vielleicht auch noch Familie? Kombinieren lassen sich diese Aspekte mit einem Online-Studium. Noch bis Ende September können sich Interessierte für den Virtuellen Weiterbildungsstudiengang Wirtschaftsinformatik (VAWi) an der Universität Duisburg-Essen einschreiben, der nach drei Semestern mit dem Master of Science abschließt.\n\nDas besondere an VAWi sind die flexiblen Wahlmöglichkeiten: 16 aus 35 Online-Kursen müssen belegt werden. Ein Expertenpool mit 21 renommierten Professoren und bis zu 50 Tutoren von 14 deutschen Universitätsstandorten betreut die Kurse. In Projektarbeiten können Studierende aktuelle Aufgabenstellungen aus ihrem Beruf bearbeiten und werden dabei durch VAWi-Betreuer unterstützt, um Beruf und Studium miteinander zu verbinden. Dank der eingesetzten Internet-Technologie spielt der Lernort keine Rolle. Die Materialien sind online jederzeit verfügbar und die Betreuer reagieren schnell.\n\nAuch bei der individuellen Zeitplanung bietet VAWi hohe Flexibilität. So können die Studierenden in jedem Semester ihre Kursbelegungen und den damit verbundenen Arbeitsaufwand frei wählen und ihrer aktuellen beruflichen und privaten Situation anpassen. „Für unsere berufstätigen Studierenden haben wir Pionierarbeit bei der Studienorganisation geleistet“, berichtet der Studiengangleiter an der Universität Duisburg-Essen – Prof. Dr. Heimo Adelsberger. Ein Großteil der Prüfungsleistung wird auf das Semester verteilt, ohne Anwesenheitspflicht an den Universitäten. Viele der jetzt über 300 Studierenden halten sich häufig beruflich im Ausland auf oder können projektbedingt nicht an den Abschlussprüfungen in Essen oder Bamberg teilnehmen. „Klausuren in Hamburg, Shanghai, Brisbane oder Melbourne sind zwar nicht an der Tagesordnung, finden aber auch statt“, freut sich Frank Körner – Studiengangkoordinator in Essen – „Wir beseitigen bürokratische Hürden und bauen unseren Studierenden Brücken.“\n\nBewerben können sich für den kostenpflichtigen Studiengang Hochschulabsolventen aller Fachrichtungen mit Berufserfahrung und einschlägigen Kenntnissen in Wirtschaftsinformatik, Informatik und BWL.',
},
@@ -352,6 +611,14 @@
_id: '19092022_BirteVierjahn_ForschunganwinzigenMagneten',
llm_label: 1,
llm_persons: ['Hari Srikanth', 'Michael Farle'],
+ pred_keywords: [
+ 'Magnetische Materialien',
+ 'Nanoskalige Strukturen',
+ 'Grenzflächenphysik',
+ 'Energieumwandlung',
+ 'Biomedizinische Anwendungen',
+ 'Informationsverarbeitung',
+ ],
full_content:
'Als einer von nur fünf Wissenschaftler:innen ist Prof. Hari Srikanth (University of South Florida, USA) mit dem Humboldt-Forschungspreis 2022 ausgezeichnet worden. Mit der Auszeichnung ist ein Forschungsaufenthalt an einem deutschen Institut nach Wahl verbunden. Srikanth hat sich für die Physik der UDE entschieden. Seine Arbeiten ergänzen insbesondere das Spektrum des großen Forschungsverbunds TRR270 „HoMMage“ zu magnetischen Materialien für die effiziente Energieumwandlung. Hari Srikanth forscht auf dem Gebiet magnetischer nanoskaliger Strukturen. Bis August 2023 wird er in der Arbeitsgruppe von Prof. Michael Farle, Co-Sprecher von „HoMMAge“, neuartige Grenzflächen in magnetischen Partikeln sowie zweidimensionale Systeme erforschen. Beides ist entscheidend für die Entwicklung energiesparender Informationsverarbeitung, für die magnetische Kühlung sowie in der biomedizinischen Diagnose und Therapie. So werden in der Tumorbehandlung magnetische Nanopartikel in das erkrankte Gewebe injiziert. Dort werden sie zum Schwingen gebracht und erhitzt, sodass sie lokal kranke Zellen zerstören. Hierzu braucht man Teilchen, die nicht überhitzen können, die nicht toxisch sind und spezielle Formen und magnetische Eigenschaften haben. Die Grenzflächen kommen insbesondere bei ultradünnen magnetischen Filmen ins Spiel, die nach der bisherigen auf Elektronenladungen basierenden Informationsverarbeitung als nächste, energiesparende Generation diskutiert werden. Denn versteht man die Vorgänge an den Grenzflächen, lassen sich auch die magnetischen Eigenschaften besser kontrollieren. „Unsere Zusammenarbeit bietet die herausragende Möglichkeit, neue Konzepte auf einer Skala von wenigen Nanometern Größe bis hin zu Millimetern zu entwickeln“, so Gastgeber Farle. „Hari Srikanth ergänzt die Erfahrungen meiner Arbeitsgruppe dabei insbesondere in der Herstellung spezieller magnetischer Materialien.“ Mit dem Humboldt-Forschungspreis werden ausschließlich Wissenschaftler:innen aus dem Ausland für ihr Gesamtschaffen ausgezeichnet, mit dem sie das eigene Fachgebiet nachhaltig geprägt haben und von denen auch künftig Spitzenleistungen erwartet werden. Der mit 60.000 Euro dotierte Preis ermöglicht es den Ausgezeichneten, für sechs bis zwölf Monate in einer Arbeitsgruppe ihrer Wahl in Deutschland zu forschen. ',
},
@@ -359,25 +626,50 @@
_id: '20112018_DrAlexandraNießen_NanogroßbeiTumorforschung',
llm_label: 1,
llm_persons: ['Karsten Seidl'],
+ pred_keywords: [
+ 'Medizintechnik',
+ 'Mikro- und Nanosysteme',
+ 'Bio-Nanosensorik',
+ 'Intelligente Implantate',
+ 'Lab-on-Chip',
+ 'DNA-Analyse',
+ ],
full_content:
'Dr. Karsten Seidl (36) ist neuer Leiter der Abteilung Mikro- und Nanosysteme am Fraunhofer-Institut für Mikroelektronische Schaltungen und Systeme (IMS). Er hat die gleichnamige Professur für die Medizintechnik an der Fakultät für Ingenieurwissenschaften der Universität Duisburg-Essen (UDE) angenommen. Kleinste intelligente Implantate für Auge, Gehirn oder Herz stehen im Fokus seiner Forschung. Zu ihnen gehören u.a. sogenannte Bio-Sensorsysteme, die überprüfen, wie die Organe arbeiten und wann sie unterstützt werden müssen. Ein weiterer Schwerpunkt ist die Bio-Nanosensorik, mit denen sich etwa die DNA von Krebszellen analysieren und individuelle Therapien realisieren lassen. Prof. Seidl: „Weil ich als UDE-Professor zugleich eine Abteilung im Duisburger Fraunhofer-Institut leite, bieten sich großartige Möglichkeiten, die Erforschung neuartiger Technologien und Systeme bis zur Anwendungsreife voranzutreiben. So können auch kleinere und mittlere Unternehmen in der Region von unseren Innovationen profitieren.“ Ein weiteres Ziel von Prof. Seidl ist der Ausbau des Bachelor- und Masterstudiengangs Medizintechnik. Mit (bio)medizinischer Technik kennt er sich aus: So entwickelte Seidl für sein Diplom (2004/05) an der Johns Hopkins University, USA, einen Sensor, der die Einstichtiefe chirurgischer Nadeln bei Prostatakrebs-Operationen misst. An der Universität Freiburg wurde er mit einer ausgezeichneten Arbeit über Neuro-Implantate promoviert (2006 bis 2011), die etwa Gehirnsignale messen und Medikamente dort abgeben, wo sie im Körper gebraucht werden. Und ab 2012 entwickelte er als Projektmanager in der Wirtschaft molekulardiagnostische Systeme (Lab-on-Chip), mit denen sich geringste Mengen von Flüssigkeiten vollständig und automatisch analysieren lassen. Weitere Informationen:\r\nProf. Dr.-Ing. Karsten Seidl, karsten.seidl@uni-due.de ',
},
{
_id: '20112019_ChristineHarrell_EinNichtsmitgroßerWirkung',
llm_label: 1,
- llm_persons: [
- 'Julian Kleine-Borgmann',
- 'Ulrike Bingel',
- 'Katharina Schmidt',
- 'Andreas Hellmann',
+ llm_persons: ['Julian Kleine-Borgmann', 'Ulrike Bingel'],
+ pred_keywords: [
+ 'Chronische Rückenschmerzen',
+ 'Open-Label Placebos',
+ 'Schmerztherapie',
+ 'Klinische Neurowissenschaften',
+ 'Schmerzwahrnehmung',
+ 'Funktionelle Einschränkung',
],
full_content:
'Jeder 10. Erwachsene leidet an chronischen Rückenschmerzen – oft mit gravierenden Folgen für den Alltag und die Arbeitsfähigkeit. Die Therapie wirkt häufig nur unzureichend und hat nicht selten schwerwiegende Nebenwirkungen. Ein Team der Medizinischen Fakultät der UDE hat nun am Universitätsklinikum Essen eine mögliche Alternative untersucht: Placebos. Hierüber berichtet die international renommierte Fachzeitschrift PAIN*. Es klingt erstaunlich, und doch hat es in der Studie am Essener Rückenschmerz-Zentrum (Klinik für Neurologie) funktioniert: 127 Patienten mit chronischen Rückenschmerzen bekamen Placebos, also Kapseln, die keinerlei Wirkstoff enthalten. Anschließend untersuchte das Team um Dr. Julian Kleine-Borgmann aus der Arbeitsgruppe von Prof. Dr. Ulrike Bingel, wie die Männer und Frauen den Schmerz wahrnahmen, und maßen ihre Beweglichkeit. Beweglichere Wirbelsäule Patienten, welche die dreiwöchige Placebo-Anwendung erhielten, hatten deutlich weniger Schmerzen als jene, die in der Kontrollgruppe ihre übliche Therapie fortsetzten. Auch schätzten sie ihre Beweglichkeit und funktionelle Einschränkung im Alltag als enorm verbessert ein. Tatsächlich – das ergaben Messungen – war die Wirbelsäule durch die Behandlung nicht beweglicher geworden, was Dr. Kleine-Borgmann nicht verwundert: „Wir wissen bereits aus verschiedenen Studien, dass Placebos vor allem subjektive Beschwerden wie Schmerzen beeinflussen können, objektive Messgrößen wie Laborparameter jedoch deutlich weniger.“ Die Behandlung mit den so genannten ‚Open-Label Placebos’ soll künftig vor allem begleitend zu etablierten Schmerztherapien angewendet werden, um mögliche Nebenwirkungen bis hin zur Medikamentenabhängigkeit zu verhindern. Dennoch sind viele Fragen unbeantwortet, etwa diese: Wie genau und für wie lange wirken Placebos, selbst wenn Patienten wissen, dass sie wirkstofffrei sind? Dies möchten die Wissenschaftler nun in größeren Studien an verschiedenen Standorten untersuchen. Teilnehmer gesucht Für aktuelle Studien sucht das Team der klinischen Neurowissenschaften sowohl interessierte Patienten als auch gesunde Probanden, die sich telefonisch (Tel. 0201/723-2439) oder per Email (schmerzstudie@uk-essen.de) melden können. *Originalpublikation\r\nKleine-Borgmann, Julian*; Schmidt, Katharina; Hellmann, Andreas; Bingel, Ulrike. Effects of open-label placebo on pain, functional disability, and spine mobility in patients with chronic back pain: a randomized controlled trial. PAIN: December 2019 - Volume 160 - Issue 12 - p 2891-2897.\r\ndoi: 10.1097/j.pain.0000000000001683 ',
},
{
_id: '21092018_BeateKostka_Zweifacherfolgreich',
- llm_label: 0,
- llm_persons: [],
+ llm_label: 1,
+ llm_persons: [
+ 'Benjamin Scheller',
+ 'Christof Schulz',
+ 'Igor Rahinov',
+ 'Stephen Tse',
+ 'Kyle Daun',
+ ],
+ pred_keywords: [
+ 'Historisch-kulturelle Dynamiken',
+ 'Ambiguität',
+ 'Nanopartikel',
+ 'Gasphasensynthese',
+ 'Materialwissenschaft',
+ 'DFG-Förderung',
+ ],
full_content:
'Volltreffer: Gleich zwei Anträge der Universität Duisburg-Essen (UDE) waren in der aktuellen Förderrunde der Deutschen Forschungsgemeinschaft (DFG) erfolgreich. Sie richtet eine Forschungsgruppe neu ein und verlängert die Laufzeit einer bereits bestehenden. Wie sind Menschen in verschiedenen Epochen und Kulturen mit ungewissen Situationen umgegangen? Mit der Uneindeutigkeit von Phänomenen, Situationen und Eindrücken vom Spätmittelalter bis in die Gegenwart befasst sich die neue Forschungsgruppe „Ambiguität und Unterscheidung: Historisch-kulturelle Dynamiken“. In den Blick genommen werden Kulturen im Mittelmeerraum, in der Türkei und im „Orient“ sowie in Schlesien, Nordamerika und Südafrika. Sprecher ist der Historiker Prof. Dr. Benjamin Scheller. Das Fördervolumen beträgt rund 1,9 Mio. Euro für die ersten drei Jahre. Designregeln für maßgeschneiderte Nanopartikel In den kommenden drei Jahren weiter forschen kann auch die Forschungsgruppe „Modellbasierte skalierbare Gasphasensynthese komplexer Nanopartikel“, die seit 2015 an der UDE angesiedelt ist. Sie entwickelt systematische Designregeln, damit komplexe Nanopartikel gezielt in der Gasphase hergestellt werden können – seien es optische, elektrische, katalytische oder auch magnetische Eigenschaften, dies hängt von der jeweils gewünschten Anwendung ab. Sprecher ist Prof. Dr. Christof Schulz vom Institut für Verbrennung und Gasdynamik (IVG). Das Fördervolumen beträgt rund 2,7 Mio. Euro. Ein Ergebnis der bisherigen Arbeiten ist zum Beispiel, dass es gemeinsam mit Industriepartnern gelungen ist, einen neuen Produktionsprozess für Silizium-Nanopartikel zu entwickeln, damit sie in Lithium-Ionen-Batterien eingebunden werden können. In die künftige Arbeit werden auch drei internationale Forscher eingebunden: Igor Rahinov von der Open University of Israel, Stephen Tse von der Rutgers University in New Jersey, USA, sowie Kyle Daun von der Waterloo University im kanadischen Ontario. Als Mercator-Fellow werden sie mehrere Monate am Duisburger Uni-Campus zu Gast zu sein. ',
},
@@ -385,6 +677,14 @@
_id: '22022006_BeateHKostka_OffenerDialog_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Studiengebührendebatte',
+ 'Hochschulpolitik',
+ 'Senatssitzung',
+ 'Öffentliche Diskussion',
+ 'Hochschulleitung',
+ 'Studentengruppen',
+ ],
full_content:
'[22.02.2006] Die hochschulpolitische Studierendengruppe Alternative Liste an der Uni Duisburg-Essen hat der Hochschulleitung heute (22.2.) in einer Presseerklärung vorgeworfen, die Studiengebührendebatte unter Ausschluss der Öffentlichkeit betreiben zu wollen. Dazu nehmen Rektor Prof. Zechlin und der Senatsvorsitzende Prof. Breyvogel wie folgt Stellung:\n\nEs gab bislang lediglich eine Besprechung zur Vorbereitung der nächsten Senatssitzung am 24. Februar. Der Senatsvorsitzende und das Rektorat verständigten sich einvernehmlich darauf, dass auf der nächsten Senatssitzung keine Beschlüsse zur Studiengebührenfrage gefasst werden, sondern nur die aktuelle Situation und mögliche Reaktionsweisen diskutiert werden. Ein verbindlicher Beschluss dazu wird frühestens in der Aprilsitzung des Senats verabschiedet werden, wenn das Sommersemester begonnen hat. Vorher wird es auf jeden Fall eine gemeinsame öffentliche Veranstaltung des Rektorats und Senats geben, zu der auch die Studierenden der Universität Duisburg-Essen eingeladen sind, damit sie ihr Votum für die Positionierung der Hochschule in der Frage einbringen können.',
},
@@ -392,6 +692,14 @@
_id: '22052017_ClaudiaBraczko_RentnerarbeitimBetrieb',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Erwerbstätigkeit von Rentnern',
+ 'Fachkräftemangel',
+ 'Teilzeit- und Minijobs',
+ 'Wissenserhalt',
+ 'Flexibler Personalpuffer',
+ 'Soziale Motivation',
+ ],
full_content:
' Über eine Million Rentner arbeiten derzeit in Betrieben. Sie gelten als zuverlässige und flexible Gelegenheitsarbeitskräfte mit oft guten Qualifikationen und langer Berufserfahrung. „Dies spart zwar Personalkosten, doch es ist keine nachhaltige Lösung“, warnt das Institut Arbeit und Qualifikation (IAQ) der Universität Duisburg-Essen (UDE). Langfristig riskiert man Nachwuchsprobleme und Wissensverlust im Betrieb. Die IAQ-Forscherinnen Jutta Schmitz und Lina Zink werteten im Auftrag der Hans-Böckler-Stiftung (HBS) Mikrozensusdaten aus und führten betriebliche Fallstudien durch. Paradox ist, dass hochqualifizierte Ruheständler oft einfache Jobs, Hilfstätigkeiten oder Aufgaben mit geringer Verantwortung übernehmen. Ihre Beweggründe sind soziale Kontakte, Freude an der Arbeit, geistige Fitness, aber auch das Halten des Lebensstandards oder das Aufstocken der Urlaubskasse. Jeder Dritte ist gezwungen zu jobben. Vor allem Teilzeit- und Mini-Jobs Etwa die Hälfte der arbeitenden Rentner ist selbständig tätig. Weit verbreitet sind Teilzeit und Minijobs, 70 Prozent der abhängig Erwerbstätigen sind geringfügig beschäftigt. Ungünstige Arbeitszeiten werden dabei möglichst vermieden, es besteht hohes Interesse, die Arbeit mit der Freizeit zu vereinbaren. Vor allem in kleinen Betrieben ist die Zusammenarbeit auf Dauer angelegt: hier waren die Rentner häufig seit zehn oder mehr Jahren angestellt. Für die Betriebe sind die weiterhin einsatzbereiten Rentner ein flexibler Personalpuffer, die das tägliche Geschäft entlasten und helfen, Auftragsspitzen abzuarbeiten. Hier spielt auch der Wissenserhalt und die Kundenbindung eine Rolle: Man kennt die Gesichter, auch wenn sich ihre Position ändert. Häufig arbeiten sie auch für vergleichsweise wenig Geld ihre Nachfolger ein. Gefragt sind ihre Fachkenntnisse, Zuverlässigkeit, Sorgfalt und Disziplin. „Nachwuchslücken lassen sich allerdings mit der Beschäftigung von Ruheständlern immer nur auf Zeit schließen“, warnen die IAQ-Forscherinnen. Vielen gehe es eher um „Tätigsein“ und einen kleinen Zuverdienst, ihr Personaleinsatz lässt sich nicht strategisch im Betrieb einplanen. „Die Hoffnung, so dem Fachkräftemangel zu begegnen, wird unerfüllt bleiben. Dafür stimmen weder die Erwartungen, die die Rentner an ihre weitere Erwerbstätigkeit stellen, noch das Arbeitsplatzangebot der Betriebe!“ ',
},
@@ -399,16 +707,28 @@
_id: '22072021_UlrikeEichweber_berdigitalesBaueninformieren',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Building Information Modeling (BIM)',
+ 'digitale Baumethoden',
+ 'Baumanagement',
+ 'BIM-Einführung',
+ 'digitale Zusammenarbeit',
+ 'Bauausführung',
+ ],
full_content:
' Auch für die Baubranche gibt es digitale Methoden – das Building Information Modeling (BIM) ist eine davon. Es schafft eine synchronisierte Datenbasis, auf die alle am Bau Beteiligten zugreifen können. Doch fast 95 Prozent kleiner und mittelständischer Unternehmen führen BIM nicht ein, weil ihre Auftraggeber das nicht nachfragen. Das ergab eine Umfrage, die das Institut für Baubetrieb und Baumanagement (IBB) der UDE gemeinsam mit der Hochschule Bochum für das Kooperationsprojekt BIM.Ruhr* durchführte. Was die Umfrage jedoch auch zeigte: Rund 90 Prozent der Befragten würden eine BIM-Nutzung im eigenen Unternehmen nicht ausschließen. Ihnen möchten die Projektverantwortlichen den Einstieg in digitale Arbeitsmethoden erleichtern. Vier Arbeitsgruppen (drei unter Leitung des IBB) gehen deshalb am 24. und 26. August an den Start: BIM-basierte Bauausführung, Geodäsie, Einführung der BIM-Methode bei öffentlichen Auftraggebern und BIM-Planungsgrundlagen. Interessierte Firmen und Kommunen sind eingeladen mitzumachen. * Das Kooperationsprojekt BIM.Ruhr fokussiert sich auf die digitale Methode Building Information Modeling (BIM), die insbesondere eine effizientere Zusammenarbeit bei der Planung, beim Bau und Betreiben von Objekten zwischen allen Beteiligten ermöglicht. Es wird geleitet vom Kreis Recklinghausen. Neben der UDE ist auch die Hochschule Bochum beteiligt. Gefördert wird das Projekt aus Mitteln des Europäischen Fonds für regionale Entwicklung. ',
},
{
_id: '22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv',
- llm_label: 1,
- llm_persons: [
- 'Ulrich Ammon',
- 'Michael Schloßmacher',
- 'Birte Kellermeier-Rehbein',
+ llm_label: 0,
+ llm_persons: [],
+ pred_keywords: [
+ 'Variantenwörterbuch',
+ 'Deutsche Sprache',
+ 'Sprachvarietäten',
+ 'Regionale Unterschiede',
+ 'Soziolinguistik',
+ 'Einheitsdeutsch',
],
full_content:
'[22.12.2004] Was ist Güsel, was ein Bartwisch und wann steht man mit abgesägten Hosen da? Rund 12 000 national wie regional geprägte Wörter und Wendungen der Standardsprache umfasst das neu erschienene „Variantenwörterbuch des Deutschen“. Linguistikprofessor Ulrich Ammon, Uni Duisburg-Essen, und seine Mitarbeiter Dr. Michael Schloßmacher und Birte Kellermeier-Rehbein haben das einmalige und mitunter amüsante Nachschlagewerk zusammen mit Forscherteams aus Basel und Innsbruck erarbeitet.\n\nRahm, Obers, Nidel – nicht überall im deutschsprachigen Raum steht Sahne drauf, wo Sahne drin ist. In Österreich, der Schweiz, in Liechtenstein, Luxemburg, Ostbelgien, Südtirol und natürlich in Deutschland spricht man zwar die gleiche Sprache. Sagen und verstehen tut man dennoch nicht immer dasselbe, selbst im eigenen Land nicht.\n\nEinen Bartwisch etwa kennt man fast überall in Österreich, nicht aber die Handeule. So heißt nämlich in Norddeutschland der Handwischer. Das wiederum ist in der Schweiz gebräuchlich für „kleiner Besen mit feinen, rechtwinklig zum kurzen Griff abstehenden Borsten“, erklärt der Eintrag im Variantenwörterbuch. Damit nicht genug, heißt das Putzutensil in Teilen Deutschlands mal Beserl, mal Kehrwisch, mal Handfeger oder Kehrbesen.\n\nAn die 50 000 solcher national oder regional geprägten Ausdrücke umfasst schätzungsweise die deutsche Standardsprache. Nur ein Viertel – so befanden die beteiligten Wissenschaftler – gehört zum öffentlich gebräuchlichen Wortschatz und wurde daher für das Wörterbuch berücksichtigt. Außen vor blieben die Fach- und Verwaltungssprache, Dialekte, Veraltetes, selten Verwendetes und Umgangssprachliches.\n\nDas 1 000 Seiten starke Werk ist mit beträchtlichem Aufwand und in gerade einmal sechs Jahren Forschungsarbeit entstanden. „Das ist für ein Wörterbuch eine recht kurze Zeit“, sagt Professor Dr. Ulrich Ammon vom Institut für Germanistik am Campus Duisburg. Er ist einer der renommiertesten Wissenschaftler auf dem Gebiet der Soziolinguistik und neueren Geschichte der deutschen Sprache. Das Gemeinschaftsprojekt „Variantenwörterbuch“ der Universitäten Duisburg-Essen, Innsbruck und Basel geht auf seine Initiative zurück. Frühere Forschungsergebnisse Ammons, so sein 1995 erschienenes Buch „Die deutsche Sprache in Deutschland, Österreich und der Schweiz“, schafften die Basis für das neue, einmalige Nachschlagewerk.\n\nWeltweit einmaliges Nachschlagewerk\n\nFür die Linguistik wie Lexikographie ist das Variantenwörterbuch umso bedeutsamer, als es nichts Vergleichbares für eine andere Sprache gibt. Es dürfte somit Vorreiterfunktion haben etwa für das Englische, Französische, Spanische oder Portugiesische, die wie Deutsch als plurizentrische Sprachen gelten. „Als solche“, so Ammon, „bezeichnet man Sprachen, die in mehr als einem Land als nationale oder regionale Amtssprache in Gebrauch sind und dabei standardsprachliche Unterschiede herausgebildet haben.“\n\nDen deutschen Variantenwortschatz erarbeiteten die drei Forschergruppen durch intensive Quellenauswertung: Sie durchforsteten Zeitungen, Zeitschriften, Magazine, populärwissenschaftliche Sachbücher, gehobene und Trivialromane, Krimis, Kinder- und Jugendbücher, Prosatexte, Broschüren, Werbematerialen, Formulare, Gesetzestexte, mündliche Quellen und natürlich das Internet.\n\nUngefährlich: Die Schwedenbombe\n\nAls schwierig erwies sich mitunter die Trennung zwischen Standarddeutsch, Mundart und Umgangssprache. Im Wörterbuch sind Grenzfälle entsprechend gekennzeichnet. Die „Schwedenbombe“ ist so einer. In Österreich isst man sie. Dagegen hat in der Schweiz und in Teilen Deutschlands die (Sch-)Leckerei etymologisch einen anderen Ursprung als in Österreich: Mohrenkopf und Negerkuss heißt sie da. Politisch korrekt, so sagt es das Variantenwörterbuch, ist natürlich der „Schokokuss“.\n\nDie Einträge sind systematisch aufbereitet und dargestellt. Geographische Verbreitung, Gebrauch, Herkunft, Grammatik und Orthografie sind dokumentiert. Es gibt Querverweise auf die gemeindeutschen, also im ganzen deutschen Sprachgebiet geltenden Entsprechungen und für jedes Stichwort auch ein Belegbeispiel.\n\n„Für über 90 Prozent der aufgenommenen Wörter und Wendungen gibt es eine oder mehrere Varianten gleicher Bedeutung in den anderen Nationen oder Regionen des deutschen Sprachgebiets“, sagt Ammon. Für manche gibt es dagegen keine Entsprechung, nur eine gemeindeutsche Übersetzung, etwa für die in der Schweiz gängige Wendung „in abgesägten Hosen dastehen" (bloßgestellt sein).\n\nEin und dasselbe Wort, mehrere Bedeutungen – auch das gibt es: Mit „Estrich“ benennen Deutsche und Österreicher den fugenlosen Fußboden, Schweizer den Dachboden. Und ein für viele Ohren Haar sträubender Grammatikfehler ist gar keiner: Man darf nicht nur „ihn rufen“ (Österreich; Norddeutschland), sondern auch „ihm“ (Schweiz; Süddeutschland).\n\nDas Einheitsdeutsch gibt es nicht\n\nDas Einheitsdeutsch, das zeigt das Variantenwörterbuch deutlich, gibt es nicht, auch wenn lange Zeit nur als richtig galt, was im Duden steht. Nationale und regionale Unterschiede im Gebrauch von Wörtern und Wendungen sowie abweichende Grammatik und Orthografie wurden ignoriert. Das machte das Österreichische und Schweizerische zu einem Deutsch zweiter Klasse. Groß war deshalb das Interesse an diesem Projekt in beiden Ländern, und die finanzielle Förderung fiel deutlich höher aus als in Deutschland. Aber auch hier unterstützte die Deutsche Forschungsgemeinschaft die Duisburger Arbeiten mit fast 700 000 €.\n\nGedacht ist das Variantenwörterbuch für Germanisten, Deutschlernende und -lehrende, für Medien- oder Tourismusfachleute oder als Nachschlagewerk für Leser deutschsprachiger Literatur. Manchen mag es auch zur Verständigung im Alltag dienen. So soll ein deutsches Computerunternehmen, das nach Österreich expandierte, für seine neuen Mitarbeiter als Begrüßungsgeschenk gleich einen ganzen Satz geordert haben. Auch Nutzer mit rein „folkloristischem Interesse“ schließt Ammon nicht aus. Denn auch sie kommen auf ihre Kosten. Ein Eintrag unter „K“: Der bundesdeutsche Korinthenkacker ist bei den österreichischen Nachbarn ein Tüpferlreiter und in der Schweiz ein Tüpflischeisser. Eine wirklich schöne Variante.\n\nUlrich Ammon u.a.: „Variantenwörterbuch des Deutschen. Die Standardsprache in Österreich, der Schweiz und Deutschland sowie in Liechtenstein, Luxemburg, Ostbelgien und Südtirol“, de Gruyter, 2004, gebunden 68 Euro, Broschur, 29,95 Euro.\n\nHinweis: Rezensionsexemplare sind ausschließlich über den Verlag de Gryter erhältlich',
@@ -417,6 +737,14 @@
_id: '23032007_AnnikaBingmann_VielWindumEnergie_archiv',
llm_label: 1,
llm_persons: ['Heinrich Brakelmann', 'István Erlich'],
+ pred_keywords: [
+ 'Offshore-Windenergie',
+ 'Energietransport',
+ 'Hochsee-Windparks',
+ 'Stromnetzoptimierung',
+ 'Seekabel',
+ 'Erdkabel',
+ ],
full_content:
'[23.03.2007] In Zukunft wird Windenergie zunehmend weit draußen in der Nord- und Ostsee, das heißt „offshore“ erzeugt. Dazu starten zwei Forschungsprojekte an der Fakultät für Ingenieurwissenschaften der Universität Duisburg-Essen. Professor Heinrich Brakelmann vom Fachgebiet Energietransport und -speicherung will neue Wege finden, um den Stromtransport von Hochsee-Windparks in Festlandnetze zu optimieren.\n\nIm Verlauf eines ersten Projekts sollen umweltfreundliche Alternativen der Energieübertragung entwickelt werden, die sich für den Ausbau der bestehenden 110 Kilovolt-Netze in Norddeutschland eignen. „Aus Angst vor elektromagnetischen Feldern akzeptiert die Bevölkerung Überlandleitungen kaum noch. Wir überprüfen welche optimierten Erdkabel sich dafür einsetzen lassen.“, erklärt Professor Heinrich Brakelmann. Durch zusätzliche Leitungen wollen die Forscher Engpässe beim Energietransport von Nord nach Süd auch in Zukunft vermeiden. Die 180.000 Euro teuren Untersuchungen werden in Kooperation mit zwei Planungsfirmen durchgeführt und sind auf anderthalb Jahre angelegt. Das Bundesamt für Naturschutz unterstützt das Projekt finanziell.\n\nLeistungsstarke Seekabel, die Energie von den Hochsee-Windparks unterirdisch zum Festland leiten, sollen in einem zweiten Forschungsprojekt entwickelt werden. „Große Hoffnungen liegen auf einem neuartigen ,bipolaren? Kabelsystem aus See- und Landkabeln, das in der Lage ist, extrem hohe Leistungen zu transportieren.“, so Projektleiter Brakelmann. An den Untersuchungen beteiligt ist außerdem Professor István Erlich vom Fachgebiet Elektrische Anlagen und Netze. Das Bundesumweltministerium sowie die Industrie unterstützen das etwa 650.000 Euro teure Projekt über einen Zeitraum von drei Jahren.',
},
@@ -424,6 +752,14 @@
_id: '24012018_BeateKostka_Sitzungvom12Januar2018',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Semesterticket',
+ 'Online-Ticket',
+ 'Studierendenvertretung',
+ 'Drittmitteleinwerbung',
+ 'Berufungsverfahren',
+ 'Onlinewahlen',
+ ],
full_content:
' Die immer noch bestehenden Probleme mit dem Semesterticket im Öffentlichen Nahverkehr zählten zu den Hauptdiskussionspunkten der Senatssitzung. Dekan Schreckenberg brachte diesen Punkt unter Anfragen zur Sprache und drängte darauf, den berechtigten Beschwerden nachzugehen. Das neue Online-Ticket funktioniere nach wie vor nicht störungsfrei insbesondere bei der Bahn. Trotz gültigem Semesterticket seien Studierende bereits mehrfach zu Nacherhebungen veranlasst worden. Die Schlichtungsstelle (http://www.schlichtungsstelle-nahverkehr.de/doc12270A) helfe da nur begrenzt. Die Studierenden bedankten sich für die Unterstützung und ergänzten, dass die dazu aufgelegte Online-Petition (http://fsreferat.asta-due.de/?page_id=1365) zur Wiedereinführung des alten Verfahrens (Semesterticket im Chip auf dem Studierendenausweis) innerhalb kürzester Zeit bereits knapp 2.000 Unterschriften bekommen habe. Studierende seien in großer Sorge um ihren alten Ausweis mit integriertem Chip: Falls er nicht mehr funktionieren sollte, müssten auch sie das umstrittene Online-Ticket nutzen. Kritisiert wird auch, dass ab dem 31. August generell darauf umgestellt werden soll. Die zuständige Dezernentin Wasmer betonte, dass im Studierendensekretariat bislang nur vereinzelt Klagen angekommen sind. Die Studierendenvertreter im Senat bitten die Verwaltung darum, nochmals mit allen Beteiligten zu prüfen, ob nicht doch eine Rückkehr zur alten Chipkartenlösung möglich ist, auch wenn dies mit Zusatzkosten verbunden sein sollte. Berufungen: Der Senat votierte jeweils einstimmig für die vorgeschlagene Besetzung der Kontrovers diskutiert wurde auch, welche Rolle Drittmitteleinwerbung bei Berufungsverfahren zukommen soll: nur „erwünscht“ oder zwingend „erforderlich“ (TOP 7)? Wettbewerblich eingeworbene Drittmittel (vor allem von der DFG) seien ein übliches Kriterium bei Berufungen. Es sollte deshalb auch direkt bei der Ausschreibung als verbindliche Kategorie benannt werden, so der Rektor, um später als Maßstab angewendet werden zu können. Wer keine DFG-Mittel einwerbe, habe in der Wissenschaftswelt ein Problem. Die Senator/innen warnten jedoch vor Pauschalurteilen angesichts der unterschiedlichen Fächerkulturen. Prorektor Spitzley verwies auf den geltenden Berufungsleitfaden, der die Vorgehensweise zur Sicherstellung der Fachbesonderheiten in diesem Bereich regelt. Die Senator/innen sprechen sich dafür aus, dass die vorgelegten Formulierungsvorschläge, wie künftig zu verfahren ist, erneut mit Rektorat und Dekanerunde diskutiert werden. Große Probleme hatten die Studierendenvertreter/innen mit der vorgeschlagenen Umstellung auf Onlinewahlen (TOP 9), die die IKM-Kommission zuvor beanstandungsfrei geprüft hatte hinsichtlich technischer und datenschutzrechtlicher Bedenken. Die Befürworter/innen verwiesen darauf, dass onlinegestützte Wahlen eine höhere Beteiligung erwarten lasse (an der TU Dortmund z.B. von 3 auf 7 %), weniger personalintensiv (Wahlhelfende) sei und die Auszählung schneller vonstatten gehe. Die Studierenden warnten vor möglichen Gefahren: etwa unsicheres Internet oder problematische Einhaltung des Wahlgeheimnisses, wenn z.B. an PCs in der UB gewählt wird. Eine Onlinewahl sei auch nicht so gut nachprüfbar und könnte deshalb leichter angefochten werden, argumentierte Corinna Kalkowsky. Dezernentin Wasmer erläuterte, dass es keine rechtlichen Bedenken gegen Online-Wahlen gebe. Für die Einführung von Online-Wahlen stimmten neun Senator/innen mit ja, zwei mit nein, drei enthielten sich der Stimme: Der Senat empfiehlt, die Option zur Durchführung von Onlinewahlen vorzubereiten und die Wahlordnung anzupassen. ',
},
@@ -431,6 +767,14 @@
_id: '25112021_UlrikeEichweber_UDE-DoktorandinimFinale',
llm_label: 1,
llm_persons: ['Janine Moyer'],
+ pred_keywords: [
+ 'Science Slam',
+ 'Endometriose',
+ 'Wirkstoffkombinationen',
+ 'Anatomie',
+ 'Forschung',
+ 'Deutsche Science Slam Meisterschaft',
+ ],
full_content:
' Acht Minuten Zeit, ihr Forschungsthema anschaulich und mitreißend auf die Bühne zu bringen: Dieser Herausforderung stellen sich die fünf Finalist:innen der Deutschen Science Slam Meisterschaft am 27. November. Eine davon: UDE-Doktorandin Janine Moyer. Am Institut für Anatomie am Uniklinikum Essen sucht die Biologin nach neuen Wirkstoffkombinationen zur Behandlung von Endometriose. Was es mit dieser weitverbreiteten gynäkologischen Erkrankung auf sich hat, und warum ihre Forschungswelt von Harry Potter inspiriert ist, erklärt sie bei ihrem Auftritt an der FH Dortmund, mit dem sie um die Gunst des Publikums kämpft. Denn das entscheidet per Voting über eine Abstimmungsplattform, wer den Meistertitel erringt. Die Veranstaltung wird live auf https://www.science-slam.com/deutsche-science-slam-meisterschaft-2021/ übertragen. Los geht es um 20 Uhr. Im Bild: Mit diesem Video kämpfte Moyer für den Einzug ins Finale, gemeinsam mit elf weiteren Kandidat:innen. Der ist ihr gelungen. ',
},
@@ -438,6 +782,14 @@
_id: '26052006__MechaniktrifftVirtualReality_archiv',
llm_label: 1,
llm_persons: ['Andrés Kecskeméthy'],
+ pred_keywords: [
+ 'computergesteuerte Bewegungsanalyse',
+ 'Mechanik',
+ 'Virtual Reality',
+ 'Medizintechnik',
+ 'Industrie',
+ 'Roboter',
+ ],
full_content:
'[26.05.2006] Einen Blick in die Zukunft der computergesteuerten Bewegungsanalyse wirft Professor Dr. Andrés Kecskeméthy beim Uni-Colleg am Mittwoch 31. Mai. „Mechanik trifft Virtual Reality“ lautet der Titel seines Vortrags. Beginn ist um Beginn ist um 19.30 Uhr im Hörsaal MD 162, Mülheimerstr./Lotharstraße, am Campus Duisburg. Der Eintritt ist frei.\n\nDie Mechanik ist ein klassisches Fach der Natur- und Ingenieurwissenschaften. Sie beschäftigt sich allgemein mit der Frage, wie sich Kräfte auf Körper und Bewegungen auswirken. Die Zusammenhänge für solche Vorgänge sind durch eine Reihe von relativ einfachen Gesetzen festgelegt. Auf dieser Grundlage gelang es mit Hilfe der Computertechnologie in den letzten Jahrzehnten, Bewegungsvorgänge für immer komplexere Systeme, wie zum Beispiel Fahrzeuge, Achterbahnen, Roboter, aber auch menschliche Bewegungen vorherzusagen und damit deren Verhalten auch ohne kostspielige und gefährliche Versuche vorauszuberechnen.\n\nDaraus ist die virtuelle Realität geworden, mit der sich ein immer genaueres Abbild des Verhaltens von mechanischen Systemen am Computer rekonstruieren lässt. In seinem Vortrag wird Professor Kecskeméthy zeigen, wie sich die virtuelle Realität nutzen lässt, um in Zukunft Optimierungen und innovative Methoden für die Medizintechnik oder die Industrie zu entwickeln.',
},
@@ -445,6 +797,14 @@
_id: '27012025__ProfDrWilhelmHeinrichsverstorben',
llm_label: 1,
llm_persons: ['Wilhelm Heinrichs'],
+ pred_keywords: [
+ 'Ingenieurmathematik',
+ 'Numerische Analysis',
+ 'Spektralverfahren',
+ 'Partielle Differentialgleichungen',
+ 'Navier-Stokes-Gleichungen',
+ 'Kollokationsverfahren',
+ ],
full_content:
' Die Fakultät für Ingenieurwissenschaften der UDE nimmt in tiefer Trauer Abschied von Prof. Dr. Wilhelm Heinrichs, der die Professur für Ingenieurmathematik seit 1994 bis zu seinem Ruhestand vertrat. Mit seinem Engagement und seiner Fachkompetenz prägte er das Fachgebiet über viele Jahre hinweg. Sein wissenschaftlicher Schwerpunkt lag auf der Entwicklung und der numerischen Analysis von Spektralverfahren zur Lösung partieller Differentialgleichungen. Insbesondere seine Arbeiten zu Kollokationsverfahren und Mehrgittermethoden sowie zur numerischen Lösung der Navier-Stokes-Gleichungen fanden nationale und internationale Beachtung. Über die Jahrtausendwende hinweg war er in der internationalen Forschungsgemeinschaft aktiv vernetzt und leistete wertvolle Beiträge zur Numerik von Spektralverfahren. Zum Nachruf der Fakultät ',
},
@@ -456,15 +816,30 @@
'Dierk Raabe',
'Oleg Prymak',
'Joachim Enax',
- 'Ulrike Bohnsack',
+ ],
+ pred_keywords: [
+ 'Biomineralisation',
+ 'Zahnstrukturen',
+ 'Werkstoffwissenschaft',
+ 'Fluorapatit',
+ 'Nano-Struktur',
+ 'Zahnersatz',
],
full_content:
'[27.07.2012] Und der Haifisch, der hat Zähne… – aber was für welche: Wissenschaftler der UDE und des Max-Planck-Instituts für Eisenforschung (MPIE) in Düsseldorf haben die Zahnstrukturen bei Hai und Mensch analysiert und dabei Erstaunliches festgestellt: Obwohl die Beißer des Raubtiers zu hundert Prozent Fluoride enthalten, also das Mineral, das niedrigdosiert in Zahncremes steckt, sind sie nicht härter als unsere.\n\nDass die Nano- und Werkstoffwissenschaftler ausgerechnet Haien auf den Zahn fühlen, ist kein Zufall. „Das wollte ich schon lange einmal tun“, betont Matthias Epple, Professor für Anorganische Chemie. „Wir beschäftigen uns an der UDE seit Jahren mit der Biomineralisation. Dabei geht es um die Frage, was anorganische Mineralien in biologischen Systemen, also Zähnen, Knochen, Muschelschalen, bewirken. Haie besitzen bekanntlich einen Zahnschmelz aus dem sehr harten Mineral Fluorapatit. Bislang hat den aber noch kein Forscher mit modernen High-end-Methoden aus Chemie und Physik analysiert.“ Das haben Epple und sein Düsseldorfer Kollege Professor Dierk Raabe zusammen mit Dr. Oleg Prymak und Joachim Enax nun nachgeholt. Den Großteil der Arbeiten führten sie an der UDE durch. Am Max-Planck-Institut fanden insbesondere die mechanischen Messungen statt.\n\nFür die Studie nahmen die Forscher die Zähne des Kurzflossen-Mako und des Tigerhais buchstäblich auseinander – diese Arten fressen ihr Beutefleisch nämlich unterschiedlich. Mithilfe des Rasterelektronenmikroskops und der Röntgenbeugung schauten sie sich Anordnung, Größe und Natur der Fluorapatit-Kristalle an, über die mechanischen Messungen prüften sie die Härte lokal in kleinen Bereichen. Obwohl der Mako das Fleisch seiner Beute reißt und der Tigerhai es schneidet, ist der chemische und kristalline Aufbau ihrer Zähne nahezu identisch, stellten Epple und seine Kollegen fest. Im Inneren ist elastisches Dentin, das Äußere ist hochmineralisiert.\n\nSo könnte man eigentlich getrost davon ausgehen, dass Haifischzähne härter sind als unsere. „Der Schmelz beim Menschen besteht aus einem etwas weicheren Mineral, dem Hydroxylapatit, der übrigens ebenfalls in Knochen vorkommt.“ Doch zur Überraschung der Forscher ergaben die Vergleichsuntersuchungen an einem menschlichen Zahn: Er ist genauso robust wie der des gefürchteten Raubtieres. „Das liegt an der besonderen Mikro- und Nanostruktur unserer Zähne, in denen Kristallnadeln durch besondere Anordnung und Verkleben mit Proteinen verhindern, dass ein Bruch durch den ganzen Kristall läuft“, so der Professor, der auch dem Center for Nanointegration Duisburg-Essen (CENIDE) der Uni angehört. Die Natur hat das übrigens bei allen Lebewesen ähnlich eingerichtet: Wären Zähne nämlich komplett mineralisch, so drohten sie zu zersplittern.\n\nIhre Arbeiten setzen die Wissenschaftler nun fort, etwa an Haien unterschiedlichen Alters. Und sie experimentieren damit, die Strukturen nachzubauen – für den Zahnersatz von morgen. „Es wäre toll, wenn man irgendwann Zähne mit einem Material restaurieren könnte, das viel natürlicher ist als die heutigen Behelfslösungen.“\n\nBis dahin muss sich der Mensch wohl damit abfinden, dass Haie dennoch die besseren Zähne haben: Diese wachsen immer wieder nach und bekommen keine Löcher. „Das mag am Fluorapatit liegen, aber auch am Wechselgebiss, das fortlaufend durch das Meerwasser umspült wird“, sagt Matthias Epple. „Nicht zu vergessen: Haie futtern keinen Zucker.“\n\nDie Forschungsergebnisse sind in der aktuellen Ausgabe des Journal of Structural Biology, 178 (2012), veröffentlicht.\nDOI http://dx.doi.org/10.1016/j.jsb.2012.03.012\n\n\nWeitere Informationen: Prof. Dr. Matthias Epple, Universität Duisburg-Essen, Tel. 0201/183-2413, matthias.epple@uni-due.de\n\nHinweis für Redaktionen: Urlaubsbedingt ist Prof. Epple erst am 20. August wieder erreichbar. Die Pressestelle kann zwischenzeitlich einen Kontakt herstellen.\n\nRedaktion: Ulrike Bohnsack, Tel. 0203/379-2429',
},
{
_id: '27102015__NeuesKonzeptsollPflegeerleichtern_archiv',
- llm_label: 0,
- llm_persons: [],
+ llm_label: 1,
+ llm_persons: ['Marcus Roth'],
+ pred_keywords: [
+ 'Entlastungskonzept',
+ 'Emotionale Belastung',
+ 'Pflegewesen',
+ 'Coaching und Training',
+ 'Pflegekultur',
+ 'Fachkräftemangel',
+ ],
full_content:
'[27.10.2015] Tagein, tagaus versorgt eine Pflegekraft alte oder kranke Menschen nicht nur medizinisch, sie hat auch ein offenes Ohr für ihren Kummer. Sie weiß, dass sie für viele die einzige Person ist, die sie täglich sehen. Doch auch ihr kann das emotionale Gepäck auf Dauer zu schwer werden. Um dem vorzubeugen, entwickelt die Universität Duisburg-Essen (UDE) jetzt ein Entlastungskonzept. Es ist Teil des Verbundprojekts empCARE, das das Bundesforschungsministerium mit über 900.000 Euro für knapp vier Jahre fördert.\n\n„Um Folgen emotionaler Belastung zu vermeiden, kombinieren wir in unserem Konzept kurzfristige Trainings mit langfristigem Coaching“, erklärt Prof. Dr. Marcus Roth, Leiter des UDE-Instituts für Psychologie. Der Projektpartner Uniklinikum Köln setzt das Programm anschließend in der stationären Pflege um und stimmt es mit der täglichen Praxis ab. Dasselbe macht der zweite Projektpartner, DIE MOBILE Intensivpflege Köln GmbH, für die ambulante Pflege. Der dritte Partner, die Pflegedirektion des Universitätsklinikums Bonn, schult Trainer und Coaches, damit sich das Konzept über Multiplikatoren weiterverbreiten kann.\n\nDie UDE begleitet den gesamten Prozess wissenschaftlich und stellt den pflegenden Institutionen - ergänzend zum Konzept - ein Handbuch bereit, das ihnen helfen soll, die Maßnahmen in ihrem Berufsalltag zu verankern. „Das Projekt soll vor allem den Pflegenden nützen und so langfristig die Pflegekultur in Deutschland verändern. Das könnte sich auch positiv auf den Fachkräftemangel und die hohe Fluktuation in der Pflege auswirken“, so der Professor.\n\nWeitere Informationen:\nProf. Dr. Marcus Roth, Institut für Psychologie, Tel. 0201/183-6057, marcus.roth@uni-due.de\n\nRedaktion: Amela Radetinac, Tel. 0203/379-2429',
},
@@ -472,6 +847,14 @@
_id: '29112010_BeateHKostka_MitRegio-ELFgutimRennen_archiv',
llm_label: 1,
llm_persons: ['Wolfgang Stark', 'Ute Klammer'],
+ pred_keywords: [
+ 'Regio-ELF',
+ 'Engagement durch Lehre und Forschung',
+ 'Service Learning',
+ 'Gemeinwesen basierte Forschung',
+ 'Regionale Zivilgesellschaft',
+ 'Diversity Management',
+ ],
full_content:
'[29.11.2010] Mit ihrem Projekt Regio-ELF (Engagement durch Lehre und Forschung für die Region) steht die Universität Duisburg-Essen (UDE) im Finale des Wettbewerbs „Mehr als Forschung und Lehre! Hochschulen in der Gesellschaft“, dem gemeinsamen Förderprogramm von Stifterverband und Stiftung Mercator. Aus den insgesamt 78 Bewerbungen wurden neben der UDE neun weitere deutsche Hochschulen für die Endrunde ausgewählt. Wer das Rennen im Finale macht, wird am 17. und 18. Februar 2011 in Berlin entschieden.\n\nProjektleiter Prof. Dr. Wolfgang Stark: „Mit dem Projekt signalisiert die Uni, dass sie ihre Rolle als aktiver Gestalter der regionalen Zivilgesellschaft annimmt und ihren Beitrag zur Bewältigung gesellschaftlicher Herausforderungen leisten will.“ Im Mittelpunkt des Projekts Regio-ELF steht die Frage, wie die Region durch das Engagement der Uni und ihrer Angehörigen in Lehre und Forschung direkt profitieren kann.\n\n„Regio-ELF“ basiert auf dem breiten Spektrum an Aktivitäten in Lehre und Forschung, mit denen die UDE bereits in der Region verankert ist. Prof. Dr.Wolfgang Stark: „Eine große Rolle spielen dabei Konzepte des Service Learnings und der Gemeinwesen basierten Forschung. Etwa mit Lehrveranstaltungen und Forschungsvorhaben, die ganz konkret auf die Region, ihre Bewohner und deren Herausforderungen zugeschnitten sind. Gemeinsam mit den Betroffenen entwickeln sich neue Formen des kontinuierlichen Dialogs und der Kooperation zum Beispiel im Bereich Stadtentwicklung, Integration, Strukturwandel, Teilhabe an Bildung oder Unterstützungsangebote für den Übergang ins Studium.\n\nDie Bewerbung wird gemeinschaftlich getragen durch das Zentrum für gesellschaftliches Lernen und soziale Verantwortung (UNIAKTIV) der UDE und das Prorektorat für Diversity Management. Prorektorin Prof. Dr. Ute Klammer: „Ich sehe die Final-Nominierung auch als Bestätigung, dass wir mit unseren Initiativen im Bereich des Diversity Management bundesweit Modellcharakter haben, sei es mit dem Programm ‚Chance hoch 2‘ - dem Förderprogramm für BildungsaufsteigerInnen, dem Förderunterricht für Kinder und Jugendliche mit Migrationshintergrund oder dem Projekt UNIAKTIV.“\n\nWeitere Informationen: http://www.uni-due.de/diversity/Prorektorat.shtml, http://www.uniaktiv.org',
},
@@ -483,6 +866,14 @@
'Alexander Schramm',
'Sven Rahmann',
],
+ pred_keywords: [
+ 'Künstliche Intelligenz',
+ 'Große Datenmengen',
+ 'Autonome Verkehrssysteme',
+ 'Molekulare Onkologie',
+ 'Datenauswertung',
+ 'Ressourcenbeschränkung',
+ ],
full_content:
'Künstliche Intelligenz mit riesigen Datenvolumen zusammenzubringen ist eine große Herausforderung für die Datenverarbeitung. Lösungen sucht der Sonderforschungsbereich 876 („Verfügbarkeit von Information durch Analyse unter Ressourcenbeschränkung“), der jetzt in die dritte Förderperiode geht. Forschungspartner sind die TU Dortmund, die Universität Duisburg-Essen (UDE), das Leibniz-Institut für Analytische Wissenschaften (ISAS) sowie das Paul-Ehrlich-Institut. Die Deutsche Forschungsgemeinschaft (DFG) fördert den SFB in den nächsten vier Jahren mit rund neun Millionen Euro. Ziel ist, aus immer größeren Datenmengen Informationen zu gewinnen – und zwar zeitnah, ohne großen Energiebedarf und direkt vor Ort, sei es für die Verkehrs- oder Krebsvorhersage. Mit diesen Themen befassen sich die UDE-Forscher in ihren beiden Teilprojekten. Im ersten UDE-Projekt beschäftigt sich Stauexperte und Physikprofessor Dr. Michael Schreckenberg mit dem Zusammenwachsen von autonomen und menschlichen Verkehrsteilnehmern. Hier steht im Vordergrund, wie sich in diesem Szenario die Kommunikation zwischen Fahrzeugen so regeln lässt, dass möglichst sicher und staufrei gefahren werden kann. Um diese Prozesse zu steuern, werden maschinelle Lernverfahren eingesetzt, die in Echtzeit den Verkehrsfluss optimieren können. Im zweiten UDE-Teilprojekt beschäftigen sich Prof. Dr. Alexander Schramm, Leiter der Molekularen Onkologie am Westdeutschen Tumorzentrum des Universitätsklinikums Essen, und der Genominformatiker Prof. Dr. Sven Rahmann mit Nachweisverfahren für das Therapieansprechen bei Lungenkrebs. Neue Entwicklungen in der mobilen DNA-Sequenzierung sollen genutzt werden, um Therapiemöglichkeiten zu verbessern und unwirksame Therapien frühzeitiger zu identifizieren. Bei diesem neuartigen Datentyp sollen auch energieeffizientere Methoden zur Datenauswertung auf mobilen Geräten wie Laptop und Handy entwickelt werden. ',
},
@@ -490,6 +881,14 @@
_id: '29122004_ChristophLindemann_Hochschulwinterkursstartet_archiv',
llm_label: 0,
llm_persons: [],
+ pred_keywords: [
+ 'Hochschulwinterkurs',
+ 'DAAD',
+ 'Internationalisierung',
+ 'Deutschlandkunde',
+ 'Sprachunterricht',
+ 'Auslandsstudien',
+ ],
full_content:
'[29.12.2004] Im Januar und Februar 2005 findet auf dem Campus Essen der Universität Duisburg-Essen der Deutschlandkundliche Hochschulwinterkurs des Deutschen Akademischen Austausch Dienstes (DAAD) statt. An dem Kurs nehmen 48 Studenten aus Argentinien, Australien, Brasilien, Chile, Neuseeland und Südafrika teil. Sie erwartet ein intensives Unterrichtsprogramm mit Sprachunterricht und Seminaren zu Literatur, Politik und interkultureller Kommunikation. Bei fast täglichen Exkursionen lernen die Winterkursler außerdem viele Facetten von Essen und der Rhein-Ruhr-Region kennen. Der Hochschulwinterkurs wird seit 1998 regelmäßig in Essen veranstaltet, parallel findet er auch in Freiburg statt.\n\nDie Uni Duisburg-Essen beherbergt derzeit noch zahlreiche weitere ausländische Studenten. So betreut das Essener Institut für Kultur und Sprache (iks) im Rahmen einer Kooperation mit der II. Fremdsprachenhochschule in Peking 16 chinesische Germanistikstudenten. Bereits seit Oktober sind außerdem 20 Stipendiaten von DAAD und Stifterverband aus Osteuropa und der GUS an der Uni, die bis Februar neben dem Sprachstudium Essen und das Ruhrgebiet kennen lernen.\n\nHinweis für die en:\nZur offiziellen Begrüßung der Teilnehmer des Deutschlandkundlichen Hochschulwinterkurses durch Prorektor Professor Dr. Eckart Hasselbrink sind Sie herzlich eingeladen. Die Veranstaltung beginnt am Dienstag, 4. Januar 2005, um 10.30 Uhr im Glaspavillon der Universität Duisburg-Essen, Eingang R 12, Universitäts-/Ecke Gladbecker Straße.',
},
@@ -522,6 +921,37 @@
checklist.appendChild(row);
}
+ // Vorhergesagte Keywords als Chips anzeigen.
+ const chips = document.getElementById('keyword-chips');
+ chips.textContent = '';
+ if (record.pred_keywords.length === 0) {
+ const empty = document.createElement('span');
+ empty.className = 'kw-empty';
+ empty.textContent = 'Keine Keywords vorhergesagt.';
+ chips.appendChild(empty);
+ } else {
+ for (const keyword of record.pred_keywords) {
+ const chip = document.createElement('span');
+ chip.className = 'kw-chip';
+ chip.textContent = keyword;
+ chips.appendChild(chip);
+ }
+ }
+
+ // Abhak-Liste fuer Keywords: gute Keywords abhaken (Praezisions-Review).
+ const keywordChecklist = document.getElementById('keyword-checklist');
+ keywordChecklist.textContent = '';
+ for (const keyword of record.pred_keywords) {
+ const row = document.createElement('div');
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ const labelText = document.createElement('span');
+ labelText.textContent = ' ' + keyword;
+ row.appendChild(checkbox);
+ row.appendChild(labelText);
+ keywordChecklist.appendChild(row);
+ }
+
// textContent -> kein HTML-/Markdown-Parsing, reiner Text aus dem JSON.
document.getElementById('content').textContent = record.full_content;
diff --git a/service/README.md b/service/README.md
index ca09165c..25961c24 100644
--- a/service/README.md
+++ b/service/README.md
@@ -15,3 +15,34 @@ This mounts the source directory into the container and enables uvicorn hot-relo
## Testing
Run tests: `./gradlew :service:test`
+
+## Scripts
+
+### index_org_patents.py
+
+Builds the `org_patents` Elasticsearch index for a given institution: fetches its
+OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee
+and/or inventor name, and reindexes. Each patent is tagged with a `match_type`
+(`institution`, `name`, or `both`, the latter being highest confidence). For common
+inventor names, a name match is only kept if the assignee is the institution itself or
+the person, to avoid pulling in unrelated patents via a shared name.
+
+```bash
+python scripts/index_org_patents.py --institution-id
+```
+
+**Example — University of Duisburg-Essen:**
+
+```bash
+python scripts/index_org_patents.py --institution-id I62318514
+```
+
+The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`.
+
+**Runtime:** ~30–40 minutes for large institutions (author count is the main driver).
+Re-running is safe — existing documents for the institution are deleted (via search +
+`_bulk` delete-by-id, not `_delete_by_query`, which the patent-cluster API key rejects)
+before reindexing, so stale documents don't linger.
+
+**Note:** This script is intended to be integrated into an Admin Panel in a later sprint,
+so that organisation admins can trigger the indexing as a background job via the UI.
diff --git a/service/scripts/build_patents_openalex_keywords.py b/service/scripts/build_patents_openalex_keywords.py
new file mode 100644
index 00000000..606660a3
--- /dev/null
+++ b/service/scripts/build_patents_openalex_keywords.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""
+build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
+
+Fetches IPC/CPC metadata from the `ipc` index, matches labels against OpenAlex topics
+(from topic_hierarchy_cache.json) and keywords (from openalex-topics) using
+SentenceTransformer embeddings, then writes results to the patents_openalex_keywords
+Elasticsearch index and a local JSON backup.
+
+Usage:
+ python scripts/build_patents_openalex_keywords.py
+ python scripts/build_patents_openalex_keywords.py --top-k 3 --min-score 0.55
+ python scripts/build_patents_openalex_keywords.py --levels section class subclass
+ python scripts/build_patents_openalex_keywords.py --skip-keywords
+
+Requires src/main/inse/.env with PATENT_ELASTICSEARCH credentials (INSE) and, unless
+--skip-keywords is set, NES Elasticsearch credentials for openalex-topics.
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+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 inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
+from inse.patents.patents_openalex_keywords.ipc_entries import (
+ DEFAULT_BUILD_LEVELS,
+ fetch_unique_ipc_entries,
+)
+from inse.patents.patents_openalex_keywords.matching import (
+ TopicVectorsMatcher,
+ build_documents_from_topicvectors,
+ documents_to_json_mapping,
+)
+
+logger = logging.getLogger(__name__)
+
+
+async def run(args: argparse.Namespace) -> None:
+ levels = tuple(args.levels)
+
+ ipc_entries = await fetch_unique_ipc_entries(levels=levels)
+ counts = {level: len(ipc_entries.get(level, {})) for level in levels}
+ logger.info("Fetched unique IPC/CPC symbols: %s", counts)
+
+ if args.skip_keywords:
+ logger.info("--skip-keywords is ignored in topicvectors mode")
+ if args.topic_cache:
+ logger.info("--topic-cache is ignored in topicvectors mode")
+ if args.batch_size != 64:
+ logger.info("--batch-size is ignored in topicvectors mode")
+
+ matcher = TopicVectorsMatcher(min_score=args.min_score)
+ logger.info("Matching IPC/CPC labels against topicvectors index...")
+ documents = await build_documents_from_topicvectors(
+ ipc_entries, matcher, levels=levels, top_k=args.top_k
+ )
+ logger.info("Built %d IPC/CPC mapping documents", len(documents))
+
+ if args.output:
+ output_path = Path(args.output)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ mapping = documents_to_json_mapping(documents)
+ output_path.write_text(
+ json.dumps(mapping, indent=2, ensure_ascii=True),
+ encoding="utf-8",
+ )
+ logger.info("Wrote local JSON backup to %s", output_path)
+
+ if not args.dry_run:
+ client = PatentsOpenAlexKeywordsClient(timeout=60.0)
+ await client.ensure_index()
+ await client.bulk_index(documents)
+ logger.info("Indexed %d documents into patents_openalex_keywords", len(documents))
+ else:
+ logger.info("Dry run — skipped Elasticsearch indexing")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ description="Build IPC/CPC → OpenAlex topic/keyword matches with SentenceTransformer.",
+ )
+ parser.add_argument(
+ "--output",
+ default=str(
+ current_dir.parent / "src" / "data" / "patents_openalex_keywords_mapping.json"
+ ),
+ help="Local JSON backup path",
+ )
+ parser.add_argument(
+ "--topic-cache",
+ default=None,
+ help="Deprecated in topicvectors mode (kept for CLI compatibility)",
+ )
+ parser.add_argument(
+ "--levels",
+ nargs="+",
+ default=list(DEFAULT_BUILD_LEVELS),
+ choices=list(DEFAULT_BUILD_LEVELS),
+ help="IPC/CPC hierarchy levels to map",
+ )
+ parser.add_argument(
+ "--top-k",
+ type=int,
+ default=3,
+ help="Number of top topic/keyword matches per IPC/CPC code",
+ )
+ parser.add_argument(
+ "--min-score",
+ type=float,
+ default=0.5,
+ help="Minimum cosine similarity for a match",
+ )
+ parser.add_argument(
+ "--batch-size",
+ type=int,
+ default=64,
+ help="Deprecated in topicvectors mode (kept for CLI compatibility)",
+ )
+ parser.add_argument(
+ "--skip-keywords",
+ action="store_true",
+ help="Deprecated in topicvectors mode (kept for CLI compatibility)",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Build matches locally without indexing into Elasticsearch",
+ )
+ args = parser.parse_args()
+
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
+ asyncio.run(run(args))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/service/scripts/index_org_patents.py b/service/scripts/index_org_patents.py
index 7eb03cef..f315f2f9 100644
--- a/service/scripts/index_org_patents.py
+++ b/service/scripts/index_org_patents.py
@@ -1,5 +1,23 @@
#!/usr/bin/env python3
-"""Index org_patents for an institution."""
+"""
+index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
+
+Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for
+patents matched via institution assignee and/or author name (match_type: "institution",
+"name", or "both"), deletes existing documents for the institution, and reindexes.
+
+Usage:
+ python scripts/index_org_patents.py --institution-id
+
+Example (University of Duisburg-Essen):
+ python scripts/index_org_patents.py --institution-id I62318514
+
+Requires src/main/inse/.env with PATENT_ELASTICSEARCH_URL/API_KEY (and OpenAlex ES
+credentials for author lookup). Runtime scales with author count (~30-40 min for UDE's
+4,740 authors). Re-running is safe: existing documents are deleted before reindexing.
+
+Future: integrate into an Admin Panel so admins can trigger this via the UI.
+"""
from __future__ import annotations
import argparse
@@ -22,16 +40,21 @@ logger = logging.getLogger(__name__)
async def main() -> None:
- parser = argparse.ArgumentParser(description="Index org_patents for an institution.")
+ parser = argparse.ArgumentParser(
+ description="Build the org_patents index for one institution.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="Example: python scripts/index_org_patents.py --institution-id I62318514",
+ )
parser.add_argument(
"--institution-id",
required=True,
- help="OpenAlex institution ID, e.g. I62318514",
+ help="OpenAlex institution ID, e.g. I62318514 (University of Duisburg-Essen)",
)
args = parser.parse_args()
+ logger.info("Starting org_patents indexing for institution %s ...", args.institution_id)
count = await index_org_patents_for_institution(args.institution_id)
- logger.info("Finished indexing %d patents for institution %s", count, args.institution_id)
+ logger.info("Done. Indexed %d patents for institution %s.", count, args.institution_id)
if __name__ == "__main__":
diff --git a/service/src/main/inse/account_management/model.py b/service/src/main/inse/account_management/model.py
index 2bb7613d..8b21edf7 100644
--- a/service/src/main/inse/account_management/model.py
+++ b/service/src/main/inse/account_management/model.py
@@ -20,6 +20,7 @@ class AccountProfile(BaseModel):
organization_id: uuid.UUID
organization_name: str
deleted: bool
+ activated: bool
is_current: bool = False
is_real_account: bool = False
is_impersonating: bool = False
@@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel):
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
+ activated: Optional[bool] = None
diff --git a/service/src/main/inse/account_management/router.py b/service/src/main/inse/account_management/router.py
index 82781fb0..81b22593 100644
--- a/service/src/main/inse/account_management/router.py
+++ b/service/src/main/inse/account_management/router.py
@@ -1,12 +1,11 @@
import uuid
-from typing import Optional
+from typing import Annotated, Optional
-from fastapi import APIRouter, Depends, Query, Response, status
-from sqlmodel import Session
+from fastapi import APIRouter, Query, Response, status
from inse.auth import service as auth_service
-from inse.auth.model import AccessToken
-from inse.database import get_session
+from inse.auth.model import AccessTokenMetadata
+from inse.database import SessionDep
from inse.tags import Tags
from . import service
@@ -24,11 +23,10 @@ router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
@router.get(
"/me",
operation_id="getCurrentAccount",
- response_model=AccountProfile,
)
async def get_current_account(
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token)
@@ -36,16 +34,15 @@ async def get_current_account(
@router.get(
"",
operation_id="listAccounts",
- response_model=AccountPage,
)
async def list_accounts(
- page: int = Query(default=0, ge=0),
- page_size: int = Query(default=25, ge=1, le=100),
- offset: Optional[int] = Query(default=None, ge=0),
- search: Optional[str] = Query(default=None),
- organization_id: Optional[uuid.UUID] = Query(default=None),
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ page: Annotated[int, Query(ge=0)] = 0,
+ page_size: Annotated[int, Query(ge=1, le=100)] = 10,
+ offset: Annotated[int, Query(ge=0)] = 0,
+ search: Annotated[Optional[str], Query()] = None,
+ organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage:
return service.list_accounts(
session=session,
@@ -61,13 +58,12 @@ async def list_accounts(
@router.post(
"",
operation_id="createAccount",
- response_model=AccountProfile,
status_code=status.HTTP_201_CREATED,
)
async def create_account(
payload: CreateAccountRequest,
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.create_account(
session=session,
@@ -79,11 +75,10 @@ async def create_account(
@router.get(
"/organizations",
operation_id="listAccountOrganizations",
- response_model=list[OrganizationProfile],
)
async def list_organizations(
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token)
@@ -91,13 +86,12 @@ async def list_organizations(
@router.put(
"/{account_id}",
operation_id="updateAccount",
- response_model=AccountProfile,
)
async def update_account(
account_id: uuid.UUID,
payload: UpdateAccountRequest,
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountProfile:
return service.update_account(
session=session,
@@ -114,8 +108,8 @@ async def update_account(
)
async def delete_account(
account_id: uuid.UUID,
- session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ session: SessionDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_account(
session=session,
diff --git a/service/src/main/inse/account_management/service.py b/service/src/main/inse/account_management/service.py
index 5ef45372..b9d9dfda 100644
--- a/service/src/main/inse/account_management/service.py
+++ b/service/src/main/inse/account_management/service.py
@@ -5,7 +5,7 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
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 (
AccountPage,
@@ -28,7 +28,7 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
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 ""
return AccountProfile(
id=account.id,
@@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
+ activated=account.activated,
is_current=account.id == token.effective_account_id,
is_real_account=account.id == token.real_account_id,
is_impersonating=token.is_impersonating(),
@@ -54,7 +55,7 @@ def _get_account_or_404(session: Session, account_id: uuid.UUID) -> 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:
return
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)
return _account_to_profile(account, access_token)
def list_accounts(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
page: int,
page_size: int,
offset: Optional[int] = None,
search: Optional[str] = None,
organization_id: Optional[uuid.UUID] = None,
) -> 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(
status_code=status.HTTP_403_FORBIDDEN,
- detail="Only admins can list accounts.",
+ detail="Only managers and admins can list accounts.",
)
statement = select(Account)
count_statement = select(func.count()).select_from(Account)
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)
elif organization_id is not None:
filters.append(Account.organization_id == organization_id)
@@ -152,7 +157,7 @@ def list_accounts(
def create_account(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
payload: CreateAccountRequest,
) -> AccountProfile:
if not _is_admin(access_token.effective_role):
@@ -202,12 +207,12 @@ def create_account(
def list_organizations(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
select(Organization)
- .where(Organization.deleted == False) # noqa: E712
+ .where(Organization.deleted.is_not(True))
.order_by(Organization.name)
).all()
elif access_token.effective_role == UserRole.ADMIN:
@@ -228,7 +233,7 @@ def list_organizations(
def update_account(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
account_id: uuid.UUID,
payload: UpdateAccountRequest,
) -> AccountProfile:
@@ -285,6 +290,15 @@ def update_account(
account.deleted = payload.deleted
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.commit()
session.refresh(account)
@@ -293,7 +307,7 @@ def update_account(
def delete_account(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
account_id: uuid.UUID,
) -> None:
account = _get_account_or_404(session, account_id)
diff --git a/service/src/main/inse/account_management/test_service.py b/service/src/main/inse/account_management/test_service.py
new file mode 100644
index 00000000..b6d43714
--- /dev/null
+++ b/service/src/main/inse/account_management/test_service.py
@@ -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"]
diff --git a/service/src/main/inse/auth/model.py b/service/src/main/inse/auth/model.py
index a79aa113..4848cb78 100644
--- a/service/src/main/inse/auth/model.py
+++ b/service/src/main/inse/auth/model.py
@@ -4,6 +4,7 @@ from enum import StrEnum
from typing import List
from pydantic import BaseModel
+from sqlalchemy import UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
@@ -15,9 +16,14 @@ class UserRole(StrEnum):
class TokenType(StrEnum):
- ID_TOKEN = "ID"
- REFRESH_TOKEN = "REFRESH"
- ACCESS_TOKEN = "ACCESS"
+ ID_TOKEN = "ID_TOKEN"
+ REFRESH_TOKEN = "REFRESH_TOKEN"
+ ACCESS_TOKEN = "ACCESS_TOKEN"
+
+
+class SecretPurpose(StrEnum):
+ LOGIN_OTK = "LOGIN_OTK"
+ PASSWORD_RESET = "PASSWORD_RESET"
class Durable(SQLModel):
@@ -77,6 +83,12 @@ class Account(Durable, table=True):
nullable=False,
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(
index=False,
nullable=False,
@@ -100,6 +112,9 @@ class Account(Durable, table=True):
class Secret(SQLModel, table=True):
+ __table_args__ = (
+ UniqueConstraint("account_id", "purpose", name="uq_secret_account_purpose"),
+ )
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
@@ -107,10 +122,16 @@ class Secret(SQLModel, table=True):
)
account_id: uuid.UUID = Field(
foreign_key="account.id",
- unique=True, # Ensure that each account can have only one associated secret
+ index=True,
nullable=False,
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(
index=False,
nullable=False,
@@ -121,39 +142,32 @@ class Secret(SQLModel, table=True):
nullable=False,
description="The timestamp indicating when the secret will expire.",
)
-
-
-class Token(BaseModel):
- token_type: TokenType = Field(
- description="The type of the token (ID, Refresh, or Access).",
- )
- real_account_id: uuid.UUID = Field(
+ request_count: int = Field(
+ default=0,
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.",
)
expires_at: datetime = Field(
- index=True,
- nullable=False,
description="The timestamp indicating when the token will expire.",
)
epoch: int = Field(
default=0,
- nullable=False,
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(
default=TokenType.ID_TOKEN,
const=True,
@@ -161,24 +175,23 @@ class IdToken(Token):
)
-class AccessToken(Token):
+class AccessTokenMetadata(BaseTokenData):
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
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(
- 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.",
)
effective_role: UserRole = Field(
default=UserRole.USER,
- index=True,
- nullable=False,
description="The specific role this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
- nullable=False,
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
-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(
default=TokenType.REFRESH_TOKEN,
const=True,
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):
- 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):
access_token: AccessToken = Field(
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."
)
diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py
index 2ce4f52a..581d714b 100644
--- a/service/src/main/inse/auth/router.py
+++ b/service/src/main/inse/auth/router.py
@@ -12,9 +12,11 @@ from inse.database import SessionDep, get_session
from inse.auth.model import (
AccessResponse,
AccessToken,
- IdToken,
+ AccessTokenMetadata,
+ IdTokenMetadata,
LoginResponse,
- RefreshToken,
+ OtkResponse,
+ RefreshTokenMetadata,
)
logger = logging.getLogger(__name__)
@@ -40,10 +42,50 @@ async def request_otk(
session: SessionDep,
email: Annotated[str, Body(description="User's email address")],
password: Annotated[str, Body(description="User's password")],
-):
+) -> OtkResponse:
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(
"/login",
summary="Login with One-Time Key",
@@ -80,7 +122,7 @@ async def get_action_tokens(
effective_account_id: Annotated[
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:
logger.debug(
"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(
+ response: Response,
refresh_token: Annotated[
- RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
+ RefreshTokenMetadata, auth_service.CurrentUserRefreshTokenPayloadDep
],
) -> 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(
@@ -125,7 +170,7 @@ async def refresh_access_token(
async def logout(
session: Annotated[Session, Depends(get_session)],
access_token: Annotated[
- AccessToken,
+ AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
@@ -150,7 +195,7 @@ async def change_password(
Body(description="New password", min_length=8),
],
access_token: Annotated[
- AccessToken,
+ AccessTokenMetadata,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py
index 0af15a4b..7c1d74d4 100644
--- a/service/src/main/inse/auth/service.py
+++ b/service/src/main/inse/auth/service.py
@@ -4,35 +4,42 @@ import json
import logging
import secrets
import uuid
-from typing import Annotated, Any, Dict, Literal, Optional
+from typing import Annotated, Any, Dict, Optional
import jwt
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
-from fastapi import Depends, HTTPException, Request, Response, status
+from fastapi import Cookie, Depends, HTTPException, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+from sqlmodel import Session, func, select
+
+from inse.auth.email_service import send_email
from inse.auth.model import (
AccessResponse,
AccessToken,
+ AccessTokenMetadata,
Account,
- IdToken,
+ IdTokenMetadata,
LoginResponse,
Organization,
- RefreshToken,
+ OtkResponse,
+ RefreshTokenMetadata,
Secret,
+ SecretPurpose,
TokenType,
UserRole,
)
from inse.config import get_settings
from inse.database import get_session
-from sqlmodel import Session, select, func
-from inse.auth.email_service import send_email
-ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days
-REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes
-ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes
+ID_TOKEN_EXPIRATION_MINUTES = 30 * 24 * 60 # 30 days
+REFRESH_TOKEN_EXPIRATION_MINUTES = 1 * 24 * 60 # 1 day
+ACCESS_TOKEN_EXPIRATION_MINUTES = 30 # 30 minutes
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
+PASSWORD_RESET_EXPIRATION_MINUTES = 5 # 5 minutes
+PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES = 5 # 5 minutes
+PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
REAL_ACCOUNT_ID_KEY = "real_account_id"
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
@@ -41,8 +48,11 @@ EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
-ID_FP_COOKIE_KEY = "_Secure-Fgp-ID"
-ACT_FP_COOKIE_KEY = "_Secure-Fgp-Act"
+
+ACCESS_FP_COOKIE_KEY = "_Secure-Fgp-Acc"
+ID_TOKEN_COOKIE_KEY = "id_token"
+REFRESH_TOKEN_COOKIE_KEY = "refresh_token"
+
settings = get_settings()
@@ -155,6 +165,31 @@ def _verify_password(password: str, password_hash: str) -> bool:
return False
+def _hash_reset_token(reset_token: str) -> str:
+ """Hashes a high-entropy password reset token for storage.
+
+ Args:
+ reset_token (str): The raw reset token sent to the user.
+
+ Returns:
+ str: SHA-256 hash of the reset token.
+ """
+ return hashlib.sha256(reset_token.encode("utf-8")).hexdigest()
+
+
+def _build_password_reset_link(reset_token: str) -> str:
+ """Builds the password reset link that will be sent to the user.
+
+ Args:
+ reset_token (str): The raw reset token to include in the link.
+
+ Returns:
+ str: The full password reset link.
+ """
+ separator = "&" if "?" in settings.password_reset_url else "?"
+ return f"{settings.password_reset_url}{separator}token={reset_token}"
+
+
def request_otk(session: Session, email: str, password: str):
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
@@ -196,10 +231,22 @@ def request_otk(session: Session, email: str, password: str):
detail="Invalid email or password",
)
+ if not account.activated:
+ logger.warning("OTK request rejected for deactivated account %s", account.id)
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Account is deactivated and cannot log in.",
+ )
+
otk_code = f"{secrets.randbelow(1_000_000):06d}"
print(otk_code)
- secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
+ secret = session.exec(
+ select(Secret).where(
+ Secret.account_id == account.id,
+ Secret.purpose == SecretPurpose.LOGIN_OTK,
+ )
+ ).first()
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=OTK_EXPIRATION_MINUTES
@@ -208,6 +255,7 @@ def request_otk(session: Session, email: str, password: str):
if secret is None:
secret = Secret(
account_id=account.id,
+ purpose=SecretPurpose.LOGIN_OTK,
secret_value=otk_code,
expires_at=expires_at,
)
@@ -236,7 +284,211 @@ def request_otk(session: Session, email: str, password: str):
else:
logger.info("OTK generated for account %s", account.id)
- return {"status": "ok", "account_id": str(account.id)}
+ return OtkResponse(status="success", account_id=account.id)
+
+
+def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
+ """Requests a one-time password reset link for the given email address.
+
+ For security reasons, this function always returns a successful response and
+ does not reveal whether the email address belongs to an active account.
+ """
+ email = email.lower().strip()
+ now = datetime.datetime.now(datetime.timezone.utc)
+
+ account = session.exec(
+ select(Account).where(
+ Account.email == email,
+ Account.deleted == False, # noqa: E712
+ )
+ ).first()
+
+ if account is None or account.deleted or account.id is None:
+ logger.info("Password reset requested for unknown email %s", email)
+ return {
+ "status": "ok",
+ "reset_link_created": False,
+ "rate_limited": False,
+ }
+
+ secret = session.exec(
+ select(Secret).where(
+ Secret.account_id == account.id,
+ Secret.purpose == SecretPurpose.PASSWORD_RESET,
+ )
+ ).first()
+
+ if secret is not None:
+ if secret.request_window_started_at is not None:
+ window_started_at = secret.request_window_started_at
+ if getattr(window_started_at, "tzinfo", None) is None:
+ window_started_at = window_started_at.replace(
+ tzinfo=datetime.timezone.utc
+ )
+
+ window_ends_at = window_started_at + datetime.timedelta(
+ minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
+ )
+
+ if window_ends_at > now:
+ if secret.request_count >= PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW:
+ retry_after_seconds = max(
+ 0,
+ int((window_ends_at - now).total_seconds()),
+ )
+
+ logger.info(
+ "Password reset request rate-limited for account %s.",
+ account.id,
+ )
+ return {
+ "status": "ok",
+ "reset_link_created": False,
+ "rate_limited": True,
+ "retry_after_seconds": retry_after_seconds,
+ }
+ else:
+ secret.request_count = 0
+ secret.request_window_started_at = now
+ else:
+ secret.request_count = 0
+ secret.request_window_started_at = now
+
+ reset_token = secrets.token_urlsafe(32)
+ reset_token_hash = _hash_reset_token(reset_token)
+
+ expires_at = now + datetime.timedelta(minutes=PASSWORD_RESET_EXPIRATION_MINUTES)
+
+ if secret is None:
+ secret = Secret(
+ account_id=account.id,
+ purpose=SecretPurpose.PASSWORD_RESET,
+ secret_value=reset_token_hash,
+ expires_at=expires_at,
+ request_count=1,
+ request_window_started_at=now,
+ )
+ session.add(secret)
+ else:
+ secret.secret_value = reset_token_hash
+ secret.expires_at = expires_at
+ secret.request_count += 1
+
+ if secret.request_window_started_at is None:
+ secret.request_window_started_at = now
+
+ session.commit()
+
+ reset_link = _build_password_reset_link(reset_token)
+
+ if settings.send_password_reset_email:
+ try:
+ send_email(
+ recipient=account.email,
+ subject="Reset your SmartGUIDE password",
+ body=(
+ "Use the following link to reset your SmartGUIDE password:\n"
+ f"{reset_link}\n\n"
+ f"This link expires in {PASSWORD_RESET_EXPIRATION_MINUTES} minutes."
+ ),
+ smtp_server=settings.smtp_server,
+ smtp_port=settings.smtp_port,
+ sender=settings.smtp_sender,
+ username=settings.smtp_username,
+ password=settings.smtp_password,
+ use_tls=settings.smtp_use_tls,
+ )
+ logger.info("Sent password reset email for account %s", account.id)
+ except Exception:
+ if settings.environment == "dev":
+ logger.exception(
+ "Failed to send password reset email for account %s. "
+ "Falling back to console reset link.",
+ account.id,
+ )
+ logger.info(
+ "Password reset link for account %s: %s",
+ account.id,
+ reset_link,
+ )
+ else:
+ raise
+ elif settings.environment == "dev":
+ logger.info("Password reset link for account %s: %s", account.id, reset_link)
+ else:
+ logger.info("Password reset token generated for account %s", account.id)
+
+ return {
+ "status": "ok",
+ "reset_link_created": True,
+ "rate_limited": False,
+ }
+
+
+def reset_password(
+ session: Session,
+ reset_token: str,
+ new_password: str,
+) -> Dict[str, str]:
+ """Resets an account password using a one-time password reset token.
+
+ Args:
+ session (Session): The database session used to query the account and secret.
+ reset_token (str): The raw reset token from the password reset link.
+ new_password (str): The new password to store for the account.
+
+ Raises:
+ HTTPException: If the reset token is invalid or expired.
+
+ Returns:
+ Dict[str, str]: A status response.
+ """
+ now = datetime.datetime.now(datetime.timezone.utc)
+ reset_token_hash = _hash_reset_token(reset_token.strip())
+
+ secret = session.exec(
+ select(Secret).where(
+ Secret.purpose == SecretPurpose.PASSWORD_RESET,
+ Secret.secret_value == reset_token_hash,
+ )
+ ).first()
+
+ if secret is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or expired password reset token",
+ )
+
+ secret_expires = secret.expires_at
+ if getattr(secret_expires, "tzinfo", None) is None:
+ secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
+
+ if secret_expires <= now:
+ session.delete(secret)
+ session.commit()
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or expired password reset token",
+ )
+
+ account = session.get(Account, secret.account_id)
+
+ if account is None or account.deleted or account.id is None:
+ session.delete(secret)
+ session.commit()
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid or expired password reset token",
+ )
+
+ account.password_hash = _hash_password(new_password)
+ account.epoch += 1
+
+ session.add(account)
+ session.delete(secret)
+ session.commit()
+
+ return {"status": "ok"}
def login(
@@ -262,6 +514,7 @@ def login(
secret = session.exec(
select(Secret).where(
Secret.account_id == account_id,
+ Secret.purpose == SecretPurpose.LOGIN_OTK,
Secret.secret_value == email_code,
# Validating the code and ensuring it matches the account ID
)
@@ -300,7 +553,7 @@ def login(
)
account = _get_active_account(session, account_id)
- if not account or account.deleted or account.id is None:
+ if not account or account.deleted or not account.activated or account.id is None:
logger.warning("Login failed: account is not active %s", account_id)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -320,9 +573,9 @@ def login(
def _get_current_user_access_token_payload(
session: Annotated[Session, Depends(get_session)],
- request: Request,
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
-) -> AccessToken:
+ secure_fgp: Annotated[str | None, Cookie(alias=ACCESS_FP_COOKIE_KEY)] = None,
+) -> AccessTokenMetadata:
"""Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args:
@@ -333,18 +586,22 @@ def _get_current_user_access_token_payload(
Returns:
AccessToken: The verified access token payload.
"""
+ if secure_fgp is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Access fingerprint cookie is missing",
+ )
token = credentials.credentials
- access_token_payload = _verify_fp_token(
- request=request,
- cookie_key=ACT_FP_COOKIE_KEY,
- token=token,
+ access_token_payload = _verify_access_token_fp(
+ secure_fgp=secure_fgp,
+ raw_access_token=token,
session=session,
)
# If reaches here, the access token is valid and the fingerprint matches
- return AccessToken(
+ return AccessTokenMetadata(
real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
@@ -356,15 +613,13 @@ def _get_current_user_access_token_payload(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
user_fingerprint_hash=access_token_payload[USER_FINGERPRINT_HASH_KEY],
- raw_token=token,
)
def _get_current_user_refresh_token_payload(
session: Annotated[Session, Depends(get_session)],
- request: Request,
- credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
-) -> RefreshToken:
+ token: Annotated[str | None, Cookie(alias=REFRESH_TOKEN_COOKIE_KEY)] = None,
+) -> RefreshTokenMetadata:
"""Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args:
@@ -373,18 +628,20 @@ def _get_current_user_refresh_token_payload(
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token.
Returns:
- RefreshToken: The verified refresh token payload.
+ RefreshTokenData: The verified refresh token payload.
"""
- token = credentials.credentials
+ if token is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Refresh token cookie is missing",
+ )
- refresh_token_payload = _verify_fp_token(
- request=request,
- cookie_key=ACT_FP_COOKIE_KEY,
- token=token,
+ refresh_token_payload = _verify_refresh_token(
+ raw_refresh_token=token,
session=session,
)
# If reaches here, the refresh token is valid and the fingerprint matches
- refresh_token = RefreshToken(
+ refresh_token = RefreshTokenMetadata(
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
@@ -395,8 +652,6 @@ def _get_current_user_refresh_token_payload(
effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
- user_fingerprint_hash=refresh_token_payload[USER_FINGERPRINT_HASH_KEY],
- raw_token=token,
)
logger.debug("Extracted refresh token payload: %s", refresh_token)
@@ -406,9 +661,8 @@ def _get_current_user_refresh_token_payload(
def _get_current_user_id_token_payload(
session: Annotated[Session, Depends(get_session)],
- request: Request,
- credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
-) -> IdToken:
+ token: Annotated[str | None, Cookie(alias=ID_TOKEN_COOKIE_KEY)] = None,
+) -> IdTokenMetadata:
"""Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
Args:
@@ -419,30 +673,24 @@ def _get_current_user_id_token_payload(
Returns:
IdToken: The verified ID token payload.
"""
- logger.debug(
- "Verifying ID token for request %s with credentials %s",
- request.url,
- credentials,
- )
- token = credentials.credentials
- logger.debug("Verifying ID token for request %s with token %s", request.url, token)
+ if token is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="ID token cookie is missing",
+ )
- id_token_payload = _verify_fp_token(
- request=request,
- cookie_key=ID_FP_COOKIE_KEY,
- token=token,
+ id_token_payload = _verify_id_token(
+ raw_id_token=token,
session=session,
)
# If reaches here, the ID token is valid and the fingerprint matches
- return IdToken(
+ return IdTokenMetadata(
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
id_token_payload["exp"], tz=datetime.timezone.utc
),
epoch=id_token_payload[EPOCH_KEY],
- user_fingerprint_hash=id_token_payload[USER_FINGERPRINT_HASH_KEY],
- raw_token=token,
)
@@ -469,7 +717,12 @@ def _get_account_epoch(
"""
account = session.get(Account, account_id)
- if account is None or account.deleted or account.id is None:
+ if (
+ account is None
+ or account.deleted
+ or not account.activated
+ or account.id is None
+ ):
raise AccountNotFoundException
return account.epoch
@@ -487,7 +740,7 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
"""
account = session.get(Account, account_id)
- if not account or account.deleted or account.id is None:
+ if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.role
@@ -505,7 +758,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
"""
account = session.get(Account, account_id)
- if not account or account.deleted or account.id is None:
+ if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.organization_id
@@ -525,12 +778,18 @@ def _is_valid_impersonation(
bool: True if impersonation is allowed, False otherwise.
"""
real_account = session.get(Account, real_account_id)
- if not real_account or real_account.deleted or real_account.id is None:
+ if (
+ not real_account
+ or real_account.deleted
+ or not real_account.activated
+ or real_account.id is None
+ ):
raise AccountNotFoundException
effective_account = session.get(Account, effective_account_id)
if (
not effective_account
or effective_account.deleted
+ or not effective_account.activated
or effective_account.id is None
):
raise AccountNotFoundException
@@ -560,26 +819,10 @@ def _is_valid_impersonation(
def get_access_token(
response: Response,
session: Session,
- id_token: IdToken,
+ id_token: IdTokenMetadata,
real_account_id: uuid.UUID,
effective_account_id: Optional[uuid.UUID] = None,
) -> AccessResponse:
- """Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies.
-
- Args:
- request (Request): The FastAPI request object containing the cookies.
- response (Response): The FastAPI response object to which the cookies will be added.
- id_token (str): The ID token to verify.
- real_account_id (uuid.UUID): The unique identifier of the real account associated with this token.
- effective_account_id (Optional[uuid.UUID], optional): The unique identifier of the effective account associated with this token. If not provided, it defaults to the real account ID.
-
- Raises:
- HTTPException: If the ID token is invalid, expired, or does not match the real account ID.
- HTTPException: If impersonation is not allowed.
-
- Returns:
- AccessResponse: An object containing the generated access and refresh tokens.
- """
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
if real_account_id != id_token.real_account_id:
@@ -594,16 +837,15 @@ def get_access_token(
if effective_account_id is None:
effective_account_id = real_account_id
- elif effective_account_id != real_account_id:
- if not _is_valid_impersonation(
- session=session,
- real_account_id=real_account_id,
- effective_account_id=effective_account_id,
- ):
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Impersonation not allowed",
- )
+ elif effective_account_id != real_account_id and not _is_valid_impersonation(
+ session=session,
+ real_account_id=real_account_id,
+ effective_account_id=effective_account_id,
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Impersonation not allowed",
+ )
role = _get_account_role(session=session, account_id=effective_account_id)
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
@@ -611,7 +853,7 @@ def get_access_token(
session=session, account_id=effective_account_id
)
- user_fingerprint_hash = _set_act_fp_cookie(response=response)
+ user_fingerprint_hash = _set_access_fp_cookie(response=response)
access_token = _build_access_token(
real_account_id=real_account_id,
@@ -621,77 +863,96 @@ def get_access_token(
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
)
- refresh_token = _build_refresh_token(
+ _set_refresh_token(
+ response=response,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
effective_role=role,
effective_organization_id=organization_id,
epoch=epoch,
- user_fingerprint_hash=user_fingerprint_hash,
)
return AccessResponse(
access_token=access_token,
- refresh_token=refresh_token,
)
-def _set_id_fp_cookie(response: Response) -> str:
- """Sets a secure fingerprint cookie for ID tokens and returns the hashed value of the fingerprint.
+def _set_id_token_cookie(response: Response, raw_id_token: str) -> None:
+ """Sets a secure cookie for the ID token.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
-
- Returns:
- str: The hashed value of the fingerprint.
+ raw_id_token (str): The raw string representation of the ID token.
"""
- return _set_fingerprint_cookie(
- response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60
+ _set_token_cookie(
+ response=response,
+ cookie_name=ID_TOKEN_COOKIE_KEY,
+ token=raw_id_token,
+ max_age=ID_TOKEN_EXPIRATION_MINUTES * 60,
)
-def _set_act_fp_cookie(response: Response) -> str:
+def _set_refresh_token_cookie(response: Response, raw_refresh_token: str) -> None:
+ """Sets a secure cookie for the refresh token.
+
+ Args:
+ response (Response): The FastAPI response object to which the cookie will be added.
+ raw_refresh_token (str): The raw string representation of the refresh token.
+ """
+ _set_token_cookie(
+ response=response,
+ cookie_name=REFRESH_TOKEN_COOKIE_KEY,
+ token=raw_refresh_token,
+ max_age=REFRESH_TOKEN_EXPIRATION_MINUTES * 60,
+ )
+
+
+def _set_token_cookie(
+ response: Response, cookie_name: str, token: str, max_age: int
+) -> None:
+ """Sets a secure cookie for the specified token.
+
+ Args:
+ response (Response): The FastAPI response object to which the cookie will be added.
+ cookie_name (str): The name of the cookie to set.
+ token (str): The raw string representation of the token.
+ max_age (int): The maximum age of the cookie in seconds.
+ """
+ secure = False if settings.environment == "dev" else True
+ response.set_cookie(
+ key=cookie_name,
+ value=token,
+ httponly=True,
+ secure=secure,
+ samesite="strict",
+ max_age=max_age,
+ )
+
+
+def _set_access_fp_cookie(response: Response) -> str:
"""Sets a secure fingerprint cookie for access tokens and returns the hashed value of the fingerprint.
Args:
response (Response): The FastAPI response object to which the cookie will be added.
- Returns:
- str: The hashed value of the fingerprint.
- """
- return _set_fingerprint_cookie(
- response, ACT_FP_COOKIE_KEY
- ) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed.
-
-
-def _set_fingerprint_cookie(
- response: Response,
- key: Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"],
- max_age: Optional[int] = None,
-) -> str:
- """Sets a secure fingerprint cookie and returns the hashed value of the fingerprint.
-
- Args:
- response (Response): The FastAPI response object to which the cookie will be added.
- key (Literal["__Secure-Fgp-ID", "__Secure-Fgp-Act"]): The name of the cookie to set.
- max_age (Optional[int], optional): The maximum age of the cookie in seconds. Defaults to None.
-
Returns:
str: The hashed value of the fingerprint.
"""
user_fingerprint = secrets.token_hex(50)
secure = False if settings.environment == "dev" else True
response.set_cookie(
- key=key,
+ key=ACCESS_FP_COOKIE_KEY,
value=user_fingerprint,
httponly=True,
secure=secure,
samesite="strict",
- max_age=max_age,
+ max_age=None, # Setting no max age to make it a session cookie, which will be deleted when the browser is closed.
)
return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest()
-def refresh_access_token(refresh_token: RefreshToken) -> AccessToken:
+def refresh_access_token(
+ response: Response, refresh_token: RefreshTokenMetadata
+) -> AccessToken:
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
Args:
@@ -704,25 +965,7 @@ def refresh_access_token(refresh_token: RefreshToken) -> AccessToken:
"""
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
- return _refresh_access_token(
- refresh_token=refresh_token,
- )
-
-
-def _refresh_access_token(
- refresh_token: RefreshToken,
-) -> AccessToken:
- """Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
-
- Args:
- request (Request): The FastAPI request object containing the cookies.
- refresh_token (RefreshToken): The refresh token to verify.
- current_user_epoch (int): The epoch value for the tokens.
-
- Returns:
- AccessToken: The refreshed access token.
- """
- # IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
+ user_fingerprint_hash = _set_access_fp_cookie(response=response)
return _build_access_token(
real_account_id=refresh_token.real_account_id,
@@ -730,7 +973,7 @@ def _refresh_access_token(
effective_role=refresh_token.effective_role,
effective_organization_id=refresh_token.effective_organization_id,
epoch=refresh_token.epoch,
- user_fingerprint_hash=refresh_token.user_fingerprint_hash,
+ user_fingerprint_hash=user_fingerprint_hash,
)
@@ -738,7 +981,7 @@ def _build_id_token(
response: Response,
real_account_id: uuid.UUID,
epoch: int,
-) -> IdToken:
+) -> IdTokenMetadata:
"""Builds an ID token for the specified real account ID, expiration time, and epoch, and sets the appropriate fingerprint cookie.
Args:
@@ -753,34 +996,31 @@ def _build_id_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ID_TOKEN_EXPIRATION_MINUTES
)
- user_fingerprint_hash = _set_id_fp_cookie(response)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EPOCH_KEY: epoch,
- USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
}
raw_token = _build_token(
payload=payload,
expiration_datetime=expires_at,
token_type=TokenType.ID_TOKEN,
)
- return IdToken(
+ _set_id_token_cookie(response=response, raw_id_token=raw_token)
+ return IdTokenMetadata(
real_account_id=real_account_id,
expires_at=expires_at,
epoch=epoch,
- user_fingerprint_hash=user_fingerprint_hash,
- raw_token=raw_token,
)
-def _build_refresh_token(
+def _set_refresh_token(
+ response: Response,
real_account_id: uuid.UUID,
effective_account_id: uuid.UUID,
effective_role: UserRole,
effective_organization_id: uuid.UUID,
epoch: int,
- user_fingerprint_hash: str,
-) -> RefreshToken:
+) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
Args:
@@ -793,7 +1033,7 @@ def _build_refresh_token(
user_fingerprint_hash (str): The hashed value of the user's fingerprint.
Returns:
- RefreshToken: The generated refresh token object.
+ RefreshTokenMetadata: The generated refresh token object.
"""
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
@@ -804,7 +1044,6 @@ def _build_refresh_token(
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
- USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
}
raw_token = _build_token(
@@ -812,16 +1051,14 @@ def _build_refresh_token(
expiration_datetime=expires_at,
token_type=TokenType.REFRESH_TOKEN,
)
-
- return RefreshToken(
+ _set_refresh_token_cookie(response=response, raw_refresh_token=raw_token)
+ return RefreshTokenMetadata(
real_account_id=real_account_id,
effective_account_id=effective_account_id,
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_organization_id=effective_organization_id,
- user_fingerprint_hash=user_fingerprint_hash,
- raw_token=raw_token,
)
@@ -908,18 +1145,57 @@ def _build_token(
return token
-def _verify_fp_token(
- request: Request,
- cookie_key: str,
- token: str,
- session: Session,
-) -> Dict[str, Any]:
- """Verifies the provided token against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
+def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
+ """Verifies the provided ID token and returns the decoded payload if valid.
Args:
- request (Request): The FastAPI request object containing the cookies.
- cookie_key (str): The name of the cookie that contains the fingerprint.
- token (str): The JWT token to verify.
+ raw_id_token (str): The JWT ID token to verify.
+ session (Session): The database session.
+
+ Raises:
+ ValueError: If the token HMAC key is not set in the configuration.
+ HTTPException: If the token has expired.
+ HTTPException: If the token is invalid.
+ HTTPException: If the token's epoch does not match the current user epoch.
+
+ Returns:
+ Dict[str, Any]: The decoded payload of the JWT ID token if verification is successful.
+ """
+ payload = _extract_valid_token_payload(session, raw_id_token)
+ return payload
+
+
+def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]:
+ """Verifies the provided refresh token and returns the decoded payload if valid.
+
+ Args:
+ raw_refresh_token (str): The JWT refresh token to verify.
+ session (Session): The database session.
+
+ Raises:
+ ValueError: If the token HMAC key is not set in the configuration.
+ HTTPException: If the token has expired.
+ HTTPException: If the token is invalid.
+ HTTPException: If the token's epoch does not match the current user epoch.
+
+ Returns:
+ Dict[str, Any]: The decoded payload of the JWT refresh token if verification is successful.
+ """
+ payload = _extract_valid_token_payload(session, raw_refresh_token)
+ return payload
+
+
+def _verify_access_token_fp(
+ secure_fgp: str,
+ raw_access_token: str,
+ session: Session,
+) -> Dict[str, Any]:
+ """Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
+
+ Args:
+ secure_fgp (str): The secure fingerprint value.
+ raw_access_token (str): The JWT token to verify.
+ session (Session): The database session.
Raises:
ValueError: If the token HMAC key is not set in the configuration.
@@ -931,19 +1207,29 @@ def _verify_fp_token(
Returns:
Dict[str, Any]: The decoded payload of the JWT token if verification is successful.
"""
- if not settings.token_hmac_key:
- raise ValueError("Token HMAC key is not set in the configuration.")
-
- secure_fgp = request.cookies.get(cookie_key)
- if not secure_fgp:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Fingerprint cookie missing",
- )
fingerprint_bytes = secure_fgp.encode("utf-8")
expected_fingerprint_hash = hashlib.sha256(fingerprint_bytes).hexdigest()
+ payload = _extract_valid_token_payload(session, raw_access_token)
+
+ token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY)
+ if (
+ not token_fingerprint_hash
+ or token_fingerprint_hash != expected_fingerprint_hash
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid context fingerprint",
+ )
+
+ return payload
+
+
+def _extract_valid_token_payload(session: Session, token: str):
+ if not settings.token_hmac_key:
+ raise ValueError("Token HMAC key is not set in the configuration.")
+
try:
payload = jwt.decode(
token,
@@ -952,23 +1238,12 @@ def _verify_fp_token(
issuer=settings.token_issuer_id,
)
- token_fingerprint_hash = payload.get(USER_FINGERPRINT_HASH_KEY)
- if (
- not token_fingerprint_hash
- or token_fingerprint_hash != expected_fingerprint_hash
- ):
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Invalid context fingerprint",
- )
-
real_account_id = payload.get(REAL_ACCOUNT_ID_KEY)
if not real_account_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing real account ID",
)
-
epoch_account_id = uuid.UUID(real_account_id)
effective_account_id = payload.get(EFFECTIVE_ACCOUNT_ID_KEY)
@@ -980,6 +1255,9 @@ def _verify_fp_token(
account_id=epoch_account_id,
)
+ if uuid.UUID(real_account_id) != epoch_account_id:
+ _get_active_account(session, uuid.UUID(real_account_id))
+
token_epoch = payload.get(EPOCH_KEY)
if token_epoch is None or token_epoch != current_account_epoch:
raise HTTPException(
@@ -988,7 +1266,6 @@ def _verify_fp_token(
)
return payload
-
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -1016,7 +1293,12 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
"""
account = session.get(Account, account_id)
- if account is None or account.deleted or account.id is None:
+ if (
+ account is None
+ or account.deleted
+ or not account.activated
+ or account.id is None
+ ):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is not active.",
@@ -1025,7 +1307,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
return account
-def logout(session: Session, access_token: AccessToken) -> Dict[str, str]:
+def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]:
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
Args:
@@ -1049,7 +1331,7 @@ def logout(session: Session, access_token: AccessToken) -> Dict[str, str]:
def change_password(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
current_password: str,
new_password: str,
) -> Dict[str, str]:
diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py
index 7db19bb4..589abc72 100644
--- a/service/src/main/inse/auth/test_auth_service.py
+++ b/service/src/main/inse/auth/test_auth_service.py
@@ -14,9 +14,11 @@ from inse.auth.model import (
Account,
Organization,
Secret,
- IdToken,
+ SecretPurpose,
AccessToken,
- RefreshToken,
+ IdTokenMetadata,
+ AccessTokenMetadata,
+ RefreshTokenMetadata,
UserRole,
)
@@ -61,6 +63,19 @@ def create_org_and_account(
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():
pw = "s3cret-password"
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
resp = auth_service.request_otk(in_memory_session, email, password)
- assert resp["status"] == "ok"
- assert resp["account_id"] == str(acc.id)
+ assert resp.status == "success"
+ assert resp.account_id == acc.id
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()
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(
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.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):
@@ -108,35 +129,29 @@ def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
- id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
- assert isinstance(id_token, IdToken)
+ secure_fgp_hash = auth_service._set_access_fp_cookie(response)
+ 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
- for header, value in response.headers.items():
- if header.lower() == "set-cookie":
- 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,
+ payload = auth_service._verify_access_token_fp(
+ secure_fgp=secure_fgp,
+ raw_access_token=access_token.raw_token,
session=in_memory_session,
)
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
with pytest.raises(Exception):
- auth_service._verify_fp_token(
- request=DummyReq({}),
- cookie_key=auth_service.ID_FP_COOKIE_KEY,
- token=id_token.raw_token,
+ auth_service._verify_access_token_fp(
+ secure_fgp="bad-fingerprint",
+ raw_access_token=access_token.raw_token,
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(
response, in_memory_session, id_token, acc.id
)
- assert isinstance(access_response.access_token, AccessToken)
- assert isinstance(access_response.refresh_token, RefreshToken)
+ assert isinstance(access_response.access_token, AccessTokenMetadata)
- refreshed = auth_service.refresh_access_token(access_response.refresh_token)
- assert isinstance(refreshed, AccessToken)
+ raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY)
+ 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
@@ -210,6 +244,36 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
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):
config_module.settings.token_hmac_key = "expired-key"
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
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.commit()
@@ -239,24 +308,20 @@ def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
- id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
-
- cookie_header = None
- 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
+ secure_fgp_hash = 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_hash,
+ )
with pytest.raises(HTTPException):
- auth_service._verify_fp_token(
- request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
- cookie_key=auth_service.ID_FP_COOKIE_KEY,
- token=id_token.raw_token,
+ auth_service._verify_access_token_fp(
+ secure_fgp="badcookie",
+ raw_access_token=access_token.raw_token,
session=in_memory_session,
)
@@ -271,28 +336,25 @@ def test_token_epoch_mismatch(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
- id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
-
- cookie_header = None
- 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
+ secure_fgp_hash = auth_service._set_access_fp_cookie(response)
+ 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,
+ )
acc.epoch += 1
in_memory_session.add(acc)
in_memory_session.commit()
with pytest.raises(HTTPException):
- auth_service._verify_fp_token(
- request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
- cookie_key=auth_service.ID_FP_COOKIE_KEY,
- token=id_token.raw_token,
+ auth_service._verify_access_token_fp(
+ secure_fgp=secure_fgp,
+ raw_access_token=access_token.raw_token,
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
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
- 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"
+ bad_token = access_token.raw_token + "x"
with pytest.raises(HTTPException):
- auth_service._verify_fp_token(
- request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
- cookie_key=auth_service.ID_FP_COOKIE_KEY,
- token=bad_token,
+ auth_service._verify_access_token_fp(
+ secure_fgp=secure_fgp,
+ raw_access_token=bad_token,
session=in_memory_session,
)
@@ -362,7 +420,7 @@ def test_impersonation_rules(in_memory_session, settings_backup):
real_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):
@@ -377,14 +435,20 @@ def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
auth_service.request_otk(in_memory_session, email, password)
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()
assert secret1 is not None
first_value = secret1.secret_value
auth_service.request_otk(in_memory_session, email, password)
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()
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(
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):
@@ -411,13 +475,19 @@ def test_otk_deleted_after_login(in_memory_session, settings_backup):
auth_service.request_otk(in_memory_session, email, password)
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()
assert secret is not None
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
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()
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
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(
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_organization_id=acc.organization_id,
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):
- auth_service._verify_fp_token(
- request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
- cookie_key=auth_service.ACT_FP_COOKIE_KEY,
- token=access_token.raw_token,
+ auth_service._verify_access_token_fp(
+ secure_fgp="wrongcookie",
+ raw_access_token=access_token.raw_token,
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
response = Response()
- cookie_raw = auth_service._set_id_fp_cookie(response)
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
+ access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
payload = {
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.USER_FINGERPRINT_HASH_KEY: cookie_raw,
+ auth_service.USER_FINGERPRINT_HASH_KEY: access_fingerprint_hash,
}
bad_token = auth_service._build_token(
payload=payload,
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):
- auth_service._verify_fp_token(
- request=DummyReq(
- {
- 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,
+ auth_service._verify_access_token_fp(
+ secure_fgp=_get_cookie_value(response, auth_service.ACCESS_FP_COOKIE_KEY),
+ raw_access_token=bad_token,
session=in_memory_session,
)
@@ -515,3 +572,180 @@ def test_get_account_epoch_not_found(in_memory_session):
random_id = uuid.uuid4()
with pytest.raises(Exception):
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
diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py
index 87ebf721..ba0c1765 100644
--- a/service/src/main/inse/config.py
+++ b/service/src/main/inse/config.py
@@ -70,6 +70,8 @@ class Settings(BaseSettings):
skip_otk_validation: bool = True
# SMTP / email config
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_port: int = 25
smtp_sender: str = "no-reply@smartguide.local"
diff --git a/service/src/main/inse/database.py b/service/src/main/inse/database.py
index 728b750f..39a7c24b 100644
--- a/service/src/main/inse/database.py
+++ b/service/src/main/inse/database.py
@@ -1,6 +1,7 @@
from typing import Annotated
from fastapi import Depends
+from sqlalchemy import inspect, text
from sqlmodel import SQLModel, Session, create_engine
from inse import config
@@ -18,6 +19,15 @@ engine = create_engine(
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
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():
diff --git a/service/src/main/inse/institutions/institutions_search_client.py b/service/src/main/inse/institutions/institutions_search_client.py
index 975d6c4d..1c3a060f 100644
--- a/service/src/main/inse/institutions/institutions_search_client.py
+++ b/service/src/main/inse/institutions/institutions_search_client.py
@@ -224,6 +224,7 @@ class InstitutionsSearchClient:
"wildcard": {
"display_name.keyword": {
"value": f"*{stripped}*",
+ "case_insensitive": True,
"boost": 2,
}
}
@@ -232,6 +233,7 @@ class InstitutionsSearchClient:
"wildcard": {
"display_name_alternatives.keyword": {
"value": f"*{stripped}*",
+ "case_insensitive": True,
"boost": 2,
}
}
@@ -240,6 +242,7 @@ class InstitutionsSearchClient:
"wildcard": {
"display_name_acronyms.keyword": {
"value": f"*{stripped.upper()}*",
+ "case_insensitive": True,
"boost": 10,
}
}
diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py
index 803aa212..3ff5dc53 100644
--- a/service/src/main/inse/integrations/elasticsearch.py
+++ b/service/src/main/inse/integrations/elasticsearch.py
@@ -23,6 +23,7 @@ def get_client() -> httpx.AsyncClient:
global _client, _loop
try:
import asyncio
+
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
@@ -45,7 +46,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
Returns:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
-
+
if cluster == ESCluster.NES:
if (
not config.settings.elasticsearch_url
@@ -54,7 +55,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
raise MissingApiKeyError(
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
)
-
+
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
elif cluster == ESCluster.INSE:
if (
@@ -108,8 +109,12 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
def _wrap_exception(e: Exception) -> Exception:
if isinstance(e, httpx.HTTPStatusError):
if e.response.status_code == 404:
- return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
- return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
+ return ElasticsearchNotFoundException(
+ f"Elasticsearch resource not found: {e}"
+ )
+ return ElasticsearchException(
+ f"Elasticsearch returned status {e.response.status_code}: {e}"
+ )
elif isinstance(e, httpx.RequestError):
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
@@ -211,7 +216,9 @@ async def search(
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."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
@@ -256,7 +263,7 @@ async def scan(
cluster: str = "nes",
) -> AsyncIterator[Dict[str, Any]]:
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
-
+
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
@@ -316,6 +323,9 @@ async def get(
cluster: ESCluster = ESCluster.NES,
) -> dict[str, Any]:
+ if isinstance(index, ESIndex):
+ cluster = _index_to_cluster(index) or cluster
+
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py
index 39924953..180edfbc 100644
--- a/service/src/main/inse/integrations/llm.py
+++ b/service/src/main/inse/integrations/llm.py
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
from openai import AsyncOpenAI
from .. import config
from typing import Optional, Dict, Any
-
+import asyncio
def call(
system_prompt: str,
user_prompt: str,
@@ -62,7 +62,7 @@ def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str,
async def call_stream(
system_prompt: str,
user_prompt: str,
- emit, # EventCallback
+ emit,
model: str = None,
json_schema=None,
schema_name=None,
@@ -98,15 +98,26 @@ async def call_stream(
stream=True,
)
- async for chunk in stream:
- delta = chunk.choices[0].delta.content
- if delta:
- full_content += delta
- await emit({"type": "llm_chunk", "content": delta})
+ 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}")
diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py
index d6ae4c97..e329fb56 100644
--- a/service/src/main/inse/keywords/logic.py
+++ b/service/src/main/inse/keywords/logic.py
@@ -126,141 +126,6 @@ async def _get_text_content(url: str) -> str:
logger.error(f"Error processing {url}: {e}")
-async def extract_keywords_stream(
- query: str,
- mode: str,
- limit: int,
- emit: EventCallback,
-) -> ExtractedKeywordsResponse:
- start_time = time.time()
- timeout_seconds = 60 # configurable
- 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)
- await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
- 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 and return ONLY the JSON object.\n"
- if limit:
- user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\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")
-
- # Holds only fully validated KeywordEntry dicts for each level
- confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS}
-
- async def emit_full_results() -> None:
- """Attempt to build and validate the full ExtractedKeywordsLLM model and emit it."""
- # Build a dict with all three fields, using empty lists for missing ones
- data = {level: confirmed.get(level, []) for level in LEVELS}
- try:
- validated = ExtractedKeywordsLLM.model_validate(data)
- except ValidationError:
- # Should not happen if all items are valid, but guard against it
- return
- await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
-
- # adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found
- 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 []
- idx = len(confirmed[level])
-
- while idx < len(current):
- raw_item = current[idx]
- try:
- validated_item = KeywordEntry.model_validate(raw_item)
- except ValidationError:
- break # item not complete yet
- confirmed[level].append(validated_item.model_dump())
- idx += 1
- grew = True
-
- if grew:
- await emit_full_results()
-
- # Accumulate full_content for incremental parsing
- 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)
-
- 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.8,
- 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
-
- if not keywords:
- await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
- raise RuntimeError("LLM streaming call returned empty content")
-
- 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")
-
- # Final emission of the full results (in case the last chunk didn't trigger it)
- final_data = {level: confirmed.get(level, []) for level in LEVELS}
- try:
- final_validated = ExtractedKeywordsLLM.model_validate(keywords_json)
- except ValidationError:
- # Fallback: use our confirmed data
- final_validated = ExtractedKeywordsLLM.model_validate(final_data)
-
- 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
-
async def extract_keywords_stream_enriched(
query: str,
@@ -275,13 +140,17 @@ async def extract_keywords_stream_enriched(
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)
- await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
+ 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"
@@ -290,15 +159,10 @@ async def extract_keywords_stream_enriched(
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
-
- # Holds enriched keyword wrappers for each level
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
-
- # Track background enrichment tasks
enrichment_tasks: List[asyncio.Task] = []
async def emit_full_results() -> None:
- """Attempt to build and emit the full enriched keyword model."""
try:
validated = _build_enriched_snapshot(confirmed)
except ValidationError:
@@ -306,29 +170,19 @@ async def extract_keywords_stream_enriched(
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
- """
- Fetch/enrich metadata for a single keyword.
- Runs concurrently without blocking the LLM stream.
- """
try:
topic = await vector_search_topics_batch(
keywords=[item.keyword],
search_type="hybrid",
)
- # Update the shared confirmed list in-place (safe in asyncio)
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
-
- # Emit the full updated set after each enrichment so the frontend sees progress.
await emit_full_results()
-
except asyncio.CancelledError:
- # If the whole request is cancelled, we can just re-raise
raise
except Exception as e:
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results()
- # ---------- on_chunk: parses LLM stream and appends new keywords ----------
async def on_chunk(event: Dict[str, Any]) -> None:
if event["type"] != "llm_chunk":
await emit(event)
@@ -338,7 +192,6 @@ async def extract_keywords_stream_enriched(
partial = partial_json_parser.loads(event.get("_full_content", ""))
except Exception:
return
-
if not isinstance(partial, dict):
return
@@ -346,19 +199,18 @@ async def extract_keywords_stream_enriched(
for level in LEVELS:
current = partial.get(level) or []
- start_idx = len(confirmed[level]) # Where we start appending
+ 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 # item not complete yet
+ break
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
grew = True
- # Launch openalex topic mapping
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
@@ -374,7 +226,6 @@ async def extract_keywords_stream_enriched(
if grew:
await emit_full_results()
- # ---------- Accumulate full_content for incremental parsing ----------
full_content_holder = {"value": ""}
async def emit_wrapper(event: Dict[str, Any]) -> None:
@@ -384,6 +235,7 @@ async def extract_keywords_stream_enriched(
await on_chunk(event)
# ---------- Call the LLM ----------
+ keywords = ""
try:
keywords = await asyncio.wait_for(
llm.call_stream(
@@ -401,14 +253,24 @@ async def extract_keywords_stream_enriched(
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:
- # Cancel all pending enrichment tasks to avoid dangling background work
- for task in enrichment_tasks:
- task.cancel()
- if enrichment_tasks:
- await asyncio.gather(*enrichment_tasks, return_exceptions=True)
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())
@@ -418,13 +280,8 @@ async def extract_keywords_stream_enriched(
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
raise RuntimeError("LLM response is not valid JSON")
- # ---------- Wait for ALL pending enrichments to complete ----------
- if enrichment_tasks:
- await asyncio.gather(*enrichment_tasks, return_exceptions=True)
-
await emit_full_results()
- # Build final response
try:
final_validated = _build_enriched_snapshot(confirmed)
except ValidationError:
diff --git a/service/src/main/inse/keywords/prompts.py b/service/src/main/inse/keywords/prompts.py
index f60c8fc3..adcf9a08 100644
--- a/service/src/main/inse/keywords/prompts.py
+++ b/service/src/main/inse/keywords/prompts.py
@@ -35,13 +35,118 @@ class KeywordsPrompt(StrEnum):
---
+ # 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, or technology areas.
+ High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
- Examples:
+ Examples (only if explicitly mentioned):
* Artificial Intelligence
* Healthcare
@@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum):
* Materials Science
* Robotics
- These should represent the major themes of the document.
+ 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, or applications.
+ Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
- Examples:
+ Examples (only if explicitly mentioned):
* Machine Learning
* Drug Discovery
@@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum):
## 3. fine_grained
- Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
+ Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
- Examples:
+ Examples (only if explicitly mentioned):
* Transformer Architecture
* CRISPR-Cas9
@@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum):
# Extraction Rules
- * Extract only concepts explicitly mentioned or strongly implied.
+ * 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.
+ 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
@@ -136,269 +276,277 @@ class KeywordsPrompt(StrEnum):
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":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]}
-
+ 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.
-
+ 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.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]}
+ {"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.
+ 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 input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
- The extracted text may contain:
+ 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
+ * 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.
+ Your first task is to identify the actual content and purpose of the webpage.
- Ignore:
+ 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
+ * 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 content that helps identify:
+ Focus only on the primary informational content of the webpage.
- * Technologies
- * Scientific concepts
- * Research areas
- * Technical methods
- * Products
- * Applications
- * Industrial sectors
- * Materials
- * Standards
- * Diseases
- * Engineering disciplines
- * Innovation domains
+ ---
- ---
+ # STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
- # Step 1: Determine Page Type
+ The output must be strictly extractive and grounded in the webpage text.
- Determine which type of page is represented:
+ ## Mandatory Rules
- * Technology/Product Page
- * Company Page
- * Research Article
- * Scientific Blog Post
- * News Article
- * Technical Documentation
- * White Paper
- * Industry Report
- * Other
+ 1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
- Use this classification internally only.
+ 2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
- Do not include it in the output.
+ 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:
- # Step 2: Extract Searchable Concepts
+ Input:
- Prioritize concepts that are useful for:
+ "The platform uses large language models and retrieval-augmented generation."
- * OpenAlex retrieval
- * Scientific literature discovery
- * Patent scouting
- * Technology scouting
- * Innovation monitoring
+ Allowed:
- Prefer canonical scientific terminology over marketing language.
+ * large language models
+ * retrieval-augmented generation
- Examples:
+ Not allowed:
- Prefer:
+ * Artificial Intelligence
+ * Generative AI
+ * Natural Language Processing
- * Large Language Models
+ unless explicitly present.
- Instead of:
+ 4. Do NOT generate synonyms.
- * AI Assistant
+ Example:
- Prefer:
+ Input:
- * Smart Manufacturing
+ "AI assistant"
- Instead of:
+ Allowed:
- * Factory Optimization Solution
+ * AI assistant
- Prefer:
+ Not allowed:
- * Retrieval-Augmented Generation
+ * large language models
+ * conversational AI
+ * generative AI
- Instead of:
+ unless those exact terms appear.
- * Intelligent Knowledge Assistant
+ 5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
- Prefer:
+ 6. Do NOT rewrite marketing terms into technical terms.
- * Predictive Maintenance
+ 7. Every keyword must have direct textual evidence in the webpage content.
- Instead of:
+ 8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
- * Equipment Performance Optimization
+ 9. Preserve original wording whenever possible.
- ---
+ 10. Do not invent keywords to satisfy target counts.
- # Keyword Hierarchy
+ 11. When insufficient keywords exist, return fewer keywords.
- ## broad_keywords
+ 12. Grounding accuracy is more important than completeness.
- High-level domains, industries, disciplines, or technology areas.
+ 13. Any keyword not directly supported by the webpage text is considered an extraction error.
- Examples:
+ ---
- * Artificial Intelligence
- * Healthcare
- * Manufacturing
- * Energy Storage
- * Biotechnology
- * Robotics
+ # Step 1: Determine Page Type
- ---
+ Determine internally whether the page is:
- ## coarse_grained
+ * Technology/Product Page
+ * Company Page
+ * Research Article
+ * Scientific Blog Post
+ * News Article
+ * Technical Documentation
+ * White Paper
+ * Industry Report
+ * Other
- Technologies, methods, research fields, and applications.
+ Use this classification only to identify the relevant content and remove boilerplate.
- Examples:
+ Do NOT include the classification in the output.
- * Machine Learning
- * Predictive Maintenance
- * Drug Discovery
- * Smart Manufacturing
- * Computer Vision
- * Clinical Decision Support
+ ---
- ---
+ # Step 2: Extract Searchable Concepts
- ## fine_grained
+ Extract concepts directly present in the page that are useful for:
- Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
+ * OpenAlex retrieval
+ * Scientific literature discovery
+ * Patent scouting
+ * Technology scouting
+ * Innovation monitoring
- Examples:
+ The extracted concepts must remain faithful to the wording used in the webpage.
- * Transformer Architecture
- * CRISPR-Cas9
- * OPC UA
- * Retrieval-Augmented Generation
- * YOLOv8
- * Lithium Iron Phosphate
+ Do NOT replace webpage terminology with your own preferred terminology.
- ---
+ ---
- # Relevance Score
+ # Keyword Hierarchy
- Assign a relevance score between 0.0 and 1.0.
+ ## broad_keywords
- Guidelines:
+ High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
- * 1.00 = central topic of the webpage
- * 0.90 = major topic
- * 0.80 = highly relevant
- * 0.70 = supporting concept
- * 0.60 = secondary concept
+ Only use this level when such broad concepts are explicitly present.
- Avoid scores below 0.60 unless necessary.
+ Examples:
- ---
+ * Healthcare
+ * Biotechnology
+ * Manufacturing
+ * Robotics
+ * Financial Technology
- # Additional Rules
+ only if those exact concepts appear in the webpage.
- * Extract only concepts supported by the page content.
- * Do not hallucinate technologies.
- * Avoid generic company descriptions.
- * Avoid generic business terminology.
- * Prefer terminology suitable for scientific literature search.
- * Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
- * Remove duplicates across hierarchy levels whenever possible.
- * Rank keywords by importance.
+ ---
- ---
- # Example 3 — News Article
+ ## coarse_grained
- ## Input
+ Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
- Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications.
+ Examples:
- ## Output
+ * Machine Learning
+ * Predictive Maintenance
+ * Drug Discovery
+ * Smart Manufacturing
+ * Clinical Decision Support
- ```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}```
+ only if explicitly present.
- ---
+ ---
- # Example 4 — Product Page
+ ## fine_grained
- ## Input
+ 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.
- The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support.
+ Examples:
- ## Output
+ * FastAPI
+ * OpenAPI
+ * Pydantic
+ * CRISPR-Cas9
+ * Retrieval-Augmented Generation
+ * OPC UA
- ```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}```
+ only if explicitly present.
- ---
+ ---
- # Example 5 — Technical Documentation
+ # Relevance Score
- ## Input
+ Assign a relevance score between 0.0 and 1.0.
- 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.
+ Guidelines:
- ## Output
+ * 1.00 = central topic of the webpage
+ * 0.90 = major topic
+ * 0.80 = highly relevant
+ * 0.70 = supporting concept
+ * 0.60 = secondary concept
- ```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}```
+ Avoid scores below 0.60 unless necessary.
- ---
+ Rank keywords by importance.
- # Example 6 — Company Website
+ ---
- ## Input
+ # Extraction Rules
- Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
+ * 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.
- ## Output
+ ---
- ```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}```
+ # 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.
- Return ONLY valid JSON matching the schema provided by the API.
"""
SIMPLE_TEXT_PROMPT = """
diff --git a/service/src/main/inse/keywords/service.py b/service/src/main/inse/keywords/service.py
index ae207f1c..f4de6cf5 100644
--- a/service/src/main/inse/keywords/service.py
+++ b/service/src/main/inse/keywords/service.py
@@ -8,10 +8,13 @@ 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",
@@ -19,26 +22,35 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
)
+
+
+
@router.websocket("/keywords/extract/ws")
async def extract_keywords_ws(websocket: WebSocket):
- print("WebSocket connection established for keyword extraction.")
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)
- disconnected = asyncio.Event()
-
- async def emit(event: dict):
- if disconnected.is_set():
- return
- await websocket.send_json(event)
-
- async def watch_disconnect() -> None:
- while True:
- message = await websocket.receive()
- if message["type"] == "websocket.disconnect":
- disconnected.set()
- return
+ request = KeywordsRequest(**raw)
extraction_task = asyncio.create_task(
logic.extract_keywords_stream_enriched(
@@ -48,60 +60,37 @@ async def extract_keywords_ws(websocket: WebSocket):
emit=emit,
)
)
- disconnect_task = asyncio.create_task(watch_disconnect())
- done, pending = await asyncio.wait(
- {extraction_task, disconnect_task},
- return_when=asyncio.FIRST_COMPLETED,
- )
+ result = await extraction_task
- if disconnect_task in done:
- disconnected.set()
+ 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:
+ except (asyncio.CancelledError, Exception):
pass
- return
- disconnect_task.cancel()
- try:
- await disconnect_task
- except asyncio.CancelledError:
- pass
- result = extraction_task.result()
-
- await websocket.send_json({"type": "completed", "result": result.model_dump()})
-
- except WebSocketDisconnect:
- print("WebSocket disconnected.")
- pass
- except Exception as e:
- await websocket.send_json({"type": "error", "message": str(e)})
- finally:
if websocket.application_state.name != "DISCONNECTED":
await websocket.close()
-
-# @router.post(
-# "/keywords/extract",
-# operation_id="extractKeywords",
-# response_model=ExtractedKeywordsResponse,
-# )
-# async def extract_keywords(
-# request: Annotated[
-# KeywordsRequest,
-# Body(description="Input text for keyword extraction"),
-# ],
-# ):
-# async def noop(_: dict):
-# pass
-
-# return await logic.extract_keywords_stream(
-# query=request.query,
-# mode=request.mode,
-# limit=request.limit,
-# emit=noop,
-# )
@router.post(
"/keywords/extract",
diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py
index f75d697c..6ed98888 100644
--- a/service/src/main/inse/main.py
+++ b/service/src/main/inse/main.py
@@ -24,7 +24,9 @@ from inse.exceptions import (
)
from inse.funders.service import router as funders_service_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
+from inse.keywords.service import router as keywords_service_router
+from inse.patents.keywords.service import router as keywords_patents_router
# caching
from inse.middleware.etag_cache import ETagCacheMiddleware
@@ -32,15 +34,11 @@ from inse.persons.service import router as persons_service_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.news.service import router as news_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.account_management.router import router as account_management_router
from inse.organization_management.router import router as organization_management_router
from inse.dashboard.router import router as dashboard_router
-
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts
@@ -54,6 +52,8 @@ from inse.patents.service import (
router as patents_service_router,
)
+from inse.works.purpose_router import router as works_purpose_router
+
logger = logging.getLogger(__name__)
### startup
@@ -84,6 +84,7 @@ app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(topics_service_router)
+app.include_router(works_purpose_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
@@ -94,6 +95,7 @@ app.include_router(university_ranking_router)
app.include_router(projects_router)
app.include_router(patents_all_router)
app.include_router(keywords_service_router)
+app.include_router(keywords_patents_router)
app.include_router(service_router)
@@ -102,6 +104,7 @@ app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(dashboard_router)
+
app.add_middleware(
ETagCacheMiddleware,
ttl=300, # 5 minutes expiration time
@@ -118,6 +121,7 @@ app.add_middleware(
# exception handlers
+
@app.exception_handler(NotFoundException)
async def handle_not_found(request: Request, exc: NotFoundException):
return JSONResponse(status_code=404, content={"message": str(exc)})
@@ -126,13 +130,18 @@ async def handle_not_found(request: Request, exc: NotFoundException):
@app.exception_handler(ElasticsearchException)
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
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)
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
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)
diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py
index 3bc9f9a7..f8c4db71 100644
--- a/service/src/main/inse/middleware/etag_cache.py
+++ b/service/src/main/inse/middleware/etag_cache.py
@@ -1,74 +1,77 @@
-# middleware/etag_cache.py
-import hashlib
-import json
-import time
-
-from starlette.middleware.base import BaseHTTPMiddleware
-from starlette.requests import Request
-from starlette.responses import Response
-
-
-class ETagCacheMiddleware(BaseHTTPMiddleware):
- def __init__(self, app, ttl: int = 60):
- super().__init__(app)
- self.ttl = ttl # timeout in seconds
- self.cache: dict[str, dict] = {} # key → {body, etag, expires}
-
- def _cache_key(self, request: Request) -> str:
- # Include query params and relevant headers in the key
- return f"{request.url.path}?{request.url.query}"
-
- def _content_type(self, response: Response) -> str | None:
- return response.headers.get("content-type")
-
- async def dispatch(self, request: Request, call_next):
- if request.method != "GET":
- return await call_next(request)
-
- if request.url.path.startswith(("/api/auth", "/api/accounts")):
- return await call_next(request)
-
- if request.headers.get("authorization"):
- return await call_next(request)
-
- key = self._cache_key(request)
- entry = self.cache.get(key)
- client_etag = request.headers.get("if-none-match")
-
- # Cache hit + not expired
- if entry and time.time() < entry["expires"]:
- if client_etag == entry["etag"]:
- headers = {"ETag": entry["etag"]}
- if entry.get("content_type"):
- headers["Content-Type"] = entry["content_type"]
- return Response(status_code=304, headers=headers)
-
- # Client has stale ETag - return fresh cached body
- headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
- if entry.get("content_type"):
- headers["Content-Type"] = entry["content_type"]
- return Response(
- content=entry["body"],
- headers=headers,
- )
-
- # Cache miss or expired → hit the actual route
- response = await call_next(request)
- body = b"".join([chunk async for chunk in response.body_iterator])
- etag = f'"{hashlib.md5(body).hexdigest()}"'
- content_type = self._content_type(response)
-
- self.cache[key] = {
- "body": body,
- "etag": etag,
- "expires": time.time() + self.ttl,
- "content_type": content_type,
- }
- headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
- if content_type:
- headers["Content-Type"] = content_type
- return Response(
- content=body,
- status_code=response.status_code,
- headers=headers,
- )
+# middleware/etag_cache.py
+import hashlib
+import json
+import time
+
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+from starlette.responses import Response
+
+
+class ETagCacheMiddleware(BaseHTTPMiddleware):
+ def __init__(self, app, ttl: int = 60):
+ super().__init__(app)
+ self.ttl = ttl # timeout in seconds
+ self.cache: dict[str, dict] = {} # key → {body, etag, expires}
+
+ def _cache_key(self, request: Request) -> str:
+ # Include query params and relevant headers in the key
+ return f"{request.url.path}?{request.url.query}"
+
+ def _content_type(self, response: Response) -> str | None:
+ return response.headers.get("content-type")
+
+ async def dispatch(self, request: Request, call_next):
+ if request.method != "GET":
+ return await call_next(request)
+
+ if request.url.path.startswith(("/api/auth", "/api/accounts")):
+ return await call_next(request)
+
+ if request.headers.get("authorization"):
+ return await call_next(request)
+
+ key = self._cache_key(request)
+ entry = self.cache.get(key)
+ client_etag = request.headers.get("if-none-match")
+
+ # Cache hit + not expired
+ if entry and time.time() < entry["expires"]:
+ if client_etag == entry["etag"]:
+ headers = {"ETag": entry["etag"]}
+ if entry.get("content_type"):
+ headers["Content-Type"] = entry["content_type"]
+ return Response(status_code=304, headers=headers)
+
+ # Client has stale ETag - return fresh cached body
+ headers = {"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
+ if entry.get("content_type"):
+ headers["Content-Type"] = entry["content_type"]
+ return Response(
+ content=entry["body"],
+ status_code=entry.get("status_code", 200),
+ headers=headers,
+ )
+
+ # Cache miss or expired → hit the actual route
+ response = await call_next(request)
+ body = b"".join([chunk async for chunk in response.body_iterator])
+ etag = f'"{hashlib.md5(body).hexdigest()}"'
+ content_type = self._content_type(response)
+
+ if response.status_code < 400:
+ self.cache[key] = {
+ "body": body,
+ "etag": etag,
+ "expires": time.time() + self.ttl,
+ "status_code": response.status_code,
+ "content_type": content_type,
+ }
+ headers = {"ETag": etag, "Cache-Control": f"max-age={self.ttl}"}
+ if content_type:
+ headers["Content-Type"] = content_type
+ return Response(
+ content=body,
+ status_code=response.status_code,
+ headers=headers,
+ )
diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py
index 222d9603..72a27008 100644
--- a/service/src/main/inse/model.py
+++ b/service/src/main/inse/model.py
@@ -5,7 +5,16 @@ This module defines the model classes returned from
our api using pydantic.
"""
-from enum import StrEnum
+import sys
+
+if sys.version_info >= (3, 11):
+ from enum import StrEnum
+else:
+ from enum import Enum
+
+ class StrEnum(str, Enum):
+ def __str__(self) -> str:
+ return self.value
from pydantic import BaseModel
from pydantic import Field
@@ -34,6 +43,10 @@ class ESIndex(StrEnum):
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
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"
USPTO_INDEX = "uspto_patents_3.0"
diff --git a/service/src/main/inse/models.zip b/service/src/main/inse/models.zip
deleted file mode 100644
index 1dc6b609..00000000
Binary files a/service/src/main/inse/models.zip and /dev/null differ
diff --git a/service/src/main/inse/models/openalex/topic.py b/service/src/main/inse/models/openalex/topic.py
index da547b58..2085a784 100644
--- a/service/src/main/inse/models/openalex/topic.py
+++ b/service/src/main/inse/models/openalex/topic.py
@@ -39,6 +39,7 @@ class Topic(BaseModel):
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
subfield: Optional[TopicSubfield] = None
var_field: Optional[TopicField] = Field(default=None, alias="field")
+ field: Optional[TopicField] = Field(default=None)
domain: Optional[TopicDomain] = None
works_count: Optional[StrictInt] = Field(default=None, description="The number of works tagged with this topic.")
cited_by_count: Optional[StrictInt] = None
diff --git a/service/src/main/inse/models/openalex/work_topic.py b/service/src/main/inse/models/openalex/work_topic.py
index c4c6fce6..e780d369 100644
--- a/service/src/main/inse/models/openalex/work_topic.py
+++ b/service/src/main/inse/models/openalex/work_topic.py
@@ -33,11 +33,12 @@ class WorkTopic(BaseModel):
""" # noqa: E501
id: Optional[StrictStr] = None
display_name: Optional[StrictStr] = None
+ description: Optional[StrictStr] = None
score: Optional[Union[StrictFloat, StrictInt]] = None
subfield: Optional[WorkTopicSubfield] = None
var_field: Optional[WorkTopicField] = Field(default=None, alias="field")
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(
validate_by_name=True,
@@ -101,6 +102,7 @@ class WorkTopic(BaseModel):
_obj = cls.model_validate({
"id": obj.get("id"),
"display_name": obj.get("display_name"),
+ "description": obj.get("description"),
"score": obj.get("score"),
"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,
diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py
index 77cf31a0..3ced9bf5 100644
--- a/service/src/main/inse/news/logic.py
+++ b/service/src/main/inse/news/logic.py
@@ -12,7 +12,8 @@ from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
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__)
@@ -20,14 +21,19 @@ TOPIC_LIMIT = 4
TOPIC_QUERY_CONTENT_CHARS = 300
TOPIC_NUM_CANDIDATES = 100
TOPIC_SIMILARITY = 0.5
+TOPIC_MATCHES_PER_KEYWORD = 1
KEYWORD_LIMIT = 6
KEYWORD_CONTENT_CHARS = 4000
KEYWORD_SYSTEM_PROMPT = """\
- Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
- Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
- des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
- weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
+ 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.
"""
RELATED_BLOCK_SIZE = 5
@@ -80,7 +86,14 @@ async def search_news(
clauses = await _filter_clauses(year_from, year_to, relevance_values)
exact_query = {
"bool": {
- "must": [{"match": {"full_content": query_text}}],
+ "must": [
+ {
+ "multi_match": {
+ "query": query_text,
+ "fields": ["maintitle^2", "full_content"],
+ }
+ }
+ ],
"filter": clauses,
}
}
@@ -240,7 +253,6 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source = response.get("_source", {})
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(
news_id,
postproc_id,
@@ -248,6 +260,7 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source.get("maintitle"),
source.get("full_content"),
)
+ topics = await _match_topics_for_keywords(keywords)
return NewsArticleDetail(
id=response.get("_id"),
@@ -258,22 +271,11 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
full_content=source.get("full_content"),
relevant=relevant,
authors=await _build_mentioned_persons(authors),
- topics=topics,
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(
news_id: str,
postproc_id: str | None,
@@ -308,7 +310,12 @@ def _parse_keywords(raw: str) -> list:
try:
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):
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}.")
+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:
try:
from ..util import get_model
diff --git a/service/src/main/inse/news/model.py b/service/src/main/inse/news/model.py
index b63c2bc0..d6107d88 100644
--- a/service/src/main/inse/news/model.py
+++ b/service/src/main/inse/news/model.py
@@ -23,12 +23,21 @@ class MentionedPerson(BaseModel):
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):
full_content: Optional[str] = None
relevant: Optional[bool] = None
authors: List[MentionedPerson] = []
- topics: List[str] = []
keywords: List[str] = []
+ topics: List[MatchedTopic] = []
class NewsPage(BaseModel):
diff --git a/service/src/main/inse/organization_management/router.py b/service/src/main/inse/organization_management/router.py
index 0a8b82ca..5a2db2bd 100644
--- a/service/src/main/inse/organization_management/router.py
+++ b/service/src/main/inse/organization_management/router.py
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
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.tags import Tags
@@ -26,7 +26,7 @@ async def get_organizations(
page_size: int = Query(default=25, ge=1, le=100),
offset: Optional[int] = Query(default=None, ge=0),
session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationPage:
return service.get_organizations(
session=session,
@@ -46,7 +46,7 @@ async def get_organizations(
async def create_organization(
payload: CreateOrganizationRequest,
session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.create_organization(session, access_token, payload)
@@ -60,7 +60,7 @@ async def update_organization(
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> OrganizationProfile:
return service.update_organization(
session, access_token, organization_id, payload
@@ -75,7 +75,7 @@ async def update_organization(
async def delete_organization(
organization_id: uuid.UUID,
session: Session = Depends(get_session),
- access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
+ access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_organization(session, access_token, organization_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py
index 56d97db2..528bcf35 100644
--- a/service/src/main/inse/organization_management/service.py
+++ b/service/src/main/inse/organization_management/service.py
@@ -4,7 +4,7 @@ from typing import Optional
from fastapi import HTTPException, status
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 (
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:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -73,6 +73,7 @@ def _member_counts(
.where(
Account.organization_id.in_(organization_ids),
Account.deleted == False, # noqa: E712
+ Account.activated == True, # noqa: E712
)
.group_by(Account.organization_id)
).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(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
page: int,
page_size: int,
offset: Optional[int] = None,
@@ -129,7 +145,7 @@ def get_organizations(
def create_organization(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
payload: CreateOrganizationRequest,
) -> OrganizationProfile:
_require_super_admin(access_token)
@@ -148,7 +164,7 @@ def create_organization(
def update_organization(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
organization_id: uuid.UUID,
payload: UpdateOrganizationRequest,
) -> OrganizationProfile:
@@ -162,6 +178,8 @@ def update_organization(
if payload.other_inst_id is not None:
organization.openalex_institution_id = payload.other_inst_id.strip() or None
if payload.deleted is not None:
+ if payload.deleted and not organization.deleted:
+ _deactivate_organization_accounts(session, organization.id)
organization.deleted = payload.deleted
session.add(organization)
@@ -173,11 +191,13 @@ def update_organization(
def delete_organization(
session: Session,
- access_token: AccessToken,
+ access_token: AccessTokenMetadata,
organization_id: uuid.UUID,
) -> None:
_require_super_admin(access_token)
organization = _get_organization_or_404(session, organization_id)
+ if not organization.deleted:
+ _deactivate_organization_accounts(session, organization.id)
organization.deleted = True
session.add(organization)
session.commit()
diff --git a/service/src/main/inse/organization_management/test_service.py b/service/src/main/inse/organization_management/test_service.py
index ce3b3e03..a7ce6ff6 100644
--- a/service/src/main/inse/organization_management/test_service.py
+++ b/service/src/main/inse/organization_management/test_service.py
@@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session):
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])
def test_only_superadmin_can_create_organizations(session, role):
organization = Organization(name="Scope")
diff --git a/service/src/main/inse/patents/all/logic.py b/service/src/main/inse/patents/all/logic.py
index f18b6a8d..76defc74 100644
--- a/service/src/main/inse/patents/all/logic.py
+++ b/service/src/main/inse/patents/all/logic.py
@@ -1,6 +1,8 @@
"""Business logic for global patent listing."""
import asyncio
+import logging
from datetime import datetime
+
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_404_NOT_FOUND
@@ -11,13 +13,17 @@ from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
enrich_patents_classifications,
+ enrich_patents_openalex_topics,
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.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
from inse.patents.search_client import PatentSearchClient
+logger = logging.getLogger(__name__)
+
async def get_all_patents(
page: int = 0,
size: int = 10,
@@ -76,6 +82,14 @@ async def get_all_patents(
) from exc
await enrich_patents_classifications(patents, ipc_search_client)
+ try:
+ await enrich_patents_openalex_topics(
+ patents, PatentsOpenAlexKeywordsClient()
+ )
+ except Exception:
+ logger.warning(
+ "Failed to enrich patents with OpenAlex topics", exc_info=True
+ )
return model.AllPatentsResponse(
total=total,
@@ -83,3 +97,115 @@ async def get_all_patents(
size=size,
patents=patents,
)
+
+
+def _normalize_patent_date(date_str: str) -> str:
+ return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
+
+
+def _parse_patent_id(patent_id: str) -> tuple[str, str]:
+ normalized = patent_id.strip().upper()
+ if normalized.startswith("EP"):
+ return "EPO", normalized.removeprefix("EP")
+ if normalized.startswith("US"):
+ return "USPTO", normalized.removeprefix("US")
+ raise HTTPException(
+ status_code=HTTP_404_NOT_FOUND,
+ detail="Patent not found.",
+ )
+
+
+async def _search_by_id(
+ client: AllPatentsSearchClient,
+ patent_id: str,
+ filling_date: str | None = None,
+) -> list[model.PatentEntry]:
+ try:
+ source, number = _parse_patent_id(patent_id)
+ except HTTPException:
+ return []
+
+ if source == "EPO":
+ data = await client.search_epo(client.epo_detail_query(number, filling_date))
+ return parse_epo_hits(data)
+ data = await client.search_uspto(client.uspto_detail_query(number, filling_date))
+ return parse_uspto_hits(data)
+
+
+async def _search_by_title(
+ client: AllPatentsSearchClient,
+ title: str,
+ filling_date: str | None = None,
+ prefix: str | None = None,
+) -> list[model.PatentEntry]:
+ if prefix and prefix.upper() == "US":
+ data = await client.search_uspto(client.uspto_title_query(title, filling_date))
+ return parse_uspto_hits(data)
+ if prefix and prefix.upper() == "EP":
+ data = await client.search_epo(client.epo_title_query(title, filling_date))
+ return parse_epo_hits(data)
+
+ epo_data, uspto_data = await asyncio.gather(
+ client.search_epo(client.epo_title_query(title, filling_date)),
+ client.search_uspto(client.uspto_title_query(title, filling_date)),
+ )
+ return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
+
+
+async def get_patent_by_id(
+ patent_id: str,
+ prefix: str | None = None,
+ title: str | None = None,
+ filling_date: str | None = None,
+ ipc_client: IpcSearchClient | None = None,
+) -> model.PatentEntry:
+ all_patents_client = AllPatentsSearchClient()
+ ipc_search_client = ipc_client or IpcSearchClient()
+ normalized_filling_date = (
+ _normalize_patent_date(filling_date) if filling_date else None
+ )
+
+ lookup_id = patent_id
+ if prefix and not patent_id.upper().startswith(prefix.upper()):
+ lookup_id = f"{prefix.upper()}{patent_id}"
+
+ try:
+ patents = await _search_by_id(
+ all_patents_client, lookup_id, normalized_filling_date
+ )
+
+ if not patents and title:
+ patents = await _search_by_title(
+ all_patents_client,
+ title,
+ normalized_filling_date,
+ prefix,
+ )
+
+ if not patents:
+ raise HTTPException(
+ status_code=HTTP_404_NOT_FOUND,
+ detail="Patent not found.",
+ )
+
+ 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[:1], ipc_search_client)
+ try:
+ await enrich_patents_openalex_topics(
+ patents[:1], PatentsOpenAlexKeywordsClient()
+ )
+ except Exception:
+ logger.warning(
+ "Failed to enrich patent with OpenAlex topics", exc_info=True
+ )
+ return patents[0]
diff --git a/service/src/main/inse/patents/all/service.py b/service/src/main/inse/patents/all/service.py
index a620c93c..2126fc29 100644
--- a/service/src/main/inse/patents/all/service.py
+++ b/service/src/main/inse/patents/all/service.py
@@ -33,3 +33,23 @@ async def get_all_patents(
year_from=year_from,
year_to=year_to,
)
+
+
+@router.get(
+ "/patents/{identifier}",
+ operation_id="getPatentByIdOrTitle",
+ response_model=model.PatentEntry,
+ summary="Get a single patent by identifier with optional title fallback.",
+)
+async def get_patent_by_identifier(
+ identifier: str,
+ prefix: str | None = None,
+ title: str | None = None,
+ filling_date: str | None = None,
+):
+ return await logic.get_patent_by_id(
+ patent_id=identifier,
+ prefix=prefix,
+ title=title,
+ filling_date=filling_date,
+ )
diff --git a/service/src/main/inse/patents/authors/identity.py b/service/src/main/inse/patents/authors/identity.py
new file mode 100644
index 00000000..320ce506
--- /dev/null
+++ b/service/src/main/inse/patents/authors/identity.py
@@ -0,0 +1,137 @@
+"""Identity signals used to decide whether a patent really belongs to a person.
+
+These are the *strong* signals (name specificity, institution/assignee overlap)
+that distinguish one same-named person from another.
+"""
+from __future__ import annotations
+
+from inse.models.openalex.author import Author
+from inse.patents.authors.name_matching import (
+ first_name_match_kind_for_person,
+ name_matches_person,
+)
+from inse.patents.authors.name_variants import parse_person_name
+from inse.patents.common import model
+from inse.patents.institutions.name_matching import assignee_matches_institution_name
+
+# Ambiguity is derived purely from data that already exists in the project (the
+# number of patent hits for the name and the number of same-named authors in the
+# local OpenAlex index) — no external name database is used.
+#
+# Thresholds are starting values and should be validated against a handful of
+# test persons.
+PATENT_HIT_COUNT_THRESHOLD = 300
+OPENALEX_FULL_NAME_COUNT_THRESHOLD = 2
+OPENALEX_LAST_NAME_COUNT_THRESHOLD = 100
+
+
+def is_ambiguous_name(
+ display_name: str | None,
+ *,
+ patent_hit_count: int = 0,
+ openalex_full_name_count: int | None = None,
+ openalex_last_name_count: int | None = None,
+) -> bool:
+ """Decide whether a name is ambiguous using only internal project data.
+
+ A name is treated as ambiguous (and therefore handled strictly) when:
+ - it is a mononym / cannot be parsed into given + family name, or
+ - several authors in the local OpenAlex index share the exact name, or
+ - many authors in the local OpenAlex index share the family name, or
+ - the patent name search returns a very large number of hits.
+
+ Ambiguous names need a strong identity signal (institution/assignee or a
+ full given-name match with a matching research field) before a patent is
+ attributed to the person.
+ """
+ parsed = parse_person_name(display_name)
+ if parsed is None or parsed.is_single_token:
+ return True
+
+ if (
+ openalex_full_name_count is not None
+ and openalex_full_name_count >= OPENALEX_FULL_NAME_COUNT_THRESHOLD
+ ):
+ return True
+
+ if (
+ openalex_last_name_count is not None
+ and openalex_last_name_count >= OPENALEX_LAST_NAME_COUNT_THRESHOLD
+ ):
+ return True
+
+ if patent_hit_count >= PATENT_HIT_COUNT_THRESHOLD:
+ return True
+
+ return False
+
+
+def author_institution_names(author: Author) -> list[str]:
+ names: list[str] = []
+ seen: set[str] = set()
+
+ def _add(display_name: str | None) -> None:
+ if not display_name or not display_name.strip():
+ return
+ key = display_name.casefold()
+ if key in seen:
+ return
+ seen.add(key)
+ names.append(display_name.strip())
+
+ for institution in author.last_known_institutions or []:
+ _add(getattr(institution, "display_name", None))
+
+ for affiliation in author.affiliations or []:
+ institution = getattr(affiliation, "institution", None)
+ if institution is not None:
+ _add(getattr(institution, "display_name", None))
+
+ return names
+
+
+def patent_institution_match(
+ patent: model.PatentEntry,
+ institution_names: list[str],
+) -> bool:
+ if not institution_names:
+ return False
+ for assignee in patent.assignees:
+ if not assignee:
+ continue
+ for institution_name in institution_names:
+ if assignee_matches_institution_name(assignee, institution_name):
+ return True
+ return False
+
+
+def patent_personal_assignee_match(
+ patent: model.PatentEntry,
+ display_name: str,
+) -> bool:
+ """True when the person themselves is listed as an applicant/assignee.
+
+ Being the personal applicant of a patent is a strong identity signal
+ (organisation assignees like companies/universities will not match a
+ full person name).
+ """
+ if not display_name or not display_name.strip():
+ return False
+ for assignee in patent.assignees:
+ if assignee and name_matches_person(assignee, display_name):
+ return True
+ return False
+
+
+def best_name_match_kind(patent: model.PatentEntry, display_name: str) -> str:
+ """Best given-name match across all inventors: 'full' > 'initial' > 'none'."""
+ best = "none"
+ for inventor in patent.inventors:
+ if not inventor:
+ continue
+ kind = first_name_match_kind_for_person(inventor, display_name)
+ if kind == "full":
+ return "full"
+ if kind == "initial":
+ best = "initial"
+ return best
diff --git a/service/src/main/inse/patents/authors/ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py
new file mode 100644
index 00000000..11619c3e
--- /dev/null
+++ b/service/src/main/inse/patents/authors/ipc_openalex_mapping.py
@@ -0,0 +1,586 @@
+"""Precomputed IPC/CPC symbol → OpenAlex topic lookups (1:1 per hierarchy level)."""
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any
+
+from inse.models.openalex.author import Author
+from inse.patents.common import model
+from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol
+
+MAPPING_FILENAME = "ipc_openalex_topic_mapping.json"
+TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json"
+LEVELS = ("section", "class", "subclass", "group", "subgroup")
+MATCH_LEVELS = ("subgroup", "group", "subclass")
+
+# High-frequency IPC subclasses missing from the ES-built mapping file.
+SUBCLASS_TOPIC_OVERRIDES: dict[str, str] = {
+ "A61B": "Cardiac electrophysiology and arrhythmias",
+ "A61K": "Pharmaceutical studies and practices",
+ "A61P": "Cancer Immunotherapy and Biomarkers",
+ "C07K": "Cancer Immunotherapy and Biomarkers",
+ "C12N": "Biotechnology and Related Fields",
+ "C12Q": "Cancer Immunotherapy and Biomarkers",
+ "G01N": "Analytical Methods in Pharmaceuticals",
+}
+
+_TOPIC_LABEL_STOPWORDS = frozenset({
+ "and",
+ "the",
+ "for",
+ "of",
+ "in",
+ "with",
+ "their",
+ "from",
+ "into",
+ "via",
+ "disease",
+ "diseases",
+ "treatment",
+ "treatments",
+ "therapy",
+ "therapies",
+ "application",
+ "applications",
+ "studies",
+ "study",
+ "research",
+ "methods",
+ "method",
+ "systems",
+ "system",
+ "analysis",
+ "molecular",
+ "compounds",
+ "compound",
+ "interactions",
+ "interaction",
+ "effects",
+ "properties",
+ "based",
+ "related",
+ "advanced",
+ "novel",
+ "using",
+ "use",
+ "field",
+ "fields",
+ "engineering",
+ "natural",
+ "human",
+ "clinical",
+ "medical",
+ "medicine",
+ "health",
+ "general",
+ "other",
+ "various",
+ "specific",
+ "particular",
+})
+
+
+def _meaningful_topic_tokens(label: str) -> set[str]:
+ return {
+ token
+ for token in label.casefold().split()
+ if len(token) > 3 and token not in _TOPIC_LABEL_STOPWORDS
+ }
+
+
+@dataclass(frozen=True)
+class MappedOpenAlexTopic:
+ topic_id: str
+ topic_display_name: str | None = None
+ subfield_id: str | None = None
+ field_id: str | None = None
+ domain_id: str | None = None
+ subfield_name: str | None = None
+ field_name: str | None = None
+ domain_name: str | None = None
+ ipc_level: str | None = None
+ ipc_symbol: str | None = None
+
+
+@dataclass(frozen=True)
+class OpenAlexTopicRefs:
+ topic_ids: frozenset[str]
+ subfield_ids: frozenset[str]
+ field_ids: frozenset[str]
+ domain_ids: frozenset[str]
+
+
+def normalize_openalex_id(value: str | None) -> str | None:
+ if not value or not str(value).strip():
+ return None
+ cleaned = str(value).strip()
+ if cleaned.startswith("https://openalex.org/"):
+ return cleaned.rsplit("/", 1)[-1]
+ return cleaned
+
+
+def _data_dir() -> str:
+ for base in (
+ "/data",
+ os.path.normpath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data")
+ ),
+ ):
+ if os.path.isdir(base):
+ return base
+ return os.path.normpath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data")
+ )
+
+
+def _mapping_path() -> str:
+ return os.path.join(_data_dir(), MAPPING_FILENAME)
+
+
+@lru_cache(maxsize=1)
+def _load_topic_cache() -> dict[str, dict[str, str]]:
+ path = os.path.join(_data_dir(), TOPIC_CACHE_FILENAME)
+ try:
+ with open(path, encoding="utf-8") as handle:
+ raw = json.load(handle)
+ except (OSError, json.JSONDecodeError):
+ return {}
+ if not isinstance(raw, dict):
+ return {}
+ return {
+ display_name: {
+ "topic_id": str(info.get("topic_id", "")),
+ "subfield": info.get("subfield"),
+ "field": info.get("field"),
+ "domain": info.get("domain"),
+ }
+ for display_name, info in raw.items()
+ if isinstance(info, dict) and info.get("topic_id")
+ }
+
+
+def _enrich_mapped_topic(mapped: MappedOpenAlexTopic) -> MappedOpenAlexTopic:
+ cache = _load_topic_cache()
+ topic_name = mapped.topic_display_name or ""
+ info = cache.get(topic_name)
+ if info is None:
+ for candidate in cache.values():
+ if candidate.get("topic_id") == mapped.topic_id:
+ info = candidate
+ break
+ if info is None:
+ return mapped
+ return MappedOpenAlexTopic(
+ topic_id=mapped.topic_id,
+ topic_display_name=mapped.topic_display_name or topic_name,
+ subfield_id=mapped.subfield_id,
+ field_id=mapped.field_id,
+ domain_id=mapped.domain_id,
+ subfield_name=info.get("subfield"),
+ field_name=info.get("field"),
+ domain_name=info.get("domain"),
+ ipc_level=mapped.ipc_level,
+ ipc_symbol=mapped.ipc_symbol,
+ )
+
+
+def _mapped_from_topic_name(
+ topic_display_name: str,
+ *,
+ ipc_level: str,
+ ipc_symbol: str,
+) -> MappedOpenAlexTopic | None:
+ cache = _load_topic_cache()
+ info = cache.get(topic_display_name)
+ if info is None:
+ return None
+ return _enrich_mapped_topic(
+ MappedOpenAlexTopic(
+ topic_id=info["topic_id"],
+ topic_display_name=topic_display_name,
+ ipc_level=ipc_level,
+ ipc_symbol=ipc_symbol,
+ )
+ )
+
+
+def _apply_subclass_overrides(
+ parsed: dict[str, dict[str, MappedOpenAlexTopic]],
+) -> None:
+ for symbol, topic_name in SUBCLASS_TOPIC_OVERRIDES.items():
+ mapped = _mapped_from_topic_name(
+ topic_name,
+ ipc_level="subclass",
+ ipc_symbol=_normalize_symbol(symbol),
+ )
+ if mapped is not None:
+ parsed["subclass"][_normalize_symbol(symbol)] = mapped
+
+
+@lru_cache(maxsize=1)
+def load_ipc_openalex_mapping() -> dict[str, dict[str, MappedOpenAlexTopic]]:
+ path = _mapping_path()
+ try:
+ with open(path, encoding="utf-8") as handle:
+ raw = json.load(handle)
+ except (OSError, json.JSONDecodeError):
+ raw = {}
+
+ parsed: dict[str, dict[str, MappedOpenAlexTopic]] = {level: {} for level in LEVELS}
+ for level in LEVELS:
+ for symbol, entry in (raw.get(level) or {}).items():
+ if not isinstance(entry, dict):
+ continue
+ topic_id = entry.get("topic_id")
+ if not topic_id:
+ continue
+ normalized_symbol = _normalize_symbol(symbol)
+ mapped = _enrich_mapped_topic(
+ MappedOpenAlexTopic(
+ topic_id=str(topic_id),
+ topic_display_name=entry.get("topic_display_name"),
+ subfield_id=entry.get("subfield_id"),
+ field_id=entry.get("field_id"),
+ domain_id=entry.get("domain_id"),
+ subfield_name=entry.get("subfield"),
+ field_name=entry.get("field"),
+ domain_name=entry.get("domain"),
+ ipc_level=level,
+ ipc_symbol=normalized_symbol,
+ )
+ )
+ parsed[level][normalized_symbol] = mapped
+ _apply_subclass_overrides(parsed)
+ return parsed
+
+
+def clear_mapping_cache() -> None:
+ load_ipc_openalex_mapping.cache_clear()
+ _load_topic_cache.cache_clear()
+ from inse.patents.patents_openalex_keywords.resolver import clear_resolver_caches
+
+ clear_resolver_caches()
+
+
+def _normalize_symbol(symbol: str | None) -> str:
+ if not symbol:
+ return ""
+ return symbol.strip().upper().replace(" ", "")
+
+
+def _entry_from_raw(entry: dict[str, Any]) -> MappedOpenAlexTopic | None:
+ topic_id = entry.get("topic_id")
+ if not topic_id:
+ return None
+ return MappedOpenAlexTopic(
+ topic_id=str(topic_id),
+ topic_display_name=entry.get("topic_display_name"),
+ subfield_id=entry.get("subfield_id"),
+ field_id=entry.get("field_id"),
+ domain_id=entry.get("domain_id"),
+ ipc_level=entry.get("ipc_level"),
+ ipc_symbol=entry.get("ipc_symbol"),
+ )
+
+
+def lookup_mapped_topic(
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]],
+ level: str,
+ symbol: str | None,
+) -> MappedOpenAlexTopic | None:
+ if not symbol:
+ return None
+ return mapping.get(level, {}).get(_normalize_symbol(symbol))
+
+
+def hierarchy_keys_for_symbol(raw_code: str):
+ return parse_ipc_symbol(extract_ipc_symbol(raw_code))
+
+
+def resolve_mapped_topics_for_code(
+ raw_code: str,
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+) -> list[MappedOpenAlexTopic]:
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ keys = hierarchy_keys_for_symbol(raw_code)
+ if keys is None:
+ return []
+
+ candidates: list[tuple[str, str | None]] = [
+ ("subgroup", keys.subgroup or keys.normalized),
+ ("group", keys.main_group or keys.normalized),
+ ("subclass", keys.subclass),
+ ]
+ for level, symbol in candidates:
+ if not symbol:
+ continue
+ mapped = lookup_mapped_topic(table, level, symbol)
+ if mapped is not None:
+ return [mapped]
+ return []
+
+
+def resolve_mapped_topics_for_patent(
+ patent: model.PatentEntry,
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+) -> list[MappedOpenAlexTopic]:
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ seen: set[str] = set()
+ resolved: list[MappedOpenAlexTopic] = []
+ for raw_code in (*patent.ipc, *patent.cpc):
+ for mapped in resolve_mapped_topics_for_code(raw_code, table):
+ topic_key = normalize_openalex_id(mapped.topic_id) or mapped.topic_id
+ if topic_key in seen:
+ continue
+ seen.add(topic_key)
+ resolved.append(mapped)
+ return resolved
+
+
+def author_openalex_topic_refs(author: Author) -> OpenAlexTopicRefs:
+ topic_ids: set[str] = set()
+ subfield_ids: set[str] = set()
+ field_ids: set[str] = set()
+ domain_ids: set[str] = set()
+
+ for topic in author.topics or []:
+ topic_id = normalize_openalex_id(getattr(topic, "id", None))
+ if topic_id:
+ topic_ids.add(topic_id)
+ subfield = getattr(topic, "subfield", None)
+ if subfield is not None:
+ subfield_id = normalize_openalex_id(getattr(subfield, "id", None))
+ if subfield_id:
+ subfield_ids.add(subfield_id)
+ field = getattr(topic, "var_field", None) or getattr(topic, "field", None)
+ if field is not None:
+ field_id = normalize_openalex_id(getattr(field, "id", None))
+ if field_id:
+ field_ids.add(field_id)
+ domain = getattr(topic, "domain", None)
+ if domain is not None:
+ domain_id = normalize_openalex_id(getattr(domain, "id", None))
+ if domain_id:
+ domain_ids.add(domain_id)
+
+ return OpenAlexTopicRefs(
+ topic_ids=frozenset(topic_ids),
+ subfield_ids=frozenset(subfield_ids),
+ field_ids=frozenset(field_ids),
+ domain_ids=frozenset(domain_ids),
+ )
+
+
+def author_topic_labels(author: Author) -> set[str]:
+ labels: set[str] = set()
+ for topic in author.topics or []:
+ if topic.display_name:
+ labels.add(topic.display_name.casefold())
+ subfield = getattr(topic, "subfield", None)
+ if subfield is not None and getattr(subfield, "display_name", None):
+ labels.add(subfield.display_name.casefold())
+ field = getattr(topic, "var_field", None) or getattr(topic, "field", None)
+ if field is not None and getattr(field, "display_name", None):
+ labels.add(field.display_name.casefold())
+ return labels
+
+
+def _topic_labels_match(
+ mapped: MappedOpenAlexTopic,
+ author: Author,
+ *,
+ strict: bool = False,
+) -> bool:
+ mapped_label = (mapped.topic_display_name or "").casefold()
+ if not mapped_label:
+ return False
+
+ author_labels = author_topic_labels(author)
+ if mapped_label in author_labels:
+ return True
+
+ if strict:
+ mapped_tokens = _meaningful_topic_tokens(mapped_label)
+ if not mapped_tokens:
+ return False
+ for label in author_labels:
+ if len(mapped_tokens & _meaningful_topic_tokens(label)) >= 2:
+ return True
+ return False
+
+ mapped_tokens = {token for token in mapped_label.split() if len(token) > 2}
+ for label in author_labels:
+ if mapped_label in label or label in mapped_label:
+ return True
+ label_tokens = {token for token in label.split() if len(token) > 2}
+ if len(mapped_tokens & label_tokens) >= 2:
+ return True
+ return False
+
+
+def mapped_topic_refs(mapped: MappedOpenAlexTopic) -> OpenAlexTopicRefs:
+ topic_id = normalize_openalex_id(mapped.topic_id)
+ return OpenAlexTopicRefs(
+ topic_ids=frozenset({topic_id}) if topic_id else frozenset(),
+ subfield_ids=frozenset(
+ {normalize_openalex_id(mapped.subfield_id)}
+ if normalize_openalex_id(mapped.subfield_id)
+ else set()
+ ),
+ field_ids=frozenset(
+ {normalize_openalex_id(mapped.field_id)}
+ if normalize_openalex_id(mapped.field_id)
+ else set()
+ ),
+ domain_ids=frozenset(
+ {normalize_openalex_id(mapped.domain_id)}
+ if normalize_openalex_id(mapped.domain_id)
+ else set()
+ ),
+ )
+
+
+def _hierarchy_names_overlap(mapped: MappedOpenAlexTopic, author: Author) -> bool:
+ mapped_names = {
+ name.casefold()
+ for name in (mapped.subfield_name, mapped.field_name, mapped.domain_name)
+ if name
+ }
+ if not mapped_names:
+ return False
+ return bool(mapped_names & author_topic_labels(author))
+
+
+def refs_overlap(left: OpenAlexTopicRefs, right: OpenAlexTopicRefs) -> bool:
+ if left.topic_ids & right.topic_ids:
+ return True
+ if left.subfield_ids & right.subfield_ids:
+ return True
+ if left.field_ids & right.field_ids:
+ return True
+ return False
+
+
+def strict_refs_overlap(left: OpenAlexTopicRefs, right: OpenAlexTopicRefs) -> bool:
+ """Topic/subfield overlap only — used for ambiguous inventor names."""
+ if left.topic_ids & right.topic_ids:
+ return True
+ if left.subfield_ids & right.subfield_ids:
+ return True
+ return False
+
+
+def mapped_topics_match_author_strict(
+ mapped_topics: list[MappedOpenAlexTopic],
+ author: Author,
+) -> bool:
+ author_refs = author_openalex_topic_refs(author)
+ if not any((author_refs.topic_ids, author_refs.subfield_ids)):
+ return True
+ if not mapped_topics:
+ return False
+ return any(
+ strict_refs_overlap(mapped_topic_refs(mapped), author_refs)
+ for mapped in mapped_topics
+ )
+
+
+def mapped_topics_match_author_for_ambiguous(
+ patent: model.PatentEntry,
+ author: Author,
+ keywords_mapped: list[MappedOpenAlexTopic],
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+) -> bool:
+ """Topic match for same-named inventors without hierarchy/field false positives."""
+ from inse.patents.authors.identity import best_name_match_kind
+
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ legacy_mapped = resolve_mapped_topics_for_patent(patent, table)
+
+ if mapped_topics_match_author_strict(keywords_mapped, author):
+ return True
+ if mapped_topics_match_author_strict(legacy_mapped, author):
+ return True
+ if any(
+ _topic_labels_match(mapped, author, strict=True)
+ for mapped in keywords_mapped
+ ):
+ return True
+ if best_name_match_kind(patent, author.display_name or "") != "full":
+ return False
+ return _legacy_primary_field_name_matches_author(patent, author, table)
+
+
+def _primary_legacy_mapped_topics(
+ patent: model.PatentEntry,
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+) -> list[MappedOpenAlexTopic]:
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ for raw_code in patent.ipc or []:
+ mapped = resolve_mapped_topics_for_code(raw_code, table)
+ if mapped:
+ return mapped
+ return []
+
+
+def _legacy_primary_field_name_matches_author(
+ patent: model.PatentEntry,
+ author: Author,
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+) -> bool:
+ if not patent.ipc:
+ return False
+ keys = parse_ipc_symbol(extract_ipc_symbol(patent.ipc[0]))
+ if keys is None:
+ return False
+ section = (keys.section or "").upper()
+ subclass = (keys.subclass or "")[:3].upper()
+ if section == "B":
+ return False
+ if section not in {"A", "C"}:
+ return False
+ if section == "C" and subclass not in {"C07", "C12"}:
+ return False
+
+ primary = _primary_legacy_mapped_topics(patent, mapping)
+ if not primary:
+ return False
+ author_labels = author_topic_labels(author)
+ return any(
+ (mapped.field_name or "").casefold() in author_labels
+ for mapped in primary
+ if mapped.field_name
+ )
+
+
+def mapped_topics_match_author(
+ mapped_topics: list[MappedOpenAlexTopic],
+ author: Author,
+) -> bool:
+ author_refs = author_openalex_topic_refs(author)
+ if not any((author_refs.topic_ids, author_refs.subfield_ids, author_refs.field_ids)):
+ return True
+ if not mapped_topics:
+ return False
+ return any(
+ refs_overlap(mapped_topic_refs(mapped), author_refs)
+ or _topic_labels_match(mapped, author)
+ or _hierarchy_names_overlap(mapped, author)
+ for mapped in mapped_topics
+ )
+
+
+def patent_topics_match_author(
+ patent: model.PatentEntry,
+ author: Author,
+ mapping: dict[str, dict[str, MappedOpenAlexTopic]] | None = None,
+ *,
+ mapped_topics: list[MappedOpenAlexTopic] | None = None,
+) -> bool:
+ if mapped_topics is None:
+ mapped_topics = resolve_mapped_topics_for_patent(patent, mapping)
+ return mapped_topics_match_author(mapped_topics, author)
diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py
index 0dc34be1..8b2df53a 100644
--- a/service/src/main/inse/patents/authors/logic.py
+++ b/service/src/main/inse/patents/authors/logic.py
@@ -7,12 +7,17 @@ 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.authors.identity import is_ambiguous_name
+from inse.patents.authors.name_matching import filter_patents_by_author_name
+from inse.patents.authors.name_variants import parse_person_name
+from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
+from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
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,
+ expand_matched_epo_application_families,
parse_epo_hits,
parse_uspto_hits,
)
@@ -23,7 +28,6 @@ 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,
@@ -32,7 +36,7 @@ async def get_patents_by_author_id(
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
- author = _get_author(author_id)
+ author = await _get_author(author_id)
if not author:
return model.PatentsByAuthorResponse(
author_id=author_id,
@@ -42,10 +46,7 @@ async def get_patents_by_author_id(
)
author_name = author.display_name
- last_name = _extract_last_name(author_name)
- first_name = _extract_first_name(author_name)
-
- if not last_name:
+ if not author_name or not author_name.strip():
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
@@ -54,9 +55,7 @@ async def get_patents_by_author_id(
)
try:
- epo_data, uspto_data = await _search_both_indices(
- search_client, last_name, first_name
- )
+ epo_data, uspto_data = await _search_both_indices(search_client, author_name)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
@@ -69,54 +68,84 @@ async def get_patents_by_author_id(
) 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)
+ patent_hit_count = len(all_patents)
+ matched_patents = filter_patents_by_author_name(all_patents, author_name)
+ try:
+ matched_patents = await expand_matched_epo_application_families(
+ matched_patents,
+ search_client,
+ )
+ except Exception:
+ logger.exception(
+ "EPO family expansion failed for %s; continuing with name-matched patents only",
+ author_name,
+ )
+
+ if not matched_patents:
+ return model.PatentsByAuthorResponse(
+ author_id=author_id,
+ author_name=author_name,
+ patent_count=0,
+ patents=[],
+ )
+
+ await enrich_patents_classifications(matched_patents, ipc_search_client)
+
+ full_name_count = await person_logic.count_authors_by_display_name(author_name)
+ parsed_for_last = parse_person_name(author_name)
+ last_name_count: int | None = None
+ if parsed_for_last and not parsed_for_last.is_single_token:
+ last_name_count = await person_logic.count_authors_by_last_name(
+ parsed_for_last.last_name
+ )
+ is_ambiguous = is_ambiguous_name(
+ author_name,
+ patent_hit_count=patent_hit_count,
+ openalex_full_name_count=full_name_count,
+ openalex_last_name_count=last_name_count,
+ )
+
+ patent_topic_map = None
+ try:
+ resolver = PatentOpenAlexMappingResolver()
+ patent_topic_map = await resolver.resolve_topics_for_patents(matched_patents)
+ except Exception:
+ logger.exception(
+ "OpenAlex topic resolution failed for %s; falling back to legacy mapping",
+ author_name,
+ )
+
+ filtered = filter_patents_by_ipc_topic_mapping(
+ matched_patents,
+ author,
+ is_ambiguous=is_ambiguous,
+ patent_topic_map=patent_topic_map,
+ )
+
+ logger.info(
+ "patents_openalex_keywords mapping for %s: ambiguous=%s, %d name-matched, %d after topic filter",
+ author_name,
+ is_ambiguous,
+ len(matched_patents),
+ len(filtered),
+ )
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
- patent_count=len(all_patents),
- patents=all_patents,
+ patent_count=len(filtered),
+ patents=[item.patent for item in filtered],
)
-
-async def _search_both_indices(client, last_name, first_name):
+async def _search_both_indices(client, display_name: str):
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)),
+ client.search_epo(client.epo_query_by_inventor(display_name)),
+ client.search_uspto(client.uspto_query_by_inventor(display_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:
+async 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)
+ result = await 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
diff --git a/service/src/main/inse/patents/authors/name_matching.py b/service/src/main/inse/patents/authors/name_matching.py
index 369c44ab..f55ff54f 100644
--- a/service/src/main/inse/patents/authors/name_matching.py
+++ b/service/src/main/inse/patents/authors/name_matching.py
@@ -1,10 +1,17 @@
"""Inventor name normalization and matching."""
-import re
+from inse.patents.authors.name_variants import (
+ ParsedPersonName,
+ parse_inventor_name,
+ parse_person_name,
+ _initials_from_tokens,
+)
+from inse.patents.common import model
from inse.patents.common.text_normalization import (
name_token_variants,
normalize_name_part,
patent_transliteration_expansions,
+ strip_person_titles,
)
@@ -49,7 +56,10 @@ def _initial_tokens_match(left: str | None, right: str | None) -> bool:
return False
-def _inventor_first_token(inventor_name: str) -> str:
+def inventor_first_token(inventor_name: str) -> str:
+ parsed = parse_inventor_name(inventor_name)
+ if parsed and parsed.primary_given_name:
+ return parsed.primary_given_name
if "," in inventor_name:
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
return first_part.split()[0] if first_part else ""
@@ -57,18 +67,111 @@ def _inventor_first_token(inventor_name: str) -> str:
return parts[0] if parts else ""
+def inventor_search_phrases(display_name: str) -> list[str]:
+ parsed = parse_person_name(display_name)
+ if parsed is None:
+ return []
+
+ if parsed.is_single_token:
+ return search_name_variants(parsed.last_name)
+
+ seen: set[str] = set()
+ phrases: list[str] = []
+
+ def _add(phrase: str) -> None:
+ phrase = phrase.strip()
+ if not phrase:
+ return
+ key = phrase.casefold()
+ if key in seen:
+ return
+ seen.add(key)
+ phrases.append(phrase)
+
+ given_names = list(parsed.given_names)
+ last_name = parsed.last_name
+ compound_last = parsed.compound_last_name
+ full_given = " ".join(given_names)
+
+ _add(f"{full_given} {last_name}")
+ if compound_last and compound_last != last_name:
+ _add(f"{full_given} {compound_last}")
+
+ for given_name in given_names:
+ _add(f"{given_name} {last_name}")
+ if compound_last and compound_last != last_name:
+ _add(f"{given_name} {compound_last}")
+
+ initials = _initials_from_tokens(given_names)
+ if initials:
+ _add(f"{initials} {last_name}")
+ if compound_last and compound_last != last_name:
+ _add(f"{initials} {compound_last}")
+ dotted = ".".join(char for char in initials) + "."
+ _add(f"{dotted} {last_name}")
+ if compound_last and compound_last != last_name:
+ _add(f"{dotted} {compound_last}")
+
+ _add(f"{last_name}, {full_given}")
+ for given_name in given_names:
+ _add(f"{last_name}, {given_name}")
+ if compound_last and compound_last != last_name:
+ _add(f"{compound_last}, {full_given}")
+
+ expanded: list[str] = []
+ expanded_seen: set[str] = set()
+ for phrase in phrases:
+ for variant in search_name_variants(phrase):
+ key = variant.casefold()
+ if key in expanded_seen:
+ continue
+ expanded_seen.add(key)
+ expanded.append(variant)
+
+ return expanded
+
+
+def name_matches_person(inventor_name: str, person_display_name: str) -> bool:
+ author = parse_person_name(person_display_name)
+ inventor = parse_inventor_name(strip_person_titles(inventor_name))
+ if author is None or inventor is None:
+ return False
+
+ if author.is_single_token:
+ return _family_name_matches(author, inventor)
+
+ if not _family_name_matches(author, inventor):
+ return False
+ if not _given_name_matches(author, inventor):
+ return False
+ return _author_middle_initials_corroborated(author, inventor)
+
+
+def first_name_match_kind_for_person(
+ inventor_name: str,
+ person_display_name: str,
+) -> str:
+ if not name_matches_person(inventor_name, person_display_name):
+ return "none"
+ if _given_names_full_match(
+ parse_person_name(person_display_name),
+ parse_inventor_name(inventor_name),
+ ):
+ return "full"
+ return "initial"
+
+
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"
+ if first_name:
+ return first_name_match_kind_for_person(
+ inventor_name,
+ f"{first_name} {last_name}",
+ )
+ return first_name_match_kind_for_person(inventor_name, last_name)
def search_name_variants(value: str | None) -> list[str]:
@@ -105,24 +208,158 @@ def search_name_variants(value: str | None) -> list[str]:
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
if not inventor_name or not last_name:
return False
+ if first_name:
+ return name_matches_person(inventor_name, f"{first_name} {last_name}")
+ return name_matches_person(inventor_name, last_name)
- 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)
+def inventor_last_name(inventor_name: str) -> str | None:
+ parsed = parse_inventor_name(inventor_name)
+ return parsed.last_name if parsed else None
+
+
+def filter_patents_by_author_name(
+ patents: list[model.PatentEntry],
+ display_name: str,
+) -> list[model.PatentEntry]:
+ parsed = parse_person_name(display_name)
+ if parsed and parsed.is_single_token:
+ last_name = parsed.last_name
+ return [
+ patent
+ for patent in patents
+ if any(
+ tokens_equal(inventor_last_name(inventor), last_name, allow_initial=False)
+ for inventor in patent.inventors
+ )
+ ]
+
+ return [
+ patent
+ for patent in patents
+ if any(
+ name_matches_person(inventor, display_name)
+ for inventor in patent.inventors
)
+ or any(
+ name_matches_person(assignee, display_name)
+ for assignee in patent.assignees
+ )
+ ]
- parts = name.split()
- if len(parts) < 2:
+
+def _family_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> bool:
+ author_candidates = _family_name_candidates(author)
+ inventor_candidates = _family_name_candidates(inventor)
+ return any(
+ tokens_equal(author_name, inventor_name, allow_initial=False)
+ for author_name in author_candidates
+ for inventor_name in inventor_candidates
+ )
+
+
+def _family_name_candidates(parsed: ParsedPersonName) -> set[str]:
+ candidates = {parsed.last_name}
+ if parsed.compound_last_name:
+ candidates.add(parsed.compound_last_name)
+ return candidates
+
+
+def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) -> bool:
+ if not author.given_names:
+ return True
+ if not inventor.given_names:
return False
- return (
- tokens_equal(parts[-1], last_name, allow_initial=False)
- and bool(first_name)
- and tokens_equal(parts[0], first_name)
+ # Accept immediately when at least one inventor given-name token matches
+ # one of the author's given names as a full token (not only initial),
+ # e.g. "Maria Schmidt" vs "Anna Maria Schmidt". This only counts if at
+ # least one side is a spelled-out name, not a bare initial — two
+ # coincidentally identical single-letter tokens (e.g. both just "K.")
+ # are far too weak a signal on their own and would otherwise match
+ # anyone sharing that one middle initial regardless of their actual
+ # first name (e.g. "Mahendra K. Sharma" incorrectly matching inventor
+ # "Vivek K." or "Virender K." on an unrelated patent).
+ if any(
+ any(
+ tokens_equal(author_given, inventor_given, allow_initial=False)
+ and not (_initial_letter(author_given) and _initial_letter(inventor_given))
+ for author_given in author.given_names
+ )
+ for inventor_given in inventor.given_names
+ ):
+ return True
+
+ inventor_tokens_full = [
+ token for token in inventor.given_names
+ if _initial_letter(token) is None
+ ]
+
+ # Prevent false positives like "Karem C Weber" for "Christian Weber":
+ # if inventor has full given-name tokens but none matches the author,
+ # we reject even if one initial overlaps.
+ if inventor_tokens_full:
+ return False
+
+ # Initials-only inventor names (e.g. "C. Weber", "P. J. Marrón")
+ # are considered a match only when every initial maps to one of
+ # the author's given names.
+ return all(
+ any(
+ tokens_equal(author_given, inventor_given, allow_initial=True)
+ for author_given in author.given_names
+ )
+ for inventor_given in inventor.given_names
)
+
+
+def _given_names_full_match(
+ author: ParsedPersonName | None,
+ inventor: ParsedPersonName | None,
+) -> bool:
+ if author is None or inventor is None or not author.given_names:
+ return False
+ if not inventor.given_names:
+ return False
+
+ primary = author.primary_given_name
+ if not primary:
+ return False
+
+ if not any(
+ tokens_equal(primary, inventor_given, allow_initial=False)
+ for inventor_given in inventor.given_names
+ ):
+ return False
+
+ for inventor_given in inventor.given_names:
+ if _initial_letter(inventor_given) and not any(
+ tokens_equal(author_given, inventor_given, allow_initial=False)
+ for author_given in author.given_names
+ ):
+ return False
+
+ return _author_middle_initials_corroborated(author, inventor)
+
+
+def _author_middle_initials_corroborated(
+ author: ParsedPersonName,
+ inventor: ParsedPersonName,
+) -> bool:
+ """Require middle initials in the author name to appear on the inventor side.
+
+ Prevents false positives such as attributing patents for "Schmitz, Oliver"
+ to the distinct person "Oliver J. Schmitz".
+ """
+ if len(author.given_names) <= 1:
+ return True
+
+ for author_given in author.given_names[1:]:
+ if _initial_letter(author_given) is None:
+ continue
+ if not any(
+ tokens_equal(author_given, inventor_given, allow_initial=True)
+ for inventor_given in inventor.given_names
+ ):
+ return False
+ return True
diff --git a/service/src/main/inse/patents/authors/name_variants.py b/service/src/main/inse/patents/authors/name_variants.py
new file mode 100644
index 00000000..c1f7a5e0
--- /dev/null
+++ b/service/src/main/inse/patents/authors/name_variants.py
@@ -0,0 +1,111 @@
+"""Parse person names and build search/match variants for multi-part names."""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from inse.patents.common.text_normalization import normalize_name_part
+
+_NAME_SUFFIXES = frozenset({
+ "dr", "prof", "mr", "mrs", "ms", "phd", "ph", "md", "jr", "sr",
+})
+
+
+@dataclass(frozen=True)
+class ParsedPersonName:
+ raw: str
+ tokens: tuple[str, ...]
+ given_names: tuple[str, ...]
+ last_name: str
+ compound_last_name: str | None
+
+ @property
+ def is_single_token(self) -> bool:
+ return len(self.tokens) == 1
+
+ @property
+ def primary_given_name(self) -> str | None:
+ return self.given_names[0] if self.given_names else None
+
+
+def parse_person_name(display_name: str | None) -> ParsedPersonName | None:
+ if not display_name or not display_name.strip():
+ return None
+
+ cleaned = _strip_name_suffixes(display_name.strip())
+ tokens = tuple(part for part in cleaned.split() if part)
+ if not tokens:
+ return None
+
+ if len(tokens) == 1:
+ return ParsedPersonName(
+ raw=display_name.strip(),
+ tokens=tokens,
+ given_names=(),
+ last_name=tokens[0],
+ compound_last_name=None,
+ )
+
+ given_names = tokens[:-1]
+ last_name = tokens[-1]
+ compound_last_name = " ".join(tokens[-2:]) if len(tokens) >= 3 else None
+
+ return ParsedPersonName(
+ raw=display_name.strip(),
+ tokens=tokens,
+ given_names=given_names,
+ last_name=last_name,
+ compound_last_name=compound_last_name,
+ )
+
+
+def parse_inventor_name(inventor_name: str | None) -> ParsedPersonName | None:
+ if not inventor_name or not inventor_name.strip():
+ return None
+
+ cleaned = _strip_name_suffixes(inventor_name.strip())
+ if "," in cleaned:
+ last_part, first_part = [part.strip() for part in cleaned.split(",", 1)]
+ family_tokens = tuple(token for token in last_part.split() if token)
+ given_tokens = tuple(token for token in first_part.split() if token)
+ if not family_tokens:
+ return None
+ tokens = given_tokens + family_tokens
+ return ParsedPersonName(
+ raw=inventor_name.strip(),
+ tokens=tokens,
+ given_names=given_tokens,
+ last_name=family_tokens[-1],
+ compound_last_name=(
+ " ".join(family_tokens)
+ if len(family_tokens) > 1
+ else None
+ ),
+ )
+
+ return parse_person_name(cleaned)
+
+
+def _strip_name_suffixes(name: str) -> str:
+ parts = [part.strip() for part in name.split(",")]
+ while len(parts) > 1 and _is_name_suffix(parts[-1]):
+ parts = parts[:-1]
+ return ", ".join(parts).strip()
+
+
+def _is_name_suffix(value: str) -> bool:
+ normalized = normalize_name_part(value).rstrip(".")
+ return normalized in _NAME_SUFFIXES
+
+
+def _initials_from_tokens(tokens: list[str]) -> str:
+ initials = ""
+ for token in tokens:
+ normalized = normalize_name_part(token)
+ if not normalized:
+ continue
+ if len(normalized) == 1:
+ initials += normalized.upper()
+ else:
+ initials += normalized[0].upper()
+ return initials
diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py
index 2149fa98..af67bf1d 100644
--- a/service/src/main/inse/patents/authors/search_queries.py
+++ b/service/src/main/inse/patents/authors/search_queries.py
@@ -1,7 +1,8 @@
"""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.authors.name_matching import inventor_search_phrases, search_name_variants
+from inse.patents.authors.name_variants import parse_person_name
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
@@ -17,32 +18,51 @@ def _match_name_field(field: str, name: str) -> dict[str, Any]:
}
+def _match_any_phrase_field(field: str, phrases: list[str]) -> dict[str, Any]:
+ if not phrases:
+ return {"match_none": {}}
+ if len(phrases) == 1:
+ return {"match": {field: phrases[0]}}
+ return {
+ "bool": {
+ "should": [{"match": {field: phrase}} for phrase in phrases],
+ "minimum_should_match": 1,
+ }
+ }
+
+
class InventorSearchQueries:
def epo_query_by_inventor(
self,
- last_name: str,
+ display_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
- if first_name:
+ if first_name and display_name and " " not in display_name.strip():
+ display_name = f"{first_name} {display_name}".strip()
+
+ parsed = parse_person_name(display_name)
+ if parsed is None:
+ query = {"match_none": {}}
+ elif parsed.is_single_token:
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),
- ]
- }
- },
+ "query": _match_name_field(
+ "inventors_name_nested.inventor",
+ parsed.last_name,
+ ),
}
}
else:
+ phrases = inventor_search_phrases(display_name)
query = {
"nested": {
"path": "inventors_name_nested",
- "query": _match_name_field("inventors_name_nested.inventor", last_name),
+ "query": _match_any_phrase_field(
+ "inventors_name_nested.inventor",
+ phrases,
+ ),
}
}
@@ -73,31 +93,73 @@ class InventorSearchQueries:
"query": query,
}
+ def epo_query_by_application_number(
+ self,
+ application_number: str,
+ size: int = 20,
+ ) -> dict[str, Any]:
+ variants = _application_number_variants(application_number)
+ if not variants:
+ return {"size": 0, "query": {"match_none": {}}}
+
+ should = [{"term": {"application_number": variant}} for variant in variants]
+ query: dict[str, Any] = (
+ should[0]
+ if len(should) == 1
+ else {"bool": {"should": should, "minimum_should_match": 1}}
+ )
+
+ return {
+ "size": size,
+ "track_total_hits": True,
+ "sort": [
+ {"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,
+ display_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
- if first_name:
+ if first_name and display_name and " " not in display_name.strip():
+ display_name = f"{first_name} {display_name}".strip()
+
+ parsed = parse_person_name(display_name)
+ if parsed is None:
+ query = {"match_none": {}}
+ elif parsed.is_single_token:
query = {
"nested": {
"path": "inventors",
- "query": {
- "bool": {
- "must": [
- _match_name_field("inventors.name", last_name),
- _match_name_field("inventors.name", first_name),
- ]
- }
- },
+ "query": _match_name_field("inventors.name", parsed.last_name),
}
}
else:
+ phrases = inventor_search_phrases(display_name)
query = {
"nested": {
"path": "inventors",
- "query": _match_name_field("inventors.name", last_name),
+ "query": _match_any_phrase_field("inventors.name", phrases),
}
}
@@ -128,3 +190,23 @@ class InventorSearchQueries:
],
"query": query,
}
+
+
+def _application_number_variants(application_number: str) -> list[str]:
+ cleaned = application_number.strip()
+ if not cleaned:
+ return []
+
+ seen: set[str] = set()
+ variants: list[str] = []
+
+ def _add(value: str) -> None:
+ value = value.strip()
+ if value and value not in seen:
+ seen.add(value)
+ variants.append(value)
+
+ _add(cleaned)
+ if cleaned.upper().startswith("EP"):
+ _add(cleaned[2:])
+ return variants
diff --git a/service/src/main/inse/patents/authors/test_identity.py b/service/src/main/inse/patents/authors/test_identity.py
new file mode 100644
index 00000000..a4ac8a05
--- /dev/null
+++ b/service/src/main/inse/patents/authors/test_identity.py
@@ -0,0 +1,51 @@
+from inse.patents.authors.identity import (
+ OPENALEX_FULL_NAME_COUNT_THRESHOLD,
+ OPENALEX_LAST_NAME_COUNT_THRESHOLD,
+ PATENT_HIT_COUNT_THRESHOLD,
+ is_ambiguous_name,
+)
+
+
+def test_mononym_is_always_ambiguous() -> None:
+ assert is_ambiguous_name("Weber") is True
+ assert is_ambiguous_name("") is True
+ assert is_ambiguous_name(None) is True
+
+
+def test_two_token_name_not_ambiguous_without_signals() -> None:
+ assert is_ambiguous_name("Pedro Marrón") is False
+
+
+def test_full_name_collision_makes_name_ambiguous() -> None:
+ assert (
+ is_ambiguous_name(
+ "Christian Weber",
+ openalex_full_name_count=OPENALEX_FULL_NAME_COUNT_THRESHOLD,
+ )
+ is True
+ )
+ # A single OpenAlex author with that exact name is not a collision.
+ assert (
+ is_ambiguous_name("Christian Weber", openalex_full_name_count=1) is False
+ )
+
+
+def test_last_name_collision_makes_name_ambiguous() -> None:
+ assert (
+ is_ambiguous_name(
+ "Christian Weber",
+ openalex_last_name_count=OPENALEX_LAST_NAME_COUNT_THRESHOLD,
+ )
+ is True
+ )
+ assert (
+ is_ambiguous_name("Christian Weber", openalex_last_name_count=10) is False
+ )
+
+
+def test_many_patent_hits_make_name_ambiguous() -> None:
+ assert (
+ is_ambiguous_name("Christian Weber", patent_hit_count=PATENT_HIT_COUNT_THRESHOLD)
+ is True
+ )
+ assert is_ambiguous_name("Christian Weber", patent_hit_count=5) is False
diff --git a/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py
new file mode 100644
index 00000000..c7a7467f
--- /dev/null
+++ b/service/src/main/inse/patents/authors/test_ipc_openalex_mapping.py
@@ -0,0 +1,224 @@
+from inse.models.openalex.author import Author
+from inse.models.openalex.work_topic import WorkTopic
+from inse.models.openalex.work_topic_domain import WorkTopicDomain
+from inse.models.openalex.work_topic_field import WorkTopicField
+from inse.models.openalex.work_topic_subfield import WorkTopicSubfield
+from inse.patents.authors import ipc_openalex_mapping as mapping_module
+from inse.patents.authors.ipc_openalex_mapping import (
+ clear_mapping_cache,
+ load_ipc_openalex_mapping,
+ mapped_topics_match_author,
+ patent_topics_match_author,
+ resolve_mapped_topics_for_code,
+)
+from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
+from inse.patents.common import model
+
+
+def _author_with_topic(
+ topic_id: str,
+ display_name: str,
+ *,
+ subfield_id: str = "https://openalex.org/subfields/2208",
+ field_id: str = "https://openalex.org/fields/22",
+ domain_id: str = "https://openalex.org/domains/3",
+) -> Author:
+ return Author(
+ display_name="Test Author",
+ topics=[
+ WorkTopic(
+ id=topic_id,
+ display_name=display_name,
+ score=1.0,
+ subfield=WorkTopicSubfield(
+ id=subfield_id,
+ display_name="Subfield",
+ ),
+ var_field=WorkTopicField(
+ id=field_id,
+ display_name="Field",
+ ),
+ domain=WorkTopicDomain(
+ id=domain_id,
+ display_name="Domain",
+ ),
+ )
+ ],
+ )
+
+
+def _patent(ipc_codes: list[str]) -> model.PatentEntry:
+ return model.PatentEntry(
+ patent_id="EP1",
+ source="EPO",
+ ipc=ipc_codes,
+ )
+
+
+def _custom_mapping() -> dict[str, dict[str, mapping_module.MappedOpenAlexTopic]]:
+ table: dict[str, dict[str, mapping_module.MappedOpenAlexTopic]] = {
+ level: {} for level in ("section", "class", "subclass", "group", "subgroup")
+ }
+ table["subclass"]["H01L"] = mapping_module.MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99999",
+ topic_display_name="Semiconductor materials and devices",
+ ipc_level="subclass",
+ ipc_symbol="H01L",
+ )
+ table["subclass"]["A61B"] = mapping_module.MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T10217",
+ topic_display_name="Cardiac electrophysiology and arrhythmias",
+ ipc_level="subclass",
+ ipc_symbol="A61B",
+ )
+ return table
+
+
+def test_resolve_mapped_topics_uses_subclass_mapping() -> None:
+ custom = _custom_mapping()
+ mapped = resolve_mapped_topics_for_code("H01L 21/02", custom)
+ assert mapped
+ assert mapped[0].topic_id.endswith("T99999")
+
+
+def test_patent_topics_match_author_on_topic_id() -> None:
+ custom = _custom_mapping()
+ author = _author_with_topic(
+ "https://openalex.org/T99999",
+ "Semiconductor materials and devices",
+ )
+ patent = _patent(["H01L 21/02"])
+ assert patent_topics_match_author(patent, author, custom) is True
+
+
+def test_patent_topics_do_not_match_unrelated_author() -> None:
+ custom = _custom_mapping()
+ author = _author_with_topic(
+ "https://openalex.org/T10217",
+ "Cardiac electrophysiology and arrhythmias",
+ subfield_id="https://openalex.org/subfields/2705",
+ field_id="https://openalex.org/fields/27",
+ domain_id="https://openalex.org/domains/4",
+ )
+ patent = _patent(["H01L 21/02"])
+ assert patent_topics_match_author(patent, author, custom) is False
+
+
+def test_filter_rejects_ambiguous_name_without_topic_match() -> None:
+ custom = _custom_mapping()
+ author = _author_with_topic(
+ "https://openalex.org/T10217",
+ "Cardiac electrophysiology and arrhythmias",
+ subfield_id="https://openalex.org/subfields/2705",
+ field_id="https://openalex.org/fields/27",
+ domain_id="https://openalex.org/domains/4",
+ )
+ patents = [
+ _patent(["H01L 21/02"]),
+ _patent(["A61B 5/00"]),
+ ]
+ filtered = filter_patents_by_ipc_topic_mapping(
+ patents,
+ author,
+ is_ambiguous=True,
+ mapping=custom,
+ )
+ assert len(filtered) == 1
+ assert filtered[0].patent.ipc == ["A61B 5/00"]
+
+
+def test_filter_rejects_rare_name_on_topic_conflict() -> None:
+ custom = _custom_mapping()
+ author = _author_with_topic(
+ "https://openalex.org/T10217",
+ "Cardiac electrophysiology and arrhythmias",
+ subfield_id="https://openalex.org/subfields/2705",
+ field_id="https://openalex.org/fields/27",
+ domain_id="https://openalex.org/domains/4",
+ )
+ patents = [_patent(["H01L 21/02"])]
+ filtered = filter_patents_by_ipc_topic_mapping(
+ patents,
+ author,
+ is_ambiguous=False,
+ mapping=custom,
+ )
+ assert filtered == []
+
+
+def test_filter_rejects_ambiguous_name_on_fuzzy_label_only_match() -> None:
+ author = _author_with_topic(
+ "https://openalex.org/T12345",
+ "Atherosclerosis and Cardiovascular Diseases",
+ subfield_id="https://openalex.org/subfields/2705",
+ field_id="https://openalex.org/fields/27",
+ domain_id="https://openalex.org/domains/4",
+ )
+ tire_patent = model.PatentEntry(
+ patent_id="US12508845",
+ source="USPTO",
+ title="Vehicle pneumatic tyre and rubber mixture for a tread",
+ ipc=["B60C 1/00"],
+ inventors=["Christian Weber"],
+ )
+ spurious_cardiac = mapping_module.MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99901",
+ topic_display_name="Cardiac Valve Diseases and Treatments",
+ subfield_id="https://openalex.org/subfields/9999",
+ field_id="https://openalex.org/fields/27",
+ field_name="Medicine",
+ )
+ filtered = filter_patents_by_ipc_topic_mapping(
+ [tire_patent],
+ author,
+ is_ambiguous=True,
+ patent_topic_map={"USPTO:US12508845": [spurious_cardiac]},
+ )
+ assert filtered == []
+
+
+def test_filter_keeps_ambiguous_name_on_legacy_ipc_subclass_match() -> None:
+ custom = _custom_mapping()
+ custom["subclass"]["C07K"] = mapping_module.MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T10158",
+ topic_display_name="Cancer Immunotherapy and Biomarkers",
+ ipc_level="subclass",
+ ipc_symbol="C07K",
+ )
+ author = _author_with_topic(
+ "https://openalex.org/T10158",
+ "Cancer Immunotherapy and Biomarkers",
+ subfield_id="https://openalex.org/subfields/2705",
+ field_id="https://openalex.org/fields/27",
+ domain_id="https://openalex.org/domains/4",
+ )
+ patent = model.PatentEntry(
+ patent_id="EP1555271",
+ source="EPO",
+ title="Peptides useful for diagnosis and therapy of TRP-2+ tumors",
+ ipc=["C07K 14/705"],
+ inventors=["Schadendorf, Dirk"],
+ )
+ spurious = mapping_module.MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99999",
+ topic_display_name="Antimicrobial Peptides and Activities",
+ field_name="Medicine",
+ )
+ filtered = filter_patents_by_ipc_topic_mapping(
+ [patent],
+ author,
+ is_ambiguous=True,
+ mapping=custom,
+ patent_topic_map={"EPO:EP1555271": [spurious]},
+ )
+ assert len(filtered) == 1
+
+
+def test_custom_mapping_table() -> None:
+ custom = _custom_mapping()
+ author = Author(
+ display_name="Custom",
+ topics=[WorkTopic(id="https://openalex.org/T99999", display_name="Semiconductor materials and devices")],
+ )
+ patent = _patent(["H01L 21/02"])
+ assert patent_topics_match_author(patent, author, custom) is True
diff --git a/service/src/main/inse/patents/authors/topic_filter.py b/service/src/main/inse/patents/authors/topic_filter.py
new file mode 100644
index 00000000..4ded689c
--- /dev/null
+++ b/service/src/main/inse/patents/authors/topic_filter.py
@@ -0,0 +1,161 @@
+"""Filter name-matched patents using precomputed IPC/CPC → OpenAlex topic mappings."""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from inse.models.openalex.author import Author
+from inse.patents.authors.identity import (
+ patent_institution_match,
+ patent_personal_assignee_match,
+)
+from inse.patents.authors.ipc_openalex_mapping import (
+ MappedOpenAlexTopic,
+ author_openalex_topic_refs,
+ load_ipc_openalex_mapping,
+ mapped_topics_match_author,
+ mapped_topics_match_author_for_ambiguous,
+ patent_topics_match_author,
+ resolve_mapped_topics_for_patent,
+)
+from inse.patents.common import model
+from inse.patents.common.parsing import patent_map_key
+
+
+@dataclass(frozen=True)
+class TopicFilterResult:
+ patent: model.PatentEntry
+ decision: str
+ matched_via_mapping: bool
+ institution_match: bool
+ personal_assignee_match: bool
+
+
+def _author_has_topic_profile(author: Author) -> bool:
+ refs = author_openalex_topic_refs(author)
+ return bool(refs.topic_ids or refs.subfield_ids or refs.field_ids)
+
+
+def _patent_has_mapped_topics(
+ mapped_topics: list[MappedOpenAlexTopic],
+) -> bool:
+ return bool(mapped_topics)
+
+
+def _topic_conflict(
+ mapped_topics: list[MappedOpenAlexTopic],
+ author: Author,
+) -> bool:
+ if not _author_has_topic_profile(author):
+ return False
+ if not _patent_has_mapped_topics(mapped_topics):
+ return False
+ return not mapped_topics_match_author(mapped_topics, author)
+
+
+def _resolve_patent_topics(
+ patent: model.PatentEntry,
+ mapping,
+ patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None,
+) -> list[MappedOpenAlexTopic]:
+ if patent_topic_map is not None:
+ return patent_topic_map.get(patent_map_key(patent), [])
+ return resolve_mapped_topics_for_patent(patent, mapping)
+
+
+def filter_patents_by_ipc_topic_mapping(
+ patents: list[model.PatentEntry],
+ author: Author,
+ *,
+ is_ambiguous: bool = False,
+ mapping=None,
+ patent_topic_map: dict[str, list[MappedOpenAlexTopic]] | None = None,
+) -> list[TopicFilterResult]:
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ institution_names = [
+ name
+ for institution in author.last_known_institutions or []
+ if (name := getattr(institution, "display_name", None))
+ ]
+ for affiliation in author.affiliations or []:
+ institution = getattr(affiliation, "institution", None)
+ if institution is not None and (name := getattr(institution, "display_name", None)):
+ institution_names.append(name)
+
+ display_name = author.display_name or ""
+ filtered: list[TopicFilterResult] = []
+
+ for patent in patents:
+ institution_match = patent_institution_match(patent, institution_names)
+ personal_assignee_match = patent_personal_assignee_match(patent, display_name)
+ strong_identity = institution_match or personal_assignee_match
+ mapped_topics = _resolve_patent_topics(patent, table, patent_topic_map)
+ if is_ambiguous:
+ matched_via_mapping = mapped_topics_match_author_for_ambiguous(
+ patent,
+ author,
+ mapped_topics,
+ table,
+ )
+ elif patent_topic_map is not None:
+ matched_via_mapping = mapped_topics_match_author(mapped_topics, author)
+ else:
+ matched_via_mapping = patent_topics_match_author(patent, author, table)
+
+ if strong_identity:
+ filtered.append(
+ TopicFilterResult(
+ patent=patent,
+ decision="keep",
+ matched_via_mapping=matched_via_mapping,
+ institution_match=institution_match,
+ personal_assignee_match=personal_assignee_match,
+ )
+ )
+ continue
+
+ if is_ambiguous:
+ if matched_via_mapping:
+ filtered.append(
+ TopicFilterResult(
+ patent=patent,
+ decision="keep",
+ matched_via_mapping=True,
+ institution_match=False,
+ personal_assignee_match=False,
+ )
+ )
+ continue
+
+ if _topic_conflict(mapped_topics, author):
+ continue
+
+ filtered.append(
+ TopicFilterResult(
+ patent=patent,
+ decision="keep",
+ matched_via_mapping=matched_via_mapping,
+ institution_match=False,
+ personal_assignee_match=False,
+ )
+ )
+
+ filtered.sort(
+ key=lambda item: (
+ not item.matched_via_mapping,
+ not (item.institution_match or item.personal_assignee_match),
+ item.patent.publication_date or "",
+ ),
+ reverse=False,
+ )
+ return filtered
+
+
+def finest_mapped_topic_label(
+ patent: model.PatentEntry,
+ mapping=None,
+) -> str | None:
+ table = mapping if mapping is not None else load_ipc_openalex_mapping()
+ mapped = resolve_mapped_topics_for_patent(patent, table)
+ if not mapped:
+ return None
+ return mapped[0].topic_display_name or mapped[0].topic_id
diff --git a/service/src/main/inse/patents/common/model.py b/service/src/main/inse/patents/common/model.py
index b3cc97a4..e9e9bb26 100644
--- a/service/src/main/inse/patents/common/model.py
+++ b/service/src/main/inse/patents/common/model.py
@@ -12,6 +12,13 @@ class IpcClassification(BaseModel):
model_config = ConfigDict(populate_by_name=True)
+class OpenAlexTopicTag(BaseModel):
+ topic_id: str | None = None
+ topic_display_name: str
+ field_name: str | None = None
+ domain_name: str | None = None
+
+
class PatentEntry(BaseModel):
patent_id: str
source: str
@@ -32,6 +39,7 @@ class PatentEntry(BaseModel):
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
+ openalex_topics: list[OpenAlexTopicTag] = Field(default_factory=list)
class PatentsByAuthorResponse(BaseModel):
diff --git a/service/src/main/inse/patents/common/parsing.py b/service/src/main/inse/patents/common/parsing.py
index 0b3cdf3b..314ca6fa 100644
--- a/service/src/main/inse/patents/common/parsing.py
+++ b/service/src/main/inse/patents/common/parsing.py
@@ -1,4 +1,5 @@
"""Shared patent hit parsing, deduplication, and classification enrichment."""
+import asyncio
import logging
import httpx
@@ -7,10 +8,21 @@ 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
+from inse.patents.patents_openalex_keywords.client import (
+ PatentsOpenAlexKeywordsClient,
+ candidate_doc_ids,
+)
logger = logging.getLogger(__name__)
+def parse_search_total(data: dict) -> int:
+ total = data.get("hits", {}).get("total")
+ if isinstance(total, dict):
+ return int(total.get("value", 0))
+ return int(total or 0)
+
+
def parse_epo_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
@@ -91,6 +103,67 @@ def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
)
+def patent_map_key(patent: model.PatentEntry) -> str:
+ source, patent_id, publication_date, stage = patent_dedup_key(patent)
+ return f"{source}:{patent_id}:{publication_date}:{stage}"
+
+
+async def expand_matched_epo_application_families(
+ matched_patents: list[model.PatentEntry],
+ search_client,
+) -> list[model.PatentEntry]:
+ """Include other EPO publication stages for already matched applications.
+
+ EPO patents are often published multiple times (e.g. A1 application, later B1
+ grant). Inventor nested search may only return one stage, so once a publication
+ is matched to an author we fetch sibling publications by application number.
+ """
+ application_numbers = sorted(
+ {
+ patent.application_number.strip()
+ for patent in matched_patents
+ if patent.source == "EPO"
+ and patent.application_number
+ and patent.application_number.strip()
+ }
+ )
+ if not application_numbers:
+ return matched_patents
+
+ existing_keys = {patent_dedup_key(patent) for patent in matched_patents}
+ extra: list[model.PatentEntry] = []
+
+ async def _fetch_family(application_number: str) -> list[model.PatentEntry]:
+ try:
+ data = await search_client.search_epo(
+ search_client.epo_query_by_application_number(application_number)
+ )
+ except (MissingApiKeyError, httpx.HTTPError) as exc:
+ logger.warning(
+ "EPO family expansion failed for application %s: %s",
+ application_number,
+ exc,
+ )
+ return []
+ return parse_epo_hits(data)
+
+ family_results = await asyncio.gather(
+ *(_fetch_family(application_number) for application_number in application_numbers)
+ )
+ for family_patents in family_results:
+ for patent in family_patents:
+ key = patent_dedup_key(patent)
+ if key in existing_keys:
+ continue
+ existing_keys.add(key)
+ extra.append(patent)
+
+ if not extra:
+ return matched_patents
+
+ return deduplicate_patents(matched_patents + extra)
+
+
async def enrich_patents_classifications(
patents: list[model.PatentEntry],
ipc_client: IpcSearchClient,
@@ -120,6 +193,68 @@ async def enrich_patents_classifications(
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
+async def enrich_patents_openalex_topics(
+ patents: list[model.PatentEntry],
+ keywords_client: PatentsOpenAlexKeywordsClient,
+) -> None:
+ """Attaches OpenAlex topic labels matched to each patent's ipc/cpc codes.
+
+ Resolves every unique symbol across all patents in a single _search
+ request against patents_openalex_keywords, then fans the results back
+ out per patent. Doing this per-symbol (even in parallel) instead of as
+ one batch added seconds of latency to endpoints enriching many patents
+ at once, like get_all_patents.
+ """
+ symbols = list(dict.fromkeys(
+ extract_ipc_symbol(raw)
+ for patent in patents
+ for raw in (*patent.ipc, *patent.cpc)
+ if raw
+ ))
+ if not symbols:
+ return
+
+ candidate_ids_by_symbol = {symbol: candidate_doc_ids(symbol) for symbol in symbols}
+ all_doc_ids = list(dict.fromkeys(
+ doc_id
+ for candidate_ids in candidate_ids_by_symbol.values()
+ for doc_id in candidate_ids
+ ))
+
+ try:
+ docs_by_id = await keywords_client.lookup_ids(all_doc_ids)
+ except Exception:
+ logger.warning("patents_openalex_keywords batch lookup failed", exc_info=True)
+ return
+
+ topics_by_symbol: dict[str, list[model.OpenAlexTopicTag]] = {}
+ for symbol, candidate_ids in candidate_ids_by_symbol.items():
+ doc = next((docs_by_id[doc_id] for doc_id in candidate_ids if doc_id in docs_by_id), None)
+ if not doc:
+ continue
+ topics_by_symbol[symbol] = [
+ model.OpenAlexTopicTag(
+ topic_id=match.get("topic_id"),
+ topic_display_name=match["topic_display_name"],
+ field_name=match.get("field"),
+ domain_name=match.get("domain"),
+ )
+ for match in doc.get("topic_matches") or []
+ if match.get("topic_display_name")
+ ]
+
+ for patent in patents:
+ seen: set[str] = set()
+ topics: list[model.OpenAlexTopicTag] = []
+ for raw in (*patent.ipc, *patent.cpc):
+ for tag in topics_by_symbol.get(extract_ipc_symbol(raw), []):
+ dedup_key = tag.topic_id or tag.topic_display_name
+ if dedup_key not in seen:
+ seen.add(dedup_key)
+ topics.append(tag)
+ patent.openalex_topics = topics[:6]
+
+
def _to_classification_strings(value) -> list[str]:
if not value:
return []
diff --git a/service/src/main/inse/patents/common/test_parsing.py b/service/src/main/inse/patents/common/test_parsing.py
new file mode 100644
index 00000000..225f1be5
--- /dev/null
+++ b/service/src/main/inse/patents/common/test_parsing.py
@@ -0,0 +1,133 @@
+import asyncio
+
+from inse.patents.common.model import PatentEntry
+from inse.patents.common.parsing import enrich_patents_openalex_topics
+
+
+class _FakeKeywordsClient:
+ def __init__(self, docs_by_id: dict[str, dict]):
+ self.docs_by_id = docs_by_id
+ self.lookup_ids_calls: list[list[str]] = []
+
+ async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict]:
+ self.lookup_ids_calls.append(doc_ids)
+ return {
+ doc_id: self.docs_by_id[doc_id]
+ for doc_id in doc_ids
+ if doc_id in self.docs_by_id
+ }
+
+
+def _patent(patent_id: str, ipc: list[str], cpc: list[str] | None = None) -> PatentEntry:
+ return PatentEntry(patent_id=patent_id, source="EPO", ipc=ipc, cpc=cpc or [])
+
+
+def test_enrich_patents_openalex_topics_attaches_field_and_domain() -> None:
+ client = _FakeKeywordsClient(
+ {
+ "subgroup:C07K11/02": {
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T1",
+ "topic_display_name": "Peptide Chemistry",
+ "field": "Chemistry",
+ "domain": "Physical Sciences",
+ },
+ ]
+ },
+ "subgroup:A61K38/00": {
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T3",
+ "topic_display_name": "Drug Delivery",
+ "field": "Pharmacology, Toxicology and Pharmaceutics",
+ "domain": "Health Sciences",
+ },
+ ]
+ },
+ }
+ )
+ patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI", "A61K 38/00 20060101ALI"])
+
+ asyncio.run(enrich_patents_openalex_topics([patent], client))
+
+ assert [t.topic_display_name for t in patent.openalex_topics] == [
+ "Peptide Chemistry",
+ "Drug Delivery",
+ ]
+ assert patent.openalex_topics[0].field_name == "Chemistry"
+ assert patent.openalex_topics[0].domain_name == "Physical Sciences"
+
+
+def test_enrich_patents_openalex_topics_dedupes_by_topic_id() -> None:
+ client = _FakeKeywordsClient(
+ {
+ "subgroup:C07K11/02": {
+ "topic_matches": [
+ {"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
+ {"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
+ ]
+ },
+ }
+ )
+ patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI"])
+
+ asyncio.run(enrich_patents_openalex_topics([patent], client))
+
+ assert len(patent.openalex_topics) == 1
+
+
+def test_enrich_patents_openalex_topics_skips_unmatched_symbols() -> None:
+ client = _FakeKeywordsClient({})
+ patent = _patent("EP2", ipc=["Z99Z 99/99"])
+
+ asyncio.run(enrich_patents_openalex_topics([patent], client))
+
+ assert patent.openalex_topics == []
+
+
+def test_enrich_patents_openalex_topics_resolves_all_patents_in_one_batch_call() -> None:
+ """A single lookup_ids() call must cover every unique symbol across all
+ patents — per-symbol requests (even in parallel) previously added
+ seconds of latency on endpoints enriching many patents at once."""
+ client = _FakeKeywordsClient(
+ {
+ "subgroup:C07K11/02": {
+ "topic_matches": [
+ {"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
+ ]
+ },
+ }
+ )
+ patents = [
+ _patent("EP1", ipc=["C07K 11/02 20060101AFI"]),
+ _patent("EP2", ipc=["C07K 11/02 20060101ALI"]),
+ ]
+
+ asyncio.run(enrich_patents_openalex_topics(patents, client))
+
+ assert len(client.lookup_ids_calls) == 1
+ assert patents[0].openalex_topics[0].topic_display_name == "Peptide Chemistry"
+ assert patents[1].openalex_topics[0].topic_display_name == "Peptide Chemistry"
+
+
+def test_enrich_patents_openalex_topics_prefers_more_specific_level() -> None:
+ client = _FakeKeywordsClient(
+ {
+ "subgroup:C07K11/02": {
+ "topic_matches": [
+ {"topic_id": "https://openalex.org/T1", "topic_display_name": "Specific Match"},
+ ]
+ },
+ "class:C07": {
+ "topic_matches": [
+ {"topic_id": "https://openalex.org/T2", "topic_display_name": "Broad Match"},
+ ]
+ },
+ }
+ )
+ patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI"])
+
+ asyncio.run(enrich_patents_openalex_topics([patent], client))
+
+ assert patent.openalex_topics[0].topic_display_name == "Specific Match"
diff --git a/service/src/main/inse/patents/common/text_normalization.py b/service/src/main/inse/patents/common/text_normalization.py
index a5f3f22b..06bac0ef 100644
--- a/service/src/main/inse/patents/common/text_normalization.py
+++ b/service/src/main/inse/patents/common/text_normalization.py
@@ -35,6 +35,23 @@ _PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"a([lmnrt])", r"ae\1"),
)
+# Titles that can appear before a person's name in patent inventor fields
+_PERSON_TITLE_PATTERN = re.compile(
+ r"^\s*(?:"
+ r"Prof\.?|Dr\.?|Dipl\.?(?:-Ing\.?|-Math\.?|-Phys\.?|-Inform\.?)?|"
+ r"M\.Sc\.?|B\.Sc\.?|M\.Eng\.?|PhD\.?|Ing\.?|"
+ r"Prof\.?\s+Dr\.?|Dr\.?-Ing\.?|Dr\.?\s+rer\.?\s+nat\.?"
+ r")[.,]?\s+",
+ re.IGNORECASE,
+)
+
+
+def strip_person_titles(value: str | None) -> str:
+ """Remove academic/professional titles from the start of a person name string."""
+ if not value:
+ return ""
+ return _PERSON_TITLE_PATTERN.sub("", value).strip()
+
def normalize_name_part(value: str | None) -> str:
if not value:
diff --git a/service/src/main/inse/patents/elastic_search_client.py b/service/src/main/inse/patents/elastic_search_client.py
index 4b6d8b02..840ac21e 100644
--- a/service/src/main/inse/patents/elastic_search_client.py
+++ b/service/src/main/inse/patents/elastic_search_client.py
@@ -1,325 +1,2 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
- HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
-"""
-from typing import Any
-from inse.integrations import elasticsearch
-from inse.model import ESCluster, ESIndex
-import httpx
-import asyncio
-from .. import config
-from .name_matching import search_name_variants
-
-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]:
- """Match a name field, including transliterated variants (Müller/Mueller)."""
- variants = search_name_variants(name)
- if len(variants) <= 1:
- return {"match_phrase": {field: variants[0] if variants else name}}
- return {
- "bool": {
- "should": [{"match_phrase": {field: variant}} for variant in variants],
- "minimum_should_match": 1,
- }
- }
-
-
-from inse.exceptions import MissingApiKeyError
-
-
-class PatentSearchClient:
- 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",
- }
-
- def epo_query_by_inventor(
- self,
- last_name: str,
- first_name: str | None = None,
- size: int = DEFAULT_SEARCH_SIZE,
- ) -> dict[str, Any]:
- """Search EPO index: first AND last name in the SAME inventor entry."""
- 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]:
- """Search USPTO index: first AND last name in the SAME inventor entry."""
- 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,
- }
-
- 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)
-
- 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)
-
- async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
- response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
- return response
-
- async def get_by_id_or_title(
- self,
- patent_id: str,
- prefix: str,
- title: str,
- filling_date: str | None = None,
- size: int = 1,
- ) -> dict[str, Any]:
- """Search EPO and USPTO by ID; fall back to match on title if no hits.
-
- Args:
- patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
- prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
- Both indices are always queried for the ID lookup.
- title: Used only when the ID lookup returns zero hits.
- size: Maximum number of results to return.
- """
- epo_id_payload = self._epo_query_by_id(patent_id, size)
- uspto_id_payload = self._uspto_query_by_id(patent_id, size)
-
- epo_result, uspto_result = await asyncio.gather(
- self.search_epo(epo_id_payload),
- self.search_uspto(uspto_id_payload),
- )
-
- epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
- uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
-
- if epo_hits > 0 or uspto_hits > 0:
- if prefix.upper() == "EP" and epo_hits > 0:
- return epo_result
- if prefix.upper() == "US" and uspto_hits > 0:
- return uspto_result
- return epo_result if epo_hits > 0 else uspto_result
-
- if prefix.upper() == "US":
- payload = self._uspto_query_by_title(title, filling_date, size)
- return await self.search_uspto(payload)
-
- payload = self._epo_query_by_title(title,filling_date, size)
- return await self.search_epo(payload)
-
- #query builders
-
- 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."""
- 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 {
- "size": size,
- "_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_id(self, patent_id: str, size: int) -> dict[str, Any]:
- """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 {
- "size": size,
- "track_total_hits": True,
- "sort": [{"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,
- }
-
- def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
- """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 {
- "size": size,
- "_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_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
- """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 {
- "size": size,
- "_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,
- }
+"""Backward-compatible re-exports."""
+from inse.patents.search_client import * # noqa: F403
diff --git a/service/src/main/inse/patents/institutions/logic.py b/service/src/main/inse/patents/institutions/logic.py
index e01ed75f..9575c38d 100644
--- a/service/src/main/inse/patents/institutions/logic.py
+++ b/service/src/main/inse/patents/institutions/logic.py
@@ -39,7 +39,7 @@ async def get_patents_by_institution_id(
institution_client = institutions_client or InstitutionsSearchClient()
short_id = institution_id.replace("https://openalex.org/", "")
- institution = institution_client.get_institution_by_id(short_id)
+ institution = await institution_client.get_institution_by_id(short_id)
search_names = _institution_search_names(institution)
if not search_names:
diff --git a/service/src/main/inse/patents/institutions/name_matching.py b/service/src/main/inse/patents/institutions/name_matching.py
index bb5f1aba..132b85cb 100644
--- a/service/src/main/inse/patents/institutions/name_matching.py
+++ b/service/src/main/inse/patents/institutions/name_matching.py
@@ -57,9 +57,12 @@ def institution_search_variants(value: str | None) -> list[str]:
def _significant_institution_tokens(text: str) -> set[str]:
+ # Normalize hyphens to spaces so "Duisburg-Essen" splits into "duisburg" + "essen",
+ # matching both hyphenated and space-separated forms in patent databases.
+ normalized = normalize_name_part(text).replace("-", " ")
return {
token
- for token in normalize_name_part(text).split()
+ for token in normalized.split()
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
and token not in _INSTITUTION_GENERIC_TOKENS
}
@@ -72,13 +75,16 @@ def assignee_matches_institution_name(assignee: str, institution_name: str) -> b
return False
original = institution_name.strip()
- assignee_tokens = set(norm_assignee.split())
+ # Normalize hyphens to spaces for consistent token splitting across patent databases
+ norm_assignee_flat = norm_assignee.replace("-", " ")
+ norm_name_flat = norm_name.replace("-", " ")
+ assignee_tokens = set(norm_assignee_flat.split())
if len(original) <= 6 and " " not in original:
- return norm_name in assignee_tokens
+ return norm_name_flat in assignee_tokens
- if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN:
- if norm_name in norm_assignee or norm_assignee in norm_name:
+ if len(norm_name_flat) >= MIN_INSTITUTION_SUBSTRING_LEN:
+ if norm_name_flat in norm_assignee_flat or norm_assignee_flat in norm_name_flat:
return True
significant = _significant_institution_tokens(institution_name)
diff --git a/service/src/main/inse/patents/keywords/__init__.py b/service/src/main/inse/patents/keywords/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/service/src/main/inse/patents/keywords/logic.py b/service/src/main/inse/patents/keywords/logic.py
new file mode 100644
index 00000000..28d95c6e
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/logic.py
@@ -0,0 +1,809 @@
+"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index."""
+from __future__ import annotations
+
+import asyncio
+import logging
+import math
+import re
+
+import httpx
+
+from inse.patents.authors.ipc_openalex_mapping import (
+ MappedOpenAlexTopic,
+ normalize_openalex_id,
+)
+from inse.patents.common import model
+from inse.patents.common.elastic_search_client import (
+ BasePatentSearchClient,
+ MissingApiKeyError,
+)
+from inse.patents.common.parsing import (
+ deduplicate_patents,
+ enrich_patents_classifications,
+ parse_epo_hits,
+ parse_uspto_hits,
+ patent_map_key,
+)
+from inse.patents.ipc_lookup import (
+ extract_ipc_symbol,
+ parse_ipc_symbol,
+)
+from inse.patents.ipc_search_client import IpcSearchClient
+from inse.patents.keywords.model import (
+ KeywordPatentMatch,
+ KeywordPatentSearchItem,
+ PatentsByKeywordsRequest,
+ PatentsByKeywordsResponse,
+)
+from inse.patents.keywords.reverse_lookup import IpcCodeMatch, KeywordIpcReverseLookup
+from inse.patents.keywords.search_queries import IpcPatentSearchQueries
+from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
+from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver
+
+logger = logging.getLogger(__name__)
+
+_MAX_PATENTS = 100
+_MAX_IPC_CODES = 20
+_MAX_IPC_CODES_PER_KEYWORD = 2
+_MAX_PATENT_SEARCH_TERMS = 10
+_MAX_SEARCH_KEYWORDS = 10
+_MIN_KEYWORD_RELEVANCE = 0.0
+_MIN_IPC_MATCH_SCORE = 0.65
+_MIN_PATENT_MATCH_SCORE = 0.50
+_SEARCHABLE_IPC_LEVELS = frozenset({"subgroup", "group", "subclass"})
+# Soft field overlap for natural-science / engineering patent domains.
+_SOFT_MATCH_FIELD_NAMES = frozenset(
+ {
+ "engineering",
+ "computer science",
+ "physical sciences",
+ "physics and astronomy",
+ "materials science",
+ "environmental science",
+ "chemical engineering",
+ "chemistry",
+ "earth and planetary sciences",
+ "medicine",
+ "biochemistry, genetics and molecular biology",
+ "immunology and microbiology",
+ }
+)
+_PREFERRED_KEYWORD_LEVELS = frozenset({"coarse", "fine", "custom"})
+_NON_TECHNICAL_FIELD_NAMES = frozenset(
+ {
+ "social sciences",
+ "arts and humanities",
+ "law",
+ "business, management and accounting",
+ }
+)
+_COMPATIBLE_FIELDS: dict[str, frozenset[str]] = {
+ "chemistry": frozenset(
+ {"chemistry", "chemical engineering", "materials science"}
+ ),
+ "chemical engineering": frozenset(
+ {"chemical engineering", "chemistry", "materials science"}
+ ),
+ "materials science": frozenset(
+ {"materials science", "chemistry", "chemical engineering", "engineering"}
+ ),
+ "computer science": frozenset({"computer science", "engineering"}),
+ "engineering": frozenset(
+ {"engineering", "computer science", "materials science"}
+ ),
+ "physical sciences": frozenset(
+ {"physical sciences", "physics and astronomy", "chemistry", "materials science"}
+ ),
+ "physics and astronomy": frozenset(
+ {"physics and astronomy", "physical sciences", "materials science"}
+ ),
+ "biochemistry, genetics and molecular biology": frozenset(
+ {
+ "biochemistry, genetics and molecular biology",
+ "chemistry",
+ "medicine",
+ }
+ ),
+ "medicine": frozenset(
+ {
+ "medicine",
+ "biochemistry, genetics and molecular biology",
+ "immunology and microbiology",
+ }
+ ),
+}
+_TEXT_STOPWORDS = frozenset(
+ {
+ "and",
+ "the",
+ "of",
+ "in",
+ "for",
+ "und",
+ "der",
+ "die",
+ "das",
+ "von",
+ "medicine",
+ "medical",
+ "science",
+ "sciences",
+ }
+)
+
+
+def _ipc_section(symbol: str) -> str:
+ normalized = normalize_symbol(symbol)
+ return normalized[:1] if normalized else ""
+
+
+def _dominant_ipc_sections(ipc_matches: list[IpcCodeMatch], limit: int = 2) -> set[str]:
+ weights: dict[str, float] = {}
+ for match in ipc_matches:
+ section = _ipc_section(match.ipc_symbol)
+ if not section:
+ continue
+ weights[section] = weights.get(section, 0.0) + match.match_score
+ ranked = sorted(weights.items(), key=lambda item: item[1], reverse=True)
+ return {section for section, _ in ranked[:limit]}
+
+
+def _prefer_searchable_ipc_levels(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
+ searchable = [
+ match for match in ipc_matches if match.ipc_level in _SEARCHABLE_IPC_LEVELS
+ ]
+ return searchable if searchable else ipc_matches
+
+
+def _filter_ipc_matches_for_search(ipc_matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
+ if not ipc_matches:
+ return []
+
+ ipc_matches = _prefer_searchable_ipc_levels(ipc_matches)
+ ranked = sorted(ipc_matches, key=lambda match: match.match_score, reverse=True)
+ strong = [
+ match
+ for match in ranked
+ if match.match_score >= _MIN_IPC_MATCH_SCORE
+ ]
+ if not strong:
+ return []
+
+ dominant_sections = _dominant_ipc_sections(strong)
+ filtered: list[IpcCodeMatch] = []
+ seen: set[tuple[str, str]] = set()
+ for match in strong:
+ key = (match.ipc_level, match.ipc_symbol)
+ if key in seen:
+ continue
+ if match.match_score >= 0.8:
+ filtered.append(match)
+ seen.add(key)
+ continue
+ if _ipc_section(match.ipc_symbol) in dominant_sections:
+ filtered.append(match)
+ seen.add(key)
+
+ return filtered
+
+
+def _limit_matches_per_keyword(
+ matches: list[IpcCodeMatch],
+ limit: int = _MAX_IPC_CODES_PER_KEYWORD,
+) -> list[IpcCodeMatch]:
+ grouped: dict[str, list[IpcCodeMatch]] = {}
+ for match in matches:
+ grouped.setdefault(match.source_keyword.casefold(), []).append(match)
+
+ result: list[IpcCodeMatch] = []
+ for keyword_matches in grouped.values():
+ keyword_matches.sort(key=lambda match: match.match_score, reverse=True)
+ result.extend(keyword_matches[:limit])
+
+ return sorted(result, key=lambda match: match.match_score, reverse=True)
+
+
+def _term_from_ipc_match(match: IpcCodeMatch) -> str | None:
+ symbol = normalize_symbol(match.ipc_symbol)
+ if not symbol:
+ return None
+
+ return infer_subclass(symbol)
+
+
+def _patent_search_terms(ipc_matches: list[IpcCodeMatch]) -> list[str]:
+ filtered = _filter_ipc_matches_for_search(ipc_matches)
+ filtered = sorted(filtered, key=lambda match: match.match_score, reverse=True)
+ terms: list[str] = []
+ seen: set[str] = set()
+ for match in filtered:
+ if match.ipc_level not in _SEARCHABLE_IPC_LEVELS:
+ continue
+ term = _term_from_ipc_match(match)
+ if not term or term in seen:
+ continue
+ seen.add(term)
+ terms.append(term)
+ if len(terms) >= _MAX_PATENT_SEARCH_TERMS:
+ break
+ return terms
+
+
+def _normalize_ipc_code(code: str) -> str:
+ extracted = extract_ipc_symbol(code) or code
+ return normalize_symbol(extracted)
+
+
+def _ipc_main_group(symbol: str) -> str | None:
+ parsed = parse_ipc_symbol(symbol)
+ if parsed is None or not parsed.main_group:
+ return None
+
+ return normalize_symbol(parsed.main_group)
+
+
+def _ipc_hierarchy_quality(
+ patent_code: str,
+ mapped_symbol: str,
+) -> float:
+ normalized_patent = _normalize_ipc_code(patent_code)
+ normalized_mapped = _normalize_ipc_code(mapped_symbol)
+
+ if not normalized_patent or not normalized_mapped:
+ return 0.0
+
+ if normalized_patent == normalized_mapped:
+ return 1.0
+
+ patent_group = _ipc_main_group(normalized_patent)
+ mapped_group = _ipc_main_group(normalized_mapped)
+
+ if patent_group and mapped_group and patent_group == mapped_group:
+ return 0.90
+
+ patent_subclass = infer_subclass(normalized_patent)
+ mapped_subclass = infer_subclass(normalized_mapped)
+
+ if (
+ patent_subclass
+ and mapped_subclass
+ and patent_subclass == mapped_subclass
+ ):
+ return 0.75
+
+ return 0.0
+
+
+def _ipc_hierarchy_level(
+ patent_code: str,
+ mapped_symbol: str,
+) -> str | None:
+ quality = _ipc_hierarchy_quality(patent_code, mapped_symbol)
+ if quality >= 1.0:
+ return "exact"
+ if quality >= 0.90:
+ return "main_group"
+ if quality >= 0.75:
+ return "subclass"
+ return None
+
+
+def _keyword_level(item: KeywordPatentSearchItem) -> str:
+ return (item.keyword_level or "").strip().casefold()
+
+
+def _keyword_is_patent_searchable(item: KeywordPatentSearchItem) -> bool:
+ if not item.keyword.strip():
+ return False
+
+ topic_id = normalize_openalex_id(item.topic_id)
+ if not topic_id:
+ return False
+
+ field_name = _normalized_field_name(item.field_name)
+ if field_name in _NON_TECHNICAL_FIELD_NAMES:
+ return False
+
+ return True
+
+
+def _sort_and_limit_keywords(
+ items: list[KeywordPatentSearchItem],
+) -> list[KeywordPatentSearchItem]:
+ ranked = sorted(items, key=lambda item: item.relevance_score, reverse=True)
+ return ranked[:_MAX_SEARCH_KEYWORDS]
+
+
+def _filter_keywords_for_patent_search(
+ items: list[KeywordPatentSearchItem],
+) -> list[KeywordPatentSearchItem]:
+ """Prefer coarse/fine/custom keywords; ignore broad when specifics exist."""
+ searchable = [item for item in items if _keyword_is_patent_searchable(item)]
+ if not searchable:
+ return []
+
+ preferred = [
+ item
+ for item in searchable
+ if _keyword_level(item) in _PREFERRED_KEYWORD_LEVELS
+ ]
+ if preferred:
+ return _sort_and_limit_keywords(preferred)
+
+ non_broad = [
+ item for item in searchable if _keyword_level(item) != "broad"
+ ]
+ if non_broad:
+ return _sort_and_limit_keywords(non_broad)
+
+ return _sort_and_limit_keywords(searchable)
+
+
+def _normalized_field_name(name: str | None) -> str:
+ return (name or "").strip().casefold()
+
+
+def _patent_has_g06_code(patent: model.PatentEntry) -> bool:
+ for code in (*patent.ipc, *patent.cpc):
+ symbol = normalize_symbol(extract_ipc_symbol(code) or code)
+ if symbol.startswith("G06"):
+ return True
+ return False
+
+
+def _compatible_patent_fields(keyword_field: str) -> frozenset[str]:
+ return _COMPATIBLE_FIELDS.get(keyword_field, frozenset({keyword_field}))
+
+
+def _keyword_overlap_criteria(
+ items: list[KeywordPatentSearchItem],
+) -> tuple[frozenset[str], frozenset[str], frozenset[str]]:
+ topic_ids: set[str] = set()
+ subfield_names: set[str] = set()
+ soft_field_names: set[str] = set()
+ for item in items:
+ topic_id = normalize_openalex_id(item.topic_id)
+ if topic_id:
+ topic_ids.add(topic_id)
+ subfield_name = (item.subfield_name or "").strip()
+ if subfield_name:
+ subfield_names.add(subfield_name.casefold())
+ field_name = _normalized_field_name(item.field_name)
+ if field_name in _SOFT_MATCH_FIELD_NAMES:
+ soft_field_names.add(field_name)
+ return (
+ frozenset(topic_ids),
+ frozenset(subfield_names),
+ frozenset(soft_field_names),
+ )
+
+
+def _topics_overlap_keywords(
+ patent_topics: list[MappedOpenAlexTopic],
+ keyword_topic_ids: frozenset[str],
+ keyword_subfield_names: frozenset[str],
+ keyword_soft_field_names: frozenset[str],
+ *,
+ patent: model.PatentEntry | None = None,
+) -> bool:
+ if (
+ not keyword_topic_ids
+ and not keyword_subfield_names
+ and not keyword_soft_field_names
+ ):
+ return True
+
+ if not patent_topics:
+ return False
+
+ patent_topic_ids = {
+ topic_id
+ for mapped in patent_topics
+ if (topic_id := normalize_openalex_id(mapped.topic_id))
+ }
+ if keyword_topic_ids & patent_topic_ids:
+ return True
+
+ patent_subfield_names = {
+ (mapped.subfield_name or "").strip().casefold()
+ for mapped in patent_topics
+ if (mapped.subfield_name or "").strip()
+ }
+ if keyword_subfield_names & patent_subfield_names:
+ return True
+
+ if keyword_soft_field_names:
+ patent_field_names = {
+ _normalized_field_name(mapped.field_name)
+ for mapped in patent_topics
+ if mapped.field_name
+ }
+ for keyword_field in keyword_soft_field_names:
+ if patent_field_names & _compatible_patent_fields(keyword_field):
+ return True
+ if (
+ patent is not None
+ and _patent_has_g06_code(patent)
+ and keyword_soft_field_names & {"engineering", "computer science"}
+ ):
+ return True
+
+ return False
+
+
+def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]:
+ terms: list[str] = []
+ seen: set[str] = set()
+
+ for item in items:
+ for value in (
+ item.keyword,
+ item.topic_display_name,
+ item.subfield_name,
+ ):
+ normalized = (value or "").strip().casefold()
+ if not normalized:
+ continue
+
+ words = re.findall(r"[a-zäöüß]{4,}", normalized)
+
+ for word in words:
+ if word in _TEXT_STOPWORDS or word in seen:
+ continue
+ seen.add(word)
+ terms.append(word)
+
+ return terms
+
+
+def _text_overlap_score(
+ patent: model.PatentEntry,
+ search_terms: list[str],
+) -> float:
+ text = " ".join(
+ part
+ for part in [patent.title or "", patent.abstract or ""]
+ if part
+ ).casefold()
+
+ if not search_terms or not text.strip():
+ return 0.0
+
+ hits = sum(1 for term in search_terms if term in text)
+ return min(hits / 3, 1.0)
+
+
+def _patent_passes_relevance_gate(
+ patent_topics: list[MappedOpenAlexTopic],
+ *,
+ keyword_topic_ids: frozenset[str],
+ keyword_subfield_names: frozenset[str],
+ keyword_soft_field_names: frozenset[str],
+ patent: model.PatentEntry,
+ text_score: float,
+) -> bool:
+ has_topic_match = bool(patent_topics) and _topics_overlap_keywords(
+ patent_topics,
+ keyword_topic_ids,
+ keyword_subfield_names,
+ keyword_soft_field_names,
+ patent=patent,
+ )
+ return has_topic_match or text_score > 0.0
+
+
+def _compute_final_score(
+ ipc_score: float,
+ topic_score: float,
+ text_score: float,
+) -> float:
+ return round(
+ 0.60 * ipc_score
+ + 0.25 * topic_score
+ + 0.15 * text_score,
+ 4,
+ )
+
+
+def _score_ipc_match(
+ patent: model.PatentEntry,
+ ipc_matches: list[IpcCodeMatch],
+) -> tuple[float, list[str], list[str]] | None:
+ searchable_matches = [
+ match
+ for match in ipc_matches
+ if match.ipc_level in _SEARCHABLE_IPC_LEVELS
+ ] or ipc_matches
+
+ best_score = 0.0
+ best_keywords: set[str] = set()
+ best_symbols: set[str] = set()
+
+ patent_codes = [
+ normalized
+ for code in (*patent.ipc, *patent.cpc)
+ if (normalized := _normalize_ipc_code(code))
+ ]
+
+ for ipc_match in searchable_matches:
+ for patent_code in patent_codes:
+ hierarchy_quality = _ipc_hierarchy_quality(
+ patent_code,
+ ipc_match.ipc_symbol,
+ )
+ if hierarchy_quality <= 0:
+ continue
+
+ candidate_score = ipc_match.match_score * hierarchy_quality
+
+ if candidate_score > best_score:
+ best_score = candidate_score
+ best_keywords = {ipc_match.source_keyword}
+ best_symbols = {ipc_match.ipc_symbol}
+ elif math.isclose(
+ candidate_score,
+ best_score,
+ rel_tol=1e-9,
+ abs_tol=1e-9,
+ ):
+ best_keywords.add(ipc_match.source_keyword)
+ best_symbols.add(ipc_match.ipc_symbol)
+
+ if best_score <= 0:
+ return None
+
+ return (
+ round(best_score, 4),
+ sorted(best_keywords),
+ sorted(best_symbols),
+ )
+
+
+def _score_patent(
+ patent: model.PatentEntry,
+ ipc_matches: list[IpcCodeMatch],
+ *,
+ patent_topics: list[MappedOpenAlexTopic] | None = None,
+ keyword_topic_ids: frozenset[str] | None = None,
+ keyword_subfield_names: frozenset[str] | None = None,
+ keyword_soft_field_names: frozenset[str] | None = None,
+ search_keywords: list[KeywordPatentSearchItem] | None = None,
+) -> tuple[float, list[str], list[str]] | None:
+ ipc_result = _score_ipc_match(patent, ipc_matches)
+ if ipc_result is None:
+ return None
+ ipc_score, matched_keywords, matched_symbols = ipc_result
+
+ text_score = 0.0
+ if search_keywords is not None:
+ text_score = _text_overlap_score(
+ patent,
+ _text_search_terms(search_keywords),
+ )
+
+ has_topic_match = bool(patent_topics) and _topics_overlap_keywords(
+ patent_topics or [],
+ keyword_topic_ids or frozenset(),
+ keyword_subfield_names or frozenset(),
+ keyword_soft_field_names or frozenset(),
+ patent=patent,
+ )
+
+ if not has_topic_match and text_score == 0.0:
+ return None
+
+ topic_score = 1.0 if has_topic_match else 0.0
+
+ return (
+ _compute_final_score(ipc_score, topic_score, text_score),
+ matched_keywords,
+ matched_symbols,
+ )
+
+
+async def get_patents_by_keywords(
+ request: PatentsByKeywordsRequest,
+ *,
+ reverse_lookup: KeywordIpcReverseLookup | None = None,
+ search_client: BasePatentSearchClient | None = None,
+ ipc_client: IpcSearchClient | None = None,
+ mapping_resolver: PatentOpenAlexMappingResolver | None = None,
+) -> PatentsByKeywordsResponse:
+ lookup = reverse_lookup or KeywordIpcReverseLookup()
+ client = search_client or BasePatentSearchClient()
+ ipc_search = ipc_client or IpcSearchClient()
+ resolver = mapping_resolver or PatentOpenAlexMappingResolver()
+ queries = IpcPatentSearchQueries()
+
+ search_keywords = _filter_keywords_for_patent_search(request.keywords)
+ if not search_keywords:
+ logger.info(
+ "Keyword patent search: no searchable keywords in %s",
+ [item.keyword for item in request.keywords],
+ )
+ return PatentsByKeywordsResponse(patent_count=0, patents=[])
+
+ logger.info(
+ "Keyword patent search: using keywords=%s (from %d requested)",
+ [
+ {
+ "keyword": item.keyword,
+ "level": item.keyword_level,
+ "relevance_score": item.relevance_score,
+ "field_name": item.field_name,
+ }
+ for item in search_keywords
+ ],
+ len(request.keywords),
+ )
+ keyword_topic_ids, keyword_subfield_names, keyword_soft_field_names = (
+ _keyword_overlap_criteria(search_keywords)
+ )
+
+ ipc_matches = await lookup.lookup_ipc_codes(
+ search_keywords,
+ max_codes=_MAX_IPC_CODES,
+ )
+ ipc_matches = _filter_ipc_matches_for_search(ipc_matches)
+ ipc_matches = _limit_matches_per_keyword(ipc_matches)
+ logger.info(
+ "Keyword patent search: search_keywords=%s ipc_matches=%s",
+ [item.keyword for item in search_keywords],
+ [
+ {
+ "symbol": match.ipc_symbol,
+ "level": match.ipc_level,
+ "score": match.match_score,
+ "keyword": match.source_keyword,
+ }
+ for match in ipc_matches
+ ],
+ )
+ if not ipc_matches:
+ logger.info(
+ "Keyword patent search: no IPC codes after filtering for keywords %s",
+ [item.keyword for item in search_keywords],
+ )
+ return PatentsByKeywordsResponse(patent_count=0, patents=[])
+
+ symbols = _patent_search_terms(ipc_matches)
+ text_search_terms = _text_search_terms(search_keywords)
+ logger.info("Keyword patent search: patent_search_terms=%s", symbols)
+ if not symbols:
+ return PatentsByKeywordsResponse(patent_count=0, patents=[])
+
+ try:
+ epo_data, uspto_data = await asyncio.gather(
+ client.search_epo(
+ queries.epo_query_by_ipc_symbols(symbols, size=_MAX_PATENTS)
+ ),
+ client.search_uspto(
+ queries.uspto_query_by_ipc_symbols(symbols, size=_MAX_PATENTS)
+ ),
+ )
+ except MissingApiKeyError:
+ logger.warning("Patent search skipped: Elasticsearch API key not configured.")
+ return PatentsByKeywordsResponse(patent_count=0, patents=[])
+ except httpx.HTTPError as exc:
+ logger.warning("Patent search failed: %s", exc)
+ return PatentsByKeywordsResponse(patent_count=0, patents=[])
+
+ raw_patents = deduplicate_patents(
+ parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
+ )
+ logger.info("Keyword patent search: raw_patents=%d", len(raw_patents))
+ patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents)
+
+ scored: list[KeywordPatentMatch] = []
+ filtered_by_ipc = 0
+ filtered_by_relevance_gate = 0
+ filtered_by_min_score = 0
+ for patent in raw_patents:
+ patent_topics = patent_topics_by_key.get(patent_map_key(patent), [])
+ ipc_result = _score_ipc_match(patent, ipc_matches)
+ if ipc_result is None:
+ filtered_by_ipc += 1
+ continue
+ ipc_score, matched_keywords, matched_symbols = ipc_result
+
+ has_topic_match = bool(patent_topics) and _topics_overlap_keywords(
+ patent_topics,
+ keyword_topic_ids,
+ keyword_subfield_names,
+ keyword_soft_field_names,
+ patent=patent,
+ )
+
+ text_score = _text_overlap_score(patent, text_search_terms)
+
+ if not has_topic_match and text_score == 0.0:
+ filtered_by_relevance_gate += 1
+ continue
+
+ topic_score = 1.0 if has_topic_match else 0.0
+
+ score = _compute_final_score(ipc_score, topic_score, text_score)
+ if score < _MIN_PATENT_MATCH_SCORE:
+ filtered_by_min_score += 1
+ continue
+
+ hierarchy_levels = sorted(
+ {
+ level
+ for symbol in matched_symbols
+ for code in (*patent.ipc, *patent.cpc)
+ if (level := _ipc_hierarchy_level(code, symbol))
+ }
+ )
+ logger.info(
+ "Patent candidate: id=%s title=%s ipc_score=%.4f "
+ "topic_score=%.4f text_score=%.4f final_score=%.4f "
+ "hierarchy_levels=%s matched_keywords=%s matched_symbols=%s",
+ patent.patent_id,
+ patent.title,
+ ipc_score,
+ topic_score,
+ text_score,
+ score,
+ hierarchy_levels,
+ matched_keywords,
+ matched_symbols,
+ )
+ scored.append(
+ KeywordPatentMatch(
+ patent=patent,
+ match_score=score,
+ matched_keywords=matched_keywords,
+ matched_ipc_symbols=matched_symbols,
+ )
+ )
+
+ logger.info(
+ "Keyword patent search: filtered_by_ipc=%d filtered_by_relevance_gate=%d "
+ "filtered_by_min_score=%d final_patents=%d",
+ filtered_by_ipc,
+ filtered_by_relevance_gate,
+ filtered_by_min_score,
+ len(scored),
+ )
+
+ scored.sort(
+ key=lambda item: (
+ item.match_score,
+ item.patent.publication_date or "",
+ item.patent.patent_id,
+ ),
+ reverse=True,
+ )
+ scored = scored[:_MAX_PATENTS]
+
+ patents = [item.patent for item in scored]
+ await enrich_patents_classifications(patents, ipc_search)
+
+ return PatentsByKeywordsResponse(
+ patent_count=len(scored),
+ patents=scored,
+ )
+
+
+def keyword_items_from_entries(
+ entries: list[dict],
+) -> list[KeywordPatentSearchItem]:
+ """Helper for tests – build search items from serialized keyword entries."""
+ items: list[KeywordPatentSearchItem] = []
+ for entry in entries:
+ llm = entry.get("llm_keyword") or {}
+ topic_mapping = entry.get("topic_mapping") or {}
+ topic = topic_mapping.get("topic") or {}
+ items.append(
+ KeywordPatentSearchItem(
+ keyword=str(llm.get("keyword") or "").strip(),
+ keyword_level=entry.get("keyword_level"),
+ topic_id=topic.get("id"),
+ topic_display_name=topic.get("display_name"),
+ subfield_name=(topic.get("subfield") or {}).get("display_name"),
+ field_name=(topic.get("field") or {}).get("display_name"),
+ relevance_score=float(llm.get("relevance_score") or 1.0),
+ )
+ )
+ return [item for item in items if item.keyword]
diff --git a/service/src/main/inse/patents/keywords/model.py b/service/src/main/inse/patents/keywords/model.py
new file mode 100644
index 00000000..fe274cad
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/model.py
@@ -0,0 +1,54 @@
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from inse.patents.common.model import PatentEntry
+
+KeywordPatentLevel = Literal["broad", "coarse", "fine", "custom"]
+
+
+class KeywordPatentSearchItem(BaseModel):
+ keyword: str = Field(description="Extracted keyword text.")
+ keyword_level: KeywordPatentLevel | None = Field(
+ default=None,
+ description="Keyword granularity from extraction UI: broad, coarse, fine, or custom.",
+ )
+ topic_id: str | None = Field(
+ default=None,
+ description="OpenAlex topic id from keyword enrichment, if available.",
+ )
+ topic_display_name: str | None = Field(
+ default=None,
+ description="OpenAlex topic display name from enrichment, if available.",
+ )
+ subfield_name: str | None = Field(
+ default=None,
+ description="OpenAlex subfield name from enrichment, if available.",
+ )
+ field_name: str | None = Field(
+ default=None,
+ description="OpenAlex field name from enrichment, if available.",
+ )
+ relevance_score: float = Field(
+ default=1.0,
+ description="LLM relevance score for the keyword.",
+ )
+
+
+class PatentsByKeywordsRequest(BaseModel):
+ keywords: list[KeywordPatentSearchItem] = Field(
+ min_length=1,
+ description="Keywords to match against patents_openalex_keywords.",
+ )
+
+
+class KeywordPatentMatch(BaseModel):
+ patent: PatentEntry
+ match_score: float = Field(description="Combined match quality score.")
+ matched_keywords: list[str] = Field(default_factory=list)
+ matched_ipc_symbols: list[str] = Field(default_factory=list)
+
+
+class PatentsByKeywordsResponse(BaseModel):
+ patent_count: int
+ patents: list[KeywordPatentMatch]
diff --git a/service/src/main/inse/patents/keywords/reverse_lookup.py b/service/src/main/inse/patents/keywords/reverse_lookup.py
new file mode 100644
index 00000000..60806eba
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/reverse_lookup.py
@@ -0,0 +1,411 @@
+"""Reverse lookup: OpenAlex keywords/topics → IPC/CPC codes via patents_openalex_keywords."""
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any
+
+import httpx
+
+from inse.patents.authors.ipc_openalex_mapping import (
+ _load_topic_cache,
+ normalize_openalex_id,
+)
+from inse.patents.common.elastic_search_client import MissingApiKeyError
+from inse.patents.keywords.model import KeywordPatentSearchItem
+from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
+from inse.patents.patents_openalex_keywords.ipc_entries import normalize_symbol
+from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX
+from inse.patents.patents_openalex_keywords.resolver import load_patents_openalex_keywords_json
+
+logger = logging.getLogger(__name__)
+
+_LEVEL_WEIGHTS = {
+ "subgroup": 1.0,
+ "group": 0.92,
+ "subclass": 0.85,
+ "class": 0.75,
+ "section": 0.6,
+}
+
+
+@dataclass(frozen=True)
+class IpcCodeMatch:
+ ipc_level: str
+ ipc_symbol: str
+ match_score: float
+ source_keyword: str
+ match_type: str
+
+
+def _keyword_variants(keyword: str) -> list[str]:
+ normalized = keyword.strip().casefold()
+ if not normalized:
+ return []
+ return list(dict.fromkeys([normalized, keyword.strip()]))
+
+
+def _topic_id_variants(topic_id: str | None) -> list[str]:
+ if not topic_id or not str(topic_id).strip():
+ return []
+ raw = str(topic_id).strip()
+ short = normalize_openalex_id(raw)
+ variants = [raw]
+ if short:
+ variants.append(short)
+ variants.append(f"https://openalex.org/{short}")
+ return list(dict.fromkeys(variants))
+
+
+def _topic_id_variants_for_item(item: KeywordPatentSearchItem) -> list[str]:
+ variants = _topic_id_variants(item.topic_id)
+ if variants:
+ return variants
+
+ display_name = (item.topic_display_name or "").strip()
+ if display_name:
+ info = _load_topic_cache().get(display_name)
+ if info and info.get("topic_id"):
+ return _topic_id_variants(str(info["topic_id"]))
+
+ return []
+
+
+def _weighted_score(
+ ipc_level: str,
+ base_score: float,
+ relevance_score: float,
+) -> float:
+ """Combine IPC mapping confidence with IPC hierarchy level.
+
+ LLM keyword relevance is not applied here: broad keywords often carry
+ relevance_score 0.0 while still mapping to valid OpenAlex topics.
+ """
+ _ = relevance_score
+ level_weight = _LEVEL_WEIGHTS.get(ipc_level, 0.7)
+ return round(base_score * level_weight, 4)
+
+
+@lru_cache(maxsize=1)
+def _build_json_inverted_index() -> tuple[
+ dict[str, list[tuple[str, str, float, str, str]]],
+ dict[str, list[tuple[str, str, float, str, str]]],
+]:
+ """keyword/topic_id -> list of (level, symbol, score, source_keyword, match_type)."""
+ by_keyword: dict[str, list[tuple[str, str, float, str, str]]] = {}
+ by_topic: dict[str, list[tuple[str, str, float, str, str]]] = {}
+
+ table = load_patents_openalex_keywords_json()
+ for level, entries in table.items():
+ for symbol, doc in entries.items():
+ for match in doc.get("keyword_matches") or []:
+ keyword = str(match.get("keyword") or "").strip()
+ if not keyword:
+ continue
+ key = keyword.casefold()
+ entry = (
+ level,
+ symbol,
+ float(match.get("match_score") or 0.0),
+ keyword,
+ "keyword",
+ )
+ by_keyword.setdefault(key, []).append(entry)
+ topic_id = match.get("topic_id")
+ if topic_id:
+ for variant in _topic_id_variants(str(topic_id)):
+ by_topic.setdefault(variant, []).append(entry)
+
+ for match in doc.get("topic_matches") or []:
+ topic_id = match.get("topic_id")
+ if not topic_id:
+ continue
+ entry = (
+ level,
+ symbol,
+ float(match.get("match_score") or 0.0),
+ str(match.get("topic_display_name") or topic_id),
+ "topic",
+ )
+ for variant in _topic_id_variants(str(topic_id)):
+ by_topic.setdefault(variant, []).append(entry)
+
+ return by_keyword, by_topic
+
+
+def clear_reverse_lookup_caches() -> None:
+ _build_json_inverted_index.cache_clear()
+
+
+def _merge_ipc_match(
+ matches: dict[tuple[str, str], IpcCodeMatch],
+ level: str,
+ symbol: str,
+ score: float,
+ source_keyword: str,
+ match_type: str,
+) -> None:
+ key = (level, normalize_symbol(symbol))
+ existing = matches.get(key)
+ if existing is None or score > existing.match_score:
+ matches[key] = IpcCodeMatch(
+ ipc_level=level,
+ ipc_symbol=normalize_symbol(symbol),
+ match_score=score,
+ source_keyword=source_keyword,
+ match_type=match_type,
+ )
+
+
+def _matches_from_doc(
+ doc: dict[str, Any],
+ item: KeywordPatentSearchItem,
+) -> list[IpcCodeMatch]:
+ ipc_level = str(doc.get("ipc_level") or "")
+ ipc_symbol = normalize_symbol(str(doc.get("ipc_symbol") or ""))
+ if not ipc_level or not ipc_symbol:
+ return []
+
+ keyword_variants = set(_keyword_variants(item.keyword))
+ topic_variants = set(_topic_id_variants_for_item(item))
+ topic_name = (item.topic_display_name or "").strip().casefold()
+ found: list[IpcCodeMatch] = []
+
+ for match in doc.get("keyword_matches") or []:
+ match_keyword = str(match.get("keyword") or "").strip()
+ if match_keyword.casefold() not in keyword_variants:
+ match_topic = match.get("topic_id")
+ if not match_topic or str(match_topic) not in topic_variants:
+ continue
+ score = _weighted_score(
+ ipc_level,
+ float(match.get("match_score") or 0.0),
+ item.relevance_score,
+ )
+ found.append(
+ IpcCodeMatch(
+ ipc_level=ipc_level,
+ ipc_symbol=ipc_symbol,
+ match_score=score,
+ source_keyword=item.keyword,
+ match_type="keyword",
+ )
+ )
+ break
+
+ for match in doc.get("topic_matches") or []:
+ match_topic = match.get("topic_id")
+ match_name = str(match.get("topic_display_name") or "").strip().casefold()
+ topic_hit = match_topic and str(match_topic) in topic_variants
+ name_hit = topic_name and match_name == topic_name
+ if not topic_hit and not name_hit:
+ continue
+ score = _weighted_score(
+ ipc_level,
+ float(match.get("match_score") or 0.0),
+ item.relevance_score,
+ )
+ found.append(
+ IpcCodeMatch(
+ ipc_level=ipc_level,
+ ipc_symbol=ipc_symbol,
+ match_score=score,
+ source_keyword=item.keyword,
+ match_type="topic",
+ )
+ )
+ break
+
+ return found
+
+
+def _json_lookup(items: list[KeywordPatentSearchItem]) -> list[IpcCodeMatch]:
+ by_keyword, by_topic = _build_json_inverted_index()
+ merged: dict[tuple[str, str], IpcCodeMatch] = {}
+
+ for item in items:
+ for level, symbol, base_score, source_keyword, match_type in by_keyword.get(
+ item.keyword.strip().casefold(), []
+ ):
+ score = _weighted_score(level, base_score, item.relevance_score)
+ _merge_ipc_match(
+ merged, level, symbol, score, item.keyword, match_type
+ )
+
+ for variant in _topic_id_variants_for_item(item):
+ for level, symbol, base_score, source_keyword, match_type in by_topic.get(
+ variant, []
+ ):
+ score = _weighted_score(level, base_score, item.relevance_score)
+ _merge_ipc_match(
+ merged, level, symbol, score, item.keyword, match_type
+ )
+
+ return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
+
+
+def _dedupe_ipc_matches(matches: list[IpcCodeMatch]) -> list[IpcCodeMatch]:
+ merged: dict[tuple[str, str], IpcCodeMatch] = {}
+ for match in matches:
+ _merge_ipc_match(
+ merged,
+ match.ipc_level,
+ match.ipc_symbol,
+ match.match_score,
+ match.source_keyword,
+ match.match_type,
+ )
+ return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
+
+
+def _build_es_should_clauses(items: list[KeywordPatentSearchItem]) -> list[dict[str, Any]]:
+ should: list[dict[str, Any]] = []
+ seen: set[str] = set()
+
+ for item in items:
+ for keyword in _keyword_variants(item.keyword):
+ if keyword in seen:
+ continue
+ seen.add(keyword)
+ should.append(
+ {
+ "nested": {
+ "path": "keyword_matches",
+ "query": {"term": {"keyword_matches.keyword": keyword}},
+ }
+ }
+ )
+
+ for topic_id in _topic_id_variants_for_item(item):
+ if topic_id in seen:
+ continue
+ seen.add(topic_id)
+ should.extend(
+ [
+ {
+ "nested": {
+ "path": "keyword_matches",
+ "query": {"term": {"keyword_matches.topic_id": topic_id}},
+ }
+ },
+ {
+ "nested": {
+ "path": "topic_matches",
+ "query": {"term": {"topic_matches.topic_id": topic_id}},
+ }
+ },
+ ]
+ )
+
+ topic_name = (item.topic_display_name or "").strip()
+ if topic_name and topic_name not in seen:
+ seen.add(topic_name)
+ should.append(
+ {
+ "nested": {
+ "path": "topic_matches",
+ "query": {
+ "term": {"topic_matches.topic_display_name": topic_name}
+ },
+ }
+ }
+ )
+
+ return should
+
+
+class KeywordIpcReverseLookup:
+ def __init__(self, client: PatentsOpenAlexKeywordsClient | None = None):
+ self.client = client or PatentsOpenAlexKeywordsClient()
+ self._elasticsearch_checked = False
+ self._elasticsearch_enabled = False
+
+ async def _elasticsearch_enabled_for_request(self) -> bool:
+ if self._elasticsearch_checked:
+ return self._elasticsearch_enabled
+ self._elasticsearch_checked = True
+ try:
+ self._elasticsearch_enabled = await self.client.index_exists()
+ except Exception as exc:
+ logger.warning("patents_openalex_keywords index check failed: %s", exc)
+ self._elasticsearch_enabled = False
+ return self._elasticsearch_enabled
+
+ async def lookup_ipc_codes(
+ self,
+ items: list[KeywordPatentSearchItem],
+ *,
+ max_codes: int = 40,
+ ) -> list[IpcCodeMatch]:
+ if not items:
+ return []
+
+ matches: list[IpcCodeMatch] = []
+ if await self._elasticsearch_enabled_for_request():
+ try:
+ matches = await self._lookup_via_elasticsearch(items)
+ except (MissingApiKeyError, httpx.HTTPError) as exc:
+ logger.warning("Keyword IPC ES lookup failed, using JSON fallback: %s", exc)
+ self._elasticsearch_enabled = False
+
+ if not matches:
+ matches = _json_lookup(items)
+
+ if not matches:
+ logger.info(
+ "No IPC codes resolved for keywords: %s; "
+ "build patents_openalex_keywords for better coverage.",
+ [item.keyword for item in items],
+ )
+
+ matches = _dedupe_ipc_matches(matches)
+ return matches[:max_codes]
+
+ async def _lookup_via_elasticsearch(
+ self,
+ items: list[KeywordPatentSearchItem],
+ ) -> list[IpcCodeMatch]:
+ should = _build_es_should_clauses(items)
+ if not should:
+ return []
+
+ payload = {
+ "size": 200,
+ "query": {"bool": {"should": should, "minimum_should_match": 1}},
+ "_source": [
+ "ipc_level",
+ "ipc_symbol",
+ "topic_matches",
+ "keyword_matches",
+ ],
+ }
+
+ async with httpx.AsyncClient(
+ base_url=self.client.base_url,
+ timeout=self.client.timeout,
+ transport=self.client.transport,
+ ) as client:
+ response = await client.post(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
+ headers=self.client._headers(),
+ json=payload,
+ )
+ response.raise_for_status()
+ data = response.json()
+
+ merged: dict[tuple[str, str], IpcCodeMatch] = {}
+ for hit in data.get("hits", {}).get("hits", []):
+ doc = hit.get("_source", {})
+ for item in items:
+ for match in _matches_from_doc(doc, item):
+ _merge_ipc_match(
+ merged,
+ match.ipc_level,
+ match.ipc_symbol,
+ match.match_score,
+ match.source_keyword,
+ match.match_type,
+ )
+
+ return sorted(merged.values(), key=lambda match: match.match_score, reverse=True)
diff --git a/service/src/main/inse/patents/keywords/search_queries.py b/service/src/main/inse/patents/keywords/search_queries.py
new file mode 100644
index 00000000..86a3ce9b
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/search_queries.py
@@ -0,0 +1,166 @@
+"""Elasticsearch query builders for IPC-based patent search."""
+from __future__ import annotations
+
+from typing import Any
+
+from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
+from inse.patents.ipc_lookup import parse_ipc_symbol
+from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
+
+_PATENT_SOURCE_FIELDS = [
+ "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",
+]
+
+_USPTO_SOURCE_FIELDS = [
+ "publication_number",
+ "country",
+ "publication_date",
+ "publication_year",
+ "application_number",
+ "application_date",
+ "application_type",
+ "number_of_claims",
+ "status",
+ "title",
+ "abstract",
+ "inventors_names",
+ "assignees_orgs",
+ "ipcr",
+ "cpc",
+]
+
+_MIN_MATCH_TERM_LEN = 4
+
+
+def _search_terms_for_symbol(symbol: str) -> list[str]:
+ """Derive EPO/USPTO `match` terms from an IPC/CPC symbol.
+
+ Patent indices store IPC values like ``B60L 53/14 20060101AFI...``.
+ Wildcard/prefix on normalized symbols (``B60L*``) does not match; ``match``
+ on subclass codes (``B60L``) does.
+ """
+ normalized = normalize_symbol(symbol)
+ if not normalized:
+ return []
+
+ terms: list[str] = []
+ subclass = infer_subclass(normalized)
+ if subclass and len(subclass) >= _MIN_MATCH_TERM_LEN:
+ terms.append(subclass)
+
+ keys = parse_ipc_symbol(normalized)
+ if keys is not None:
+ if keys.subclass and len(keys.subclass) >= _MIN_MATCH_TERM_LEN:
+ terms.append(normalize_symbol(keys.subclass))
+ if keys.main_group and len(normalize_symbol(keys.main_group)) >= _MIN_MATCH_TERM_LEN:
+ terms.append(normalize_symbol(keys.main_group))
+
+ if len(normalized) >= _MIN_MATCH_TERM_LEN:
+ prefix = normalized[:_MIN_MATCH_TERM_LEN]
+ if prefix not in terms:
+ terms.append(prefix)
+
+ return list(dict.fromkeys(term for term in terms if len(term) >= _MIN_MATCH_TERM_LEN))
+
+
+def _ipc_match_clauses(field: str, terms: list[str]) -> list[dict[str, Any]]:
+ clauses: list[dict[str, Any]] = []
+ seen: set[tuple[str, str]] = set()
+ for term in terms:
+ if len(term) < _MIN_MATCH_TERM_LEN:
+ continue
+ key = (field, term)
+ if key in seen:
+ continue
+ seen.add(key)
+ clauses.append({"match": {field: term}})
+ return clauses
+
+
+class IpcPatentSearchQueries:
+ def epo_query_by_ipc_terms(
+ self,
+ terms: list[str],
+ size: int = DEFAULT_SEARCH_SIZE,
+ ) -> dict[str, Any]:
+ should = _ipc_match_clauses("ipc", terms) + _ipc_match_clauses("cpc", terms)
+ query: dict[str, Any] = (
+ {"match_none": {}}
+ if not should
+ else {"bool": {"should": should, "minimum_should_match": 1}}
+ )
+ return {
+ "size": size,
+ "track_total_hits": True,
+ "sort": [
+ {"date_publication": {"order": "desc", "missing": "_last"}},
+ "_doc",
+ ],
+ "_source": _PATENT_SOURCE_FIELDS,
+ "query": query,
+ }
+
+ def uspto_query_by_ipc_terms(
+ self,
+ terms: list[str],
+ size: int = DEFAULT_SEARCH_SIZE,
+ ) -> dict[str, Any]:
+ should = _ipc_match_clauses("ipcr", terms) + _ipc_match_clauses("cpc", terms)
+ query: dict[str, Any] = (
+ {"match_none": {}}
+ if not should
+ else {"bool": {"should": should, "minimum_should_match": 1}}
+ )
+ return {
+ "size": size,
+ "track_total_hits": True,
+ "sort": [
+ {"publication_date": {"order": "desc", "missing": "_last"}},
+ "_doc",
+ ],
+ "_source": _USPTO_SOURCE_FIELDS,
+ "query": query,
+ }
+
+ def epo_query_by_ipc_symbols(
+ self,
+ symbols: list[str],
+ size: int = DEFAULT_SEARCH_SIZE,
+ ) -> dict[str, Any]:
+ terms: list[str] = []
+ seen: set[str] = set()
+ for symbol in symbols:
+ for term in _search_terms_for_symbol(symbol):
+ if term in seen:
+ continue
+ seen.add(term)
+ terms.append(term)
+ return self.epo_query_by_ipc_terms(terms, size=size)
+
+ def uspto_query_by_ipc_symbols(
+ self,
+ symbols: list[str],
+ size: int = DEFAULT_SEARCH_SIZE,
+ ) -> dict[str, Any]:
+ terms: list[str] = []
+ seen: set[str] = set()
+ for symbol in symbols:
+ for term in _search_terms_for_symbol(symbol):
+ if term in seen:
+ continue
+ seen.add(term)
+ terms.append(term)
+ return self.uspto_query_by_ipc_terms(terms, size=size)
diff --git a/service/src/main/inse/patents/keywords/service.py b/service/src/main/inse/patents/keywords/service.py
new file mode 100644
index 00000000..8aac2ea4
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/service.py
@@ -0,0 +1,23 @@
+from typing import Annotated
+
+from fastapi import APIRouter, Body
+
+from inse.patents.keywords import logic
+from inse.patents.keywords.model import PatentsByKeywordsRequest, PatentsByKeywordsResponse
+
+router = APIRouter(prefix="/api/inse-service/keywords", tags=["Keywords"])
+
+
+@router.post(
+ "/patents",
+ operation_id="getPatentsByKeywords",
+ response_model=PatentsByKeywordsResponse,
+ summary="Find patents matching extracted OpenAlex keywords.",
+)
+async def get_patents_by_keywords(
+ request: Annotated[
+ PatentsByKeywordsRequest,
+ Body(description="Keywords enriched with OpenAlex topics."),
+ ],
+):
+ return await logic.get_patents_by_keywords(request)
diff --git a/service/src/main/inse/patents/keywords/test_logic.py b/service/src/main/inse/patents/keywords/test_logic.py
new file mode 100644
index 00000000..cb6dda70
--- /dev/null
+++ b/service/src/main/inse/patents/keywords/test_logic.py
@@ -0,0 +1,672 @@
+"""Tests for keyword-based patent search."""
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
+from inse.patents.common import model
+from inse.patents.keywords.logic import (
+ _compute_final_score,
+ _filter_keywords_for_patent_search,
+ _ipc_hierarchy_quality,
+ _keyword_is_patent_searchable,
+ _limit_matches_per_keyword,
+ _patent_passes_relevance_gate,
+ _patent_search_terms,
+ _score_ipc_match,
+ _score_patent,
+ _term_from_ipc_match,
+ _text_overlap_score,
+ _text_search_terms,
+ _topics_overlap_keywords,
+ get_patents_by_keywords,
+)
+from inse.patents.keywords.reverse_lookup import (
+ IpcCodeMatch,
+ _json_lookup,
+ _weighted_score,
+ clear_reverse_lookup_caches,
+)
+from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
+from inse.patents.keywords.search_queries import IpcPatentSearchQueries, _search_terms_for_symbol
+
+
+def test_ipc_hierarchy_quality_exact_match() -> None:
+ assert _ipc_hierarchy_quality("C07C243/08", "C07C243/08") == 1.0
+
+
+def test_ipc_hierarchy_quality_same_main_group() -> None:
+ assert _ipc_hierarchy_quality("C07C243/086", "C07C243/088") == 0.90
+
+
+def test_ipc_hierarchy_quality_same_subclass() -> None:
+ assert _ipc_hierarchy_quality("C07C243/08", "C07C31/20") == 0.75
+
+
+def test_ipc_hierarchy_quality_no_match() -> None:
+ assert _ipc_hierarchy_quality("C07C243/08", "C08F110/10") == 0.0
+
+
+def test_ipc_hierarchy_quality_invalid_code() -> None:
+ assert _ipc_hierarchy_quality("", "C07C243/08") == 0.0
+ assert _ipc_hierarchy_quality("C07", "C07C243/08") == 0.0
+
+
+def test_term_from_ipc_match_returns_subclass() -> None:
+ match = IpcCodeMatch("subgroup", "C07C243/08", 0.9, "Organic Chemistry", "keyword")
+ assert _term_from_ipc_match(match) == "C07C"
+
+
+def test_term_from_ipc_match_skips_class_level() -> None:
+ match = IpcCodeMatch("class", "C07", 0.7, "Chemistry", "topic")
+ assert _term_from_ipc_match(match) is None
+
+
+def test_patent_search_terms_deduplicates_chemistry_subclasses() -> None:
+ ipc_matches = [
+ IpcCodeMatch("subgroup", "C25B3/03", 0.9037, "Anorganische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"),
+ IpcCodeMatch("subgroup", "D06L4/17", 0.8745, "Technische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "C09B43/34", 0.8738, "Chemische Reaktionen", "keyword"),
+ IpcCodeMatch("subgroup", "C02F1/285", 0.8698, "Organische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "B01J2219/00709", 0.8679, "Organische Chemie", "keyword"),
+ ]
+ terms = _patent_search_terms(ipc_matches)
+ assert terms == ["C25B", "C07C", "C09B", "D06L", "C02F", "B01J"]
+
+
+def test_score_ipc_match_returns_only_best_evidence() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP123",
+ source="EPO",
+ ipc=["C07C243/08"],
+ )
+ ipc_matches = [
+ IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "C09B68/48", 0.8885, "Chemische Reaktionen", "keyword"),
+ ]
+ result = _score_ipc_match(patent, ipc_matches)
+ assert result is not None
+ score, keywords, symbols = result
+ assert score == 0.8989
+ assert keywords == ["Anorganische Chemie"]
+ assert symbols == ["C07C243/08"]
+
+
+def test_score_ipc_match_keeps_equal_best_matches() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP123",
+ source="EPO",
+ ipc=["C07C243/08"],
+ )
+ ipc_matches = [
+ IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Anorganische Chemie", "keyword"),
+ IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"),
+ ]
+ result = _score_ipc_match(patent, ipc_matches)
+ assert result is not None
+ _, keywords, symbols = result
+ assert keywords == ["Anorganische Chemie", "Organische Chemie"]
+ assert symbols == ["C07C243/08"]
+
+
+def test_score_patent_uses_best_ipc_match() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP123",
+ source="EPO",
+ ipc=["G01S 5/02"],
+ title="Wireless localization system",
+ )
+ ipc_matches = [
+ IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
+ IpcCodeMatch("class", "G01", 0.5, "wireless", "topic"),
+ ]
+ result = _score_patent(
+ patent,
+ ipc_matches,
+ patent_topics=[
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T12345",
+ subfield_name="Remote Sensing",
+ )
+ ],
+ keyword_topic_ids=frozenset({"T12345"}),
+ search_keywords=[
+ KeywordPatentSearchItem(
+ keyword="wireless localization",
+ topic_id="https://openalex.org/T12345",
+ relevance_score=1.0,
+ )
+ ],
+ )
+ assert result is not None
+ score, keywords, symbols = result
+ assert score == _compute_final_score(0.675, 1.0, 2 / 3)
+ assert "localization" in keywords
+ assert "G01S" in symbols
+
+
+def test_score_patent_requires_topic_overlap() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP123",
+ source="EPO",
+ ipc=["G01S 5/02"],
+ )
+ ipc_matches = [
+ IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
+ ]
+ patent_topics = [
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99999",
+ subfield_name="Oncology",
+ )
+ ]
+ result = _score_patent(
+ patent,
+ ipc_matches,
+ patent_topics=patent_topics,
+ keyword_topic_ids=frozenset({"T12345"}),
+ keyword_subfield_names=frozenset({"law"}),
+ )
+ assert result is None
+
+
+def test_score_patent_accepts_compatible_engineering_and_computer_science() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP456",
+ source="EPO",
+ ipc=["G06N 3/08"],
+ title="Deep learning classifier",
+ abstract="A neural network for classification tasks.",
+ )
+ ipc_matches = [
+ IpcCodeMatch("subclass", "G06N", 0.9, "Deep Learning", "keyword"),
+ ]
+ result = _score_patent(
+ patent,
+ ipc_matches,
+ patent_topics=[
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T12072",
+ field_name="Computer Science",
+ )
+ ],
+ keyword_topic_ids=frozenset({"T10653"}),
+ keyword_subfield_names=frozenset({"control and systems engineering"}),
+ keyword_soft_field_names=frozenset({"engineering"}),
+ search_keywords=[
+ KeywordPatentSearchItem(
+ keyword="Deep Learning",
+ topic_id="https://openalex.org/T10653",
+ field_name="Engineering",
+ relevance_score=0.9,
+ )
+ ],
+ )
+ assert result is not None
+
+
+def test_filter_keywords_for_patent_search_prefers_coarse_and_fine_over_broad() -> None:
+ items = [
+ KeywordPatentSearchItem(
+ keyword="Naturwissenschaft",
+ keyword_level="broad",
+ relevance_score=1.0,
+ topic_id="https://openalex.org/T14329",
+ field_name="Environmental Science",
+ ),
+ KeywordPatentSearchItem(
+ keyword="Thermodynamik",
+ keyword_level="coarse",
+ relevance_score=0.8,
+ topic_id="https://openalex.org/T12345",
+ field_name="Physics and Astronomy",
+ subfield_name="Statistical and Nonlinear Physics",
+ ),
+ KeywordPatentSearchItem(
+ keyword="noise",
+ keyword_level="coarse",
+ relevance_score=0.0,
+ ),
+ ]
+ filtered = _filter_keywords_for_patent_search(items)
+ assert [item.keyword for item in filtered] == ["Thermodynamik"]
+
+
+def test_filter_keywords_for_patent_search_allows_zero_relevance_with_topic() -> None:
+ item = KeywordPatentSearchItem(
+ keyword="Deep Learning",
+ keyword_level="fine",
+ relevance_score=0.0,
+ topic_id="https://openalex.org/T12072",
+ field_name="Computer Science",
+ subfield_name="Artificial Intelligence",
+ )
+ assert _keyword_is_patent_searchable(item)
+
+
+def test_filter_keywords_for_patent_search_allows_high_relevance_with_technical_topic() -> None:
+ items = [
+ KeywordPatentSearchItem(
+ keyword="Deep Learning",
+ keyword_level="fine",
+ relevance_score=0.9,
+ topic_id="https://openalex.org/T12072",
+ field_name="Computer Science",
+ subfield_name="Artificial Intelligence",
+ ),
+ ]
+ filtered = _filter_keywords_for_patent_search(items)
+ assert [item.keyword for item in filtered] == ["Deep Learning"]
+
+
+def test_topics_overlap_keywords_soft_match_engineering_and_computer_science() -> None:
+ patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["G06N 3/08"])
+ patent_topics = [
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T12072",
+ field_name="Computer Science",
+ )
+ ]
+ assert _topics_overlap_keywords(
+ patent_topics,
+ frozenset({"T10653"}),
+ frozenset({"control and systems engineering"}),
+ frozenset({"engineering"}),
+ patent=patent,
+ )
+
+
+def test_score_patent_accepts_matching_topic_id() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP123",
+ source="EPO",
+ ipc=["G01S 5/02"],
+ )
+ ipc_matches = [
+ IpcCodeMatch("subclass", "G01S", 0.9, "localization", "keyword"),
+ ]
+ patent_topics = [
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T12345",
+ subfield_name="Remote Sensing",
+ )
+ ]
+ result = _score_patent(
+ patent,
+ ipc_matches,
+ patent_topics=patent_topics,
+ keyword_topic_ids=frozenset({"T12345"}),
+ )
+ assert result is not None
+
+
+def test_topics_overlap_keywords_uses_subfield_name_not_field() -> None:
+ patent_topics = [
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99999",
+ subfield_name="Chemistry",
+ field_name="Physical Sciences",
+ )
+ ]
+ assert not _topics_overlap_keywords(
+ patent_topics,
+ frozenset(),
+ frozenset({"law"}),
+ frozenset(),
+ )
+ assert _topics_overlap_keywords(
+ patent_topics,
+ frozenset(),
+ frozenset({"chemistry"}),
+ frozenset(),
+ )
+ assert _topics_overlap_keywords(
+ patent_topics,
+ frozenset(),
+ frozenset(),
+ frozenset({"physical sciences"}),
+ )
+ assert not _topics_overlap_keywords(
+ patent_topics,
+ frozenset(),
+ frozenset(),
+ frozenset({"engineering"}),
+ )
+
+
+def test_topics_overlap_keywords_rejects_patents_without_topics() -> None:
+ assert not _topics_overlap_keywords(
+ [],
+ frozenset({"T12345"}),
+ frozenset(),
+ frozenset({"chemistry"}),
+ )
+
+
+def test_limit_matches_per_keyword() -> None:
+ matches = [
+ IpcCodeMatch("subclass", "C07C", 0.95, "Organic Chemistry", "keyword"),
+ IpcCodeMatch("group", "C07C31", 0.9, "Organic Chemistry", "keyword"),
+ IpcCodeMatch("subclass", "C01B", 0.88, "Inorganic Chemistry", "keyword"),
+ IpcCodeMatch("subclass", "C01C", 0.87, "Inorganic Chemistry", "keyword"),
+ ]
+ limited = _limit_matches_per_keyword(matches, limit=2)
+ assert len(limited) == 4
+ organic = [match for match in limited if match.source_keyword == "Organic Chemistry"]
+ inorganic = [match for match in limited if match.source_keyword == "Inorganic Chemistry"]
+ assert len(organic) == 2
+ assert len(inorganic) == 2
+ assert organic[0].ipc_symbol == "C07C"
+ assert inorganic[0].ipc_symbol == "C01B"
+
+
+def test_text_overlap_score_uses_title_and_abstract() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP1",
+ source="EPO",
+ title="Organic chemistry synthesis",
+ abstract="A method for catalytic reactions.",
+ )
+ score = _text_overlap_score(
+ patent,
+ ["organic", "chemistry", "catalytic", "reactions", "unrelated"],
+ )
+ assert score == 1.0
+
+
+def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP1",
+ source="EPO",
+ title="Diagnostic imaging device",
+ abstract="Medical diagnosis using imaging.",
+ )
+ assert _patent_passes_relevance_gate(
+ [],
+ keyword_topic_ids=frozenset({"T99999"}),
+ keyword_subfield_names=frozenset(),
+ keyword_soft_field_names=frozenset({"medicine"}),
+ patent=patent,
+ text_score=_text_overlap_score(patent, ["diagnostic", "imaging", "diagnosis"]),
+ )
+
+
+def test_patent_passes_relevance_gate_rejects_ipc_only() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP1",
+ source="EPO",
+ title="Humidifier system",
+ abstract="Water exchange membrane.",
+ )
+ assert not _patent_passes_relevance_gate(
+ [],
+ keyword_topic_ids=frozenset({"T99999"}),
+ keyword_subfield_names=frozenset(),
+ keyword_soft_field_names=frozenset({"medicine"}),
+ patent=patent,
+ text_score=0.0,
+ )
+
+
+def test_compute_final_score_weights_ipc_topic_and_text() -> None:
+ assert _compute_final_score(0.9, 1.0, 1.0) == round(
+ 0.60 * 0.9 + 0.25 * 1.0 + 0.15 * 1.0,
+ 4,
+ )
+ assert _compute_final_score(0.6742, 0.0, 0.0) == round(0.60 * 0.6742, 4)
+
+
+def test_score_patent_rejects_subclass_only_without_topic_or_text() -> None:
+ patent = model.PatentEntry(
+ patent_id="EP1",
+ source="EPO",
+ ipc=["C07C31/20"],
+ title="Humidifier system",
+ abstract="Water exchange membrane.",
+ )
+ ipc_matches = [
+ IpcCodeMatch("subgroup", "C07C243/08", 0.8989, "Organische Chemie", "keyword"),
+ ]
+ result = _score_patent(
+ patent,
+ ipc_matches,
+ patent_topics=[],
+ keyword_topic_ids=frozenset({"T99999"}),
+ keyword_soft_field_names=frozenset({"chemistry"}),
+ search_keywords=[
+ KeywordPatentSearchItem(
+ keyword="Organische Chemie",
+ topic_id="https://openalex.org/T99999",
+ field_name="Chemistry",
+ relevance_score=1.0,
+ )
+ ],
+ )
+ assert result is None
+
+
+def test_get_patents_by_keywords_uses_symbol_queries() -> None:
+ queries = IpcPatentSearchQueries()
+ captured: list[str] = []
+
+ async def fake_search_epo(query):
+ captured.append("epo")
+ assert "query" in query
+ return {"hits": {"hits": []}}
+
+ async def fake_search_uspto(query):
+ captured.append("uspto")
+ return {"hits": {"hits": []}}
+
+ request = PatentsByKeywordsRequest(
+ keywords=[
+ KeywordPatentSearchItem(
+ keyword="Organische Chemie",
+ keyword_level="coarse",
+ topic_id="https://openalex.org/T13859",
+ field_name="Chemistry",
+ relevance_score=1.0,
+ )
+ ]
+ )
+
+ with patch(
+ "inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
+ new=AsyncMock(
+ return_value=[
+ IpcCodeMatch(
+ "subgroup",
+ "C07C243/08",
+ 0.8989,
+ "Organische Chemie",
+ "keyword",
+ )
+ ]
+ ),
+ ), patch(
+ "inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
+ new=AsyncMock(side_effect=fake_search_epo),
+ ), patch(
+ "inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
+ new=AsyncMock(side_effect=fake_search_uspto),
+ ), patch(
+ "inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
+ new=AsyncMock(return_value={}),
+ ), patch(
+ "inse.patents.keywords.logic.enrich_patents_classifications",
+ new=AsyncMock(),
+ ), patch.object(
+ IpcPatentSearchQueries,
+ "epo_query_by_ipc_symbols",
+ wraps=queries.epo_query_by_ipc_symbols,
+ ) as epo_symbols, patch.object(
+ IpcPatentSearchQueries,
+ "uspto_query_by_ipc_symbols",
+ wraps=queries.uspto_query_by_ipc_symbols,
+ ) as uspto_symbols:
+ asyncio.run(get_patents_by_keywords(request))
+
+ epo_symbols.assert_called_once()
+ uspto_symbols.assert_called_once()
+ assert epo_symbols.call_args.args[0] == ["C07C"]
+ assert captured == ["epo", "uspto"]
+
+
+def test_text_search_terms_include_topic_metadata() -> None:
+ items = [
+ KeywordPatentSearchItem(
+ keyword="Organische Chemie",
+ topic_display_name="Organic Chemistry",
+ subfield_name="Organic Chemistry",
+ field_name="Chemistry",
+ relevance_score=0.9,
+ topic_id="https://openalex.org/T1",
+ )
+ ]
+ terms = _text_search_terms(items)
+ assert "organische" in terms
+ assert "organic" in terms
+ assert "chemistry" in terms
+
+
+def test_weighted_score_applies_level_not_llm_relevance() -> None:
+ score_high = _weighted_score("subclass", 0.8, 1.0)
+ score_zero = _weighted_score("subclass", 0.8, 0.0)
+ assert score_high == round(0.8 * 0.85, 4)
+ assert score_zero == score_high
+
+
+def test_search_terms_use_subclass_prefix() -> None:
+ assert "B60R" in _search_terms_for_symbol("B60R2300/8086")
+ assert "G06N" in _search_terms_for_symbol("G06N")
+
+
+def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
+ clear_reverse_lookup_caches()
+ monkeypatch.setattr(
+ "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
+ lambda: {},
+ )
+ clear_reverse_lookup_caches()
+
+ items = [KeywordPatentSearchItem(keyword="Medizin", relevance_score=1.0)]
+ assert _json_lookup(items) == []
+
+
+def test_json_lookup_finds_ipc_for_keyword(monkeypatch) -> None:
+ clear_reverse_lookup_caches()
+ monkeypatch.setattr(
+ "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
+ lambda: {
+ "subclass": {
+ "G01S": {
+ "ipc_level": "subclass",
+ "ipc_symbol": "G01S",
+ "keyword_matches": [
+ {
+ "keyword": "wireless localization",
+ "match_score": 0.91,
+ "topic_id": "https://openalex.org/T12345",
+ }
+ ],
+ "topic_matches": [],
+ }
+ }
+ },
+ )
+ clear_reverse_lookup_caches()
+
+ items = [
+ KeywordPatentSearchItem(
+ keyword="wireless localization",
+ topic_id="https://openalex.org/T12345",
+ relevance_score=1.0,
+ )
+ ]
+ matches = _json_lookup(items)
+ assert len(matches) == 1
+ assert matches[0].ipc_symbol == "G01S"
+ assert matches[0].match_score > 0
+
+
+def test_json_lookup_finds_ipc_for_topic_id(monkeypatch) -> None:
+ clear_reverse_lookup_caches()
+ monkeypatch.setattr(
+ "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
+ lambda: {
+ "subclass": {
+ "G06N": {
+ "ipc_level": "subclass",
+ "ipc_symbol": "G06N",
+ "keyword_matches": [],
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T12072",
+ "topic_display_name": "Machine Learning and Algorithms",
+ "match_score": 0.88,
+ }
+ ],
+ }
+ }
+ },
+ )
+ clear_reverse_lookup_caches()
+
+ items = [
+ KeywordPatentSearchItem(
+ keyword="Klassifikation",
+ topic_id="https://openalex.org/T12072",
+ topic_display_name="Machine Learning and Algorithms",
+ relevance_score=1.0,
+ )
+ ]
+ matches = _json_lookup(items)
+ assert len(matches) == 1
+ assert matches[0].ipc_symbol == "G06N"
+ assert matches[0].match_type == "topic"
+
+
+def test_json_lookup_resolves_topic_id_from_display_name(monkeypatch) -> None:
+ clear_reverse_lookup_caches()
+ monkeypatch.setattr(
+ "inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
+ lambda: {
+ "subclass": {
+ "G01N": {
+ "ipc_level": "subclass",
+ "ipc_symbol": "G01N",
+ "keyword_matches": [],
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T14329",
+ "topic_display_name": "Science and Climate Studies",
+ "match_score": 0.9,
+ }
+ ],
+ }
+ }
+ },
+ )
+ monkeypatch.setattr(
+ "inse.patents.keywords.reverse_lookup._load_topic_cache",
+ lambda: {
+ "Science and Climate Studies": {
+ "topic_id": "https://openalex.org/T14329",
+ }
+ },
+ )
+ clear_reverse_lookup_caches()
+
+ items = [
+ KeywordPatentSearchItem(
+ keyword="Science and Climate Studies",
+ topic_display_name="Science and Climate Studies",
+ relevance_score=1.0,
+ )
+ ]
+ matches = _json_lookup(items)
+ assert len(matches) == 1
+ assert matches[0].ipc_symbol == "G01N"
diff --git a/service/src/main/inse/patents/logic.py b/service/src/main/inse/patents/logic.py
index 6d2522c4..26e73984 100644
--- a/service/src/main/inse/patents/logic.py
+++ b/service/src/main/inse/patents/logic.py
@@ -1,5 +1,5 @@
"""Backward-compatible re-exports."""
-from inse.patents.all.logic import get_all_patents
+from inse.patents.all.logic import get_all_patents, get_patent_by_id
from inse.patents.authors.logic import get_patents_by_author_id
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
from inse.patents.institutions.logic import (
@@ -7,316 +7,11 @@ from inse.patents.institutions.logic import (
get_patents_by_institution_id,
)
-import logging
-import asyncio
-
-
-from ..persons import logic as person_logic
-from ..models.openalex.author import Author
-from . import model
-from inse.exceptions import MissingApiKeyError, ElasticsearchException
-from .elastic_search_client import PatentSearchClient
-from .elastic_search_all_patents_client import AllPatentsSearchClient
-from .ipc_search_client import IpcSearchClient
-from .ipc_lookup import extract_ipc_symbol
-from .name_matching import name_matches
-from datetime import datetime
-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(
- patent_id: str,
- title: str,
- prefix: str,
- filling_date: str | None = None,
- client: PatentSearchClient | None = None,
-) -> model.PatentEntry:
- search_client = client or PatentSearchClient()
-
- if filling_date:
- filling_date = normalize_patent_date(filling_date)
- data = await search_client.get_by_id_or_title(
- patent_id=patent_id,
- prefix=prefix,
- title=title,
- filling_date=filling_date,
- )
-
- parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
- elements = parse(data)
-
- if not elements:
- return None
- return elements[0]
-
-
-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 = await _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=[],
- )
-
- epo_data, uspto_data = await _search_both_indices(
- search_client, last_name, first_name
- )
-
- 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):
- epo_result, uspto_result = 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)),
- )
- return epo_result, uspto_result
-
-
-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 _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
- ]
-
-
-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 ElasticsearchException 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 _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 _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 _get_author(author_id: str) -> Author | None:
- short_id = author_id.replace("https://openalex.org/", "")
- result = await 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
-
-
-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",
- client: PatentSearchClient | None = None,
- ipc_client: IpcSearchClient | None = None,
-) -> model.AllPatentsResponse:
- all_patents_client = AllPatentsSearchClient()
- ipc_search_client = ipc_client or IpcSearchClient()
-
- if source == "EPO":
- epo_data = await all_patents_client.search_epo(
- all_patents_client.epo_query(page, size, search, sort_direction)
- )
- 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)
- )
- 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)
- ),
- all_patents_client.search_uspto(
- all_patents_client.uspto_query(page, half, search, sort_direction)
- ),
- )
- 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)
- )
-
-
- await _enrich_patents_classifications(patents, ipc_search_client)
-
- return model.AllPatentsResponse(
- total=total,
- page=page,
- size=size,
- patents=patents,
- )
+__all__ = [
+ "_deduplicate_patents",
+ "_filter_patents_by_institution",
+ "get_all_patents",
+ "get_patent_by_id",
+ "get_patents_by_author_id",
+ "get_patents_by_institution_id",
+]
diff --git a/service/src/main/inse/patents/name_matching.py b/service/src/main/inse/patents/name_matching.py
index a1e45065..c40ce50c 100644
--- a/service/src/main/inse/patents/name_matching.py
+++ b/service/src/main/inse/patents/name_matching.py
@@ -1,7 +1,10 @@
"""Backward-compatible re-exports."""
from inse.patents.authors.name_matching import ( # noqa: F401
first_name_match_kind,
+ first_name_match_kind_for_person,
+ inventor_search_phrases,
name_matches,
+ name_matches_person,
search_name_variants,
tokens_equal,
)
diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py
index 5f5e32f1..157fefe1 100644
--- a/service/src/main/inse/patents/org/elastic_search_client.py
+++ b/service/src/main/inse/patents/org/elastic_search_client.py
@@ -1,10 +1,13 @@
"""HTTP client for the org_patents Elasticsearch index."""
import json
import logging
+from datetime import datetime
from typing import Any
import httpx
+from inse.integrations import elasticsearch
+from inse.models.openalex.author import Author
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
@@ -13,6 +16,91 @@ from inse import config
logger = logging.getLogger(__name__)
DEFAULT_PAGE_SIZE = 20
+OPENALEX_AUTHORS_INDEX = "openalex-authors"
+AUTHOR_PAGE_SIZE = 500
+
+
+async def fetch_authors_by_institution_name(institution_name: str) -> list[Author]:
+ """Fetches OpenAlex authors currently affiliated with institution_name.
+
+ Mirrors the persons/search-list default filter: last_known_institutions
+ must match AND there must be an affiliations entry for the same
+ institution from the current year or the year before.
+ """
+ target_year = datetime.now().year - 1
+ query = {
+ "bool": {
+ "filter": [
+ {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "match_phrase": {
+ "last_known_institutions.display_name": institution_name,
+ }
+ },
+ }
+ },
+ {
+ "nested": {
+ "path": "affiliations",
+ "query": {
+ "bool": {
+ "filter": [
+ {
+ "match_phrase": {
+ "affiliations.institution.display_name": institution_name,
+ }
+ },
+ {
+ "range": {
+ "affiliations.years": {"gte": target_year},
+ }
+ },
+ ]
+ }
+ },
+ }
+ },
+ ]
+ }
+ }
+ sort = [
+ {"works_count": {"order": "desc"}},
+ {"id": {"order": "asc"}},
+ ]
+
+ authors: list[Author] = []
+ search_after: list | None = None
+
+ while True:
+ body: dict = {
+ "size": AUTHOR_PAGE_SIZE,
+ "query": query,
+ "sort": sort,
+ }
+ if search_after:
+ body["search_after"] = search_after
+
+ response = await elasticsearch.search(index=OPENALEX_AUTHORS_INDEX, 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
class OrgPatentsSearchClient:
@@ -65,24 +153,66 @@ class OrgPatentsSearchClient:
mapping_response.raise_for_status()
async def delete_by_institution(self, institution_id: str) -> int:
- payload = {
- "query": {"term": {"institution_id": institution_id.upper()}},
- }
+ """Deletes all org_patents documents for institution_id.
+
+ Uses a search + bulk-delete-by-id loop instead of _delete_by_query:
+ the patent-cluster API key has been observed to reject _delete_by_query
+ with 403 Forbidden, while individual document deletes via _bulk succeed.
+ """
+ short_id = institution_id.upper()
+ query = {"term": {"institution_id": short_id}}
+ page_size = 1000
+ deleted_total = 0
+
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)
+ while True:
+ search_response = await client.post(
+ f"/{ORG_PATENTS_INDEX}/_search",
+ headers=self._headers(),
+ json={
+ "size": page_size,
+ "query": query,
+ "_source": False,
+ "sort": ["_doc"],
+ },
+ )
+ if search_response.status_code == 404:
+ return deleted_total
+ search_response.raise_for_status()
+ hits = search_response.json().get("hits", {}).get("hits", [])
+ if not hits:
+ break
+
+ bulk_lines = [
+ json.dumps({"delete": {"_index": ORG_PATENTS_INDEX, "_id": hit["_id"]}})
+ for hit in hits
+ ]
+ bulk_response = await client.post(
+ "/_bulk",
+ content="\n".join(bulk_lines) + "\n",
+ headers=self._headers("application/x-ndjson"),
+ params={"refresh": "true"},
+ )
+ bulk_response.raise_for_status()
+ result = bulk_response.json()
+ if result.get("errors"):
+ failed = [
+ item
+ for item in result.get("items", [])
+ if item.get("delete", {}).get("status", 200) >= 400
+ ]
+ logger.error("Bulk delete errors: %s", failed[:3])
+ raise RuntimeError("Bulk deleting existing org_patents documents failed.")
+
+ deleted_total += len(hits)
+ if len(hits) < page_size:
+ break
+
+ return deleted_total
async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None:
if not documents:
diff --git a/service/src/main/inse/patents/org/logic.py b/service/src/main/inse/patents/org/logic.py
index 4e8f8308..c6cc79e4 100644
--- a/service/src/main/inse/patents/org/logic.py
+++ b/service/src/main/inse/patents/org/logic.py
@@ -10,21 +10,31 @@ 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.authors.identity import (
+ author_institution_names,
+ is_ambiguous_name,
+ patent_institution_match,
+ patent_personal_assignee_match,
+)
+from inse.patents.authors.name_matching import filter_patents_by_author_name
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.model import PatentEntry
from inse.patents.common.parsing import (
deduplicate_patents,
enrich_patents_classifications,
+ enrich_patents_openalex_topics,
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.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
+from inse.patents.org.elastic_search_client import (
+ OrgPatentsSearchClient,
+ fetch_authors_by_institution_name,
+)
from inse.patents.org.model import (
MatchType,
MatchTypeFilter,
@@ -36,40 +46,10 @@ 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
@@ -103,6 +83,33 @@ def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchTy
return "name"
+def _canonical_authors_by_name(
+ author_patents: list[tuple[Author, list[PatentEntry]]],
+) -> dict[str, Author]:
+ """Picks one Author per case-normalized display name to attribute matches to.
+
+ OpenAlex sometimes merges multiple real people who share a name into a
+ single, noisy author record with a long, unrelated affiliation history
+ (e.g. an economist and a biochemist both named "Michael Ehrmann" ending up
+ under one ID with both "European Central Bank" and "University of X").
+ Such merged records tend to have an inflated works_count and therefore
+ sort first in the author list, which would otherwise make them "win" the
+ dedup below. Preferring the author with the fewest total institutions
+ favors the cleaner, more specific identity for the drill-down link.
+ """
+ canonical: dict[str, Author] = {}
+ for author, _ in author_patents:
+ name_key = (author.display_name or "").casefold().strip()
+ if not name_key:
+ continue
+ current_best = canonical.get(name_key)
+ if current_best is None or (
+ len(author_institution_names(author)) < len(author_institution_names(current_best))
+ ):
+ canonical[name_key] = author
+ return canonical
+
+
def merge_org_patents(
institution_id: str,
institution_name: str | None,
@@ -119,15 +126,25 @@ def merge_org_patents(
else:
entry.institution_match = True
+ canonical_authors = _canonical_authors_by_name(author_patents)
+
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
+ # Use case-normalized name as dedup key to collapse OpenAlex duplicate records
+ # (e.g. "Kenji TANAKA" and "Kenji Tanaka" are the same person)
+ author_dedup_key = author_name.casefold().strip() or author_id
+
+ # Attribute the match to the canonical (cleanest-profile) author for
+ # this name, not necessarily the one whose patents we're iterating —
+ # see _canonical_authors_by_name().
+ canonical = canonical_authors.get(author_dedup_key, author)
matched_author = MatchedAuthor(
- openalex_author_id=author_id,
- author_name=author_name,
+ openalex_author_id=normalize_author_id(canonical.id) or author_id,
+ author_name=canonical.display_name or author_name,
)
for patent in patents:
key = patent_dedup_key(patent)
@@ -135,10 +152,10 @@ def merge_org_patents(
if entry is None:
accumulated[key] = _AccumulatedPatent(
patent=patent,
- matched_authors={author_id: matched_author},
+ matched_authors={author_dedup_key: matched_author},
)
else:
- entry.matched_authors[author_id] = matched_author
+ entry.matched_authors.setdefault(author_dedup_key, matched_author)
org_patents: list[OrgPatentEntry] = []
short_institution_id = normalize_institution_id(institution_id)
@@ -201,76 +218,28 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
}
-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,
+ institution_name: str | None,
search_client: PatentSearchClient,
+ ipc_client: IpcSearchClient,
) -> 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:
+ if not author_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
+ author_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
+ author_name,
+ size=ORG_PATENT_SEARCH_SIZE,
)
),
)
@@ -278,9 +247,41 @@ async def _search_patents_by_author(
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)
+ patents = deduplicate_patents(patents)
+ patent_hit_count = len(patents)
+ name_matched = filter_patents_by_author_name(patents, author_name)
+ if not name_matched:
+ return []
+
+ from inse.persons import logic as person_logic
+ from inse.patents.authors.name_variants import parse_person_name
+
+ full_name_count = await person_logic.count_authors_by_display_name(author_name)
+ parsed_for_last = parse_person_name(author_name)
+ last_name_count: int | None = None
+ if parsed_for_last and not parsed_for_last.is_single_token:
+ last_name_count = await person_logic.count_authors_by_last_name(
+ parsed_for_last.last_name
+ )
+ is_ambiguous = is_ambiguous_name(
+ author_name,
+ patent_hit_count=patent_hit_count,
+ openalex_full_name_count=full_name_count,
+ openalex_last_name_count=last_name_count,
+ )
+
+ if is_ambiguous:
+ # Common names (Zhang, Li, Wang): only keep if the assignee matches the
+ # institution we're building this index for (not any institution from
+ # the author's whole affiliation history) or the person themselves.
+ inst_names = [institution_name] if institution_name else []
+ return [
+ p for p in name_matched
+ if patent_institution_match(p, inst_names)
+ or patent_personal_assignee_match(p, author_name)
+ ]
+ else:
+ return name_matched
async def build_org_patents_for_institution(
@@ -294,7 +295,7 @@ async def build_org_patents_for_institution(
institution_client = institutions_client or InstitutionsSearchClient()
short_id = normalize_institution_id(institution_id)
- institution = institution_client.get_institution_by_id(short_id)
+ institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
institution_response = await get_patents_by_institution_id(
@@ -305,7 +306,7 @@ async def build_org_patents_for_institution(
)
institution_patents = institution_response.patents
- authors = fetch_authors_for_institution(short_id)
+ authors = await fetch_authors_by_institution_name(institution_name)
logger.info(
"Building org_patents for %s (%s): %d authors, %d institution patents",
institution_name,
@@ -318,7 +319,9 @@ async def build_org_patents_for_institution(
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
async with semaphore:
- patents = await _search_patents_by_author(author, patent_client)
+ patents = await _search_patents_by_author(
+ author, institution_name, patent_client, ipc_search_client
+ )
return author, patents
author_results = await asyncio.gather(
@@ -394,7 +397,7 @@ async def get_org_patents_by_institution_id(
institution_client = institutions_client or InstitutionsSearchClient()
try:
- institution = institution_client.get_institution_by_id(short_id)
+ institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
except Exception:
institution_name = None
@@ -419,6 +422,15 @@ async def get_org_patents_by_institution_id(
detail="org_patents search request failed.",
) from exc
+ try:
+ await enrich_patents_openalex_topics(
+ patents, PatentsOpenAlexKeywordsClient()
+ )
+ except Exception:
+ logger.warning(
+ "Failed to enrich org_patents with OpenAlex topics", exc_info=True
+ )
+
return OrgPatentsResponse(
institution_id=short_id,
institution_name=institution_name,
diff --git a/service/src/main/inse/patents/org/service.py b/service/src/main/inse/patents/org/service.py
index df04d86b..2db362c2 100644
--- a/service/src/main/inse/patents/org/service.py
+++ b/service/src/main/inse/patents/org/service.py
@@ -1,7 +1,9 @@
from functools import lru_cache
from typing import Annotated
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
+from pydantic import BaseModel
+from starlette.status import HTTP_202_ACCEPTED
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.patents.org import logic
@@ -9,6 +11,8 @@ from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
+_rebuild_running: set[str] = set()
+
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
@@ -42,3 +46,44 @@ async def get_org_patents_by_institution(
source=source,
institutions_client=client,
)
+
+
+class RebuildResponse(BaseModel):
+ status: str
+ institution_id: str
+ message: str
+
+
+@router.post(
+ "/{id}/org-patents/rebuild",
+ operation_id="rebuildOrgPatents",
+ response_model=RebuildResponse,
+ status_code=HTTP_202_ACCEPTED,
+ summary="Trigger a background rebuild of the org_patents index for an institution.",
+)
+async def rebuild_org_patents(
+ id: str,
+ background_tasks: BackgroundTasks,
+) -> RebuildResponse:
+ short_id = logic.normalize_institution_id(id)
+
+ if short_id in _rebuild_running:
+ raise HTTPException(
+ status_code=409,
+ detail=f"A rebuild for institution {short_id} is already in progress.",
+ )
+
+ async def _run() -> None:
+ _rebuild_running.add(short_id)
+ try:
+ await logic.index_org_patents_for_institution(short_id)
+ finally:
+ _rebuild_running.discard(short_id)
+
+ background_tasks.add_task(_run)
+
+ return RebuildResponse(
+ status="accepted",
+ institution_id=short_id,
+ message=f"Rebuild started for institution {short_id}. Check server logs for progress.",
+ )
diff --git a/service/src/main/inse/patents/org/test_logic.py b/service/src/main/inse/patents/org/test_logic.py
index ca01887e..bb0313ef 100644
--- a/service/src/main/inse/patents/org/test_logic.py
+++ b/service/src/main/inse/patents/org/test_logic.py
@@ -1,5 +1,9 @@
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.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
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/__init__.py b/service/src/main/inse/patents/patents_openalex_keywords/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/client.py b/service/src/main/inse/patents/patents_openalex_keywords/client.py
new file mode 100644
index 00000000..d60c9b42
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/client.py
@@ -0,0 +1,216 @@
+"""HTTP client for the patents_openalex_keywords Elasticsearch index."""
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+import httpx
+
+from inse import config
+from inse.patents.common.elastic_search_client import MissingApiKeyError
+from inse.patents.patents_openalex_keywords.mapping import (
+ PATENTS_OPENALEX_KEYWORDS_INDEX,
+ PATENTS_OPENALEX_KEYWORDS_MAPPING,
+)
+
+logger = logging.getLogger(__name__)
+
+_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section")
+
+
+def candidate_doc_ids(symbol: str) -> list[str]:
+ """Builds the ordered (most to least specific) doc ids to try for a symbol."""
+ from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass
+
+ normalized = symbol.strip().upper().replace(" ", "")
+ candidates: list[tuple[str, str]] = [(level, normalized) for level in _LEVEL_LOOKUP_ORDER]
+ subclass = infer_subclass(normalized)
+ if subclass:
+ candidates.append(("subclass", subclass))
+ if len(normalized) >= 3:
+ candidates.append(("class", normalized[:3]))
+ if normalized:
+ candidates.append(("section", normalized[:1]))
+
+ seen: set[tuple[str, str]] = set()
+ ordered_ids: list[str] = []
+ for level, candidate in candidates:
+ key = (level, candidate)
+ if key in seen:
+ continue
+ seen.add(key)
+ ordered_ids.append(f"{level}:{candidate}")
+ return ordered_ids
+
+
+class PatentsOpenAlexKeywordsClient:
+ def __init__(
+ self,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ timeout: float = 10.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"/{PATENTS_OPENALEX_KEYWORDS_INDEX}",
+ headers=self._headers(),
+ )
+ if response.status_code == 404:
+ create_response = await client.put(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}",
+ headers=self._headers(),
+ json={"mappings": PATENTS_OPENALEX_KEYWORDS_MAPPING},
+ )
+ create_response.raise_for_status()
+ logger.info("Created index %s", PATENTS_OPENALEX_KEYWORDS_INDEX)
+ return
+
+ response.raise_for_status()
+ mapping_response = await client.put(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_mapping",
+ headers=self._headers(),
+ json=PATENTS_OPENALEX_KEYWORDS_MAPPING,
+ )
+ mapping_response.raise_for_status()
+
+ async def index_exists(self) -> bool:
+ async with httpx.AsyncClient(
+ base_url=self.base_url,
+ timeout=self.timeout,
+ transport=self.transport,
+ ) as client:
+ response = await client.head(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}",
+ headers=self._headers(),
+ )
+ if response.status_code == 404:
+ return False
+ response.raise_for_status()
+ return True
+
+ 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": PATENTS_OPENALEX_KEYWORDS_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(
+ f"Bulk indexing into {PATENTS_OPENALEX_KEYWORDS_INDEX} failed."
+ )
+
+ async def lookup(self, level: str, symbol: str) -> dict[str, Any] | None:
+ normalized = symbol.strip().upper().replace(" ", "")
+ doc_id = f"{level}:{normalized}"
+ async with httpx.AsyncClient(
+ base_url=self.base_url,
+ timeout=self.timeout,
+ transport=self.transport,
+ ) as client:
+ # Doc ids like "subgroup:C07K11/02" contain a "/", which breaks
+ # GET .../_doc/{id} through the gateway in front of this cluster
+ # (it mangles the path before ES sees it). A _search with an ids
+ # query sends the id in the request body instead, sidestepping
+ # the issue.
+ response = await client.post(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
+ headers=self._headers(),
+ json={"size": 1, "query": {"ids": {"values": [doc_id]}}},
+ )
+ if response.status_code == 404:
+ return None
+ response.raise_for_status()
+ hits = response.json().get("hits", {}).get("hits", [])
+ return hits[0].get("_source") if hits else None
+
+ async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict[str, Any]]:
+ """Resolves multiple doc ids in a single _search request (id -> _source)."""
+ unique_ids = list(dict.fromkeys(doc_ids))
+ if not unique_ids:
+ return {}
+
+ async with httpx.AsyncClient(
+ base_url=self.base_url,
+ timeout=self.timeout,
+ transport=self.transport,
+ ) as client:
+ response = await client.post(
+ f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
+ headers=self._headers(),
+ json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}},
+ )
+ if response.status_code == 404:
+ return {}
+ response.raise_for_status()
+ hits = response.json().get("hits", {}).get("hits", [])
+ return {hit["_id"]: hit.get("_source", {}) for hit in hits}
+
+ async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
+ ordered_ids = candidate_doc_ids(symbol)
+ if not ordered_ids:
+ return None
+
+ # One _search covering every candidate level instead of up to 5
+ # sequential requests per symbol — this matters a lot when enriching
+ # many patents at once (see get_all_patents), where a sequential
+ # per-symbol lookup chain added multiple seconds of latency.
+ docs_by_id = await self.lookup_ids(ordered_ids)
+ for doc_id in ordered_ids:
+ if doc_id in docs_by_id:
+ return docs_by_id[doc_id]
+ return None
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py
new file mode 100644
index 00000000..b89ad79e
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/ipc_entries.py
@@ -0,0 +1,207 @@
+"""Fetch unique IPC/CPC hierarchy symbols and labels from the ipc Elasticsearch index."""
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
+from inse.patents.ipc_search_client import IPC_INDEX
+
+LEVEL_FIELDS: tuple[tuple[str, str, str], ...] = (
+ ("section", "cpc_section_number", "cpc_section_name"),
+ ("class", "cpc_class_number", "cpc_class_name"),
+ ("group", "cpc_group_number", "cpc_group_name"),
+ ("subgroup", "cpc_subgroup_number", "cpc_subgroup_name"),
+)
+DEFAULT_BUILD_LEVELS = ("section", "class", "subclass", "group", "subgroup")
+
+
+def normalize_symbol(symbol: str | None) -> str:
+ if not symbol:
+ return ""
+ return symbol.strip().upper().replace(" ", "")
+
+
+def infer_subclass(symbol: str | None) -> str | None:
+ if not symbol:
+ return None
+ cleaned = normalize_symbol(symbol)
+ match = re.match(r"^([A-HY]\d{2}[A-Z])", cleaned)
+ return match.group(1) if match else None
+
+
+def infer_class(symbol: str | None) -> str | None:
+ if not symbol:
+ return None
+ cleaned = normalize_symbol(symbol)
+ match = re.match(r"^([A-HY]\d{2})", cleaned)
+ return match.group(1) if match else None
+
+
+def build_class_entries_from_subclasses(
+ subclass_entries: dict[str, str],
+ max_labels_per_class: int = 8,
+) -> dict[str, str]:
+ labels_by_class: dict[str, list[str]] = defaultdict(list)
+ seen_labels_by_class: dict[str, set[str]] = defaultdict(set)
+
+ for subclass_symbol, subclass_label in sorted(subclass_entries.items()):
+ class_symbol = infer_class(subclass_symbol)
+ if not class_symbol:
+ continue
+
+ label = " ".join(subclass_label.split())
+ label_key = label.casefold()
+ if label_key in seen_labels_by_class[class_symbol]:
+ continue
+
+ seen_labels_by_class[class_symbol].add(label_key)
+ labels_by_class[class_symbol].append(f"{subclass_symbol}: {label}")
+
+ class_entries: dict[str, str] = {}
+ for class_symbol, labels in labels_by_class.items():
+ selected_labels = labels[:max_labels_per_class]
+ class_entries[class_symbol] = (
+ f"IPC/CPC class {class_symbol}. Related subclasses: " + "; ".join(selected_labels)
+ )
+ return class_entries
+
+
+async def fetch_unique_ipc_entries(
+ levels: tuple[str, ...] = DEFAULT_BUILD_LEVELS,
+) -> dict[str, dict[str, str]]:
+ entries: dict[str, dict[str, str]] = defaultdict(dict)
+
+ async def _composite_with_label(
+ level: str,
+ number_field: str,
+ name_field: str,
+ page_size: int,
+ ) -> bool:
+ for field_name in (number_field, f"{number_field}.keyword"):
+ after_key: dict[str, str] | None = None
+ found_any = False
+ while True:
+ payload: dict[str, object] = {
+ "size": 0,
+ "aggs": {
+ "items": {
+ "composite": {
+ "size": page_size,
+ "sources": [
+ {"symbol": {"terms": {"field": field_name}}},
+ ],
+ },
+ "aggs": {
+ "sample": {
+ "top_hits": {"size": 1, "_source": [name_field]},
+ }
+ },
+ }
+ },
+ }
+ if after_key:
+ payload["aggs"]["items"]["composite"]["after"] = after_key
+ try:
+ data = await elasticsearch.search(
+ index=IPC_INDEX,
+ body=payload,
+ cluster=ESCluster.INSE,
+ )
+ except Exception:
+ found_any = False
+ break
+ items = data.get("aggregations", {}).get("items", {})
+ buckets = items.get("buckets", [])
+ if not buckets:
+ break
+ found_any = True
+ for bucket in buckets:
+ key = bucket.get("key", {})
+ symbol = key.get("symbol")
+ hits = bucket.get("sample", {}).get("hits", {}).get("hits", [])
+ if not symbol or not hits:
+ continue
+ name = hits[0].get("_source", {}).get(name_field)
+ if not name:
+ continue
+ normalized = normalize_symbol(str(symbol))
+ if level == "subclass":
+ if len(normalized) <= 3:
+ continue
+ normalized = infer_subclass(str(symbol)) or normalized
+ entries[level][normalized] = str(name).strip()
+ after_key = items.get("after_key")
+ if not after_key:
+ break
+ if found_any:
+ return True
+ return False
+
+ async def _terms_with_label(
+ level: str,
+ number_field: str,
+ name_field: str,
+ size: int,
+ ) -> None:
+ for field_name in (number_field, f"{number_field}.keyword"):
+ payload = {
+ "size": 0,
+ "aggs": {
+ "items": {
+ "terms": {"field": field_name, "size": size},
+ "aggs": {
+ "sample": {
+ "top_hits": {"size": 1, "_source": [name_field]},
+ }
+ },
+ }
+ },
+ }
+ try:
+ data = await elasticsearch.search(
+ index=IPC_INDEX,
+ body=payload,
+ cluster=ESCluster.INSE,
+ )
+ except Exception:
+ continue
+ buckets = data.get("aggregations", {}).get("items", {}).get("buckets", [])
+ if buckets:
+ break
+ else:
+ return
+ for bucket in buckets:
+ symbol = bucket.get("key")
+ hits = bucket.get("sample", {}).get("hits", {}).get("hits", [])
+ if not symbol or not hits:
+ continue
+ name = hits[0].get("_source", {}).get(name_field)
+ if not name:
+ continue
+ normalized = normalize_symbol(str(symbol))
+ if level == "class" and len(normalized) != 3:
+ continue
+ if level == "subclass":
+ if len(normalized) <= 3:
+ continue
+ normalized = infer_subclass(str(symbol)) or normalized
+ entries[level][normalized] = str(name).strip()
+
+ if "section" in levels:
+ await _terms_with_label("section", "cpc_section_number", "cpc_section_name", 30)
+ if "subclass" in levels or "class" in levels:
+ await _terms_with_label("subclass", "cpc_class_number", "cpc_class_name", 10000)
+ if "group" in levels:
+ if not await _composite_with_label("group", "cpc_group_number", "cpc_group_name", 1000):
+ await _terms_with_label("group", "cpc_group_number", "cpc_group_name", 20000)
+ if "subgroup" in levels:
+ if not await _composite_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 1000):
+ await _terms_with_label("subgroup", "cpc_subgroup_number", "cpc_subgroup_name", 20000)
+ if "class" in levels:
+ subclass_entries = entries.get("subclass", {})
+ entries["class"].update(build_class_entries_from_subclasses(subclass_entries))
+ if "subclass" not in levels:
+ entries.pop("subclass", None)
+ return entries
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/mapping.py b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py
new file mode 100644
index 00000000..8464dd30
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/mapping.py
@@ -0,0 +1,34 @@
+PATENTS_OPENALEX_KEYWORDS_INDEX = "patents_openalex_keywords"
+
+PATENTS_OPENALEX_KEYWORDS_MAPPING = {
+ "properties": {
+ "ipc_level": {"type": "keyword"},
+ "ipc_symbol": {"type": "keyword"},
+ "ipc_label": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
+ "topic_matches": {
+ "type": "nested",
+ "properties": {
+ "rank": {"type": "integer"},
+ "topic_id": {"type": "keyword"},
+ "topic_display_name": {"type": "keyword"},
+ "subfield": {"type": "keyword"},
+ "field": {"type": "keyword"},
+ "domain": {"type": "keyword"},
+ "match_score": {"type": "float"},
+ },
+ },
+ "keyword_matches": {
+ "type": "nested",
+ "properties": {
+ "rank": {"type": "integer"},
+ "keyword": {"type": "keyword"},
+ "topic_id": {"type": "keyword"},
+ "topic_display_name": {"type": "keyword"},
+ "match_score": {"type": "float"},
+ },
+ },
+ "match_method": {"type": "keyword"},
+ "model_name": {"type": "keyword"},
+ "built_at": {"type": "date"},
+ }
+}
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/matching.py b/service/src/main/inse/patents/patents_openalex_keywords/matching.py
new file mode 100644
index 00000000..2467d4d6
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/matching.py
@@ -0,0 +1,409 @@
+"""SentenceTransformer-based IPC/CPC → OpenAlex topic/keyword matching."""
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from sentence_transformers import SentenceTransformer
+
+from inse.config import settings
+from inse.integrations import elasticsearch
+from inse.model import ESCluster
+from inse.util import get_model
+
+logger = logging.getLogger(__name__)
+
+TOPIC_CACHE_FILENAME = "topic_hierarchy_cache.json"
+MATCH_METHOD = "sentence_transformer"
+TOPIC_VECTORS_INDEX = "topicvectors"
+
+
+@dataclass(frozen=True)
+class TopicCandidate:
+ topic_id: str
+ display_name: str
+ subfield: str | None = None
+ field: str | None = None
+ domain: str | None = None
+
+
+@dataclass(frozen=True)
+class KeywordCandidate:
+ keyword: str
+ topic_id: str
+ topic_display_name: str | None = None
+
+
+def _data_dir() -> Path:
+ return Path(__file__).resolve().parents[4] / "data"
+
+
+def load_topic_cache(cache_path: Path | None = None) -> list[TopicCandidate]:
+ path = cache_path or (_data_dir() / TOPIC_CACHE_FILENAME)
+ with path.open(encoding="utf-8") as handle:
+ raw = json.load(handle)
+ topics: list[TopicCandidate] = []
+ for display_name, info in raw.items():
+ topic_id = info.get("topic_id")
+ if not topic_id:
+ continue
+ topics.append(
+ TopicCandidate(
+ topic_id=str(topic_id),
+ display_name=display_name,
+ subfield=info.get("subfield"),
+ field=info.get("field"),
+ domain=info.get("domain"),
+ )
+ )
+ return topics
+
+
+def topic_embedding_text(topic: TopicCandidate) -> str:
+ parts = [topic.display_name]
+ for label in (topic.subfield, topic.field, topic.domain):
+ if label:
+ parts.append(label)
+ return ". ".join(parts)
+
+
+async def fetch_keyword_candidates() -> list[KeywordCandidate]:
+ candidates: list[KeywordCandidate] = []
+ seen: set[tuple[str, str]] = set()
+ async for hit in elasticsearch.scan(
+ index="openalex-topics",
+ query={"match_all": {}},
+ source=["id", "display_name", "keywords"],
+ cluster=ESCluster.NES,
+ ):
+ source = hit.get("_source", {})
+ topic_id = source.get("id")
+ topic_name = source.get("display_name")
+ if not topic_id:
+ continue
+ keywords = source.get("keywords") or []
+ if not isinstance(keywords, list):
+ keywords = [keywords] if keywords else []
+ for keyword in keywords:
+ if not keyword or not str(keyword).strip():
+ continue
+ key = (str(topic_id), str(keyword).strip().casefold())
+ if key in seen:
+ continue
+ seen.add(key)
+ candidates.append(
+ KeywordCandidate(
+ keyword=str(keyword).strip(),
+ topic_id=str(topic_id),
+ topic_display_name=topic_name,
+ )
+ )
+ return candidates
+
+
+def _normalize_rows(vectors: np.ndarray) -> np.ndarray:
+ norms = np.linalg.norm(vectors, axis=1, keepdims=True)
+ norms = np.where(norms == 0, 1.0, norms)
+ return vectors / norms
+
+
+def top_k_indices(query_vector: np.ndarray, corpus_matrix: np.ndarray, k: int) -> list[tuple[int, float]]:
+ if corpus_matrix.size == 0:
+ return []
+ scores = corpus_matrix @ query_vector
+ limit = min(k, len(scores))
+ if limit <= 0:
+ return []
+ top_idx = np.argpartition(-scores, limit - 1)[:limit]
+ top_idx = top_idx[np.argsort(-scores[top_idx])]
+ return [(int(idx), float(scores[idx])) for idx in top_idx]
+
+
+class EmbeddingMatcher:
+ def __init__(
+ self,
+ model: SentenceTransformer | None = None,
+ min_score: float = 0.5,
+ batch_size: int = 64,
+ ):
+ self.model = model or get_model()
+ self.min_score = min_score
+ self.batch_size = batch_size
+ self.model_name = settings.sentence_transformers_model_name
+ self._topic_candidates: list[TopicCandidate] = []
+ self._keyword_candidates: list[KeywordCandidate] = []
+ self._topic_matrix: np.ndarray | None = None
+ self._keyword_matrix: np.ndarray | None = None
+
+ def prepare_topics(self, topics: list[TopicCandidate]) -> None:
+ self._topic_candidates = topics
+ texts = [topic_embedding_text(topic) for topic in topics]
+ vectors = self.model.encode(
+ texts,
+ batch_size=self.batch_size,
+ show_progress_bar=True,
+ convert_to_numpy=True,
+ )
+ self._topic_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32))
+
+ def prepare_keywords(self, keywords: list[KeywordCandidate]) -> None:
+ self._keyword_candidates = keywords
+ if not keywords:
+ self._keyword_matrix = np.empty((0, 0), dtype=np.float32)
+ return
+ texts = [item.keyword for item in keywords]
+ vectors = self.model.encode(
+ texts,
+ batch_size=self.batch_size,
+ show_progress_bar=True,
+ convert_to_numpy=True,
+ )
+ self._keyword_matrix = _normalize_rows(np.asarray(vectors, dtype=np.float32))
+
+ def match_ipc_label(
+ self,
+ ipc_label: str,
+ top_k: int,
+ ) -> tuple[list[dict], list[dict]]:
+ query_vector = self.model.encode(
+ ipc_label,
+ convert_to_numpy=True,
+ )
+ query_vector = query_vector / max(float(np.linalg.norm(query_vector)), 1e-9)
+
+ topic_matches: list[dict] = []
+ if self._topic_matrix is not None and len(self._topic_candidates):
+ for rank, (idx, score) in enumerate(
+ top_k_indices(query_vector, self._topic_matrix, top_k),
+ start=1,
+ ):
+ if score < self.min_score:
+ continue
+ topic = self._topic_candidates[idx]
+ topic_matches.append(
+ {
+ "rank": rank,
+ "topic_id": topic.topic_id,
+ "topic_display_name": topic.display_name,
+ "subfield": topic.subfield,
+ "field": topic.field,
+ "domain": topic.domain,
+ "match_score": round(score, 4),
+ }
+ )
+
+ keyword_matches: list[dict] = []
+ if self._keyword_matrix is not None and len(self._keyword_candidates):
+ for rank, (idx, score) in enumerate(
+ top_k_indices(query_vector, self._keyword_matrix, top_k),
+ start=1,
+ ):
+ if score < self.min_score:
+ continue
+ keyword = self._keyword_candidates[idx]
+ keyword_matches.append(
+ {
+ "rank": rank,
+ "keyword": keyword.keyword,
+ "topic_id": keyword.topic_id,
+ "topic_display_name": keyword.topic_display_name,
+ "match_score": round(score, 4),
+ }
+ )
+
+ return topic_matches, keyword_matches
+
+
+def build_documents(
+ ipc_entries: dict[str, dict[str, str]],
+ matcher: EmbeddingMatcher,
+ levels: tuple[str, ...],
+ top_k: int,
+) -> list[tuple[str, dict]]:
+ built_at = datetime.now(timezone.utc).isoformat()
+ documents: list[tuple[str, dict]] = []
+ label_cache: dict[str, tuple[list[dict], list[dict]]] = {}
+
+ for level in levels:
+ for symbol, label in ipc_entries.get(level, {}).items():
+ cache_key = label.casefold()
+ if cache_key not in label_cache:
+ label_cache[cache_key] = matcher.match_ipc_label(label, top_k=top_k)
+ topic_matches, keyword_matches = label_cache[cache_key]
+ if not topic_matches and not keyword_matches:
+ continue
+ doc_id = f"{level}:{symbol}"
+ documents.append(
+ (
+ doc_id,
+ {
+ "ipc_level": level,
+ "ipc_symbol": symbol,
+ "ipc_label": label,
+ "topic_matches": topic_matches,
+ "keyword_matches": keyword_matches,
+ "match_method": MATCH_METHOD,
+ "model_name": matcher.model_name,
+ "built_at": built_at,
+ },
+ )
+ )
+ return documents
+
+
+def documents_to_json_mapping(documents: list[tuple[str, dict]]) -> dict[str, dict[str, dict]]:
+ mapping: dict[str, dict[str, dict]] = {
+ "section": {},
+ "class": {},
+ "subclass": {},
+ "group": {},
+ "subgroup": {},
+ }
+ for _doc_id, source in documents:
+ level = source["ipc_level"]
+ symbol = source["ipc_symbol"]
+ mapping.setdefault(level, {})[symbol] = source
+ return mapping
+
+
+class TopicVectorsMatcher:
+
+ def __init__(
+ self,
+ model: SentenceTransformer | None = None,
+ min_score: float = 0.5,
+ num_candidates: int = 200,
+ ):
+ self.model = model or get_model()
+ self.min_score = min_score
+ self.num_candidates = num_candidates
+ self.model_name = settings.sentence_transformers_model_name
+
+ async def _search_topic_vectors(
+ self,
+ *,
+ vector: list[float],
+ top_k: int,
+ ) -> list[dict[str, Any]]:
+ payload = {
+ "size": max(top_k * 4, top_k),
+ "_source": ["id", "display_name", "subfield", "field", "domain", "keywords"],
+ "knn": {
+ "field": "display_name_vector",
+ "query_vector": vector,
+ "k": max(top_k * 4, top_k),
+ "num_candidates": max(self.num_candidates, top_k * 8),
+ },
+ }
+ data = await elasticsearch.search(
+ index=TOPIC_VECTORS_INDEX,
+ body=payload,
+ cluster=ESCluster.NES,
+ )
+ return data.get("hits", {}).get("hits", []) or []
+
+ async def match_ipc_label(
+ self,
+ ipc_label: str,
+ top_k: int,
+ ) -> tuple[list[dict], list[dict]]:
+ vector = self.model.encode(ipc_label, convert_to_numpy=True)
+ query_vector = _normalize_rows(np.asarray([vector], dtype=np.float32))[0].tolist()
+ hits = await self._search_topic_vectors(vector=query_vector, top_k=top_k)
+
+ topic_matches: list[dict] = []
+ keyword_matches: list[dict] = []
+ seen_topics: set[str] = set()
+ seen_keywords: set[tuple[str, str]] = set()
+
+ for hit in hits:
+ source = hit.get("_source", {})
+ topic_id = str(source.get("id") or "")
+ topic_name = str(source.get("display_name") or "")
+ if not topic_id or not topic_name or topic_id in seen_topics:
+ continue
+ score = float(hit.get("_score") or 0.0)
+ if score < self.min_score:
+ continue
+
+ seen_topics.add(topic_id)
+ topic_matches.append(
+ {
+ "rank": len(topic_matches) + 1,
+ "topic_id": topic_id,
+ "topic_display_name": topic_name,
+ "subfield": source.get("subfield"),
+ "field": source.get("field"),
+ "domain": source.get("domain"),
+ "match_score": round(score, 4),
+ }
+ )
+
+ keywords = source.get("keywords") or []
+ if not isinstance(keywords, list):
+ keywords = [keywords] if keywords else []
+ for keyword in keywords:
+ normalized_keyword = str(keyword).strip()
+ if not normalized_keyword:
+ continue
+ key = (topic_id, normalized_keyword.casefold())
+ if key in seen_keywords:
+ continue
+ seen_keywords.add(key)
+ keyword_matches.append(
+ {
+ "rank": len(keyword_matches) + 1,
+ "keyword": normalized_keyword,
+ "topic_id": topic_id,
+ "topic_display_name": topic_name,
+ "match_score": round(score, 4),
+ }
+ )
+ break
+
+ if len(topic_matches) >= top_k and len(keyword_matches) >= top_k:
+ break
+
+ return topic_matches[:top_k], keyword_matches[:top_k]
+
+
+async def build_documents_from_topicvectors(
+ ipc_entries: dict[str, dict[str, str]],
+ matcher: TopicVectorsMatcher,
+ levels: tuple[str, ...],
+ top_k: int,
+) -> list[tuple[str, dict]]:
+ built_at = datetime.now(timezone.utc).isoformat()
+ documents: list[tuple[str, dict]] = []
+ label_cache: dict[str, tuple[list[dict], list[dict]]] = {}
+
+ for level in levels:
+ for symbol, label in ipc_entries.get(level, {}).items():
+ cache_key = label.casefold()
+ if cache_key not in label_cache:
+ label_cache[cache_key] = await matcher.match_ipc_label(label, top_k=top_k)
+ topic_matches, keyword_matches = label_cache[cache_key]
+ if not topic_matches and not keyword_matches:
+ continue
+ doc_id = f"{level}:{symbol}"
+ documents.append(
+ (
+ doc_id,
+ {
+ "ipc_level": level,
+ "ipc_symbol": symbol,
+ "ipc_label": label,
+ "topic_matches": topic_matches,
+ "keyword_matches": keyword_matches,
+ "match_method": "topicvectors_knn",
+ "model_name": matcher.model_name,
+ "built_at": built_at,
+ },
+ )
+ )
+ return documents
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py
new file mode 100644
index 00000000..bb33970b
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/resolver.py
@@ -0,0 +1,284 @@
+"""Runtime resolver for IPC/CPC → OpenAlex matches from patents_openalex_keywords."""
+from __future__ import annotations
+
+import json
+import logging
+import os
+from functools import lru_cache
+
+from inse.patents.authors.ipc_openalex_mapping import (
+ MappedOpenAlexTopic,
+ _enrich_mapped_topic,
+ load_ipc_openalex_mapping,
+ normalize_openalex_id,
+ resolve_mapped_topics_for_code,
+)
+from inse.patents.common import model
+from inse.patents.ipc_lookup import extract_ipc_symbol, parse_ipc_symbol
+from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
+from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass, normalize_symbol
+
+logger = logging.getLogger(__name__)
+
+KEYWORDS_MAPPING_FILENAME = "patents_openalex_keywords_mapping.json"
+_LEVEL_ORDER = {"subgroup": 5, "group": 4, "subclass": 3, "class": 2, "section": 1}
+
+
+def _data_dir() -> str:
+ for base in (
+ "/data",
+ os.path.normpath(
+ os.path.join(
+ os.path.dirname(__file__),
+ "..",
+ "..",
+ "..",
+ "..",
+ "data",
+ )
+ ),
+ ):
+ if os.path.isdir(base):
+ return base
+ return os.path.normpath(
+ os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "data")
+ )
+
+
+@lru_cache(maxsize=1)
+def load_patents_openalex_keywords_json() -> dict[str, dict[str, dict]]:
+ path = os.path.join(_data_dir(), KEYWORDS_MAPPING_FILENAME)
+ try:
+ with open(path, encoding="utf-8") as handle:
+ raw = json.load(handle)
+ except (OSError, json.JSONDecodeError):
+ return {}
+ if not isinstance(raw, dict):
+ return {}
+ return {
+ level: {
+ normalize_symbol(symbol): entry
+ for symbol, entry in (entries or {}).items()
+ if isinstance(entry, dict)
+ }
+ for level, entries in raw.items()
+ if isinstance(entries, dict)
+ }
+
+
+def clear_resolver_caches() -> None:
+ load_patents_openalex_keywords_json.cache_clear()
+
+
+def mapped_topics_from_index_doc(doc: dict) -> list[MappedOpenAlexTopic]:
+ seen: set[str] = set()
+ mapped: list[MappedOpenAlexTopic] = []
+ ipc_level = doc.get("ipc_level")
+ ipc_symbol = doc.get("ipc_symbol")
+
+ for match in doc.get("topic_matches") or []:
+ topic_id = match.get("topic_id")
+ if not topic_id:
+ continue
+ key = normalize_openalex_id(str(topic_id)) or str(topic_id)
+ if key in seen:
+ continue
+ seen.add(key)
+ mapped.append(
+ _enrich_mapped_topic(
+ MappedOpenAlexTopic(
+ topic_id=str(topic_id),
+ topic_display_name=match.get("topic_display_name"),
+ subfield_name=match.get("subfield"),
+ field_name=match.get("field"),
+ domain_name=match.get("domain"),
+ ipc_level=ipc_level,
+ ipc_symbol=ipc_symbol,
+ )
+ )
+ )
+
+ for match in doc.get("keyword_matches") or []:
+ topic_id = match.get("topic_id")
+ if not topic_id:
+ continue
+ key = normalize_openalex_id(str(topic_id)) or str(topic_id)
+ if key in seen:
+ continue
+ seen.add(key)
+ mapped.append(
+ _enrich_mapped_topic(
+ MappedOpenAlexTopic(
+ topic_id=str(topic_id),
+ topic_display_name=match.get("topic_display_name"),
+ ipc_level=ipc_level,
+ ipc_symbol=ipc_symbol,
+ )
+ )
+ )
+
+ return mapped
+
+
+def _json_lookup_symbol(
+ symbol: str,
+ table: dict[str, dict[str, dict]],
+) -> dict | None:
+ normalized = normalize_symbol(symbol)
+ best_doc: dict | None = None
+ best_rank = -1
+
+ subclass = infer_subclass(normalized)
+ candidates: list[tuple[str, str]] = [
+ ("subgroup", normalized),
+ ("group", normalized),
+ ]
+ if subclass:
+ candidates.append(("subclass", subclass))
+ if len(normalized) >= 3:
+ candidates.append(("class", normalized[:3]))
+ if normalized:
+ candidates.append(("section", normalized[:1]))
+
+ for level, candidate in candidates:
+ doc = table.get(level, {}).get(candidate)
+ if not doc:
+ continue
+ rank = _LEVEL_ORDER.get(level, 0)
+ if rank > best_rank:
+ best_rank = rank
+ best_doc = doc
+
+ if best_doc is not None:
+ return best_doc
+
+ for entries in table.values():
+ if normalized in entries:
+ return entries[normalized]
+ return None
+
+
+def _lookup_candidates(raw_code: str) -> list[str]:
+ symbol = extract_ipc_symbol(raw_code)
+ if not symbol:
+ return []
+
+ candidates: list[str] = []
+ normalized = normalize_symbol(symbol)
+ if normalized:
+ candidates.append(normalized)
+
+ keys = parse_ipc_symbol(symbol) or parse_ipc_symbol(normalized)
+ if keys is not None:
+ for value in (
+ keys.subgroup or keys.normalized,
+ keys.main_group,
+ keys.subclass,
+ keys.ipc_class,
+ keys.section,
+ ):
+ if value:
+ candidates.append(normalize_symbol(value))
+
+ subclass = infer_subclass(normalized)
+ if subclass:
+ candidates.append(subclass)
+
+ seen: set[str] = set()
+ ordered: list[str] = []
+ for candidate in candidates:
+ if candidate and candidate not in seen:
+ seen.add(candidate)
+ ordered.append(candidate)
+ return ordered
+
+
+class PatentOpenAlexMappingResolver:
+ """Resolve patent IPC/CPC codes via patents_openalex_keywords (ES → JSON → legacy)."""
+
+ def __init__(
+ self,
+ client: PatentsOpenAlexKeywordsClient | None = None,
+ *,
+ use_elasticsearch: bool = True,
+ ):
+ self.client = client or PatentsOpenAlexKeywordsClient()
+ self.use_elasticsearch = use_elasticsearch
+ self._doc_cache: dict[str, dict | None] = {}
+ self._legacy_mapping = load_ipc_openalex_mapping()
+ self._elasticsearch_checked = False
+ self._elasticsearch_enabled = False
+
+ async def resolve_topics_for_patents(
+ self,
+ patents: list[model.PatentEntry],
+ ) -> dict[str, list[MappedOpenAlexTopic]]:
+ from inse.patents.common.parsing import patent_map_key
+
+ result: dict[str, list[MappedOpenAlexTopic]] = {}
+ for patent in patents:
+ result[patent_map_key(patent)] = await self.resolve_mapped_topics_for_patent(
+ patent
+ )
+ return result
+
+ async def _elasticsearch_enabled_for_request(self) -> bool:
+ if not self.use_elasticsearch:
+ return False
+ if self._elasticsearch_checked:
+ return self._elasticsearch_enabled
+ self._elasticsearch_checked = True
+ try:
+ self._elasticsearch_enabled = await self.client.index_exists()
+ except Exception as exc:
+ logger.warning("patents_openalex_keywords index check failed: %s", exc)
+ self._elasticsearch_enabled = False
+ return self._elasticsearch_enabled
+
+ async def resolve_mapped_topics_for_patent(
+ self,
+ patent: model.PatentEntry,
+ ) -> list[MappedOpenAlexTopic]:
+ seen: set[str] = set()
+ resolved: list[MappedOpenAlexTopic] = []
+ for raw_code in (*patent.ipc, *patent.cpc):
+ for mapped in await self.resolve_mapped_topics_for_code(raw_code):
+ topic_key = normalize_openalex_id(mapped.topic_id) or mapped.topic_id
+ if topic_key in seen:
+ continue
+ seen.add(topic_key)
+ resolved.append(mapped)
+ return resolved
+
+ async def resolve_mapped_topics_for_code(self, raw_code: str) -> list[MappedOpenAlexTopic]:
+ for candidate in _lookup_candidates(raw_code):
+ doc = await self._lookup_document(candidate)
+ if doc is not None:
+ mapped = mapped_topics_from_index_doc(doc)
+ if mapped:
+ return mapped
+
+ return resolve_mapped_topics_for_code(raw_code, self._legacy_mapping)
+
+ async def _lookup_document(self, symbol: str) -> dict | None:
+ normalized = normalize_symbol(symbol)
+ if normalized in self._doc_cache:
+ return self._doc_cache[normalized]
+
+ doc: dict | None = None
+ if await self._elasticsearch_enabled_for_request():
+ try:
+ doc = await self.client.lookup_symbol(normalized)
+ except Exception as exc:
+ logger.warning(
+ "patents_openalex_keywords ES lookup failed for %s: %s",
+ normalized,
+ exc,
+ )
+ self._elasticsearch_enabled = False
+
+ if doc is None:
+ doc = _json_lookup_symbol(normalized, load_patents_openalex_keywords_json())
+
+ self._doc_cache[normalized] = doc
+ return doc
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_client.py b/service/src/main/inse/patents/patents_openalex_keywords/test_client.py
new file mode 100644
index 00000000..ec74f4c2
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/test_client.py
@@ -0,0 +1,118 @@
+import json
+
+import httpx
+import pytest
+
+from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
+from inse.patents.patents_openalex_keywords.mapping import PATENTS_OPENALEX_KEYWORDS_INDEX
+
+
+@pytest.fixture
+def anyio_backend():
+ return "asyncio"
+
+
+@pytest.mark.anyio
+async def test_lookup_uses_search_with_ids_query_not_doc_get():
+ """Doc ids like "subgroup:C07K11/02" contain a "/", which breaks a GET to
+ .../_doc/{id} through the gateway in front of this cluster. lookup() must
+ use _search with an ids query (id goes in the body, not the URL) instead.
+ """
+ captured: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.append(request)
+ return httpx.Response(
+ 200,
+ json={
+ "hits": {
+ "hits": [
+ {"_id": "subgroup:C07K11/02", "_source": {"ipc_label": "cyclic"}}
+ ]
+ }
+ },
+ )
+
+ client = PatentsOpenAlexKeywordsClient(
+ api_key="test-key",
+ transport=httpx.MockTransport(handler),
+ )
+ doc = await client.lookup("subgroup", "C07K 11/02")
+
+ assert len(captured) == 1
+ request = captured[0]
+ assert request.method == "POST"
+ assert request.url.path.endswith(f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search")
+ body = json.loads(request.content)
+ assert body["query"] == {"ids": {"values": ["subgroup:C07K11/02"]}}
+ assert doc == {"ipc_label": "cyclic"}
+
+
+@pytest.mark.anyio
+async def test_lookup_returns_none_when_no_hits():
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"hits": {"hits": []}})
+
+ client = PatentsOpenAlexKeywordsClient(
+ api_key="test-key",
+ transport=httpx.MockTransport(handler),
+ )
+ doc = await client.lookup("subgroup", "Z99Z99/99")
+
+ assert doc is None
+
+
+@pytest.mark.anyio
+async def test_lookup_symbol_resolves_via_a_single_batched_request():
+ """lookup_symbol must send exactly one _search covering every candidate
+ level (subgroup/group/subclass/class/section), not one request per level
+ — sequential per-level requests previously added multiple seconds of
+ latency when enriching many patents at once."""
+ captured: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured.append(request)
+ body = json.loads(request.content)
+ values = body["query"]["ids"]["values"]
+ if "group:C07K11/02" in values:
+ return httpx.Response(
+ 200,
+ json={
+ "hits": {
+ "hits": [
+ {"_id": "group:C07K11/02", "_source": {"ipc_label": "match"}}
+ ]
+ }
+ },
+ )
+ return httpx.Response(200, json={"hits": {"hits": []}})
+
+ client = PatentsOpenAlexKeywordsClient(
+ api_key="test-key",
+ transport=httpx.MockTransport(handler),
+ )
+ doc = await client.lookup_symbol("C07K 11/02")
+
+ assert len(captured) == 1
+ assert doc == {"ipc_label": "match"}
+
+
+@pytest.mark.anyio
+async def test_lookup_symbol_prefers_more_specific_level_when_multiple_match():
+ def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ values = body["query"]["ids"]["values"]
+ hits = []
+ if "subgroup:C07K11/02" in values:
+ hits.append({"_id": "subgroup:C07K11/02", "_source": {"ipc_label": "subgroup-match"}})
+ if "class:C07" in values:
+ hits.append({"_id": "class:C07", "_source": {"ipc_label": "class-match"}})
+ return httpx.Response(200, json={"hits": {"hits": hits}})
+
+ client = PatentsOpenAlexKeywordsClient(
+ api_key="test-key",
+ transport=httpx.MockTransport(handler),
+ )
+ doc = await client.lookup_symbol("C07K 11/02")
+
+ assert doc == {"ipc_label": "subgroup-match"}
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py
new file mode 100644
index 00000000..66417433
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/test_matching.py
@@ -0,0 +1,88 @@
+"""Tests for patents_openalex_keywords embedding matcher."""
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from inse.patents.patents_openalex_keywords.matching import (
+ EmbeddingMatcher,
+ TopicCandidate,
+ top_k_indices,
+ topic_embedding_text,
+)
+
+
+def test_topic_embedding_text_joins_hierarchy() -> None:
+ topic = TopicCandidate(
+ topic_id="T1",
+ display_name="Cancer Immunotherapy",
+ subfield="Oncology",
+ field="Medicine",
+ domain="Health",
+ )
+ assert topic_embedding_text(topic) == "Cancer Immunotherapy. Oncology. Medicine. Health"
+
+
+def test_top_k_indices_returns_highest_scores() -> None:
+ corpus = np.array(
+ [
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.9, 0.1, 0.0],
+ ],
+ dtype=np.float32,
+ )
+ corpus = corpus / np.linalg.norm(corpus, axis=1, keepdims=True)
+ query = np.array([1.0, 0.0, 0.0], dtype=np.float32)
+
+ matches = top_k_indices(query, corpus, k=2)
+ assert len(matches) == 2
+ assert matches[0][0] in {0, 2}
+ assert matches[0][1] >= matches[1][1]
+
+
+class _FakeModel:
+ def encode(self, sentences, **kwargs):
+ del kwargs
+ if isinstance(sentences, str):
+ sentences = [sentences]
+ vectors = []
+ for text in sentences:
+ lowered = text.casefold()
+ if "surgery" in lowered:
+ vectors.append(np.array([1.0, 0.0], dtype=np.float32))
+ elif "immunotherapy" in lowered:
+ vectors.append(np.array([0.95, 0.05], dtype=np.float32))
+ else:
+ vectors.append(np.array([0.0, 1.0], dtype=np.float32))
+ arr = np.vstack(vectors)
+ if len(sentences) == 1 and isinstance(sentences[0], str):
+ return arr[0]
+ return arr
+
+
+def test_embedding_matcher_returns_topic_and_keyword_matches() -> None:
+ matcher = EmbeddingMatcher(model=_FakeModel(), min_score=0.5)
+ matcher.prepare_topics(
+ [
+ TopicCandidate(topic_id="T1", display_name="Cancer Immunotherapy"),
+ TopicCandidate(topic_id="T2", display_name="Unrelated Topic"),
+ ]
+ )
+ from inse.patents.patents_openalex_keywords.matching import KeywordCandidate
+
+ matcher.prepare_keywords(
+ [
+ KeywordCandidate(keyword="surgery", topic_id="T9", topic_display_name="Surgery"),
+ KeywordCandidate(keyword="finance", topic_id="T8", topic_display_name="Finance"),
+ ]
+ )
+
+ topic_matches, keyword_matches = matcher.match_ipc_label(
+ "medical immunotherapy devices",
+ top_k=2,
+ )
+ assert topic_matches
+ assert topic_matches[0]["topic_id"] == "T1"
+ assert keyword_matches
+ assert keyword_matches[0]["keyword"] == "surgery"
diff --git a/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py
new file mode 100644
index 00000000..f46378de
--- /dev/null
+++ b/service/src/main/inse/patents/patents_openalex_keywords/test_resolver.py
@@ -0,0 +1,102 @@
+"""Tests for patents_openalex_keywords runtime resolver."""
+from __future__ import annotations
+
+import asyncio
+
+from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
+from inse.patents.authors.test_ipc_openalex_mapping import _author_with_topic
+from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping
+from inse.patents.common import model
+from inse.patents.patents_openalex_keywords.resolver import (
+ PatentOpenAlexMappingResolver,
+ mapped_topics_from_index_doc,
+)
+
+
+def test_mapped_topics_from_index_doc_includes_topics_and_keywords() -> None:
+ doc = {
+ "ipc_level": "subclass",
+ "ipc_symbol": "H01L",
+ "topic_matches": [
+ {
+ "rank": 1,
+ "topic_id": "https://openalex.org/T99999",
+ "topic_display_name": "Semiconductor materials and devices",
+ "subfield": "Electrical Engineering",
+ }
+ ],
+ "keyword_matches": [
+ {
+ "rank": 1,
+ "keyword": "silicon",
+ "topic_id": "https://openalex.org/T88888",
+ "topic_display_name": "Silicon Processing",
+ }
+ ],
+ }
+ mapped = mapped_topics_from_index_doc(doc)
+ assert len(mapped) == 2
+ assert {item.topic_id for item in mapped} == {
+ "https://openalex.org/T99999",
+ "https://openalex.org/T88888",
+ }
+
+
+class _FakeKeywordsClient:
+ def __init__(self, docs: dict[str, dict]):
+ self.docs = docs
+
+ async def index_exists(self) -> bool:
+ return True
+
+ async def lookup_symbol(self, symbol: str):
+ return self.docs.get(symbol)
+
+
+def test_resolver_uses_index_doc_before_legacy_fallback() -> None:
+ resolver = PatentOpenAlexMappingResolver(
+ client=_FakeKeywordsClient(
+ {
+ "H01L": {
+ "ipc_level": "subclass",
+ "ipc_symbol": "H01L",
+ "topic_matches": [
+ {
+ "topic_id": "https://openalex.org/T99999",
+ "topic_display_name": "Semiconductor materials and devices",
+ }
+ ],
+ "keyword_matches": [],
+ }
+ }
+ ),
+ use_elasticsearch=True,
+ )
+ mapped = asyncio.run(resolver.resolve_mapped_topics_for_code("H01L 21/02"))
+ assert mapped
+ assert mapped[0].topic_id.endswith("T99999")
+
+
+def test_filter_uses_patent_topic_map_from_resolver() -> None:
+ author = _author_with_topic(
+ "https://openalex.org/T99999",
+ "Semiconductor materials and devices",
+ )
+ patent = model.PatentEntry(patent_id="EP1", source="EPO", ipc=["H01L 21/02"])
+ from inse.patents.common.parsing import patent_map_key
+
+ topic_map = {
+ patent_map_key(patent): [
+ MappedOpenAlexTopic(
+ topic_id="https://openalex.org/T99999",
+ topic_display_name="Semiconductor materials and devices",
+ )
+ ]
+ }
+ filtered = filter_patents_by_ipc_topic_mapping(
+ [patent],
+ author,
+ is_ambiguous=True,
+ patent_topic_map=topic_map,
+ )
+ assert len(filtered) == 1
diff --git a/service/src/main/inse/patents/service.py b/service/src/main/inse/patents/service.py
index 39b30968..3cd2f6d8 100644
--- a/service/src/main/inse/patents/service.py
+++ b/service/src/main/inse/patents/service.py
@@ -1,70 +1,10 @@
"""Aggregates patent API routers."""
from fastapi import APIRouter
-from . import logic
-from . import model
-from typing import Annotated, Optional
-from fastapi import Path
-from fastapi import Query
-
-router = APIRouter(prefix="/api/inse-service/authors", 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(
- "/{author_id}/patents",
- operation_id="getPatentsByAuthor",
- summary="Get patents matched to an author by name.",
-)
-async def get_patents_by_author(author_id: str) -> model.PatentsByAuthorResponse:
- return await logic.get_patents_by_author_id(author_id)
-
-
-@patents_router.get(
- "/patents/{identifier}",
- operation_id="getPatentByIdOrTitle",
- summary="Returns one publication by OpenAlex ID or DOI.",
-)
-async def get_patent_by_identifier(
- identifier: Annotated[str, Path(description="")],
- prefix: Annotated[
- Optional[str], Query(description="Application Prefix (EP or US)")
- ] = "",
- title: Annotated[
- Optional[str],
- Query(
- 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:
- return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date)
-
-
-@patents_router.get(
- "/patents",
- operation_id="getAllPatents",
- 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",
-) -> model.AllPatentsResponse:
- return await logic.get_all_patents(
- page=page,
- size=size,
- search=search,
- source=source,
- sort_by=sort_by,
- sort_direction=sort_direction,
- )
+router = author_patents_router
+patents_router = all_patents_router
+institution_patents_router = institution_patents_router
diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py
index 6aea4c7c..d9225534 100644
--- a/service/src/main/inse/patents/test_elastic_search_client.py
+++ b/service/src/main/inse/patents/test_elastic_search_client.py
@@ -1,5 +1,7 @@
+import json
+
+import httpx
import pytest
-from unittest.mock import patch, MagicMock
from inse.model import ESIndex
from inse.patents.elastic_search_client import (
DEFAULT_SEARCH_SIZE,
@@ -12,17 +14,23 @@ def anyio_backend():
return "asyncio"
+def test_patent_search_client_exposes_inventor_queries():
+ client = PatentSearchClient(api_key="test-key")
+ assert hasattr(client, "epo_query_by_inventor")
+ assert hasattr(client, "uspto_query_by_inventor")
+ assert hasattr(client, "epo_query_by_application_number")
+
+
def test_epo_query_uses_nested_search_and_name_variants():
client = PatentSearchClient(api_key="test-key")
- payload = client.epo_query_by_inventor("Müller", "Christian")
+ payload = client.epo_query_by_inventor("Pedro José Marrón")
assert payload["size"] == DEFAULT_SEARCH_SIZE
assert payload["sort"][0] == {"_score": {"order": "desc"}}
nested = payload["query"]["nested"]
assert nested["path"] == "inventors_name_nested"
- must = nested["query"]["bool"]["must"]
- assert len(must) == 2
- assert "should" in must[0]["bool"]
+ inventor_query = nested["query"]
+ assert "should" in inventor_query["bool"]
def test_uspto_index_is_3_0():
@@ -30,17 +38,51 @@ def test_uspto_index_is_3_0():
assert ESIndex.EPO_INDEX == "epo_index_1.0"
+def test_epo_query_by_application_number_uses_term_filter():
+ client = PatentSearchClient(api_key="test-key")
+ payload = client.epo_query_by_application_number("12743403.3")
+
+ assert payload["query"] == {"term": {"application_number": "12743403.3"}}
+ assert "application_number" in payload["_source"]
+
+
+def test_epo_query_by_applicant_uses_applicants_name_field():
+ client = PatentSearchClient(api_key="test-key")
+ payload = client.epo_query_by_applicant(
+ ["University of Duisburg-Essen", "Universität Duisburg-Essen"]
+ )
+
+ assert payload["size"] == DEFAULT_SEARCH_SIZE
+ assert "applicants_name" in str(payload["query"])
+ assert payload["query"]["bool"]["minimum_should_match"] == 1
+
+
+def test_uspto_query_by_assignee_uses_assignees_orgs_field():
+ client = PatentSearchClient(api_key="test-key")
+ payload = client.uspto_query_by_assignee(["Harvard University"])
+
+ assert "assignees_orgs" in str(payload["query"])
+
+
@pytest.mark.anyio
async def test_search_epo_posts_to_correct_index():
captured: list[dict] = []
- def fake_search(index: str, body: dict, cluster=None):
- captured.append({"index": index, "body": body})
- return {"hits": {"hits": []}}
+ def handler(request: httpx.Request) -> httpx.Response:
+ path_parts = request.url.path.strip("/").split("/")
+ captured.append(
+ {
+ "index": path_parts[-2],
+ "body": json.loads(request.content) if request.content else {},
+ }
+ )
+ return httpx.Response(200, json={"hits": {"hits": []}})
- with patch("inse.integrations.elasticsearch.search", side_effect=fake_search):
- client = PatentSearchClient(api_key="test-key")
- await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
+ client = PatentSearchClient(
+ api_key="test-key",
+ transport=httpx.MockTransport(handler),
+ )
+ await client.search_epo(client.epo_query_by_inventor("Christian Weber"))
assert len(captured) == 1
- assert captured[0]["index"] == ESIndex.EPO_INDEX
\ No newline at end of file
+ assert captured[0]["index"] == ESIndex.EPO_INDEX
diff --git a/service/src/main/inse/patents/test_logic.py b/service/src/main/inse/patents/test_logic.py
index 5e60288d..9e5f8744 100644
--- a/service/src/main/inse/patents/test_logic.py
+++ b/service/src/main/inse/patents/test_logic.py
@@ -1,5 +1,8 @@
from inse.patents import model
-from inse.patents.common.parsing import deduplicate_patents
+from inse.patents.common.parsing import (
+ deduplicate_patents,
+ expand_matched_epo_application_families,
+)
from inse.patents.institutions.logic import filter_patents_by_institution
@@ -93,6 +96,71 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types
assert [patent.application_type for patent in result] == ["utility", "reissue"]
+def test_expand_matched_epo_application_families_adds_grant_stage() -> None:
+ application = _epo_patent(
+ publication_date="20150506",
+ kind="A1",
+ )
+ application.application_number = "12743403.3"
+ application.inventors = ["MARRÓN, Pedro José"]
+
+ grant = _epo_patent(
+ publication_date="20180411",
+ kind="B1",
+ )
+ grant.application_number = "12743403.3"
+ grant.inventors = ["HANDTE, Marcus"]
+
+ class _FakeSearchClient:
+ async def search_epo(self, payload):
+ return {
+ "hits": {
+ "hits": [
+ {
+ "_id": "2867692",
+ "_source": {
+ "doc_number": "2867692",
+ "kind": "A1",
+ "date_publication": "20150506",
+ "date_publication_year": 2015,
+ "application_number": "12743403.3",
+ "title_en": "METHOD FOR GENERATING AND USING A MAP",
+ "inventors_name": ["MARRÓN, Pedro José"],
+ "applicants_name": ["Universität Duisburg-Essen"],
+ "ipc": ["G01S 5/02"],
+ },
+ },
+ {
+ "_id": "2867692",
+ "_source": {
+ "doc_number": "2867692",
+ "kind": "B1",
+ "date_publication": "20180411",
+ "date_publication_year": 2018,
+ "application_number": "12743403.3",
+ "title_en": "METHOD FOR GENERATING AND USING A MAP",
+ "inventors_name": ["HANDTE, Marcus"],
+ "applicants_name": ["Universität Duisburg-Essen"],
+ "ipc": ["G01S 5/02"],
+ },
+ },
+ ]
+ }
+ }
+
+ def epo_query_by_application_number(self, application_number: str):
+ return {"query": {"term": {"application_number": application_number}}}
+
+ import asyncio
+
+ expanded = asyncio.run(
+ expand_matched_epo_application_families([application], _FakeSearchClient())
+ )
+
+ assert len(expanded) == 2
+ assert {patent.kind for patent in expanded} == {"A1", "B1"}
+
+
def test_assignee_matches_institution_name_accepts_alternative_names() -> None:
from inse.patents.name_matching import assignee_matches_institution_name
diff --git a/service/src/main/inse/patents/test_name_matching.py b/service/src/main/inse/patents/test_name_matching.py
index cc93465d..828a1082 100644
--- a/service/src/main/inse/patents/test_name_matching.py
+++ b/service/src/main/inse/patents/test_name_matching.py
@@ -2,7 +2,10 @@ import pytest
from inse.patents.name_matching import (
first_name_match_kind,
+ first_name_match_kind_for_person,
+ inventor_search_phrases,
name_matches,
+ name_matches_person,
name_token_variants,
normalize_name_part,
search_name_variants,
@@ -52,7 +55,7 @@ def test_hyphenated_first_name() -> None:
[
("Christian Weber", "Christian", "Weber", True),
("Weber, Christian", "Christian", "Weber", True),
- ("Marc Christian Weber", "Christian", "Weber", False),
+ ("Marc Christian Weber", "Christian", "Weber", True),
("Müller, Hans", "Hans", "Müller", True),
("Mueller, Hans", "Hans", "Müller", True),
("Hans Mueller", "Hans", "Müller", True),
@@ -114,7 +117,64 @@ def test_name_matches_initials(inventor: str, first: str, last: str, expected: b
def test_first_name_match_kind() -> None:
assert first_name_match_kind("Christian Weber", "Christian", "Weber") == "full"
assert first_name_match_kind("C. Weber", "Christian", "Weber") == "initial"
- assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "none"
+ assert first_name_match_kind("Marc Christian Weber", "Christian", "Weber") == "full"
+
+
+@pytest.mark.parametrize(
+ ("inventor", "display_name", "expected"),
+ [
+ ("Marrón, Pedro José", "Pedro José Marrón", True),
+ ("Marron, Pedro Jose, Dr.", "Pedro José Marrón", True),
+ ("P. J. Marrón", "Pedro José Marrón", True),
+ ("Schmidt, Anna Maria", "Anna Maria Schmidt", True),
+ ("Maria Schmidt", "Anna Maria Schmidt", True),
+ ("García López, Juan Carlos", "Juan Carlos García López", True),
+ ("López, Juan", "Juan Carlos García López", True),
+ ("Mohamed Ali Hassan", "Mohamed Ali Hassan", True),
+ ("Ali Hassan", "Mohamed Ali Hassan", True),
+ ("Karem C Weber", "Christian Weber", False),
+ ("Schmitz, Oliver", "Oliver J. Schmitz", False),
+ ("Schmitz, Oliver J.", "Oliver J. Schmitz", True),
+ ("Schmitz, O. J.", "Oliver J. Schmitz", True),
+ ],
+)
+def test_name_matches_person_multi_part(
+ inventor: str,
+ display_name: str,
+ expected: bool,
+) -> None:
+ assert name_matches_person(inventor, display_name) is expected
+
+
+def test_inventor_search_phrases_include_comma_and_initials() -> None:
+ phrases = inventor_search_phrases("Pedro José Marrón")
+ folded = {phrase.casefold() for phrase in phrases}
+ assert any("marron" in phrase and "pedro" in phrase for phrase in folded)
+ assert any("," in phrase for phrase in phrases)
+
+
+def test_first_name_match_kind_multi_part() -> None:
+ assert (
+ first_name_match_kind_for_person("Marrón, Pedro José", "Pedro José Marrón")
+ == "full"
+ )
+ assert (
+ first_name_match_kind_for_person("P. J. Marrón", "Pedro José Marrón")
+ == "initial"
+ )
+
+
+def test_middle_initial_requires_corroboration() -> None:
+ assert not name_matches_person("Schmitz, Oliver", "Oliver J. Schmitz")
+ assert name_matches_person("Schmitz, Oliver J.", "Oliver J. Schmitz")
+ assert (
+ first_name_match_kind_for_person("Schmitz, Oliver", "Oliver J. Schmitz")
+ == "none"
+ )
+ assert (
+ first_name_match_kind_for_person("Schmitz, Oliver J.", "Oliver J. Schmitz")
+ == "full"
+ )
def test_search_name_variants_includes_initial() -> None:
diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py
index baeded67..7bf9c9a7 100644
--- a/service/src/main/inse/persons/logic.py
+++ b/service/src/main/inse/persons/logic.py
@@ -4,39 +4,40 @@
Business logic for persons / authors.
"""
+import hashlib
import json
import logging
import time
from datetime import datetime
-from typing import Optional, Callable, Any, List
-import hashlib
+from typing import List, Optional
+
from inse.exceptions import (
- NotFoundException,
+ BadRequestException,
ElasticsearchException,
ElasticsearchNotFoundException,
- ElasticsearchConnectionException,
- BadRequestException,
+ NotFoundException,
)
-
+from inse.integrations import elasticsearch
from inse.model import ESIndex
-from .. import config
-from .. import util
-from ..integrations import llm
from inse.models.openalex.author import Author
from inse.models.openalex.authors_list_response import AuthorsListResponse
-from inse.integrations import elasticsearch
from inse.models.openalex.meta import Meta
-from inse.persons.query_builder import build_authors_search_rescored
from inse.persons.model import (
+ CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
- CareerMetrics,
)
+from inse.persons.query_builder import build_authors_search_rescored
+from inse.works.logic import enrich_topic_descriptions
+
+from .. import config, util
+from ..integrations import llm
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
+
async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
query = {
"_source": ["display_name"],
@@ -153,8 +154,41 @@ async def search_persons(
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
-async def _fetch_author_display_name(author_id: str) -> Optional[str]:
+async def _count_authors(query: dict) -> int:
+ """Return the total number of authors matching a query (no documents fetched)."""
+ data = await elasticsearch.search(
+ index=ESIndex.OPENALEX_AUTHORS,
+ query=query,
+ size=0,
+ track_total_hits=True,
+ )
+ total = data.get("hits", {}).get("total", {})
+ if isinstance(total, dict):
+ return int(total.get("value", 0))
+ return int(total or 0)
+
+async def count_authors_by_display_name(display_name: str) -> int:
+ """Count authors in the local OpenAlex index whose full name collides.
+
+ Used purely as an internal ambiguity signal: a value >= 2 means at least one
+ other author shares the exact name.
+ """
+ if not display_name or not display_name.strip():
+ return 0
+ query = {"match_phrase": {"display_name": display_name.strip()}}
+ return await _count_authors(query)
+
+
+async def count_authors_by_last_name(last_name: str) -> int:
+ """Count authors in the local OpenAlex index sharing a family name."""
+ if not last_name or not last_name.strip():
+ return 0
+ query = {"match": {"display_name": last_name.strip()}}
+ return await _count_authors(query)
+
+
+async def _fetch_author_display_name(author_id: str) -> Optional[str]:
query = {
"query_string": {
"default_field": "_id",
@@ -177,7 +211,6 @@ async def _fetch_author_display_name(author_id: str) -> Optional[str]:
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
-
WORK_SOURCE_FIELDS = [
"title",
"display_name",
@@ -363,7 +396,6 @@ async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
def _build_papers(works: list) -> list:
-
papers = []
for work in works:
name = work.get("title") or work.get("display_name")
@@ -381,7 +413,6 @@ def _build_papers(works: list) -> list:
async def get_data_for_bio(author_id: str) -> Optional[dict]:
-
display_name = await _fetch_author_display_name(author_id)
if display_name is None:
return None
@@ -397,7 +428,9 @@ async def get_data_for_bio(author_id: str) -> Optional[dict]:
return author_data
-async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
+async def generate_person_bio(
+ author_id: str, include: Optional[set[str]] = None
+) -> str:
start_time = time.time()
author_data = await get_data_for_bio(author_id)
if author_data is None:
@@ -583,26 +616,73 @@ async def search_persons_by_institution(
page_offset: Optional[int] = 0,
include: Optional[str] = None,
) -> AuthorsListResponse:
-
if not institution_name:
raise BadRequestException("institution_name must be provided")
- search_query = {
+ target_year = datetime.now().year - 1
+
+ recent_affiliation_query = {
"nested": {
- "path": "last_known_institutions",
+ "path": "affiliations",
"query": {
"bool": {
- "must": [
+ "filter": [
{
"match_phrase": {
- "last_known_institutions.display_name": institution_name
+ "affiliations.institution.display_name": institution_name
}
- }
+ },
+ {"range": {"affiliations.years": {"gte": target_year}}},
]
}
},
}
}
+ matching_last_known_institution_query = {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "match_phrase": {
+ "last_known_institutions.display_name": institution_name
+ }
+ },
+ }
+ }
+ missing_last_known_institutions_query = {
+ "bool": {
+ "must_not": [
+ {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {"exists": {"field": "last_known_institutions.id"}},
+ }
+ }
+ ]
+ }
+ }
+ search_query = {
+ "bool": {
+ "should": [
+ {
+ "bool": {
+ "filter": [
+ matching_last_known_institution_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ {
+ "bool": {
+ "filter": [
+ missing_last_known_institutions_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
+ }
try:
response = await elasticsearch.search(
index="openalex-authors",
@@ -728,6 +808,10 @@ async def advanced_search_persons(
)
results.append(custom_author)
+ await enrich_topic_descriptions(
+ [topic for author in results for topic in author.topics or []]
+ )
+
return CustomAuthorsListResponse(
results=results, meta=Meta(count=total_count, page=page, per_page=page_size)
)
diff --git a/service/src/main/inse/persons/query_builder.py b/service/src/main/inse/persons/query_builder.py
index 7431558d..d6b4119d 100644
--- a/service/src/main/inse/persons/query_builder.py
+++ b/service/src/main/inse/persons/query_builder.py
@@ -1,232 +1,4 @@
-# -*- coding: utf-8 -*-
-from typing import List, Optional, Set, Any
-import json
-# def build_authors_search(
-# using: Any = None,
-# index: Optional[str] = None,
-# query: Optional[str] = None,
-# institution_name: Optional[str] = None,
-# sort_by: Optional[str] = None,
-# sort_order: Optional[str] = None,
-# topics: Optional[List[str]] = None,
-# page: int = 1,
-# page_size: int = 10,
-# include: Optional[Set[str]] = None,
-# strict: Optional[bool] = False,
-# track_total_hits: Optional[bool] = False,
-# filter_mode: Optional[str] = "from",
-# filter_year: Optional[int] = None,
-# ) -> dict:
-# """
-# Builds an Elasticsearch search request query body for authors as a dictionary.
-# """
-# # 1. Build Query Clauses
-# query_clause = None
-# if query:
-# query_clause = {
-# "bool": {
-# "should": [
-# {
-# "match_phrase": {
-# "display_name": {
-# "query": query,
-# "boost": 5
-# }
-# }
-# },
-# {
-# "match_phrase_prefix": {
-# "display_name": {
-# "query": query,
-# "boost": 3
-# }
-# }
-# },
-# {
-# "match": {
-# "display_name": {
-# "query": query,
-# "fuzziness": 1
-# }
-# }
-# }
-# ],
-# "minimum_should_match": 1
-# }
-# }
-
-# # 2. Build Filters
-# filter_clauses = []
-
-# # Filter against false entries (nested ((Works > 2 AND Year > 2020) OR has last_known_institution))
-# filter_clauses.append({
-# "bool": {
-# "should": [
-# {
-# "bool": {
-# "filter": [
-# {
-# "range": { "works_count": { "gt": 2 } }
-# },
-# {
-# "nested": {
-# "path": "counts_by_year",
-# "query": {
-# "range": { "counts_by_year.year": { "gt": 2020 } } # hardcoded for now
-# }
-# }
-# }
-# ]
-# }
-# },
-# {
-# "nested": {
-# "path": "last_known_institutions",
-# "query": {
-# "exists": {
-# "field": "last_known_institutions.id"
-# }
-# }
-# }
-# }
-
-# ],
-# "minimum_should_match": 1
-# }
-# })
-# # Institution filter with optional year-based filtering
-# if institution_name:
-# if filter_year is not None:
-# target_year = filter_year
-# mode = filter_mode or "from"
-# else:
-# from datetime import datetime
-# current_year = datetime.now().year
-# target_year = current_year - 1
-# mode = "from"
-
-# range_query = {"gte": target_year}
-# if mode == "in":
-# range_query["lte"] = target_year
-
-# if strict:
-# filter_clauses.append({
-# "nested": {
-# "path": "affiliations",
-# "query": {
-# "bool": {
-# "filter": [
-# {
-# "match_phrase": {
-# "affiliations.institution.display_name": institution_name
-# }
-# },
-# {
-# "range": {
-# "affiliations.years": range_query
-# }
-# }
-# ]
-# }
-# }
-# }
-# })
-# else:
-# filter_clauses.append({
-# "bool": {
-# "filter": [
-# {
-# "nested": {
-# "path": "last_known_institutions",
-# "query": {
-# "match_phrase": {
-# "last_known_institutions.display_name": institution_name
-# }
-# }
-# }
-# },
-# {
-# "nested": {
-# "path": "affiliations",
-# "query": {
-# "bool": {
-# "filter": [
-# {
-# "match_phrase": {
-# "affiliations.institution.display_name": institution_name
-# }
-# },
-# {
-# "range": {
-# "affiliations.years": range_query
-# }
-# }
-# ]
-# }
-# }
-# }
-# }
-# ]
-# }
-# })
-
-# if topics:
-# for t in topics:
-# if t:
-# filter_clauses.append({
-# "nested": {
-# "path": "topics",
-# "query": {
-# "match_phrase": {
-# "topics.display_name": t
-# }
-# }
-# }
-# })
-
-# # Combine query and filters
-# body = {}
-# if query_clause:
-# if filter_clauses:
-# body["query"] = {
-# "bool": {
-# "must": [query_clause],
-# "filter": filter_clauses
-# }
-# }
-# else:
-# body["query"] = query_clause
-# else:
-# if filter_clauses:
-# body["query"] = {
-# "bool": {
-# "filter": filter_clauses
-# }
-# }
-# else:
-# body["query"] = {
-# "match_all": {}
-# }
-
-# # 3. Source Filtering
-# if include:
-# body["_source"] = list(include)
-# else:
-# body["_source"] = True
-
-# # 4. Pagination
-# es_size = page_size
-# es_from = (page - 1) * page_size
-# body["from"] = es_from
-# body["size"] = es_size
-# body["track_total_hits"] = track_total_hits
-
-# # 5. Sorting
-# if sort_by and sort_order:
-# body["sort"] = [
-# {sort_by: {"order": sort_order}},
-# ]
-# return body
+from typing import Any, List, Optional, Set
def build_authors_search_rescored(
@@ -244,11 +16,11 @@ def build_authors_search_rescored(
track_total_hits: Optional[bool] = False,
filter_mode: Optional[str] = "from",
filter_year: Optional[int] = None,
- name_quality_boost = True,
- h_index_boost = True,
- citations_boost =True,
- works_boost = True,
- _2yr_mean_citedness_boost = True,
+ name_quality_boost=True,
+ h_index_boost=True,
+ citations_boost=True,
+ works_boost=True,
+ _2yr_mean_citedness_boost=True,
) -> dict:
"""
Builds an Elasticsearch search request query body for authors as a dictionary.
@@ -259,73 +31,56 @@ def build_authors_search_rescored(
query_clause = {
"bool": {
"should": [
- {
- "match_phrase": {
- "display_name": {
- "query": query,
- "boost": 5
- }
- }
- },
+ {"match_phrase": {"display_name": {"query": query, "boost": 5}}},
{
"match_phrase_prefix": {
- "display_name": {
- "query": query,
- "boost": 3
- }
+ "display_name": {"query": query, "boost": 3}
}
},
- {
- "match": {
- "display_name": {
- "query": query
- }
- }
- }
+ {"match": {"display_name": {"query": query}}},
],
- "minimum_should_match": 1
+ "minimum_should_match": 1,
}
}
# 2. Build Filters
filter_clauses = []
-
- # Filter against false entries (nested ((Works > 2 AND Year > 2020) OR has last_known_institution))
- filter_clauses.append({
- "bool": {
- "should": [
- {
- "bool": {
- "filter": [
- {
- "range": { "works_count": { "gt": 2 } }
- },
- {
- "nested": {
- "path": "counts_by_year",
- "query": {
- "range": { "counts_by_year.year": { "gt": 2020 } } # hardcoded for now
- }
- }
- }
- ]
- }
- },
- {
- "nested": {
- "path": "last_known_institutions",
- "query": {
- "exists": {
- "field": "last_known_institutions.id"
- }
- }
- }
- }
- ],
- "minimum_should_match": 1
+ # Filter against false entries (nested ((Works > 2 AND Year > 2020) OR has last_known_institution))
+ filter_clauses.append(
+ {
+ "bool": {
+ "should": [
+ {
+ "bool": {
+ "filter": [
+ {"range": {"works_count": {"gt": 2}}},
+ {
+ "nested": {
+ "path": "counts_by_year",
+ "query": {
+ "range": {
+ "counts_by_year.year": {"gt": 2020}
+ } # hardcoded for now
+ },
+ }
+ },
+ ]
+ }
+ },
+ {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "exists": {"field": "last_known_institutions.id"}
+ },
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
}
- })
+ )
# Institution filter with optional year-based filtering
if institution_name:
if filter_year is not None:
@@ -333,6 +88,7 @@ def build_authors_search_rescored(
mode = filter_mode or "from"
else:
from datetime import datetime
+
current_year = datetime.now().year
target_year = current_year - 1
mode = "from"
@@ -342,7 +98,27 @@ def build_authors_search_rescored(
range_query["lte"] = target_year
if strict:
- filter_clauses.append({
+ filter_clauses.append(
+ {
+ "nested": {
+ "path": "affiliations",
+ "query": {
+ "bool": {
+ "filter": [
+ {
+ "match_phrase": {
+ "affiliations.institution.display_name": institution_name
+ }
+ },
+ {"range": {"affiliations.years": range_query}},
+ ]
+ }
+ },
+ }
+ }
+ )
+ else:
+ recent_affiliation_query = {
"nested": {
"path": "affiliations",
"query": {
@@ -353,71 +129,75 @@ def build_authors_search_rescored(
"affiliations.institution.display_name": institution_name
}
},
- {
- "range": {
- "affiliations.years": range_query
- }
- }
+ {"range": {"affiliations.years": range_query}},
]
}
- }
+ },
}
- })
- else:
- filter_clauses.append({
- "bool": {
- "filter": [
- {
- "nested": {
- "path": "last_known_institutions",
- "query": {
- "match_phrase": {
- "last_known_institutions.display_name": institution_name
- }
- }
+ }
+ matching_last_known_institution_query = {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "match_phrase": {
+ "last_known_institutions.display_name": institution_name
}
},
- {
- "nested": {
- "path": "affiliations",
- "query": {
- "bool": {
- "filter": [
- {
- "match_phrase": {
- "affiliations.institution.display_name": institution_name
- }
- },
- {
- "range": {
- "affiliations.years": range_query
- }
- }
- ]
- }
+ }
+ }
+ missing_last_known_institutions_query = {
+ "bool": {
+ "must_not": [
+ {
+ "nested": {
+ "path": "last_known_institutions",
+ "query": {
+ "exists": {"field": "last_known_institutions.id"}
+ },
}
}
- }
- ]
+ ]
+ }
}
- })
-
+ filter_clauses.append(
+ {
+ "bool": {
+ "should": [
+ {
+ "bool": {
+ "filter": [
+ matching_last_known_institution_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ {
+ "bool": {
+ "filter": [
+ missing_last_known_institutions_query,
+ recent_affiliation_query,
+ ]
+ }
+ },
+ ],
+ "minimum_should_match": 1,
+ }
+ }
+ )
+
if topics:
for t in topics:
if t:
- filter_clauses.append({
- "nested": {
- "path": "topics",
- "query": {
- "match_phrase": {
- "topics.display_name": t
- }
+ filter_clauses.append(
+ {
+ "nested": {
+ "path": "topics",
+ "query": {"match_phrase": {"topics.display_name": t}},
}
}
- })
+ )
functions = []
if not sort_by:
-
# if (name_quality_boost): # Name quality boost, boost names which are not "Value Value"
# name_boost_query={
# "script_score": {
@@ -428,68 +208,61 @@ def build_authors_search_rescored(
# }
# }
# functions.append(name_boost_query)
- if (h_index_boost): # h_index boost
- h_index_boost_query={
- "script_score": {
- "script": {
- "lang": "painless",
- "source": "if (!doc.containsKey('summary_stats.h_index') || doc['summary_stats.h_index'].empty) return 1.0;double h = doc['summary_stats.h_index'].value;return 1.0 + Math.log1p(h) / 5.0;"
- }
+ if h_index_boost: # h_index boost
+ h_index_boost_query = {
+ "script_score": {
+ "script": {
+ "lang": "painless",
+ "source": "if (!doc.containsKey('summary_stats.h_index') || doc['summary_stats.h_index'].empty) return 1.0;double h = doc['summary_stats.h_index'].value;return 1.0 + Math.log1p(h) / 5.0;",
}
+ }
}
functions.append(h_index_boost_query)
- if (citations_boost): # cited_by_count boost
+ if citations_boost: # cited_by_count boost
cited_by_count_boost_query = {
"script_score": {
"script": {
"lang": "painless",
- "source": "if (!doc.containsKey('cited_by_count') || doc['cited_by_count'].empty) return 1.0;double citations = doc['cited_by_count'].value;return 1.0 + Math.log1p(citations) / 10.0;"
+ "source": "if (!doc.containsKey('cited_by_count') || doc['cited_by_count'].empty) return 1.0;double citations = doc['cited_by_count'].value;return 1.0 + Math.log1p(citations) / 10.0;",
}
}
}
functions.append(cited_by_count_boost_query)
- if (works_boost): # works_count boost
+ if works_boost: # works_count boost
works_count_boost_query = {
"script_score": {
"script": {
"lang": "painless",
- "source": "if (!doc.containsKey('works_count') || doc['works_count'].empty) return 1.0;double works = doc['works_count'].value;return 1.0 + Math.log1p(works) / 8.0;"
+ "source": "if (!doc.containsKey('works_count') || doc['works_count'].empty) return 1.0;double works = doc['works_count'].value;return 1.0 + Math.log1p(works) / 8.0;",
}
}
}
functions.append(works_count_boost_query)
# Combine query and filters
body = {}
-
+
if functions:
inner_query = None
if query_clause:
if filter_clauses:
inner_query = {
- "bool": {
- "must": [query_clause],
- "filter": filter_clauses
- }
+ "bool": {"must": [query_clause], "filter": filter_clauses}
}
else:
inner_query = query_clause
# if query not null then multiply with name matching
- body["query"] = {
+ body["query"] = {
"function_score": {
"query": inner_query,
"functions": functions,
"score_mode": "multiply",
- "boost_mode": "multiply"
+ "boost_mode": "multiply",
}
}
else:
if filter_clauses:
- inner_query = {
- "bool": {
- "filter": filter_clauses
- }
- }
+ inner_query = {"bool": {"filter": filter_clauses}}
else:
inner_query = {"match_all": {}}
# if the query is null, replace the scoring completely
@@ -498,27 +271,20 @@ def build_authors_search_rescored(
"query": inner_query,
"functions": functions,
"score_mode": "multiply",
- "boost_mode": "replace"
+ "boost_mode": "replace",
}
}
else:
if query_clause:
if filter_clauses:
body["query"] = {
- "bool": {
- "must": [query_clause],
- "filter": filter_clauses
- }
+ "bool": {"must": [query_clause], "filter": filter_clauses}
}
else:
body["query"] = query_clause
else:
if filter_clauses:
- body["query"] = {
- "bool": {
- "filter": filter_clauses
- }
- }
+ body["query"] = {"bool": {"filter": filter_clauses}}
else:
body["query"] = {"match_all": {}}
@@ -541,4 +307,3 @@ def build_authors_search_rescored(
{sort_by: {"order": sort_order}},
]
return body
-
diff --git a/service/src/main/inse/tags.py b/service/src/main/inse/tags.py
index ceb507b5..51a6eec6 100644
--- a/service/src/main/inse/tags.py
+++ b/service/src/main/inse/tags.py
@@ -12,4 +12,5 @@ class Tags(StrEnum):
AUTH = "Auth"
ACCOUNT = "Account"
ORGANIZATION = "Organization"
+ UNIVERSITY_RANKINGS = "University Rankings"
DASHBOARD = "Dashboard"
diff --git a/service/src/main/inse/topics/logic.py b/service/src/main/inse/topics/logic.py
index eced478e..cec2bfa6 100644
--- a/service/src/main/inse/topics/logic.py
+++ b/service/src/main/inse/topics/logic.py
@@ -4,13 +4,12 @@
Business logic for OpenAlex topics.
"""
-import asyncio
import logging
from copy import deepcopy
from typing import Any
-
-import httpx
+import asyncio
from pydantic import ValidationError
+
from inse.exceptions import (
UpstreamAPIException,
BadRequestException,
@@ -23,8 +22,8 @@ from inse.models.openalex.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner,
)
from inse.models.openalex.topics_list_response import TopicsListResponse
-from inse.model import ESCluster
-from .search_client import OpenAlexTopicsClient
+from inse.model import ESCluster, ESIndex
+from .search_client import TopicsSearchClient
logger = logging.getLogger(__name__)
@@ -40,15 +39,15 @@ async def list_topics(
cursor: str | None = None,
sample: int | None = None,
select: str | None = None,
- client: OpenAlexTopicsClient | None = None,
+ client: TopicsSearchClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise BadRequestException("sample cannot be combined with sort or page.")
- openalex_client = client or OpenAlexTopicsClient()
+ topics_client = client or TopicsSearchClient()
try:
- data = await openalex_client.list_topics(
+ data = await topics_client.list_topics(
search=search,
filter=filter,
sort=sort,
@@ -59,25 +58,24 @@ async def list_topics(
sample=sample,
select=select,
)
- except httpx.HTTPStatusError as exc:
- status_code = exc.response.status_code
- detail = "OpenAlex topics request failed."
- try:
- 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.")
+ except ValueError as exc:
+ raise BadRequestException(str(exc)) from exc
+ except ElasticsearchException as exc:
+ logger.exception("OpenAlex topics Elasticsearch request failed.")
raise UpstreamAPIException(
- message="OpenAlex topics request failed.",
+ message="OpenAlex topics Elasticsearch request failed.",
status_code=502,
) from exc
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()
except ValidationError as exc:
logger.exception("OpenAlex topics response could not be parsed.")
@@ -94,7 +92,7 @@ async def autocomplete_topics(
field_id: str | None = None,
subfield_id: str | None = None,
limit: int = 10,
- client: OpenAlexTopicsClient | None = None,
+ client: TopicsSearchClient | None = None,
) -> AutocompleteResponse:
filters = []
if domain_id:
@@ -153,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]:
normalized = deepcopy(data)
@@ -264,7 +355,6 @@ def _datetime_str_or_none(value: Any) -> str | None:
return f"{text}T00:00:00Z"
return text
-
# Configuration for vector search similarity thresholds and boosts
SIMILARITY_THRESHOLD = (
0.8 # intfloat/multilingual-e5-base uses cosine similarity between 0.7 - 1
@@ -388,7 +478,7 @@ async def vector_search_topics(
try:
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:
logger.exception("Elasticsearch vector search failed with unexpected error.")
@@ -458,7 +548,7 @@ async def vector_search_topics_batch(
)
tasks.append(
elasticsearch.search(
- index="topicvectors", body=body, cluster=ESCluster.NES
+ index=ESIndex.OPENALEX_TOPIC_VECTORS, body=body, cluster=ESCluster.NES
)
)
diff --git a/service/src/main/inse/topics/search_client.py b/service/src/main/inse/topics/search_client.py
index 7c70afa0..b6ec024a 100644
--- a/service/src/main/inse/topics/search_client.py
+++ b/service/src/main/inse/topics/search_client.py
@@ -1,33 +1,200 @@
#!/usr/bin/env python
# -*- 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
-import httpx
+from inse.model import ESCluster, ESIndex
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__(
self,
- base_url: str | None = None,
- api_key: str | None = None,
- timeout: float | None = None,
- transport: httpx.AsyncBaseTransport | None = None,
+ *,
+ index: ESIndex | str | None = None,
+ cluster: ESCluster = ESCluster.NES,
):
- self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
- self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
- self.timeout = (
- timeout
- if timeout is not None
- else config.settings.openalex_api_timeout_seconds
- )
- self.transport = transport
+ self.index = index or self._default_index()
+ self.cluster = cluster
- 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,
*,
search: str | None = None,
@@ -40,28 +207,118 @@ class OpenAlexTopicsClient:
sample: int | None = None,
select: str | None = None,
) -> 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:
- params["search"] = search
- if filter:
- params["filter"] = filter
- if sort:
- params["sort"] = sort
- if group_by:
- params["group_by"] = group_by
- 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
+ must_clauses.append(
+ {
+ "multi_match": {
+ "query": search,
+ "fields": self.DEFAULT_SEARCH_FIELDS,
+ "type": "best_fields",
+ "operator": "and",
+ }
+ }
+ )
- 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(
self,
@@ -76,24 +333,17 @@ class OpenAlexTopicsClient:
sample: int | None = None,
select: str | None = None,
) -> dict[str, Any]:
- async with httpx.AsyncClient(
- base_url=self.base_url,
- timeout=self.timeout,
- transport=self.transport,
- ) as client:
- response = await client.get(
- "/topics",
- params=self.list_topics_params(
- search=search,
- filter=filter,
- sort=sort,
- group_by=group_by,
- per_page=per_page,
- page=page,
- cursor=cursor,
- sample=sample,
- select=select,
- ),
- )
- response.raise_for_status()
- return response.json()
+ """
+ Backwards-compatible alias for the old OpenAlex client method name.
+ """
+ return await self.search_topics(
+ search=search,
+ filter=filter,
+ sort=sort,
+ group_by=group_by,
+ per_page=per_page,
+ page=page,
+ cursor=cursor,
+ sample=sample,
+ select=select,
+ )
\ No newline at end of file
diff --git a/service/src/main/inse/topics/test_logic.py b/service/src/main/inse/topics/test_logic.py
index 5e88a461..60b8b1f1 100644
--- a/service/src/main/inse/topics/test_logic.py
+++ b/service/src/main/inse/topics/test_logic.py
@@ -1,9 +1,7 @@
-import httpx
import pytest
-from inse.exceptions import BadRequestException
+from inse.exceptions import BadRequestException
from inse.topics import logic
-from inse.topics.search_client import OpenAlexTopicsClient
@pytest.fixture
@@ -11,108 +9,144 @@ def anyio_backend():
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
-async def test_list_topics_maps_openalex_response_to_model():
- def handler(_: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "meta": {"count": 1, "page": 1, "per_page": 25},
- "results": [
+async def test_list_topics_maps_elasticsearch_response_to_model():
+ client = FakeTopicsSearchClient(
+ {
+ "took": 12,
+ "hits": {
+ "total": {"value": 1, "relation": "eq"},
+ "hits": [
{
- "id": "https://openalex.org/T12419",
- "display_name": "Machine learning",
- "description": "Methods that learn from data.",
- "keywords": ["machine learning", "classification"],
- "subfield": {
- "id": "https://openalex.org/subfields/1702",
- "display_name": "Artificial Intelligence",
+ "_id": "https://openalex.org/T12419",
+ "_source": {
+ "id": "https://openalex.org/T12419",
+ "display_name": "Machine learning",
+ "description": "Methods that learn from data.",
+ "keywords": ["machine learning", "classification"],
+ "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,
}
],
},
- )
-
- client = OpenAlexTopicsClient(
- api_key="test-key",
- transport=httpx.MockTransport(handler),
+ "aggregations": {
+ "group_by": {
+ "buckets": [
+ {
+ "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.db_response_time_ms == 12
+
topic = result.results[0]
assert topic.display_name == "Machine learning"
assert topic.var_field.display_name == "Computer Science"
assert topic.subfield.display_name == "Artificial Intelligence"
assert topic.domain.display_name == "Physical Sciences"
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].count == 1
@pytest.mark.anyio
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")
@pytest.mark.anyio
async def test_list_topics_accepts_practical_openalex_type_variants():
- def handler(_: httpx.Request) -> httpx.Response:
- return httpx.Response(
- 200,
- json={
- "meta": {"count": "1", "page": "1", "per_page": "25"},
- "results": [
+ client = FakeTopicsSearchClient(
+ {
+ "took": "10",
+ "hits": {
+ "total": {"value": "1", "relation": "eq"},
+ "hits": [
{
- "id": 123,
- "display_name": 456,
- "description": True,
- "keywords": ["topic", 123],
- "subfield": {"id": 1, "display_name": 2},
- "field": {"id": 3, "display_name": 4},
- "domain": {"id": 5, "display_name": 6},
- "works_count": "12.0",
- "cited_by_count": False,
- "ids": {"openalex": 123, "wikipedia": 456},
- "created_date": "2023-12-25T10:11:12Z",
- "updated_date": "2023-12-25",
+ "_id": "123",
+ "_source": {
+ "id": 123,
+ "display_name": 456,
+ "description": True,
+ "keywords": ["topic", 123],
+ "subfield": {"id": 1, "display_name": 2},
+ "field": {"id": 3, "display_name": 4},
+ "domain": {"id": 5, "display_name": 6},
+ "works_count": "12.0",
+ "cited_by_count": False,
+ "ids": {"openalex": 123, "wikipedia": 456},
+ "created_date": "2023-12-25T10:11:12Z",
+ "updated_date": "2023-12-25",
+ },
}
],
- "group_by": [{"key": True, "count": "1"}],
},
- )
-
- client = OpenAlexTopicsClient(
- api_key="test-key",
- transport=httpx.MockTransport(handler),
+ "aggregations": {
+ "group_by": {
+ "buckets": [
+ {
+ "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]
assert topic.id == "123"
@@ -131,42 +165,33 @@ async def test_list_topics_accepts_practical_openalex_type_variants():
@pytest.mark.anyio
async def test_autocomplete_topics_returns_frontend_options():
- def handler(request: httpx.Request) -> httpx.Response:
- assert request.url.params["search"] == "machine learning"
- assert request.url.params["filter"] == (
- "domain.id:https://openalex.org/domains/4,"
- "field.id:https://openalex.org/fields/17,"
- "subfield.id:https://openalex.org/subfields/1702"
- )
- 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": [
+ client = FakeTopicsSearchClient(
+ {
+ "took": 12,
+ "hits": {
+ "total": {"value": 1, "relation": "eq"},
+ "hits": [
{
- "id": "https://openalex.org/T12419",
- "display_name": "Machine learning",
- "description": "Methods that learn from data.",
- "field": {"display_name": "Computer Science"},
- "subfield": {"display_name": "Artificial Intelligence"},
- "domain": {"display_name": "Physical Sciences"},
- "works_count": 123,
- "cited_by_count": 456,
- "ids": {"openalex": "https://openalex.org/T12419"},
+ "_id": "https://openalex.org/T12419",
+ "_source": {
+ "id": "https://openalex.org/T12419",
+ "display_name": "Machine learning",
+ "description": "Methods that learn from data.",
+ "field": {"display_name": "Computer Science"},
+ "subfield": {
+ "display_name": "Artificial Intelligence",
+ },
+ "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(
@@ -178,9 +203,24 @@ async def test_autocomplete_topics_returns_frontend_options():
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.db_response_time_ms == 12
assert len(result.results) == 1
+
option = result.results[0]
assert option.id == "https://openalex.org/T12419"
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.cited_by_count == 456
assert option.entity_type == "topic"
- assert option.external_id == "https://openalex.org/T12419"
+ assert option.external_id == "https://openalex.org/T12419"
\ No newline at end of file
diff --git a/service/src/main/inse/topics/test_search_client.py b/service/src/main/inse/topics/test_search_client.py
index 69c16a82..74de07f7 100644
--- a/service/src/main/inse/topics/test_search_client.py
+++ b/service/src/main/inse/topics/test_search_client.py
@@ -1,7 +1,7 @@
-import httpx
import pytest
-from inse.topics.search_client import OpenAlexTopicsClient
+from inse.model import ESCluster, ESIndex
+from inse.topics.search_client import TopicsSearchClient
@pytest.fixture
@@ -9,10 +9,10 @@ def anyio_backend():
return "asyncio"
-def test_list_topics_params_include_openalex_query_parameters():
- client = OpenAlexTopicsClient(api_key="test-key")
+def test_build_search_body_includes_openalex_query_parameters():
+ client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
- params = client.list_topics_params(
+ body = client.build_search_body(
search="machine learning",
filter="domain.id:4,works_count:>1000",
sort="works_count:desc",
@@ -22,54 +22,128 @@ def test_list_topics_params_include_openalex_query_parameters():
select="id,display_name",
)
- assert params == {
- "search": "machine learning",
- "filter": "domain.id:4,works_count:>1000",
- "sort": "works_count:desc",
- "group_by": "domain.id",
- "per_page": 10,
- "page": 2,
- "select": "id,display_name",
- "api_key": "test-key",
+ assert body["query"] == {
+ "bool": {
+ "must": [
+ {
+ "multi_match": {
+ "query": "machine learning",
+ "fields": client.DEFAULT_SEARCH_FIELDS,
+ "type": "best_fields",
+ "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():
- client = OpenAlexTopicsClient(api_key="test-key")
+def test_build_search_body_prefers_cursor_over_page():
+ 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"] == "*"
- assert "page" not in params
+ body = client.build_search_body(
+ 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
-async def test_list_topics_calls_openalex_topics_endpoint():
- def handler(request: httpx.Request) -> httpx.Response:
- assert request.method == "GET"
- assert request.url.path == "/topics"
- assert request.url.params["search"] == "machine learning"
- assert request.url.params["api_key"] == "test-key"
- return httpx.Response(
- 200,
- json={
- "meta": {"count": 1, "page": 1, "per_page": 25},
- "results": [
+async def test_list_topics_calls_elasticsearch_search_wrapper(monkeypatch):
+ captured = {}
+
+ async def fake_elasticsearch_search(*, index, body, cluster):
+ captured["index"] = index
+ captured["body"] = body
+ captured["cluster"] = cluster
+
+ return {
+ "took": 3,
+ "hits": {
+ "total": {"value": 1, "relation": "eq"},
+ "hits": [
{
- "id": "https://openalex.org/T12419",
- "display_name": "Machine learning",
+ "_id": "https://openalex.org/T12419",
+ "_source": {
+ "id": "https://openalex.org/T12419",
+ "display_name": "Machine learning",
+ },
+ "sort": [1000, "https://openalex.org/T12419"],
}
],
},
- )
+ }
- client = OpenAlexTopicsClient(
- base_url="https://api.openalex.org",
- api_key="test-key",
- transport=httpx.MockTransport(handler),
+ monkeypatch.setattr(
+ "inse.topics.search_client.elasticsearch_search",
+ fake_elasticsearch_search,
)
+ client = TopicsSearchClient(index=ESIndex.OPENALEX_TOPICS, cluster=ESCluster.NES)
+
result = await client.list_topics(search="machine learning")
- assert result["meta"]["count"] == 1
- assert result["results"][0]["display_name"] == "Machine learning"
+ assert captured["index"] == ESIndex.OPENALEX_TOPICS
+ 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
\ No newline at end of file
diff --git a/service/src/main/inse/university_ranking/logic.py b/service/src/main/inse/university_ranking/logic.py
index 10d926ff..2f368665 100644
--- a/service/src/main/inse/university_ranking/logic.py
+++ b/service/src/main/inse/university_ranking/logic.py
@@ -1,65 +1,228 @@
import logging
+import datetime
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.models.openalex.topic import Topic
logger = logging.getLogger(__name__)
-START_YEAR = 2015
-END_YEAR = 2026
+START_YEAR = 2000
+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.
"""
+ 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 = {
"bool": {
- "must": [
- {
- "match_phrase": {
- "topics.display_name": topic
- }
- },
- {
- "term": {
- "geo.country_code": "DE"
- }
- }
- ]
+ "filter": [
+ {"term": {"type": "education"}},
+ {"term": {"geo.country_code": "DE"}},
+ topic_filter
+ ]
}
}
-
- # Fetch top institutions for the topic by works_count
res = await elasticsearch.search(
index="openalex-institutions",
query=query,
- size=10,
- sort=[{"works_count": "desc"}],
+ size=50,
+ source=["id", "display_name", "topics"],
cluster="nes"
)
hits = res.get("hits", {}).get("hits", [])
- timeseries: List[UniversityTopicData] = []
+ candidates = []
for hit in hits:
source = hit["_source"]
- # Map the counts_by_year from ES to our model
- # We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
- es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
+ inst_id = source.get("id")
+ display_name = source.get("display_name", "Unknown")
+ # 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 = []
- for year in range(START_YEAR, END_YEAR + 1):
- count_item = es_counts.get(year, {})
+ for yr in years_range:
+ pubs, cits = year_dict[yr]
yearly_data.append(YearlyData(
- year=year,
- publications=count_item.get("works_count", 0),
- citations=count_item.get("cited_by_count", 0)
+ year=yr,
+ publications=pubs,
+ citations=cits
))
-
+
timeseries.append(UniversityTopicData(
- university=source.get("display_name", "Unknown"),
- topic=topic,
+ university=inst_name_map[inst_id],
+ topic=topic_obj,
yearly_data=yearly_data
))
diff --git a/service/src/main/inse/university_ranking/model.py b/service/src/main/inse/university_ranking/model.py
index 1b4b8605..18a2fb32 100644
--- a/service/src/main/inse/university_ranking/model.py
+++ b/service/src/main/inse/university_ranking/model.py
@@ -1,7 +1,7 @@
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']
class YearlyData(BaseModel):
@@ -11,7 +11,7 @@ class YearlyData(BaseModel):
class UniversityTopicData(BaseModel):
university: str
- topic: ResearchTopic
+ topic: Topic
yearly_data: List[YearlyData]
class UniversityRanking(BaseModel):
@@ -27,4 +27,37 @@ class RankingResponse(BaseModel):
# Raw timeseries data for the ECharts line race
timeseries: List[UniversityTopicData]
# Computed metrics for the ranking table
- rankings: List[UniversityRanking]
\ No newline at end of file
+ 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']
\ No newline at end of file
diff --git a/service/src/main/inse/university_ranking/router.py b/service/src/main/inse/university_ranking/router.py
deleted file mode 100644
index 60c52c9d..00000000
--- a/service/src/main/inse/university_ranking/router.py
+++ /dev/null
@@ -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)
\ No newline at end of file
diff --git a/service/src/main/inse/university_ranking/service.py b/service/src/main/inse/university_ranking/service.py
index 4eac89e6..c81ae0ee 100644
--- a/service/src/main/inse/university_ranking/service.py
+++ b/service/src/main/inse/university_ranking/service.py
@@ -1,6 +1,80 @@
-from . import logic
-from .model import RankingResponse, ResearchTopic, DashboardMetric
+import logging
+from typing import List, Optional
+from fastapi import APIRouter, Query
-async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
- """Orchestrates data retrieval and computation for the dashboard."""
- return await logic.get_ranking_data(topic, metric)
\ No newline at end of file
+from inse.tags import Tags
+from . import logic, trend_logic
+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)
\ No newline at end of file
diff --git a/service/src/main/inse/university_ranking/trend_logic.py b/service/src/main/inse/university_ranking/trend_logic.py
new file mode 100644
index 00000000..8e1365d7
--- /dev/null
+++ b/service/src/main/inse/university_ranking/trend_logic.py
@@ -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)
+
diff --git a/service/src/main/inse/works/logic.py b/service/src/main/inse/works/logic.py
index eb36f5a9..ec4f16af 100644
--- a/service/src/main/inse/works/logic.py
+++ b/service/src/main/inse/works/logic.py
@@ -55,6 +55,7 @@ async def get_author_works(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
+ sort: str = "year",
client: OpenAlexWorksSearchClient | None = None,
) -> WorkPage:
search_client = client or OpenAlexWorksSearchClient()
@@ -68,9 +69,11 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
+ sort=sort,
)
elements, total = _parse_full_work_search_response(data)
+ await _enrich_work_topic_descriptions(elements)
offset = (page - 1) * size
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": {
"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", {})
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 = []
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
@@ -202,9 +229,44 @@ async def get_work(
elements, _ = _parse_full_work_search_response(response_by_title)
if not elements:
return None
+ await _enrich_work_topic_descriptions(elements[:1])
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]:
if not topic_ids:
return {}
@@ -869,6 +931,7 @@ async def _search_author_works_data(
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
+ sort: str = "year",
) -> dict:
return await search_client.search_author_works(
author_id,
@@ -879,6 +942,7 @@ async def _search_author_works_data(
language=language,
institution_id=institution_id,
topic_id=topic_id,
+ sort=sort,
)
diff --git a/service/src/main/inse/works/model.py b/service/src/main/inse/works/model.py
index e16d723a..c4e01fdb 100644
--- a/service/src/main/inse/works/model.py
+++ b/service/src/main/inse/works/model.py
@@ -4,6 +4,7 @@
Pydantic models for publication works.
"""
+from enum import StrEnum
from typing import List
from typing import Optional
@@ -41,3 +42,35 @@ class WorkPage(BaseModel):
class WorkList(BaseModel):
elements: List[Work] = Field(default_factory=list, description="All 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."
+ )
diff --git a/service/src/main/inse/works/purpose_router.py b/service/src/main/inse/works/purpose_router.py
new file mode 100644
index 00000000..b641e008
--- /dev/null
+++ b/service/src/main/inse/works/purpose_router.py
@@ -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)
diff --git a/service/src/main/inse/works/purpose_service.py b/service/src/main/inse/works/purpose_service.py
new file mode 100644
index 00000000..9003f4c4
--- /dev/null
+++ b/service/src/main/inse/works/purpose_service.py
@@ -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
+ )
diff --git a/service/src/main/inse/works/search_client.py b/service/src/main/inse/works/search_client.py
index 9c106e18..2e52a9a6 100644
--- a/service/src/main/inse/works/search_client.py
+++ b/service/src/main/inse/works/search_client.py
@@ -35,6 +35,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
+ sort: str = "year",
) -> dict[str, Any]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
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 {
"from": (page - 1) * size,
"size": size,
+ "track_total_hits": True,
"query": {
"bool": {
"must": must_clauses,
"filter": filters,
},
},
- "sort": [
- {"publication_year": {"order": "desc", "missing": "_last"}},
- {"cited_by_count": {"order": "desc", "missing": "_last"}},
- ],
+ "sort": sort_clauses,
}
def _work_filters(
@@ -129,6 +138,7 @@ class OpenAlexWorksSearchClient:
language: list[str] | None = None,
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
+ sort: str = "year",
) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
@@ -142,6 +152,7 @@ class OpenAlexWorksSearchClient:
language=language,
institution_id=institution_id,
topic_id=topic_id,
+ sort=sort,
)
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
diff --git a/service/src/main/inse/works/service.py b/service/src/main/inse/works/service.py
index 382f3fd7..ead6daad 100644
--- a/service/src/main/inse/works/service.py
+++ b/service/src/main/inse/works/service.py
@@ -4,7 +4,7 @@
REST API for publication works.
"""
-from typing import Annotated, Optional
+from typing import Annotated, Literal, Optional
from fastapi import APIRouter
from fastapi import Path
@@ -54,6 +54,10 @@ async def get_author_works(
list[str] | None,
Query(description="Filter by OpenAlex topic id. Can be repeated."),
] = None,
+ sort: Annotated[
+ Literal["year", "citations"],
+ Query(description="Sort order: by publication year or by citation count."),
+ ] = "year",
):
return await logic.get_author_works(
author_id,
@@ -64,6 +68,7 @@ async def get_author_works(
language=language,
institution_id=institution_id,
topic_id=topic_id,
+ sort=sort,
)
diff --git a/service/src/main/inse/works/test_search_client.py b/service/src/main/inse/works/test_search_client.py
index 2d9e2a41..1f3c905e 100644
--- a/service/src/main/inse/works/test_search_client.py
+++ b/service/src/main/inse/works/test_search_client.py
@@ -26,6 +26,28 @@ def test_author_works_query_searches_authorship_author_id():
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():
client = OpenAlexWorksSearchClient(api_key="test-key")
diff --git a/ude_person.http b/ude_person.http
index 9354020f..94a219fb 100644
--- a/ude_person.http
+++ b/ude_person.http
@@ -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
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
diff --git a/webapp/openapitools.json b/webapp/openapitools.json
index 6e1605ed..a20f2fa7 100644
--- a/webapp/openapitools.json
+++ b/webapp/openapitools.json
@@ -19,4 +19,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES
index 99b72add..d1311b2f 100644
--- a/webapp/src/app/api/.openapi-generator/FILES
+++ b/webapp/src/app/api/.openapi-generator/FILES
@@ -17,6 +17,7 @@ api/personNetwork.service.ts
api/persons.service.ts
api/projects.service.ts
api/topics.service.ts
+api/universityRankings.service.ts
api/works.service.ts
configuration.ts
encoder.ts
@@ -35,9 +36,11 @@ model/authorNetworkNode.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
model/authorSummaryStats.ts
+model/authorWorkPurposes.ts
model/authorsFilterProperties.ts
model/authorsListResponse.ts
model/authorship.ts
+model/autocompleteLocationItem.ts
model/autocompleteResponse.ts
model/autocompleteResponseMeta.ts
model/autocompleteResponseResultsInner.ts
@@ -46,6 +49,8 @@ model/bodyChangePassword.ts
model/bodyGetAccessToken.ts
model/bodyLogin.ts
model/bodyRequestOtk.ts
+model/bodyRequestPasswordReset.ts
+model/bodyResetPassword.ts
model/bundProject.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
@@ -113,7 +118,7 @@ model/hEUReportSummary.ts
model/hEUTopic.ts
model/hEUWebLink.ts
model/hTTPValidationError.ts
-model/idToken.ts
+model/idTokenMetadata.ts
model/inseAccountManagementModelOrganizationProfile.ts
model/inseOrganizationManagementModelOrganizationProfile.ts
model/institution.ts
@@ -127,6 +132,8 @@ model/institutionsListResponse.ts
model/ipcClassification.ts
model/keywordEntry.ts
model/keywordEntryWithTopic.ts
+model/keywordPatentMatch.ts
+model/keywordPatentSearchItem.ts
model/keywordTopicMatch.ts
model/keywords.ts
model/keywordsRequest.ts
@@ -138,6 +145,7 @@ model/loginResponse.ts
model/longitude.ts
model/matchedAuthor.ts
model/matchedOfficer.ts
+model/matchedTopic.ts
model/mentionedPerson.ts
model/meta.ts
model/model2YrMeanCitedness.ts
@@ -146,12 +154,16 @@ model/newsArticle.ts
model/newsArticleDetail.ts
model/newsPage.ts
model/openAccess.ts
+model/openAlexTopicTag.ts
model/orgPatentEntry.ts
model/orgPatentsResponse.ts
model/organizationPage.ts
+model/otkResponse.ts
model/patentEntry.ts
model/patentsByAuthorResponse.ts
model/patentsByInstitutionResponse.ts
+model/patentsByKeywordsRequest.ts
+model/patentsByKeywordsResponse.ts
model/personBio.ts
model/projectType.ts
model/projectsFilteringProperties.ts
@@ -160,20 +172,25 @@ model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationsByAuthorResponse.ts
model/rankingResponse.ts
-model/refreshToken.ts
+model/rebuildResponse.ts
model/score.ts
model/sortDirection.ts
+model/specificWorkPurpose.ts
model/tokenType.ts
+model/topInstitutionItem.ts
model/topic.ts
model/topicCount.ts
model/topicDomain.ts
model/topicField.ts
model/topicIds.ts
model/topicSubfield.ts
+model/topicYearlyData.ts
model/topics.ts
model/topicsByTime.ts
model/topicsByYear.ts
model/topicsListResponse.ts
+model/trendResponse.ts
+model/trendSeries.ts
model/universityRanking.ts
model/universityTopicData.ts
model/updateAccountRequest.ts
@@ -193,6 +210,7 @@ model/workKeyword.ts
model/workMeshInner.ts
model/workNetworkNode.ts
model/workPage.ts
+model/workPurpose.ts
model/workSustainableDevelopmentGoalsInner.ts
model/workTopic.ts
model/workTopicDomain.ts
diff --git a/webapp/src/app/api/api/api.ts b/webapp/src/app/api/api/api.ts
index 8ea55e0b..64e95400 100644
--- a/webapp/src/app/api/api/api.ts
+++ b/webapp/src/app/api/api/api.ts
@@ -24,21 +24,8 @@ export * from './projects.service';
import { ProjectsService } from './projects.service';
export * from './topics.service';
import { TopicsService } from './topics.service';
+export * from './universityRankings.service';
+import { UniversityRankingsService } from './universityRankings.service';
export * from './works.service';
import { WorksService } from './works.service';
-export const APIS = [
- AuthService,
- CompanyConnectionsService,
- FundingService,
- INSEServiceService,
- InstitutionsService,
- KeywordsService,
- 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];
diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts
index 6beb60cc..a906d12f 100644
--- a/webapp/src/app/api/api/auth.service.ts
+++ b/webapp/src/app/api/api/auth.service.ts
@@ -33,6 +33,10 @@ import { BodyLogin } from '../model/bodyLogin';
// @ts-ignore
import { BodyRequestOtk } from '../model/bodyRequestOtk';
// @ts-ignore
+import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset';
+// @ts-ignore
+import { BodyResetPassword } from '../model/bodyResetPassword';
+// @ts-ignore
import { CreateAccountRequest } from '../model/createAccountRequest';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -41,6 +45,8 @@ import { InseAccountManagementModelOrganizationProfile } from '../model/inseAcco
// @ts-ignore
import { LoginResponse } from '../model/loginResponse';
// @ts-ignore
+import { OtkResponse } from '../model/otkResponse';
+// @ts-ignore
import { UpdateAccountRequest } from '../model/updateAccountRequest';
// @ts-ignore
@@ -64,13 +70,14 @@ export class AuthService extends BaseService {
* Change the user\'s password and invalidate existing tokens.
* @endpoint post /api/auth/v2/change-password
* @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 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;
- public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public changePassword(bodyChangePassword: BodyChangePassword, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (bodyChangePassword === null || bodyChangePassword === undefined) {
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
}
@@ -132,13 +139,14 @@ export class AuthService extends BaseService {
* Create Account
* @endpoint post /api/accounts
* @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 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;
- public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public createAccount(createAccountRequest: CreateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (createAccountRequest === null || createAccountRequest === undefined) {
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
}
@@ -200,13 +208,14 @@ export class AuthService extends BaseService {
* Delete Account
* @endpoint delete /api/accounts/{account_id}
* @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 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;
- public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public deleteAccount(accountId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public deleteAccount(accountId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (accountId === null || accountId === undefined) {
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.
* @endpoint post /api/auth/v2/access
* @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 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;
- public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, idToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
}
let localVarHeaders = this.defaultHeaders;
- // authentication (HTTPBearer) required
- localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
-
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
@@ -326,13 +333,14 @@ export class AuthService extends BaseService {
/**
* Get Current Account
* @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 reportProgress flag to report request and response progress.
*/
- public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
- public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public getCurrentAccount(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public getCurrentAccount(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public getCurrentAccount(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public getCurrentAccount(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
let localVarHeaders = this.defaultHeaders;
@@ -431,13 +439,14 @@ export class AuthService extends BaseService {
/**
* List 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 reportProgress flag to report request and response progress.
*/
- public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>;
- public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>;
- public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public listAccountOrganizations(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public listAccountOrganizations(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>;
+ public listAccountOrganizations(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>>;
+ public listAccountOrganizations(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
let localVarHeaders = this.defaultHeaders;
@@ -490,13 +499,14 @@ export class AuthService extends BaseService {
* @param offset
* @param search
* @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 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;
- 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>;
- 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>;
- 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 {
+ 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;
+ 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>;
+ 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>;
+ 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 {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -624,13 +634,14 @@ export class AuthService extends BaseService {
* Logout
* Logout the authenticated user.
* @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 reportProgress flag to report request and response progress.
*/
- public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
- public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public logout(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public logout(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public logout(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public logout(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
let localVarHeaders = this.defaultHeaders;
@@ -679,19 +690,17 @@ export class AuthService extends BaseService {
* Refresh Access Token
* Refresh the access token using a valid refresh token.
* @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 reportProgress flag to report request and response progress.
*/
- public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
- public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public refreshAccessToken(refreshToken?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public refreshAccessToken(refreshToken?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public refreshAccessToken(refreshToken?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public refreshAccessToken(refreshToken?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
let localVarHeaders = this.defaultHeaders;
- // authentication (HTTPBearer) required
- localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
-
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'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 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;
- public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
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`;
const { basePath, withCredentials } = this.configuration;
- return this.httpClient.request('post', `${basePath}${localVarPath}`,
+ return this.httpClient.request('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
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;
+ public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public requestPasswordReset(bodyRequestPasswordReset: BodyRequestPasswordReset, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ 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('post', `${basePath}${localVarPath}`,
+ {
+ context: localVarHttpContext,
+ body: bodyRequestPasswordReset,
+ responseType: 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;
+ public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public resetPassword(bodyResetPassword: BodyResetPassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public resetPassword(bodyResetPassword: BodyResetPassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ 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('post', `${basePath}${localVarPath}`,
+ {
+ context: localVarHttpContext,
+ body: bodyResetPassword,
+ responseType: responseType_,
+ ...(withCredentials ? { withCredentials } : {}),
+ headers: localVarHeaders,
+ observe: observe,
+ ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
+ reportProgress: reportProgress
+ }
+ );
+ }
+
/**
* Update Account
* @endpoint put /api/accounts/{account_id}
* @param accountId
* @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 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;
- public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
- public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
+ public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable;
+ public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>;
+ public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable {
if (accountId === null || accountId === undefined) {
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
}
diff --git a/webapp/src/app/api/api/iNSEService.service.ts b/webapp/src/app/api/api/iNSEService.service.ts
index da26fff7..1149c309 100644
--- a/webapp/src/app/api/api/iNSEService.service.ts
+++ b/webapp/src/app/api/api/iNSEService.service.ts
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
- *
+ *
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,355 +9,205 @@
*/
/* 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';
+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 { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
-import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
-import { Configuration } from '../configuration';
+import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
+import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
+
+
@Injectable({
- providedIn: 'root',
+ providedIn: 'root'
})
export class INSEServiceService extends BaseService {
- constructor(
- protected httpClient: HttpClient,
- @Optional() @Inject(BASE_PATH) basePath: string | string[],
- @Optional() configuration?: Configuration,
- ) {
- super(basePath, configuration);
- }
- /**
- * Builds the topic hierarchy cache.
- * @endpoint get /api/inse-service/topics/cache
- * @param pageSize Page size for each search page.
- * @param saveJson Persist cache JSON to data folder.
- * @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 buildTopicCache(
- pageSize?: number,
- saveJson?: boolean,
- observe?: 'body',
- reportProgress?: boolean,
- options?: {
- httpHeaderAccept?: 'application/json';
- context?: HttpContext;
- transferCache?: boolean;
- },
- ): Observable