Compare commits

...
Author SHA1 Message Date
farajollahi 97ba57b9a2 fix test service
LocationBasedServices/smartguide/pipeline/pr-auth This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 19:36:11 +02:00
farajollahi 5a91887861 implement organisation management
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/pr-auth There was a failure building this commit
2026-06-29 19:11:03 +02:00
Mats Paul Tončik c8179d44f6 Added tests for auth service
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-28 15:27:53 +02:00
spsaefan 1019cedb97 Add SMTP support for OTK emails
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-27 14:17:21 +02:00
Roman 4b6ad1ec3d show effective account profile in sidebar
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-27 14:16:45 +02:00
Roman 0648e1774c fix(auth): reset frontend auth state on logout and failed refresh
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-27 13:57:18 +02:00
Mats Paul Tončik b993862afb Updated credential service to modern signal api
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-27 11:57:30 +02:00
Mats Paul Tončik f951eba7e4 Removed Armans old auth models 2026-06-27 11:42:35 +02:00
Mats Paul Tončik d5122a5eb7 Merge remote-tracking branch 'origin/auth' into auth
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-27 10:57:28 +02:00
Mats Paul Tončik 1351264c80 Updated endpoint schemas 2026-06-27 10:41:29 +02:00
Roman 7b13db6dbf fix(auth): clean up auth v2 integration and legacy auth flow
LocationBasedServices/smartguide/pipeline/head This commit looks good
Connect logout and change-password handling to the new auth v2 flow and
remove remaining legacy auth usage from the active frontend/backend flow.

