Compare commits

...
Author SHA1 Message Date
farajollahi 92e32cd79e Merge branch 'dev' into dfg-projects-analyse
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 20:59:36 +02:00
farajollahi acad12bf27 remove dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-12 20:32:01 +02:00
farajollahi 3fa6f1dd6e Merge pull request 'fix dfg projects analyse' (#210) from dfg-projects-analyse into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #210
2026-07-12 20:20:07 +02:00
farajollahi f20be8aa63 fix dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-12 18:32:04 +02:00
genja 0f3388d290 Merge pull request 'feature/keywords-analysis' (#209) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #209
2026-07-12 16:32:28 +02:00
genja 2e855dcf7b removed commented sections, cleaned log outputs
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:30:44 +02:00
genja 680d2924ee Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keyword-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:25:12 +02:00
genja ace2a6bba3 added tooltips, snackbar messages 2026-07-12 16:23:19 +02:00
genja 6dfec1cfd4 updated keywords extraction logic for accepting pdfs 2026-07-12 16:22:43 +02:00
farajollahi 4568669d53 Merge pull request 'bookmark-Authors' (#208) from bookmark-Authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #208
2026-07-12 13:42:42 +02:00
farajollahi e162ec1cac Merge branch 'dev' into bookmark-Authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-12 13:35:35 +02:00
farajollahi 4027728626 Merge pull request 'dashboard-statics' (#207) from dashboard-statics into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #207
2026-07-12 13:33:11 +02:00
farajollahi 1fc64c9c21 Merge branch 'dev' into dashboard-statics
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 13:26:15 +02:00
farajollahi 85610215b5 fix styles
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-12 13:23:00 +02:00
farajollahi c12393a906 bookmark authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 13:12:57 +02:00
Mats Paul Tončik 9cf6348f55 Merge remote-tracking branch 'origin/dev' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-11 23:32:09 +02:00
farajollahi fafd5018bd implement charts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-11 22:15:44 +02:00
khalti f1ff7c9f66 Merge pull request 'perf(patents): batch OpenAlex topic lookups into a single request per page, cutting endpoint latency from ~4-8s to ~0.6-1.1s' (#206) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-11 21:53:23 +02:00
khalti b3af72a6ae perf(patents): batch OpenAlex topic lookups into a single request per page, cutting endpoint latency from ~4-8s to ~0.6-1.1s
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-11 21:49:53 +02:00
Mats Paul Tončik 7f02de2194 Merge branch 'dev' into work-purpose 2026-07-11 21:30:42 +02:00
Mats Paul Tončik 5f71a4b56c Merge remote-tracking branch 'origin/dev' into work-purpose
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-11 21:16:58 +02:00
khalti 390e1049b8 Merge pull request 'feat(patents): color OpenAlex topic and IPC/CPC classification tags by academic field, reusing the existing topic-chip color palette' (#205) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #205
2026-07-11 20:55:08 +02:00
khalti 34b01f2ae8 feat(patents): color OpenAlex topic and IPC/CPC classification tags by academic field, reusing the existing topic-chip color palette
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-11 20:50:31 +02:00
khalti 6360e86179 Merge pull request 'ts-136-patent-to-researchers-v2' (#172) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #172
2026-07-11 20:17:11 +02:00
khaltiandClaude Sonnet 5 2427f4baa0 feat(patents): show OpenAlex topic labels for patent IPC/CPC codes
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Enriches patents with matched OpenAlex topic names from
patents_openalex_keywords, shown alongside classifications on the
patent detail page. Also fixes lookup() using a broken GET on doc ids
containing "/" (400 from the gateway) by switching to a _search with
an ids query.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-11 11:39:45 +02:00
Roman 0e7bc41522 fix institutions_search and institution_filter
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-10 19:07:54 +02:00
Mats Paul Tončik 77c7eeef8b fix(person/publications): changed publications to generic data table
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-10 17:02:19 +02:00
Mats Paul Tončik 5b894d8927 fix(person/publications): moved work purposes and publications table to new expansion panel 2026-07-10 15:23:56 +02:00
Mats Paul Tončik b352e5288a feat(frontend/work-purpose): added work purpose bar chart for author publications 2026-07-10 14:58:46 +02:00
Louis 7bbfe1761d reduce publications: reduce .scss below budget
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-10 14:08:20 +02:00
Louis 09cb54109a person: remove dummy contact data in profile header 2026-07-10 13:52:29 +02:00
Louis 010e1c7f21 publications: sort author publications by citations or year
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-10 13:43:08 +02:00
taguesokoudjou f5bf3ecbe4 feat(keywords): show patents for extracted keywords
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-10 13:26:23 +02:00
Louis d1802fa1f8 publication detail: paginate authors and institutions lists 2026-07-10 13:12:27 +02:00
Louis 4d0a6db3c3 Merge remote-tracking branch 'origin/dev' into publications-and-topics 2026-07-10 12:39:46 +02:00
genja e5cf17620a fixed layout for fileupload, added snackbars on errors 2026-07-09 23:29:06 +02:00
genja ea3ddabac0 file upload integration fixes 2026-07-09 23:28:40 +02:00
taguesokoudjou fa43ff8106 fix: add patent_map_key and resolver topic-map support for tests
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-09 16:01:55 +02:00
taguesokoudjou 1c9ca6fa7d fix: resolve merge conflicts in keywords search
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-09 15:11:05 +02:00
taguesokoudjou 23b1be3b7b Add patents-by-keywords mapping pipeline and keyword patent search flow
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-09 15:01:43 +02:00
genja 233a2d2fca file upload component added (version 1) 2026-07-09 11:37:12 +02:00
genja b12e254cae added file upload component to keywords extraction UI 2026-07-09 11:36:30 +02:00
genja 40610c94c5 regenerated services 2026-07-09 11:34:56 +02:00
genja 2b1aa8d9e3 added file upload backend logic + content extraction from pdf files 2026-07-09 11:34:43 +02:00
genja db604feb37 Merge pull request 'feature/keywords-analysis' (#200) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #200
2026-07-08 12:57:47 +02:00
genja cd0e98ec5f Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-08 12:55:20 +02:00
genja 42685ae44f ui and navigation adjustments 2026-07-08 12:53:58 +02:00
genja 9be024bb13 used sessionStorage for keywords handoff from keywords extraction to search results 2026-07-08 12:53:26 +02:00
genja 87b7e207e3 added publications and news tabs for keyword search 2026-07-08 12:51:23 +02:00
genja 8eaa9c2420 Merge pull request 'feature/keywords-analysis' (#199) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #199
2026-07-08 03:36:21 +02:00
genja 87b02ed0a4 added reusable weights sliders component
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-08 03:31:43 +02:00
genja a6d30dd897 added navigate event to keywords-search on keyword click 2026-07-08 03:30:55 +02:00
genja 134055b8b9 created a template for projects results for keyword search 2026-07-08 03:29:26 +02:00
genja be72d28bda created a template component for persons results for keyword search 2026-07-08 03:29:04 +02:00
genja 2bfb877e77 created a template for patents results for keyword search 2026-07-08 03:28:16 +02:00
genja 48e33e7fe5 added search-results parent component 2026-07-08 03:27:29 +02:00
genja f469594c17 added topic mapping toggle logic 2026-07-08 03:25:56 +02:00
genja 3e115619a6 added topic mapping toggle 2026-07-08 03:25:37 +02:00
genja 13b2fb3350 added new routes for keywords search components 2026-07-08 03:19:43 +02:00
Mats Paul Tončik d26ddb8cb4 fix(frontend/auth): fixed change password form
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-07 10:58:10 +02:00
Louis a8e582cf23 publication-detail: make external links section collapsible 2026-07-07 09:46:53 +02:00
Louis 940c050cd7 publication-detail: make sources and funding sections collapsible 2026-07-07 09:44:17 +02:00
Louis e470b65b5a publication-detail: make authors and institutions collapsible like news sidebar 2026-07-07 09:38:06 +02:00
Louis 383c77134a publication-detail: link topic chips to person search topic filter 2026-07-07 09:19:34 +02:00
Louis bb941361a1 publication-detail: link topic chips to keywords topic mapping 2026-07-07 09:04:43 +02:00
Louis 5d22b201e9 publications/persons: add open-institution shortcut to institution tags and filter chips 2026-07-07 08:50:48 +02:00
Louis 1c6dbb540f Merge remote-tracking branch 'origin/dev' into publications-and-topics
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-07 01:08:55 +02:00
Louis cf9a5df4e9 works: count interesting-for topics like the publications filter 2026-07-07 01:08:14 +02:00
Louis 213edf8a5f works: report exact publication totals beyond 10k 2026-07-07 00:43:28 +02:00
Louis c277fcfece person: add publication and citation icons to stats line 2026-07-07 00:33:59 +02:00
Louis 8efbbf1f1a person-publication: show topic hierarchy tooltip on active filter chip 2026-07-07 00:21:06 +02:00
Louis 9ad6d5cd8c person overview: show topic hierarchy tooltip on active filter chip 2026-07-07 00:17:30 +02:00
Louis 77540e4002 person overview: enrich person search topics with descriptions 2026-07-07 00:12:38 +02:00
genja fd3ceb54aa Merge pull request 'feature/keywords-analysis' (#196) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #196
2026-07-07 00:07:37 +02:00
genja 7baeab92c2 fixed borders issues
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-07 00:06:49 +02:00
Louis 0c526be983 person: pass topic field/domain to publications filter for consistent chip colors 2026-07-07 00:05:19 +02:00
Louis 53f5440d01 works: enrich publication topics with descriptions from topics index 2026-07-06 23:54:38 +02:00
Louis e86a19f800 person: add apartment icon to institution line for consistency
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:43:51 +02:00
genja 61fd920a9f Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:38:51 +02:00
genja 7eed7e6614 tooltip added for select all button
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:37:44 +02:00
Roman e34e1fe3d5 Merge branch 'reset-password&forgot-password' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:35:12 +02:00
Roman 2418821691 fix tests
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:29:31 +02:00
Louis 058c92227a person-interesting: reduce card height while topics are loading 2026-07-06 23:27:15 +02:00
kallweit bf38147acc Merge pull request 'feat/news_keyword_extraction' (#195) from feat/news_keyword_extraction into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #195
2026-07-06 23:25:10 +02:00
genja 3f23845c89 enriched autocomplete options with data 2026-07-06 23:21:36 +02:00
genja 52e70a5b24 regenerated tests 2026-07-06 23:21:14 +02:00
genja d502431102 replaced old httpx requests and openalex_api with elastic wrapper and own indices 2026-07-06 23:21:04 +02:00
kallweit 3533b994d0 fix(news): restore changes after rebase
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 23:20:14 +02:00
genja 5d22f4831a added topic indicies to global enum 2026-07-06 23:19:07 +02:00
Louis 8130192a44 person: link institution to detail page and show country flag 2026-07-06 23:16:24 +02:00
Roman bda7aff447 fix(login): re-enable forms after failed auth requests
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-06 23:15:52 +02:00
Roman 82421c1040 reset-password and forgot-password 2026-07-06 23:13:30 +02:00
Louis 0723bb5c5b publication detail: link institutions to their detail page 2026-07-06 23:06:54 +02:00
Louis e4dbe07436 publication detail:
show country flags for institutions
2026-07-06 22:54:39 +02:00
kallweit 19c6574945 fix(news): highlight full word forms of keywords in article text
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-06 22:45:19 +02:00
kallweit 0b750d27e7 feat(news-details): add pagination to 'mentioned persons' accordion, expand only one accordion at a time 2026-07-06 22:45:19 +02:00
kallweit 398ea7b56c feat(news): remove unmatched keywords list 2026-07-06 22:45:19 +02:00
kallweit 0176eea873 fix(keywords): adjust prompt to deduplicate and extract keywords in article's language 2026-07-06 22:45:19 +02:00
kallweit b0e8c86743 feat(news): add info icon to accordions 2026-07-06 22:45:19 +02:00
kallweit 03a2954c72 feat(news): redesign news detail page 2026-07-06 22:45:19 +02:00
kallweit b9d382c78a feat(news): wire keywords to OpenAlex topics 2026-07-06 22:43:26 +02:00
Louis 78a8e5d919 publication detail: split topics and keywords into separate sections 2026-07-06 22:42:22 +02:00
kallweit f9f6a58ad5 fix(news): add missing routes 2026-07-06 22:37:40 +02:00
kallweit 5cc110174a feat(news): add preprocessing keyword extraction 2026-07-06 22:37:40 +02:00
Louis c3ec93fba1 show loading spinner for interesting-topics instead of empty state 2026-07-06 22:35:45 +02:00
genja 169b825195 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into ts-82-author-overview-and-description 2026-07-06 22:01:13 +02:00
kallweit 0a3bf72e14 Merge pull request 'refactor/news-list-ui' (#194) from refactor/news-list-ui into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #194
2026-07-06 22:00:04 +02:00
kallweit eb94fc5942 fix(news): add title search
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-06 21:52:40 +02:00
kallweit e868c4a47e refactor(news): change list to card layout 2026-07-06 21:46:56 +02:00
genja 1cf80ae074 added highlighted source text of extracted keywords
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 18:49:49 +02:00
taguesokoudjou 9d6656b6c4 feat(patents): replace semantic filtering with IPC topic mapping
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-06 17:58:11 +02:00
genja c74d0b5b87 Merge pull request 'ui fixes' (#193) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #193
2026-07-06 15:31:47 +02:00
genja a69f014413 ui fixes
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 15:30:43 +02:00
genja cabf819e94 Merge pull request 'added loading component, adjusted ui' (#192) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #192
2026-07-06 14:50:34 +02:00
genja c243088752 added loading component, adjusted ui
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-06 14:49:24 +02:00
taguesokoudjou de4ba0591e fix(patents): restore patent detail API and align frontend service types
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Re-add getPatentByIdOrTitle endpoint and OrgPatentMatchTypeFilter export
lost during dev merge; update institution-patents to use options-based API.
2026-07-06 13:57:47 +02:00
taguesokoudjou eb89076070 Merge origin/dev into ts-136-patent-to-researchers-v2
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Resolve merge conflicts from dev integration: keep refactored patent
module structure, add keywords router and otkResponse export from dev.
2026-07-06 13:35:54 +02:00
kuzko 1dd032a66c Merge pull request 'feature/FrontendGeneralKeywordSearch' (#191) from feature/FrontendGeneralKeywordSearch into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #191
2026-07-06 11:43:27 +02:00
Kazgatari 9f03c92bc1 updated old code to remove warnings
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-06 11:35:53 +02:00
Kazgatari 86bced4940 fixed diagramm tooltip cutoff 2026-07-06 11:32:31 +02:00
Kazgatari 4461b26270 changed icons, to match the project icons 2026-07-06 11:22:33 +02:00
Kazgatari 19fd2ac86d Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/FrontendGeneralKeywordSearch 2026-07-06 11:05:30 +02:00
Kazgatari e9ba874103 regenerated frontend service 2026-07-06 10:46:36 +02:00
Kazgatari dfb1413b05 Changed trend frontend (Everything in German, stacking chart, y-axis overlap fix, tooltip information addition, recomended institutions layout change) 2026-07-06 10:45:57 +02:00
Kazgatari b5d03c84c4 attempt to optimize backend search time and small modeltype changes 2026-07-06 10:20:42 +02:00
khalti 40d8a5458d fix(frontend/patents): update year-range display live while dragging, keep request on release
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-05 21:15:59 +02:00
genja ef41c0ad96 Merge pull request 'feature/keywords-analysis' (#190) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #190
2026-07-05 20:12:26 +02:00
genja a07fadc30e deleted unused TopicChipComponent from person-list
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 20:10:53 +02:00
genja 4bf351cf66 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-05 20:01:34 +02:00
Louis f55a37867c Merge pull request 'topic-colored-chips' (#189) from topic-colored-chips into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #189
2026-07-05 19:59:25 +02:00
genja ae42bc46ed Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 19:54:35 +02:00
genja c38355c817 minor logic and layout adjustments 2026-07-05 19:53:23 +02:00
Louis 0c004f0cdf Merge remote-tracking branch 'origin/dev' into topic-colored-chips
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-05 19:50:41 +02:00
Mats Paul Tončik 16c0b399c8 feat(frontend/search): added card search template, moved institutions and projects to it
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 19:47:16 +02:00
Louis 3867540a4c refactor(publications, people): unify active topic chip, add loading states
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 19:46:24 +02:00
Louis 32cab01a8b Merge remote-tracking branch 'origin/dev' into topic-colored-chips 2026-07-05 19:40:55 +02:00
genja 2b606b8473 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-05 18:36:21 +02:00
genja e0ac41da91 cleaned log outputs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 18:35:39 +02:00
genja 86bed62ac0 delete button removed for autocompletion field
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 18:10:24 +02:00
genja 1eaf8f8c8f responsivness adjusted 2026-07-05 18:09:59 +02:00
genja 0c3db967b0 added handling autocomplete topics ( no extra backend call anymore) 2026-07-05 18:01:54 +02:00
genja 04eb0f0185 fixed bug with no url content 2026-07-05 18:01:10 +02:00
Mats Paul Tončik b2d965d604 fix(frontend): added label to some query param selectors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 16:15:41 +02:00
Mats Paul Tončik 0e80cc3fc3 feat(auth): completed auth restructure
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 15:59:34 +02:00
khalti c4e05a4376 fix(patents): correct author-institution query and name-matching ambiguity checks for org_patents
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-05 15:44:30 +02:00
genja 92c4edfb4f added, colored Keywords, legend, loading state on keyword adding, fixed ui
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-05 02:27:49 +02:00
genja 79f2aa0263 added "field" field to the Topic model 2026-07-05 02:26:59 +02:00
genja 5878edc4cd added error handling on websocket close 2026-07-05 02:23:18 +02:00
genja f4122263dd added stream interrupt logic by socket close for llm wrapper 2026-07-05 02:22:21 +02:00
genja 20faff13ec fixed concetenated keywords issue 2026-07-05 02:21:26 +02:00
genja 73315457a6 fixed resonsiveness issue 2026-07-05 02:19:38 +02:00
Mats Paul Tončik a464a95c4e fix(frontend/organizations): unfucked everything (again) 2026-07-05 00:19:06 +02:00
Mats Paul Tončik 2264582d1e fix(frontend/accounts): unfucked everything 2026-07-04 23:49:39 +02:00
Kazgatari 2703f46575 Implemented scikit normalize batch, fixed blocking elastic search query, changed frontend to resize dynamically, fixed bug in dashboard 2026-07-04 23:12:03 +02:00
Mats Paul Tončik e648ea1ec4 feat(backend/auth): added otk response model 2026-07-04 22:37:34 +02:00
Kazgatari 261f97eee0 regenerated frontend with openapi generator gradle service 2026-07-04 21:04:48 +02:00
Kazgatari f4b8d0884c changed and refactored university-ranking to unify ranking and trend. Removed hardcoded placeholder, Whitelisted fields to reduce response size 2026-07-04 21:01:49 +02:00
Kazgatari 1ddc5c42c5 generated frontend services and models 2026-07-03 22:33:32 +02:00
Kazgatari 47fb41105a Parent componentn to diplay different trend diagrams 2026-07-03 22:20:56 +02:00
Kazgatari 4394ced772 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/FrontendGeneralKeywordSearch 2026-07-03 21:25:27 +02:00
Kazgatari 15fc57da51 First demo implementation of trend analysis frontend 2026-07-03 20:04:35 +02:00
Kazgatari 3c910fa0e4 Backend for institution trend analysis (implemented into university ranking) 2026-07-03 19:50:28 +02:00
farajollahi 8805ec9e57 Merge pull request 'active-deactive-accounts' (#187) from active-deactive-accounts into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #187
2026-07-03 19:24:15 +02:00
farajollahi 6f498bb754 Merge branch 'dev' into active-deactive-accounts
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-03 19:15:18 +02:00
farajollahi 0ea7713f05 implement active accounts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 19:14:41 +02:00
Mats Paul Tončik 7b4c459fd8 fix(frontend/register): fixed wrong variable name
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 17:00:19 +02:00
Mats Paul Tončik 08824bd7ba Merge remote-tracking branch 'origin/dev' into auth-restructure
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-03 16:57:10 +02:00
Mats Paul Tončik 1297f85124 feat(auth): started auth restructure
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-03 16:56:17 +02:00
genja 7613569711 Merge pull request 'feature/keywords-analysis' (#186) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #186
2026-07-03 16:04:57 +02:00
Louis c1cba4bd4c person cards: limit topic display if too large 2026-07-03 15:54:24 +02:00
Louis d43c406820 publication overview: make Jahr/Typ/Sprache filters searchable
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-03 14:53:30 +02:00
genja 63db1c9564 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-03 13:54:42 +02:00
Louis 398df55f50 publication overview: fix institution search 2026-07-03 13:49:19 +02:00
Louis 5888a71b36 publication overview: make institution field expandable 2026-07-03 13:43:31 +02:00
Louis c707064dfb pulbication overview: Make institution field expandable 2026-07-03 13:42:57 +02:00
Louis 8e56b59122 person card: highlight institution when it matches active filter 2026-07-03 13:16:04 +02:00
Mats Paul Tončik cac2d81b5c fix(auth): prevention for same old and new password
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 13:14:05 +02:00
Mats Paul Tončik 0b9f325045 feat(auth): added change password functionality in frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 13:10:16 +02:00
Louis 6fa5792e5e publication overview: show institution filter as person-card chip with flag 2026-07-03 13:10:13 +02:00
Louis 116492baca person list: style active institution filter as person-card chip 2026-07-03 13:02:09 +02:00
Louis b1fee136ce Merge remote-tracking branch 'origin/dev' into topic-colored-chips 2026-07-03 12:31:34 +02:00
Louis 95ce3a47fc publications overview: make table cells clickable filters with active state 2026-07-03 12:21:39 +02:00
genja d1255deaec Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 10:57:51 +02:00
genja 6dd57bfe2b ui adjusments
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-03 10:56:51 +02:00
genja 25988d6c46 added keywords enrichment, refactored 2026-07-03 10:56:43 +02:00
genja f8228c5ea7 added click event on keywords to navigate to keywords component 2026-07-03 10:54:56 +02:00
genja f19059164e added simple shared topic autocompletion component 2026-07-03 10:54:21 +02:00
genja aaab04596d translated status messaged on german 2026-07-03 10:53:52 +02:00
taguesokoudjou 6962b49771 feat(patents): add identity signals for patent disambiguation
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Use name specificity, institution/assignee overlap and topic similarity
to reduce false positives in inventor-based patent matching.
Treat IPC/CPC similarity as a supporting signal instead of proof of identity.
2026-07-02 13:42:04 +02:00
Mats Paul Tončik 6c4688185f fix: applied currency and date pipes where possible
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-02 12:17:34 +02:00
genja 647eb55a88 hardcoded basePath (temporary)
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-02 10:27:56 +02:00
genja 2603580587 ui adjusted 2026-07-02 10:27:13 +02:00
genja 42ecebb27f regenerated services 2026-07-02 10:26:51 +02:00
genja f383952547 simple prompts for testing added 2026-07-02 10:26:19 +02:00
genja 6db4c80258 adden dynamic keywords enriching with openalex topics 2026-07-02 10:26:07 +02:00
genja f0173cbf8a increased llm response timeout up to 120s 2026-07-02 10:25:16 +02:00
taguesokoudjou 4a17157643 Remove patent disambiguation and keep name-only author matching.
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-01 22:52:46 +02:00
taguesokoudjou 503377e3bc Resolve merge conflicts
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-01 20:53:45 +02:00
genja 7bd8659638 regenerated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-01 14:08:27 +02:00
genja 074e237c84 updated endpoint for patent fetching 2026-07-01 14:07:37 +02:00
genja 7e8a796623 moved getPatentById logic from allPatentsSearchClient to PatentSearchClient 2026-07-01 14:06:48 +02:00
genja 5432d814c6 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-01 12:00:32 +02:00
genja 9e5b2c1a21 services cleaned 2026-07-01 11:46:21 +02:00
genja 1fa755769b added websocket interface for streamed keywords extraction
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-01 10:48:09 +02:00
genja cfac12e218 another merging issue fixed 2026-07-01 10:45:45 +02:00
genja 2ec9047565 added websocket implementation to frontend 2026-07-01 10:45:31 +02:00
genja b499fd2877 fixed merging issues for compatibility 2026-07-01 10:44:31 +02:00
genja e5599845ba regenerated services 2026-07-01 10:43:22 +02:00
genja 249fb080e9 added keywords extraction endpoint + logic as stream via websockets 2026-07-01 10:42:51 +02:00
khaltiandClaude Sonnet 4.6 171e87f575 Fix merge conflict in main.py: keep dev auth/account routers, remove duplicate projects_router import
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 10:28:11 +02:00
khaltiandClaude Sonnet 4.6 b37718e792 Fix TS2345: coerce optional IpcClassification fields to null in addRow calls
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 10:25:32 +02:00
khaltiandClaude Sonnet 4.6 eba78a080e Fix build errors from dev merge: remove duplicate AllPatentsResponse, fix IpcClassification import, add null safety for optional arrays in patent-detail template
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 10:22:47 +02:00
genja 050c68ea5e added function for streaming mode to llm wrapper 2026-07-01 10:17:36 +02:00
khalti 204e419fed Fix merge conflicts with dev branch
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-01 10:16:12 +02:00
khalti 0d18ee49f3 merge: resolve conflicts with dev
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-01 09:56:54 +02:00
khalti 65e428f4c2 fix(patents): prevent slider handles from crossing and reduce server requests on drag
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-01 09:51:04 +02:00
genja 67d5306c6e added websocket and partial json parser packages to docker build 2026-07-01 04:19:34 +02:00
Kazgatari 64ab9325a0 Added new Api with keyword list for similarity search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-30 21:06:16 +02:00
Kazgatari 5126e530e6 hopefully last async fix
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-30 19:56:10 +02:00
Kazgatari 8b7f8b7d6a Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into dev 2026-06-30 18:57:49 +02:00
Kazgatari a0cd8d0904 removed other direct httpx references 2026-06-30 18:54:38 +02:00
genja 1113a6a2be Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-30 11:01:30 +02:00
genja 3702b216a0 increased llm response timeout up to 60s 2026-06-30 10:55:29 +02:00
genja dbaabeb9a5 minor ui adjustments 2026-06-30 10:55:16 +02:00
Louis 195fd2d55b Merge remote-tracking branch 'origin/dev' into topic-colored-chips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-30 01:26:14 +02:00
Louis 5d13b07c73 Add field-based color indicators to person search cards filtering 2026-06-30 00:09:37 +02:00
Louis d8aca8ee3e Publication overview filter design updated 2026-06-29 23:52:26 +02:00
Louis 495c7d34e5 timeline legend across full width 2026-06-29 23:40:05 +02:00
genja 677ef59440 Merge branch 'feature/dfg-details' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-06-29 23:07:35 +02:00
genja c259635bdf added loading state to keywords extraction part
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 23:06:02 +02:00
Louis 39fdb23942 Replace topic chips in publication detail view with shared topic chips 2026-06-29 22:47:28 +02:00
Louis 0d2c7f93be filter topic chips use same topic color 2026-06-29 22:38:31 +02:00
Louis 7c68a5cd71 Replace topic chips in publication overview with shared topic chips 2026-06-29 22:26:45 +02:00
genja 17931a82b0 added optional response schema to llm response
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 22:25:55 +02:00
genja 0502a9a553 added new endpoint for keywords search 2026-06-29 22:25:35 +02:00
genja 4b8256b56e added new route for keywords search 2026-06-29 22:24:54 +02:00
genja 095a4c8bac generated models for frontend (2) 2026-06-29 22:24:27 +02:00
genja 473bc96e90 generated models for frontend 2026-06-29 22:24:02 +02:00
genja 642fda7542 added keywords-search component 2026-06-29 22:23:14 +02:00
genja 1fdd5339fa added new category "Keywords" to app-menu 2026-06-29 22:22:29 +02:00
Louis b69fe4e15c Improve timeline legend width 2026-06-29 21:25:01 +02:00
Louis 873e4bbbec Merge remote-tracking branch 'origin/dev' into topic-colored-chips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 20:33:22 +02:00
khalti ba86d417b4 docs(org-patents): document index_org_patents script and add to service README
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-29 20:12:35 +02:00
taguesokoudjou 513489e790 fix(patents): await async person and co-author lookups after dev merge
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-29 19:59:31 +02:00
taguesokoudjou 185d2c3aa2 Merge branch 'dev' into ts-136-patent-to-researchers-v2
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Resolve conflicts in patent module re-export shims by keeping the
refactored search_client and modular logic layout from this branch.
2026-06-29 19:34:36 +02:00
taguesokoudjou ca6c132bb9 feat(patents): score and filter patent-to-researcher matches
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-29 19:27:26 +02:00
Kazgatari dfa9c70a25 removed httpx imports 2026-06-29 18:35:15 +02:00
genja 0817640449 added patent linking from projects to patents page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 00:45:16 +02:00
khalti 569d73aa9f feat(patents): add server-side pagination and source filter to org_patents endpoint
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 14:15:38 +02:00
khalti 0873d25345 feat(patents): add server-side pagination and source filter to org_patents endpoint
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 13:58:23 +02:00
taguesokoudjou 6c13415b1e Add org_patents indexing and institution patent match-type UI
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Introduce a batch script and Elasticsearch index to pre-aggregate institution
patents via assignee and inventor name matching, expose them through a new API
endpoint, and update the institution patents page with match-type filtering.
2026-06-28 12:21:17 +02:00
khalti 56015846b0 feat(patents): Customize search field
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 11:33:37 +02:00
taguesokoudjou 7602fef243 Fix patent search client test to mock httpx transport
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-27 19:18:18 +02:00
taguesokoudjou 81539d5dbd Merge branch 'dev' into ts-136-patent-to-researchers-v2
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-27 19:09:45 +02:00
taguesokoudjou f5991ef660 Add centralized patent detail page with backend lookup by ID
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Introduce /patent/:patentId and a dedicated detail view modeled after
publications, backed by GET /api/inse-service/patents/{patent_id}.
Route patent overview and detail actions from list, person, and
institution views to the shared page instead of inline detail panels.
2026-06-27 18:53:55 +02:00
khalti 6fc491fd87 feat(patents): add year range filter to global patents page
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-27 11:30:09 +02:00
Louis f2cf83f63b topic-legend: select fields and subfields separately 2026-06-26 14:16:56 +02:00
Louis 512356e106 topic-legend: highlight selected fields and topic 2026-06-26 13:58:18 +02:00
Louis 309fecf008 use topic chips for active topic filters 2026-06-26 13:35:06 +02:00
taguesokoudjou 163fdfaa39 refactor(patents): decouple author and institution patent lookup into separate modules
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 12:17:50 +02:00
Louis 29c954227f use shared topic chips in person card
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-26 12:05:00 +02:00
Louis 1f70f9fe2d Merge remote-tracking branch 'origin/dev' into topic-colored-chips 2026-06-26 11:42:04 +02:00
taguesokoudjou e37de88cc8 feat(institutions): add patents view per institution with assignee-based search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 11:27:11 +02:00
389 changed files with 38740 additions and 7369 deletions
@@ -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)
@@ -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 []
+81 -2
View File
@@ -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()
File diff suppressed because one or more lines are too long
+6 -2
View File
@@ -12,10 +12,14 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"uvicorn~=0.29.0" \
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"\
"python-multipart~=0.0.19" \
"beautifulsoup4==4.12.3" \
"openai~=2.41.0" \
"websockets==12.0" \
"partial-json-parser==0.2.1.1.post7" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0"
"argon2-cffi~=25.1.0" \
"pypdf==6.14.2"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+31
View File
@@ -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 <OpenAlex-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.
+1
View File
@@ -10,6 +10,7 @@ dependencies = [
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
"pypdf==6.14.2",
"pydantic~=2.7.1",
"pydantic-settings~=2.2.1",
"pyjwt~=2.8.0",
@@ -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()
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""
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 <OpenAlex-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
import asyncio
import logging
import sys
from pathlib import Path
current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
from dotenv import load_dotenv
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
from inse.patents.org.logic import index_org_patents_for_institution
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger(__name__)
async def main() -> None:
parser = argparse.ArgumentParser(
description="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 (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("Done. Indexed %d patents for institution %s.", count, args.institution_id)
if __name__ == "__main__":
asyncio.run(main())
@@ -8,7 +8,7 @@ Usage (run once from project root):
"""
from sentence_transformers import SentenceTransformer
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
MODEL_NAME = "intfloat/multilingual-e5-base"
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
model = SentenceTransformer(MODEL_NAME)
print("Done.")
@@ -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
@@ -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,
@@ -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)
@@ -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"]
+75 -34
View File
@@ -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."
)
+53 -8
View File
@@ -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,
],
):
File diff suppressed because it is too large Load Diff
+351 -117
View File
@@ -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
@@ -0,0 +1 @@
"""User bookmark feature."""
+36
View File
@@ -0,0 +1,36 @@
import uuid
from datetime import datetime, timezone
from pydantic import BaseModel, Field as PydanticField
from sqlalchemy import UniqueConstraint
from sqlmodel import Field, SQLModel
class PersonBookmark(SQLModel, table=True):
__tablename__ = "person_bookmark"
__table_args__ = (
UniqueConstraint(
"account_id", "person_id", name="uq_person_bookmark_account_person"
),
)
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
account_id: uuid.UUID = Field(
foreign_key="account.id", nullable=False, index=True
)
person_id: str = Field(nullable=False, index=True)
person_name: str | None = Field(default=None)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
)
class CreatePersonBookmark(BaseModel):
person_name: str | None = PydanticField(default=None, max_length=500)
class PersonBookmarkResponse(BaseModel):
person_id: str
person_name: str | None
created_at: datetime
+47
View File
@@ -0,0 +1,47 @@
from fastapi import APIRouter, Response, status
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata
from inse.database import SessionDep
from . import service
from .model import CreatePersonBookmark, PersonBookmarkResponse
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
@router.get("/persons", operation_id="listPersonBookmarks")
def list_person_bookmarks(
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[PersonBookmarkResponse]:
return service.list_person_bookmarks(session, access_token.effective_account_id)
@router.put("/persons/{person_id}", operation_id="bookmarkPerson")
def bookmark_person(
person_id: str,
payload: CreatePersonBookmark,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> PersonBookmarkResponse:
return service.create_person_bookmark(
session, access_token.effective_account_id, person_id, payload
)
@router.delete(
"/persons/{person_id}",
operation_id="removePersonBookmark",
status_code=status.HTTP_204_NO_CONTENT,
)
def remove_person_bookmark(
person_id: str,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_person_bookmark(
session, access_token.effective_account_id, person_id
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -0,0 +1,81 @@
import uuid
from fastapi import HTTPException, status
from sqlmodel import Session, select
from .model import CreatePersonBookmark, PersonBookmark, PersonBookmarkResponse
def normalize_person_id(person_id: str) -> str:
normalized = person_id.strip().rstrip("/").split("/")[-1]
if not normalized:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="A person ID is required.",
)
return normalized
def list_person_bookmarks(
session: Session, account_id: uuid.UUID
) -> list[PersonBookmarkResponse]:
bookmarks = session.exec(
select(PersonBookmark)
.where(PersonBookmark.account_id == account_id)
.order_by(PersonBookmark.created_at.desc())
).all()
return [
PersonBookmarkResponse(
person_id=bookmark.person_id,
person_name=bookmark.person_name,
created_at=bookmark.created_at,
)
for bookmark in bookmarks
]
def create_person_bookmark(
session: Session,
account_id: uuid.UUID,
person_id: str,
payload: CreatePersonBookmark,
) -> PersonBookmarkResponse:
normalized_id = normalize_person_id(person_id)
bookmark = session.exec(
select(PersonBookmark).where(
PersonBookmark.account_id == account_id,
PersonBookmark.person_id == normalized_id,
)
).first()
if bookmark is None:
bookmark = PersonBookmark(
account_id=account_id,
person_id=normalized_id,
person_name=payload.person_name,
)
session.add(bookmark)
elif payload.person_name:
bookmark.person_name = payload.person_name
session.commit()
session.refresh(bookmark)
return PersonBookmarkResponse(
person_id=bookmark.person_id,
person_name=bookmark.person_name,
created_at=bookmark.created_at,
)
def delete_person_bookmark(
session: Session, account_id: uuid.UUID, person_id: str
) -> None:
normalized_id = normalize_person_id(person_id)
bookmark = session.exec(
select(PersonBookmark).where(
PersonBookmark.account_id == account_id,
PersonBookmark.person_id == normalized_id,
)
).first()
if bookmark is not None:
session.delete(bookmark)
session.commit()
@@ -0,0 +1,71 @@
import uuid
from sqlmodel import Session, SQLModel, create_engine
from inse.auth.model import Account, Organization
from .model import CreatePersonBookmark
from .service import (
create_person_bookmark,
delete_person_bookmark,
list_person_bookmarks,
)
def _session_with_account():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
session = Session(engine)
organization = Organization(name="Bookmark Test Org")
session.add(organization)
session.flush()
account = Account(
email="bookmarks@example.org",
name="Bookmark Tester",
password_hash="not-used",
organization_id=organization.id,
)
session.add(account)
session.commit()
return session, account.id
def test_person_bookmarks_are_idempotent_and_normalize_openalex_ids():
session, account_id = _session_with_account()
assert isinstance(account_id, uuid.UUID)
create_person_bookmark(
session,
account_id,
"https://openalex.org/A123",
CreatePersonBookmark(person_name="Ada Example"),
)
create_person_bookmark(
session,
account_id,
"A123",
CreatePersonBookmark(person_name="Ada Updated"),
)
bookmarks = list_person_bookmarks(session, account_id)
assert len(bookmarks) == 1
assert bookmarks[0].person_id == "A123"
assert bookmarks[0].person_name == "Ada Updated"
def test_deleting_a_person_bookmark_is_idempotent():
session, account_id = _session_with_account()
assert isinstance(account_id, uuid.UUID)
create_person_bookmark(
session,
account_id,
"A123",
CreatePersonBookmark(person_name="Ada Example"),
)
delete_person_bookmark(session, account_id, "A123")
delete_person_bookmark(session, account_id, "A123")
assert list_person_bookmarks(session, account_id) == []
@@ -1,7 +1,5 @@
from typing import Any
import httpx
from .. import config
@@ -16,18 +14,10 @@ from inse.exceptions import MissingApiKeyError
class CompanyConnectionsSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
openalex_index: str = "openalex-authors",
handelsregister_index: str = "handelsregister",
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (
base_url
or config.settings.elasticsearch_url
or ""
).rstrip("/")
self.api_key = (
api_key
if api_key is not None
@@ -35,8 +25,6 @@ class CompanyConnectionsSearchClient:
)
self.openalex_index = openalex_index
self.handelsregister_index = handelsregister_index
self.timeout = timeout
self.transport = transport
@staticmethod
def openalex_doc_id(author_id: str) -> str:
+3 -1
View File
@@ -44,7 +44,7 @@ class Settings(BaseSettings):
llm_model: Optional[str] = None
# Sentence Transformers config
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
# Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
@@ -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"
@@ -0,0 +1 @@
"""Dashboard statistics package."""
+52
View File
@@ -0,0 +1,52 @@
from pydantic import BaseModel
class DashboardStatistics(BaseModel):
institution_id: str
organization_name: str
publications: int
persons: int
projects: int
dfg_projects: int
eu_projects: int
bmbf_projects: int
class DashboardStatisticValue(BaseModel):
institution_id: str
organization_name: str
value: int
class TopAuthor(BaseModel):
id: str | None = None
name: str
count: int
class TopAuthorStatistics(BaseModel):
institution_id: str
works: list[TopAuthor]
projects: list[TopAuthor]
patents: list[TopAuthor]
news: list[TopAuthor]
class TopicHeatmapValue(BaseModel):
year: int
count: int
share: float
class TopicHeatmapField(BaseModel):
id: str
name: str
total: int
values: list[TopicHeatmapValue]
class TopicHeatmap(BaseModel):
institution_id: str
organization_name: str
years: list[int]
fields: list[TopicHeatmapField]
+168
View File
@@ -0,0 +1,168 @@
from typing import Literal
from fastapi import APIRouter, Depends, Query
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessToken
from inse.database import get_session
from inse.tags import Tags
from .model import (
DashboardStatisticValue,
DashboardStatistics,
TopAuthorStatistics,
TopicHeatmap,
)
from .service import (
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_eu_projects,
get_dashboard_organization,
get_dashboard_persons,
get_dashboard_publications,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
)
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
@router.get(
"/statistics",
operation_id="getDashboardStatistics",
response_model=DashboardStatistics,
)
async def dashboard_statistics(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_statistics(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/statistics/publications",
operation_id="getDashboardPublications",
response_model=DashboardStatisticValue,
)
async def dashboard_publications(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_publications(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/statistics/persons",
operation_id="getDashboardPersons",
response_model=DashboardStatisticValue,
)
async def dashboard_persons(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_persons(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/statistics/projects/eu",
operation_id="getDashboardEuProjects",
response_model=DashboardStatisticValue,
)
async def dashboard_eu_projects(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_eu_projects(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/statistics/projects/bmbf",
operation_id="getDashboardBmbfProjects",
response_model=DashboardStatisticValue,
)
async def dashboard_bmbf_projects(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_bmbf_projects(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/statistics/projects/dfg",
operation_id="getDashboardDfgProjects",
response_model=DashboardStatisticValue,
)
async def dashboard_dfg_projects(
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_projects(
organization.openalex_institution_id,
organization.name,
)
@router.get(
"/top-authors",
operation_id="getDashboardTopAuthors",
response_model=TopAuthorStatistics,
)
async def dashboard_top_authors(
works_period: Literal["all_time", "last_5_years"] = Query(
default="all_time",
pattern="^(all_time|last_5_years)$",
),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_top_authors(
organization.openalex_institution_id,
organization.name,
works_period=works_period,
)
@router.get(
"/topic-heatmap",
operation_id="getDashboardTopicHeatmap",
response_model=TopicHeatmap,
)
async def dashboard_topic_heatmap(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
limit: int = Query(default=25, ge=1, le=50),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopicHeatmap:
organization = get_dashboard_organization(session, access_token)
return await get_topic_heatmap(
institution_id=organization.openalex_institution_id,
organization_name=organization.name,
from_year=from_year,
to_year=to_year,
limit=limit,
)
+732
View File
@@ -0,0 +1,732 @@
import asyncio
import logging
from datetime import datetime
from typing import Any, Literal
from fastapi import HTTPException, status
from sqlmodel import Session
from inse import config
from inse.auth.model import AccessToken, Organization
from inse.integrations import elasticsearch
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from .model import (
DashboardStatisticValue,
DashboardStatistics,
TopAuthor,
TopAuthorStatistics,
TopicHeatmap,
TopicHeatmapField,
TopicHeatmapValue,
)
TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25
TOPIC_HEATMAP_YEARS = 5
WorksPeriod = Literal["all_time", "last_5_years"]
logger = logging.getLogger(__name__)
DFG_INSTITUTION_FIELDS = [
"Antragstellende Institution",
"Mitantragstellende Institution",
"Beteiligte Einrichtung",
"Beteiligte Hochschule",
"Beteiligte Institution",
"IGK-Partnerinstitution",
"Partnerorganisation",
"Unternehmen",
]
def _total(response: dict[str, Any]) -> int:
total = response.get("hits", {}).get("total", 0)
if isinstance(total, dict):
return int(total.get("value", 0))
return int(total or 0)
def get_dashboard_organization(
session: Session,
access_token: AccessToken,
) -> Organization:
organization = session.get(Organization, access_token.effective_organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
if not organization.openalex_institution_id:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Organization has no OpenAlex institution ID configured.",
)
return organization
async def get_dashboard_statistics(
institution_id: str,
organization_name: str,
) -> DashboardStatistics:
normalized_id = _normalize_institution_id(institution_id)
publications, persons, eu_projects, bmbf_projects, dfg_projects = (
await asyncio.gather(
get_dashboard_publications(institution_id, organization_name),
get_dashboard_persons(institution_id, organization_name),
get_dashboard_eu_projects(institution_id, organization_name),
get_dashboard_bmbf_projects(institution_id, organization_name),
get_dashboard_dfg_projects(institution_id, organization_name),
)
)
return DashboardStatistics(
institution_id=normalized_id,
organization_name=organization_name,
publications=publications.value,
persons=persons.value,
projects=eu_projects.value + bmbf_projects.value + dfg_projects.value,
dfg_projects=dfg_projects.value,
eu_projects=eu_projects.value,
bmbf_projects=bmbf_projects.value,
)
async def get_dashboard_publications(
institution_id: str,
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
query=_institution_works_query(normalized_id),
size=0,
track_total_hits=True,
cluster=ESCluster.NES,
)
return _dashboard_statistic_value(normalized_id, organization_name, response)
async def get_dashboard_persons(
institution_id: str,
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
query={
"nested": {
"path": "affiliations",
"query": {"term": {"affiliations.institution.id": normalized_id}},
}
},
size=0,
track_total_hits=True,
cluster=ESCluster.NES,
)
return _dashboard_statistic_value(normalized_id, organization_name, response)
async def get_dashboard_eu_projects(
institution_id: str,
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
aliases = await _institution_aliases(normalized_id, organization_name)
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
body={
"size": 0,
"query": _eu_organization_query(aliases),
"aggs": {
"projects": {
"cardinality": {
"field": "projectID",
}
}
},
},
cluster=ESCluster.INSE,
)
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
value=int(
response.get("aggregations", {})
.get("projects", {})
.get("value", 0)
),
)
async def get_dashboard_bmbf_projects(
institution_id: str,
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
aliases = await _institution_aliases(normalized_id, organization_name)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=_alias_match_query("Zuwendungsempfänger", aliases),
size=0,
track_total_hits=True,
cluster=ESCluster.INSE,
)
return _dashboard_statistic_value(normalized_id, organization_name, response)
async def get_dashboard_dfg_projects(
institution_id: str,
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
aliases = await _institution_aliases(normalized_id, organization_name)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
query=_dfg_institution_query(aliases),
size=0,
track_total_hits=True,
cluster=ESCluster.INSE,
)
return _dashboard_statistic_value(normalized_id, organization_name, response)
def _dashboard_statistic_value(
institution_id: str,
organization_name: str,
response: dict[str, Any],
) -> DashboardStatisticValue:
return DashboardStatisticValue(
institution_id=institution_id,
organization_name=organization_name,
value=_total(response),
)
async def _institution_aliases(
institution_id: str,
organization_name: str,
) -> list[str]:
aliases = await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
_raw_institution_id(institution_id)
)
return sorted(
{
alias.strip()
for alias in [organization_name, *aliases]
if alias and alias.strip()
}
)
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
return {
"terms": {
"name.keyword": [alias.upper() for alias in aliases],
}
}
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
return {
"bool": {
"should": [
{
"match": {
field: {
"query": alias,
"operator": "and",
}
}
}
for alias in aliases
],
"minimum_should_match": 1,
}
}
def _dfg_institution_query(aliases: list[str]) -> dict[str, Any]:
return {
"bool": {
"should": [
_alias_match_query(field, aliases)
for field in DFG_INSTITUTION_FIELDS
],
"minimum_should_match": 1,
}
}
async def get_top_authors(
institution_id: str,
organization_name: str,
works_period: WorksPeriod = "all_time",
) -> TopAuthorStatistics:
normalized_id = _normalize_institution_id(institution_id)
authors = await _safe_institution_authors(normalized_id)
works = _top_work_authors(authors, works_period)
aliases = await _safe_institution_aliases(normalized_id, organization_name)
projects = await _safe_top_authors(
"projects",
_top_project_authors(authors, aliases),
)
patents = await _safe_top_authors(
"patents",
_top_patent_authors(normalized_id),
)
news = await _safe_top_authors(
"news",
_top_news_authors(authors),
)
return TopAuthorStatistics(
institution_id=normalized_id,
works=works,
projects=projects,
patents=patents,
news=news,
)
async def get_topic_heatmap(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
limit: int = TOPIC_HEATMAP_LIMIT,
) -> TopicHeatmap:
normalized_id = _normalize_institution_id(institution_id)
current_year = datetime.now().year
effective_to_year = to_year or current_year
effective_from_year = from_year or (effective_to_year - TOPIC_HEATMAP_YEARS + 1)
if effective_from_year > effective_to_year:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="from_year must be less than or equal to to_year.",
)
years = list(range(effective_from_year, effective_to_year + 1))
response = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body={
"size": 0,
"query": {
"bool": {
"must": [_institution_works_query(normalized_id)],
"filter": [
{
"range": {
"publication_year": {
"gte": effective_from_year,
"lte": effective_to_year,
}
}
}
],
}
},
"aggs": {
"publication_years": {
"terms": {
"field": "publication_year",
"size": len(years),
"order": {"_key": "asc"},
}
},
"topics_nested": {
"nested": {"path": "topics"},
"aggs": {
"fields": {
"terms": {
"field": "topics.field.id",
"size": limit,
"order": [
{"works": "desc"},
{"_key": "asc"},
],
},
"aggs": {
"field_name": {
"terms": {
"field": "topics.field.display_name.keyword",
"size": 1,
}
},
"works": {
"reverse_nested": {},
"aggs": {
"by_year": {
"terms": {
"field": "publication_year",
"size": len(years),
"order": {"_key": "asc"},
}
}
},
}
},
}
},
},
},
},
cluster=ESCluster.NES,
)
year_totals = _year_totals(response)
buckets = (
response.get("aggregations", {})
.get("topics_nested", {})
.get("fields", {})
.get("buckets", [])
)
field_names = await _field_names([bucket.get("key") for bucket in buckets])
return TopicHeatmap(
institution_id=normalized_id,
organization_name=organization_name,
years=years,
fields=[
_topic_heatmap_field(bucket, years, year_totals, field_names)
for bucket in buckets
if bucket.get("key")
],
)
async def _safe_top_authors(
source: str, operation: Any
) -> list[TopAuthor]:
try:
return await operation
except Exception:
logger.exception("Dashboard top-author aggregation failed for %s.", source)
return []
def _normalize_institution_id(value: str) -> str:
short_id = value.replace("https://openalex.org/", "").strip().upper()
return f"https://openalex.org/{short_id}"
def _raw_institution_id(value: str) -> str:
return value.replace("https://openalex.org/", "").strip().upper()
def _institution_works_query(institution_id: str) -> dict[str, Any]:
return {
"nested": {
"path": "authorships.institutions",
"query": {"term": {"authorships.institutions.id": institution_id}},
}
}
def _year_totals(response: dict[str, Any]) -> dict[int, int]:
buckets = (
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
return {
int(bucket["key"]): int(bucket.get("doc_count", 0))
for bucket in buckets
if bucket.get("key") is not None
}
async def _field_names(field_ids: list[str | None]) -> dict[str, str]:
ids = [field_id for field_id in field_ids if field_id]
if not ids:
return {}
try:
response = await elasticsearch.search(
index="openalex-fields",
query={"terms": {"id": ids}},
source=["id", "display_name"],
size=len(ids),
cluster=ESCluster.NES,
)
except Exception:
logger.exception("Could not load dashboard field names.")
return {}
return {
source["id"]: source["display_name"]
for hit in response.get("hits", {}).get("hits", [])
if (source := hit.get("_source", {})).get("id")
and source.get("display_name")
}
def _topic_heatmap_field(
bucket: dict[str, Any],
years: list[int],
year_totals: dict[int, int],
field_names: dict[str, str],
) -> TopicHeatmapField:
field_id = str(bucket["key"])
by_year = {
int(year_bucket["key"]): int(year_bucket.get("doc_count", 0))
for year_bucket in (
bucket.get("works", {}).get("by_year", {}).get("buckets", [])
)
if year_bucket.get("key") is not None
}
values = []
for year in years:
count = by_year.get(year, 0)
total = year_totals.get(year, 0)
values.append(
TopicHeatmapValue(
year=year,
count=count,
share=(count / total) if total else 0,
)
)
return TopicHeatmapField(
id=field_id,
name=_field_name(bucket, field_names.get(field_id, field_id)),
total=int(bucket.get("works", {}).get("doc_count", 0)),
values=values,
)
def _field_name(bucket: dict[str, Any], fallback: str) -> str:
name_buckets = bucket.get("field_name", {}).get("buckets", [])
if name_buckets and name_buckets[0].get("key"):
return str(name_buckets[0]["key"])
return fallback
def _short_author_id(value: str) -> str:
return value.replace("https://openalex.org/", "").strip().upper()
def _top_work_authors(
authors: list[dict[str, Any]],
works_period: WorksPeriod,
) -> list[TopAuthor]:
if works_period == "last_5_years":
from_year = datetime.now().year - 4
ranked_authors = sorted(
(
{
**author,
"selected_works_count": _works_count_since(author, from_year),
}
for author in authors
),
key=lambda author: author["selected_works_count"],
reverse=True,
)
else:
ranked_authors = [
{**author, "selected_works_count": author["works_count"]}
for author in authors
]
return [
TopAuthor(
id=_short_author_id(author["id"]),
name=author["name"],
count=author["selected_works_count"],
)
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
if author["selected_works_count"] > 0
]
def _works_count_since(author: dict[str, Any], from_year: int) -> int:
return sum(
int(item.get("works_count", 0) or 0)
for item in author.get("counts_by_year", [])
if int(item.get("year", 0) or 0) >= from_year
)
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
try:
return await _institution_authors(institution_id)
except Exception:
logger.exception("Could not load authors for institution %s.", institution_id)
return []
async def _safe_institution_aliases(
institution_id: str,
organization_name: str,
) -> list[str]:
try:
return await _institution_aliases(institution_id, organization_name)
except Exception:
logger.exception("Could not load aliases for institution %s.", institution_id)
return [organization_name]
async def _institution_authors(institution_id: str) -> list[dict[str, Any]]:
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
query={
"nested": {
"path": "last_known_institutions",
"query": {"term": {"last_known_institutions.id": institution_id}},
}
},
source=["id", "display_name", "works_count", "counts_by_year"],
size=10000,
sort=[{"works_count": {"order": "desc", "missing": "_last"}}],
cluster=ESCluster.NES,
)
return [
{
"id": str(source["id"]),
"name": str(source["display_name"]),
"works_count": int(source.get("works_count", 0)),
"counts_by_year": source.get("counts_by_year", []) or [],
}
for hit in response.get("hits", {}).get("hits", [])
if (source := hit.get("_source", {})).get("id")
and source.get("display_name")
]
async def _top_project_authors(
authors: list[dict[str, Any]],
aliases: list[str],
) -> list[TopAuthor]:
if not aliases:
return []
counts: dict[str, int] = {}
names: dict[str, str] = {}
for bucket in await _top_dfg_project_author_buckets(aliases):
key = str(bucket.get("key", "")).strip()
if key:
normalized_key = key.casefold()
names[normalized_key] = key
counts[normalized_key] = counts.get(normalized_key, 0) + int(
bucket.get("doc_count", 0)
)
institution_authors = {author["name"].casefold(): author for author in authors}
ranked = sorted(
(
(name, count)
for name, count in counts.items()
if count > 0
),
key=lambda item: (-item[1], names[item[0]].casefold()),
)
return [
TopAuthor(
id=(
_short_author_id(institution_authors[name]["id"])
if name in institution_authors
else None
),
name=(
institution_authors[name]["name"]
if name in institution_authors
else names[name]
),
count=count,
)
for name, count in ranked[:TOP_AUTHOR_LIMIT]
]
async def _top_dfg_project_author_buckets(
aliases: list[str],
) -> list[dict[str, Any]]:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
body={
"size": 0,
"query": _dfg_institution_query(aliases),
"aggs": {
"people": {
"terms": {
"script": {
"lang": "painless",
"source": _dfg_involved_persons_script(),
},
"size": 10000,
}
}
},
},
cluster=ESCluster.INSE,
)
return (
response.get("aggregations", {}).get("people", {}).get("buckets", [])
)
def _dfg_involved_persons_script() -> str:
return (
"def names = new HashSet(); "
"def value = params['_source'].containsKey('Beteiligte Personen') "
" ? params['_source']['Beteiligte Personen'] : null; "
"if (value instanceof String && value.length() > 0) { "
" for (name in value.splitOnToken(';')) { "
" def trimmed = name.trim(); "
" if (trimmed.length() > 0) { names.add(trimmed); } "
" } "
"} "
"return new ArrayList(names);"
)
async def _top_patent_authors(institution_id: str) -> list[TopAuthor]:
client = OrgPatentsSearchClient()
authors = await client.top_authors_by_institution(
institution_id=institution_id,
size=TOP_AUTHOR_LIMIT,
)
return [
TopAuthor(
id=_short_author_id(author["id"]),
name=author["name"],
count=author["count"],
)
for author in authors
]
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
if not authors:
return []
author_names = [author["name"] for author in authors]
response = await elasticsearch.search(
index="aktuell_postproc",
body={
"size": 0,
"query": {"terms": {"authors.keyword": author_names}},
"aggs": {
"authors": {
"terms": {
"field": "authors.keyword",
"size": 10000,
"order": [
{"_count": "desc"},
{"_key": "asc"},
],
}
}
},
},
cluster=ESCluster.INSE,
)
buckets = response.get("aggregations", {}).get("authors", {}).get("buckets", [])
institution_authors = {author["name"].casefold(): author for author in authors}
return [
TopAuthor(
id=_short_author_id(institution_authors[str(bucket["key"]).casefold()]["id"]),
name=institution_authors[str(bucket["key"]).casefold()]["name"],
count=int(bucket.get("doc_count", 0)),
)
for bucket in buckets
if str(bucket.get("key", "")).casefold() in institution_authors
][:TOP_AUTHOR_LIMIT]
@@ -0,0 +1,581 @@
from unittest.mock import AsyncMock, patch
from datetime import datetime
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
get_dashboard_organization,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
)
from inse.model import ESCluster, ESIndex
ORG_INSTITUTION_ID = "https://openalex.org/I123"
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
index = kwargs["index"]
if index == config.settings.openalex_works_search_index:
return {"hits": {"total": {"value": 120}}}
if index == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"total": {"value": 35}}}
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
return {"aggregations": {"projects": {"value": 10}}}
if index == ESIndex.PROJECTS_BUND_V1:
return {"hits": {"total": {"value": 5}}}
return {"hits": {"total": {"value": 3}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University", "Example Uni"]),
):
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"publications": 120,
"persons": 35,
"projects": 18,
"dfg_projects": 3,
"eu_projects": 10,
"bmbf_projects": 5,
}
calls = mocked_search.await_args_list
assert calls[0].kwargs["index"] == config.settings.openalex_works_search_index
assert calls[0].kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert calls[1].kwargs["query"]["nested"]["query"]["term"] == {
"affiliations.institution.id": ORG_INSTITUTION_ID
}
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in calls[2:])
assert [call.kwargs["index"] for call in calls[2:]] == [
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
]
assert calls[2].kwargs["body"]["query"] == {
"terms": {
"name.keyword": [
"EXAMPLE ORG",
"EXAMPLE UNI",
"EXAMPLE UNIVERSITY",
]
}
}
assert calls[3].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[3].kwargs["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
assert calls[4].kwargs["query"]["bool"]["minimum_should_match"] == 1
assert calls[4].kwargs["query"]["bool"]["should"][0]["bool"]["should"][0][
"match"
] == {
"Antragstellende Institution": {
"query": "Example Org",
"operator": "and",
}
}
@pytest.mark.anyio
async def test_top_authors_maps_works_and_dfg_project_aggregations():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 42,
"counts_by_year": [],
}
},
{
"_source": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
"works_count": 12,
"counts_by_year": [],
}
},
]
}
}
if kwargs["index"] == "aktuell_postproc":
return {
"aggregations": {
"authors": {
"buckets": [{"key": "Ada Example", "doc_count": 6}]
}
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [{"key": "Grace Example", "doc_count": 3}]
}
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(
return_value=[
{"id": "A1", "name": "Ada Example", "count": 4},
]
),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 42,
}
assert result.projects[0].model_dump() == {
"id": "A2",
"name": "Grace Example",
"count": 3,
}
assert result.patents[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 4,
}
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 6,
}
project_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
assert project_calls[0].kwargs["body"]["query"]["bool"][
"minimum_should_match"
] == 1
assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
"people"
]["terms"]["script"]["source"]
@pytest.mark.anyio
async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [{"key": "Project Person", "doc_count": 9}]
}
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert result.projects[0].model_dump() == {
"id": None,
"name": "Project Person",
"count": 9,
}
@pytest.mark.anyio
async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [
{"key": f"Project Person {count}", "doc_count": count}
for count in range(1, 12)
]
}
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert [author.count for author in result.projects] == list(range(11, 1, -1))
assert result.projects[0].name == "Project Person 11"
assert len(result.projects) == 10
@pytest.mark.anyio
async def test_top_authors_combines_dfg_involved_people_case_insensitively():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 1,
"counts_by_year": [],
}
}
]
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [
{"key": "Ada Example", "doc_count": 2},
{"key": "ada example", "doc_count": 3},
{"key": "DFG Person", "doc_count": 4},
]
}
}
}
return {"aggregations": {"authors": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert [author.model_dump() for author in result.projects] == [
{"id": "A1", "name": "Ada Example", "count": 5},
{"id": None, "name": "DFG Person", "count": 4},
]
@pytest.mark.anyio
async def test_top_authors_returns_partial_response_when_one_source_fails():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 42,
"counts_by_year": [],
}
}
]
}
}
raise RuntimeError("projects unavailable")
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert result.works[0].name == "Ada Example"
assert result.projects == []
assert result.patents == []
assert result.news == []
@pytest.mark.anyio
async def test_top_authors_can_rank_works_by_last_five_years():
current_year = datetime.now().year
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 100,
"counts_by_year": [
{"year": current_year - 6, "works_count": 90},
{"year": current_year - 1, "works_count": 2},
],
}
},
{
"_source": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
"works_count": 50,
"counts_by_year": [
{"year": current_year - 1, "works_count": 12},
{"year": current_year, "works_count": 4},
],
}
},
]
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
works_period="last_5_years",
)
assert result.works[0].model_dump() == {
"id": "A2",
"name": "Grace Example",
"count": 16,
}
assert result.works[1].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 2,
}
@pytest.mark.anyio
async def test_topic_heatmap_maps_field_year_counts_and_shares():
async def search(**kwargs):
if kwargs["index"] == config.settings.openalex_works_search_index:
return {
"aggregations": {
"publication_years": {
"buckets": [
{"key": 2023, "doc_count": 10},
{"key": 2024, "doc_count": 20},
]
},
"topics_nested": {
"fields": {
"buckets": [
{
"key": "https://openalex.org/fields/17",
"field_name": {
"buckets": [
{
"key": "Computer Science",
"doc_count": 12,
}
]
},
"works": {
"doc_count": 12,
"by_year": {
"buckets": [
{"key": 2023, "doc_count": 4},
{"key": 2024, "doc_count": 8},
]
},
},
}
]
}
},
}
}
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/fields/17",
"display_name": "Computer Science",
}
}
]
}
}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search:
result = await get_topic_heatmap(
institution_id=ORG_INSTITUTION_ID,
organization_name="Example Org",
from_year=2023,
to_year=2024,
limit=10,
)
assert result.institution_id == ORG_INSTITUTION_ID
assert result.organization_name == "Example Org"
assert result.years == [2023, 2024]
assert result.fields[0].model_dump() == {
"id": "https://openalex.org/fields/17",
"name": "Computer Science",
"total": 12,
"values": [
{"year": 2023, "count": 4, "share": 0.4},
{"year": 2024, "count": 8, "share": 0.4},
],
}
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["must"][0]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["terms"]["field"]
== "topics.field.id"
)
@pytest.mark.anyio
async def test_topic_heatmap_defaults_to_last_five_years():
async def search(**kwargs):
if kwargs["index"] == config.settings.openalex_works_search_index:
return {
"aggregations": {
"publication_years": {"buckets": []},
"topics_nested": {"fields": {"buckets": []}},
}
}
return {"hits": {"hits": []}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search:
result = await get_topic_heatmap(
institution_id=ORG_INSTITUTION_ID,
organization_name="Example Org",
)
current_year = datetime.now().year
assert result.years == list(range(current_year - 4, current_year + 1))
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
"gte": current_year - 4,
"lte": current_year,
}
def test_get_dashboard_organization_uses_effective_organization():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(
name="Example University",
openalex_institution_id="I456",
)
session.add(organization)
session.commit()
session.refresh(organization)
token = _access_token(organization.id)
result = get_dashboard_organization(session, token)
assert result.id == organization.id
assert result.openalex_institution_id == "I456"
def test_get_dashboard_organization_rejects_missing_openalex_id():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
organization = Organization(name="Example University")
session.add(organization)
session.commit()
session.refresh(organization)
with pytest.raises(HTTPException) as exc_info:
get_dashboard_organization(session, _access_token(organization.id))
assert exc_info.value.status_code == 422
def _access_token(organization_id):
return AccessToken(
real_account_id=organization_id,
effective_account_id=organization_id,
effective_role=UserRole.USER,
effective_organization_id=organization_id,
expires_at="2099-01-01T00:00:00Z",
epoch=0,
user_fingerprint_hash="hash",
raw_token="token",
)
+73
View File
@@ -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
@@ -15,9 +16,81 @@ engine = create_engine(
)
def _migrate_secret_table():
"""Upgrade the legacy login-only secret table without losing its data."""
columns = {column["name"] for column in inspect(engine).get_columns("secret")}
required_columns = {
"purpose",
"request_count",
"request_window_started_at",
}
if required_columns.issubset(columns):
return
# SQLite cannot alter a UNIQUE constraint in place. Rebuild the table so an
# account can hold both a login OTK and a password-reset secret.
with engine.begin() as connection:
connection.execute(text("ALTER TABLE secret RENAME TO secret_legacy"))
connection.execute(
text(
"""
CREATE TABLE secret (
id CHAR(32) NOT NULL PRIMARY KEY,
account_id CHAR(32) NOT NULL,
purpose VARCHAR NOT NULL,
secret_value VARCHAR NOT NULL,
expires_at DATETIME NOT NULL,
request_count INTEGER NOT NULL DEFAULT 0,
request_window_started_at DATETIME,
CONSTRAINT uq_secret_account_purpose
UNIQUE (account_id, purpose),
FOREIGN KEY(account_id) REFERENCES account (id)
)
"""
)
)
connection.execute(
text(
"""
INSERT INTO secret (
id, account_id, purpose, secret_value, expires_at,
request_count, request_window_started_at
)
SELECT id, account_id, 'LOGIN_OTK', secret_value, expires_at,
0, NULL
FROM secret_legacy
"""
)
)
connection.execute(text("DROP TABLE secret_legacy"))
connection.execute(
text("CREATE INDEX ix_secret_account_id ON secret (account_id)")
)
connection.execute(text("CREATE INDEX ix_secret_purpose ON secret (purpose)"))
connection.execute(
text("CREATE INDEX ix_secret_expires_at ON secret (expires_at)")
)
connection.execute(
text(
"CREATE INDEX ix_secret_request_window_started_at "
"ON secret (request_window_started_at)"
)
)
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
_migrate_secret_table()
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():
@@ -5,8 +5,6 @@
"""
from typing import Any
import httpx
from .. import config
from inse.integrations import elasticsearch
from inse.model import ESCluster
@@ -18,17 +16,11 @@ from inse.exceptions import MissingApiKeyError
class FundedPublicationsSearchClient:
def __init__(
self,
base_url: str | None = None,
index: str | None = None,
api_key: str | None = None,
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.elasticsearch_url or "").rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.elasticsearch_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@staticmethod
def indexed_author_id(author_id: str) -> str:
@@ -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,
}
}
@@ -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"}
+93 -6
View File
@@ -1,25 +1,31 @@
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,
model: str = None,
timeout: int = 30,
json_schema = None,
schema_name = None,
timeout: int = 120,
temperature: float = 1.0,
top_p: float = 0.95,
) -> str:
if model is None:
model = config.settings.llm_model
response_format = None
if json_schema is not None:
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
client = OpenAI(
base_url=config.settings.llm_api_url,
api_key=config.settings.llm_api_key,
timeout=timeout,
)
try:
response = client.chat.completions.create(
model=model,
@@ -27,10 +33,10 @@ def call(
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
response_format=response_format
)
except APIConnectionError:
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
@@ -38,3 +44,84 @@ def call(
return response.choices[0].message.content or (
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
)
def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]:
response_format = {
"type": "json_schema",
"json_schema": {
"name": schema_name or "response",
"strict": True,
"schema": schema,
},
}
return response_format
async def call_stream(
system_prompt: str,
user_prompt: str,
emit,
model: str = None,
json_schema=None,
schema_name=None,
timeout: int = 120,
temperature: float = 1.0,
top_p: float = 0.95,
) -> str:
if model is None:
model = config.settings.llm_model
response_format = None
if json_schema is not None:
response_format = _get_response_format(schema=json_schema, schema_name=schema_name)
client = AsyncOpenAI(
base_url=config.settings.llm_api_url,
api_key=config.settings.llm_api_key,
timeout=timeout,
)
full_content = ""
try:
stream = await client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
response_format=response_format,
stream=True,
)
try:
async for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
full_content += delta
await emit({"type": "llm_chunk", "content": delta})
finally:
# Always release the underlying HTTP connection, whether we
# finished normally, timed out, were cancelled, or emit()
# failed because the client disconnected. This is what
# actually tells the backend to stop generating.
await stream.close()
except APIConnectionError as e:
print(f"Connection error: {e}")
return ""
except asyncio.CancelledError:
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
# from the router)
raise
except Exception as e:
import traceback
print(f"LLM streaming failed: {type(e).__name__}: {e}")
traceback.print_exc()
return ""
return full_content
@@ -0,0 +1,58 @@
# inse/keywords/file_extraction.py
import base64
import logging
import httpx
from bs4 import BeautifulSoup
# import fitz
import io
from pypdf import PdfReader
from pypdf.errors import PdfReadError
logger = logging.getLogger(__name__)
def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str:
try:
raw = base64.b64decode(content_base64)
except Exception:
logger.warning("Failed to decode base64 for %s", filename)
return f"[{filename}: could not decode upload]"
if mime_type == "application/pdf" or filename.lower().endswith(".pdf"):
return _extract_pdf_text(filename, raw)
try:
return raw.decode("utf-8", errors="replace")
except Exception:
logger.warning("Failed to decode %s as text", filename)
return f"[{filename}: unsupported or undecodable content]"
def _extract_pdf_text(filename: str, raw: bytes) -> str:
try:
reader = PdfReader(io.BytesIO(raw), strict=False) # non-strict: tolerate minor spec violations
except Exception as e:
logger.warning("Failed to open PDF %s: %s", filename, e)
return f"[{filename}: PDF could not be opened (corrupted or invalid)]"
if reader.is_encrypted:
try:
# Attempt to decrypt with an empty password (common for "owner-locked"
# PDFs that don't require one to read content)
reader.decrypt("")
except Exception as e:
logger.warning("Encrypted PDF %s could not be decrypted: %s", filename, e)
return f"[{filename}: PDF is encrypted and could not be read]"
parts = []
for page_num, page in enumerate(reader.pages):
try:
parts.append(page.extract_text() or "")
except PdfReadError as e:
logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
except Exception as e:
logger.warning("Unexpected error extracting page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
return "\n".join(parts)
+434
View File
@@ -0,0 +1,434 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for persons / authors.
"""
import asyncio
from typing import Any, Dict, List
import partial_json_parser
import json
import logging
import time
import httpx
from bs4 import BeautifulSoup
from pydantic import ValidationError
from typing import Awaitable, Callable
from inse.keywords.prompts import KeywordsPrompt
from inse.integrations import llm
from inse.keywords.model import (
ExtractedKeywords,
ExtractedKeywordsLLM,
ExtractedKeywordsResponse,
KeywordEntry,
KeywordEntryWithTopic,
KeywordsWsEvent,
FileUpload,
)
from inse.keywords.extract_text import extract_text_from_upload
from inse.topics.logic import vector_search_topics_batch
logger = logging.getLogger(__name__)
EventCallback = Callable[[dict], Awaitable[None]]
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
def _build_enriched_snapshot(
confirmed: Dict[str, List[KeywordEntryWithTopic]],
) -> ExtractedKeywords:
return ExtractedKeywords.model_validate(
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
)
async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords:
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {
level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)]
for level in LEVELS
}
keywords: List[str] = []
positions: List[tuple[str, int]] = []
for level in LEVELS:
for idx, entry in enumerate(getattr(results, level)):
keywords.append(entry.keyword)
positions.append((level, idx))
if keywords:
matches = await vector_search_topics_batch(keywords=keywords, search_type="hybrid")
for (level, idx), match in zip(positions, matches.results):
confirmed[level][idx].topic_mapping = match
return _build_enriched_snapshot(confirmed)
async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse:
"""
Extracts keywords from the given text or URL using a language model.
"""
start_time = time.time()
if mode == "url":
text = await get_text_from_url(query)
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
else:
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
text = query
user_prompt = f"""
Now analyze the following text and return ONLY the JSON object.\n"""
if limit:
user_prompt +=f"Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n"
user_prompt += f"""Input:{text}"""
keywords = llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema = ExtractedKeywordsLLM.model_json_schema(),
schema_name = "extracted_keywords",
temperature=0.8,
top_p=0.95,
)
keywords_json = json.loads(keywords)
validated = ExtractedKeywordsLLM.model_validate(keywords_json)
enriched = await _enrich_llm_keywords(validated)
elapsed_time = time.time() - start_time
logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds")
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
async def extract_keywords_stream_enriched(
query: str,
mode: str,
limit: int,
emit: EventCallback,
files: List[FileUpload] | None = None,
) -> ExtractedKeywordsResponse:
start_time = time.time()
timeout_seconds = 120
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
enrichment_tasks: List[asyncio.Task] = []
async def emit_full_results() -> None:
try:
validated = _build_enriched_snapshot(confirmed)
except ValidationError:
return
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
try:
topic = await vector_search_topics_batch(
keywords=[item.keyword],
search_type="hybrid",
)
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
await emit_full_results()
except asyncio.CancelledError:
raise
except Exception as e:
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results()
def make_on_chunk(base_offset: Dict[str, int]):
"""
Builds an on_chunk callback for a single streaming LLM call.
`base_offset` records how many items each level already had in the
shared `confirmed` list *before* this call started, so growth from
this call's own (independent) partial JSON can be tracked correctly
even though `confirmed` keeps accumulating across multiple calls
(one per file).
"""
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 []
# How many items belonging to *this* call have already been
# appended to the shared `confirmed` list.
local_have = len(confirmed[level]) - base_offset[level]
start_idx = len(confirmed[level])
while local_have < len(current):
raw_item = current[local_have]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
local_have += 1
grew = True
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
KeywordsWsEvent(
type="status",
step="enriching",
message=f"Extracting topic for keyword '{keyword_text}'",
).model_dump()
)
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
enrichment_tasks.append(task)
if grew:
await emit_full_results()
return on_chunk
async def run_llm_extraction(text: str, system_prompt: str, label: str | None = None) -> None:
"""
Runs a single independent streaming LLM extraction call over `text`
and folds its results into the shared `confirmed` structure. Used
once for url/text mode, and once *per file* for file mode.
"""
base_offset = {level: len(confirmed[level]) for level in LEVELS}
on_chunk = make_on_chunk(base_offset)
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)
user_prompt = "\nNow analyze the following text.\n"
if limit:
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
user_prompt += f"\nInput:\n{text}"
suffix = f" for {label}" if label else ""
try:
keywords_raw = await asyncio.wait_for(
llm.call_stream(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=ExtractedKeywordsLLM.model_json_schema(),
schema_name="extracted_keywords",
temperature=0.0,
top_p=0.95,
emit=emit_wrapper,
),
timeout=timeout_seconds,
)
except asyncio.TimeoutError:
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call timed out{suffix}")
except asyncio.CancelledError:
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
raise
if not keywords_raw:
# 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=f"LLM call failed or returned no content{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call returned empty content{suffix}")
try:
json.loads(keywords_raw)
except json.JSONDecodeError as e:
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response{suffix}: {e}").model_dump())
raise RuntimeError(f"LLM response is not valid JSON{suffix}")
# ---------- Gather input text & run extraction(s) ----------
source_content = ""
try:
if mode == "url":
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
text = await get_text_from_url(query)
if text:
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
else:
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
raise RuntimeError(f"Failed to fetch content from {query}")
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT)
elif mode == "files":
provided_files = files or []
total_files = len(provided_files)
await emit(
KeywordsWsEvent(
type="status",
step="extracting_files",
message=f"Extrahiere Inhalt aus {total_files} Datei(en)",
).model_dump()
)
file_texts: List[str] = []
failed_files: List[str] = []
for i, f in enumerate(provided_files, start=1):
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
if not text or not text.strip():
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"Kein Text in '{f.filename}' gefunden, überspringe",
).model_dump()
)
failed_files.append(f.filename)
continue
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"'{f.filename}': {len(text)} Zeichen extrahiert ({i}/{total_files})",
).model_dump()
)
await emit(
KeywordsWsEvent(
type="status",
step="calling_llm",
message=f"Extrahiere Keywords aus '{f.filename}' ({i}/{total_files})",
).model_dump()
)
try:
# Each file gets its own, independent LLM call so
# keywords from one file can't dilute or get mixed up
# with the content of another. Results from every call
# still accumulate into the same shared `confirmed`
# structure, so they keep streaming to the client
# progressively as before.
await run_llm_extraction(
text,
KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT,
label=f"file '{f.filename}'",
)
file_texts.append(f"# {f.filename}\n\n{text}")
except asyncio.CancelledError:
raise
except Exception as e:
# Isolate failures: one broken/unparseable file shouldn't
# abort keyword extraction for the rest of the batch.
logger.error(f"Keyword extraction failed for file '{f.filename}': {e}")
failed_files.append(f.filename)
continue
if not file_texts:
await emit(KeywordsWsEvent(type="error", message="Kein Text konnte aus den Dateien extrahiert werden").model_dump())
raise RuntimeError("Failed to extract text from uploaded files")
if failed_files:
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"{len(failed_files)} Datei(en) konnten nicht verarbeitet werden: {', '.join(failed_files)}",
).model_dump()
)
source_content = "\n\n---\n\n".join(file_texts)
else:
text = query
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT)
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)
# ---------- Finalize ----------
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
await emit_full_results()
try:
final_validated = _build_enriched_snapshot(confirmed)
except ValidationError:
final_validated = ExtractedKeywords.model_validate(
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
)
elapsed_time = time.time() - start_time
result = ExtractedKeywordsResponse(
results=final_validated,
source=mode,
source_url=query if mode == "url" else None,
source_content=source_content,
duration=elapsed_time,
)
return result
async def get_text_from_url(url: str) -> str:
"""
Fetches the HTML content from the given URL using httpx and extracts visible text.
"""
try:
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/91.0.4472.124 Safari/537.36"
)
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for element in soup(["script", "style"]):
element.decompose()
text = soup.get_text(separator=" ", strip=True)
text = " ".join(text.split())
return text
except httpx.HTTPError as e:
logger.error(f"HTTP error for {url}: {e}")
except Exception as e:
logger.error(f"Error processing {url}: {e}")
async def _get_files_text(files: List[FileUpload]) -> str:
"""
Extracts and joins text from uploaded files. Runs blocking PDF parsing
in a thread so it doesn't stall the event loop.
NOTE: no longer used by extract_keywords_stream_enriched(), which now
extracts and processes each file independently so it can run a
separate LLM call per file. Kept here in case other callers still rely
on a single combined text blob.
"""
parts = []
for f in files:
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
parts.append(text)
return "\n\n---\n\n".join(parts)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for persons / authors.
"""
from typing import List, Literal
from pydantic import BaseModel, Field
from inse.topics.model import KeywordTopicMatch
class FileUpload(BaseModel):
filename: str = Field(description="The name of the uploaded file.")
content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
mime_type: str = Field(description="The MIME type of the uploaded file, e.g., 'application/pdf', 'image/png', etc.")
class KeywordsRequest(BaseModel):
query: str = Field(description="The input text from which to extract keywords.")
files: list[FileUpload] | None = None
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
# class KeywordsRequest(BaseModel):
# query: str = Field(description="The input text from which to extract keywords.")
# mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
# limit: int = Field(default=None, description="The maximum number of keywords to extract.")
class KeywordEntry(BaseModel):
keyword: str = Field(description="The extracted keyword.")
relevance_score: float = Field(description="The relevance score of the keyword.")
class KeywordEntryWithTopic(BaseModel):
llm_keyword: KeywordEntry = Field(description="The keyword extracted by the LLM.")
topic_mapping: KeywordTopicMatch | None = Field(
default=None,
description="The corresponding OpenAlex topic match for the keyword, if any.",
)
class ExtractedKeywords(BaseModel):
broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
class ExtractedKeywordsLLM(BaseModel):
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.")
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
class ExtractedKeywordsResponse(BaseModel):
results_llm: ExtractedKeywordsLLM | None = None
results: ExtractedKeywords | None = None
source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.")
source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.")
source_content: str = Field(description="The actual content from which keywords were extracted.")
duration: float | None = Field(default=None, description="The time taken to extract keywords, in seconds.")
class KeywordsWsEvent(BaseModel):
type: str
step: str | None = None
message: str | None = None
result: ExtractedKeywordsResponse | None = None
keywords: ExtractedKeywords | ExtractedKeywordsLLM | None = None
duration: float | None = None
completed: str | None = None
+617
View File
@@ -0,0 +1,617 @@
from enum import StrEnum
class KeywordsPrompt(StrEnum):
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval.
The extracted keywords should prioritize:
* Scientific domains
* Technologies
* Research fields
* Methods
* Applications
* Materials
* Standards
* Diseases
* Industrial sectors
* Technical concepts
Avoid generic business terms unless they are core topics of the text.
Examples of terms to avoid:
* Solution
* Platform
* Improvement
* Capability
* Innovation
* Process
* Service
* Performance
* Efficiency
unless they represent an actual searchable concept.
---
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
The output must be strictly extractive and grounded in the input text.
## Mandatory Rules
1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text.
2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text.
3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text.
Example:
Input contains:
"transformer-based machine learning framework"
Allowed:
* transformer-based machine learning framework
* machine learning
* transformer
Not allowed:
* Artificial Intelligence
* Deep Learning
* Neural Networks
unless those exact terms appear in the text.
4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text.
Example:
Input:
"large language models"
Allowed:
* large language models
Not allowed:
* LLMs
* Generative AI
* Artificial Intelligence
unless explicitly present.
5. Do NOT generate implied concepts.
Example:
Input:
"patient records"
Not allowed:
* Healthcare
* Medical Informatics
* Clinical Documentation
unless explicitly mentioned.
6. Every keyword must have direct textual evidence in the input.
7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output.
8. Prefer exact surface forms from the text.
9. Preserve original capitalization when possible.
10. Do not invent keywords to satisfy target counts.
11. When insufficient keywords exist for a level, return fewer keywords.
12. Grounding accuracy is more important than completeness.
13. Any keyword not directly supported by the text is considered an extraction error.
## Hierarchy Assignment Rules
The hierarchy is only an organizational grouping.
Do NOT create broader concepts to populate broad_keywords.
If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text.
Do not create abstraction layers that are not explicitly present in the document.
## Self-Validation Before Output
Before returning the final JSON, verify every keyword:
* Can this exact phrase be found in the input text?
* Can a user highlight the phrase directly in the source text?
If the answer is NO, remove the keyword.
---
# Keyword Hierarchy
## 1. broad_keywords
High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text.
Examples (only if explicitly mentioned):
* Artificial Intelligence
* Healthcare
* Biotechnology
* Renewable Energy
* Materials Science
* Robotics
These should represent the major themes of the document when those themes are explicitly stated.
---
## 2. coarse_grained
Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text.
Examples (only if explicitly mentioned):
* Machine Learning
* Drug Discovery
* Computer Vision
* Predictive Maintenance
* Smart Manufacturing
* Gene Editing
These should provide more specific context within the broad domains.
---
## 3. fine_grained
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text.
Examples (only if explicitly mentioned):
* Transformer Architecture
* CRISPR-Cas9
* Retrieval-Augmented Generation
* Lithium Iron Phosphate
* YOLOv8
* OPC UA
These should be the most specific and actionable concepts for literature retrieval.
---
# Relevance Score
Each keyword must include a relevance score.
Definition:
* 1.0 = central concept of the text
* 0.9 = extremely important concept
* 0.8 = highly relevant concept
* 0.7 = important supporting concept
* 0.6 = relevant secondary concept
* below 0.6 = use sparingly
Guidelines:
* Scores must be between 0.0 and 1.0.
* Use decimal precision up to 3 digits.
* Rank keywords by importance.
* The most important keywords should appear first.
* Broad keywords generally receive higher scores than secondary topics.
* Only include keywords with meaningful relevance.
---
# Extraction Rules
* Extract only concepts explicitly mentioned in the text.
* Do not use concepts that are merely implied, inferred, generalized, or derived.
* Every keyword must be directly traceable to text spans in the input.
* Prefer noun phrases.
* Avoid complete sentences.
* Avoid duplicates across levels whenever possible.
* Do not invent technologies not supported by the text.
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
* Return between 5 and 15 keywords per level when sufficient information exists.
* If fewer valid keywords exist, return fewer.
---
# Output Schema
Return ONLY valid JSON using the following structure:
{
"broad_keywords": [
{
"keyword": "string",
"relevance_score": 0.0
}
],
"coarse_grained": [
{
"keyword": "string",
"relevance_score": 0.0
}
],
"fine_grained": [
{
"keyword": "string",
"relevance_score": 0.0
}
]
}
Requirements:
* Return ONLY valid JSON.
* Do not include explanations.
* Do not include markdown.
* Do not include comments.
* Do not include reasoning.
* Do not include any text outside the JSON object.
* Every keyword must be directly supported by the input text.
* Any keyword not explicitly present in the source text must be excluded.
Return ONLY valid JSON matching the schema provided by the API.
---
# Example 1
Input:
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
Output:
broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]}
---
# Example 2
Input:
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
Output:
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]}
Return ONLY valid JSON matching the schema provided by the API.
"""
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
The extracted text may contain:
* Navigation menus
* Headers and footers
* Cookie notices
* Marketing language
* Contact information
* Repeated sections
* Calls to action
* Legal disclaimers
* Product pages
* Blog articles
* News articles
* Landing pages
Your first task is to identify the actual content and purpose of the webpage.
Ignore:
* Navigation elements
* Cookie banners
* Legal notices
* Copyright text
* Generic marketing statements
* Contact information
* Login/signup content
* Careers pages unless they contain relevant technical information
* Repeated website boilerplate
Focus only on the primary informational content of the webpage.
---
# STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY)
The output must be strictly extractive and grounded in the webpage text.
## Mandatory Rules
1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text.
2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text.
3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text.
Example:
Input:
"The platform uses large language models and retrieval-augmented generation."
Allowed:
* large language models
* retrieval-augmented generation
Not allowed:
* Artificial Intelligence
* Generative AI
* Natural Language Processing
unless explicitly present.
4. Do NOT generate synonyms.
Example:
Input:
"AI assistant"
Allowed:
* AI assistant
Not allowed:
* large language models
* conversational AI
* generative AI
unless those exact terms appear.
5. Do NOT generate canonical scientific terminology when it does not appear in the source text.
6. Do NOT rewrite marketing terms into technical terms.
7. Every keyword must have direct textual evidence in the webpage content.
8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output.
9. Preserve original wording whenever possible.
10. Do not invent keywords to satisfy target counts.
11. When insufficient keywords exist, return fewer keywords.
12. Grounding accuracy is more important than completeness.
13. Any keyword not directly supported by the webpage text is considered an extraction error.
---
# Step 1: Determine Page Type
Determine internally whether the page is:
* Technology/Product Page
* Company Page
* Research Article
* Scientific Blog Post
* News Article
* Technical Documentation
* White Paper
* Industry Report
* Other
Use this classification only to identify the relevant content and remove boilerplate.
Do NOT include the classification in the output.
---
# Step 2: Extract Searchable Concepts
Extract concepts directly present in the page that are useful for:
* OpenAlex retrieval
* Scientific literature discovery
* Patent scouting
* Technology scouting
* Innovation monitoring
The extracted concepts must remain faithful to the wording used in the webpage.
Do NOT replace webpage terminology with your own preferred terminology.
---
# Keyword Hierarchy
## broad_keywords
High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage.
Only use this level when such broad concepts are explicitly present.
Examples:
* Healthcare
* Biotechnology
* Manufacturing
* Robotics
* Financial Technology
only if those exact concepts appear in the webpage.
---
## coarse_grained
Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage.
Examples:
* Machine Learning
* Predictive Maintenance
* Drug Discovery
* Smart Manufacturing
* Clinical Decision Support
only if explicitly present.
---
## fine_grained
Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage.
Examples:
* FastAPI
* OpenAPI
* Pydantic
* CRISPR-Cas9
* Retrieval-Augmented Generation
* OPC UA
only if explicitly present.
---
# Relevance Score
Assign a relevance score between 0.0 and 1.0.
Guidelines:
* 1.00 = central topic of the webpage
* 0.90 = major topic
* 0.80 = highly relevant
* 0.70 = supporting concept
* 0.60 = secondary concept
Avoid scores below 0.60 unless necessary.
Rank keywords by importance.
---
# Extraction Rules
* Extract only concepts explicitly mentioned in the webpage text.
* Do not use concepts that are merely implied, inferred, generalized, or derived.
* Every keyword must be directly traceable to text spans in the webpage.
* Prefer noun phrases.
* Avoid complete sentences.
* Avoid duplicates across hierarchy levels whenever possible.
* Preserve original wording.
* Rank keywords by importance.
* Return between 5 and 15 keywords per level when sufficient information exists.
* If fewer valid keywords exist, return fewer.
---
# Self-Validation Before Output
For every keyword, verify:
* Can this exact phrase be found in the webpage text?
* Can a user highlight the phrase directly in the extracted content?
If the answer is NO, remove the keyword.
---
# Example — Technical Documentation
Input:
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
Output:
{"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]}
Return ONLY valid JSON matching the schema provided by the API.
"""
SIMPLE_TEXT_PROMPT = """
You are a scientific and technology intelligence expert. Extract keywords from the given text into three hierarchical levels. Each keyword must include a relevance_score (0.0–1.0) indicating centrality.
**Levels:**
- **broad_keywords** – high‑level domains/industries (e.g., Artificial Intelligence, Healthcare, Renewable Energy).
- **coarse_grained** – mid‑level technologies/methods/applications (e.g., Machine Learning, Drug Discovery, Smart Manufacturing).
- **fine_grained** – specific technical concepts, algorithms, materials, protocols (e.g., Transformer Architecture, CRISPR‑Cas9, Retrieval‑Augmented Generation).
**Guidelines:**
- Prioritize scientific, technical, and research‑oriented terminology.
- Avoid generic business fluff: "solution", "platform", "improvement", "service", "performance" – unless they are explicit searchable concepts.
- Prefer noun phrases; avoid complete sentences.
- Extract 5–15 keywords per level when possible.
- Rank by importance (higher scores first).
**Relevance scores:**
- 1.0 = central topic
- 0.9 = extremely important
- 0.8 = highly relevant
- 0.7 = supporting concept
- 0.6 = secondary
- Below 0.6 – use sparingly.
**Output schema (JSON only):**
{
"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],
"coarse_grained": [...],
"fine_grained": [...]
}
**Example:**
Input: Researchers developed a transformer-based ML framework for predictive maintenance in smart factories using sensor fusion and anomaly detection.
Output:
{
"broad_keywords": [{"keyword": "Artificial Intelligence", "relevance_score": 0.98}, {"keyword": "Manufacturing", "relevance_score": 0.94}],
"coarse_grained": [{"keyword": "Predictive Maintenance", "relevance_score": 0.95}, {"keyword": "Anomaly Detection", "relevance_score": 0.85}],
"fine_grained": [{"keyword": "Transformer Architecture", "relevance_score": 0.95}, {"keyword": "Sensor Fusion", "relevance_score": 0.82}]
}
Return ONLY the JSON object, nothing else.
"""
SIMPLE_WEBSITE_PROMPT = """
You are a technology scout and scientific analyst. The input is text scraped from a webpage (using BeautifulSoup or similar). Your goal: extract keywords into three hierarchical levels, just like the text prompt, but with extra care to ignore website boilerplate.
**Ignore:**
- Navigation menus, headers/footers, cookie banners, legal disclaimers, copyright notices.
- Generic marketing language, calls-to-action, contact details, login/signup content.
- Repeated site templates or boilerplate.
**Focus only on:**
- Technologies, research areas, scientific methods, products, applications, industrial sectors, materials, standards, diseases, engineering disciplines, innovation domains.
- Prefer canonical scientific terms over marketing buzzwords (e.g., "Large Language Models" instead of "AI Assistant").
**Hierarchy and relevance scores** are the same as in the text prompt (broad → coarse → fine, scores 0.0–1.0).
**Output schema (JSON only):**
'''{"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],"coarse_grained": [...],"fine_grained": [...]}'''
**Example (company website):**
Input: Stripe provides payment infrastructure for businesses, supporting processing, billing, fraud prevention, and global commerce.
Output:
{"broad_keywords": [{"keyword": "Financial Technology", "relevance_score": 0.98}, {"keyword": "Business Services", "relevance_score": 0.91}],"coarse_grained": [{"keyword": "Payment Processing", "relevance_score": 0.97}, {"keyword": "Digital Payments", "relevance_score": 0.95}],"fine_grained": [{"keyword": "Stripe Platform", "relevance_score": 0.99}, {"keyword": "Fraud Prevention", "relevance_score": 0.91}]}
**Return ONLY the JSON object, nothing else.**
- Nno leading/trailing spaces, newlines, or any text before or after. NO IDENTATION, justa stringified JSON
"""
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for persons / authors.
"""
import asyncio
from typing import Annotated
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
from uvicorn.protocols.utils import ClientDisconnected
from . import logic
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
import logging
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/api/inse-service",
tags=["Keywords"],
responses={404: {"description": "Not found"}},
)
@router.websocket("/keywords/extract/ws")
async def extract_keywords_ws(websocket: WebSocket):
await websocket.accept()
disconnected = asyncio.Event()
extraction_task: asyncio.Task | None = None
def _is_socket_open() -> bool:
return not disconnected.is_set() and websocket.application_state.name != "DISCONNECTED"
async def emit(event: dict):
if not _is_socket_open():
return
try:
await websocket.send_json(event)
except (WebSocketDisconnect, ClientDisconnected):
disconnected.set()
async def safe_send(payload: dict):
if not _is_socket_open():
return
try:
await websocket.send_json(payload)
except (WebSocketDisconnect, ClientDisconnected):
disconnected.set()
try:
raw = await websocket.receive_json()
request = KeywordsRequest(**raw)
extraction_task = asyncio.create_task(
logic.extract_keywords_stream_enriched(
query=request.query,
mode=request.mode,
limit=request.limit,
files=request.files,
emit=emit,
)
)
result = await extraction_task
await safe_send({
"type": "completed",
"result": result.model_dump(),
})
except (WebSocketDisconnect, ClientDisconnected):
disconnected.set()
logger.info("Client disconnected from keyword extraction ws")
except Exception as e:
disconnected.set()
logger.exception("Error in keyword extraction ws")
await safe_send({
"type": "error",
"message": str(e),
})
finally:
if extraction_task is not None and not extraction_task.done():
extraction_task.cancel()
try:
await extraction_task
except (asyncio.CancelledError, Exception):
pass
if _is_socket_open():
try:
await websocket.close()
except RuntimeError:
logger.debug("WebSocket already closed, skipping close()")
@router.post(
"/keywords/extract",
operation_id="extractKeywords",
response_model=ExtractedKeywordsResponse,
summary="Extracts keywords from text.",
response_model_exclude_none=True,
)
async def extract_keywords(
request: Annotated[
KeywordsRequest,
Body(description="Input text for keyword extraction")
],
):
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
-1
View File
@@ -7,7 +7,6 @@ web service.
from typing import List
import logging
import httpx
import json
from . import config
+28 -7
View File
@@ -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,12 +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.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.bookmarks.router import router as bookmarks_router
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
@@ -45,7 +46,14 @@ from inse.auth.service import create_predefined_accounts
from . import config
from .service import router as service_router
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
from inse.patents.org.service import router as org_patents_router
from inse.patents.service import (
institution_patents_router,
patents_router as patents_all_router,
router as patents_service_router,
)
from inse.works.purpose_router import router as works_purpose_router
logger = logging.getLogger(__name__)
@@ -73,8 +81,11 @@ app = FastAPI(
lifespan=lifespan,
)
app.include_router(collaboration_network_router)
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(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)
@@ -84,12 +95,16 @@ app.include_router(patents_service_router)
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)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(dashboard_router)
app.include_router(bookmarks_router)
app.add_middleware(
ETagCacheMiddleware,
@@ -107,6 +122,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)})
@@ -115,13 +131,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)
+79 -74
View File
@@ -1,74 +1,79 @@
# 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", "/api/bookmarks")
):
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,
)
+15 -1
View File
@@ -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,9 +43,14 @@ 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"
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
Binary file not shown.
@@ -39,6 +39,7 @@ class Topic(BaseModel):
keywords: Optional[List[StrictStr]] = Field(default=None, description="Keywords representing the content of papers in the topic.")
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
@@ -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,
+56 -20
View File
@@ -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
+10 -1
View File
@@ -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):
@@ -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)
@@ -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()
@@ -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")
@@ -0,0 +1 @@
"""Global patent listing."""
+211
View File
@@ -0,0 +1,211 @@
"""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
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
enrich_patents_classifications,
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,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.AllPatentsResponse:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
try:
if source == "EPO":
epo_data = await all_patents_client.search_epo(
all_patents_client.epo_query(page, size, search, sort_direction, year_from, year_to)
)
patents = parse_epo_hits(epo_data)
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
elif source == "USPTO":
uspto_data = await all_patents_client.search_uspto(
all_patents_client.uspto_query(page, size, search, sort_direction, year_from, year_to)
)
patents = parse_uspto_hits(uspto_data)
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
else:
half = size // 2
epo_data, uspto_data = await asyncio.gather(
all_patents_client.search_epo(
all_patents_client.epo_query(page, half, search, sort_direction, year_from, year_to)
),
all_patents_client.search_uspto(
all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to)
),
)
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
total = (
epo_data.get("hits", {}).get("total", {}).get("value", 0)
+ uspto_data.get("hits", {}).get("total", {}).get("value", 0)
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
await enrich_patents_classifications(patents, ipc_search_client)
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,
page=page,
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]
@@ -0,0 +1,55 @@
"""Business logic for global patent listing."""
from fastapi import APIRouter
from inse.patents.all import logic
from inse.patents.common import model
router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
@router.get(
"/patents",
operation_id="getAllPatents",
response_model=model.AllPatentsResponse,
summary="Get all patents with pagination and search.",
)
async def get_all_patents(
page: int = 0,
size: int = 10,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
):
return await logic.get_all_patents(
page=page,
size=size,
search=search,
source=source,
sort_by=sort_by,
sort_direction=sort_direction,
year_from=year_from,
year_to=year_to,
)
@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,
)
@@ -0,0 +1 @@
"""Patent lookup by inventor."""
@@ -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
@@ -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)
@@ -0,0 +1,151 @@
"""Business logic for patent lookup by inventor."""
import asyncio
import logging
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.patents.authors.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,
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
from inse.persons import logic as person_logic
from inse.models.openalex.author import Author
logger = logging.getLogger(__name__)
async def get_patents_by_author_id(
author_id: str,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentsByAuthorResponse:
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
author = 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
if not author_name or not author_name.strip():
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=0,
patents=[],
)
try:
epo_data, uspto_data = await _search_both_indices(search_client, author_name)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
all_patents = deduplicate_patents(all_patents)
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(filtered),
patents=[item.patent for item in filtered],
)
async def _search_both_indices(client, display_name: str):
return await asyncio.gather(
client.search_epo(client.epo_query_by_inventor(display_name)),
client.search_uspto(client.uspto_query_by_inventor(display_name)),
)
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
@@ -0,0 +1,365 @@
"""Inventor name normalization and matching."""
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,
)
def tokens_equal(
left: str | None,
right: str | None,
*,
allow_initial: bool = True,
) -> bool:
left_variants = name_token_variants(left)
right_variants = name_token_variants(right)
if not left_variants or not right_variants:
return False
if left_variants & right_variants:
return True
if not allow_initial:
return False
return _initial_tokens_match(left, right)
def _initial_letter(token: str | None) -> str | None:
normalized = normalize_name_part(token)
if len(normalized) == 1 and normalized.isalpha():
return normalized
return None
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
left_initial = _initial_letter(left)
right_initial = _initial_letter(right)
left_full = normalize_name_part(left)
right_full = normalize_name_part(right)
if left_initial and right_full and len(right_full) > 1:
return right_full.startswith(left_initial)
if right_initial and left_full and len(left_full) > 1:
return left_full.startswith(right_initial)
if left_initial and right_initial:
return left_initial == right_initial
return False
def inventor_first_token(inventor_name: str) -> str:
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 ""
parts = inventor_name.split()
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 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]:
if not value or not value.strip():
return []
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
key = candidate.casefold()
if candidate.strip() and key not in seen:
seen.add(key)
ordered.append(candidate.strip())
_add(value.strip())
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in patent_transliteration_expansions(normalized):
_add(variant.title())
if normalized and len(normalized) > 1:
_add(normalized[0].upper())
return ordered
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
if not inventor_name or not last_name:
return False
if first_name:
return name_matches_person(inventor_name, f"{first_name} {last_name}")
return name_matches_person(inventor_name, last_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
)
]
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
# 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
@@ -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
@@ -0,0 +1,212 @@
"""Elasticsearch query builders for inventor-based patent search."""
from typing import Any
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
def _match_name_field(field: str, name: str) -> dict[str, Any]:
variants = search_name_variants(name)
if len(variants) <= 1:
return {"match": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {field: variant}} for variant in variants],
"minimum_should_match": 1,
}
}
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,
display_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
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": _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_any_phrase_field(
"inventors_name_nested.inventor",
phrases,
),
}
}
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 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,
display_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
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": _match_name_field("inventors.name", parsed.last_name),
}
}
else:
phrases = inventor_search_phrases(display_name)
query = {
"nested": {
"path": "inventors",
"query": _match_any_phrase_field("inventors.name", phrases),
}
}
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,
}
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
@@ -0,0 +1,16 @@
from fastapi import APIRouter
from inse.patents.authors import logic
from inse.patents.common import model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
@router.get(
"/{author_id}/patents",
operation_id="getPatentsByAuthor",
response_model=model.PatentsByAuthorResponse,
summary="Get patents matched to an author by name.",
)
async def get_patents_by_author(author_id: str):
return await logic.get_patents_by_author_id(author_id)
@@ -0,0 +1,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
@@ -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
@@ -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
@@ -0,0 +1 @@
"""Shared patent infrastructure."""
@@ -0,0 +1,56 @@
"""Base HTTP client for patent Elasticsearch indices."""
from typing import Any
import httpx
from ... import config
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
DEFAULT_SEARCH_SIZE = 100
class MissingApiKeyError(Exception):
pass
class BasePatentSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self) -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": "application/json",
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{index}/_search",
headers=self._headers(),
json=payload,
)
response.raise_for_status()
return response.json()
@@ -0,0 +1,63 @@
from pydantic import BaseModel, ConfigDict, Field
class IpcClassification(BaseModel):
symbol: str
section: str | None = None
ipc_class: str | None = Field(default=None, serialization_alias="class")
subclass: str | None = None
main_group: str | None = None
subgroup: str | None = None
model_config = ConfigDict(populate_by_name=True)
class 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
title: str | None = None
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
application_number: str | None = None
application_date: str | None = None
kind: str | None = None
application_type: str | None = None
number_of_claims: int | None = None
status: str | None = None
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
openalex_topics: list[OpenAlexTopicTag] = Field(default_factory=list)
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class PatentsByInstitutionResponse(BaseModel):
institution_id: str
institution_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class AllPatentsResponse(BaseModel):
total: int
page: int
size: int
patents: list[PatentEntry]
@@ -0,0 +1,273 @@
"""Shared patent hit parsing, deduplication, and classification enrichment."""
import asyncio
import logging
import httpx
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.ipc_lookup import extract_ipc_symbol
from inse.patents.ipc_search_client import IpcSearchClient
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", []):
src = hit.get("_source", {})
inventors = src.get("inventors_name") or []
applicants = src.get("applicants_name") or []
ipc = src.get("ipc") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
source="EPO",
title=src.get("title_en") or src.get("title_de"),
abstract=src.get("abstract"),
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
application_number=src.get("application_number"),
application_date=src.get("application_filing_date"),
kind=src.get("kind"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "EP"),
))
return patents
def parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_names") or []
assignees = src.get("assignees_orgs") or []
ipc = src.get("ipcr") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
source="USPTO",
title=src.get("title"),
abstract=src.get("abstract"),
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
application_number=src.get("application_number"),
application_date=str(src.get("application_date")) if src.get("application_date") else None,
application_type=src.get("application_type"),
number_of_claims=src.get("number_of_claims"),
status=src.get("status"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "US"),
))
return patents
def deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
seen: set[tuple[str, str, str, str]] = set()
deduplicated: list[model.PatentEntry] = []
for patent in patents:
key = patent_dedup_key(patent)
if key in seen:
continue
seen.add(key)
deduplicated.append(patent)
return deduplicated
def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
stage = patent.kind or patent.application_type or ""
return (
patent.source,
patent.patent_id,
patent.publication_date or "",
stage,
)
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,
) -> None:
symbols = list(dict.fromkeys(
extract_ipc_symbol(raw)
for patent in patents
for raw in (*patent.ipc, *patent.cpc)
))
if not symbols:
return
try:
resolved = await ipc_client.resolve_symbols(symbols)
except MissingApiKeyError:
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
return
except httpx.HTTPError as exc:
logger.warning("Classification enrichment failed: %s", exc)
return
except Exception as exc:
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
return
for patent in patents:
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
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 []
items = value if isinstance(value, list) else [value]
return [str(item).strip() for item in items if item and str(item).strip()]
def _descriptions_for_raw_codes(
raw_codes: list[str],
resolved: dict[str, model.IpcClassification],
) -> list[model.IpcClassification]:
return [
resolved[extract_ipc_symbol(raw)]
for raw in raw_codes
if extract_ipc_symbol(raw) in resolved
]
@@ -0,0 +1,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"
@@ -0,0 +1,96 @@
"""Shared text normalization for patent name matching."""
import re
import unicodedata
_CHAR_REPLACEMENTS: dict[str, str] = {
"ß": "ss",
"ẞ": "ss",
"æ": "ae",
"Æ": "ae",
"œ": "oe",
"Œ": "oe",
"ø": "o",
"Ø": "o",
"đ": "d",
"Đ": "d",
"ð": "d",
"Ð": "d",
"þ": "th",
"Þ": "th",
"ł": "l",
"Ł": "l",
"ı": "i",
"ſ": "s",
}
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
("ae", "a"),
("oe", "o"),
("ue", "u"),
)
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"u([lmnrt])", r"ue\1"),
(r"o([lmnrt])", r"oe\1"),
(r"a([lmnrt])", r"ae\1"),
)
# 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:
return ""
text = value.strip()
for src, dst in _CHAR_REPLACEMENTS.items():
text = text.replace(src, dst)
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.lower()
text = re.sub(r"[''`´]", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def name_token_variants(value: str | None) -> set[str]:
base = normalize_name_part(value)
if not base:
return set()
variants = {base}
for src, dst in _DIGRAPH_COLLAPSES:
if src in base:
variants.add(base.replace(src, dst))
if "-" in base:
variants.add(base.replace("-", ""))
variants.add(base.replace("-", " "))
return {v for v in variants if v}
def patent_transliteration_expansions(normalized: str) -> set[str]:
expanded = {normalized}
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
if re.search(pattern, normalized):
expanded.add(re.sub(pattern, repl, normalized))
return expanded
@@ -5,8 +5,6 @@
"""
from typing import Any
import httpx
from .. import config
from inse.exceptions import MissingApiKeyError
@@ -20,15 +18,9 @@ USPTO_INDEX = "uspto_patents_3.0"
class AllPatentsSearchClient:
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:
@@ -44,24 +36,45 @@ class AllPatentsSearchClient:
size: int = 10,
search: str | None = None,
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]:
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
if search and search.strip():
term = search.strip()
doc_number = term.upper().removeprefix("EP")
query: dict[str, Any] = {
search_query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title_en": {"query": term}}},
{"match_phrase": {"title_de": {"query": term}}},
{"match": {"title_en": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"match": {"title_de": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"term": {"doc_number": doc_number}},
],
"minimum_should_match": 1,
}
}
else:
query = {"match_all": {}}
search_query = {"match_all": {}}
filters = []
if year_from or year_to:
date_range: dict[str, Any] = {}
if year_from:
date_range["gte"] = year_from * 10000
if year_to:
date_range["lte"] = (year_to * 10000) + 9999
filters.append({"range": {"date_publication": date_range}})
if filters:
query: dict[str, Any] = {
"bool": {
"must": search_query,
"filter": filters,
}
}
else:
query = search_query
return {
"from": page * size,
@@ -76,30 +89,54 @@ class AllPatentsSearchClient:
],
"query": query,
}
def remove_year(self, patent_id: str) -> str:
return patent_id[4:].strip()
def uspto_query(
self,
page: int = 0,
size: int = 10,
search: str | None = None,
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]:
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
if search and search.strip():
term = search.strip()
pub_number = term.upper().removeprefix("US")
query: dict[str, Any] = {
search_query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title": {"query": term}}},
{"match": {"title": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"term": {"publication_number": pub_number}},
],
"minimum_should_match": 1,
}
}
else:
query = {"match_all": {}}
search_query = {"match_all": {}}
filters = []
if year_from or year_to:
date_range: dict[str, Any] = {}
if year_from:
date_range["gte"] = year_from * 10000
if year_to:
date_range["lte"] = (year_to * 10000) + 9999
filters.append({"range": {"publication_date": date_range}})
if filters:
query: dict[str, Any] = {
"bool": {
"must": search_query,
"filter": filters,
}
}
else:
query = search_query
return {
"from": page * size,
@@ -115,6 +152,103 @@ class AllPatentsSearchClient:
"query": query,
}
def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"doc_number": doc_number}},
{"term": {"doc_number": self.remove_year(doc_number)}},
{"term": {"application_number": self.remove_year(doc_number)}},
{"term": {"application_number": doc_number}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": 1,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de",
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
],
"query": query,
}
def uspto_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"publication_number": number}},
{"term": {"publication_number": self.remove_year(number)}},
{"term": {"application_number": number}},
{"term": {"application_number": self.remove_year(number)}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": query,
}
def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": 1,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de",
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
],
"query": query,
}
def uspto_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [{"match_phrase": {"title": title}}],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": query,
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(EPO_INDEX, payload)
@@ -1,281 +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 _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": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {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]:
return await self._search(ESIndex.EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
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,
size: int = 1,
) -> dict[str, Any]:
"""Search EPO and USPTO by ID; fall back to match_phrase 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, size)
return await self.search_uspto(payload)
payload = self._epo_query_by_title(title, 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")
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": {"term": {"doc_number": raw_id}},
}
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
"""Term query against publication_number; tries the ID as-is."""
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": {"term": {"publication_number": patent_id}},
}
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title_en (and title_de as a should clause)."""
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": {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
{"match_phrase": {"title_fr": title}},
],
"minimum_should_match": 1,
}
},
}
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title."""
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": {"match_phrase": {"title": title}},
}
"""Backward-compatible re-exports."""
from inse.patents.search_client import * # noqa: F403
@@ -0,0 +1 @@
"""Patent lookup by institution assignee."""
@@ -0,0 +1,144 @@
"""Business logic for patent lookup by institution assignee."""
import asyncio
import logging
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.models.openalex.institution import Institution
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
deduplicate_patents,
enrich_patents_classifications,
parse_epo_hits,
parse_uspto_hits,
)
from inse.patents.institutions.name_matching import (
MIN_INSTITUTION_ACRONYM_LEN,
assignee_matches_institution_name,
institution_search_variants,
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
logger = logging.getLogger(__name__)
async def get_patents_by_institution_id(
institution_id: str,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> model.PatentsByInstitutionResponse:
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
short_id = institution_id.replace("https://openalex.org/", "")
institution = await institution_client.get_institution_by_id(short_id)
search_names = _institution_search_names(institution)
if not search_names:
return model.PatentsByInstitutionResponse(
institution_id=short_id,
institution_name=institution.display_name,
patent_count=0,
patents=[],
)
try:
epo_data, uspto_data = await asyncio.gather(
search_client.search_epo(
search_client.epo_query_by_applicant(search_names)
),
search_client.search_uspto(
search_client.uspto_query_by_assignee(search_names)
),
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
all_patents = filter_patents_by_institution(all_patents, institution)
all_patents = deduplicate_patents(all_patents)
await enrich_patents_classifications(all_patents, ipc_search_client)
return model.PatentsByInstitutionResponse(
institution_id=short_id,
institution_name=institution.display_name,
patent_count=len(all_patents),
patents=all_patents,
)
def _institution_search_names(institution: Institution) -> list[str]:
names: list[str] = []
seen: set[str] = set()
def _add(name: str | None) -> None:
if not name or not name.strip():
return
for variant in institution_search_variants(name.strip()):
key = variant.casefold()
if key not in seen:
seen.add(key)
names.append(variant)
_add(institution.display_name)
for alternative in institution.display_name_alternatives or []:
_add(alternative)
for acronym in institution.display_name_acronyms or []:
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
_add(acronym)
return names
def _institution_canonical_names(institution: Institution) -> list[str]:
names: list[str] = []
seen: set[str] = set()
def _add(name: str | None) -> None:
if not name or not name.strip():
return
key = name.strip().casefold()
if key not in seen:
seen.add(key)
names.append(name.strip())
_add(institution.display_name)
for alternative in institution.display_name_alternatives or []:
_add(alternative)
for acronym in institution.display_name_acronyms or []:
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
_add(acronym)
return names
def filter_patents_by_institution(
patents: list[model.PatentEntry],
institution: Institution,
) -> list[model.PatentEntry]:
canonical_names = _institution_canonical_names(institution)
return [
patent for patent in patents
if any(
assignee_matches_institution_name(assignee, name)
for assignee in patent.assignees
for name in canonical_names
)
]
@@ -0,0 +1,97 @@
"""Institution assignee name normalization and matching."""
from inse.patents.common.text_normalization import (
name_token_variants,
normalize_name_part,
patent_transliteration_expansions,
)
_INSTITUTION_GENERIC_TOKENS = frozenset({
"university", "universitat", "universitaet", "universiteit", "college",
"institute", "institut", "institution", "national", "sciences", "science",
"school", "center", "centre", "laboratory", "department", "academy",
"the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und",
"fur", "von",
})
MIN_INSTITUTION_SUBSTRING_LEN = 6
MIN_INSTITUTION_VARIANT_LEN = 4
MIN_INSTITUTION_ACRONYM_LEN = 3
def institution_search_variants(value: str | None) -> list[str]:
if not value or not value.strip():
return []
stripped = value.strip()
min_len = (
MIN_INSTITUTION_ACRONYM_LEN
if stripped.isupper() and " " not in stripped
else MIN_INSTITUTION_VARIANT_LEN
)
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
candidate = candidate.strip()
if len(candidate) < min_len:
return
key = candidate.casefold()
if key not in seen:
seen.add(key)
ordered.append(candidate)
_add(stripped)
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in patent_transliteration_expansions(normalized):
_add(variant.title())
return ordered
def _significant_institution_tokens(text: str) -> set[str]:
# 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 normalized.split()
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
and token not in _INSTITUTION_GENERIC_TOKENS
}
def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool:
norm_assignee = normalize_name_part(assignee)
norm_name = normalize_name_part(institution_name)
if not norm_assignee or not norm_name:
return False
original = institution_name.strip()
# 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_flat in assignee_tokens
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)
if not significant:
return False
matched = significant & assignee_tokens
if len(significant) >= 2:
return len(matched) >= 2
return bool(matched)
@@ -0,0 +1,94 @@
"""Elasticsearch query builders for institution assignee patent search."""
from typing import Any
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
from inse.patents.institutions.name_matching import institution_search_variants
class AssigneeSearchQueries:
def _match_organization_names(self, field: str, names: list[str]) -> dict[str, Any]:
clauses: list[dict[str, Any]] = []
seen: set[str] = set()
for name in names:
for variant in institution_search_variants(name):
key = variant.casefold()
if not variant or key in seen:
continue
seen.add(key)
clauses.append({"match_phrase": {field: {"query": variant}}})
if not clauses:
return {"match_none": {}}
return {
"bool": {
"should": clauses,
"minimum_should_match": 1,
}
}
def epo_query_by_applicant(
self,
institution_names: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"application_number",
"application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"cpc",
],
"query": self._match_organization_names("applicants_name", institution_names),
}
def uspto_query_by_assignee(
self,
institution_names: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"application_number",
"application_date",
"application_type",
"title",
"abstract",
"inventors_names",
"assignees_orgs",
"ipcr",
"cpc",
"number_of_claims",
"status",
],
"query": self._match_organization_names("assignees_orgs", institution_names),
}
@@ -0,0 +1,33 @@
from functools import lru_cache
from typing import Annotated
from fastapi import APIRouter, Depends
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.patents.common import model
from inse.patents.institutions import logic
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
return InstitutionsSearchClient()
@router.get(
"/{id}/patents",
operation_id="getPatentsByInstitution",
response_model=model.PatentsByInstitutionResponse,
summary="Get patents matched to an institution by assignee name.",
)
async def get_patents_by_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
) -> model.PatentsByInstitutionResponse:
return await logic.get_patents_by_institution_id(
institution_id=id,
institutions_client=client,
)
@@ -7,8 +7,6 @@ from __future__ import annotations
from typing import Any
import httpx
from .. import config
from . import model
from inse.exceptions import MissingApiKeyError
@@ -32,15 +30,9 @@ _LEVELS: tuple[tuple[str, str, str], ...] = (
class IpcSearchClient:
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:
@@ -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]
@@ -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]
@@ -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)
@@ -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)
@@ -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)
@@ -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"
+16 -312
View File
@@ -1,313 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for patent matching by author name.
"""
import logging
import asyncio
"""Backward-compatible re-exports."""
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 (
filter_patents_by_institution as _filter_patents_by_institution,
get_patents_by_institution_id,
)
import httpx
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
logger = logging.getLogger(__name__)
async def get_patent(
patent_id: str,
title: str,
prefix: str,
client: PatentSearchClient | None = None,
) -> model.PatentEntry:
search_client = client or PatentSearchClient()
data = await search_client.get_by_id_or_title(
patent_id=patent_id,
prefix=prefix,
title=title,
)
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",
]
+2 -47
View File
@@ -1,47 +1,2 @@
from pydantic import BaseModel, ConfigDict, Field
class IpcClassification(BaseModel):
symbol: str
section: str | None = None
ipc_class: str | None = Field(default=None, serialization_alias="class")
subclass: str | None = None
main_group: str | None = None
subgroup: str | None = None
model_config = ConfigDict(populate_by_name=True)
class PatentEntry(BaseModel):
patent_id: str
source: str # "EPO" or "USPTO"
title: str | None = None
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
application_number: str | None = None
application_date: str | None = None
kind: str | None = None # EPO only
application_type: str | None = None # USPTO only
number_of_claims: int | None = None # USPTO only
status: str | None = None # USPTO only
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class AllPatentsResponse(BaseModel):
total: int
page: int
size: int
patents: list[PatentEntry]
"""Backward-compatible re-exports."""
from inse.patents.common.model import * # noqa: F403
+19 -240
View File
@@ -1,242 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name normalization and matching for patent inventor lookup.
Handles umlauts, diacritics, and common Latin transliterations so that
e.g. 'Müller' matches 'Mueller' and 'Muller'.
"""
import re
import unicodedata
# Characters that NFKD does not map to ASCII-friendly forms.
_CHAR_REPLACEMENTS: dict[str, str] = {
"ß": "ss",
"ẞ": "ss",
"æ": "ae",
"Æ": "ae",
"œ": "oe",
"Œ": "oe",
"ø": "o",
"Ø": "o",
"đ": "d",
"Đ": "d",
"ð": "d",
"Ð": "d",
"þ": "th",
"Þ": "th",
"ł": "l",
"Ł": "l",
"ı": "i",
"ſ": "s",
}
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
("ae", "a"),
("oe", "o"),
("ue", "u"),
"""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,
)
# Common ASCII spellings in patent records for umlaut-derived vowels.
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"u([lmnrt])", r"ue\1"),
(r"o([lmnrt])", r"oe\1"),
(r"a([lmnrt])", r"ae\1"),
from inse.patents.common.text_normalization import ( # noqa: F401
name_token_variants,
normalize_name_part,
)
from inse.patents.institutions.name_matching import ( # noqa: F401
MIN_INSTITUTION_ACRONYM_LEN,
MIN_INSTITUTION_SUBSTRING_LEN,
MIN_INSTITUTION_VARIANT_LEN,
assignee_matches_institution_name,
institution_search_variants,
)
def normalize_name_part(value: str | None) -> str:
"""
Normalize a single name token for comparison.
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
-> remove apostrophes/punctuation -> collapse whitespace.
"""
if not value:
return ""
text = value.strip()
for src, dst in _CHAR_REPLACEMENTS.items():
text = text.replace(src, dst)
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.lower()
text = re.sub(r"[''`´]", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def name_token_variants(value: str | None) -> set[str]:
"""
Return equivalent forms of a name token.
Includes the normalized base plus German digraph collapses
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
"""
base = normalize_name_part(value)
if not base:
return set()
variants = {base}
for src, dst in _DIGRAPH_COLLAPSES:
if src in base:
variants.add(base.replace(src, dst))
if "-" in base:
variants.add(base.replace("-", ""))
variants.add(base.replace("-", " "))
return {v for v in variants if v}
def _patent_transliteration_expansions(normalized: str) -> set[str]:
"""
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
Used for Elasticsearch recall only; post-filter applies stricter matching.
"""
expanded = {normalized}
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
if re.search(pattern, normalized):
expanded.add(re.sub(pattern, repl, normalized))
return expanded
def tokens_equal(
left: str | None,
right: str | None,
*,
allow_initial: bool = True,
) -> bool:
"""True when two name tokens are equivalent after normalization."""
left_variants = name_token_variants(left)
right_variants = name_token_variants(right)
if not left_variants or not right_variants:
return False
if left_variants & right_variants:
return True
if not allow_initial:
return False
return _initial_tokens_match(left, right)
def _initial_letter(token: str | None) -> str | None:
normalized = normalize_name_part(token)
if len(normalized) == 1 and normalized.isalpha():
return normalized
return None
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
"""True when one token is a single-letter initial matching the other token."""
left_initial = _initial_letter(left)
right_initial = _initial_letter(right)
left_full = normalize_name_part(left)
right_full = normalize_name_part(right)
if left_initial and right_full and len(right_full) > 1:
return right_full.startswith(left_initial)
if right_initial and left_full and len(left_full) > 1:
return left_full.startswith(right_initial)
if left_initial and right_initial:
return left_initial == right_initial
return False
def _inventor_first_token(inventor_name: str) -> str:
if "," in inventor_name:
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
return first_part.split()[0] if first_part else ""
parts = inventor_name.split()
return parts[0] if parts else ""
def first_name_match_kind(
inventor_name: str,
first_name: str,
last_name: str,
) -> str:
"""
Match quality for the inventor first name: 'full', 'initial', or 'none'.
"""
if not name_matches(inventor_name, first_name, last_name):
return "none"
inventor_first = _inventor_first_token(inventor_name)
if tokens_equal(inventor_first, first_name, allow_initial=False):
return "full"
return "initial"
def search_name_variants(value: str | None) -> list[str]:
"""
Distinct search strings for Elasticsearch, preserving original casing
where useful but including normalized and transliterated forms.
"""
if not value or not value.strip():
return []
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
key = candidate.casefold()
if candidate.strip() and key not in seen:
seen.add(key)
ordered.append(candidate.strip())
_add(value.strip())
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in _patent_transliteration_expansions(normalized):
_add(variant.title())
if normalized and len(normalized) > 1:
_add(normalized[0].upper())
return ordered
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
"""
True when an inventor entry matches first_name + last_name.
Supports:
- USPTO: 'Christian Weber', 'Christian Hans Weber'
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
"""
if not inventor_name or not last_name:
return False
name = inventor_name.strip()
if "," in name:
last_part, first_part = [p.strip() for p in name.split(",", 1)]
first_token = first_part.split()[0] if first_part else ""
return (
tokens_equal(last_part, last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(first_token, first_name)
)
parts = name.split()
if len(parts) < 2:
return False
return (
tokens_equal(parts[-1], last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(parts[0], first_name)
)
@@ -0,0 +1 @@
"""Org patents index: institution-scoped patent aggregation."""
@@ -0,0 +1,401 @@
"""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
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:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 60.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self, content_type: str = "application/json") -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": content_type,
}
async def ensure_index(self) -> None:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.head(
f"/{ORG_PATENTS_INDEX}",
headers=self._headers(),
)
if response.status_code == 404:
create_response = await client.put(
f"/{ORG_PATENTS_INDEX}",
headers=self._headers(),
json={"mappings": ORG_PATENTS_MAPPING},
)
create_response.raise_for_status()
logger.info("Created index %s", ORG_PATENTS_INDEX)
return
response.raise_for_status()
mapping_response = await client.put(
f"/{ORG_PATENTS_INDEX}/_mapping",
headers=self._headers(),
json=ORG_PATENTS_MAPPING,
)
mapping_response.raise_for_status()
async def delete_by_institution(self, institution_id: str) -> int:
"""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:
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:
return
batch_size = 500
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
for start in range(0, len(documents), batch_size):
batch = documents[start : start + batch_size]
bulk_lines: list[str] = []
for doc_id, source in batch:
bulk_lines.append(json.dumps({"index": {"_index": ORG_PATENTS_INDEX, "_id": doc_id}}))
bulk_lines.append(json.dumps(source))
payload = "\n".join(bulk_lines) + "\n"
response = await client.post(
"/_bulk",
content=payload,
headers=self._headers("application/x-ndjson"),
params={"refresh": "true"},
)
response.raise_for_status()
result = response.json()
if result.get("errors"):
failed = [
item
for item in result.get("items", [])
if item.get("index", {}).get("status", 200) >= 400
]
logger.error("Bulk index errors: %s", failed[:3])
raise RuntimeError("Bulk indexing into org_patents failed.")
async def search_by_institution(
self,
institution_id: str,
match_type: MatchTypeFilter = "all",
page: int = 0,
size: int = DEFAULT_PAGE_SIZE,
source: str | None = None,
) -> tuple[list[OrgPatentEntry], int]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
if match_type == "institution":
filters.append({"terms": {"match_type": ["institution", "both"]}})
elif match_type == "name":
filters.append({"terms": {"match_type": ["name", "both"]}})
elif match_type == "both":
filters.append({"term": {"match_type": "both"}})
if source in ("EPO", "USPTO"):
filters.append({"term": {"source": source}})
payload = {
"from": page * size,
"size": size,
"track_total_hits": True,
"query": {"bool": {"filter": filters}},
"sort": [
{"publication_year": {"order": "desc", "missing": "_last"}},
{"patent_id": {"order": "asc"}},
],
}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{ORG_PATENTS_INDEX}/_search",
headers=self._headers(),
json=payload,
)
if response.status_code == 404:
return [], 0
response.raise_for_status()
data = response.json()
total = data.get("hits", {}).get("total", {}).get("value", 0)
patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])]
return patents, total
async def top_authors_by_institution(
self,
institution_id: str,
size: int = 10,
) -> list[dict[str, Any]]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
payload = {
"size": 0,
"query": {"term": {"institution_id": short_id}},
"aggs": {
"matched_authors_nested": {
"nested": {"path": "matched_authors"},
"aggs": {
"authors": {
"terms": {
"field": "matched_authors.openalex_author_id",
"size": size,
"order": [{"_count": "desc"}, {"_key": "asc"}],
},
"aggs": {
"names": {
"terms": {
"field": "matched_authors.author_name",
"size": 1,
}
},
"patents": {"reverse_nested": {}},
},
}
},
}
},
}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{ORG_PATENTS_INDEX}/_search",
headers=self._headers(),
json=payload,
)
if response.status_code == 404:
return []
response.raise_for_status()
data = response.json()
buckets = (
data.get("aggregations", {})
.get("matched_authors_nested", {})
.get("authors", {})
.get("buckets", [])
)
return [
{
"id": bucket.get("key"),
"name": _top_author_name(bucket),
"count": int(bucket.get("patents", {}).get("doc_count", 0)),
}
for bucket in buckets
if bucket.get("key")
]
def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
source = hit.get("_source", {})
publication_year = source.get("publication_year")
return OrgPatentEntry(
institution_id=source.get("institution_id", ""),
institution_name=source.get("institution_name"),
patent_id=source.get("patent_id", ""),
source=source.get("source", ""),
match_type=source.get("match_type", "institution"),
title=source.get("title"),
abstract=source.get("abstract"),
publication_date=source.get("publication_date"),
publication_year=str(publication_year) if publication_year is not None else None,
application_number=source.get("application_number"),
application_date=source.get("application_date"),
kind=source.get("kind"),
application_type=source.get("application_type"),
number_of_claims=source.get("number_of_claims"),
status=source.get("status"),
inventors=source.get("inventors") or [],
assignees=source.get("assignees") or [],
ipc=source.get("ipc") or [],
cpc=source.get("cpc") or [],
country=source.get("country"),
matched_authors=source.get("matched_authors") or [],
)
def _top_author_name(bucket: dict[str, Any]) -> str:
name_buckets = bucket.get("names", {}).get("buckets", [])
if name_buckets:
return str(name_buckets[0].get("key") or bucket.get("key"))
return str(bucket.get("key"))
+441
View File
@@ -0,0 +1,441 @@
"""Business logic for org_patents index build and retrieval."""
import asyncio
import logging
import re
from dataclasses import dataclass, field
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.models.openalex.author import Author
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.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,
MatchedAuthor,
OrgPatentEntry,
OrgPatentsResponse,
)
from inse.patents.search_client import PatentSearchClient
logger = logging.getLogger(__name__)
ORG_PATENT_SEARCH_SIZE = 500
AUTHOR_SEARCH_CONCURRENCY = 8
@dataclass
class _AccumulatedPatent:
patent: PatentEntry
institution_match: bool = False
matched_authors: dict[str, MatchedAuthor] = field(default_factory=dict)
def normalize_institution_id(institution_id: str) -> str:
return institution_id.replace("https://openalex.org/", "").upper()
def normalize_author_id(author_id: str | None) -> str:
if not author_id:
return ""
return author_id.replace("https://openalex.org/", "").upper()
def org_patent_document_id(institution_id: str, patent: PatentEntry) -> str:
stage = patent.kind or patent.application_type or "none"
safe_patent_id = re.sub(r"[^A-Za-z0-9_-]", "_", patent.patent_id)
safe_date = patent.publication_date or "none"
safe_stage = re.sub(r"[^A-Za-z0-9_-]", "_", stage)
return f"{normalize_institution_id(institution_id)}_{patent.source}_{safe_patent_id}_{safe_date}_{safe_stage}"
def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchType:
if institution_match and has_name_match:
return "both"
if institution_match:
return "institution"
return "name"
def _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,
institution_patents: list[PatentEntry],
author_patents: list[tuple[Author, list[PatentEntry]]],
) -> list[OrgPatentEntry]:
accumulated: dict[tuple[str, str, str, str], _AccumulatedPatent] = {}
for patent in institution_patents:
key = patent_dedup_key(patent)
entry = accumulated.get(key)
if entry is None:
accumulated[key] = _AccumulatedPatent(patent=patent, institution_match=True)
else:
entry.institution_match = True
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=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)
entry = accumulated.get(key)
if entry is None:
accumulated[key] = _AccumulatedPatent(
patent=patent,
matched_authors={author_dedup_key: matched_author},
)
else:
entry.matched_authors.setdefault(author_dedup_key, matched_author)
org_patents: list[OrgPatentEntry] = []
short_institution_id = normalize_institution_id(institution_id)
for entry in accumulated.values():
has_name_match = bool(entry.matched_authors)
match_type = resolve_match_type(entry.institution_match, has_name_match)
org_patents.append(
OrgPatentEntry(
institution_id=short_institution_id,
institution_name=institution_name,
match_type=match_type,
matched_authors=list(entry.matched_authors.values()),
**entry.patent.model_dump(),
)
)
org_patents.sort(
key=lambda patent: (
patent.publication_year or "",
patent.patent_id,
),
reverse=True,
)
return org_patents
def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
publication_year = None
if patent.publication_year:
try:
publication_year = int(patent.publication_year)
except ValueError:
publication_year = None
return {
"institution_id": patent.institution_id,
"institution_name": patent.institution_name,
"patent_id": patent.patent_id,
"source": patent.source,
"match_type": patent.match_type,
"title": patent.title,
"abstract": patent.abstract,
"publication_date": patent.publication_date,
"publication_year": publication_year,
"application_number": patent.application_number,
"application_date": patent.application_date,
"kind": patent.kind,
"application_type": patent.application_type,
"number_of_claims": patent.number_of_claims,
"status": patent.status,
"inventors": patent.inventors,
"assignees": patent.assignees,
"ipc": patent.ipc,
"cpc": patent.cpc,
"country": patent.country,
"matched_authors": [
author.model_dump() for author in patent.matched_authors
],
}
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
if not author_name:
return []
try:
epo_data, uspto_data = await asyncio.gather(
search_client.search_epo(
search_client.epo_query_by_inventor(
author_name,
size=ORG_PATENT_SEARCH_SIZE,
)
),
search_client.search_uspto(
search_client.uspto_query_by_inventor(
author_name,
size=ORG_PATENT_SEARCH_SIZE,
)
),
)
except (MissingApiKeyError, httpx.HTTPError):
raise
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
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(
institution_id: str,
search_client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> list[OrgPatentEntry]:
patent_client = search_client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
short_id = normalize_institution_id(institution_id)
institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
institution_response = await get_patents_by_institution_id(
institution_id=short_id,
client=patent_client,
ipc_client=ipc_search_client,
institutions_client=institution_client,
)
institution_patents = institution_response.patents
authors = await fetch_authors_by_institution_name(institution_name)
logger.info(
"Building org_patents for %s (%s): %d authors, %d institution patents",
institution_name,
short_id,
len(authors),
len(institution_patents),
)
semaphore = asyncio.Semaphore(AUTHOR_SEARCH_CONCURRENCY)
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
async with semaphore:
patents = await _search_patents_by_author(
author, institution_name, patent_client, ipc_search_client
)
return author, patents
author_results = await asyncio.gather(
*[_fetch_for_author(author) for author in authors],
return_exceptions=True,
)
author_patents: list[tuple[Author, list[PatentEntry]]] = []
for result in author_results:
if isinstance(result, Exception):
logger.warning("Author patent search failed: %s", result)
continue
author_patents.append(result)
org_patents = merge_org_patents(
institution_id=short_id,
institution_name=institution_name,
institution_patents=institution_patents,
author_patents=author_patents,
)
await enrich_patents_classifications(
[patent for patent in org_patents],
ipc_search_client,
)
return org_patents
async def index_org_patents_for_institution(
institution_id: str,
search_client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
org_client: OrgPatentsSearchClient | None = None,
) -> int:
short_id = normalize_institution_id(institution_id)
org_patents_client = org_client or OrgPatentsSearchClient()
org_patents = await build_org_patents_for_institution(
institution_id=short_id,
search_client=search_client,
ipc_client=ipc_client,
institutions_client=institutions_client,
)
await org_patents_client.ensure_index()
deleted = await org_patents_client.delete_by_institution(short_id)
logger.info("Deleted %d existing org_patents documents for %s", deleted, short_id)
documents = [
(
org_patent_document_id(short_id, patent),
org_patent_to_es_document(patent),
)
for patent in org_patents
]
await org_patents_client.bulk_index(documents)
logger.info("Indexed %d org_patents documents for %s", len(documents), short_id)
return len(documents)
async def get_org_patents_by_institution_id(
institution_id: str,
match_type: MatchTypeFilter = "all",
page: int = 0,
size: int = 20,
source: str | None = None,
org_client: OrgPatentsSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> OrgPatentsResponse:
short_id = normalize_institution_id(institution_id)
org_patents_client = org_client or OrgPatentsSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
try:
institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
except Exception:
institution_name = None
try:
await org_patents_client.ensure_index()
patents, total = await org_patents_client.search_by_institution(
institution_id=short_id,
match_type=match_type,
page=page,
size=size,
source=source,
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="org_patents search request failed.",
) from exc
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,
patent_count=total,
page=page,
size=size,
patents=patents,
)
@@ -0,0 +1,33 @@
ORG_PATENTS_INDEX = "org_patents"
ORG_PATENTS_MAPPING = {
"properties": {
"institution_id": {"type": "keyword"},
"institution_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"patent_id": {"type": "keyword"},
"source": {"type": "keyword"},
"match_type": {"type": "keyword"},
"title": {"type": "text"},
"abstract": {"type": "text"},
"publication_date": {"type": "keyword"},
"publication_year": {"type": "integer"},
"application_number": {"type": "keyword"},
"application_date": {"type": "keyword"},
"kind": {"type": "keyword"},
"application_type": {"type": "keyword"},
"number_of_claims": {"type": "integer"},
"status": {"type": "keyword"},
"inventors": {"type": "keyword"},
"assignees": {"type": "keyword"},
"ipc": {"type": "keyword"},
"cpc": {"type": "keyword"},
"country": {"type": "keyword"},
"matched_authors": {
"type": "nested",
"properties": {
"openalex_author_id": {"type": "keyword"},
"author_name": {"type": "keyword"},
},
},
}
}
@@ -0,0 +1,29 @@
from typing import Literal
from pydantic import BaseModel, Field
from inse.patents.common.model import PatentEntry
MatchType = Literal["institution", "name", "both"]
MatchTypeFilter = Literal["institution", "name", "both", "all"]
class MatchedAuthor(BaseModel):
openalex_author_id: str
author_name: str
class OrgPatentEntry(PatentEntry):
institution_id: str
institution_name: str | None = None
match_type: MatchType
matched_authors: list[MatchedAuthor] = Field(default_factory=list)
class OrgPatentsResponse(BaseModel):
institution_id: str
institution_name: str | None = None
patent_count: int
page: int = 0
size: int = 20
patents: list[OrgPatentEntry]
@@ -0,0 +1,89 @@
from functools import lru_cache
from typing import Annotated
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
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:
return InstitutionsSearchClient()
@router.get(
"/{id}/org-patents",
operation_id="getOrgPatentsByInstitution",
response_model=OrgPatentsResponse,
summary="Get pre-indexed org patents for an institution.",
)
async def get_org_patents_by_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
match_type: Annotated[
MatchTypeFilter,
Query(description="Filter patents by match type."),
] = "all",
page: int = 0,
size: int = 20,
source: str | None = None,
) -> OrgPatentsResponse:
return await logic.get_org_patents_by_institution_id(
institution_id=id,
match_type=match_type,
page=page,
size=size,
source=source,
institutions_client=client,
)
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.",
)
@@ -0,0 +1,55 @@
import json
import httpx
import pytest
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
@pytest.mark.anyio
async def test_top_authors_by_institution_aggregates_matched_authors():
requests: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
return httpx.Response(
200,
json={
"aggregations": {
"matched_authors_nested": {
"authors": {
"buckets": [
{
"key": "A1",
"patents": {"doc_count": 5},
"names": {
"buckets": [
{"key": "Ada Example", "doc_count": 5}
]
},
}
]
}
}
}
},
)
client = OrgPatentsSearchClient(
base_url="https://example.test",
api_key="key",
transport=httpx.MockTransport(handler),
)
result = await client.top_authors_by_institution(
"https://openalex.org/I123",
size=10,
)
assert result == [{"id": "A1", "name": "Ada Example", "count": 5}]
payload = json.loads(requests[0].content)
assert payload["query"] == {"term": {"institution_id": "I123"}}
assert (
payload["aggs"]["matched_authors_nested"]["nested"]["path"]
== "matched_authors"
)
@@ -0,0 +1,104 @@
from inse.patents.common.model import PatentEntry
from inse.patents.org.logic import (
merge_org_patents,
org_patent_document_id,
resolve_match_type,
)
from inse.patents.org.model import MatchedAuthor
from inse.models.openalex.author import Author
def _patent(
patent_id: str = "EP1234567",
source: str = "EPO",
) -> PatentEntry:
return PatentEntry(
patent_id=patent_id,
source=source,
title="Example patent",
publication_year="2024",
)
def _author(author_id: str, name: str) -> Author:
return Author(
id=f"https://openalex.org/{author_id}",
display_name=name,
)
def test_resolve_match_type() -> None:
assert resolve_match_type(True, True) == "both"
assert resolve_match_type(True, False) == "institution"
assert resolve_match_type(False, True) == "name"
def test_merge_org_patents_keeps_institution_only_patents() -> None:
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[_patent("EP111")],
author_patents=[],
)
assert len(result) == 1
assert result[0].match_type == "institution"
assert result[0].matched_authors == []
def test_merge_org_patents_keeps_name_only_patents() -> None:
author = _author("A123", "Max Mustermann")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[],
author_patents=[(author, [_patent("EP222")])],
)
assert len(result) == 1
assert result[0].match_type == "name"
assert result[0].matched_authors[0].openalex_author_id == "A123"
def test_merge_org_patents_marks_both_when_same_patent_found_twice() -> None:
author = _author("A123", "Max Mustermann")
patent = _patent("EP333")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[patent],
author_patents=[(author, [patent])],
)
assert len(result) == 1
assert result[0].match_type == "both"
assert len(result[0].matched_authors) == 1
def test_merge_org_patents_deduplicates_and_collects_multiple_authors() -> None:
author_one = _author("A111", "Max Mustermann")
author_two = _author("A222", "Maria Muster")
patent = _patent("EP444")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[],
author_patents=[
(author_one, [patent]),
(author_two, [patent]),
],
)
assert len(result) == 1
assert result[0].match_type == "name"
assert {author.openalex_author_id for author in result[0].matched_authors} == {"A111", "A222"}
def test_org_patent_document_id_is_stable() -> None:
patent = _patent("EP1234567")
patent.kind = "A1"
patent.publication_date = "20240101"
doc_id = org_patent_document_id("I62318514", patent)
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"

Some files were not shown because too many files have changed in this diff Show More