Main changes:
- wire frontend logout and change-password handling to auth v2
- remove old auth service references from the active flow
- fix self-access handling so real_account_id == effective_account_id is not treated as impersonation
- update CredentialService token/session state handling
- update guards to validate the current session through /api/accounts/me
- update the auth interceptor for bearer tokens, public endpoint skips, and 401 recovery
- improve impersonation recovery UX with snackbar feedback and focus cleanup
- keep the registration page for now, but disable registration in CredentialService
2026-06-27 01:38:05 +02:00
Roman b4257f2efa Exclude auth endpoints from ETag cache
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 17:35:46 +02:00
farajollahi 52a567df3e Merge pull request 'Ui-login' (#168) from Ui-login into auth
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #168
2026-06-26 10:36:01 +02:00
farajollahi 901cca5eb9 connect front to back
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-auth Build started...
2026-06-26 10:31:20 +02:00
farajollahi a1b1cf0473 Merge branch 'auth' into Ui-login 2026-06-26 09:13:10 +02:00
spsaefan 653dcb0a14 Log OTK code for development testing
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 00:27:58 +02:00
Mats Paul Tončik 91ec7d841c Added token type to JWT payload
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-25 17:33:24 +02:00
Mats Paul Tončik d8a991cc3a Fixed minor validation flaws 2026-06-25 17:26:28 +02:00
Mats Paul Tončik 6d25d5c51f Added functionality to populate predefined accounts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-25 15:28:57 +02:00
Mats Paul Tončik 3d8fc2431f Integrated different auth methods with eachother
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-25 14:58:06 +02:00
spsaefan 8390764ff4 Implement OTK login
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-25 12:06:58 +02:00
Roman 699dc32b0d Added logout epoch invalidation and change password
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-25 05:38:17 +02:00
Mats Paul Tončik bea26c70ec Added prototype for fingerprinted token generation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-24 22:31:44 +02:00
farajollahi 40fcdba595 implement UI Frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-24 13:14:26 +02:00
Mats Paul Tončik 81441dc588 Added models for auth and account, cleaned up old models
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-23 21:21:08 +02:00
Louis ad697e8a8b Merge pull request 'ts-frontend-colored-chips-v2' (#161) from ts-frontend-colored-chips-v2 into dev
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
Reviewed-on: #161
2026-06-23 01:25:24 +02:00
Louis 9025852972 Merge remote-tracking branch 'origin/dev' into ts-frontend-colored-chips
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-23 01:06:34 +02:00
Roman 7a137deb71 network and sidebar fix
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-23 00:58:35 +02:00
Louis 9905750d75 show subfields, fields and domains descriptions in tooltips 2026-06-23 00:47:39 +02:00
Louis 03e21fcb32 expanded state in URL 2026-06-23 00:21:52 +02:00
Louis ddb3439324 enlarge topic color markers
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-23 00:03:38 +02:00
Louis 6ea5ac1b17 add expandable topic color legend 2026-06-22 23:54:23 +02:00
Louis 95a9dcceff translate openalex labels 2026-06-22 23:35:05 +02:00
Louis 38896304e8 refine timeline topic legend layout 2026-06-22 23:31:27 +02:00
Louis e8c0144441 increase topic chip contrast 2026-06-22 23:11:48 +02:00
Louis e76a33d28f refine semantic topic color 2026-06-22 23:05:26 +02:00
Louis 278e0f529d improve topic tooltip spacing 2026-06-22 22:31:55 +02:00
Louis 9c75728bbf Merge branch 'dev' into ts-frontend-colored-chips 2026-06-22 22:03:36 +02:00
Mats Paul Tončik 1ab51196ce Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-22 15:49:50 +02:00
Mats Paul Tončik 043db9b7cc Added sort query param manipulation by generic data table 2026-06-22 15:48:57 +02:00
Mats Paul Tončik c222d422a9 Updated more components to use query param components 2026-06-22 15:30:32 +02:00
arzani d1310f24ff permission fixes for the py_cache
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-22 10:14:00 +02:00
Kazgatari fbf5dbefe3 test jenkins
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-22 09:34:05 +02:00
kuzko 387cab897a Merge pull request 'feature/keyword_search_rework' (#157) from feature/keyword_search_rework into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #157
2026-06-22 09:12:52 +02:00
Kazgatari d78aef8df1 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/keyword_search_rework
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-22 09:07:55 +02:00
erfanian 1a34333c63 Merge pull request 'api-key-cleanup' (#158) from api-key-cleanup into dev
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
Reviewed-on: #158
2026-06-21 23:51:51 +02:00
spsaefan 514e572eb9 Use shared Elasticsearch config
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-21 23:36:30 +02:00
spsaefan 0c2a45ba66 Clean API key config 2026-06-21 23:36:15 +02:00
Louis 882b681036 style(ui): intensify topic colors
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-21 23:28:43 +02:00
Louis 1b77071dc4 feat(ui): show topic hierarchy in tooltips 2026-06-21 23:27:54 +02:00
Louis f8c7b1daac add grouped subfield legend to timeline 2026-06-21 23:03:13 +02:00
Louis 7e95b46779 add semantic topic legend to interests 2026-06-21 23:03:03 +02:00
Mats Paul Tončik 70ed62a220 Updated projects to use query params components
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-21 22:48:04 +02:00
Mats Paul Tončik 9d1ab1babb Added general purpose query param manipulating components for input, pagination, and selectors
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-21 22:36:16 +02:00
Louis 6651737b65 color research timeline topics semantically 2026-06-21 22:23:21 +02:00
Louis 6d2b7a9873 color interest topics semantically 2026-06-21 22:17:11 +02:00
Louis 7a7e04d2f0 add shared topic color utility 2026-06-21 22:15:50 +02:00
Louis 424918404f Extend TopicCount (backend) with domain, field and subfield metadata 2026-06-21 22:11:06 +02:00
Kazgatari d7a269589c added outline of active topic filters
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-21 20:43:27 +02:00
Kazgatari 84747b9efb refactor frontend (changed old decorator Input, Output to modern signals. Added URL parameters to safe topic filer) 2026-06-21 20:39:04 +02:00
Kazgatari 3596c42947 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/keyword_search_rework 2026-06-21 19:48:16 +02:00
Kazgatari 3249a8569b changed topic-hierarchy to use Angular Material tooltip. Fixed Tooltip to also show, when only navigating with tab (no only mouse over) 2026-06-21 19:43:45 +02:00
Kazgatari 479c144c8b removed logging 2026-06-21 19:01:41 +02:00
Kazgatari d89d1ded98 changed k and num_candidates. Low number leads to ignored Keyword vectors 2026-06-21 18:51:30 +02:00
Mats Paul Tončik fa7e607f3e Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-21 16:07:03 +02:00
Mats Paul Tončik a0477fcdb1 Added documentation for projects search client
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-21 15:50:54 +02:00
Mats Paul Tončik f3539e4210 Moved dfg projects search client out of class 2026-06-21 15:35:56 +02:00
Mats Paul Tončik 9cd109fc17 Moved all projects search client out of class 2026-06-21 14:44:21 +02:00
Mats Paul Tončik 84f3314b60 Fixed institution cordis eu funding amount to show the amount actually received not total for project 2026-06-21 14:07:39 +02:00
Kazgatari 5b37115e46 changed logic of semantic and hybrid query. Tested different boostings 2026-06-21 12:36:36 +02:00
Kazgatari 8f707df86f implementing radio button option to select hybrid vs semantic 2026-06-21 09:33:57 +02:00
tischer 514634d5f0 Merge pull request 'feat/add_site_news' (#156) from feat/add_site_news into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #156
2026-06-20 21:19:14 +02:00
Steven Tischer d1588ac5c1 Resolve conflicts in generated OpenAPI client by regenerating from dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-20 21:14:17 +02:00
Kazgatari c30208e61e added model to config and .env 2026-06-20 21:08:27 +02:00
Kazgatari 8c61b4d54f Changed index to vectorize each keyword & updated database topicvector 2026-06-20 21:07:23 +02:00
Steven Tischer 239129e513 Merge branch 'dev' into feat/add_site_news 2026-06-20 21:06:29 +02:00
tischer e21b84544c Merge pull request 'extract latest institution from affiliations if last_known_institutions is null' (#155) from fix/wrong_last_uni_at_person_page into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #155
2026-06-20 20:44:33 +02:00
Steven Tischer 3b16f8d8fc extract latest institution from affiliations if last_known_institutions is null
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-20 20:31:13 +02:00
Louis 535e5d165f Create reusable topic chip component
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 17:33:49 +02:00
Steven Tischer be74063a51 order person list in news to show ude authors on top
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 17:10:30 +02:00
Steven Tischer c8b055902f Add badge with link to author profile in news 2026-06-20 17:03:45 +02:00
Louis 2bd12e447a Merge remote-tracking branch 'origin/dev' into ts-frontend-colored-chips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 16:40:34 +02:00
Mats Paul Tončik 124d65f8c9 Added eu projects for single persons by DOI publication mapping 2026-06-20 15:50:55 +02:00
Steven Tischer db5156a02d feat: display search findings directly in news
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 15:39:06 +02:00
Steven Tischer 9dadc1f12f extends es-client with highlighting 2026-06-20 15:33:16 +02:00
Louis b79816bafe Merge remote-tracking branch 'origin/ts-career-stage-backend' into ts-career-stage-backend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 15:31:41 +02:00
Louis 522c8ca3e8 Update career stage labels (frontend) 2026-06-20 15:30:31 +02:00
Steven Tischer 08cfec6be0 Replace author with "Relevant" label in news list 2026-06-20 15:15:23 +02:00
Mats Paul Tončik 28b57059b7 Added support for eu projects for other institutions than UDE 2026-06-20 15:12:33 +02:00
spsaefan 110977c847 Update career stage labels
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-20 10:55:41 +02:00
khalti c3944b71e0 Merge pull request 'ts-136-patent-to-researchers' (#154) from ts-136-patent-to-researchers into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #154
2026-06-19 22:41:47 +02:00
khalti 0cdacf20f7 fix: correct Author import path in patents logic
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-19 22:37:51 +02:00
khalti b4fe867eee fix: resolve merge conflicts with dev
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-19 22:26:11 +02:00
khalti fc9c18f965 feat(patents): add interactive detail view with source card navigation
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-19 22:05:47 +02:00
taguesokoudjou c211e8d210 fix: repair patent ES search and add name matching for inventor lookup
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 17:02:31 +02:00
Louis 79854123b6 correct career stage tooltip wording
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 15:01:19 +02:00
Louis ae04eae6e6 update career stage tooltip boundaries
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 14:57:58 +02:00
spsaefan 123db12ac4 Update career stage backend thresholds
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 14:46:42 +02:00
Louis 5def7ac5f1 fix(persons): include required detail fields in resolver
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 14:29:50 +02:00
Louis 013a3bd2a2 Merge remote-tracking branch 'origin/dev' into ts-career-stage-backend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 14:08:32 +02:00
Louis eba2b73c6b update career stage tooltip 2026-06-19 14:03:41 +02:00
Louis c62f284866 batch career metrics for search results 2026-06-19 13:35:17 +02:00
Mats Paul Tončik d86c871918 Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 12:43:39 +02:00
Mats Paul Tončik 7baddf2b54 Added projects search page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 12:33:51 +02:00
genja e9178cb26e Merge pull request 'feature/dfg-details' (#152) from feature/dfg-details into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #152
2026-06-19 11:39:47 +02:00
genja 466b36fb88 regenerated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-19 11:33:18 +02:00
genja 86cbe025ca Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details 2026-06-19 11:27:34 +02:00
Mats Paul Tončik 000b68758d Fixed navigation to single dfg project from person projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 10:48:17 +02:00
Mats Paul Tončik e7cf85116d Merge remote-tracking branch 'origin/feature/dfg-details' into researchers-to-projects 2026-06-19 10:37:37 +02:00
Mats Paul Tončik edb76054d5 Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 10:27:58 +02:00
Mats Paul Tončik 6cd32eecec Added funding visualization for institution cordis eu projects 2026-06-19 10:17:48 +02:00
Mats Paul Tončik 305ab7ba6a Updated institution eu projects to new cordis indices
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 09:40:52 +02:00
Roman 5396b45314 add sidebar collapse and refine company connections
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 05:26:25 +02:00
genja 226ab22e69 some layout adjustments
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-19 01:28:48 +02:00
genja 8d4045d428 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details 2026-06-19 00:53:37 +02:00
genja 17f52d1e2d regenerated services 2026-06-19 00:51:51 +02:00
genja 6c6f13de14 added an endpoint for single BUND project search + model 2026-06-19 00:51:40 +02:00
genja 4945e3d7e7 created single BUND project component 2026-06-19 00:50:01 +02:00
genja 37ef212304 added resolver for a single BUND project 2026-06-19 00:49:18 +02:00
Louis 7c85624c1c Merge remote-tracking branch 'origin/dev' into feature/timeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-18 23:40:13 +02:00
Louis fb9d2c23d9 Merge remote-tracking branch 'origin/dev' into feature/timeline 2026-06-18 23:37:58 +02:00
genja 2d3ff1a092 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details 2026-06-18 23:12:40 +02:00
Louis 6e3c5107f1 show career stage on person cards
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-18 23:09:32 +02:00
Louis 2eac8dc215 Merge remote-tracking branch 'origin/dev' into ts-career-stage-backend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-18 22:11:56 +02:00
Louis 6a6e07a0dc display career stage in profile 2026-06-18 22:10:41 +02:00
davletshin 70a517e456 Merge pull request 'company-connections' (#151) from company-connections into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #151
2026-06-18 19:05:05 +02:00
Roman 98ef93f642 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into company-connections
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-18 18:48:28 +02:00
genja 73e67fa336 minor display bug fixed
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-18 18:41:30 +02:00
genja dae9147cce added detailed overview page for a single DFG project 2026-06-18 18:40:53 +02:00
genja 44ab578078 regenerated models 2026-06-18 18:40:20 +02:00
genja 513cfeaed4 added new endpoint for searching single dfg project by id 2026-06-18 18:39:38 +02:00
genja dbd1616e36 created new detailed dfg project model 2026-06-18 18:33:31 +02:00
genja 09aeb537cf removed redundant data 2026-06-18 18:32:59 +02:00
genja f644473f3d added resolver for dfg project page 2026-06-18 18:32:40 +02:00
genja 75e7d2313e added navigating options to app-data-table component enabling navigating on click 2026-06-18 18:31:41 +02:00
genja 6f81849364 fixed institution autocomplete bug 2026-06-18 18:29:39 +02:00
genja 9711c4694d Merge branch 'researchers-to-projects' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details 2026-06-18 10:37:00 +02:00
Mats Paul Tončik 82e3bb514c Added funding graph for institution bund projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 22:33:57 +02:00
Louis d2aeb970da Merge remote-tracking branch 'origin/dev' into ts-career-stage-backend 2026-06-17 21:19:50 +02:00
Mats Paul Tončik 51a369de4a Removed border radius on app menu 2026-06-17 20:48:05 +02:00
Mats Paul Tončik 98ce10fcd4 Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 20:41:12 +02:00
Steven Tischer dc2ef6fd20 refactor person news to load via resolver
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 20:26:51 +02:00
Steven Tischer 11d20546b1 WIP: show news in author overview 2026-06-17 20:15:16 +02:00
Mats Paul Tončik 029bdb5bca Added institutions search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 20:03:42 +02:00
Steven Tischer b6618e030e feat: add info about article relevance to the news page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 13:18:08 +02:00
Steven Tischer 23da3e44ba feat(frontend/news_aritcle): show extracted authors 2026-06-17 13:08:46 +02:00
Steven Tischer 379f94ddc7 feat(backend/news): combine data from aktuell_postproc with news model 2026-06-17 13:06:41 +02:00
Steven Tischer ebdf0b8eab Merge branch 'dev' into feat/add_site_news
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 12:43:49 +02:00
Kazgatari b496cfd52c removed old code and truncated cards in person search to keep layout static
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 11:46:16 +02:00
khalti e9935207ea refactor: clean up patents module
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-17 09:55:01 +02:00
spsaefan dc573433d9 Log career metrics runtime
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 16:27:31 +02:00
erfanian bb066117bc Merge pull request 'ts-career-stage-backend' (#149) from ts-career-stage-backend into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #149
2026-06-16 15:55:54 +02:00
spsaefan a7d41237eb Merge dev into career stage backend
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-16 15:52:06 +02:00
spsaefan 13c4975932 add career stage
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 15:24:37 +02:00
genja 66e56fda29 removed slashes from Elastic Urls
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 14:34:48 +02:00
genja 7f387ee45d regenerated model 2026-06-16 14:33:21 +02:00
genja 9269af4c5d replaced institution autocompletion logic with wildcards 2026-06-16 11:41:59 +02:00
arzani a7620b1900 jenkins save docker step executed only in main
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 11:28:28 +02:00
Louis 6ecc0acc23 Merge remote-tracking branch 'origin/dev' into feature/timeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 10:44:52 +02:00
genja 48aad9f164 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/user-accounts 2026-06-16 08:02:56 +02:00
tischer 27987080ea Merge pull request 'fix 404 on root : redirect from root path to dashboard' (#148) from fix/404_root_page into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #148
2026-06-16 07:30:46 +02:00
Steven Tischer c92bb39683 redirect from root path to dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-16 07:03:25 +02:00
genja 1a174168f8 added uni ranking prototype to dashboard 2026-06-16 01:17:02 +02:00
Roman 563ade40e9 sample
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 23:58:26 +02:00
Roman 9ac9e1785e v1
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 23:55:21 +02:00
kallweit a5fe9728e8 feat(wordcloud): implement year slider, add colors, remove topic count slider
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 23:43:20 +02:00
kallweit bd39e16d9b feat(news): wire full-text search to global news page and client-side filter to person news tab
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 22:35:38 +02:00
taguesokoudjou 6d3e68a759 fix: remove ORCID from patent disambiguation scoring
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 21:43:21 +02:00
Louis 79105b83b9 timeline: use aggregations for topic counts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 21:42:42 +02:00
Louis 678ab84995 timeline: reduce stylesheet size
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 20:59:51 +02:00
Louis 3b220051a2 Timeline: show topic count tooltips
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-15 20:51:36 +02:00
taguesokoudjou c298a388d0 fix: resolve patents build error
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 20:41:32 +02:00
taguesokoudjou 0dd03e0ae0 feat: improve patent matching with disambiguation pipeline and caching
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-15 20:27:21 +02:00
Louis bad95c65dd Timeline: show topic description on hover (frontend)
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 20:26:59 +02:00
genja 8949e6d1c6 Merge pull request 'feature/user-accounts' (#147) from feature/user-accounts into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #147
2026-06-15 19:14:53 +02:00
genja 9de6d4408d undid openapi config push
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 19:12:12 +02:00
genja 5065de562d Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/user-accounts
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 19:05:23 +02:00
genja e52204a90d fixed routing logic 2026-06-15 19:05:02 +02:00
genja 8515a01ff4 fixed institutuin autocompletion logic, used existing elastic wrapper for queries 2026-06-15 19:04:44 +02:00
Steven Tischer 977ac97241 add page news
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 17:46:20 +02:00
taguesokoudjou ba8a9216e6 Merge pull request 'ts-86-funding-design-improvements' (#146) from ts-86-funding-design-improvements into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #146
2026-06-15 17:29:21 +02:00
taguesokoudjou eb4937bedf Merge dev into funding design improvements
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 17:27:32 +02:00
Steven Tischer d465ef6915 Merge branch 'dev' into feat/add_site_news
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 17:16:21 +02:00
taguesokoudjou 3fc0b5ca19 Reduce person-funding component styles below 10 kB CI budget
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-15 16:52:48 +02:00
genja eed69a75b4 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/user-accounts 2026-06-15 16:29:33 +02:00
kuzko 8a77a3425f Merge pull request 'feature/keyword_search' (#144) from feature/keyword_search into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #144
2026-06-15 08:52:18 +02:00
Kazgatari e24a6ca49b regenerate frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-15 08:34:01 +02:00
Kazgatari 7d869d8a82 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/keyword_search 2026-06-15 08:18:00 +02:00
genja 60ba32e563 minor layout fixes
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-15 01:50:29 +02:00
genja bd9e38c6cf fix(auth): adjust interceptor bypass rules for auth and autocomplete endpoints 2026-06-15 01:50:07 +02:00
genja a34119b22c fixed wrong endpoint recognition in institute autocompletion 2026-06-15 01:45:46 +02:00
genja 3037215506 added email and organization_name to user credentials 2026-06-15 01:43:47 +02:00
genja 28b8fff4dd added users register component 2026-06-15 01:41:37 +02:00
genja a2ed442dcc adjusted confirmation dialog component for reusability 2026-06-15 01:38:42 +02:00
Mats Paul Tončik 152679e3e9 Merge branch 'researchers-to-projects' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 23:42:16 +02:00
Mats Paul Tončik b88f459bde Added dfg projects for single persons
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 23:39:22 +02:00
Mats Paul Tončik 28a77796a2 Added resolving indicator to app menu
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 13:32:01 +02:00
Mats Paul Tončik fdc59d8b0b Fixed error page logic for resolvers
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 12:53:40 +02:00
Mats Paul Tončik 1874f41fb0 Added error page 2026-06-14 12:18:19 +02:00
Mats Paul Tončik 7d7bd87201 Reused generic data table for person network tables 2026-06-14 12:17:53 +02:00
khalti bc7b7784ea feat: add patent-to-researchers backend and frontend
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 11:43:48 +02:00
spsaefan db853f72a1 Fix person detail runtime
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 01:05:17 +02:00
spsaefan e5efd351f0 Update person response
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-14 00:27:57 +02:00
spsaefan 11eb898745 Compute career metrics for person detail 2026-06-14 00:23:38 +02:00
spsaefan 08669a4776 Add career metrics 2026-06-14 00:23:11 +02:00
erfanian 3437a8288d Merge pull request 'ts-add-description-to-timeline' (#143) from ts-add-description-to-timeline into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #143
2026-06-13 22:25:41 +02:00
erfanian 4536adafc4 Merge branch 'dev' into ts-add-description-to-timeline
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-13 22:23:40 +02:00
spsaefan 0780271109 Add topic descriptions to timeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-13 22:17:53 +02:00
Kazgatari 32fdd1281c exclude description & siblings field for now from the topicvector retrieval
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-13 13:34:28 +02:00
Mats Paul Tončik 7f2d0aa6b0 Merge branch 'dev' into researchers-to-projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-13 12:35:03 +02:00
Mats Paul Tončik 997c573295 Added search for institution bund and eu projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-13 12:33:40 +02:00
Kazgatari 96b59888f3 Added second static image (additional dockerfile & Gradle build change)
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-13 09:17:07 +02:00
Kazgatari 6aaeaad580 Changed to Hybrid appraoch with Reciprocal Rank Fusion (RRF)
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-12 21:40:56 +02:00
genja 7657a61674 Merge pull request 'caching added' (#140) from caching into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #140
2026-06-12 18:51:39 +02:00
genja 2b6f6bfc51 removed interceptor logic, enabling browser caching only
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-12 18:31:29 +02:00
genja 0d16159a23 5 minutes expiration time set for ETags 2026-06-12 18:31:00 +02:00
Kazgatari 89ab84bcb6 Increase size to 50 for now. Added Transient logging to finetune return similarity cutoff
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-12 14:05:14 +02:00
Louis 0c52b6f324 Timeline: add publication count tooltips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-12 12:50:22 +02:00
Kazgatari 15392b5757 Exclude vectors from response 2026-06-12 12:50:10 +02:00
Louis 12f866a9d4 integrate wordcloud view in timeline 2026-06-12 12:23:49 +02:00
Kazgatari bca5bf74bf Implemented Sentence-Transformer (Setup, Backend & Frontend) => downloading custom torch wheel to not pull gpu packages 2026-06-12 12:10:47 +02:00
taguesokoudjou 5fa764e7e8 Improve funding list filters and empty-state overview for clearer navigation
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-12 09:10:05 +02:00
kallweit 7442a56b0a feat(news-tab): add news tab and details page to person overview
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-11 21:40:26 +02:00
genja f417374827 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into caching
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-11 19:24:37 +02:00
genja ecc6aabfa3 Merge pull request 'ts-82-author-overview-and-description' (#137) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #137
2026-06-11 19:23:42 +02:00
genja 4e1ea6d04c added h_index to displayed data
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-11 19:21:30 +02:00
genja f288fb7306 added sorting by h_index 2026-06-11 19:21:23 +02:00
genja 2836cf02a7 removed mead_citedness from person scroing strategy 2026-06-11 19:11:47 +02:00
genja f7c7a9751a removed debug info from console
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-11 18:37:29 +02:00
genja c2b8f54fb7 added ETag caching
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-11 18:34:58 +02:00
genja 229c4126de removed name_quality_boost from person list ranking 2026-06-11 11:55:47 +02:00
Mats Paul Tončik b657508f1a Added institution based finding of bund and eu projects
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-10 21:24:26 +02:00
Steven Tischer 9432d01135 add news module with business logic and models
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-10 19:18:31 +02:00
tischer 16d302842c Merge pull request 'add cluster parameter to elasticsearch integration (nes/inse)' (#135) from feat/add_inse_elasticsearch_cluster into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #135
2026-06-10 16:34:39 +02:00
Steven Tischer b0b2ca2085 add cluster parameter to elasticsearch integration (nes/inse)
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-10 16:30:10 +02:00
genja 9bd86b391b Merge pull request 'ts-82-author-overview-and-description' (#134) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #134
2026-06-10 14:32:16 +02:00
genja 560af6a1eb updated loadingState computing
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-10 14:28:37 +02:00
genja 8e284916e6 added resolver for person component 2026-06-10 14:25:20 +02:00
genja 6979aaef8d fixed loading component 2026-06-10 14:22:03 +02:00
genja abe96098b5 increased timeout for elastic rqeuests up to 30 seconds 2026-06-10 14:13:58 +02:00
genja 0f212d189e removed fuzziness from person names matching + added applying rescoring strategy when query is empty 2026-06-10 14:13:28 +02:00
genja 486ea0d2ba Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-10 11:23:03 +02:00
tischer 103b783635 Merge pull request 'feat/improve_bio_gen' (#127) from feat/improve_bio_gen into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #127
2026-06-10 11:04:45 +02:00
Steven Tischer 84f1cdfead load bio via non-blocking route resolver
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-10 09:35:57 +02:00
Steven Tischer 517b974ef2 add get_data_for_bio to fetch author data for bio generation 2026-06-10 09:11:52 +02:00
Steven Tischer d4eaf343e7 change system_prompt & temperature/top_p 2026-06-10 08:03:30 +02:00
Kazgatari b114e33767 corrected wrong import statements
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 21:44:17 +02:00
Kazgatari 0ed80e2b36 changed model file structure in backend. Added generated models from other indices. 2026-06-09 21:36:06 +02:00
tischer d516660e36 Merge pull request 'fix/slow_author_interesting' (#126) from fix/slow_author_interesting into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #126
2026-06-09 20:37:10 +02:00
Steven Tischer fc123d81aa replace * marker with paper icon
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-09 20:18:28 +02:00
genja 58156025e9 replaced old person search logic by the new rescored logic
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 19:02:31 +02:00
genja aa28aa0e02 sorting logic in UI fixed 2026-06-09 19:00:11 +02:00
genja fe89113ad6 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-09 18:57:59 +02:00
Steven Tischer 903ee594a3 count primary topics via ES aggregation instead of full works
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 18:55:24 +02:00
genja f0a8363536 added relevancy rescoring for persons search based on publications, citations, h_index, mean_citations and name quality 2026-06-09 18:23:59 +02:00
genja bc99b6deb8 moved sorting logic to backend 2026-06-09 18:21:16 +02:00
genja e9d931fe74 UI adjusted 2026-06-09 18:20:11 +02:00
tischer 16d2f3ecf5 Merge pull request 'remove terminal prefix' (#125) from feat/add_code_formater into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #125
2026-06-09 17:55:02 +02:00
tischer 5b8a20b0ac Merge branch 'dev' into feat/add_code_formater
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 17:50:46 +02:00
Steven Tischer 5e49e75160 remove terminal prefix
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-09 17:47:43 +02:00
tischer 9746346919 Merge pull request 'feat/add_code_formater' (#124) from feat/add_code_formater into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #124
2026-06-09 17:40:41 +02:00
Steven Tischer 9479192f01 add Prettier pre-commit hook instructions to README
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-09 17:36:45 +02:00
Steven Tischer 72dc3bd852 add pre-commit hook for automatic code formatting with Prettier 2026-06-09 17:33:50 +02:00
Steven Tischer 91eb08a083 add package.json and package-lock.json for Prettier configuration 2026-06-09 17:33:39 +02:00
Steven Tischer 7ff0eda286 run formatter across entire project 2026-06-09 12:50:17 +02:00
Steven Tischer 59035f97ed add Prettier configuration file for code formatting 2026-06-09 12:46:46 +02:00
Mats Paul Tončik c58a8da461 Readded missing single work retrieval logic
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 10:07:53 +02:00
genja 6eb2ecb466 Merge pull request 'ts-82-author-overview-and-description' (#123) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #123
2026-06-09 01:33:28 +02:00
genja a247ff7cac added loading component for persons bio
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-09 01:31:49 +02:00
genja 68f239e808 minimal width for loading skeleton directive adjusted 2026-06-09 01:31:29 +02:00
taguesokoudjou bd958d1621 Merge pull request 'Improve funding publication detail view with richer metadata and clearer layout' (#122) from ts-86-funding-design-improvements into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #122
2026-06-08 23:46:56 +02:00
taguesokoudjou 3c08bc1866 Improve funding publication detail view with richer metadata and clearer layout
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-08 23:40:15 +02:00
Louis 88f9474443 Style the earlier-years control as a distinct action button
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 23:30:58 +02:00
kallweit 78990d9b73 Merge pull request 'ts-84-word-cloud-v2' (#121) from ts-84-word-cloud-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #121
2026-06-08 23:19:15 +02:00
kallweit 701931d641 fix(wordcloud): update package-lock.json
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-08 23:09:45 +02:00
kallweit fc03a69ad3 fix(wordcloud): remove duplicate code after rebase
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 22:55:43 +02:00
kallweit 4a909ab166 Merge branch 'ts-84-word-cloud-v2' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-84-word-cloud-v2
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-08 22:49:49 +02:00
kallweit 90d3a8aa21 fix(wordcloud): merge with older version 2026-06-08 22:47:36 +02:00
kallweit e9b4cbc0c7 feat(wordcloud): integrate wordcloud in person overview page 2026-06-08 22:47:17 +02:00
kallweit 0ae41ef95e feat(wordcloud): change hover effect for topics 2026-06-08 22:44:04 +02:00
kallweit a5f7204b59 feat(wordcloud): integrate wordcloud in person overview page 2026-06-08 22:44:04 +02:00
kallweit 81c7bee3d8 fix(wordcloud): merge with older version
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 22:33:28 +02:00
Louis e758fb5f96 Merge remote-tracking branch 'origin/dev' into ts-85-add-topic-id-to-timeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 22:29:39 +02:00
kallweit 585ac19c12 Merge branch 'ts-84-word-cloud-v2' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-84-word-cloud-v2
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-08 22:27:39 +02:00
kallweit 8dc9f0bccd feat(wordcloud): change hover effect for topics 2026-06-08 22:26:57 +02:00
Kazgatari b62dd33a33 Adapted the chip design of topics from Forschungtimeline. Implemented routing to Publication search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 22:20:48 +02:00
Louis b41b19a40f Timeline: limit initial publication loading
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 22:07:08 +02:00
Louis b7c8a6cfdc Timeline: add manual loading for earlier years 2026-06-08 21:12:36 +02:00
kallweit a00e8a88e4 feat(wordcloud): integrate wordcloud in person overview page 2026-06-08 21:00:13 +02:00
genja 17607d856b Merge pull request 'ts-82-author-overview-and-description' (#120) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #120
2026-06-08 17:45:58 +02:00
genja 250b5c2de9 added loading component for persons loadings
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-06-08 17:41:15 +02:00
genja 9cfd4e9b87 added loading component 2026-06-08 17:40:05 +02:00
genja 282d761c02 added resolver state service 2026-06-08 17:34:49 +02:00
tischer 5a83c7eb52 Merge pull request 'feat/show_description_to_author_topics' (#119) from feat/show_description_to_author_topics into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #119
2026-06-08 16:36:03 +02:00
Steven Tischer 05fabbb231 Merge branch 'dev' into feat/show_description_to_author_topics
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-08 16:28:32 +02:00
genja ad900a69d7 Merge pull request 'ts-82-author-overview-and-description' (#118) from ts-82-author-overview-and-description into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #118
2026-06-08 15:40:01 +02:00
genja cad97057cf Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-08 15:34:21 +02:00
genja efd9d62477 fixed FormControl <-> Query Params binding
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 15:17:39 +02:00
genja 60fa0e0a45 applied loading skeletion for text data 2026-06-08 15:17:08 +02:00
genja 4ff574e9f1 removed search value from shared state 2026-06-08 15:16:41 +02:00
kallweit c9601b06a2 feat(wordcloud): integrate wordcloud in person overview page
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-08 15:15:07 +02:00
genja a82e76bdef added and applied person-list resolver 2026-06-08 15:10:52 +02:00
genja cf43330206 added loading skeleton directive for text data 2026-06-08 15:06:53 +02:00
Kazgatari 351f43aca6 Changed icon to match the one in Network. Added autocomplete to institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 14:39:52 +02:00
kuzko 0f838e3429 Merge pull request 'refactor/person-list' (#117) from refactor/person-list into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #117
2026-06-08 12:49:32 +02:00
Kazgatari 9a6166b4ee Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/person-list
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-08 12:44:22 +02:00
Kazgatari 4701f294d0 removed old Institution, changes default sort to Publications 2026-06-08 12:43:29 +02:00
genja 755488fef7 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-08 12:01:07 +02:00
Kazgatari a7a579ef57 Truncation, mouseover and populate filter button in person-list 2026-06-08 11:23:14 +02:00
Kazgatari 038fdb8899 Pagination 2026-06-08 10:39:55 +02:00
erfanian 8d412fef4a Merge pull request 'ts-85-limit-timeline-complete-years' (#116) from ts-85-limit-timeline-complete-years into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #116
2026-06-08 10:16:25 +02:00
Kazgatari 52efe1a45a added clickable card body
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-08 09:34:36 +02:00
Kazgatari 801f7419c5 Extracted person card into own component & added link to card header. disable Frontend institution checkbox until Institution selected 2026-06-08 09:29:07 +02:00
Kazgatari c75203c755 removed old filter code 2026-06-08 09:09:28 +02:00
spsaefan 770f2b31e1 Add timeline API options
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-08 01:25:03 +02:00
spsaefan 3325590735 Limit timeline publications 2026-06-08 01:24:49 +02:00
Louis 8e1ac13ca7 Align topic count badges in yearly and compact timeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-07 23:22:34 +02:00
Louis d79d0b842e Further reduce research timeline style size
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-07 23:06:17 +02:00
Louis 6e64b3a633 Reduce research timeline style size
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-07 23:01:23 +02:00
Louis 8ce107f9e0 Refine research timeline publication layout
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-06-07 22:54:42 +02:00
Louis 41f34a2e1b Show primary topic counts in research timeline 2026-06-07 22:45:02 +02:00
Louis c482a917b2 Add year filter navigation from timeline labels 2026-06-07 22:16:14 +02:00
Louis 472ff1208e Add year-only navigation from research timeline 2026-06-07 22:04:05 +02:00
Louis f903e417ad Fix timeline topic year selection
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-07 21:34:26 +02:00
Steven Tischer f01f17dbaf show topic description tooltip in interesting-for card
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 20:18:27 +02:00
Steven Tischer ac69aa3915 regenerate OpenAPI client 2026-06-06 20:18:07 +02:00
Steven Tischer 68c354ad82 add topic descriptions to primary topic counts 2026-06-06 20:16:48 +02:00
genja 135705adc9 removed redundant proprerty
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-06 14:49:41 +02:00
genja ca6ab84465 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description 2026-06-06 14:45:42 +02:00
genja 44bd8c6ce5 added persons filtering 2026-06-05 17:22:19 +02:00
542 changed files with 43127 additions and 6534 deletions
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0
# Prettify all selected files
echo "$FILES" | xargs ./node_modules/.bin/prettier --ignore-unknown --write
# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add
exit 0
+20 -17
View File
@@ -1,17 +1,20 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
# Ignore vscode metadata
.vscode
# Ingore pyhton cache
__pycache__
# Ignore macos
.DS_Store
# Ignore generated python code
src/python/account/
*.pyc
node_modules/
angular-app/.angular
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
# Ignore vscode metadata
.vscode
# Ingore pyhton cache
__pycache__
# Ignore macos
.DS_Store
# Ignore generated python code
src/python/account/
*.pyc
node_modules/
angular-app/.angular
# Ignore sentence-transformer local model cache
service/sentence_transformer/models/␍
+11
View File
@@ -0,0 +1,11 @@
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"semi": true,
"bracketSpacing": true,
"arrowParens": "always",
"trailingComma": "all",
"bracketSameLine": true,
"printWidth": 80
}
Vendored
+3
View File
@@ -28,6 +28,9 @@ pipeline {
}
stage('Save Docker image') {
when {
branch 'main'
}
steps {
sh 'docker save ${IMAGE_PREFIX}-app:${IMAGE_VERSION} | gzip > app-image.tar.gz'
}
+56 -40
View File
@@ -12,11 +12,11 @@ A minimal full-stack web application using Docker, Gradle, FastAPI and Angular.
## Build System: Gradle (Root)
| File | Purpose |
|------|---------|
| build.gradle | Root config defining Docker image name (`inse`), prefix, and version (`1.0.0`) |
| settings.gradle | Declares the three submodules: `:service`, `:webapp`, `:app` |
| libs.versions.toml | Centralized dependency version catalog |
| File | Purpose |
| ------------------ | ------------------------------------------------------------------------------ |
| build.gradle | Root config defining Docker image name (`inse`), prefix, and version (`1.0.0`) |
| settings.gradle | Declares the three submodules: `:service`, `:webapp`, `:app` |
| libs.versions.toml | Centralized dependency version catalog |
Gradle orchestrates the entire build, including Docker image creation and the Angular frontend.
@@ -26,36 +26,38 @@ Gradle orchestrates the entire build, including Docker image creation and the An
A REST API running in Docker, exposing **three mounted FastAPI sub-applications**:
| Mount path | Description |
|---|---|
| `/inse-service` | Main resource API (items CRUD) |
| `/inse-webapp` | Serves the static Angular SPA |
| Mount path | Description |
| --------------- | ------------------------------------- |
| `/inse-service` | Main resource API (items CRUD) |
| `/inse-webapp` | Serves the static Angular SPA |
| `/inse-account` | Authentication service (login/tokens) |
### Key source files in inse:
| File | Role |
|---|---|
| main.py | FastAPI app bootstrap, mounts the three sub-apps |
| service.py | CRUD REST endpoints for `Item` resources (GET, POST, PUT, DELETE), protected by JWT roles |
| model.py | Pydantic response models: `Item`, `ItemCreate`, `ItemPage` (generic pagination) |
| schema.py | SQLAlchemy ORM table definitions — `Item` table in SQLite |
| logic.py | Business logic layer (called by the service) |
| database.py | SQLAlchemy engine/session setup, reads from `config` |
| security.py | JWT decoding, `Principal` / `Account` models, role-based access via `roles_allowed()` |
| config.py | App settings via env vars prefixed `inse_` (DB URL, auth secret, feature flags) |
| webapp.py | Mounts the static Angular build as a `StaticFiles` app |
| util.py | Utility helpers (e.g. `raise_not_found_if_none`) |
| File | Role |
| ----------- | ----------------------------------------------------------------------------------------- |
| main.py | FastAPI app bootstrap, mounts the three sub-apps |
| service.py | CRUD REST endpoints for `Item` resources (GET, POST, PUT, DELETE), protected by JWT roles |
| model.py | Pydantic response models: `Item`, `ItemCreate`, `ItemPage` (generic pagination) |
| schema.py | SQLAlchemy ORM table definitions — `Item` table in SQLite |
| logic.py | Business logic layer (called by the service) |
| database.py | SQLAlchemy engine/session setup, reads from `config` |
| security.py | JWT decoding, `Principal` / `Account` models, role-based access via `roles_allowed()` |
| config.py | App settings via env vars prefixed `inse_` (DB URL, auth secret, feature flags) |
| webapp.py | Mounts the static Angular build as a `StaticFiles` app |
| util.py | Utility helpers (e.g. `raise_not_found_if_none`) |
### `account/` sub-package (account):
Handles authentication independently:
- account/service.py — `POST /auth/id` (username+password → identity token) and `POST /auth/access` (ID token → access token)
- account/logic.py — validates users from users.json
- account/model.py — Pydantic models for `IdentityGrant`, `AccessGrant`
- account/security.py — JWT signing
### Data & Config:
- users.json — Hardcoded user accounts (superadmin/user)
- log-config.yaml — Logging configuration
- entrypoint.sh — Docker entrypoint script
@@ -69,20 +71,20 @@ An **Angular 18 SPA** using Angular Material, built with Node.js + Gradle.
### App structure in app:
| Directory/File | Role |
|---|---|
| app.routes.ts | Routes: `/login` → `AppLoginComponent`, `/items` → `ListItemComponent` (guarded), `**` → redirect to login |
| app.config.ts | Angular app bootstrap config (providers, interceptors) |
| `app-login/` | Login form component |
| `app-layout/` | Shell/layout wrapper component |
| `app-menu/` | Navigation menu component |
| `list-item/` | The main feature page — lists `Item` resources with pagination |
| `confirmation-dialog/` | Reusable dialog for destructive actions |
| `guards/` | Route guards: `user.guard.ts` (authenticated), `admin.guard.ts` (admin role) |
| `interceptors/` | authentication.interceptor.ts — attaches JWT Bearer token to all requests except auth endpoints |
| `services/` | api.service.ts (CRUD calls to `/inse-service`), `credential.service.ts` (token management), `pagination.service.ts` |
| `pipes/` | `truncate.pipe.ts` — truncates long strings in templates |
| `utils/` | Utility helpers |
| Directory/File | Role |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------- |
| app.routes.ts | Routes: `/login` → `AppLoginComponent`, `/items` → `ListItemComponent` (guarded), `**` → redirect to login |
| app.config.ts | Angular app bootstrap config (providers, interceptors) |
| `app-login/` | Login form component |
| `app-layout/` | Shell/layout wrapper component |
| `app-menu/` | Navigation menu component |
| `list-item/` | The main feature page — lists `Item` resources with pagination |
| `confirmation-dialog/` | Reusable dialog for destructive actions |
| `guards/` | Route guards: `user.guard.ts` (authenticated), `admin.guard.ts` (admin role) |
| `interceptors/` | authentication.interceptor.ts — attaches JWT Bearer token to all requests except auth endpoints |
| `services/` | api.service.ts (CRUD calls to `/inse-service`), `credential.service.ts` (token management), `pagination.service.ts` |
| `pipes/` | `truncate.pipe.ts` — truncates long strings in templates |
| `utils/` | Utility helpers |
---
@@ -111,7 +113,6 @@ Browser
**Auth flow**: The Angular interceptor calls `/inse-account/auth/id` with credentials → receives an ID token → exchanges it for an access JWT via `/inse-account/auth/access` → attaches the access token as `Authorization: Bearer` on all subsequent requests. The backend's security.py decodes and validates this JWT to enforce role-based access control (`SUPER_ADMIN`, `UNI_ADMIN`).
## Prerequisites
- Docker
@@ -155,7 +156,22 @@ The app will be available at `http://localhost:8080/inse-webapp/`.
Defined in `service/src/data/users.json`:
| Username | Password | Role |
|-------------|-------------|-------------|
| superadmin | superadmin | SUPER_ADMIN |
| user | user | UNI_ADMIN |
| Username | Password | Role |
| ---------- | ---------- | ----------- |
| superadmin | superadmin | SUPER_ADMIN |
| user | user | UNI_ADMIN |
## Prettier pre-commit hook
- Install Prettier
```bash
npm install
```
- To enable automatic code formatting with Prettier on commit, copy the pre-commit hook script to the Git hooks directory and make it executable:
```shell
cp .githooks/pre-commit .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
```
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "smartguide",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"devDependencies": {
"prettier": "^3.8.3"
}
},
"node_modules/prettier": {
"version": "3.8.3",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.3.tgz",
"integrity": "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"devDependencies": {
"prettier": "^3.8.3"
}
}
+8
View File
@@ -0,0 +1,8 @@
UNIVERSITAET DUISBURG-ESSEN
UNIVERSITAET DUISBURG-ESSEN - STANDORT DUISBURG
UNIVERSITÄT DUISBURG-ESSEN
UNIVERSITAET DUISBURG-ESSEN - STANDORT ESSEN
UNIVERSITAET DUISBURG-ESSEN (UNIVERSITY OF DUISBURG-ESSEN)
UNIVERSITAT DUISBURG-ESSEN
UNIVERSITY OF DUISBURG-ESSEN
UNIVERSITÄT DUISBURG ESSEN
+6 -7
View File
@@ -1,9 +1,7 @@
FROM python:3.12-slim-bookworm
ARG BASE_IMAGE=inse-base-static:latest
FROM $BASE_IMAGE
RUN mkdir /test && \
mkdir /data && \
pip install --root-user-action=ignore --no-cache-dir --upgrade pip && \
pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-check \
RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-check \
"fastapi~=0.115.0" \
"SQLAlchemy~=2.0.0" \
"pyjwt~=2.8.0" \
@@ -15,8 +13,9 @@ RUN mkdir /test && \
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"\
"elasticsearch~=9.4.0" \
"openai~=2.41.0"
"openai~=2.41.0" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+10
View File
@@ -0,0 +1,10 @@
FROM python:3.12-slim-bookworm
RUN mkdir /test && \
mkdir /data && \
pip install --root-user-action=ignore --no-cache-dir --upgrade pip && \
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
ENV SENTENCE_TRANSFORMERS_HOME=/models
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('paraphrase-multilingual-mpnet-base-v2')"
+2 -2
View File
@@ -10,8 +10,8 @@ To build the container: `./gradlew :service:build`
To launch the service with hot-reload: `./gradlew :service:serve`
This mounts the source directory into the container and enables uvicorn hot-reloading. Press *ENTER* to stop.
This mounts the source directory into the container and enables uvicorn hot-reloading. Press _ENTER_ to stop.
## Testing
Run tests: `./gradlew :service:test`
Run tests: `./gradlew :service:test`
+26 -1
View File
@@ -2,7 +2,32 @@ plugins {
id 'base'
}
task createBaseImage(type: Exec) {
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-f', 'Dockerfile.base', '-t', "${imagePrefix}-base-static:latest", '.'
}
task buildBaseImageIfNeeded {
doLast {
def baseImage = "${imagePrefix}-base-static:latest"
def checkCmd = ["docker", "image", "inspect", baseImage]
def process = checkCmd.execute()
process.waitFor()
if (process.exitValue() != 0) {
println "Base image ${baseImage} not found. Building it..."
def buildCmd = ["docker", "build", "--platform", "${targetPlatform}", "-f", "Dockerfile.base", "-t", baseImage, "."]
def buildProcess = buildCmd.execute([], projectDir)
buildProcess.consumeProcessOutput(System.out, System.err)
if (buildProcess.waitFor() != 0) {
throw new GradleException("Failed to build base image.")
}
} else {
println "Base image ${baseImage} found. Skipping build."
}
}
}
task createImage(type: Exec) {
dependsOn buildBaseImageIfNeeded
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-t', "${imagePrefix}-service:${imageVersion}", '.'
}
@@ -24,7 +49,7 @@ task exportOpenApiSpec(type: Exec) {
commandLine 'docker', 'run', '--rm',
'--platform', "${targetPlatform}",
'-w', '/home',
'-v', "${projectDir}/src/main:/home",
//'-v', "${projectDir}/src/main:/home", the source code is already baked into the image at build time
'-v', "${openApiDir}:/mnt/openapi",
'-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'",
'--name', "${imageName}-service-openapi",
+12 -2
View File
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
dependencies = [
"cryptography~=42.0.0",
"dotenv>=0.9.9",
"elasticsearch~=9.4.0",
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
@@ -17,6 +16,17 @@ dependencies = [
"pytest~=8.1.0",
"python-multipart~=0.0.19",
"pyyaml~=6.0.1",
"sqlalchemy~=2.0.0",
"uvicorn~=0.29.0",
"sentence-transformers~=5.5.1",
"torch",
"sqlmodel~=0.0.33",
"argon2-cffi~=25.1.0",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
@@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""
Download the sentence-transformers model to the default cache directory
so it is available for local runs or testing.
Usage (run once from project root):
python service/sentence_transformer/download_model.py
"""
from sentence_transformers import SentenceTransformer
MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
model = SentenceTransformer(MODEL_NAME)
print("Done.")
@@ -0,0 +1,237 @@
#!/usr/bin/env python3
"""
Script to fetch all topics from 'openalex-topics',
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector mapping.
"""
import sys
import json
from pathlib import Path
import httpx
from dotenv import load_dotenv
# Add service/src/main to python path to load settings
current_dir = Path(__file__).parent.resolve()
project_root = current_dir.parent.parent.resolve()
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
load_dotenv(dotenv_path=env_path)
sys.path.append(str(project_root / "service" / "src" / "main"))
from inse.config import settings
ELASTIC_URL = settings.elasticsearch_url
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
ELASTIC_URL += "/"
API_KEY = settings.elasticsearch_api_key
MODEL_NAME = settings.sentence_transformers_model_name
# Import sentence-transformers
from sentence_transformers import SentenceTransformer
headers = {
"Authorization": f"ApiKey {API_KEY}",
"Content-Type": "application/json"
}
def fetch_all_topics():
print("Fetching topics from 'openalex-topics'...")
topics = []
size = 1000
offset = 0
with httpx.Client(timeout=60.0) as client:
while True:
payload = {
"query": {"match_all": {}},
"from": offset,
"size": size
}
resp = client.post(
f"{ELASTIC_URL}openalex-topics/_search",
json=payload,
headers=headers
)
resp.raise_for_status()
data = resp.json()
hits = data.get("hits", {}).get("hits", [])
if not hits:
break
topics.extend(hits)
offset += len(hits)
print(f"Fetched {len(topics)} topics so far...")
if len(hits) < size:
break
print(f"Total topics fetched: {len(topics)}")
return topics
def update_mappings():
print("Checking/updating mappings for 'topicvectors'...")
mapping_payload = {
"properties": {
"display_name_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"description_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"keyword_vectors": {
"type": "nested",
"properties": {
"vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
}
}
}
}
}
with httpx.Client(timeout=30.0) as client:
# Check if index exists
check_resp = client.get(f"{ELASTIC_URL}topicvectors", headers=headers)
if check_resp.status_code == 404:
print("Index 'topicvectors' does not exist. Creating it...")
create_payload = {
"mappings": mapping_payload
}
resp = client.put(f"{ELASTIC_URL}topicvectors", json=create_payload, headers=headers)
resp.raise_for_status()
else:
print("Index 'topicvectors' exists. Updating mappings...")
resp = client.put(f"{ELASTIC_URL}topicvectors/_mapping", json=mapping_payload, headers=headers)
resp.raise_for_status()
print("Mappings update process completed.")
def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list):
print("Bulk indexing vectorized topics into 'topicvectors'...")
batch_size = 500
with httpx.Client(timeout=60.0) as client:
for i in range(0, len(topics), batch_size):
batch_topics = topics[i:i+batch_size]
batch_name_vecs = display_name_vectors[i:i+batch_size]
batch_desc_vecs = description_vectors[i:i+batch_size]
batch_kw_vecs_list = keyword_vectors_list[i:i+batch_size]
bulk_lines = []
for t, name_vec, desc_vec, kw_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs, batch_kw_vecs_list):
source = t["_source"]
source.pop("siblings", None) # drop siblings field when making the copy
# Assign name vector as a standard float list
source["display_name_vector"] = name_vec.tolist()
# Assign description vector
source["description_vector"] = desc_vec.tolist()
# Assign nested keyword vectors
source["keyword_vectors"] = [
{"vector": vec.tolist()} for vec in kw_vecs
]
# Meta line
meta = {"index": {"_index": "topicvectors", "_id": t["_id"]}}
bulk_lines.append(json.dumps(meta))
# Document line
bulk_lines.append(json.dumps(source))
payload = "\n".join(bulk_lines) + "\n"
resp = client.post(
f"{ELASTIC_URL}_bulk",
content=payload,
headers={"Authorization": f"ApiKey {API_KEY}", "Content-Type": "application/x-ndjson"}
)
resp.raise_for_status()
resp_data = resp.json()
if resp_data.get("errors"):
print("Bulk indexing encountered errors! First few failed items:")
failed_items = [item for item in resp_data.get("items", []) if item.get("index", {}).get("status", 200) >= 400]
for item in failed_items[:5]:
print(json.dumps(item, indent=2))
raise ValueError("Bulk indexing failed with document errors.")
print(f"Indexed batch {i} to {i + len(batch_topics)}")
def main():
update_mappings()
topics = fetch_all_topics()
if not topics:
print("No topics found. Exiting.")
return
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
model = SentenceTransformer(MODEL_NAME)
# 1. Gather all texts to embed
keywords_by_topic = []
all_texts_to_embed = []
for t in topics:
source = t["_source"]
name = source.get("display_name") or ""
all_texts_to_embed.append(name)
desc = source.get("description") or ""
all_texts_to_embed.append(desc)
kws = source.get("keywords") or []
if not isinstance(kws, list):
kws = [kws] if kws else []
keywords_by_topic.append(kws)
all_texts_to_embed.extend(kws)
print(f"Embedding {len(all_texts_to_embed)} texts (display names, descriptions, and keywords)...")
all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32)
# 2. Map embeddings back to topics
display_name_vectors = []
description_vectors = []
keyword_vectors_list = []
vector_idx = 0
for idx, t in enumerate(topics):
display_name_vectors.append(all_vectors[vector_idx])
vector_idx += 1
description_vectors.append(all_vectors[vector_idx])
vector_idx += 1
kws = keywords_by_topic[idx]
topic_kw_vecs = []
for _ in range(len(kws)):
topic_kw_vecs.append(all_vectors[vector_idx])
vector_idx += 1
keyword_vectors_list.append(topic_kw_vecs)
# Bulk index
bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list)
print("Done!")
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
{
"organizations": [
{
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
"name": "The Super Admin Organization"
},
{
"name": "Universität Duisburg-Essen",
"openalex_instution_id": "https://openalex.org/I62318514"
},
{
"name": "Ruhr-Universität Bochum",
"openalex_instution_id": "https://openalex.org/I904495901"
},
{
"name": "TU Dortmund",
"openalex_instution_id": "https://openalex.org/I200332995"
}
],
"accounts": [
{
"email": "super@admin.com",
"password": "superadmin",
"name": "Super Admin",
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
"role": "SUPER_ADMIN"
}
]
}
+1 -1
View File
@@ -27095,4 +27095,4 @@
"field": "Medicine",
"domain": "Health Sciences"
}
}
}
-18
View File
@@ -1,18 +0,0 @@
{
"users": [
{
"account": 0,
"organization": 0,
"username": "superadmin",
"password": "superadmin",
"superadmin": true
},
{
"account": 1,
"organization": 1,
"username": "user",
"password": "user",
"superadmin": false
}
]
}
+17 -4
View File
@@ -1,6 +1,19 @@
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
LLM_MODEL=gemma4-e4b
# Patent search (EPO + USPTO)
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2
TOKEN_ISSUER_ID=inse
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the validation logic for
user names and passwords.
"""
import typing
import logging
from . import model
logger = logging.getLogger(__name__)
def _get_users() -> typing.List[model.User]:
''' Returns the list of users from the user configuration file. '''
try:
with open('../data/users.json') as file:
config = model.UserFile.model_validate_json(file.read())
return config.users
except Exception as e:
logger.error('Could not read user configuration file.', exc_info=e)
return []
def get_user(username: str) -> typing.Optional[model.User]:
''' Returns the user with the given username. '''
for user in _get_users():
if user.username == username:
return user
return None
def validate_user(username: str, password: str) -> typing.Optional[model.User]:
''' Validates the user with the given username and password. '''
user = get_user(username)
if user and user.password == password:
return user
return None
-52
View File
@@ -1,52 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data models for the standalone account sub-app.
"""
from pydantic import BaseModel
from pydantic import Field
from pydantic import StrictInt
from typing import List, Optional
class User(BaseModel):
''' An entry in the user configuration file. '''
username: str = Field(description="The username of the user.")
password: str = Field(description="The password of the user.")
account: StrictInt = Field(description="The account id of the user.")
organization: StrictInt = Field(description="The organization id of the user.")
superadmin: bool = Field(default=False, description="Indicates whether the user is a superadmin.")
class UserFile(BaseModel):
''' The data model for the file containing the user configuration. '''
users: List[User] = Field(default=[], description="The list of users.")
class AuthAccount(BaseModel):
i: int
l: str
o: int
class AuthScope(BaseModel):
t: str
a: AuthAccount
d: Optional[int] = None
r: List[str] = []
class IdentityGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
class AccessGrant(BaseModel):
token_type: str
access_token: str
expires_in: int
scope: AuthScope
refresh_token: str
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the security-related code.
"""
from typing import Optional
from typing import Dict
from typing import Literal
import jwt
import time
import logging
from .. import config
from .. import security
from . import model
logger = logging.getLogger(__name__)
def principal(id_token: str) -> Optional[security.Principal]:
''' Extracts the principal from the id token. '''
return security._extract_principal(id_token, config.settings.auth_secret, 'HS256', token_types=['ID', 'REFRESH'])
def id_token(user: model.User, exp: int) -> str:
''' Creates a new identity token for the specified user. '''
return _encode(_payload(user, 'ID', exp))
def access_token(user: model.User, exp: int) -> str:
''' Creates a new access token for the specified user. '''
return _encode(_payload(user, 'ACCESS', exp))
def refresh_token(user: model.User, exp: int) -> str:
''' Creates a new refresh token for the specified user. '''
return _encode(_payload(user, 'REFRESH', exp))
def _encode(payload: Dict[str, any]) -> str:
''' Creates a valid web token that encodes the contents with the symmetric key. '''
headers = {
"kid" : "sym",
}
return jwt.encode(payload, config.settings.auth_secret, algorithm="HS256", headers=headers)
def _payload(user: model.User, type: Literal['ID', 'ACCESS', 'REFRESH'], exp: int) -> str:
''' Creates the payload of the token for the specified user and token type. '''
now = int(time.time())
roles = [ 'SUPER_ADMIN' ] if user.superadmin else [ 'UNI_ADMIN' ]
payload = {
"iss" : "my-app",
"exp" : now + exp,
"iat" : now,
"nbf" : now,
"inse" : {
"t" : type,
"a" : {
"i" : user.account,
"l" : user.username,
"o" : user.organization
},
"d" : None,
"r" : roles if type == 'ACCESS' else []
}
}
return payload
-126
View File
@@ -1,126 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone account service that provides identity and access
token endpoints for authentication.
"""
import logging
import fastapi
import typing
from . import logic
from . import model
from . import security
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_403_FORBIDDEN
from starlette.status import HTTP_200_OK
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
logger = logging.getLogger(__name__)
router = fastapi.APIRouter(
prefix="/inse-account",
tags=["INSE Account Service"],
responses={404: {"description": "Not found"}},
)
@router.post(
"/auth/id",
responses={
HTTP_200_OK: {"model": model.IdentityGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {
"model": None,
"description": "Account login not successful.",
},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_identity_grant(
username: typing.Annotated[str, fastapi.Form()],
password: typing.Annotated[str, fastapi.Form()],
):
user = logic.validate_user(username, password)
if user is None:
logger.info("Invalid login attempt (%s).", username)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 12 * 60 * 60
token = security.id_token(user, exp=exp)
account = model.AuthAccount(
i=user.account, l=user.username, o=user.organization
)
scope = model.AuthScope(t="ID", a=account, d=None, r=[])
grant = model.IdentityGrant(
token_type="bearer", access_token=token, expires_in=exp, scope=scope
)
logger.info("Identity token generated (%s).", username)
return grant
except Exception as e:
logger.error("Token generation failed (%s).", username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@router.post(
"/auth/access",
responses={
HTTP_200_OK: {"model": model.AccessGrant},
HTTP_400_BAD_REQUEST: {
"model": None,
"description": "Invalid request parameters.",
},
HTTP_403_FORBIDDEN: {"model": None, "description": "Access not allowed."},
HTTP_500_INTERNAL_SERVER_ERROR: {
"model": None,
"description": "Token generation failed.",
},
},
)
async def get_access_grant(
secret: typing.Annotated[str, fastapi.Form()],
account: typing.Annotated[int, fastapi.Form()],
organization: typing.Annotated[int, fastapi.Form()],
):
principal = security.principal(secret)
if principal is None:
logger.info("Invalid access attempt without principal (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_400_BAD_REQUEST)
user = logic.get_user(principal.account.login)
if user is None:
logger.info("Invalid access attempt without user (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
if user.organization != organization or user.account != account:
logger.info("Invalid personation attempt (%s).", account)
raise fastapi.HTTPException(status_code=HTTP_403_FORBIDDEN)
try:
exp = 10 * 60
token = security.access_token(user, exp=exp)
refresh = security.refresh_token(user, exp=exp)
auth_account = model.AuthAccount(
i=user.account, l=user.username, o=user.organization
)
scope = model.AuthScope(
t="ACCESS",
a=auth_account,
d=None,
r=["SUPER_ADMIN"] if user.superadmin else ["UNI_ADMIN"],
)
grant = model.AccessGrant(
token_type="bearer",
access_token=token,
expires_in=exp,
scope=scope,
refresh_token=refresh,
)
logger.info("Access token generated (%s).", user.username)
return grant
except Exception as e:
logger.error("Token generation failed (%s).", user.username, exc_info=e)
raise fastapi.HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR)
@@ -0,0 +1 @@
@@ -0,0 +1,51 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
from inse.auth.model import UserRole
class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
openalex_institution_id: Optional[str] = None
class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
role: UserRole
organization_id: uuid.UUID
organization_name: str
deleted: bool
is_current: bool = False
is_real_account: bool = False
is_impersonating: bool = False
class AccountPage(BaseModel):
items: List[AccountProfile]
total: int
page: int
page_size: int
class CreateAccountRequest(BaseModel):
email: str = Field(min_length=3)
name: str = Field(min_length=1)
role: UserRole = UserRole.USER
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
class UpdateAccountRequest(BaseModel):
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
role: Optional[UserRole] = None
organization_id: Optional[uuid.UUID] = None
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
@@ -0,0 +1,125 @@
import uuid
from typing import Optional
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.database import get_session
from inse.tags import Tags
from . import service
from .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
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,
) -> AccountProfile:
return service.get_current_account(session=session, access_token=access_token)
@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,
) -> AccountPage:
return service.list_accounts(
session=session,
access_token=access_token,
page=page,
page_size=page_size,
offset=offset,
search=search,
organization_id=organization_id,
)
@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,
) -> AccountProfile:
return service.create_account(
session=session,
access_token=access_token,
payload=payload,
)
@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,
) -> list[OrganizationProfile]:
return service.list_organizations(session=session, access_token=access_token)
@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,
) -> AccountProfile:
return service.update_account(
session=session,
access_token=access_token,
account_id=account_id,
payload=payload,
)
@router.delete(
"/{account_id}",
operation_id="deleteAccount",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_account(
account_id: uuid.UUID,
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_account(
session=session,
access_token=access_token,
account_id=account_id,
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -0,0 +1,311 @@
import uuid
from typing import Optional
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 .model import (
AccountPage,
AccountProfile,
CreateAccountRequest,
OrganizationProfile,
UpdateAccountRequest,
)
def _is_admin(role: UserRole) -> bool:
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
if editor_role == UserRole.SUPER_ADMIN:
return True
if editor_role == UserRole.ADMIN:
return role in {UserRole.MANAGER, UserRole.USER}
return False
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
is_current=account.id == token.effective_account_id,
is_real_account=account.id == token.real_account_id,
is_impersonating=token.is_impersonating(),
)
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
account = session.get(Account, account_id)
if account is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Account not found.",
)
return account
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
if token.effective_role == UserRole.SUPER_ADMIN:
return
if (
token.effective_role == UserRole.ADMIN
and account.organization_id == token.effective_organization_id
):
return
if account.id == token.effective_account_id:
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is outside your scope.",
)
def _ensure_email_available(
session: Session,
email: str,
excluded_account_id: Optional[uuid.UUID] = None,
) -> None:
normalized_email = email.lower().strip()
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Invalid email address.",
)
statement = select(Account).where(Account.email == normalized_email)
if excluded_account_id is not None:
statement = statement.where(Account.id != excluded_account_id)
existing = session.exec(statement).first()
if existing is not None:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Email address is already used by another account.",
)
def get_current_account(session: Session, access_token: AccessToken) -> 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,
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):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can list accounts.",
)
statement = select(Account)
count_statement = select(func.count()).select_from(Account)
filters = []
if access_token.effective_role == UserRole.ADMIN:
filters.append(Account.organization_id == access_token.effective_organization_id)
elif organization_id is not None:
filters.append(Account.organization_id == organization_id)
if search:
pattern = f"%{search.lower().strip()}%"
filters.append(
or_(
func.lower(Account.name).like(pattern),
func.lower(Account.email).like(pattern),
)
)
for filter_expression in filters:
statement = statement.where(filter_expression)
count_statement = count_statement.where(filter_expression)
total = session.exec(count_statement).one()
effective_offset = offset if offset is not None else page * page_size
accounts = session.exec(
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
).all()
return AccountPage(
items=[_account_to_profile(account, access_token) for account in accounts],
total=total,
page=page,
page_size=page_size,
)
def create_account(
session: Session,
access_token: AccessToken,
payload: CreateAccountRequest,
) -> AccountProfile:
if not _is_admin(access_token.effective_role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only admins can create accounts.",
)
if (
access_token.effective_role == UserRole.ADMIN
and payload.organization_id != access_token.effective_organization_id
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
email = payload.email.lower().strip()
_ensure_email_available(session, email)
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
)
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def list_organizations(
session: Session,
access_token: AccessToken,
) -> list[OrganizationProfile]:
if access_token.effective_role == UserRole.SUPER_ADMIN:
organizations = session.exec(
select(Organization)
.where(Organization.deleted == False) # noqa: E712
.order_by(Organization.name)
).all()
elif access_token.effective_role == UserRole.ADMIN:
organization = session.get(Organization, access_token.effective_organization_id)
organizations = [organization] if organization and not organization.deleted else []
else:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
return [
OrganizationProfile(
id=organization.id,
name=organization.name,
openalex_institution_id=organization.openalex_institution_id,
)
for organization in organizations
]
def update_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
payload: UpdateAccountRequest,
) -> AccountProfile:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
is_self_update = account.id == access_token.effective_account_id
can_admin_update = _is_admin(access_token.effective_role)
if not can_admin_update and not is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if payload.email is not None:
email = payload.email.lower().strip()
_ensure_email_available(session, email, excluded_account_id=account.id)
account.email = email
if payload.name is not None:
account.name = payload.name.strip()
if payload.password is not None:
account.password_hash = auth_service._hash_password(payload.password)
account.epoch += 1
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role is not None:
if not can_admin_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.epoch += 1
if payload.organization_id is not None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
organization = session.get(Organization, payload.organization_id)
if organization is None or organization.deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Organization not found.",
)
account.organization_id = payload.organization_id
account.epoch += 1
if payload.deleted is not None:
if not can_admin_update or is_self_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = payload.deleted
account.epoch += 1
session.add(account)
session.commit()
session.refresh(account)
return _account_to_profile(account, access_token)
def delete_account(
session: Session,
access_token: AccessToken,
account_id: uuid.UUID,
) -> None:
account = _get_account_or_404(session, account_id)
_ensure_account_in_editor_scope(account, access_token)
if (
not _is_admin(access_token.effective_role)
or account.id == access_token.effective_account_id
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
account.deleted = True
account.epoch += 1
session.add(account)
session.commit()
@@ -0,0 +1,29 @@
import smtplib
from email.message import EmailMessage
def send_email(
recipient: str,
subject: str,
body: str,
smtp_server: str = "localhost",
smtp_port: int = 25,
sender: str = "no-reply@smartguide.local",
username: str | None = None,
password: str | None = None,
use_tls: bool = False,
):
msg = EmailMessage()
msg["From"] = sender
msg["To"] = recipient
msg["Subject"] = subject
msg.set_content(body)
with smtplib.SMTP(smtp_server, smtp_port) as server:
if use_tls:
server.starttls()
if username and password:
server.login(username, password)
server.send_message(msg)
+212
View File
@@ -0,0 +1,212 @@
import uuid
from datetime import datetime
from enum import StrEnum
from typing import List
from pydantic import BaseModel
from sqlmodel import Field, Relationship, SQLModel
class UserRole(StrEnum):
SUPER_ADMIN = "SUPER_ADMIN"
ADMIN = "ADMIN"
MANAGER = "MANAGER"
USER = "USER"
class TokenType(StrEnum):
ID_TOKEN = "ID"
REFRESH_TOKEN = "REFRESH"
ACCESS_TOKEN = "ACCESS"
class Durable(SQLModel):
deleted: bool = Field(
default=False,
nullable=False,
index=True,
description="Indicates whether the record is marked as deleted.",
)
class Organization(Durable, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the organization. Generated automatically if not provided.",
)
name: str = Field(
index=True,
unique=True,
nullable=False,
description="The unique name of the organization.",
)
openalex_institution_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the institution associated with the organization.",
)
accounts: List["Account"] = Relationship(back_populates="organization")
class Account(Durable, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the account. Generated automatically if not provided.",
)
email: str = Field(
index=True,
unique=True,
nullable=False,
description="The email address associated with the account.",
)
name: str = Field(
index=True,
nullable=False,
description="The name of the account holder.",
)
openalex_person_id: str | None = Field(
default=None,
index=True,
description="The OpenAlex ID of the person associated with the account.",
)
epoch: int = Field(
default=0,
nullable=False,
description="The epoch value for the account. Used for versioning of tokens.",
)
password_hash: str = Field(
index=False,
nullable=False,
description="The hashed password for the account using Argon2id algorithm.",
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
)
organization_id: uuid.UUID = Field(
foreign_key="organization.id",
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this account holds within its organization.",
)
organization: Organization = Relationship(back_populates="accounts")
class Secret(SQLModel, table=True):
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
description="Unique identifier for the secret. Generated automatically if not provided.",
)
account_id: uuid.UUID = Field(
foreign_key="account.id",
unique=True, # Ensure that each account can have only one associated secret
nullable=False,
description="The unique identifier of the account associated with this secret.",
)
secret_value: str = Field(
index=False,
nullable=False,
description="The actual secret value. This should be stored securely and encrypted.",
)
expires_at: datetime = Field(
index=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(
nullable=False,
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):
token_type: TokenType = Field(
default=TokenType.ID_TOKEN,
const=True,
description="The type of the token, which is always ID_TOKEN for this class.",
)
class AccessToken(Token):
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
description="The type of the token, which is always ACCESS_TOKEN for this class.",
)
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.",
)
def is_impersonating(self) -> bool:
"""Determine if the access token is being used for impersonation.
Returns:
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
"""
return self.effective_account_id != self.real_account_id
class RefreshToken(AccessToken):
token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN,
const=True,
description="The type of the token, which is always REFRESH_TOKEN for this class.",
)
class LoginResponse(BaseModel):
id_token: IdToken = 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."
)
+162
View File
@@ -0,0 +1,162 @@
import logging
from typing import Annotated
import uuid
from fastapi import APIRouter, Body, Depends, Response, status
from sqlmodel import Session
from inse.tags import Tags
import inse.auth.service as auth_service
from inse.database import SessionDep, get_session
from inse.auth.model import (
AccessResponse,
AccessToken,
IdToken,
LoginResponse,
RefreshToken,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
@router.get("/health")
async def health_check():
return {"status": "ok"}
@router.post(
"/request-otk",
summary="Request One-Time Key",
description="Request a one-time key (OTK) for authentication using email and password.",
operation_id="requestOtk",
responses={
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
},
)
async def request_otk(
session: SessionDep,
email: Annotated[str, Body(description="User's email address")],
password: Annotated[str, Body(description="User's password")],
):
return auth_service.request_otk(session=session, email=email, password=password)
@router.post(
"/login",
summary="Login with One-Time Key",
description="Login using a one-time key (OTK) sent to the user's email.",
operation_id="login",
responses={status.HTTP_200_OK: {"description": "Login successful."}},
)
async def login(
session: SessionDep,
response: Response,
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
email_code: Annotated[
str, Body(embed=True, description="One-time code sent to user's email")
],
) -> LoginResponse:
return auth_service.login(
session=session, response=response, account_id=account_id, email_code=email_code
)
@router.post(
"/access",
summary="Get Access Token",
description="Retrieve an access token for the authenticated user.",
operation_id="getAccessToken",
responses={
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
},
)
async def get_action_tokens(
response: Response,
session: SessionDep,
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
effective_account_id: Annotated[
uuid.UUID, Body(description="Effective account ID for the access token")
],
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
) -> AccessResponse:
logger.debug(
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
real_account_id,
effective_account_id,
id_token,
)
return auth_service.get_access_token(
response=response,
session=session,
real_account_id=real_account_id,
effective_account_id=effective_account_id,
id_token=id_token,
)
@router.post(
"/refresh",
summary="Refresh Access Token",
description="Refresh the access token using a valid refresh token.",
operation_id="refreshAccessToken",
responses={
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
},
)
async def refresh_access_token(
refresh_token: Annotated[
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
],
) -> AccessToken:
return auth_service.refresh_access_token(refresh_token=refresh_token)
@router.post(
"/logout",
summary="Logout",
description="Logout the authenticated user.",
operation_id="logout",
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
)
async def logout(
session: Annotated[Session, Depends(get_session)],
access_token: Annotated[
AccessToken,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
return auth_service.logout(session=session, access_token=access_token)
@router.post(
"/change-password",
summary="Change Password",
description="Change the user's password and invalidate existing tokens.",
operation_id="changePassword",
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
)
async def change_password(
session: Annotated[Session, Depends(get_session)],
current_password: Annotated[
str,
Body(description="Current password"),
],
new_password: Annotated[
str,
Body(description="New password", min_length=8),
],
access_token: Annotated[
AccessToken,
auth_service.CurrentUserAccessTokenPayloadDep,
],
):
return auth_service.change_password(
session=session,
access_token=access_token,
current_password=current_password,
new_password=new_password,
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,517 @@
import inse.config as config_module
import uuid
import pytest
from sqlmodel import Session, SQLModel, create_engine, select
from fastapi import Response, HTTPException
import datetime as _dt
from datetime import timedelta
from inse.auth import service as auth_service
from inse.auth.model import (
Account,
Organization,
Secret,
IdToken,
AccessToken,
RefreshToken,
UserRole,
)
@pytest.fixture()
def settings_backup():
orig = config_module.get_settings()
backup = config_module.Settings(**orig.model_dump())
yield backup
for k, v in backup.model_dump().items():
setattr(config_module.settings, k, v)
@pytest.fixture()
def in_memory_session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
def create_org_and_account(
session: Session, email: str, password: str, role=UserRole.USER
):
org = Organization(name=f"Test Org {email}")
session.add(org)
session.flush()
assert org.id is not None
pwd_hash = auth_service._hash_password(password)
acc = Account(
email=email,
name="Tester",
organization_id=org.id,
password_hash=pwd_hash,
role=role,
)
session.add(acc)
session.commit()
session.refresh(acc)
return org, acc
def test_hash_and_verify_password():
pw = "s3cret-password"
h = auth_service._hash_password(pw)
assert auth_service._verify_password(pw, h) is True
assert auth_service._verify_password("wrong", h) is False
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "test-hmac-key"
config_module.settings.token_issuer_id = "test-issuer"
config_module.settings.skip_otk_validation = False
email = "user@example.com"
password = "hunter2"
org, acc = create_org_and_account(in_memory_session, email, password)
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)
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).first()
assert secret is not None
response = Response()
login_result = auth_service.login(
in_memory_session, response, acc.id, secret.secret_value
)
assert isinstance(login_result.id_token, IdToken)
assert login_result.id_token.real_account_id == acc.id
assert login_result.id_token.user_fingerprint_hash is not None
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "another-key"
config_module.settings.token_issuer_id = "issuer-2"
email = "fp@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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)
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,
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,
session=in_memory_session,
)
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "flow-key"
config_module.settings.token_issuer_id = "flow-issuer"
email = "flow@example.com"
password = "pwflow"
org, acc = create_org_and_account(
in_memory_session, email, password, role=UserRole.ADMIN
)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
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)
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
assert isinstance(refreshed, AccessToken)
assert refreshed.real_account_id == access_response.access_token.real_account_id
def test_logout_and_change_password(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "logout-key"
config_module.settings.token_issuer_id = "logout-issuer"
email = "logout@example.com"
password = "oldpw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
access_resp = auth_service.get_access_token(
response, in_memory_session, id_token, acc.id
)
before_epoch = acc.epoch
out = auth_service.logout(in_memory_session, access_resp.access_token)
assert out["status"] == "ok"
in_memory_session.refresh(acc)
assert acc.epoch == before_epoch + 1
new_pw = "newpw123"
acc.password_hash = auth_service._hash_password(password)
in_memory_session.add(acc)
in_memory_session.commit()
change_out = auth_service.change_password(
in_memory_session, access_resp.access_token, password, new_pw
)
assert change_out["status"] == "ok"
in_memory_session.refresh(acc)
assert auth_service._verify_password(new_pw, acc.password_hash)
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
email = "nope@example.com"
password = "rightpw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
with pytest.raises(HTTPException):
auth_service.request_otk(in_memory_session, email, "wrongpw")
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"
config_module.settings.skip_otk_validation = False
email = "expired@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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)
in_memory_session.add(secret)
in_memory_session.commit()
with pytest.raises(HTTPException):
auth_service.login(in_memory_session, Response(), acc.id, "000000")
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "cookie-key"
config_module.settings.token_issuer_id = "cookie-issuer"
email = "cookie@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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
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,
session=in_memory_session,
)
def test_token_epoch_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "epoch-key"
config_module.settings.token_issuer_id = "epoch-issuer"
email = "epoch@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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
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,
session=in_memory_session,
)
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "sig-key"
config_module.settings.token_issuer_id = "sig-issuer"
email = "sig@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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
bad_token = id_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,
session=in_memory_session,
)
def test_impersonation_rules(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "imp-key"
config_module.settings.token_issuer_id = "imp-issuer"
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
assert real_acc.id is not None
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
assert eff_acc.id is not None
response = Response()
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
with pytest.raises(HTTPException):
auth_service.get_access_token(
response,
in_memory_session,
id_token,
real_acc.id,
effective_account_id=eff_acc.id,
)
real_acc.role = UserRole.SUPER_ADMIN
in_memory_session.add(real_acc)
in_memory_session.commit()
access_resp = auth_service.get_access_token(
response,
in_memory_session,
id_token,
real_acc.id,
effective_account_id=eff_acc.id,
)
assert isinstance(access_resp.access_token, AccessToken)
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "regen-key"
config_module.settings.token_issuer_id = "regen-issuer"
config_module.settings.skip_otk_validation = False
email = "regen@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
auth_service.request_otk(in_memory_session, email, password)
secret1 = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).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)
).first()
assert secret2 is not None
assert first_value != secret2.secret_value
with pytest.raises(HTTPException):
auth_service.login(in_memory_session, Response(), acc.id, first_value)
login_res = auth_service.login(
in_memory_session, Response(), acc.id, secret2.secret_value
)
assert isinstance(login_res.id_token, IdToken)
def test_otk_deleted_after_login(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "del-key"
config_module.settings.token_issuer_id = "del-issuer"
config_module.settings.skip_otk_validation = False
email = "single@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
auth_service.request_otk(in_memory_session, email, password)
secret = in_memory_session.exec(
select(Secret).where(Secret.account_id == acc.id)
).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)
).first()
assert post is None
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "act-key"
config_module.settings.token_issuer_id = "act-issuer"
email = "act@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
response = Response()
raw = auth_service._set_act_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=raw,
)
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,
session=in_memory_session,
)
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
config_module.settings.token_hmac_key = "exp-key"
config_module.settings.token_issuer_id = "exp-issuer"
email = "exp@example.com"
password = "pw"
org, acc = create_org_and_account(in_memory_session, email, password)
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)
payload = {
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
auth_service.EPOCH_KEY: acc.epoch,
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
}
bad_token = auth_service._build_token(
payload=payload,
expiration_datetime=past,
token_type=auth_service.TokenType.ID_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,
session=in_memory_session,
)
def test_missing_hmac_key_raises_value_error(settings_backup):
orig = config_module.get_settings()
saved = orig.token_hmac_key
config_module.settings.token_hmac_key = None
with pytest.raises(ValueError):
auth_service._build_token(
payload={},
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
token_type=auth_service.TokenType.ID_TOKEN,
)
config_module.settings.token_hmac_key = saved
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)
@@ -3,7 +3,7 @@ from typing import List, Optional, Set
from pydantic import BaseModel, Field
from inse.models.work_topic import WorkTopic
from inse.models.openalex.work_topic import WorkTopic
from inse.utils import extract_raw_topic_id
@@ -26,11 +26,11 @@ from inse.utils import (
extract_raw_topic_id,
extract_raw_work_id,
)
from inse.models.author import Author
from inse.models.authorship import Authorship
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.institution import Institution
from inse.models.openalex.author import Author
from inse.models.openalex.authorship import Authorship
from inse.models.openalex.dehydrated_author import DehydratedAuthor
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
@@ -0,0 +1,298 @@
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
from . import model
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
logger = logging.getLogger(__name__)
UDE_OPENALEX_ID = "https://openalex.org/I62318514"
UDE_ROR = "https://ror.org/04mz5ra38"
UDE_DISPLAY_NAME = "University of Duisburg-Essen"
MATCHING_METHOD = "exact_openalex_display_name_to_handelsregister_officer_name"
async def get_company_connections_by_author_id(
author_id: str,
client: CompanyConnectionsSearchClient | None = None,
) -> model.CompanyConnectionsResponse:
search_client = client or CompanyConnectionsSearchClient()
try:
author_hit = await search_client.get_openalex_author(author_id)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Elasticsearch is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex author lookup failed for %s.", author_id)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex author lookup failed.",
) from exc
if author_hit is None:
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
institution_scope, matching_institutions = _get_ude_institution_scope(source)
is_ude_author = institution_scope is not None
if not is_ude_author or not display_name:
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name or None,
is_ude_author=is_ude_author,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=None,
company_count=0,
has_more_results=False,
common_name_warning=False,
connections=[],
)
try:
hr_response = await search_client.search_handelsregister_by_officer_name(
display_name
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Elasticsearch is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("Handelsregister lookup failed for %s.", display_name)
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Handelsregister lookup failed.",
) from exc
company_count, company_count_relation = _parse_total(hr_response)
connections = _parse_company_connections(
response=hr_response,
matched_person_name=display_name,
)
has_more_results = company_count_relation == "gte" or company_count > len(
connections
)
common_name_warning = has_more_results or company_count > 3
return model.CompanyConnectionsResponse(
author_id=author_id,
display_name=display_name,
is_ude_author=True,
institution_scope=institution_scope,
matching_institutions=matching_institutions,
matching_method=MATCHING_METHOD,
company_count=company_count,
has_more_results=has_more_results,
common_name_warning=common_name_warning,
connections=connections,
)
def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]:
institutions = source.get("last_known_institutions") or []
direct_matches: list[str] = []
child_matches: list[str] = []
for institution in institutions:
if not isinstance(institution, dict):
continue
institution_id = _clean(institution.get("id"))
ror = _clean(institution.get("ror"))
name = _clean(institution.get("display_name"))
lineage = institution.get("lineage") or []
label = name or institution_id or ror
is_direct = (
institution_id == UDE_OPENALEX_ID
or ror == UDE_ROR
or name == UDE_DISPLAY_NAME
)
is_child = UDE_OPENALEX_ID in lineage and not is_direct
if is_direct:
direct_matches.append(label)
elif is_child:
child_matches.append(label)
if direct_matches:
return "direct_ude", sorted(set(direct_matches))
if child_matches:
return "child_of_ude", sorted(set(child_matches))
return None, []
def _parse_total(response: dict[str, Any]) -> tuple[int, str]:
total = response.get("hits", {}).get("total", 0)
if isinstance(total, dict):
return int(total.get("value") or 0), total.get("relation") or "eq"
return int(total or 0), "eq"
def _parse_company_connections(
response: dict[str, Any],
matched_person_name: str,
) -> list[model.CompanyConnection]:
connections: list[model.CompanyConnection] = []
hits = response.get("hits", {}).get("hits", [])
for hit in hits:
source = hit.get("_source", {})
matched_officers = _parse_inner_hit_officers(hit)
officers = _parse_source_officers(
source=source,
matched_person_name=matched_person_name,
)
connections.append(
model.CompanyConnection(
company_number=source.get("company_number"),
company_name=source.get("name"),
company_status=source.get("current_status"),
register_art=source.get("register_art"),
register_nummer=source.get("register_nummer"),
native_company_number=source.get("native_company_number"),
registrar=source.get("registrar"),
registered_office=source.get("registered_office"),
registered_address=source.get("registered_address"),
retrieved_at=source.get("retrieved_at"),
matched_officers=matched_officers,
officers=officers,
)
)
return connections
def _parse_inner_hit_officers(hit: dict[str, Any]) -> list[model.MatchedOfficer]:
inner_hits = (
hit.get("inner_hits", {}).get("officers", {}).get("hits", {}).get("hits", [])
)
officers: list[model.MatchedOfficer] = []
for inner_hit in inner_hits:
source = inner_hit.get("_source", {})
officer_source = _normalize_officer_source(source)
officers.append(
_to_officer(
officer_source,
is_matched_person=True,
)
)
return _deduplicate_officers(officers)
def _parse_source_officers(
source: dict[str, Any],
matched_person_name: str,
) -> list[model.MatchedOfficer]:
raw_officers = source.get("officers") or []
if not isinstance(raw_officers, list):
return []
officers: list[model.MatchedOfficer] = []
for raw_officer in raw_officers:
if not isinstance(raw_officer, dict):
continue
if _clean(raw_officer.get("type")) != "person":
continue
officer_name = _clean(raw_officer.get("name"))
is_matched_person = officer_name == matched_person_name
officers.append(
_to_officer(
raw_officer,
is_matched_person=is_matched_person,
)
)
return _deduplicate_officers(officers)
def _to_officer(
source: dict[str, Any],
is_matched_person: bool,
) -> model.MatchedOfficer:
return model.MatchedOfficer(
name=_clean_or_none(source.get("name")),
firstname=_clean_or_none(source.get("firstname")),
lastname=_clean_or_none(source.get("lastname")),
city=_clean_or_none(source.get("city")),
position=_clean_or_none(source.get("position")),
start_date=_clean_or_none(source.get("start_date")),
type=_clean_or_none(source.get("type")),
flag=_clean_or_none(source.get("flag")),
is_matched_person=is_matched_person,
)
def _deduplicate_officers(
officers: list[model.MatchedOfficer],
) -> list[model.MatchedOfficer]:
seen: set[tuple[str, str, str, str]] = set()
deduplicated: list[model.MatchedOfficer] = []
for officer in officers:
key = (
officer.name or "",
officer.position or "",
officer.city or "",
officer.start_date or "",
)
if key in seen:
continue
seen.add(key)
deduplicated.append(officer)
return deduplicated
def _normalize_officer_source(source: dict[str, Any]) -> dict[str, Any]:
officers = source.get("officers")
if isinstance(officers, dict):
return officers
return source
def _clean_or_none(value: Any) -> str | None:
cleaned = _clean(value)
return cleaned or None
def _clean(value: Any) -> str:
if value is None:
return ""
return str(value).strip()
@@ -0,0 +1,44 @@
from pydantic import BaseModel, Field
class MatchedOfficer(BaseModel):
name: str | None = None
firstname: str | None = None
lastname: str | None = None
city: str | None = None
position: str | None = None
start_date: str | None = None
type: str | None = None
flag: str | None = None
is_matched_person: bool = False
class CompanyConnection(BaseModel):
company_number: str | None = None
company_name: str | None = None
company_status: str | None = None
register_art: str | None = None
register_nummer: str | None = None
native_company_number: str | None = None
registrar: str | None = None
registered_office: str | None = None
registered_address: str | None = None
retrieved_at: str | None = None
matched_officers: list[MatchedOfficer] = Field(default_factory=list)
officers: list[MatchedOfficer] = Field(default_factory=list)
class CompanyConnectionsResponse(BaseModel):
author_id: str
display_name: str | None = None
is_ude_author: bool
institution_scope: str | None = None
matching_institutions: list[str] = Field(default_factory=list)
matching_method: str | None = None
company_count: int
has_more_results: bool
common_name_warning: bool
connections: list[CompanyConnection] = Field(default_factory=list)
@@ -0,0 +1,140 @@
from typing import Any
import httpx
from .. import config
class MissingApiKeyError(Exception):
pass
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
else config.settings.elasticsearch_api_key
)
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:
return author_id.strip().removeprefix("https://openalex.org/")
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
if not self.api_key:
raise MissingApiKeyError("Elasticsearch API key is not configured.")
doc_id = self.openalex_doc_id(author_id)
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.get(
f"/{self.openalex_index}/_doc/{doc_id}",
headers={"Authorization": f"ApiKey {self.api_key}"},
)
if response.status_code == 404:
return None
response.raise_for_status()
return response.json()
async def search_handelsregister_by_officer_name(
self,
officer_name: str,
size: int = 10000,
track_total_hits: bool = True,
) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("Elasticsearch API key is not configured.")
payload = self.handelsregister_officer_name_query(
officer_name=officer_name,
size=size,
track_total_hits=track_total_hits,
)
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{self.handelsregister_index}/_search",
headers={"Authorization": f"ApiKey {self.api_key}"},
json=payload,
)
response.raise_for_status()
return response.json()
@staticmethod
def handelsregister_officer_name_query(
officer_name: str,
size: int,
track_total_hits: bool,
) -> dict[str, Any]:
return {
"track_total_hits": track_total_hits,
"size": size,
"_source": [
"company_number",
"name",
"current_status",
"registered_address",
"registered_office",
"registrar",
"register_art",
"register_nummer",
"native_company_number",
"retrieved_at",
"officers",
],
"query": {
"nested": {
"path": "officers",
"query": {
"bool": {
"filter": [
{"term": {"officers.type": "person"}},
{"term": {"officers.name.keyword": officer_name}},
]
}
},
"inner_hits": {
"size": 10,
"_source": [
"officers.name",
"officers.firstname",
"officers.lastname",
"officers.city",
"officers.position",
"officers.start_date",
"officers.type",
"officers.flag",
],
},
}
},
"sort": [{"company_number": {"order": "asc"}}],
}
@@ -0,0 +1,25 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for possible company connections of OpenAlex authors.
"""
from fastapi import APIRouter
from . import logic, model
router = APIRouter(
prefix="/api/inse-service/authors",
tags=["Company Connections"],
)
@router.get(
"/{author_id}/company-connections",
operation_id="getCompanyConnectionsByAuthor",
response_model=model.CompanyConnectionsResponse,
response_model_exclude_none=True,
summary="Get possible company connections by OpenAlex author ID.",
)
async def get_company_connections_by_author(author_id: str):
return await logic.get_company_connections_by_author_id(author_id)
+29 -8
View File
@@ -7,7 +7,7 @@ that can be adjusted via environment variables.
from functools import lru_cache
import logging
from typing import Dict, List, Optional
from typing import Dict, List, Literal, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
@@ -26,27 +26,31 @@ class Settings(BaseSettings):
auth_disabled: bool = False
auth_standalone: bool = True
auth_secret: str = "change-me-to-a-secure-secret-key"
# OpenAlex works search config
openalex_works_search_base_url: str = "https://project.nes.uni-due.de/elastic"
# IMPORTANT: wildcard * needed to query all work indices
openalex_works_search_index: str = "openalex-works*"
openalex_works_api_key: str = (
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
)
openalex_works_search_timeout_seconds: float = 30.0
# OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org"
openalex_api_key: Optional[str] = None
openalex_api_timeout_seconds: float = 30.0
# Patent Elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
patent_elasticsearch_api_key: Optional[str] = None
# LLM config
llm_api_url: Optional[str] = None
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
# elasticsearch config
elasticsearch_url: Optional[str] = None
# Sentence Transformers config
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
# Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
model_config = SettingsConfigDict(env_file=".env")
@@ -56,6 +60,23 @@ class Settings(BaseSettings):
{"url": "http://localhost:8000", "description": "Local development server"},
]
logging_level: str = "DEBUG"
environment: Literal["dev", "prod"] = "dev"
token_issuer_id: Optional[str] = None
token_hmac_key: Optional[str] = None
skip_otk_validation: bool = True
# SMTP / email config
send_otk_email: bool = False
smtp_server: str = "localhost"
smtp_port: int = 25
smtp_sender: str = "no-reply@smartguide.local"
smtp_username: Optional[str] = None
smtp_password: Optional[str] = None
smtp_use_tls: bool = False
settings = Settings()
+30 -22
View File
@@ -1,25 +1,33 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the code to bootstrap the database
using our schema and sqlalchemy.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from . import schema
from . import config
from typing import Annotated
engine = create_engine(config.settings.database_url, echo=config.settings.database_debug)
from fastapi import Depends
from sqlmodel import SQLModel, Session, create_engine
if config.settings.database_init:
schema.Base.metadata.create_all(engine)
from inse import config
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get():
''' Returns a database connection and closes it when done. '''
db = SessionLocal()
try:
yield db
finally:
db.close()
settings = config.get_settings()
connect_args = {"check_same_thread": False}
engine = create_engine(
url=settings.database_url,
echo=settings.database_debug,
connect_args=connect_args,
)
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
def get_session():
"""Yields a database session for use in FastAPI endpoints.
Yields:
Session: A SQLModel session connected to the database.
"""
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
+8
View File
@@ -0,0 +1,8 @@
class NotFoundException(Exception):
"""Exception raised when a requested resource is not found.
Args:
Exception (_type_): Base exception class.
"""
def __init__(self, message: str):
super().__init__(message)
@@ -23,9 +23,9 @@ class FundedPublicationsSearchClient:
timeout: float | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_works_search_base_url).rstrip("/")
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.openalex_works_api_key
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
@@ -78,22 +78,53 @@ class FundedPublicationsSearchClient:
"doi",
"title",
"display_name",
"abstract_inverted_index",
"publication_year",
"publication_date",
"type",
"language",
"cited_by_count",
"is_retracted",
"primary_location.landing_page_url",
"primary_location.pdf_url",
"primary_location.is_oa",
"primary_location.license",
"primary_location.source.display_name",
"primary_location.source.type",
"best_oa_location.landing_page_url",
"best_oa_location.pdf_url",
"best_oa_location.is_oa",
"best_oa_location.license",
"best_oa_location.source.display_name",
"open_access.oa_url",
"open_access.is_oa",
"open_access.oa_status",
"open_access.any_repository_has_fulltext",
"topics.display_name",
"topics.score",
"primary_topic.display_name",
"primary_topic.subfield.display_name",
"primary_topic.field.display_name",
"primary_topic.domain.display_name",
"keywords.display_name",
"keywords.score",
"counts_by_year.year",
"counts_by_year.cited_by_count",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"authorships.countries",
"funders.id",
"funders.display_name",
"funders.ror",
"awards.id",
"awards.display_name",
"awards.funder_id",
"awards.funder_display_name",
"awards.funder_award_id",
"awards.doi",
]
@staticmethod
+249
View File
@@ -242,6 +242,246 @@ def _resolve_publication_url(publication: dict) -> str | None:
return publication.get("id")
def _publication_author_names(publication: dict) -> list[str]:
names: list[str] = []
for authorship in publication.get("authorships", []):
author_name = authorship.get("author", {}).get("display_name")
if author_name:
names.append(author_name)
return names
def _unique_strings(values: list[Any], limit: int | None = None) -> list[str]:
seen: set[str] = set()
unique_values: list[str] = []
for value in values:
if not value:
continue
text = str(value).strip()
if not text or text in seen:
continue
seen.add(text)
unique_values.append(text)
if limit and len(unique_values) >= limit:
break
return unique_values
def _publication_pdf_url(publication: dict) -> str | None:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
return primary_location.get("pdf_url") or best_oa_location.get("pdf_url")
def _publication_source(publication: dict) -> dict:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
primary_source = primary_location.get("source") or {}
best_oa_source = best_oa_location.get("source") or {}
return primary_source or best_oa_source
def _publication_license(publication: dict) -> str | None:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
return primary_location.get("license") or best_oa_location.get("license")
def _publication_is_open_access(publication: dict) -> bool:
primary_location = publication.get("primary_location") or {}
best_oa_location = publication.get("best_oa_location") or {}
open_access = publication.get("open_access") or {}
return bool(
open_access.get("is_oa")
or open_access.get("oa_url")
or primary_location.get("is_oa")
or best_oa_location.get("is_oa")
)
def _publication_has_fulltext(publication: dict) -> bool:
open_access = publication.get("open_access") or {}
return bool(open_access.get("any_repository_has_fulltext") or _publication_pdf_url(publication))
def _publication_topic_names(publication: dict) -> list[str]:
topics = publication.get("topics")
if not isinstance(topics, list):
return []
sorted_topics = sorted(
topics,
key=lambda topic: topic.get("score", 0) if isinstance(topic, dict) else 0,
reverse=True,
)
return _unique_strings(
[topic.get("display_name") for topic in sorted_topics if isinstance(topic, dict)],
limit=6,
)
def _publication_keyword_names(publication: dict) -> list[str]:
keywords = publication.get("keywords")
if not isinstance(keywords, list):
return []
sorted_keywords = sorted(
keywords,
key=lambda keyword: keyword.get("score", 0) if isinstance(keyword, dict) else 0,
reverse=True,
)
return _unique_strings(
[keyword.get("display_name") for keyword in sorted_keywords if isinstance(keyword, dict)],
limit=8,
)
def _publication_institutions(publication: dict) -> list[str]:
institution_names: list[str] = []
for authorship in publication.get("authorships", []):
if not isinstance(authorship, dict):
continue
for institution in authorship.get("institutions") or []:
if isinstance(institution, dict):
institution_names.append(institution.get("display_name"))
return _unique_strings(institution_names, limit=8)
def _publication_countries(publication: dict) -> list[str]:
countries: list[str] = []
for authorship in publication.get("authorships", []):
if not isinstance(authorship, dict):
continue
countries.extend(authorship.get("countries") or [])
for institution in authorship.get("institutions") or []:
if isinstance(institution, dict):
countries.append(institution.get("country_code"))
return _unique_strings(countries, limit=8)
def _publication_counts_by_year(publication: dict) -> list[dict[str, int]]:
counts_by_year = publication.get("counts_by_year")
if not isinstance(counts_by_year, list):
return []
sanitized_counts: list[dict[str, int]] = []
for year_count in counts_by_year:
if not isinstance(year_count, dict):
continue
year = year_count.get("year")
cited_by_count = year_count.get("cited_by_count")
if isinstance(year, int) and isinstance(cited_by_count, int):
sanitized_counts.append({"year": year, "cited_by_count": cited_by_count})
return sorted(sanitized_counts, key=lambda year_count: year_count["year"], reverse=True)[:6]
def _publication_funder_names(publication: dict) -> list[str]:
names: list[Any] = []
for funder in publication.get("funders", []):
if isinstance(funder, dict):
names.append(funder.get("display_name"))
for award in publication.get("awards", []):
if isinstance(award, dict):
names.append(award.get("funder_display_name"))
return sorted(_unique_strings(names), key=str.casefold)
def _publication_grant_labels(
publication: dict,
funder_id: str | None,
funder_name: str | None,
) -> list[str]:
labels: list[str] = []
for award in publication.get("awards", []):
if not isinstance(award, dict):
continue
award_funder_id = award.get("funder_id")
award_funder_name = award.get("funder_display_name")
matches_funder_id = bool(funder_id and award_funder_id == funder_id)
matches_funder_name = bool(funder_name and award_funder_name == funder_name)
has_funder_reference = bool(award_funder_id or award_funder_name)
if has_funder_reference and not (matches_funder_id or matches_funder_name):
continue
display_name = award.get("display_name")
if display_name:
labels.append(display_name)
return _unique_strings(labels, limit=6)
def _publication_abstract(publication: dict) -> str | None:
inverted_index = publication.get("abstract_inverted_index")
if not isinstance(inverted_index, dict):
return None
words: list[tuple[int, str]] = []
for word, positions in inverted_index.items():
if not isinstance(positions, list):
continue
for position in positions:
if isinstance(position, int):
words.append((position, word))
if not words:
return None
return " ".join(word for _, word in sorted(words))
def _publication_detail_summary(
publication: dict,
publication_id: str,
publication_url: str | None,
author_position: str,
funder_id: str | None,
funder_name: str | None,
) -> dict[str, Any]:
title = publication.get("title") or publication.get("display_name") or publication_id
source = _publication_source(publication)
open_access = publication.get("open_access") or {}
primary_topic = publication.get("primary_topic") or {}
topic_field = primary_topic.get("field") or {}
topic_subfield = primary_topic.get("subfield") or {}
topic_domain = primary_topic.get("domain") or {}
return {
"id": publication_id,
"title": title,
"abstract": _publication_abstract(publication),
"doi": publication.get("doi"),
"publication_year": publication.get("publication_year"),
"publication_date": publication.get("publication_date"),
"publication_type": publication.get("type"),
"language": publication.get("language"),
"publication_url": publication_url,
"pdf_url": _publication_pdf_url(publication),
"source_name": source.get("display_name"),
"source_type": source.get("type"),
"is_open_access": _publication_is_open_access(publication),
"open_access_status": open_access.get("oa_status"),
"has_fulltext": _publication_has_fulltext(publication),
"license": _publication_license(publication),
"cited_by_count": publication.get("cited_by_count"),
"is_retracted": publication.get("is_retracted"),
"primary_topic": primary_topic.get("display_name"),
"topic_field": topic_field.get("display_name"),
"topic_subfield": topic_subfield.get("display_name"),
"topic_domain": topic_domain.get("display_name"),
"author_position": author_position,
"authors": _publication_author_names(publication),
"funder_names": _publication_funder_names(publication),
"institutions": _publication_institutions(publication),
"countries": _publication_countries(publication),
"topics": _publication_topic_names(publication),
"keywords": _publication_keyword_names(publication),
"grant_labels": _publication_grant_labels(publication, funder_id, funder_name),
"counts_by_year": _publication_counts_by_year(publication),
}
def _collect_funders_from_publications(
results: list[dict],
author_id: str,
@@ -291,6 +531,7 @@ def _collect_funders_from_publications(
},
"publication_urls": {},
"publication_titles": {},
"publication_details": {},
}
entry = funder_counts[key]
@@ -302,4 +543,12 @@ def _collect_funders_from_publications(
if publication_id:
title = publication.get("display_name") or publication.get("title") or publication_id
entry["publication_titles"][publication_id] = title
entry["publication_details"][publication_id] = _publication_detail_summary(
publication,
publication_id,
publication_url,
author_position,
funder_id,
funder_name,
)
+36
View File
@@ -1,6 +1,7 @@
from typing import Any
from pydantic import BaseModel
from pydantic import Field
class PublicationsByAuthorResponse(BaseModel):
@@ -27,6 +28,40 @@ class AuthorPositionCount(BaseModel):
unknown: int = 0
class PublicationDetailByFunder(BaseModel):
id: str
title: str
abstract: str | None = None
doi: str | None = None
publication_year: int | None = None
publication_date: str | None = None
publication_type: str | None = None
language: str | None = None
publication_url: str | None = None
pdf_url: str | None = None
source_name: str | None = None
source_type: str | None = None
is_open_access: bool | None = None
open_access_status: str | None = None
has_fulltext: bool | None = None
license: str | None = None
cited_by_count: int | None = None
is_retracted: bool | None = None
primary_topic: str | None = None
topic_field: str | None = None
topic_subfield: str | None = None
topic_domain: str | None = None
author_position: str | None = None
authors: list[str] = Field(default_factory=list)
funder_names: list[str] = Field(default_factory=list)
institutions: list[str] = Field(default_factory=list)
countries: list[str] = Field(default_factory=list)
topics: list[str] = Field(default_factory=list)
keywords: list[str] = Field(default_factory=list)
grant_labels: list[str] = Field(default_factory=list)
counts_by_year: list[dict[str, Any]] = Field(default_factory=list)
class FunderByAuthor(BaseModel):
funder_id: str | None = None
funder_name: str | None = None
@@ -35,6 +70,7 @@ class FunderByAuthor(BaseModel):
publication_ids: PublicationIdsByAuthorPosition
publication_urls: dict[str, str] = {}
publication_titles: dict[str, str] = {}
publication_details: dict[str, PublicationDetailByFunder] = Field(default_factory=dict)
class FundersByAuthorResponse(BaseModel):
+136 -1
View File
@@ -21,7 +21,11 @@ def _funded_publication_hit(
author_position: str = "first",
award_funder_id: str | None = None,
award_funder_name: str | None = None,
award_display_name: str | None = None,
award_number: str | None = None,
pdf_url: str | None = None,
abstract_inverted_index: dict | None = None,
extra_source: dict | None = None,
) -> dict:
source: dict = {
"id": work_id,
@@ -40,6 +44,10 @@ def _funded_publication_hit(
"funders": [],
"awards": [],
}
if abstract_inverted_index:
source["abstract_inverted_index"] = abstract_inverted_index
if extra_source:
source.update(extra_source)
if funder_id or funder_name:
source["funders"].append(
{
@@ -52,6 +60,8 @@ def _funded_publication_hit(
{
"funder_id": award_funder_id,
"funder_display_name": award_funder_name,
"display_name": award_display_name,
"funder_award_id": award_number,
}
)
return {"_source": source}
@@ -74,6 +84,59 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
funder_name="Funder A",
author_position="first",
pdf_url="https://example.org/w1.pdf",
abstract_inverted_index={
"This": [0],
"is": [1],
"an": [2],
"abstract.": [3],
},
extra_source={
"title": "Example publication: full detail",
"funders": [
{
"id": "https://openalex.org/F456",
"display_name": "Funder B",
}
],
"publication_year": 2020,
"publication_date": "2020-05-10",
"type": "article",
"language": "en",
"cited_by_count": 12,
"is_retracted": False,
"primary_location": {
"pdf_url": "https://example.org/w1.pdf",
"is_oa": True,
"license": "cc-by",
"source": {
"display_name": "Example Journal",
"type": "journal",
},
},
"open_access": {
"is_oa": True,
"oa_status": "gold",
"any_repository_has_fulltext": True,
},
"primary_topic": {
"display_name": "Clinical Trials",
"subfield": {"display_name": "Medicine"},
"field": {"display_name": "Health Sciences"},
"domain": {"display_name": "Life Sciences"},
},
"topics": [
{"display_name": "Trials", "score": 0.8},
{"display_name": "Guidelines", "score": 0.6},
],
"keywords": [
{"display_name": "randomised trials", "score": 0.9},
{"display_name": "reporting guideline", "score": 0.7},
],
"counts_by_year": [
{"year": 2024, "cited_by_count": 3},
{"year": 2023, "cited_by_count": 2},
],
},
),
_funded_publication_hit(
"https://openalex.org/W2",
@@ -81,6 +144,8 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
funder_name=None,
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
award_display_name="Project Grant",
award_number="PG-42",
author_position="last",
),
],
@@ -108,7 +173,7 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
assert response.author_id == "https://openalex.org/A5023888391"
assert response.author_name == "Example Author"
assert response.funder_count == 1
assert response.funder_count == 2
assert response.funders[0].funder_id == "https://openalex.org/F123"
assert response.funders[0].funder_name == "Funder A"
assert response.funders[0].publication_count == 2
@@ -118,6 +183,76 @@ async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatc
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
assert publication_detail.title == "Example publication: full detail"
assert publication_detail.funder_names == ["Funder A", "Funder B"]
assert publication_detail.abstract == "This is an abstract."
assert publication_detail.publication_date == "2020-05-10"
assert publication_detail.publication_type == "article"
assert publication_detail.source_name == "Example Journal"
assert publication_detail.source_type == "journal"
assert publication_detail.is_open_access is True
assert publication_detail.open_access_status == "gold"
assert publication_detail.has_fulltext is True
assert publication_detail.license == "cc-by"
assert publication_detail.cited_by_count == 12
assert publication_detail.primary_topic == "Clinical Trials"
assert publication_detail.topic_field == "Health Sciences"
assert publication_detail.topic_subfield == "Medicine"
assert publication_detail.topic_domain == "Life Sciences"
assert publication_detail.topics == ["Trials", "Guidelines"]
assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
assert publication_detail.counts_by_year == [
{"year": 2024, "cited_by_count": 3},
{"year": 2023, "cited_by_count": 2},
]
assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
"Project Grant"
]
@pytest.mark.anyio
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 1},
"hits": [
_funded_publication_hit(
"https://openalex.org/W3",
funder_id="https://openalex.org/F123",
funder_name="Funder A",
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
award_display_name=None,
award_number="ANR-12-1234",
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
@pytest.mark.anyio
@@ -0,0 +1,504 @@
import logging
from typing import List, Set
from typing import Any, Dict, Literal, Optional
from inse.models.openalex.institution import Institution
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.institutions.model import InstitutionPage
logger = logging.getLogger(__name__)
class InstitutionsSearchClient:
def __init__(self):
"""
Initializes the client. Credentials and URLs are handled by the
centralized elasticsearch integration.
"""
pass
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
"""Retrieves an institution by its raw OpenAlex institution ID.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID to search for.
Raises:
NotFoundException: If no institution is found with the given ID or if the institution data cannot be parsed.
Returns:
Institution: The institution corresponding to the given raw OpenAlex institution ID.
"""
query = {
"match": {
"id": f"https://openalex.org/{raw_oa_institution_id.upper()}",
}
}
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
hits = res.get("hits", {}).get("hits", [])
if not hits:
raise NotFoundException(
f"Institution with ID '{raw_oa_institution_id}' not found."
)
institution = self._convert_hit_to_institution(hits[0])
if not institution:
raise NotFoundException(
f"Institution with ID '{raw_oa_institution_id}' could not be parsed."
)
return institution
async def get_eu_organisation_id_by_oa_institution_id(
self, raw_institution_id: str
) -> Optional[str]:
"""Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available.
Args:
raw_institution_id (str): The raw OpenAlex institution ID for which to retrieve the EU organisation ID.
Returns:
Optional[str]: The corresponding EU organisation ID, or None if not found.
"""
raw_institution_id = raw_institution_id.upper()
cache = {
"I62318514": "999843312",
}
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
return cache.get(raw_institution_id)
def get_institutions_by_name(
self,
name: str,
page: int = 0,
size: int = 10,
sort_by: Literal[
"relevance", "name", "works_count", "citations_count"
] = "relevance",
sorting_direction: Literal["asc", "desc"] = "asc",
) -> InstitutionPage:
sort_config: list = []
if sort_by == "relevance":
sort_config.append(
{
"_score": {
"order": sorting_direction if sorting_direction else "desc"
}
}
)
elif sort_by == "works_count":
sort_config.append({"works_count": {"order": sorting_direction}})
elif sort_by == "citations_count":
sort_config.append({"cited_by_count": {"order": sorting_direction}})
else:
sort_config.append({"display_name.keyword": {"order": sorting_direction}})
query: Dict[str, Any] = {"match_all": {}}
if len(name) > 0:
query = {
"match_phrase_prefix": {
"display_name": {
"query": name,
"max_expansions": 50,
}
}
}
elif sort_by == "relevance":
sort_config = [{"display_name.keyword": {"order": sorting_direction}}]
logger.debug(
"Searching institutions with name='%s', page=%d, size=%d, sorting_direction='%s', query: %s",
name,
page,
size,
sorting_direction,
query,
)
try:
response = elasticsearch.search(
index="openalex-institutions",
offset=page * size,
size=size,
sort=sort_config,
query=query,
)
except Exception as e:
logger.exception("Error while searching for institutions: %s", e)
raise
return self.response_to_institution_page(response, page, size)
def response_to_institution_page(
self, response: Dict[str, Any], page: int, size: int
) -> InstitutionPage:
hits = response.get("hits", {}).get("hits", [])
institutions = []
for hit in hits:
institution = self._convert_hit_to_institution(hit)
if institution:
institutions.append(institution)
total = response.get("hits", {}).get("total", {}).get("value", 0)
logger.debug(
"Parsed institution page: page=%d, size=%d, total=%d", page, size, total
)
return InstitutionPage(
elements=institutions,
page=page,
size=size,
total=total,
)
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
"""
Fetches authors associated with an institution.
Note: This query is specifically looking for current affiliations (2026).
"""
query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"must": [
{
"term": {
"affiliations.institution.id": f"https://openalex.org/{raw_institution_id.upper()}"
}
},
{
"range": {
"affiliations.years": {"gte": 2026, "lte": 2026}
}
},
]
}
},
}
}
logger.debug(
"Fetching authors for institution_id=%s with query: %s",
raw_institution_id,
query,
)
res = elasticsearch.search(index="openalex-authors", query=query)
hits = res.get("hits", {}).get("hits", [])
# Extracting display_name directly from the author document source
authors = {
hit["_source"].get("display_name")
for hit in hits
if hit["_source"].get("display_name")
}
return list(authors)
def search_institutions(
self,
query_text: str,
country_code: str | None = None,
institution_type: str | None = None,
limit: int = 10,
) -> list[Institution]:
"""
Autocomplete search for institutions using multi_match on search_as_you_type fields.
Falls back to fuzzy match for typo tolerance on longer queries.
"""
must = []
if query_text:
stripped = query_text.strip()
must.append(
{
"bool": {
"should": [
{
"wildcard": {
"display_name.keyword": {
"value": f"*{stripped}*",
"boost": 2,
}
}
},
{
"wildcard": {
"display_name_alternatives.keyword": {
"value": f"*{stripped}*",
"boost": 2,
}
}
},
{
"wildcard": {
"display_name_acronyms.keyword": {
"value": f"*{stripped.upper()}*",
"boost": 10,
}
}
},
],
"minimum_should_match": 1,
}
}
)
filter_queries = []
if country_code:
filter_queries.append({"term": {"country_code": country_code.upper()}})
if institution_type:
filter_queries.append({"term": {"type": institution_type}})
query = {
"bool": {
"must": must,
"filter": filter_queries,
}
}
res = elasticsearch.search(
index="openalex-institutions",
query=query,
size=limit,
# Blend relevance score with works_count popularity signal
sort=[
{"works_count": {"order": "desc"}},
],
source=[
"id",
"display_name",
"country_code",
"type",
"works_count",
"cited_by_count",
"geo",
],
)
hits = res.get("hits", {}).get("hits", [])
return [Institution.from_dict(hit["_source"]) for hit in hits]
def get_institution_aliases_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> List[str]:
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve aliases.
Returns:
List[str]: A list of aliases for the given institution ID.
"""
institution = self.get_institution_by_id(raw_oa_institution_id)
aliases = list(
self.augment_aliases(set(institution.display_name_alternatives or []))
| self.get_predefined_institution_aliases(raw_oa_institution_id)
)
logger.debug(
"Retrieved aliases for institution_id=%s: %s",
raw_oa_institution_id,
aliases,
)
return aliases
def get_predefined_institution_aliases(
self, raw_oa_institution_id: str
) -> Set[str]:
"""Get predefined aliases for a given institution ID.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve predefined aliases.
Returns:
Set[str]: A set of predefined aliases for the given institution ID.
"""
raw_oa_institution_id = raw_oa_institution_id.upper()
predefined_aliases = {
"I62318514": [
"universität duisburg-essen",
"university of duisburg-essen",
"universitaet duisburg-essen",
"universität duisburg-essen",
"universitat duisburg-essen",
],
}
return self.augment_aliases(
set(predefined_aliases.get(raw_oa_institution_id, []))
)
def augment_aliases(self, aliases: Set[str]) -> Set[str]:
"""Augment a set of aliases by applying the augment_alias function to each alias.
Args:
aliases (Set[str]): A set of aliases to augment.
Returns:
Set[str]: A set of augmented aliases.
"""
augmented_aliases = set()
for alias in aliases:
augmented_aliases.update(self.augment_alias(alias))
return augmented_aliases
def augment_alias(self, alias: str) -> List[str]:
"""Augment an alias by replacing German umlauts and ß with their alternative spellings.
Args:
alias (str): The alias to augment.
Returns:
List[str]: A list of augmented aliases.
"""
alias = alias.lower()
aliases = [alias]
aliases.append(
alias.replace("ä", "ae")
.replace("ö", "oe")
.replace("ü", "ue")
.replace("ß", "ss")
)
aliases.append(
alias.replace("ae", "ä")
.replace("oe", "ö")
.replace("ue", "ü")
.replace("ss", "ß")
)
aliases.append(
alias.replace("ä", "a")
.replace("ö", "o")
.replace("ü", "u")
.replace("ß", "s")
)
aliases.append(alias.replace("-", " "))
return aliases
def _convert_hit_to_institution(self, hit: Dict[str, Any]) -> Optional[Institution]:
"""Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
Args:
hit (Dict[str, Any]): The Elasticsearch hit to convert.
Returns:
Optional[Institution]: The converted Institution object or None if conversion fails.
"""
source = hit.get("_source")
if not source:
return None
ALLOWED_TYPES = {
"education",
"healthcare",
"company",
"archive",
"nonprofit",
"government",
"facility",
"other",
}
cleaned_source = {}
for key, value in source.items():
if isinstance(value, str) and "T" in value:
cleaned_source[key] = value.split("T")[0]
elif key == "type" and value not in ALLOWED_TYPES:
cleaned_source[key] = "other"
else:
cleaned_source[key] = value
try:
return Institution.model_validate(cleaned_source)
except Exception as e:
logger.exception(
"Failed to validate institution hit ID %s: %s", hit.get("_id"), e
)
return None
def get_cordis_eu_organisation_ids_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> Optional[List[str]]:
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
Args:
raw_oa_institution_id (str): The raw OpenAlex institution ID for which to retrieve the corresponding EU organisation IDs.
Returns:
Optional[List[str]]: A list of corresponding EU organisation IDs or None if the search fails.
"""
institution_aliases = set(
self.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id=raw_oa_institution_id
)
)
body = {
"size": 0,
"query": {
"bool": {
"filter": [
{
"terms": {
"name.keyword": [
institution_alias.upper()
for institution_alias in institution_aliases
]
}
}
]
}
},
"aggs": {
"organisation_ids": {
"terms": {"field": "organisationID", "size": 10000}
}
},
}
logger.debug(
"Searching for EU organisation IDs for raw_oa_institution_id=%s with aliases=%s and query: %s",
raw_oa_institution_id,
institution_aliases,
body,
)
try:
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
response = elasticsearch.search(
index="cordis_eu_*_organizations", body=body, cluster="inse"
)
except Exception as e:
logger.exception("Error while searching for EU organisation IDs: %s", e)
return None
logger.debug(
"Received response for EU organisation ID search for raw_oa_institution_id=%s: %s",
raw_oa_institution_id,
response,
)
aggregations = response.get("aggregations", {})
organisation_ids_buckets = aggregations.get("organisation_ids", {}).get(
"buckets", []
)
organisation_ids = [bucket.get("key") for bucket in organisation_ids_buckets]
logger.debug(
"Extracted EU organisation IDs for raw_oa_institution_id=%s: %s",
raw_oa_institution_id,
organisation_ids,
)
return organisation_ids
+49 -37
View File
@@ -3,9 +3,10 @@
"""
Business logic for OpenAlex institutions.
"""
import logging
from copy import deepcopy
from typing import Any
from typing import Any, Optional
import httpx
from fastapi import HTTPException
@@ -13,11 +14,15 @@ from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.openalex.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner,
)
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.models.openalex.institution import Institution
from .search_client import OpenAlexInstitutionsClient
from inse.institutions.institutions_search_client import InstitutionsSearchClient
logger = logging.getLogger(__name__)
@@ -33,6 +38,12 @@ _VALID_INSTITUTION_TYPES = {
}
async def get_institution_by_id(
raw_institution_id: str, client: InstitutionsSearchClient
) -> Institution:
return client.get_institution_by_id(raw_institution_id)
async def list_institutions(
*,
search: str | None = None,
@@ -85,7 +96,10 @@ async def list_institutions(
try:
normalized_data = _normalize_institutions_response(data)
return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse()
return (
InstitutionsListResponse.from_dict(normalized_data)
or InstitutionsListResponse()
)
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
raise HTTPException(
@@ -100,37 +114,29 @@ async def autocomplete_institutions(
country_code: str | None = None,
institution_type: str | None = None,
limit: int = 10,
client: OpenAlexInstitutionsClient | None = None,
client: InstitutionsSearchClient,
) -> AutocompleteResponse:
filters = []
if country_code:
filters.append(f"country_code:{country_code}")
if institution_type:
filters.append(f"type:{institution_type}")
response = await list_institutions(
search=query,
filter=",".join(filters) if filters else None,
sort="works_count:desc",
per_page=limit,
page=1,
select=(
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
),
client=client,
"""
Returns institution options for autocomplete inputs using the local
Elasticsearch cluster via the provided client.
"""
institutions = client.search_institutions(
query_text=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
)
results = []
for institution in response.results or []:
for institution in institutions:
if not institution.id or not institution.display_name:
continue
hint_parts = []
if institution.geo:
if institution.geo.city:
if hasattr(institution, "geo") and institution.geo:
if hasattr(institution.geo, "city") and institution.geo.city:
hint_parts.append(institution.geo.city)
if institution.geo.country:
if hasattr(institution.geo, "country") and institution.geo.country:
hint_parts.append(institution.geo.country)
elif institution.country_code:
hint_parts.append(institution.country_code)
@@ -150,12 +156,7 @@ async def autocomplete_institutions(
)
return AutocompleteResponse(
meta=AutocompleteResponseMeta(
count=response.meta.count if response.meta else len(results),
db_response_time_ms=(
response.meta.db_response_time_ms if response.meta else None
),
),
meta=AutocompleteResponseMeta(count=len(results)),
results=results,
)
@@ -165,7 +166,13 @@ def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
meta = normalized.get("meta")
if isinstance(meta, dict):
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
for field in [
"count",
"db_response_time_ms",
"page",
"per_page",
"groups_count",
]:
meta[field] = _int_or_none(meta.get(field))
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
@@ -187,7 +194,10 @@ def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
institution[field] = _str_or_none(institution.get(field))
institution_type = institution.get("type")
if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES:
if (
institution_type is not None
and institution_type not in _VALID_INSTITUTION_TYPES
):
institution["type"] = None
else:
institution["type"] = _str_or_none(institution_type)
@@ -202,7 +212,9 @@ def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
institution["works_count"] = _int_or_none(institution.get("works_count"))
institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count"))
institution["created_date"] = _date_str_or_none(institution.get("created_date"))
institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date"))
institution["updated_date"] = _datetime_str_or_none(
institution.get("updated_date")
)
summary_stats = institution.get("summary_stats")
if isinstance(summary_stats, dict):
@@ -0,0 +1,17 @@
from typing import List
from pydantic import BaseModel, Field
from inse.models.openalex.institution import Institution
class InstitutionPage(BaseModel):
elements: List[Institution] = Field(
default_factory=list, description="List of institutions in the current page."
)
page: int = Field(default=0, description="Current page number. (0-indexed)")
size: int = Field(default=10, description="Number of institutions per page.")
total: int = Field(
default=0,
description="Total number of institutions matching the search criteria.",
)
@@ -0,0 +1,207 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
from functools import lru_cache
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, status, Query
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from inse.models.openalex.institution import Institution
from inse.institutions.model import InstitutionPage
from . import logic
from inse.institutions.institutions_search_client import InstitutionsSearchClient
router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS])
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
return InstitutionsSearchClient()
@router.get(
"/search",
summary="Searches for institutions by name.",
description="Searches for institutions by name with pagination.",
operation_id="searchInstitutionsByName",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": InstitutionPage,
},
},
response_model_exclude_none=True,
)
async def search_institutions_by_name(
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
name: Annotated[
str,
Query(
description="Institution name to search for, for example 'University of Duisburg Essen'.",
),
] = "",
page: Annotated[
int,
Query(description="Page number (0-indexed).", ge=0),
] = 0,
size: Annotated[
int,
Query(description="Number of institutions per page.", ge=1, le=100),
] = 10,
sort_by: Annotated[
Literal["relevance", "name", "works_count", "citations_count"],
Query(
description="Field to sort by, either 'relevance', 'name', 'works_count', or 'citations_count'.",
regex="^(relevance|name|works_count|citations_count)$",
),
] = "name",
sorting_direction: Annotated[
Literal["asc", "desc"],
Query(
description="Sorting direction, either 'asc' or 'desc'.",
regex="^(asc|desc)$",
),
] = "asc",
) -> InstitutionPage:
return client.get_institutions_by_name(
name=name,
page=page,
size=size,
sort_by=sort_by,
sorting_direction=sorting_direction,
)
@router.get(
"/autocomplete",
operation_id="autocompleteInstitutions",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns institution options for autocomplete inputs.",
)
async def autocomplete_institutions(
query: Annotated[
str,
Query(
description="Institution search text, for example 'Duisburg Essen'.",
min_length=1,
),
],
country_code: Annotated[
str | None,
Query(alias="countryCode", description="Optional ISO country code filter."),
] = None,
institution_type: Annotated[
str | None,
Query(alias="type", description="Optional institution type filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
] = None,
):
return await logic.autocomplete_institutions(
query=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
client=client,
)
@router.get(
"/{id}",
summary="Returns a single institution by ID.",
description="Returns a single institution by its OpenAlex ID.",
operation_id="getInstitutionById",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": Institution,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
)
async def get_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
) -> Institution:
return await logic.get_institution_by_id(raw_institution_id=id, client=client)
@router.get(
"",
operation_id="listInstitutions",
response_model=InstitutionsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex institutions.",
)
async def list_institutions(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'Duisburg Essen'."),
] = None,
filter: Annotated[
str | None,
Query(
description="OpenAlex filter, for example 'country_code:DE,type:education'."
),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'country_code'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(
description="Random sample size. Cannot be combined with sort or page.",
ge=1,
le=10000,
),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
@@ -3,6 +3,7 @@
"""
HTTP client for OpenAlex institutions.
"""
from typing import Any
import httpx
@@ -19,8 +20,14 @@ class OpenAlexInstitutionsClient:
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds
self.api_key = (
api_key if api_key is not None else config.settings.openalex_api_key
)
self.timeout = (
timeout
if timeout is not None
else config.settings.openalex_api_timeout_seconds
)
self.transport = transport
def list_institutions_params(
@@ -1,108 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from . import logic
router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
@router.get(
"/autocomplete",
operation_id="autocompleteInstitutions",
response_model=AutocompleteResponse,
response_model_exclude_none=True,
summary="Returns institution options for autocomplete inputs.",
)
async def autocomplete_institutions(
query: Annotated[
str,
Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1),
],
country_code: Annotated[
str | None,
Query(alias="countryCode", description="Optional ISO country code filter."),
] = None,
institution_type: Annotated[
str | None,
Query(alias="type", description="Optional institution type filter."),
] = None,
limit: Annotated[
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
):
return await logic.autocomplete_institutions(
query=query,
country_code=country_code,
institution_type=institution_type,
limit=limit,
)
@router.get(
"",
operation_id="listInstitutions",
response_model=InstitutionsListResponse,
response_model_exclude_none=True,
summary="Returns a list of OpenAlex institutions.",
)
async def list_institutions(
search: Annotated[
str | None,
Query(description="Full-text search, for example 'Duisburg Essen'."),
] = None,
filter: Annotated[
str | None,
Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."),
] = None,
sort: Annotated[
str | None,
Query(description="Sort field, for example 'works_count:desc'."),
] = "works_count:desc",
group_by: Annotated[
str | None,
Query(description="OpenAlex group_by field, for example 'country_code'."),
] = None,
per_page: Annotated[
int,
Query(description="Results per page.", ge=1, le=100),
] = 25,
page: Annotated[
int | None,
Query(description="Page number. Use cursor for deep pagination.", ge=1),
] = 1,
cursor: Annotated[
str | None,
Query(description="Cursor pagination token. Use '*' to start."),
] = None,
sample: Annotated[
int | None,
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
] = None,
select: Annotated[
str | None,
Query(description="Comma-separated fields to return."),
] = None,
):
return await logic.list_institutions(
search=search,
filter=filter,
sort=sort,
group_by=group_by,
per_page=per_page,
page=page,
cursor=cursor,
sample=sample,
select=select,
)
@@ -176,61 +176,3 @@ async def test_list_institutions_accepts_practical_openalex_type_variants():
assert result.results[0].counts_by_year[0].cited_by_count is None
assert result.group_by[0].key == "true"
@pytest.mark.anyio
async def test_autocomplete_institutions_returns_frontend_options():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.params["search"] == "Duisburg Essen"
assert request.url.params["filter"] == "country_code:DE,type:education"
assert request.url.params["sort"] == "works_count:desc"
assert request.url.params["per_page"] == "5"
assert request.url.params["select"] == (
"id,ror,display_name,country_code,type,works_count,"
"cited_by_count,geo"
)
return httpx.Response(
200,
json={
"meta": {"count": 1, "db_response_time_ms": 12},
"results": [
{
"id": "https://openalex.org/I123",
"ror": "https://ror.org/04mz5ra38",
"display_name": "University of Duisburg-Essen",
"country_code": "DE",
"type": "education",
"works_count": 123,
"cited_by_count": 456,
"geo": {
"city": "Duisburg",
"country": "Germany",
},
}
],
},
)
client = OpenAlexInstitutionsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
result = await logic.autocomplete_institutions(
query="Duisburg Essen",
country_code="DE",
institution_type="education",
limit=5,
client=client,
)
assert result.meta.count == 1
assert result.meta.db_response_time_ms == 12
assert len(result.results) == 1
option = result.results[0]
assert option.id == "https://openalex.org/I123"
assert option.display_name == "University of Duisburg-Essen"
assert option.hint == "Duisburg · Germany · education"
assert option.works_count == 123
assert option.cited_by_count == 456
assert option.entity_type == "institution"
assert option.external_id == "https://ror.org/04mz5ra38"
@@ -1,30 +1,143 @@
from typing import Any, Optional
import json
import logging
from typing import Any, Dict, List, Optional, Tuple
import httpx
from inse.model import ESCluster, ESIndex
from .. import config
logger = logging.getLogger(__name__)
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
Args:
cluster (ElasticsearchCluster): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse".
Raises:
ValueError: If the cluster is unknown or the credentials are not set in the configuration.
Returns:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
if cluster == ESCluster.NES:
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
):
raise ValueError(
"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 (
not config.settings.elasticsearch_inse_url
or not config.settings.elasticsearch_inse_api_key
):
raise ValueError(
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
)
return (
config.settings.elasticsearch_inse_url,
config.settings.elasticsearch_inse_api_key,
)
else:
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
"""Determines the Elasticsearch cluster to use based on the specified index.
Args:
index (ESIndex): The Elasticsearch index for which to determine the cluster. Allowed values are defined in the ESIndex enum.
Raises:
ValueError: If the index is unknown.
Returns:
ESCluster: The Elasticsearch cluster to use for the specified index.
"""
if index in {
ESIndex.OPENALEX_WORKS,
ESIndex.OPENALEX_AUTHORS,
ESIndex.OPENALEX_INSTITUTIONS,
ESIndex.OPENALEX_PUBLICATIONS,
}:
return ESCluster.NES
elif index in {
ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
ESIndex.PROJECTS_BUND_V1,
ESIndex.PROJECTS_DFG_ALL,
}:
return ESCluster.INSE
else:
return None
def search(
index: str,
query_field: str = None,
query_value: str = None,
query: dict = None,
source = None,
size: int = None,
offset:int = None,
sort: list = None,
body: dict = None,
track_total_hits = False
) -> dict[str, Any]:
index: ESIndex | List[ESIndex],
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
offset: Optional[int] = None,
sort: Optional[List] = None,
body: Optional[Dict] = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
Args:
index (ElasticsearchIndex): The Elasticsearch index to search.
query (Optional[Dict], optional): The full query body. Defaults to None.
source (Optional[List], optional): The fields to include in the response. Defaults to None.
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
offset (Optional[int], optional): The number of results to skip. Defaults to None.
sort (Optional[List], optional): The fields to sort by. Defaults to None.
body (Optional[Dict], optional): The full query body. Defaults to None.
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
cluster (ElasticsearchCluster, optional): The Elasticsearch cluster to search. Defaults to ElasticsearchCluster.NES.
Returns:
Dict[str, Any]: The search results.
"""
clusters = set()
if isinstance(index, list):
for idx in index:
cluster_for_index = _index_to_cluster(idx)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
else:
cluster_for_index = _index_to_cluster(index)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
if len(clusters) > 1:
raise ValueError(
f"All indices in the search request must belong to the same cluster, but found clusters: {clusters}"
)
elif len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
payload: Dict[str, Any] = {}
if body is not None:
payload = body
elif query is not None:
payload = {"query": query}
else:
if query is not None:
payload["query"] = query
if source is not None:
payload["_source"] = source
if size is not None:
@@ -35,34 +148,40 @@ def search(
payload["sort"] = sort
if track_total_hits:
payload["track_total_hits"] = True
else:
payload = {
"query": {
"query_string": {
"default_field": query_field,
"query": query_value
}
}
}
if highlight is not None:
payload["highlight"] = highlight
if len(payload) == 0:
raise ValueError(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
)
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(index)
else:
index_str = index
with httpx.Client() as client:
response = client.post(
f"{config.settings.elasticsearch_url}/{index}/_search",
json=payload,
headers=headers
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
def get(
index: str,
index: ESIndex,
doc_id: str,
source: list = None,
source: Optional[list] = None,
cluster: ESCluster = ESCluster.NES,
) -> dict[str, Any]:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
params = {}
if source is not None:
@@ -70,11 +189,7 @@ def get(
with httpx.Client() as client:
response = client.get(
f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}",
params=params,
headers=headers
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
+17 -90
View File
@@ -6,91 +6,29 @@ web service.
"""
from typing import List
from typing import TypeVar
from typing import Optional
from typing import Type
from sqlalchemy.orm import Session
from sqlalchemy import select
from sqlalchemy import func
import logging
import httpx
import json
from . import schema
from . import model
from . import config
from inse.models.topic import Topic
from inse.models.topic_subfield import TopicSubfield
from inse.models.topic_field import TopicField
from inse.models.topic_domain import TopicDomain
from inse.models.openalex.topic import Topic
from inse.models.openalex.topic_subfield import TopicSubfield
from inse.models.openalex.topic_field import TopicField
from inse.models.openalex.topic_domain import TopicDomain
logger = logging.getLogger(__name__)
topic_cache_filename: str = "topic_hierarchy_cache.json"
S = TypeVar('S', bound=schema.Base)
M = TypeVar('M', bound=model.BaseModel)
def filter_none():
return True
def get_page(
db: Session,
schema_type: Type[S],
model_type: Type[M],
offset: int,
limit: int,
filter=filter_none,
) -> model.Page[M]:
result = model.Page[model_type]()
result.offset = offset
result.total = get_count(db, schema_type, filter)
result.size = limit
if result.total > result.offset:
result.elements = get_elements(db, schema_type, offset, limit, filter)
else:
result.elements = []
return result
def get_count(db: Session, schema_type: Type[S], filter=filter_none) -> int:
return db.scalar(select(func.count()).select_from(schema_type).where(filter))
def get_elements(
db: Session, schema_type: Type[S], offset: int, limit: int, filter=filter_none
) -> List[S]:
return db.scalars(
select(schema_type).where(filter).offset(offset).limit(limit)
).all()
def get_element(db: Session, schema_type: Type[S], element_id: int) -> Optional[S]:
return db.scalars(
select(schema_type).where(schema_type.id == element_id).limit(1)
).first()
def delete_element(db: Session, schema_type: Type[S], element_id: int):
element = get_element(db, schema_type, element_id)
db.delete(element)
def insert_element(db: Session, value: S) -> S:
db.add(value)
db.flush()
db.refresh(value)
return value
def _load_topic_cache() -> dict:
"""Loads the topic hierarchy cache from a JSON file."""
import os
try:
cache_path = "/data/" + topic_cache_filename
if not os.path.exists(cache_path):
@@ -231,6 +169,7 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict:
return counts
def get_topic_hierarchy() -> dict:
"""
Builds and returns a hierarchical tree structure of topics:
@@ -238,28 +177,25 @@ def get_topic_hierarchy() -> dict:
"""
flat_cache = _load_topic_cache()
tree = {}
for topic_name, info in flat_cache.items():
domain = info.get("domain") or "Unbekannter Bereich"
field = info.get("field") or "Unbekanntes Feld"
subfield = info.get("subfield") or "Unbekanntes Teilfeld"
topic_id = info.get("topic_id", "")
# Clean topic ID to just be the trailing ID or keep full URL
# For querying, display name is used in persons search, but ID is useful
if domain not in tree:
tree[domain] = {}
if field not in tree[domain]:
tree[domain][field] = {}
if subfield not in tree[domain][field]:
tree[domain][field][subfield] = []
tree[domain][field][subfield].append({
"id": topic_id,
"name": topic_name
})
tree[domain][field][subfield].append({"id": topic_id, "name": topic_name})
formatted_domains = []
for d_name, d_fields in tree.items():
formatted_fields = []
@@ -267,20 +203,11 @@ def get_topic_hierarchy() -> dict:
formatted_subfields = []
for sf_name, sf_topics in f_subfields.items():
sf_topics.sort(key=lambda x: x["name"])
formatted_subfields.append({
"name": sf_name,
"topics": sf_topics
})
formatted_subfields.append({"name": sf_name, "topics": sf_topics})
formatted_subfields.sort(key=lambda x: x["name"])
formatted_fields.append({
"name": f_name,
"subfields": formatted_subfields
})
formatted_fields.append({"name": f_name, "subfields": formatted_subfields})
formatted_fields.sort(key=lambda x: x["name"])
formatted_domains.append({
"name": d_name,
"fields": formatted_fields
})
formatted_domains.append({"name": d_name, "fields": formatted_fields})
formatted_domains.sort(key=lambda x: x["name"])
return {"domains": formatted_domains}
+59 -9
View File
@@ -6,20 +6,39 @@ for fastapi that loads the service and the
webapp.
"""
from contextlib import asynccontextmanager, contextmanager
import logging
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from inse.collaboration_network.router import router as collaboration_network_router
from inse.institutions.service import router as institutions_service_router
from inse.company_connections.service import router as company_connections_router
from inse.exceptions import NotFoundException
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
# caching
from inse.middleware.etag_cache import ETagCacheMiddleware
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.persons.service import router as persons_service_router
from inse.funders.service import router as funders_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.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts
from . import config
from .service import router as service_router
from .account.service import router as account_router
logger = logging.getLogger(__name__)
@@ -27,31 +46,62 @@ logger = logging.getLogger(__name__)
settings = config.get_settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting up the application...")
create_db_and_tables()
with contextmanager(get_session)() as session:
create_predefined_accounts(session, "../data/predefined_accounts.json")
yield
logger.info("Shutting down the application...")
app = FastAPI(
redoc_url=None,
title="Innovation Search Engine API",
description="API for the Innovation Search Engine (INSE) application.",
version="0.1.0",
servers=settings.servers,
lifespan=lifespan,
)
app.include_router(collaboration_network_router)
app.include_router(institutions_service_router)
app.include_router(institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
app.include_router(funders_service_router)
app.include_router(service_router)
app.include_router(account_router)
app.include_router(news_service_router)
app.include_router(company_connections_router)
app.include_router(patents_service_router)
app.include_router(university_ranking_router)
app.include_router(projects_router)
app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=300, # 5 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["ETag"],
)
@app.exception_handler(NotFoundException)
async def handle_not_found(request: Request, exc: NotFoundException):
return JSONResponse(status_code=404, content={"message": str(exc)})
@app.exception_handler(404)
async def redirect(_, __):
return RedirectResponse(url="/inse-webapp/")
@@ -0,0 +1,74 @@
# 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,
)
+24 -21
View File
@@ -1,40 +1,43 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module defines the model classes returned from
our api using pydantic.
This module defines the model classes returned from
our api using pydantic.
"""
from enum import StrEnum
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from typing import List
from typing import TypeVar
from typing import Generic
from typing import Optional
T = TypeVar('T', bound=BaseModel)
T = TypeVar("T", bound=BaseModel)
class Entity(BaseModel):
id: int = Field(description="The id of the entity.")
class Item(Entity):
model_config = ConfigDict(from_attributes=True)
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class ItemCreate(BaseModel):
name: str = Field(description="The name of the item.")
description: str = Field(description="The description of the item.")
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page offset in elements.")
total: int = Field(default=0, description="The total number of elements.")
offset: int = Field(default=0, description="The page number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
class ItemPage(Page[Item]):
pass
total: int = Field(default=0, description="The total number of elements.")
class ESCluster(StrEnum):
NES = "nes"
INSE = "inse"
class ESIndex(StrEnum):
OPENALEX_WORKS = "openalex-works"
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
OPENALEX_PUBLICATIONS = "openalex-publications"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
+1 -128
View File
@@ -1,128 +1 @@
# coding: utf-8
# flake8: noqa
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
# import models into model package
from inse.models.author import Author
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.author_ids import AuthorIds
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.author_summary_stats import AuthorSummaryStats
from inse.models.author_topics_inner import AuthorTopicsInner
from inse.models.authors_list_response import AuthorsListResponse
from inse.models.authorship import Authorship
from inse.models.autocomplete_response import AutocompleteResponse
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.award import Award
from inse.models.award_full import AwardFull
from inse.models.award_full_funder import AwardFullFunder
from inse.models.awards_list_response import AwardsListResponse
from inse.models.concept import Concept
from inse.models.concept_ids import ConceptIds
from inse.models.concepts_list_response import ConceptsListResponse
from inse.models.continent import Continent
from inse.models.continent_ids import ContinentIds
from inse.models.continents_list_response import ContinentsListResponse
from inse.models.countries_list_response import CountriesListResponse
from inse.models.country import Country
from inse.models.country_continent import CountryContinent
from inse.models.country_ids import CountryIds
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_funder import DehydratedFunder
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.dehydrated_source import DehydratedSource
from inse.models.domain import Domain
from inse.models.domain_fields_inner import DomainFieldsInner
from inse.models.domain_ids import DomainIds
from inse.models.domains_list_response import DomainsListResponse
from inse.models.error import Error
from inse.models.fields_list_response import FieldsListResponse
from inse.models.funder import Funder
from inse.models.funder_ids import FunderIds
from inse.models.funders_list_response import FundersListResponse
from inse.models.get_changefile200_response import GetChangefile200Response
from inse.models.get_changefile200_response_meta import GetChangefile200ResponseMeta
from inse.models.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
from inse.models.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
from inse.models.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
from inse.models.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
from inse.models.group_by_result import GroupByResult
from inse.models.institution import Institution
from inse.models.institution_geo import InstitutionGeo
from inse.models.institution_ids import InstitutionIds
from inse.models.institution_type import InstitutionType
from inse.models.institution_types_list_response import InstitutionTypesListResponse
from inse.models.institutions_list_response import InstitutionsListResponse
from inse.models.keyword import Keyword
from inse.models.keywords_list_response import KeywordsListResponse
from inse.models.language import Language
from inse.models.languages_list_response import LanguagesListResponse
from inse.models.license import License
from inse.models.licenses_list_response import LicensesListResponse
from inse.models.list_changefiles200_response import ListChangefiles200Response
from inse.models.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
from inse.models.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
from inse.models.location import Location
from inse.models.meta import Meta
from inse.models.model_field import ModelField
from inse.models.open_access import OpenAccess
from inse.models.publisher import Publisher
from inse.models.publisher_ids import PublisherIds
from inse.models.publisher_parent_publisher import PublisherParentPublisher
from inse.models.publishers_list_response import PublishersListResponse
from inse.models.rate_limit_response import RateLimitResponse
from inse.models.rate_limit_response_rate_limit import RateLimitResponseRateLimit
from inse.models.rate_limit_response_rate_limit_endpoint_costs_usd import RateLimitResponseRateLimitEndpointCostsUsd
from inse.models.sdg import Sdg
from inse.models.sdg_ids import SdgIds
from inse.models.sdgs_list_response import SdgsListResponse
from inse.models.source import Source
from inse.models.source_ids import SourceIds
from inse.models.source_type import SourceType
from inse.models.source_types_list_response import SourceTypesListResponse
from inse.models.sources_list_response import SourcesListResponse
from inse.models.subfield import Subfield
from inse.models.subfield_domain import SubfieldDomain
from inse.models.subfield_field import SubfieldField
from inse.models.subfields_list_response import SubfieldsListResponse
from inse.models.text_classification_response import TextClassificationResponse
from inse.models.text_classification_response_meta import TextClassificationResponseMeta
from inse.models.topic import Topic
from inse.models.topic_domain import TopicDomain
from inse.models.topic_field import TopicField
from inse.models.topic_ids import TopicIds
from inse.models.topic_subfield import TopicSubfield
from inse.models.topics_list_response import TopicsListResponse
from inse.models.work import Work
from inse.models.work_biblio import WorkBiblio
from inse.models.work_citation_normalized_percentile import WorkCitationNormalizedPercentile
from inse.models.work_cited_by_percentile_year import WorkCitedByPercentileYear
from inse.models.work_counts_by_year_inner import WorkCountsByYearInner
from inse.models.work_has_content import WorkHasContent
from inse.models.work_ids import WorkIds
from inse.models.work_keyword import WorkKeyword
from inse.models.work_mesh_inner import WorkMeshInner
from inse.models.work_sustainable_development_goals_inner import WorkSustainableDevelopmentGoalsInner
from inse.models.work_topic import WorkTopic
from inse.models.work_topic_domain import WorkTopicDomain
from inse.models.work_topic_field import WorkTopicField
from inse.models.work_topic_subfield import WorkTopicSubfield
from inse.models.work_type import WorkType
from inse.models.work_types_list_response import WorkTypesListResponse
from inse.models.works_list_response import WorksListResponse
from inse.models.work_page import WorkPage
from inse.models.lsf_person import LsfPerson
# empty package marker
@@ -0,0 +1,226 @@
from datetime import datetime, date
from typing import Annotated, Optional
from pydantic import BaseModel, BeforeValidator, ConfigDict, Field
def parse_german_date(value: Optional[str]) -> Optional[date]:
if value is None or isinstance(value, date):
return value
return datetime.strptime(value, "%d.%m.%Y").date()
class BundProject(BaseModel):
model_config = ConfigDict(
populate_by_name=True,
extra="ignore",
)
funding_code: Optional[str] = Field(
default=None,
validation_alias="Förderkennzeichen",
description="The funding code of the project",
examples=["19F2266G"],
)
department: Optional[str] = Field(
default=None,
validation_alias="Ressort",
description="The department of the project",
examples=["BMDV"],
)
department_fullname: Optional[str] = Field(
default=None,
validation_alias="Ressort_fullname",
description="The full name of the department of the project",
examples=["Bundesministerium für Digitales und Verkehr"],
)
referat: Optional[str] = Field(
default=None,
validation_alias="Referat",
description="The referat of the project",
examples=["DP20"],
)
project_sponsor: Optional[str] = Field(
default=None,
validation_alias="Projektträger",
description="The project sponsor of the project",
examples=["PT-TÜV"],
)
project_sponsor_fullname: Optional[str] = Field(
default=None,
validation_alias="Projektträger_fullname",
description="The full name of the project sponsor of the project",
examples=["Projektträger TÜV Rheinland"],
)
work_unit: Optional[str] = Field(
default=None,
validation_alias="Arb.-Einh.",
description="The work unit of the project",
examples=["mFUND"],
)
recipient: Optional[str] = Field(
default=None,
validation_alias="Zuwendungsempfänger",
description="The recipient of the project",
examples=["Universität Duisburg-Essen"],
)
municipal_code: Optional[str] = Field(
default=None,
validation_alias="Gemeindekennziffer",
description="The municipal code of the project",
examples=["05113000"],
)
municipality: Optional[str] = Field(
default=None,
validation_alias="Stadt/Gemeinde",
description="The municipality of the project",
examples=["Essen"],
)
place: Optional[str] = Field(
default=None,
validation_alias="Ort",
description="The place of the project",
examples=["Essen"],
)
state: Optional[str] = Field(
default=None,
validation_alias="Bundesland",
description="The state of the project",
examples=["Nordrhein-Westfalen"],
)
country: Optional[str] = Field(
default=None,
validation_alias="Staat",
description="The country of the project",
examples=["Deutschland"],
)
implementing_agency: Optional[str] = Field(
default=None,
validation_alias="Ausführende Stelle",
description="The implementing agency of the project",
examples=[
"Universität Duisburg-Essen - Fachbereich Allgemeine Informatik - Lehrstuhl Networked Embedded Systems (NES)"
],
)
topic: Optional[str] = Field(
default=None,
validation_alias="Thema",
description="The topic of the project",
examples=[
"Verbundprojekt: Multimodaler Mobilitäts-Index - Moby_Dex -, Teilvorhaben: Universität Duisburg-Essen"
],
)
performance_plan_system: Optional[str] = Field(
default=None,
validation_alias="Leistungsplansystematik",
description="The performance plan system of the project",
examples=["GA6011"],
)
performance_plan_system_text: Optional[str] = Field(
default=None,
validation_alias="Klartext Leistungsplansystematik",
description="The performance plan system text of the project",
examples=["Angewandte Forschung und Experimentelle Entwicklung"],
)
funding_start: Annotated[
Optional[date],
Field(
default=None,
validation_alias="Förderbeginn",
description="The funding start date of the project",
examples=["01.09.2023"],
),
BeforeValidator(parse_german_date),
]
funding_end: Annotated[
Optional[date],
Field(
default=None,
validation_alias="Förderende",
description="The funding end date of the project",
examples=["31.08.2026"],
),
BeforeValidator(parse_german_date),
]
grant_amount: Optional[float] = Field(
default=None,
validation_alias="Fördersumme",
description="The grant amount of the project",
examples=[367651.00],
)
funding_profile: Optional[str] = Field(
default=None,
validation_alias="Förderprofil",
description="The funding profile of the project",
examples=["Technologie- und Innovationsförderung"],
)
joint_project: Optional[str] = Field(
default=None,
validation_alias="Verbundprojekt",
description="Whether the project is a joint project",
examples=["Moby_Dex"],
)
funding_type: Optional[str] = Field(
default=None,
validation_alias="Förderart",
description="The funding type of the project",
examples=["PDIR"],
)
publication_date: Optional[str] = Field(
default=None,
validation_alias="Publikationsdatum",
description="The publication date of the project",
examples=["2023"],
)
unix_timestamp: Optional[int] = Field(
default=None,
validation_alias="Unix-Timestamp",
description="The unix timestamp of the project",
examples=[1737411518],
)
date: Optional[str] = Field(
default=None,
validation_alias="datum",
description="The date of the project",
examples=["20.01.2025"],
)
new: Optional[bool] = Field(
default=None,
validation_alias="neu",
description="Whether the project is new",
examples=[False],
)
duration: Optional[str] = Field(
default=None,
validation_alias="Laufzeit",
description="The duration of the project",
examples=["von 01.09.2023 bis 31.08.2026"],
)
@@ -0,0 +1,337 @@
# coding: utf-8
"""
Bund Project Clean Model
Summary model that consolidates scattered fields from the raw projects_bund index
into clean, semantic field names with proper native Python types.
"""
from datetime import date, datetime
from typing import Optional, List, Set, Any
from pydantic import BaseModel, ConfigDict, Field, field_validator
class BundProjectDetails(BaseModel):
"""
Clean summary model for a Bund (federal) project, consolidating all fields
into semantic English names with proper native types.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
)
# Core identifiers
id: str = Field(description="The ID of the Bund project")
funding_reference: Optional[str] = Field(
default=None,
description="The funding reference number (Förderkennzeichen)",
)
# Project metadata
title: Optional[str] = Field(
default=None,
description="The project topic/title",
)
description: Optional[str] = Field(
default=None,
description="Plain text description of the performance plan classification",
)
joint_project: Optional[str] = Field(
default=None,
description="Parent joint project if this is a sub-project",
)
# Funding information
funding_type: Optional[str] = Field(
default=None,
description="Type of funding (Förderart)",
)
funding_profile: Optional[str] = Field(
default=None,
description="Funding profile (Förderprofil)",
)
funding_amount: Optional[float] = Field(
default=None,
description="Funding amount in EUR",
)
funding_start_date: Optional[date] = Field(
default=None,
description="Funding start date",
)
funding_end_date: Optional[date] = Field(
default=None,
description="Funding end date",
)
duration: Optional[str] = Field(
default=None,
description="Project duration (Laufzeit)",
)
# Classification
performance_plan_code: Optional[str] = Field(
default=None,
description="Performance plan classification code",
)
performance_plan_fullname: Optional[str] = Field(
default=None,
description="Full name of the performance plan classification",
)
# Organizational
executing_agency: Optional[str] = Field(
default=None,
description="Executing agency",
)
funding_recipient: Optional[str] = Field(
default=None,
description="Funding recipient",
)
project_agency: Optional[str] = Field(
default=None,
description="Project management agency",
)
project_agency_fullname: Optional[str] = Field(
default=None,
description="Full name of the project management agency",
)
# Government hierarchy
department: Optional[str] = Field(
default=None,
description="Government department code",
)
department_fullname: Optional[str] = Field(
default=None,
description="Full name of the government department",
)
division: Optional[str] = Field(
default=None,
description="Division/unit reference",
)
# Location
location: Optional[str] = Field(
default=None,
description="Location/city",
)
municipality: Optional[str] = Field(
default=None,
description="City/Municipality",
)
state: Optional[str] = Field(
default=None,
description="Federal state",
)
country: Optional[str] = Field(
default=None,
description="Country",
)
municipality_code: Optional[str] = Field(
default=None,
description="Municipality code",
)
# Publication
publication_date: Optional[str] = Field(
default=None,
description="Publication date",
)
# Additional
is_new: Optional[bool] = Field(
default=None,
description="Flag indicating if the project is new",
)
record_date: Optional[str] = Field(
default=None,
description="Record date",
)
unix_timestamp: Optional[int] = Field(
default=None,
description="Unix timestamp of the record",
)
# Unified lists for aggregation
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the Bund project (from nested Arb object)",
)
institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the Bund project",
)
# --- Validators for type coercion ---
@field_validator("funding_amount", mode="before")
@classmethod
def parse_funding_amount(cls, v: Any) -> Optional[float]:
"""Parse funding amount from string or number."""
if v is None:
return None
if isinstance(v, (int, float)):
return float(v)
if isinstance(v, str):
# Remove thousands separators and trim
cleaned = v.replace(".", "").replace(",", ".").strip()
try:
return float(cleaned)
except ValueError:
return None
return None
@field_validator("funding_start_date", "funding_end_date", mode="before")
@classmethod
def parse_german_date(cls, v: Any) -> Optional[date]:
"""Parse date from German format (dd.MM.yyyy) or date/datetime object."""
if v is None:
return None
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if isinstance(v, str):
v = v.strip()
# Try German format first: dd.MM.yyyy
try:
return datetime.strptime(v, "%d.%m.%Y").date()
except ValueError:
pass
# Try ISO format: yyyy-MM-dd
try:
return datetime.strptime(v, "%Y-%m-%d").date()
except ValueError:
pass
# Try with time component
try:
return datetime.fromisoformat(v).date()
except ValueError:
pass
return None
@field_validator("is_new", mode="before")
@classmethod
def parse_is_new(cls, v: Any) -> Optional[bool]:
"""Parse is_new from bool or string."""
if v is None:
return None
if isinstance(v, bool):
return v
if isinstance(v, str):
return v.lower() in ("true", "1", "yes", "ja")
if isinstance(v, (int, float)):
return bool(v)
return None
@field_validator("unix_timestamp", mode="before")
@classmethod
def parse_unix_timestamp(cls, v: Any) -> Optional[int]:
"""Parse unix timestamp from int, float, or string."""
if v is None:
return None
if isinstance(v, (int, float)):
return int(v)
if isinstance(v, str):
try:
return int(v)
except ValueError:
return None
return None
@classmethod
def from_elastic_hit(cls, hit: dict) -> "BundProject":
"""
Create a BundProject from an Elasticsearch hit, consolidating all fields.
"""
source = hit.get("_source", {})
# --- Extract persons from nested Arb object ---
persons: Set[str] = set()
arb = source.get("Arb")
if arb and isinstance(arb, dict):
for key, value in arb.items():
if isinstance(value, str) and value.strip():
for person in value.split(";"):
person = person.strip()
if person:
persons.add(person)
# --- Extract institutions ---
institutions: Set[str] = set()
inst_fields = [
"Ausführende Stelle",
"Zuwendungsempfänger",
"Projektträger",
]
for field in inst_fields:
if field in source and source[field]:
for inst in source[field].split(";"):
inst = inst.strip()
if inst:
institutions.add(inst)
if source.get("PT_fullname"):
institutions.add(source["PT_fullname"].strip())
return cls(
id=hit["_id"],
funding_reference=source.get("Förderkennzeichen"),
title=source.get("Thema"),
description=source.get("Klartext Leistungsplansystematik"),
joint_project=source.get("Verbundprojekt"),
funding_type=source.get("Förderart"),
funding_profile=source.get("Förderprofil"),
funding_amount=source.get("Fördersumme"),
funding_start_date=source.get("funding_start"),
funding_end_date=source.get("funding_end"),
duration=source.get("Laufzeit"),
performance_plan_code=source.get("Leistungsplansystematik"),
performance_plan_fullname=source.get("Leistungsplansystematik_fullname"),
executing_agency=source.get("Ausführende Stelle"),
funding_recipient=source.get("Zuwendungsempfänger"),
project_agency=source.get("Projektträger"),
project_agency_fullname=source.get("PT_fullname"),
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
division=source.get("Referat"),
location=source.get("Ort"),
municipality=source.get("Stadt/Gemeinde"),
state=source.get("Bundesland"),
country=source.get("Staat"),
municipality_code=source.get("Gemeindekennziffer"),
publication_date=source.get("Publikationsdatum"),
is_new=source.get("new"),
record_date=source.get("datum"),
unix_timestamp=source.get("unix_timestamp"),
associated_persons=sorted(persons),
institutions=sorted(institutions),
)
@@ -0,0 +1,62 @@
from datetime import datetime
from typing import Optional, List, Union
from pydantic import BaseModel, Field
class CordisEuProject(BaseModel):
id: str = Field(
description="Unique identifier for the project, typically the CORDIS ID"
)
rcn: Optional[str] = Field(
None, description="Research and Innovation project number (CORDIS RCN)"
)
acronym: Optional[str] = Field(None, description="Acronym for the project")
title: Optional[str] = Field(None, description="Title of the project")
objective: Optional[str] = Field(None, description="Objective of the project")
frameworkProgramme: Optional[str] = Field(
None, description="Framework Programme under which the project was funded"
)
fundingScheme: Optional[str] = Field(
None, description="Funding scheme of the project"
)
legalBasis: Optional[str] = Field(
None, description="Legal basis for the project funding"
)
masterCall: Optional[str] = Field(
None, description="Master call identifier if applicable"
)
subCall: Optional[str] = Field(
None, description="Sub call identifier if applicable"
)
topics: Optional[Union[str, List[str]]] = (
None # Elastic keyword can map to a single string or list of strings
)
nature: Optional[str] = Field(None, description="Nature of the project")
status: Optional[str] = Field(None, description="Status of the project")
ecMaxContribution: Optional[float] = Field(
None, description="Maximum European Commission contribution"
)
totalCost: Optional[float] = Field(None, description="Total cost of the project")
startDate: Optional[datetime] = Field(None, description="Start date of the project")
endDate: Optional[datetime] = Field(None, description="End date of the project")
ecSignatureDate: Optional[datetime] = Field(
None, description="Date of the European Commission signature"
)
contentUpdateDate: Optional[datetime] = Field(
None, description="Date when the project content was last updated"
)
grantDoi: Optional[str] = Field(None, description="DOI for the project grant")
humanValidated: Optional[bool] = Field(
None,
description="Indicates if the project information has been human validated",
)
keywords: Optional[Union[str, List[str]]] = Field(
None, description="Keywords associated with the project"
)
class Config:
populate_by_name = True
@@ -0,0 +1,94 @@
from datetime import date
from typing import Optional, Set
from pydantic import BaseModel, Field
class DfgProject(BaseModel):
id: str = Field(description="The ID of the DFG project")
link: str = Field(description="The link to the DFG project")
title: str = Field(description="The title of the DFG project")
description: str = Field(description="The description of the DFG project")
project_identifier: str = Field(
description="The project identifier of the DFG project"
)
funding_start_date: str = Field(
description="The funding start date of the DFG project"
)
funding_end_date: str = Field(description="The funding end date of the DFG project")
associated_persons: list[str] = Field(
description="The associated persons of the DFG project"
)
institutions: list[str] = Field(
description="The institutions associated with the DFG project"
)
@classmethod
def from_elastic_hit(cls, hit: dict):
source = hit["_source"]
associated_persons: Set[str] = set()
institutions: Set[str] = set()
# persons
if "Antragsteller" in source:
associated_persons.update(source["Antragsteller"].split(";"))
if "Antragstellerin" in source:
associated_persons.add(source["Antragstellerin"])
if "Sprecher" in source:
associated_persons.add(source["Sprecher"])
if "Sprecherin" in source:
associated_persons.add(source["Sprecherin"])
if "Leiter" in source:
associated_persons.add(source["Leiter"])
if "Leiterin" in source:
associated_persons.add(source["Leiterin"])
if "beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler" in source:
associated_persons.update(
source[
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler"
].split(";")
)
if "Beteiligte Personen" in source:
associated_persons.update(source["Beteiligte Personen"].split(";"))
if "Teilprojektleiter" in source:
associated_persons.update(source["Teilprojektleiter"].split(";"))
# institutions
if "Antragstellende Institution" in source:
institutions.add(source["Antragstellende Institution"])
if "Mitantragstellende Institution" in source:
institutions.add(source["Mitantragstellende Institution"])
if "Beteiligte Institution" in source:
institutions.add(source["Beteiligte Institution"])
if "Beteiligte Hochschule" in source:
institutions.add(source["Beteiligte Hochschule"])
return cls(
id=hit["_id"],
link=source["link"],
title=source["title"],
description=source["description"],
project_identifier=source["Projektkennzeichen"],
funding_start_date=source["funding_start"],
funding_end_date=source["funding_end"],
associated_persons=list(associated_persons),
institutions=list(institutions),
)
@@ -0,0 +1,275 @@
# coding: utf-8
"""
DFG Project Clean Model
Summary model that consolidates all scattered person and institution fields
from the raw projects_dfg_all index into clean, unified lists.
"""
from typing import Optional, List, Set
from pydantic import BaseModel, ConfigDict, Field
class DfgProjectDetails(BaseModel):
"""
Clean summary model for a DFG project, consolidating all person roles
and institution references into unified lists.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
)
id: str = Field(description="The ID of the DFG project")
link: Optional[str] = Field(default=None, description="The link to the DFG project")
title: Optional[str] = Field(
default=None, description="The title of the DFG project"
)
description: Optional[str] = Field(
default=None, description="The description of the DFG project"
)
project_identifier: Optional[str] = Field(
default=None,
description="The project identifier of the DFG project",
)
funding_start_date: Optional[str] = Field(
default=None, description="The funding start date of the DFG project"
)
funding_end_date: Optional[str] = Field(
default=None, description="The funding end date of the DFG project"
)
dfg_procedure: Optional[str] = Field(
default=None, description="The DFG procedure"
)
subject_area: Optional[str] = Field(
default=None,
description="The subject area classification",
)
funding_type: Optional[str] = Field(
default=None, description="The type of funding"
)
international_reference: Optional[str] = Field(
default=None,
description="International reference",
)
website: Optional[str] = Field(
default=None, description="The project website"
)
# Unified person list: all person names from any role
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the DFG project (any role)",
)
# Unified institution list: all institutions involved
institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the DFG project",
)
# Sub-project reference
subproject_of: Optional[str] = Field(
default=None,
description="Parent project this is a sub-project of",
)
@classmethod
def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails":
"""
Create a DfgProject from an Elasticsearch hit, consolidating all
person and institution fields into unified lists.
"""
source = hit.get("_source", {})
associated_persons: Set[str] = set()
institutions: Set[str] = set()
# --- Collect all persons from every person-related field ---
# Applicant fields
_add_persons(source, associated_persons, "Antragsteller") # semicolon-separated
_add_person(source, associated_persons, "Antragstellerin")
_add_persons(
source, associated_persons, "Antragstellerinnen"
) # semicolon-separated
_add_persons(
source, associated_persons, "Antragstellerinnen / Antragsteller"
) # semicolon-separated
# Co-applicant fields
_add_persons(source, associated_persons, "Mitantragsteller")
_add_person(source, associated_persons, "Mitantragstellerin")
_add_persons(source, associated_persons, "Mitantragstellerinnen")
_add_persons(
source, associated_persons, "Mitantragstellerinnen / Mitantragsteller"
)
# Former applicant fields
_add_persons(source, associated_persons, "Ehemalige Antragsteller")
_add_person(source, associated_persons, "Ehemalige Antragstellerin")
_add_persons(source, associated_persons, "Ehemalige Antragstellerinnen")
_add_persons(
source,
associated_persons,
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
)
_add_person(source, associated_persons, "Ehemaliger Antragsteller")
# Speaker / coordinator fields
_add_person(source, associated_persons, "Sprecher")
_add_person(source, associated_persons, "Sprecherin")
_add_persons(source, associated_persons, "Sprecherinnen")
_add_persons(source, associated_persons, "Sprecherinnen / Sprecher")
_add_person(source, associated_persons, "Co-Sprecher")
_add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher")
# IGK partner speaker fields
_add_person(source, associated_persons, "Sprecher (IGK-Partner)")
_add_person(source, associated_persons, "Sprecherin (IGK-Partner)")
_add_persons(
source,
associated_persons,
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
)
# Leader fields
_add_person(source, associated_persons, "Leiter")
_add_person(source, associated_persons, "Leiterin")
_add_persons(source, associated_persons, "Leiterinnen")
_add_persons(source, associated_persons, "Leiterinnen / Leiter")
# Sub-project leader fields
_add_persons(source, associated_persons, "Teilprojektleiter")
_add_person(source, associated_persons, "Teilprojektleiterin")
_add_persons(source, associated_persons, "Teilprojektleiterinnen")
_add_persons(
source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter"
)
# Participating scientist fields
_add_persons(source, associated_persons, "beteiligte Wissenschaftler")
_add_person(source, associated_persons, "beteiligte Wissenschaftlerin")
_add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen")
_add_persons(
source,
associated_persons,
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
)
_add_person(source, associated_persons, "beteiligter Wissenschaftler")
# Participating person fields
_add_person(source, associated_persons, "Beteiligte Person")
_add_persons(source, associated_persons, "Beteiligte Personen")
# Host fields (for guest researchers)
_add_person(source, associated_persons, "Gastgeber")
_add_person(source, associated_persons, "Gastgeberin")
_add_persons(source, associated_persons, "Gastgeberinnen")
_add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber")
# Cooperation partner fields
_add_person(source, associated_persons, "Kooperationspartner")
_add_person(source, associated_persons, "Kooperationspartnerin")
_add_persons(source, associated_persons, "Kooperationspartnerinnen")
_add_persons(
source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner"
)
# Co-responsible fields
_add_person(source, associated_persons, "Mitverantwortlich")
_add_person(source, associated_persons, "Mitverantwortlich(e)")
_add_persons(source, associated_persons, "Mitverantwortliche")
# Application partner
_add_person(source, associated_persons, "Anwendungspartner")
# Foreign co-applicant fields
_add_persons(source, associated_persons, "ausländische Mitantragsteller")
_add_person(source, associated_persons, "ausländischer Mitantragsteller")
# Person creator (from nested fields)
if "person_creater_name" in source and source["person_creater_name"]:
associated_persons.add(source["person_creater_name"].strip())
# Deputy (stellvertr) - nested object
stellvertr = source.get("stellvertr")
if stellvertr and isinstance(stellvertr, dict):
for field in ["stellvertreter", "stellvertreterin"]:
if field in stellvertr and stellvertr[field]:
associated_persons.add(stellvertr[field].strip())
# --- Collect all institutions ---
_add_institution(source, institutions, "Antragstellende Institution")
_add_institution(source, institutions, "Mitantragstellende Institution")
_add_institution(source, institutions, "Beteiligte Einrichtung")
_add_institution(source, institutions, "Beteiligte Hochschule")
_add_institution(source, institutions, "Beteiligte Institution")
_add_institution(source, institutions, "IGK-Partnerinstitution")
_add_institution(source, institutions, "Partnerorganisation")
_add_institution(source, institutions, "Unternehmen")
# Foreign institution (nested object)
auslaend = source.get("ausländ")
if auslaend and isinstance(auslaend, dict):
for field in [
"auslaendischeInstitution",
"auslaendischeInstitution2",
"auslaendischesUnternehmen",
"auslaendischesUnternehmen2",
]:
if field in auslaend and auslaend[field]:
institutions.add(auslaend[field].strip())
return cls(
id=hit["_id"],
link=source.get("link"),
title=source.get("title"),
description=source.get("description"),
project_identifier=source.get("Projektkennung"),
funding_start_date=source.get("funding_start"),
funding_end_date=source.get("funding_end"),
dfg_procedure=source.get("DFG-Verfahren"),
subject_area=source.get("Fachliche Zuordnung"),
funding_type=source.get("Förderung"),
international_reference=source.get("Internationaler Bezug"),
website=source.get("Webseite"),
associated_persons=sorted(associated_persons), # sorted for consistency
institutions=sorted(institutions),
subproject_of=source.get("Teilprojekt zu"),
)
# --- Helper functions for parsing source fields ---
def _add_person(source: dict, persons: Set[str], field: str) -> None:
"""Add a single person value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
persons.add(value)
def _add_persons(source: dict, persons: Set[str], field: str) -> None:
"""Add persons from a semicolon-separated field."""
if field in source and source[field]:
for person in source[field].split(";"):
cleaned = person.strip()
if cleaned:
persons.add(cleaned)
def _add_institution(source: dict, institutions: Set[str], field: str) -> None:
"""Add a single institution value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
institutions.add(value)
+192
View File
@@ -0,0 +1,192 @@
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
class DisplayCodeSplittedNested(BaseModel):
model_config = ConfigDict(populate_by_name=True)
single_display_code: Optional[str] = Field(
default=None,
validation_alias="singleDisplayCode",
description="A solitary segment or specific component broken out from the main display code.",
)
class CategoryNested(BaseModel):
model_config = ConfigDict(populate_by_name=True)
category: Optional[str] = Field(
default=None,
description="The descriptive classification title or taxonomy name for the project.",
)
code: Optional[str] = Field(
default=None, description="The system code representing the specific category."
)
display_code: Optional[str] = Field(
default=None,
validation_alias="displayCode",
description="The alphanumeric code formatted for user interface display purposes.",
)
# REFINED: Mapped to List[str] because the real data provides an array of strings
display_code_splitted: List[str] = Field(
default_factory=list,
validation_alias="displayCode_splitted",
description="A tokenized hierarchy breakdown of the display code represented as an array of strings.",
)
display_code_splitted_nested: List[DisplayCodeSplittedNested] = Field(
default_factory=list,
validation_alias="displayCode_splitted_nested",
description="Granular, nested breakdowns of the split parts of the display code.",
)
class KeywordNested(BaseModel):
model_config = ConfigDict(populate_by_name=True)
keyword: Optional[str] = Field(
default=None,
description="An individual standalone keyword or tag used for granular search index filtering.",
)
class OrganizationNested(BaseModel):
model_config = ConfigDict(populate_by_name=True)
ec_contribution: Optional[str] = Field(
default=None,
validation_alias="ecContribution",
description="The gross European Commission financial contribution allocated to this specific participant organization.",
)
id: Optional[str] = Field(
default=None,
description="The unique identifier or Participant Identification Code (PIC) of the organization.",
)
name: Optional[str] = Field(
default=None,
description="The full legal name of the participating organization or institution.",
)
net_ec_contribution: Optional[str] = Field(
default=None,
validation_alias="netEcContribution",
description="The net European Commission financial funding provided to the organization after adjustments.",
)
total_cost: Optional[str] = Field(
default=None,
validation_alias="totalCost",
description="The overall individual budget or total cost declared by this organization for its share of work.",
)
organization_type: Optional[str] = Field(
default=None,
validation_alias="type",
description="The legal entity type or role of the organization (e.g., coordinator, participant).",
)
class ProgrammeNested(BaseModel):
model_config = ConfigDict(populate_by_name=True)
code: Optional[str] = Field(
default=None,
description="The structural code identifying the framework or specific funding sub-programme.",
)
id: Optional[str] = Field(
default=None,
description="The unique identifier of the funding program within the registry.",
)
programme: Optional[str] = Field(
default=None,
description="The official title or description of the EU funding program.",
)
class EuProject(BaseModel):
model_config = ConfigDict(populate_by_name=True)
acronym: Optional[str] = Field(
default=None,
description="The official, short acronym chosen to identify the EU project.",
)
categories_nested: List[CategoryNested] = Field(
default_factory=list,
description="Structured lists of classification categories and taxonomy mappings assigned to the project.",
)
doc_number: Optional[str] = Field(
default=None,
description="The internal administrative document control number or record tracking identifier.",
)
doi: Optional[str] = Field(
default=None,
description="The Digital Object Identifier (DOI) linked to the project's official metadata or primary publication.",
)
ec_max_contribution: Optional[str] = Field(
default=None,
validation_alias="ecMaxContribution",
description="The maximum authorized limit for the European Commission's financial grant contribution to the project.",
)
end_date: Optional[str] = Field(
default=None,
validation_alias="endDate",
description="The calendar date marking the official structural conclusion of the project execution timeline.",
)
funding_end: Optional[str] = Field(
default=None,
description="The exact calendar termination year for the project's financial eligibility period.",
)
funding_start: Optional[str] = Field(
default=None,
description="The exact calendar activation year from which project expenses can be billed against the grant.",
)
id: Optional[str] = Field(
default=None,
description="The unique global record ID for the project document (typically the Grant Agreement Number).",
)
keywords: Optional[str] = Field(
default=None,
description="A general text string or comma-separated list of keywords applied to the project record.",
)
keywords_nested: List[KeywordNested] = Field(
default_factory=list,
description="Strictly tokenized and isolated keywords nested for targeted search engine aggregations.",
)
link: Optional[str] = Field(
default=None,
description="The web URL linking directly to the project's public profile page on CORDIS or an equivalent registry.",
)
objective: Optional[str] = Field(
default=None,
description="The complete, detailed abstract outlining the goals, methodology, and expected impact of the project.",
)
organization_nested: List[OrganizationNested] = Field(
default_factory=list,
description="The full roster of academic, public, or private organizations participating in the project consortium.",
)
programme_nested: List[ProgrammeNested] = Field(
default_factory=list,
description="The nested historical line of EU funding frameworks and structural grants supporting this project.",
)
source: Optional[str] = Field(
default=None,
description="The specific upstream system or database repository from which this document was fetched or synced.",
)
start_date: Optional[str] = Field(
default=None,
validation_alias="startDate",
description="The official calendar date marking the active kickoff and formal initiation of the project.",
)
status: Optional[str] = Field(
default=None,
description="The lifecycle phase of the project (e.g., 'CLOSED', 'ONGOING').",
)
teaser: Optional[str] = Field(
default=None,
description="A brief, high-level summary or editorial sentence written for general public consumption.",
)
title: Optional[str] = Field(
default=None,
description="The comprehensive, full legal title describing the scope of the project.",
)
total_cost: Optional[str] = Field(
default=None,
validation_alias="totalCost",
description="The combined sum total budget estimated for the implementation of the entire project.",
)
@@ -0,0 +1,132 @@
# coding: utf-8
"""
Aktuell Index Backend Models
Pydantic models for the Elasticsearch \"aktuell\" index.
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.news_aktuell.link_item import LinkItem
from inse.models.news_aktuell.tag_item import TagItem
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class Aktuell(BaseModel):
"""
Main document model for the aktuell index.
""" # noqa: E501
author: Optional[StrictStr] = None
var_date: Optional[StrictStr] = Field(default=None, alias="date")
date_full: Optional[StrictInt] = None
date_year: Optional[StrictInt] = None
full_content: Optional[StrictStr] = None
further_content: Optional[StrictStr] = None
intro_content: Optional[StrictStr] = None
links_nested: Optional[List[LinkItem]] = None
main_content: Optional[StrictStr] = None
maintitle: Optional[StrictStr] = None
redaktion: Optional[StrictStr] = None
subtitle: Optional[StrictStr] = None
tags: Optional[StrictStr] = None
tags_nested: Optional[List[TagItem]] = None
url: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["author", "date", "date_full", "date_year", "full_content", "further_content", "intro_content", "links_nested", "main_content", "maintitle", "redaktion", "subtitle", "tags", "tags_nested", "url"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of Aktuell from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of each item in links_nested (list)
_items = []
if self.links_nested:
for _item_links_nested in self.links_nested:
if _item_links_nested:
_items.append(_item_links_nested.to_dict())
_dict['links_nested'] = _items
# override the default output from pydantic by calling `to_dict()` of each item in tags_nested (list)
_items = []
if self.tags_nested:
for _item_tags_nested in self.tags_nested:
if _item_tags_nested:
_items.append(_item_tags_nested.to_dict())
_dict['tags_nested'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of Aktuell from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"author": obj.get("author"),
"date": obj.get("date"),
"date_full": obj.get("date_full"),
"date_year": obj.get("date_year"),
"full_content": obj.get("full_content"),
"further_content": obj.get("further_content"),
"intro_content": obj.get("intro_content"),
"links_nested": [LinkItem.from_dict(_item) for _item in obj["links_nested"]] if obj.get("links_nested") is not None else None,
"main_content": obj.get("main_content"),
"maintitle": obj.get("maintitle"),
"redaktion": obj.get("redaktion"),
"subtitle": obj.get("subtitle"),
"tags": obj.get("tags"),
"tags_nested": [TagItem.from_dict(_item) for _item in obj["tags_nested"]] if obj.get("tags_nested") is not None else None,
"url": obj.get("url")
})
return _obj
@@ -0,0 +1,90 @@
# coding: utf-8
"""
Aktuell Index Backend Models
Pydantic models for the Elasticsearch \"aktuell\" index.
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class LinkItem(BaseModel):
"""
Nested link object within the Aktuell document.
""" # noqa: E501
text: Optional[StrictStr] = None
url: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["text", "url"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of LinkItem from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of LinkItem from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"text": obj.get("text"),
"url": obj.get("url")
})
return _obj
@@ -0,0 +1,88 @@
# coding: utf-8
"""
Aktuell Index Backend Models
Pydantic models for the Elasticsearch \"aktuell\" index.
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
class TagItem(BaseModel):
"""
Nested tag object within the Aktuell document.
""" # noqa: E501
tag: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["tag"]
model_config = ConfigDict(
validate_by_name=True,
validate_by_alias=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
return json.dumps(to_jsonable_python(self.to_dict()))
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of TagItem from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of TagItem from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"tag": obj.get("tag")
})
return _obj
@@ -0,0 +1,128 @@
# coding: utf-8
# flake8: noqa
"""
OpenAlex API
The OpenAlex API provides access to a comprehensive catalog of scholarly works, authors, sources, institutions, topics, keywords, publishers, and funders. OpenAlex indexes over 250 million scholarly works.
The version of the OpenAPI document: 1.0.0
Contact: support@openalex.org
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
# import models into model package
from inse.models.openalex.author import Author
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.author_ids import AuthorIds
from inse.models.openalex.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
from inse.models.openalex.author_topics_inner import AuthorTopicsInner
from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse.models.openalex.authorship import Authorship
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.openalex.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.openalex.award import Award
from inse.models.openalex.award_full import AwardFull
from inse.models.openalex.award_full_funder import AwardFullFunder
from inse.models.openalex.awards_list_response import AwardsListResponse
from inse.models.openalex.concept import Concept
from inse.models.openalex.concept_ids import ConceptIds
from inse.models.openalex.concepts_list_response import ConceptsListResponse
from inse.models.openalex.continent import Continent
from inse.models.openalex.continent_ids import ContinentIds
from inse.models.openalex.continents_list_response import ContinentsListResponse
from inse.models.openalex.countries_list_response import CountriesListResponse
from inse.models.openalex.country import Country
from inse.models.openalex.country_continent import CountryContinent
from inse.models.openalex.country_ids import CountryIds
from inse.models.openalex.dehydrated_author import DehydratedAuthor
from inse.models.openalex.dehydrated_funder import DehydratedFunder
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.dehydrated_source import DehydratedSource
from inse.models.openalex.domain import Domain
from inse.models.openalex.domain_fields_inner import DomainFieldsInner
from inse.models.openalex.domain_ids import DomainIds
from inse.models.openalex.domains_list_response import DomainsListResponse
from inse.models.openalex.error import Error
from inse.models.openalex.fields_list_response import FieldsListResponse
from inse.models.openalex.funder import Funder
from inse.models.openalex.funder_ids import FunderIds
from inse.models.openalex.funders_list_response import FundersListResponse
from inse.models.openalex.get_changefile200_response import GetChangefile200Response
from inse.models.openalex.get_changefile200_response_meta import GetChangefile200ResponseMeta
from inse.models.openalex.get_changefile200_response_results_inner import GetChangefile200ResponseResultsInner
from inse.models.openalex.get_changefile200_response_results_inner_formats import GetChangefile200ResponseResultsInnerFormats
from inse.models.openalex.get_changefile200_response_results_inner_formats_jsonl import GetChangefile200ResponseResultsInnerFormatsJsonl
from inse.models.openalex.get_changefile200_response_results_inner_formats_parquet import GetChangefile200ResponseResultsInnerFormatsParquet
from inse.models.openalex.group_by_result import GroupByResult
from inse.models.openalex.institution import Institution
from inse.models.openalex.institution_geo import InstitutionGeo
from inse.models.openalex.institution_ids import InstitutionIds
from inse.models.openalex.institution_type import InstitutionType
from inse.models.openalex.institution_types_list_response import InstitutionTypesListResponse
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.models.openalex.keyword import Keyword
from inse.models.openalex.keywords_list_response import KeywordsListResponse
from inse.models.openalex.language import Language
from inse.models.openalex.languages_list_response import LanguagesListResponse
from inse.models.openalex.license import License
from inse.models.openalex.licenses_list_response import LicensesListResponse
from inse.models.openalex.list_changefiles200_response import ListChangefiles200Response
from inse.models.openalex.list_changefiles200_response_meta import ListChangefiles200ResponseMeta
from inse.models.openalex.list_changefiles200_response_results_inner import ListChangefiles200ResponseResultsInner
from inse.models.openalex.location import Location
from inse.models.openalex.meta import Meta
from inse.models.openalex.model_field import ModelField
from inse.models.openalex.open_access import OpenAccess
from inse.models.openalex.publisher import Publisher
from inse.models.openalex.publisher_ids import PublisherIds
from inse.models.openalex.publisher_parent_publisher import PublisherParentPublisher
from inse.models.openalex.publishers_list_response import PublishersListResponse
from inse.models.openalex.rate_limit_response import RateLimitResponse
from inse.models.openalex.rate_limit_response_rate_limit import RateLimitResponseRateLimit
from inse.models.openalex.rate_limit_response_rate_limit_endpoint_costs_usd import RateLimitResponseRateLimitEndpointCostsUsd
from inse.models.openalex.sdg import Sdg
from inse.models.openalex.sdg_ids import SdgIds
from inse.models.openalex.sdgs_list_response import SdgsListResponse
from inse.models.openalex.source import Source
from inse.models.openalex.source_ids import SourceIds
from inse.models.openalex.source_type import SourceType
from inse.models.openalex.source_types_list_response import SourceTypesListResponse
from inse.models.openalex.sources_list_response import SourcesListResponse
from inse.models.openalex.subfield import Subfield
from inse.models.openalex.subfield_domain import SubfieldDomain
from inse.models.openalex.subfield_field import SubfieldField
from inse.models.openalex.subfields_list_response import SubfieldsListResponse
from inse.models.openalex.text_classification_response import TextClassificationResponse
from inse.models.openalex.text_classification_response_meta import TextClassificationResponseMeta
from inse.models.openalex.topic import Topic
from inse.models.openalex.topic_domain import TopicDomain
from inse.models.openalex.topic_field import TopicField
from inse.models.openalex.topic_ids import TopicIds
from inse.models.openalex.topic_subfield import TopicSubfield
from inse.models.openalex.topics_list_response import TopicsListResponse
from inse.models.openalex.work import Work
from inse.models.openalex.work_biblio import WorkBiblio
from inse.models.openalex.work_citation_normalized_percentile import WorkCitationNormalizedPercentile
from inse.models.openalex.work_cited_by_percentile_year import WorkCitedByPercentileYear
from inse.models.openalex.work_counts_by_year_inner import WorkCountsByYearInner
from inse.models.openalex.work_has_content import WorkHasContent
from inse.models.openalex.work_ids import WorkIds
from inse.models.openalex.work_keyword import WorkKeyword
from inse.models.openalex.work_mesh_inner import WorkMeshInner
from inse.models.openalex.work_sustainable_development_goals_inner import WorkSustainableDevelopmentGoalsInner
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.models.openalex.work_type import WorkType
from inse.models.openalex.work_types_list_response import WorkTypesListResponse
from inse.models.openalex.works_list_response import WorksListResponse
from inse.models.openalex.work_page import WorkPage
from inse.models.openalex.lsf_person import LsfPerson
@@ -21,13 +21,13 @@ import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.author_ids import AuthorIds
from inse.models.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.author_summary_stats import AuthorSummaryStats
from inse.models.work_topic import WorkTopic
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.author_ids import AuthorIds
from inse.models.openalex.author_parsed_longest_name import AuthorParsedLongestName
from inse.models.openalex.author_summary_stats import AuthorSummaryStats
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -19,7 +19,7 @@ import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,9 +20,9 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.author import Author
from inse.models.group_by_result import GroupByResult
from inse.models.meta import Meta
from inse.models.openalex.author import Author
from inse.models.openalex.group_by_result import GroupByResult
from inse.models.openalex.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.dehydrated_author import DehydratedAuthor
from inse.models.dehydrated_institution import DehydratedInstitution
from inse.models.openalex.dehydrated_author import DehydratedAuthor
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.openalex.autocomplete_response_results_inner import AutocompleteResponseResultsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -21,7 +21,7 @@ import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from inse.models.award_full_funder import AwardFullFunder
from inse.models.openalex.award_full_funder import AwardFullFunder
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.award_full import AwardFull
from inse.models.meta import Meta
from inse.models.openalex.award_full import AwardFull
from inse.models.openalex.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -21,7 +21,7 @@ import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.concept_ids import ConceptIds
from inse.models.openalex.concept_ids import ConceptIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.concept import Concept
from inse.models.meta import Meta
from inse.models.openalex.concept import Concept
from inse.models.openalex.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -21,8 +21,8 @@ import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.continent_ids import ContinentIds
from inse.models.domain_fields_inner import DomainFieldsInner
from inse.models.openalex.continent_ids import ContinentIds
from inse.models.openalex.domain_fields_inner import DomainFieldsInner
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.continent import Continent
from inse.models.meta import Meta
from inse.models.openalex.continent import Continent
from inse.models.openalex.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -20,8 +20,8 @@ import json
from pydantic import BaseModel, ConfigDict
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.country import Country
from inse.models.meta import Meta
from inse.models.openalex.country import Country
from inse.models.openalex.meta import Meta
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
@@ -21,8 +21,8 @@ import json
from datetime import date, datetime
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from inse.models.country_continent import CountryContinent
from inse.models.country_ids import CountryIds
from inse.models.openalex.country_continent import CountryContinent
from inse.models.openalex.country_ids import CountryIds
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python

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