Compare commits

..
Author SHA1 Message Date
Kazgatari 641f40ff45 fixed merge conflict
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-01 21:49:00 +02:00
Kazgatari 6f0d17a991 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual 2026-08-01 21:48:12 +02:00
Kazgatari 2d1155d46b Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual 2026-08-01 21:43:25 +02:00
khalti a1cf6e06af Merge pull request 'fix(person-funding): icon-only publication link + return to Förderungen' (#257) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #257
2026-08-01 21:35:49 +02:00
khalti 2e4a861e9c fix(person-funding): icon-only publication link + return to Förderungen
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-08-01 21:29:05 +02:00
Kazgatari 70e4ad71a6 adapted network graph to dark mode & added padding to trend pie chart
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-01 21:23:52 +02:00
Kazgatari dc27b49f63 changed style value for input fields. Avoids propblem of standard html color when no input is provided (e.g. Input field placeholder vanishes after clicking out, when clicking back inside, the color is static black) 2026-08-01 21:08:00 +02:00
khalti b8707c7619 Merge pull request 'refactor(person-funding, person-patents, institution-patents): match publication-table styling and pagination' (#256) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #256
2026-08-01 20:48:02 +02:00
Kazgatari b251abb79f adapted topic chip v2 (why do we have 2?) to be more intense in color and change the text in dark mode 2026-08-01 20:44:15 +02:00
khalti 14be6c1a6c refactor(person-funding, person-patents, institution-patents): match publication-table styling and pagination
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-01 20:40:02 +02:00
Kazgatari 7addfe2a71 added overide for angular material tooltip (did not work natively with dark mode) 2026-08-01 20:35:58 +02:00
Kazgatari 2474700473 refactored from legacy host binding to use modern @component (host: ) implementation 2026-08-01 20:35:21 +02:00
Kazgatari 0150f81a24 !!! Implemented big style changes to overall style.css for scroll bars and navigation tabs!!! + minor style changes for the author compare components to adapt in darkmode. 2026-08-01 20:14:29 +02:00
Kazgatari 8a801d0bb5 implement dynamic color changes for e-chart (test) 2026-08-01 19:31:47 +02:00
Kazgatari 496d2c88f0 more hardcoded changes 2026-08-01 19:31:23 +02:00
Kazgatari 9d8b287c13 reverted some color values because EChart breaks 2026-08-01 19:09:08 +02:00
Kazgatari 94e0cad2d0 revert soft colors 2026-08-01 18:20:47 +02:00
Kazgatari 8be123bf3a changed hardcoded values to theme 2026-08-01 18:00:21 +02:00
Kazgatari 570da1b47c changed more static hex colors to dynamic themed ones 2026-08-01 15:42:23 +02:00
Kazgatari 02dd286d55 replaced other hard coded values with theme 2026-08-01 15:28:50 +02:00
Kazgatari 58199760de smaller theme adaptions like shadows 2026-08-01 15:22:20 +02:00
Kazgatari 17b59213d3 changed static color to use dynamic theme 2026-08-01 15:12:59 +02:00
Kazgatari 06e2785914 changed static color to use dynamic theme 2026-08-01 15:12:48 +02:00
Kazgatari 0aea390e5e changed static color to use dynamic theme 2026-08-01 15:12:18 +02:00
Kazgatari c33a900c66 changed static color to use dynamic theme 2026-08-01 15:11:56 +02:00
Kazgatari f36e9a7d54 changed static color to use dynamic theme 2026-08-01 15:11:36 +02:00
Kazgatari 7259e3a0c0 changed static color to use dynamic theme 2026-08-01 15:11:04 +02:00
Kazgatari b0581ad452 changed static color to use dynamic theme 2026-08-01 15:10:41 +02:00
Kazgatari 813953f1f5 changed static colors to use new theme 2026-08-01 15:09:55 +02:00
Kazgatari 288b21d407 added proper color theme and services to inject based on system, dark, light mode 2026-08-01 15:08:30 +02:00
kuzko 01453f73dc Merge pull request 'refactor/trend_visual' (#255) from refactor/trend_visual into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #255
2026-08-01 13:05:15 +02:00
Kazgatari 410f1ade01 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-01 12:53:55 +02:00
Kazgatari 621a9dd2a1 fix: moved huggingface offline mode settings to base image, to prevent first call to fetch updates from huggingface
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-01 12:30:18 +02:00
genja 18b9b8bf67 Merge pull request 'feature/keywords-analysis: updated project tables, added authors to eu projects page, updated project funding retrieval' (#254) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #254
2026-08-01 02:17:46 +02:00
genja 3f1ea0a418 updated project funding resolvers to apply filters
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-01 01:58:19 +02:00
genja 211f7b82dc optimized funding data retrieval + added filters 2026-08-01 01:57:42 +02:00
genja 6675976feb Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-08-01 01:09:32 +02:00
Kazgatari 034d3ee453 style changes and removed last logs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-31 16:56:32 +02:00
Kazgatari faa866f4e1 added exception handling 2026-07-31 16:04:14 +02:00
Kazgatari 9c3e36930c changed caching to Parameter Keyed caching. Rest is handled by resolver and e-tags
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-31 14:24:20 +02:00
Kazgatari d4daecd921 fix fuzzy / keyword names on chips 2026-07-31 14:08:24 +02:00
Kazgatari 9f10e9e7af fixed resolver issues, where fuzzy search would not display anything 2026-07-31 13:55:02 +02:00
Kazgatari fa9def349c fuzzy search does not work 2026-07-31 13:22:29 +02:00
tischer 4073214131 Merge pull request 'enforce_llm_response_schema' (#253) from enforce_llm_response_schema into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #253
2026-07-30 21:26:07 +02:00
Steven Tischer 03fac2a656 add LLM response schema to keyword extraction
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-30 21:15:37 +02:00
Steven Tischer a204584ddd implement LLM response schema validation for author bio generation 2026-07-30 21:04:09 +02:00
genja 25de01c7be regenerated models and services
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-30 01:30:44 +02:00
genja 176235689f removed unused imports 2026-07-30 01:30:30 +02:00
genja f27ee8b295 updated resolvers for projects fetching for institutions 2026-07-30 01:30:14 +02:00
genja 32616fe6aa old chips replaced for oa_topics and oa_authors 2026-07-30 01:24:30 +02:00
genja 9a5cb9e9b0 added oa_authors to eu cordis details page 2026-07-30 01:23:31 +02:00
genja d11869c70b inserted generic project tables to institute component 2026-07-30 01:22:56 +02:00
genja abb8c9dbb5 fxied bug with too many author results 2026-07-30 01:21:53 +02:00
genja b8442213f8 splitted logic for ROOT and underlying institute results into 2 separated entities 2026-07-30 01:21:40 +02:00
genja 0d19abb293 added corresponding oa_authors to each EU publication response 2026-07-30 01:19:57 +02:00
khalti 6ea3e79087 Merge pull request 'refactor(person-funding): reuse shared publication-detail page for 'Mehr Infos' instead of duplicated inline panel' (#252) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #252
2026-07-28 15:39:48 +02:00
khalti ba72b146a2 fix: resolve merge conflict with dev in person-funding.component.ts
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 15:35:09 +02:00
farajollahi 0f360c86b2 Merge pull request 'eu-top-authors' (#251) from eu-top-authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #251
2026-07-28 12:21:22 +02:00
farajollahi ecf7a6f905 Merge branch 'dev' into eu-top-authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-28 12:09:16 +02:00
farajollahi 7b912196e9 Merge pull request 'implement keyword select and dfg status diagramm' (#250) from dfg-status-dashboard into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #250
2026-07-28 11:06:24 +02:00
farajollahi 6e4742206f Merge branch 'dev' into dfg-status-dashboard
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:45:41 +02:00
farajollahi a28ecc9d02 implement keyword select and dfg status diagramm
LocationBasedServices/smartguide/pipeline/head Build started...
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-28 10:43:42 +02:00
genja 53397f844e Merge pull request 'feature/keywords-analysis' (#249) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #249
2026-07-28 10:09:56 +02:00
genja 818398ccda Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:08:48 +02:00
spsaefan a6c7068ca6 Merge branch 'global-time-filter' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
# Please enter a commit message to explain why this merge is necessary,
:wq
2026-07-28 09:31:03 +02:00
genja 4785bb4d40 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:19:31 +02:00
genja 1a9f9496fd date formatting for BUND details page fixed 2026-07-28 09:18:56 +02:00
genja 78f35daa58 fixed pagination options for project tables 2026-07-28 09:17:51 +02:00
Kazgatari b2e70c2bb3 fix: institution visisbility button & refactor ID type (full OpenAlex link vs ID) into parent component
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:11:40 +02:00
genja 3d8ceeb5b6 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 00:40:19 +02:00
genja 0b8540d70b regenerated services and models 2026-07-28 00:35:34 +02:00
genja e9ccfe6796 added BUND institutions resolver, BUND projects desolver adjusted for the new logic 2026-07-28 00:35:20 +02:00
genja e20f2732b3 minor UI fixes 2026-07-28 00:34:35 +02:00
genja 4da4ea1bff moved BUND projects out from person component to keywords search 2026-07-28 00:32:21 +02:00
genja 93ba39f9b0 fixed filters for BUND projects 2026-07-28 00:31:51 +02:00
genja 0642a3704d added new func for retrievingbund project by topic_ids 2026-07-28 00:31:30 +02:00
genja 57e1bafa8b added BUND institutions endpoint with autocomplete 2026-07-28 00:30:20 +02:00
genja 3d5eb524aa added Institutions filter and funding-type filter for BUND 2026-07-28 00:24:52 +02:00
genja c15afed0aa added funding type selector for BUND projects 2026-07-28 00:18:24 +02:00
genja b133ce80c9 added BUND institutions selector 2026-07-28 00:17:36 +02:00
Roman ae8332dc3d (dashboard) fix pytest
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 23:10:01 +02:00
Roman 026a35dd90 (work-classifications): show orientation scores for limited publication samples
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:58:55 +02:00
Roman 5fdc1cdce3 refactor(dashboard): use shared active institution membership query for person count
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:40:35 +02:00
Roman 02bb8b8fb8 (work-classifications): add research profiles to author comparison (ranking) 2026-07-27 21:23:53 +02:00
khalti 27f289f4a0 refactor(person-funding): reuse shared publication-detail page for 'Mehr Infos' instead of duplicated inline panel
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-27 21:22:49 +02:00
spsaefan 6af1747477 Add time filter UI
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 11:57:36 +02:00
spsaefan 401b82c226 Add global dashboard period state 2026-07-27 11:57:04 +02:00
spsaefan 9d128e18b6 Pass dashboard period to API 2026-07-27 11:56:45 +02:00
spsaefan a6a78bb556 Add time filter tests 2026-07-27 11:56:19 +02:00
spsaefan bc59c3f563 Support patent year filtering 2026-07-27 11:55:49 +02:00
spsaefan 8b7ac08192 Add dashboard time range filtering 2026-07-27 11:52:55 +02:00
Kazgatari 4fe78c2b88 made pie chart bigger and seperated header to properly resize
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 09:22:16 +02:00
genja 2e8dd00aa6 Merge pull request 'feature/keywords-analysis' (#247) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #247
2026-07-26 22:49:24 +02:00
genja 127eed5c49 regenerated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-26 22:41:38 +02:00
genja 7a84fc2b12 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-26 22:39:48 +02:00
genja 96e0925054 dfg tests adjusted 2026-07-26 22:36:36 +02:00
genja 730ee7f89a applied the new OpenAlex topics component for EU detail page 2026-07-26 21:55:48 +02:00
genja e62d1ca458 new ui component for displaying OpenAlex topics on project pages 2026-07-26 21:55:02 +02:00
genja 6bca5643ee added openalex topics and authors to EU details project page 2026-07-26 21:54:25 +02:00
genja db20b23ff3 reworked the dfg detail page for the new DFG data 2026-07-26 21:53:21 +02:00
genja 66f34668a9 added openalex topics to dfg detail page 2026-07-26 21:52:53 +02:00
genja ceadc26741 added openalex topics to bund detail page 2026-07-26 21:51:23 +02:00
genja 3a74dc9b7b created new DfgProjectsDetails model from the new DFG data models 2026-07-26 18:38:32 +02:00
genja 4a47d752cb removed unused components from uni-trend-parent component 2026-07-26 18:31:43 +02:00
Mats Paul Tončik 1bca6648bd Merge branch 'dev' into chips-and-tooltips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 15:03:47 +02:00
Mats Paul Tončik af00bc4635 feat(publication-search): added publication card search and respective card
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 14:49:23 +02:00
Mats Paul Tončik def210b4b9 feat(topic): added topic detail page with publication table
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 13:15:29 +02:00
tischer 89bdab0a26 Merge pull request 'refactor/es_integration' (#246) from refactor/es_integration into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #246
2026-07-26 13:09:47 +02:00
Steven Tischer 448922d907 enable logging of Elasticsearch request timings
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-26 12:58:38 +02:00
Mats Paul Tončik 3ef8c28191 feat: added topics card search; dedicated chips, cards, and tooltips for authors, institutions, and topics
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 12:11:02 +02:00
genja 46aee46ea3 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 10:59:40 +02:00
Steven Tischer e57875d2a5 add logging for Elasticsearch request timings 2026-07-26 09:48:35 +02:00
Steven Tischer 28726cf4c7 add env value to enable logging of outgoing Elasticsearch queries 2026-07-26 09:43:39 +02:00
Steven Tischer b0e4ad639e centralize HTTP request handling 2026-07-26 09:34:02 +02:00
Steven Tischer 1810918e43 move headers to function 2026-07-26 09:22:50 +02:00
Mats Paul Tončik a736539851 feat(chips-and-tooltips): started adding reusable chips and tooltips
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 02:14:13 +02:00
erfanian 591233e255 Merge pull request 'Add DFG top authors to dashboard' (#245) from dfg-top-authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #245
2026-07-26 00:12:24 +02:00
spsaefan c2a2a31fb9 Merge dev into dfg PG authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-25 23:53:49 +02:00
Kazgatari d4a4bfa2c7 added optional parameters to topic chip to get the correct hue for hsl conversion (required by ECharts). Changed components to adapt the new color
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-25 23:26:08 +02:00
kuzko 3a127450e3 Merge pull request 'feature/Keyword_search_rework' (#244) from feature/Keyword_search_rework into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #244
2026-07-25 22:10:39 +02:00
Kazgatari c2f9a6381a Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/Keyword_search_rework
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-25 21:57:35 +02:00
Kazgatari 7adf12912f added resolver preloading and child component state management. (If something breaks in behavior, revert to this point) 2026-07-25 21:50:02 +02:00
Mats Paul Tončik 0b2b05ae85 fix(frontend/person): made tab labels and descriptions uniform
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-25 20:22:59 +02:00
Kazgatari 127c32dce7 patched missmatch inside news (openalex id vs name) 2026-07-25 20:05:00 +02:00
Kazgatari 652ff8db15 changed news trend search to use new index & added test for top 20 news search 2026-07-25 18:39:08 +02:00
genja 3a78519655 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 16:36:54 +02:00
genja c6de85d4a0 cache time increased up to 10 minutes 2026-07-24 16:35:26 +02:00
spsaefan f25c5cd222 Link DFG top authors to person pages
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 11:32:14 +02:00
spsaefan 0b5c6bed37 Use DFG person IDs for project 2026-07-24 11:31:55 +02:00
spsaefan 2d485263d1 Improve DFG top author OpenAlex matching 2026-07-24 11:31:25 +02:00
spsaefan 3d78ec900e Fix DFG top authors aggregation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-23 01:06:44 +02:00
spsaefan fc134dad8e Update DFG project test
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-22 23:46:23 +02:00
spsaefan 59a1f765d0 Add DFG projects
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-22 23:14:05 +02:00
farajollahi 0dd2023224 Restrict EU top authors to user institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-21 09:41:27 +02:00
farajollahi d4880b417b Align dashboard EU authors with person details 2026-07-21 09:33:18 +02:00
farajollahi a7ced052dd Verify EU author counts by unique project 2026-07-21 09:20:07 +02:00
farajollahi 9ac618ebec Revert "Align EU project author counts with person details"
This reverts commit 167913aa85.
2026-07-21 01:05:55 +02:00
farajollahi de6339586f Remove DFG top authors from dashboard 2026-07-21 00:59:34 +02:00
farajollahi 97c9e2eec3 Merge branch 'dev' into eu-top-authors
# Conflicts:
#	service/src/main/inse/dashboard/service.py
#	service/src/main/inse/dashboard/test_service.py
#	webapp/src/app/api/model/topAuthorStatistics.ts
2026-07-21 00:51:45 +02:00
farajollahi 167913aa85 Align EU project author counts with person details 2026-07-21 00:48:28 +02:00
farajollahi 18c9785325 change index
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-20 23:59:08 +02:00
farajollahi f4e0888ce2 fix organsaition id
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-20 22:50:31 +02:00
spsaefan d3266ee50e Use EU project index for top authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-20 20:37:40 +02:00
spsaefan 410bcdec4b Use OpenAlex IDs for EU authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 13:32:59 +02:00
330 changed files with 18933 additions and 160739 deletions
+10 -1
View File
@@ -6,5 +6,14 @@ RUN mkdir /test && \
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"
ARG MODEL_NAME=intfloat/multilingual-e5-base
ENV MODEL_NAME=${MODEL_NAME}
ENV SENTENCE_TRANSFORMERS_HOME=/models
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
ENV HF_HOME=/models
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
ENV HF_HUB_OFFLINE=1
ENV TRANSFORMERS_OFFLINE=1
ENV HF_DATASETS_OFFLINE=1
+22 -3
View File
@@ -6,9 +6,28 @@ so it is available for local runs or testing.
Usage (run once from project root):
python service/sentence_transformer/download_model.py
"""
import os
import sys
from pathlib import Path
# Ensure service/src/main is in sys.path
current_dir = Path(__file__).parent.resolve()
src_main_dir = current_dir.parent / "src" / "main"
if str(src_main_dir) not in sys.path:
sys.path.insert(0, str(src_main_dir))
from inse.config import settings
from sentence_transformers import SentenceTransformer
MODEL_NAME = "intfloat/multilingual-e5-base"
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
MODEL_NAME = settings.sentence_transformers_model_name
print(f"Downloading '{MODEL_NAME}' to cache directory...")
model = SentenceTransformer(MODEL_NAME)
print("Done.")
print(f"Verifying offline model loading for '{MODEL_NAME}'...")
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True)
print("Done. Model downloaded and verified for 100% offline usage.")
+2 -1
View File
@@ -169,8 +169,9 @@ def main():
print("No topics found. Exiting.")
return
from inse.util import get_model
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
model = SentenceTransformer(MODEL_NAME)
model = get_model()
# 1. Gather all texts to embed
keywords_by_topic = []
+5
View File
@@ -12,6 +12,11 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
# Debugging: Log every outgoing Elasticsearch query (index + payload)
PRINT_ES_QUERIES=false
# Debugging: Log the duration of every Elasticsearch request
PRINT_ES_TIMINGS=true
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
@@ -9,6 +9,7 @@ from inse.authors.v2.model import (
StartCollaborationGraphResponse,
)
from inse.database import SessionDep
from inse.models.openalex.author import Author
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
@@ -18,6 +19,22 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2])
@router.get(
"/{raw_oa_author_id}",
operation_id="getAuthorById",
summary="Returns an author for a given author ID.",
)
async def get_author_by_id(
raw_oa_author_id: Annotated[
str,
Path(description="The ID of the author to retrieve."),
],
) -> Author:
return await authors_service.get_author_by_id_strict_or_raise(
raw_oa_author_id=raw_oa_author_id
)
@router.get(
"/authors/id",
operation_id="getAuthorsByIds",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+26 -5
View File
@@ -18,6 +18,7 @@ from inse.authors.v2.model import (
StartCollaborationGraphResponse,
WorkNode,
)
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.models.openalex.author import Author
@@ -68,21 +69,41 @@ async def search_authors(
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
async def get_author_by_id(author_id: str) -> Author | None:
async def get_author_by_id(raw_oa_author_id: str) -> Author | None:
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
Args:
author_id (str): The ID of the author to retrieve.
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
Returns:
Optional[Author]: The retrieved author, or None if not found.
"""
response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id)
response = await elasticsearch.get(
index=ESIndex.OPENALEX_AUTHORS, doc_id=raw_oa_author_id
)
if not response.get("found"):
return None
return Author.from_dict(response.get("_source", {})) # type: ignore
async def get_author_by_id_strict_or_raise(raw_oa_author_id: str) -> Author:
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
Args:
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
Returns:
Author: The retrieved author.
Raises:
ValueError: If the author is not found.
"""
author = await get_author_by_id(raw_oa_author_id=raw_oa_author_id)
if not author:
raise NotFoundException(f"Author with ID {raw_oa_author_id} not found.")
return author
async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
"""Autocompletes authors based on a search term for use in a selector component.
@@ -121,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
return await search_authors(
page=0,
size=len(author_ids),
size=len(author_ids) if len(author_ids) <10000 else 10000,
query={"terms": {"id": author_ids}},
source=[
"id",
@@ -367,7 +388,7 @@ async def _build_collaboration_graph(
f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}"
)
work_page: WorkPageV2 = await works_service.search_works(
work_page: WorkPageV2 = await works_service._search_works(
query=query,
source=COLLABORATION_GRAPH_SOURCE_FIELDS,
page=0,
+2
View File
@@ -69,6 +69,8 @@ class Settings(BaseSettings):
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
print_es_queries: bool = False
print_es_timings: bool = False
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
+9
View File
@@ -34,6 +34,14 @@ class BmbfProjectStatusStatistics(BaseModel):
completed: int
class DfgProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectTopic(BaseModel):
id: str
name: str
@@ -60,6 +68,7 @@ class TopAuthor(BaseModel):
class TopAuthorStatistics(BaseModel):
institution_id: str
works: list[TopAuthor]
projects: list[TopAuthor]
eu_projects: list[TopAuthor]
patents: list[TopAuthor]
news: list[TopAuthor]
+58
View File
@@ -12,6 +12,7 @@ from .model import (
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
@@ -22,6 +23,7 @@ from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses,
@@ -60,6 +62,8 @@ async def dashboard_statistics(
response_model=DashboardStatisticValue,
)
async def dashboard_publications(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -67,6 +71,8 @@ async def dashboard_publications(
return await get_dashboard_publications(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -92,6 +98,8 @@ async def dashboard_persons(
response_model=DashboardStatisticValue,
)
async def dashboard_patents(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -99,6 +107,8 @@ async def dashboard_patents(
return await get_dashboard_patents(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -108,6 +118,8 @@ async def dashboard_patents(
response_model=DashboardStatisticValue,
)
async def dashboard_eu_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -115,6 +127,8 @@ async def dashboard_eu_projects(
return await get_dashboard_eu_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -124,6 +138,8 @@ async def dashboard_eu_projects(
response_model=EuProjectStatusStatistics,
)
async def dashboard_eu_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> EuProjectStatusStatistics:
@@ -131,6 +147,8 @@ async def dashboard_eu_project_statuses(
return await get_dashboard_eu_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -140,6 +158,8 @@ async def dashboard_eu_project_statuses(
response_model=DashboardStatisticValue,
)
async def dashboard_bmbf_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -147,6 +167,8 @@ async def dashboard_bmbf_projects(
return await get_dashboard_bmbf_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -156,6 +178,8 @@ async def dashboard_bmbf_projects(
response_model=BmbfProjectStatusStatistics,
)
async def dashboard_bmbf_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BmbfProjectStatusStatistics:
@@ -163,6 +187,8 @@ async def dashboard_bmbf_project_statuses(
return await get_dashboard_bmbf_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -172,6 +198,8 @@ async def dashboard_bmbf_project_statuses(
response_model=DashboardStatisticValue,
)
async def dashboard_dfg_projects(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue:
@@ -179,6 +207,28 @@ async def dashboard_dfg_projects(
return await get_dashboard_dfg_projects(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/dfg/status",
operation_id="getDashboardDfgProjectStatuses",
response_model=DfgProjectStatusStatistics,
)
async def dashboard_dfg_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -188,6 +238,8 @@ async def dashboard_dfg_projects(
response_model=DfgProjectTopics,
)
async def dashboard_dfg_project_topics(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectTopics:
@@ -195,6 +247,8 @@ async def dashboard_dfg_project_topics(
return await get_dashboard_dfg_topics(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -208,6 +262,8 @@ async def dashboard_top_authors(
default="all_time",
pattern="^(all_time|last_5_years)$",
),
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> TopAuthorStatistics:
@@ -216,6 +272,8 @@ async def dashboard_top_authors(
organization.openalex_institution_id,
organization.name,
works_period=works_period,
from_year=from_year,
to_year=to_year,
)
File diff suppressed because it is too large Load Diff
+446 -304
View File
@@ -1,5 +1,6 @@
from unittest.mock import AsyncMock, patch
from datetime import datetime
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
@@ -8,11 +9,8 @@ from sqlmodel import Session, SQLModel, create_engine
from inse import config
from inse.auth.model import AccessToken, Organization, UserRole
from inse.dashboard.service import (
get_dashboard_bmbf_project_statuses,
_openalex_work_authors_by_eu_projects,
get_dashboard_organization,
get_dashboard_dfg_topics,
get_dashboard_eu_project_statuses,
get_dashboard_patents,
get_dashboard_statistics,
get_top_authors,
get_topic_heatmap,
@@ -29,137 +27,23 @@ def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_dashboard_patents_uses_org_patent_total():
with patch(
"inse.dashboard.service.OrgPatentsSearchClient.search_by_institution",
new=AsyncMock(return_value=([], 42)),
) as search:
result = await get_dashboard_patents(ORG_INSTITUTION_ID, "Example Org")
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"value": 42,
}
search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0)
@pytest.mark.anyio
async def test_dashboard_eu_project_statuses_deduplicates_projects():
async def scan(**kwargs):
assert kwargs["index"] == str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD)
assert kwargs["source"] == ["projectID"]
yield {"_source": {"projectID": "P2"}}
yield {"_source": {"projectID": "P1"}}
yield {"_source": {"projectID": "P1"}}
response = {
"aggregations": {
"ongoing": {"projects": {"value": 2}},
"upcoming": {"projects": {"value": 1}},
"completed": {"projects": {"value": 7}},
}
}
with patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(return_value=response),
) as search:
result = await get_dashboard_eu_project_statuses(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"ongoing": 2,
"upcoming": 1,
"completed": 7,
}
call = search.await_args
assert call.kwargs["index"] == ESIndex.CORDIS_EU_PROJECTS_WILDCARD
assert call.kwargs["body"]["query"] == {
"terms": {"id": ["P1", "P2"]}
}
today = datetime.now().date().isoformat()
aggregations = call.kwargs["body"]["aggs"]
assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
{"range": {"startDate": {"lte": today}}},
{"range": {"endDate": {"gte": today}}},
]
assert aggregations["upcoming"]["filter"] == {
"range": {"startDate": {"gt": today}}
}
assert aggregations["completed"]["filter"] == {
"range": {"endDate": {"lt": today}}
}
assert all(
aggregation["aggs"]["projects"]["cardinality"]["field"] == "id"
for aggregation in aggregations.values()
)
@pytest.mark.anyio
async def test_dashboard_bmbf_project_statuses_uses_funding_dates():
response = {
"aggregations": {
"ongoing": {"doc_count": 4},
"upcoming": {"doc_count": 2},
"completed": {"doc_count": 19},
}
}
with patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(return_value=response),
) as search:
result = await get_dashboard_bmbf_project_statuses(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"ongoing": 4,
"upcoming": 2,
"completed": 19,
}
call = search.await_args
assert call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
assert call.kwargs["body"]["query"]["bool"]["minimum_should_match"] == 1
today = datetime.now().strftime("%d.%m.%Y")
aggregations = call.kwargs["body"]["aggs"]
assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
{"range": {"funding_start": {"lte": today}}},
{"range": {"funding_end": {"gte": today}}},
]
assert aggregations["upcoming"]["filter"] == {
"range": {"funding_start": {"gt": today}}
}
assert aggregations["completed"]["filter"] == {
"range": {"funding_end": {"lt": today}}
}
@pytest.mark.anyio
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
async def search(**kwargs):
index = kwargs["index"]
if index == config.settings.openalex_works_search_index:
return {"hits": {"total": {"value": 120}}}
if index == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"total": {"value": 35}}}
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
return {"aggregations": {"projects": {"value": 10}}}
if index == ESIndex.PROJECTS_BUND_V1:
return {"hits": {"total": {"value": 5}}}
if index == ESIndex.DFG_INSTITUTES_V2:
if "institute_ids" in kwargs["body"].get("aggs", {}):
return {
@@ -182,6 +66,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
}
}
}
return {"hits": {"total": {"value": 3}}}
with patch(
@@ -200,7 +85,10 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
)
),
):
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
result = await get_dashboard_statistics(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
@@ -212,34 +100,34 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
"eu_projects": 10,
"bmbf_projects": 5,
}
calls = mocked_search.await_args_list
calls_by_index = {
call.kwargs["index"]: call
for call in calls
if call.kwargs["index"] != ESIndex.DFG_INSTITUTES_V2
}
works_call = calls_by_index[config.settings.openalex_works_search_index]
authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS]
eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD]
bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1]
dfg_calls = [
publication_call = next(
call
for call in calls
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
]
dfg_institutes_call, dfg_projects_call = dfg_calls
assert works_call.kwargs["query"]["nested"]["query"]["term"] == {
for call in mocked_search.await_args_list
if call.kwargs["index"] == config.settings.openalex_works_search_index
)
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
"authorships.institutions.id": ORG_INSTITUTION_ID
}
assert authors_call.kwargs["query"]["bool"]["should"][0]["bool"]["filter"][
0
]["nested"]["query"]["match_phrase"] == {
"last_known_institutions.id": ORG_INSTITUTION_ID
}
assert all(
call.kwargs["cluster"] == ESCluster.INSE
for call in [eu_call, bmbf_call, *dfg_calls]
person_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
)
person_query = person_call.kwargs["query"]
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
assert recent_affiliation["nested"]["path"] == "affiliations"
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == {
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
}
eu_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
)
assert eu_call.kwargs["cluster"] == ESCluster.INSE
assert eu_call.kwargs["body"]["query"] == {
"terms": {
"name.keyword": [
@@ -249,141 +137,32 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
]
}
}
assert bmbf_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
assert bmbf_call.kwargs["query"]["bool"]["should"][0]["match"] == {
bund_call = next(
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
)
assert bund_call.kwargs["cluster"] == ESCluster.INSE
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
dfg_query = dfg_institutes_call.kwargs["body"]["query"]
assert dfg_query["bool"]["minimum_should_match"] == 1
assert dfg_query["bool"]["should"] == [
{
"terms": {
"institute_name_de.keyword": [
"Example University",
"Example Universität",
]
}
},
{
"terms": {
"institute_name_en.keyword": [
"Example University",
"Example Universität",
]
}
},
dfg_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
]
assert dfg_projects_call.kwargs["body"]["query"] == {
"terms": {"institute_id": [10210]}
}
assert dfg_projects_call.kwargs["body"]["aggs"] == {
"projects_nested": {
"nested": {"path": "projects"},
"aggs": {
"project_ids": {
"filter": {
"terms": {"projects.institute_ref_id": [10210]}
},
"aggs": {
"values": {
"terms": {
"field": "projects.project_id",
"size": 10000,
}
}
},
}
},
}
}
assert len(dfg_calls) == 2
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
@pytest.mark.anyio
async def test_dashboard_dfg_topics_returns_deduplicated_topics():
async def scan(**kwargs):
assert kwargs == {
"index": "projects_dfg_openalex_topics",
"query": {"terms": {"project_id": ["101", "102"]}},
"source": ["project_id", "topic_matches"],
"page_size": 1000,
"cluster": ESCluster.INSE,
}
yield {
"_source": {
"project_id": "101",
"topic_matches": [
{
"topic_id": "https://openalex.org/T1",
"topic_display_name": "Topic One",
"subfield": "Subfield One",
"field": "Field One",
"domain": "Domain One",
}
],
}
}
yield {
"_source": {
"project_id": "102",
"topic_matches": [
{
"topic_id": "https://openalex.org/T1",
"topic_display_name": "Topic One",
"subfield": "Subfield One",
"field": "Field One",
"domain": "Domain One",
},
{
"topic_id": "https://openalex.org/T2",
"topic_display_name": "Topic Two",
"subfield": "Subfield Two",
"field": "Field Two",
"domain": "Domain Two",
},
],
}
}
with patch(
"inse.dashboard.service._get_dfg_project_ids_for_institution",
new=AsyncMock(return_value=["101", "102"]),
), patch("inse.dashboard.service.elasticsearch.scan", new=scan):
result = await get_dashboard_dfg_topics(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.model_dump() == {
"institution_id": ORG_INSTITUTION_ID,
"organization_name": "Example Org",
"project_count": 2,
"matched_project_count": 2,
"topics": [
{
"id": "https://openalex.org/T1",
"name": "Topic One",
"subfield": "Subfield One",
"field": "Field One",
"domain": "Domain One",
"project_count": 2,
},
{
"id": "https://openalex.org/T2",
"name": "Topic Two",
"subfield": "Subfield Two",
"field": "Field Two",
"domain": "Domain Two",
"project_count": 1,
},
],
}
@pytest.mark.anyio
async def test_top_authors_maps_works_patents_and_news_without_project_queries():
async def test_top_authors_maps_works_patents_news_and_eu_projects():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -408,31 +187,109 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
]
}
}
if kwargs["index"] == "aktuell_postproc":
return {
"aggregations": {
"authors": {
"buckets": [{"key": "Ada Example", "doc_count": 6}]
}
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS:
return {
"aggregations": {
"authors": {
"buckets": [
{"key": "Grace Example", "doc_count": 8},
{"key": "Ada Example", "doc_count": 5},
{"key": "Ada Example", "doc_count": 6}
]
}
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
return {
"hits": {
"hits": [
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1234/p1",
}
},
{
"_source": {
"projectID": "P2",
"qaProcessedDoi": "https://doi.org/10.1234/p2",
}
},
]
}
}
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"aggregations": {
"people": {
"buckets": [{"key": "Grace Example", "doc_count": 3}]
}
}
}
if kwargs["index"] == "openalex-works":
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1234/p1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1234/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
]
}
}
return {"aggregations": {"people": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
) as mocked_search, patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
SimpleNamespace(project_id="P2"),
SimpleNamespace(project_id="P3"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(
return_value=[
@@ -440,7 +297,10 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
]
),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].model_dump() == {
"id": "A1",
@@ -453,30 +313,295 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
"count": 4,
}
assert [author.model_dump() for author in result.eu_projects] == [
{"id": None, "name": "Grace Example", "count": 8},
{"id": None, "name": "Ada Example", "count": 5},
{"id": "A2", "name": "Grace Example", "count": 2},
{"id": "A1", "name": "Ada Example", "count": 1},
]
assert result.news[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 6,
}
project_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"]
in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1}
in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
]
assert project_calls == []
eu_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS
if call.kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD
]
assert len(eu_calls) == 1
terms = eu_calls[0].kwargs["body"]["aggs"]["authors"]["terms"]
assert terms["size"] == 10
assert "splitOnToken(';')" in terms["script"]["source"]
eu_body = eu_calls[0].kwargs["body"]
assert set(eu_body["query"]["terms"]["projectID"]) == {
"P1",
"P2",
"P3",
}
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
works_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
assert len(works_calls) == 1
works_body = works_calls[0].kwargs["body"]
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
assert works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
]
def test_eu_author_count_groups_multiple_publications_by_project_id():
works_response = {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1/marcus-a",
"authorships": [
{
"author": {
"id": "https://openalex.org/A5007170803",
"display_name": "Marcus Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A999",
"display_name": "External Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/marcus-b",
"authorships": [
{
"author": {
"id": "https://openalex.org/A5007170803",
"display_name": "Marcus Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
]
}
}
doi_project_ids = {
"https://doi.org/10.1/marcus-a": {"P1"},
"https://doi.org/10.1/marcus-b": {"P1"},
}
result = _openalex_work_authors_by_eu_projects(
works_response,
doi_project_ids,
ORG_INSTITUTION_ID,
{"https://openalex.org/A5007170803"},
)
assert [author.model_dump() for author in result] == [
{"id": "A5007170803", "name": "Marcus Example", "count": 1}
]
@pytest.mark.anyio
async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_id():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 3,
"counts_by_year": [],
}
},
{
"_source": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
"works_count": 1,
"counts_by_year": [],
}
},
]
}
}
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
assert kwargs["body"]["query"] == {
"terms": {"projectID": ["P1", "P2"]}
}
return {
"hits": {
"hits": [
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1/P1-A",
}
},
{
"_source": {
"projectID": "P1",
"qaProcessedDoi": "10.1/P1-B",
}
},
{
"_source": {
"projectID": "P2",
"qaProcessedDoi": "10.1/P2",
}
},
{
"_source": {
"projectID": "OUTSIDE",
"qaProcessedDoi": "10.1/OUT",
}
},
]
}
}
if kwargs["index"] == "openalex-works":
assert kwargs["body"]["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1/p1-a",
"https://doi.org/10.1/p1-b",
"https://doi.org/10.1/p2",
]
return {
"hits": {
"hits": [
{
"_source": {
"doi": "https://doi.org/10.1/p1-a",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p1-b",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
{
"_source": {
"doi": "https://doi.org/10.1/not-requested",
"authorships": [
{
"author": {
"id": "https://openalex.org/A999",
"display_name": "Outside Author",
}
}
],
}
},
]
}
}
if kwargs["index"] == ESIndex.DFG_PROJECTS:
return {
"aggregations": {
"people": {
"buckets": [
{"key": "Ada Example", "doc_count": 2},
{"key": "ada example", "doc_count": 3},
{"key": "DFG Person", "doc_count": 4},
]
}
}
}
return {"aggregations": {"authors": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
SimpleNamespace(project_id="P2"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert [author.model_dump() for author in result.eu_projects] == [
{"id": "A1", "name": "Ada Example", "count": 2},
{"id": "A2", "name": "Grace Example", "count": 1},
]
@pytest.mark.anyio
@@ -497,16 +622,32 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
]
}
}
raise RuntimeError("projects unavailable")
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(
return_value=SimpleNamespace(
elements=[
SimpleNamespace(project_id="P1"),
],
)
),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
result = await get_top_authors(
ORG_INSTITUTION_ID,
"Example Org",
)
assert result.works[0].name == "Ada Example"
assert result.eu_projects == []
@@ -556,6 +697,9 @@ async def test_top_authors_can_rank_works_by_last_five_years():
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.get_eu_organization_project_contributions",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
@@ -716,13 +860,15 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
== "topics.field.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
["subfields"]["terms"]["field"]
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["terms"][
"field"
]
== "topics.subfield.id"
)
assert (
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
["subfields"]["aggs"]["topics"]["terms"]["field"]
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
"aggs"
]["topics"]["terms"]["field"]
== "topics.id"
)
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
@@ -734,7 +880,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
@pytest.mark.anyio
async def test_topic_heatmap_defaults_to_last_five_years():
async def test_topic_heatmap_defaults_to_all_time():
async def search(**kwargs):
if kwargs["index"] == config.settings.openalex_works_search_index:
return {
@@ -754,13 +900,9 @@ async def test_topic_heatmap_defaults_to_last_five_years():
organization_name="Example Org",
)
current_year = datetime.now().year
assert result.years == list(range(current_year - 4, current_year + 1))
assert result.years == []
body = mocked_search.await_args_list[0].kwargs["body"]
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
"gte": current_year - 4,
"lte": current_year,
}
assert body["query"]["bool"]["filter"] == []
@pytest.mark.anyio
@@ -1,8 +1,10 @@
import logging
from typing import Annotated
from fastapi import APIRouter, Query
import inse.institutions.v2.service as institutions_service
from fastapi import APIRouter, Path, Query
from inse.institutions.v2.model import InstitutionPageV2
from inse.models.openalex.institution import Institution
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
@@ -13,7 +15,32 @@ router = APIRouter(prefix=RouterPrefixes.INSTITUTIONS_V2, tags=[Tags.INSTITUTION
@router.get(
"/ids",
"/single/{institution_id}",
operation_id="getInstitutionById2",
summary="Returns an institution based on its ID.",
)
async def get_institution_by_id(
institution_id: Annotated[
str,
Path(description="The ID of the institution to retrieve."),
],
) -> Institution:
return await institutions_service.get_institution_by_id_or_raise(
raw_oa_institution_id=institution_id,
source=[
"id",
"display_name",
"display_name_alternatives",
"works_count",
"cited_by_count",
"geo",
"summary_stats",
],
)
@router.get(
"/multiple/ids",
operation_id="getInstitutionsByIds",
summary="Returns a list of institutions based on their IDs.",
)
@@ -23,9 +50,9 @@ async def get_institutions_by_ids(
Query(description="A list of institution IDs to retrieve."),
] = None,
) -> InstitutionPageV2:
from inse.institutions.v2.service import get_institutions_by_ids
return await get_institutions_by_ids(institution_ids=institution_ids or [])
return await institutions_service.get_institutions_by_ids(
institution_ids=institution_ids or []
)
@router.get(
@@ -41,6 +68,6 @@ async def get_institution_autocomplete(
),
] = "",
) -> InstitutionPageV2:
from inse.institutions.v2.service import autocomplete_institutions_for_selector
return await autocomplete_institutions_for_selector(query=query)
return await institutions_service.autocomplete_institutions_for_selector(
query=query
)
@@ -1,5 +1,6 @@
import logging
from inse.exceptions import NotFoundException
from inse.institutions.v2.model import InstitutionPageV2
from inse.integrations import elasticsearch
from inse.model import ESIndex
@@ -8,6 +9,51 @@ from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
async def get_institution_by_id(
raw_oa_institution_id: str, source: list[str] | None = None
) -> Institution | None:
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index.
Args:
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
Institution | None: The institution object if found, otherwise None.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_INSTITUTIONS, doc_id=raw_oa_institution_id, source=source
)
if not response.get("found"):
return None
return Institution.from_dict(response.get("_source", {})) # type: ignore
async def get_institution_by_id_or_raise(
raw_oa_institution_id: str, source: list[str] | None = None
) -> Institution:
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index, raising an exception if not found.
Args:
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Raises:
NotFoundException: If the institution is not found.
Returns:
Institution: The institution object if found.
"""
institution = await get_institution_by_id(
raw_oa_institution_id=raw_oa_institution_id, source=source
)
if institution is None:
raise NotFoundException(
f"Institution with ID {raw_oa_institution_id} not found."
)
return institution
async def search_institutions(
page: int = 0,
size: int = 10,
@@ -1,5 +1,6 @@
import json
import logging
import time
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
import httpx
@@ -110,6 +111,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
return None
def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]:
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
@@ -125,6 +130,63 @@ def _wrap_exception(e: Exception) -> Exception:
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
async def _request(
method: str,
cluster: ESCluster,
path: str,
*,
json_body: Optional[Any] = None,
params: Optional[Dict[str, Any]] = None,
content: Optional[bytes] = None,
content_type: str = "application/json",
) -> httpx.Response:
"""Sends an authenticated request to cluster and returns the raw response.
Args:
method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE").
cluster: The Elasticsearch cluster to send the request to.
path: The path appended to the cluster URL (without leading slash).
json_body: Optional JSON-serialisable request body.
params: Optional query parameters.
content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body.
content_type: The Content-Type header value.
Returns:
httpx.Response: The successful response (status already checked).
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
client = get_client()
start = time.perf_counter()
try:
response = await client.request(
method,
f"{elasticsearch_url}/{path}",
json=json_body,
params=params,
content=content,
headers=_headers(api_key, content_type=content_type),
)
response.raise_for_status()
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms"
)
return response
except Exception as exc:
if config.settings.print_es_timings:
elapsed_ms = (time.perf_counter() - start) * 1000
logger.debug(
f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms"
)
raise _wrap_exception(exc) from exc
async def search(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
@@ -175,10 +237,6 @@ async def search(
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:
@@ -210,61 +268,34 @@ async def search(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
)
client = get_client()
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
)
if config.settings.print_es_queries:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload)
return response.json()
async def open_point_in_time(
index: str, keep_alive: str = "1m", cluster: str = "nes"
) -> str:
"""Opens a point-in-time on the given index and returns its id."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive})
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_pit",
params={"keep_alive": keep_alive},
headers=headers,
)
response.raise_for_status()
return response.json()["id"]
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()["id"]
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
"""Closes a previously opened point-in-time."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
client = get_client()
try:
response = await client.request(
"DELETE",
f"{elasticsearch_url}/_pit",
json={"id": pit_id},
headers=headers,
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
await _request("DELETE", cluster, "_pit", json_body={"id": pit_id})
async def scan(
@@ -280,13 +311,9 @@ async def scan(
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
search_after: Optional[List] = None
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
"size": page_size,
@@ -299,14 +326,7 @@ async def scan(
if search_after is not None:
payload["search_after"] = search_after
try:
response = await client.post(
f"{elasticsearch_url}/_search", json=payload, headers=headers
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, "_search", json_body=payload)
result = response.json()
hits = result.get("hits", {}).get("hits", [])
@@ -338,23 +358,13 @@ async def get(
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
client = get_client()
try:
response = await client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params)
return response.json()
async def update(
@@ -363,20 +373,11 @@ async def update(
doc: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
)
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_update/{doc_id}",
json={"doc": doc},
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def index_doc(
@@ -385,20 +386,11 @@ async def index_doc(
document: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
response = await _request(
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
)
client = get_client()
try:
response = await client.put(
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
json=document,
headers=headers,
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def count(
@@ -431,24 +423,15 @@ async def count(
if len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
payload = {"query": query} if query else {}
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers
)
response.raise_for_status()
return response.json().get("count", 0)
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload)
return response.json().get("count", 0)
async def msearch(
@@ -473,9 +456,6 @@ async def msearch(
if c is not None:
cluster = c
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"}
lines = []
for idx, body in searches:
if isinstance(idx, list):
@@ -488,16 +468,13 @@ async def msearch(
ndjson_payload = "\n".join(lines) + "\n"
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/_msearch",
content=ndjson_payload.encode("utf-8"),
headers=headers,
)
response.raise_for_status()
res_json = response.json()
return res_json.get("responses", [])
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request(
"POST",
cluster,
"_msearch",
content=ndjson_payload.encode("utf-8"),
content_type="application/x-ndjson",
)
return response.json().get("responses", [])
+3 -1
View File
@@ -52,6 +52,7 @@ from inse.patents.service import (
)
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
@@ -103,6 +104,7 @@ app = FastAPI(
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(bund_institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
@@ -137,7 +139,7 @@ app.include_router(background_jobs_router)
app.include_router(eu_organizations_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=120, # 2 minutes expiration time
ttl=600, # 10 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
@@ -16,10 +16,11 @@ NO_STORE_PATH_PREFIXES = (
"/api/background-jobs",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/works/v2/classification/",
)
"/api/dashboard",
"/api/rank/rank-author",
"/api/rank/orientation-profiles",
"/api/works/v2/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
+1
View File
@@ -68,6 +68,7 @@ class ESIndex(StrEnum):
AKTUELLES = "aktuell"
AKTUELLES_POSTPROC = "aktuell_postproc"
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
@@ -8,8 +8,8 @@
"""
from datetime import date, datetime
from typing import Optional, List, Set, Any
from typing import Optional, List, Set, Any, Dict
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -189,6 +189,10 @@ class BundProjectDetails(BaseModel):
default_factory=list,
description="All institutions associated with the Bund project",
)
oa_topics: Optional[List[Topic]] = Field(
default_factory=list,
description="OpenAlex topics associated with the Bund project",
)
# --- Validators for type coercion ---
@@ -301,7 +305,17 @@ class BundProjectDetails(BaseModel):
if source.get("PT_fullname"):
institutions.add(source["PT_fullname"].strip())
topics_raw = source.get("oa_topics") or []
if not isinstance(source, dict):
return cls.model_validate(source)
oa_topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
return cls(
id=hit["_id"],
funding_reference=source.get("Förderkennzeichen"),
@@ -334,4 +348,24 @@ class BundProjectDetails(BaseModel):
unix_timestamp=source.get("unix_timestamp"),
associated_persons=sorted(persons),
institutions=sorted(institutions),
oa_topics=oa_topics
)
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -1,293 +1,435 @@
# coding: utf-8
"""
DFG Project Clean Model
DFG Project Clean Model (v2)
Summary model that consolidates all scattered person and institution fields
from the raw projects_dfg_all index into clean, unified lists.
Enriched, consolidated model built on top of the structured
projects_dfg_v2 API models (DFGProject / DFGPerson / DFGInstitute),
rather than the old flat projects_dfg_all Elasticsearch index.
"""
from typing import Optional, List, Set
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
from inse.models.projects_dfg_v2.project.dfg_project import DFGProject
from inse.models.projects_dfg_v2.project.dfg_project_persons_inner import (
DFGProjectPersonsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_institutions_inner import (
DFGProjectInstitutionsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import (
DFGProjectSubprojectsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_publications_inner import (
DFGProjectPublicationsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
DFGProjectFachgebieteInner,
)
from inse.topics.model import Topic
class DfgProjectPersonRole(BaseModel):
"""A person associated with the project, together with their role."""
model_config = ConfigDict(populate_by_name=True)
person_id: Optional[int] = Field(default=None, description="DFG person ID")
full_name: Optional[str] = Field(default=None, description="Full name of the person")
orcid_id: Optional[str] = Field(
default=None,
description=(
"ORCID iD, if known. Not present on the project's embedded person "
"record (DFGProjectPersonsInner) -- only populated if the caller "
"cross-references the full DFGPerson record via person_id and "
"calls DfgProjectDetails.enrich_orcids afterwards."
),
)
role_key: Optional[str] = Field(
default=None, description="Machine-readable role key (e.g. 'antragsteller')"
)
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
affiliation_de: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (German)"
)
affiliation_en: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (English)"
)
is_deceased: Optional[bool] = Field(default=None, description="Whether the person is deceased")
is_head: Optional[bool] = Field(
default=None, description="Whether this person is highlighted as the project head"
)
@classmethod
def from_inner(cls, p: DFGProjectPersonsInner) -> "DfgProjectPersonRole":
return cls(
person_id=p.person_id,
full_name=p.full_name,
role_key=p.role_key,
role_label_de=p.role_label_de,
role_label_en=p.role_label_en,
affiliation_de=p.affiliation_de,
affiliation_en=p.affiliation_en,
is_deceased=p.is_deceased,
is_head=p.is_head_display,
)
class DfgProjectInstitutionRole(BaseModel):
"""An institution associated with the project, together with its role."""
model_config = ConfigDict(populate_by_name=True)
institute_id: Optional[int] = Field(default=None, description="DFG institute ID")
name_de: Optional[str] = Field(default=None, description="Institution name (German)")
name_en: Optional[str] = Field(default=None, description="Institution name (English)")
role_key: Optional[str] = Field(default=None, description="Machine-readable role key")
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
is_dissolved: Optional[bool] = Field(
default=None, description="Whether the institution has since been dissolved"
)
is_head: Optional[bool] = Field(
default=None, description="Whether this institution is highlighted as the lead institution"
)
@classmethod
def from_inner(cls, i: DFGProjectInstitutionsInner) -> "DfgProjectInstitutionRole":
return cls(
institute_id=i.institute_id,
name_de=i.institute_name_de,
name_en=i.institute_name_en,
role_key=i.role_key,
role_label_de=i.role_label_de,
role_label_en=i.role_label_en,
is_dissolved=i.is_dissolved,
is_head=i.is_head_display,
)
class DfgProjectSubprojectSummary(BaseModel):
"""A lightweight reference to a sub-project of this project."""
model_config = ConfigDict(populate_by_name=True)
subproject_id: Optional[int] = None
title_de: Optional[str] = None
title_en: Optional[str] = None
short_title: Optional[str] = None
role_label_de: Optional[str] = Field(
default=None, description="Role of the sub-project lead within the sub-project"
)
person_full_name: Optional[str] = Field(
default=None, description="Sub-project lead, derived from first/last name fields"
)
status_de: Optional[str] = None
funding_start: Optional[int] = None
funding_end: Optional[int] = None
@classmethod
def from_inner(cls, s: DFGProjectSubprojectsInner) -> "DfgProjectSubprojectSummary":
person_full_name = None
if s.person_first_names or s.person_last_name:
person_full_name = " ".join(
part for part in [s.person_first_names, s.person_last_name] if part
).strip() or None
return cls(
subproject_id=s.subproject_id,
title_de=s.title_de,
title_en=s.title_en,
short_title=s.short_title,
role_label_de=s.role_label_de,
person_full_name=person_full_name,
status_de=s.status_de,
funding_start=s.funding_start,
funding_end=s.funding_end,
)
class DfgProjectPublicationSummary(BaseModel):
"""A lightweight reference to a publication resulting from the project."""
model_config = ConfigDict(populate_by_name=True)
publication_id: Optional[int] = None
title: Optional[str] = None
authors_editors: Optional[str] = None
doi: Optional[str] = None
publication_year: Optional[int] = None
@classmethod
def from_inner(cls, p: DFGProjectPublicationsInner) -> "DfgProjectPublicationSummary":
return cls(
publication_id=p.publication_id,
title=p.title,
authors_editors=p.authors_editors,
doi=p.doi,
publication_year=p.publication_year,
)
class DfgProjectSubjectArea(BaseModel):
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
model_config = ConfigDict(populate_by_name=True)
fach: Optional[str] = None
fachgebiet: Optional[str] = None
fachkollegium: Optional[str] = None
wissenschaftsbereich: Optional[str] = None
@classmethod
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
return cls(
fach=f.fach,
fachgebiet=f.fachgebiet,
fachkollegium=f.fachkollegium,
wissenschaftsbereich=f.wissenschaftsbereich,
)
class DfgProjectDetails(BaseModel):
"""
Clean summary model for a DFG project, consolidating all person roles
and institution references into unified lists.
Clean, enriched summary model for a DFG project.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
id: Optional[int] = Field(default=None, description="The DFG project ID")
link: Optional[str] = Field(default=None, description="Canonical DFG link to the project")
page_url: Optional[str] = Field(default=None, description="DFG GEPRIS page URL")
external_link: Optional[str] = Field(
default=None, description="External project website/link, if provided"
)
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"
title_de: Optional[str] = Field(default=None, description="Project title (German)")
title_en: Optional[str] = Field(default=None, description="Project title (English)")
description_de: Optional[str] = Field(default=None, description="Project abstract (German)")
description_en: Optional[str] = Field(default=None, description="Project abstract (English)")
final_report_abstract_de: Optional[str] = Field(
default=None, description="Final report abstract (German), if the project has concluded"
)
description: Optional[str] = Field(
default=None, description="The description of the DFG project"
final_report_abstract_en: Optional[str] = Field(
default=None, description="Final report abstract (English), if the project has concluded"
)
project_identifier: Optional[str] = Field(
default=None,
description="The project identifier of the DFG project",
)
project_identifier_de: Optional[str] = Field(default=None, description="DFG project identifier (German)")
project_identifier_en: Optional[str] = Field(default=None, description="DFG project identifier (English)")
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"
)
funding_start: Optional[int] = Field(default=None, description="Funding start year")
funding_end: Optional[int] = Field(default=None, description="Funding end year")
funding_period_de: Optional[str] = Field(default=None, description="Human-readable funding period (German)")
funding_period_en: Optional[str] = Field(default=None, description="Human-readable funding period (English)")
funding_type_de: Optional[str] = Field(default=None, description="Funding type / programme (German)")
funding_type_en: Optional[str] = Field(default=None, description="Funding type / programme (English)")
funding_type_key: Optional[str] = Field(default=None, description="Machine-readable funding type key")
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",
default=None, description="DFG procedure / template type (e.g. Sachbeihilfe, SFB, GRK)"
)
website: Optional[str] = Field(
default=None, description="The project website"
is_transfer_project: Optional[bool] = Field(
default=None, description="Whether this is a transfer project"
)
# Unified person list: all person names from any role
website_html_de: Optional[str] = Field(
default=None, description="Raw project website HTML content (German), as served by DFG"
)
website_html_en: Optional[str] = Field(
default=None, description="Raw project website HTML content (English), as served by DFG"
)
equipment_group: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) group, for equipment-funding projects",
)
equipment_name: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) name, for equipment-funding projects",
)
subject_area_de: Optional[str] = Field(default=None, description="Subject area, summary text (German)")
subject_area_en: Optional[str] = Field(default=None, description="Subject area, summary text (English)")
subject_classifications: List[DfgProjectSubjectArea] = Field(
default_factory=list,
description="Detailed DFG subject-area classification entries (Fachsystematik)",
)
international_relation_de: Optional[str] = Field(
default=None, description="International reference/cooperation (German)"
)
international_relation_en: Optional[str] = Field(
default=None, description="International reference/cooperation (English)"
)
# Structured, role-aware person and institution lists
persons: List[DfgProjectPersonRole] = Field(
default_factory=list,
description="All persons associated with the project, each with their role",
)
institutions: List[DfgProjectInstitutionRole] = Field(
default_factory=list,
description="All institutions associated with the project, each with their role",
)
# Convenience flat views, derived from the structured lists above
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the DFG project (any role)",
description="Flat, de-duplicated list of all person full names (convenience view)",
)
# Unified institution list: all institutions involved
institutions: List[str] = Field(
associated_institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the DFG project",
description="Flat, de-duplicated list of all institution names (convenience view)",
)
# Sub-project reference
subproject_of: Optional[str] = Field(
default=None,
description="Parent project this is a sub-project of",
# Parent / sub-project structure
parent_project_id: Optional[int] = Field(default=None, description="Parent project ID, if this is a sub-project")
parent_title_de: Optional[str] = Field(default=None, description="Parent project title (German)")
parent_title_en: Optional[str] = Field(default=None, description="Parent project title (English)")
subprojects: List[DfgProjectSubprojectSummary] = Field(
default_factory=list, description="Sub-projects of this project, if any"
)
publications: List[DfgProjectPublicationSummary] = Field(
default_factory=list, description="Publications resulting from the project"
)
topics: Optional[List[Topic]] = Field(
default_factory=list, description="OpenAlex topics associated with the project ID"
)
@classmethod
def from_dfg_project(cls, project: DFGProject) -> "DfgProjectDetails":
"""
Build a DfgProjectDetails from a fully-typed DFGProject instance
(e.g. as returned by the projects_dfg_v2 API client).
"""
persons = [DfgProjectPersonRole.from_inner(p) for p in (project.persons or [])]
institutions = [
DfgProjectInstitutionRole.from_inner(i) for i in (project.institutions or [])
]
subprojects = [
DfgProjectSubprojectSummary.from_inner(s) for s in (project.subprojects or [])
]
publications = [
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
]
subject_classifications = [
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
]
# De-duplicated flat views, order-preserving
seen_persons = set()
associated_persons = []
for p in persons:
if p.full_name and p.full_name not in seen_persons:
seen_persons.add(p.full_name)
associated_persons.append(p.full_name)
seen_institutions = set()
associated_institutions = []
for i in institutions:
name = i.name_de or i.name_en
if name and name not in seen_institutions:
seen_institutions.add(name)
associated_institutions.append(name)
return cls(
id=project.id or project.project_id,
link=project.link,
page_url=project.page_url,
external_link=project.external_link,
title_de=project.title_de,
title_en=project.title_en,
description_de=project.abstract_de,
description_en=project.abstract_en,
final_report_abstract_de=project.final_report_abstract_de,
final_report_abstract_en=project.final_report_abstract_en,
project_identifier_de=project.project_identifier_de,
project_identifier_en=project.project_identifier_en,
funding_start=project.funding_start,
funding_end=project.funding_end,
funding_period_de=project.funding_period_de,
funding_period_en=project.funding_period_en,
funding_type_de=project.funding_type_de,
funding_type_en=project.funding_type_en,
funding_type_key=project.funding_type_key,
dfg_procedure=project.template_type,
is_transfer_project=project.is_transfer_project,
website_html_de=project.website_html_de,
website_html_en=project.website_html_en,
equipment_group=project.equipment_group,
equipment_name=project.equipment_name,
subject_area_de=project.subject_area_de,
subject_area_en=project.subject_area_en,
subject_classifications=subject_classifications,
international_relation_de=project.international_relation_de,
international_relation_en=project.international_relation_en,
persons=persons,
institutions=institutions,
associated_persons=associated_persons,
associated_institutions=associated_institutions,
parent_project_id=project.parent_project_id,
parent_title_de=project.parent_title_de,
parent_title_en=project.parent_title_en,
subprojects=subprojects,
publications=publications,
topics=project.topics,
)
@classmethod
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
obj = cls._sanitize_raw_project_dict(obj)
return cls.from_dfg_project(DFGProject.from_dict(obj))
@staticmethod
def _sanitize_raw_project_dict(obj: dict) -> dict:
"""
Work around known mismatches between the generated DFGProject model
and the actual shape of API/index data, before handing off to
DFGProject.from_dict (which would otherwise raise a ValidationError
and abort the whole parse).
"""
if isinstance(obj.get("subject_classifications"), list):
obj = dict(obj)
obj.pop("subject_classifications", None)
return obj
@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.
Compatibility constructor for callers still reading from an
Elasticsearch hit (e.g. `{"_id": ..., "_source": {...}}`), matching
the old model's from_elastic_hit signature.
"""
source = dict(hit.get("_source", {}))
source = hit.get("_source", {})
if source.get("id") is None and source.get("project_id") is None:
raw_id = hit.get("_id")
if raw_id is not None:
try:
source["id"] = int(raw_id)
except (TypeError, ValueError):
# Non-numeric _id (e.g. a composite/legacy key) - leave
# id unset rather than fail the whole parse.
pass
associated_persons: Set[str] = set()
institutions: Set[str] = set()
return cls.from_dict(source)
# --- Collect all persons and institutions from nested persons array ---
persons_list = source.get("persons", [])
if isinstance(persons_list, list):
for p in persons_list:
if isinstance(p, dict):
full_name = p.get("full_name")
if full_name:
associated_persons.add(full_name.strip())
aff_de = p.get("affiliation_de")
if aff_de:
institutions.add(aff_de.strip())
aff_en = p.get("affiliation_en")
if aff_en:
institutions.add(aff_en.strip())
# --- 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") or source.get("page_url"),
title=source.get("title") or source.get("title_de") or source.get("title_en"),
description=source.get("description") or source.get("abstract_de") or source.get("abstract_en"),
project_identifier=source.get("Projektkennung") or source.get("project_identifier_de") or source.get("project_identifier_en"),
funding_start_date=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
funding_end_date=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
dfg_procedure=source.get("DFG-Verfahren") or source.get("template_type"),
subject_area=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
funding_type=source.get("Förderung") or source.get("funding_type_sort"),
international_reference=source.get("Internationaler Bezug") or source.get("international_relation_de") or source.get("international_relation_en"),
website=source.get("Webseite"),
associated_persons=sorted(associated_persons), # sorted for consistency
institutions=sorted(institutions),
subproject_of=source.get("Teilprojekt zu") or source.get("parent_project_id"),
)
# --- 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)
def enrich_orcids(self, persons_by_id: dict) -> None:
"""
Fill in orcid_id on each entry in `self.persons`, given a mapping of
person_id -> DFGPersonPerson (or DFGPerson) for the persons involved
in this project
"""
for person in self.persons:
record = persons_by_id.get(person.person_id)
if record is not None:
person.orcid_id = getattr(record, "orcid_id", None)
@@ -29,6 +29,7 @@ from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import DF
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
class DFGProject(BaseModel):
"""
@@ -52,7 +53,7 @@ class DFGProject(BaseModel):
funding_type_key: Optional[StrictStr] = None
funding_type_sort: Optional[StrictStr] = None
id: Optional[StrictInt] = None
institution_roles_order: Optional[StrictStr] = None
institution_roles_order: Optional[list[StrictStr]] = None
institutions: Optional[List[DFGProjectInstitutionsInner]] = None
international_relation_de: Optional[StrictStr] = None
international_relation_en: Optional[StrictStr] = None
@@ -62,7 +63,7 @@ class DFGProject(BaseModel):
parent_project_id: Optional[StrictInt] = None
parent_title_de: Optional[StrictStr] = None
parent_title_en: Optional[StrictStr] = None
person_roles_order: Optional[StrictStr] = None
person_roles_order: Optional[list[StrictStr]] = None
persons: Optional[List[DFGProjectPersonsInner]] = None
project: Optional[DFGProjectProject] = None
project_id: Optional[StrictInt] = None
@@ -72,13 +73,14 @@ class DFGProject(BaseModel):
subject_area_de: Optional[StrictStr] = None
subject_area_en: Optional[StrictStr] = None
subject_classifications: Optional[DFGProjectFachgebieteInner] = None
subproject_order: Optional[StrictStr] = None
subproject_order: Optional[list[StrictStr]] = None
subprojects: Optional[List[DFGProjectSubprojectsInner]] = None
template_type: Optional[StrictStr] = None
title_de: Optional[StrictStr] = None
title_en: Optional[StrictStr] = None
website_html_de: Optional[StrictStr] = None
website_html_en: Optional[StrictStr] = None
topics: Optional[List[Topic]] = None
__properties: ClassVar[List[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
model_config = ConfigDict(
@@ -168,9 +170,18 @@ class DFGProject(BaseModel):
"""Create an instance of DFGProject from a dict"""
if obj is None:
return None
topics_raw = obj.get("topics") or []
if not isinstance(obj, dict):
return cls.model_validate(obj)
topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
_obj = cls.model_validate({
"abstract_de": obj.get("abstract_de"),
@@ -217,8 +228,29 @@ class DFGProject(BaseModel):
"title_de": obj.get("title_de"),
"title_en": obj.get("title_en"),
"website_html_de": obj.get("website_html_de"),
"website_html_en": obj.get("website_html_en")
"website_html_en": obj.get("website_html_en"),
"topics": topics,
})
return _obj
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class Fp7ProjectDetails(BaseModel):
"""
@@ -70,6 +71,9 @@ class Fp7ProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
ipr_count: Optional[int] = Field(default=None, alias="iprCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
@@ -79,7 +83,7 @@ class Fp7ProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "iprs", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "iprCount"
"organizationCount", "publicationCount", "iprCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -163,6 +167,10 @@ class Fp7ProjectDetails(BaseModel):
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
"iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
# # OpenAlex related fields
# "oaTopics": [Topic.from_dict(topic) for topic in obj.get("oaTopics", [])] if obj.get("oaTopics") else None,
# "oaAuthors": AuthorPage.from_dict(obj.get("oaAuthors")) if obj.get("oaAuthors") else None,
})
return _obj
@@ -178,6 +186,8 @@ class Fp7ProjectDetails(BaseModel):
web_links: Optional[List[Fp7WebLink]] = None,
eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +221,6 @@ class Fp7ProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
iprCount=len(iprs) if iprs else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,14 @@ 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
from inse.authors.v2.model import Author
class Fp7Publication(BaseModel):
"""
Fp7Publication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +48,7 @@ class Fp7Publication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
@@ -26,7 +26,8 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLi
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class H2020ProjectDetails(BaseModel):
"""
@@ -73,7 +74,10 @@ class H2020ProjectDetails(BaseModel):
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -84,6 +88,7 @@ class H2020ProjectDetails(BaseModel):
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"ercPrincipalInvestigators",
"organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
,"oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -185,6 +190,8 @@ class H2020ProjectDetails(BaseModel):
eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
legal_basis_list: Optional[List[H2020LegalBasis]] = None,
erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -221,4 +228,6 @@ class H2020ProjectDetails(BaseModel):
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,13 @@ 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
from inse.authors.v2.model import Author
class H2020Publication(BaseModel):
"""
H2020Publication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +47,8 @@ class H2020Publication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class HEUProjectDetails(BaseModel):
"""
@@ -70,7 +71,9 @@ class HEUProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -79,7 +82,7 @@ class HEUProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "deliverables", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "deliverableCount"
"organizationCount", "publicationCount", "deliverableCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -178,6 +181,8 @@ class HEUProjectDetails(BaseModel):
web_links: Optional[List[HEUWebLink]] = None,
eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
legal_basis_list: Optional[List[HEULegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +216,6 @@ class HEUProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,14 @@ 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
from inse.authors.v2.model import Author
class HEUPublication(BaseModel):
"""
HEUPublication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +48,8 @@ class HEUPublication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
+15 -20
View File
@@ -4,16 +4,16 @@
Business logic for the "aktuell" news index on the INSE cluster.
"""
import json
import logging
import re
from pydantic import ValidationError
from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from ..topics.logic import vector_search_topics_batch
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
from .model import (MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsKeywords, NewsPage)
logger = logging.getLogger(__name__)
@@ -294,12 +294,19 @@ async def _get_article_keywords(
if not text:
return [], postproc_id
raw = await llm.call(
response = await llm.call(
system_prompt=KEYWORD_SYSTEM_PROMPT,
user_prompt=f"Artikel:\n{text}",
json_schema=NewsKeywords.model_json_schema(),
schema_name="keywords",
temperature=0.3,
)
keywords = _parse_keywords(raw)
try:
keywords = _normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
except ValidationError:
logger.warning(f"Keyword extraction for news {news_id} returned no valid JSON: {response}")
keywords = []
if keywords:
postproc_id = await _store_keywords(news_id, postproc_id, keywords)
@@ -359,24 +366,12 @@ async def get_article_topics_from_index(news_id: str) -> list:
return matched
def _parse_keywords(raw: str) -> list:
raw = (raw or "").strip()
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
candidates = parsed
elif isinstance(parsed, dict):
candidates = parsed.get("keywords", [])
else:
candidates = []
except (json.JSONDecodeError, TypeError):
candidates = re.split(r"[,\n]", raw)
def _normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
keywords = []
for item in candidates:
term = str(item).strip().strip('"').strip()
term = item.strip().strip('"').strip()
if term and term.lower() not in seen:
seen.add(term.lower())
keywords.append(term)
+5 -1
View File
@@ -3,7 +3,11 @@
from typing import List, Optional
from pydantic import BaseModel
from pydantic import BaseModel, Field
class NewsKeywords(BaseModel):
keywords: List[str] = Field(description="The extracted keywords from the article.")
class NewsArticle(BaseModel):
@@ -256,6 +256,8 @@ class OrgPatentsSearchClient:
page: int = 0,
size: int = DEFAULT_PAGE_SIZE,
source: str | None = None,
from_year: int | None = None,
to_year: int | None = None,
) -> tuple[list[OrgPatentEntry], int]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
@@ -270,6 +272,14 @@ class OrgPatentsSearchClient:
if source in ("EPO", "USPTO"):
filters.append({"term": {"source": source}})
year_range: dict[str, int] = {}
if from_year is not None:
year_range["gte"] = from_year
if to_year is not None:
year_range["lte"] = to_year
if year_range:
filters.append({"range": {"publication_year": year_range}})
payload = {
"from": page * size,
"size": size,
@@ -304,11 +314,27 @@ class OrgPatentsSearchClient:
self,
institution_id: str,
size: int = 10,
from_year: int | None = None,
to_year: int | None = None,
) -> list[dict[str, Any]]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
year_range: dict[str, int] = {}
if from_year is not None:
year_range["gte"] = from_year
if to_year is not None:
year_range["lte"] = to_year
if year_range:
filters.append({"range": {"publication_year": year_range}})
query = (
{"term": {"institution_id": short_id}}
if len(filters) == 1
else {"bool": {"filter": filters}}
)
payload = {
"size": 0,
"query": {"term": {"institution_id": short_id}},
"query": query,
"aggs": {
"matched_authors_nested": {
"nested": {"path": "matched_authors"},
@@ -53,3 +53,43 @@ async def test_top_authors_by_institution_aggregates_matched_authors():
payload["aggs"]["matched_authors_nested"]["nested"]["path"]
== "matched_authors"
)
@pytest.mark.anyio
async def test_top_authors_by_institution_filters_by_publication_year():
requests: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
return httpx.Response(
200,
json={
"aggregations": {
"matched_authors_nested": {
"authors": {"buckets": []}
}
}
},
)
client = OrgPatentsSearchClient(
base_url="https://example.test",
api_key="key",
transport=httpx.MockTransport(handler),
)
await client.top_authors_by_institution(
"https://openalex.org/I123",
from_year=2020,
to_year=2024,
)
payload = json.loads(requests[0].content)
assert payload["query"] == {
"bool": {
"filter": [
{"term": {"institution_id": "I123"}},
{"range": {"publication_year": {"gte": 2020, "lte": 2024}}},
]
}
}
+14 -4
View File
@@ -11,6 +11,8 @@ import time
from datetime import datetime
from typing import List, Optional
from pydantic import ValidationError
from inse.exceptions import (
BadRequestException,
ElasticsearchException,
@@ -26,6 +28,7 @@ from inse.persons.model import (
CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
PersonBio
)
from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions
@@ -473,21 +476,28 @@ async def generate_person_bio(
Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text.
Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten.
Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen.
Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält.
"""
user_prompt = f"Daten zur Person:\n{person_json}"
bio = await llm.call(
response = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=PersonBio.model_json_schema(),
schema_name="bio",
temperature=0.8,
top_p=0.95,
)
try:
bio = PersonBio.model_validate_json(response).bio
except ValidationError:
logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}")
bio = "Etwas ist schiefgelaufen."
elapsed_time = time.time() - start_time
logger.info(
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
)
logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds")
return bio
@@ -0,0 +1,42 @@
from typing import Optional
from inse.model import Page
from pydantic import BaseModel
class BundInstitutionSummary(BaseModel):
"""A single institution entry derived from a BUND project record.
Note: this index has no dedicated institution entity — each entry is
reconstructed from the agency/recipient fields on a single project hit,
so the same institution may appear multiple times (once per project).
"""
department: Optional[str] = None
department_fullname: Optional[str] = None
name: Optional[str] = None
recepient: Optional[str] = None
municipality: Optional[str] = None
place: Optional[str] = None
state: Optional[str] = None
country: Optional[str] = None
@classmethod
def from_source(cls, source: dict) -> "BundInstitutionSummary":
"""Build a BundInstitutionSummary from a raw Elasticsearch _source dict."""
return cls(
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
name=source.get("Ausführende Stelle"),
recepient=source.get("Zuwendungsempfänger"),
municipality=source.get("Stadt/Gemeinde"),
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
)
class BundInstitutionSummaryPage(Page[BundInstitutionSummary]):
"""A paginated response containing a list of institutions."""
pass
@@ -0,0 +1,47 @@
import logging
from typing import Annotated
from fastapi import APIRouter, Query
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
from inse.tags import Tags
from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names
logger = logging.getLogger(__name__)
INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions"
router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS])
@router.get(
"/names",
operation_id="getBundInstitutionsByName",
summary="Returns a list of institutions based on their names.",
)
async def get_bund_institutions(
institution_names: Annotated[
list[str],
Query(description="A list of institution names to retrieve."),
] = [],
) -> BundInstitutionSummaryPage:
return await get_institutions_by_names(institution_names=institution_names or [])
@router.get(
"/autocomplete/selector",
operation_id="getBundInstitutionAutocompleteForSelector",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_bund_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> BundInstitutionSummaryPage:
return await autocomplete_institutions_for_selector(query=query)
@@ -0,0 +1,169 @@
import logging
from typing import Dict, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESIndex, ESCluster
from inse.projects.bund_institutions.model import BundInstitutionSummary
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
logger = logging.getLogger(__name__)
# Fields on the BUND project index that describe the institution/agency involved,
# used consistently across all lookup functions below.
_INSTITUTION_SOURCE_FIELDS = [
"Ressort",
"Ressort_fullname",
"Ausführende Stelle",
"Zuwendungsempfänger",
"Stadt/Gemeinde",
"Ort",
"Bundesland",
"Staat",
]
async def search_institutions(
page: int = 0,
size: int = 10,
query: Optional[Dict] = None,
source: Optional[List[str]] = None,
sort: Optional[List[Dict]] = None,
body: Optional[Dict] = None,
) -> BundInstitutionSummaryPage:
"""Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters.
Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each
matching project hit is reshaped into a BundInstitutionSummary. The same
institution may therefore appear multiple times if it's tied to multiple projects.
Args:
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the search criteria.
"""
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
cluster=ESCluster.INSE,
query=query,
source=source or _INSTITUTION_SOURCE_FIELDS,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[BundInstitutionSummary] = [
BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits
]
return BundInstitutionSummaryPage(
elements=institutions,
total=hits_block.get("total", {}).get("value", len(institutions)),
page=page,
size=size,
)
async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage:
"""Retrieves institutions based on a list of institution (Ausführende Stelle) names.
Args:
institution_names (List[str]): A list of institution names to retrieve.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the provided names.
"""
logger.debug(f"Fetching institutions for names: {institution_names}")
if not institution_names:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=0,
size=len(institution_names),
query={
"terms": {
"Ausführende Stelle.keyword": institution_names,
}
},
source=_INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions(
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term, matching against both the
executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields.
Args:
query (str): The search term to autocomplete institutions with.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
logger.debug(f"Autocomplete institutions for query: {query}")
if not query:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=page,
size=size,
query={
"bool": {
"should": [
{
"match_phrase_prefix": {
"Ausführende Stelle": {
"query": query,
"max_expansions": 50,
"boost": 2,
}
}
},
{
"match_phrase_prefix": {
"Zuwendungsempfänger": {
"query": query,
"max_expansions": 50,
}
}
},
],
"minimum_should_match": 1,
}
},
source=source or _INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions_for_selector(
query: str, page: int = 0, size: int = 10
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term for use in a selector component.
Args:
query (str): The search term to filter institutions by (partial matches allowed).
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
return await autocomplete_institutions(
query=query,
page=page,
size=size,
source=_INSTITUTION_SOURCE_FIELDS,
)
@@ -5,7 +5,7 @@ from collections import defaultdict
from inse.config import get_settings
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.authors.v2.model import AuthorPage
from inse.authors.v2.model import AuthorPage,Author
from inse.authors.v2.service import get_authors_by_ids
# Import base models
from inse.models.cordis_eu_project import CordisEuProject
@@ -46,7 +46,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLin
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.projects.model import EuCordisProjectType, EuCordisProjectSummary
from inse.projects.model import (
EuCordisProjectType,
EuCordisProjectSearchPage,
@@ -56,7 +56,7 @@ from inse.projects.model import (
EuCordisEurosciVocSummary,
)
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
from inse.models.openalex.topic import Topic
settings = get_settings()
logger = logging.getLogger(__name__)
@@ -96,24 +96,13 @@ _HEU_ENTITY_CONFIGS = [
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
]
async def get_enriched_cordis_project_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
Fetches and enriches a single Cordis EU project by its ID across all programme types.
Args:
project_id: The project ID to fetch.
Returns:
The enriched detailed project model, or None if not found.
"""
if not project_id:
return None
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
@@ -130,32 +119,143 @@ async def get_enriched_cordis_project_by_id(
index = hit.get("_index", "")
source = hit.get("_source", {})
program_type = _determine_program_type_from_index(index)
project_type = EuCordisProjectType.from_index_name(index)
enrichers = {
"fp7": _enrich_fp7_project,
"h2020": _enrich_h2020_project,
"heu": _enrich_heu_project,
EuCordisProjectType.FP7: _enrich_fp7_project,
EuCordisProjectType.H2020: _enrich_h2020_project,
EuCordisProjectType.HEU: _enrich_heu_project,
}
enricher = enrichers.get(program_type)
enricher = enrichers.get(project_type)
if enricher is None:
logger.warning(f"Unknown programme type for index: {index}")
return CordisEuProject.model_validate(source)
return await enricher(project_id, source)
return await enricher(project_id, source, project_type)
# helpers
def _determine_program_type_from_index(index: str) -> str:
"""Determines the programme type from the Elasticsearch index name."""
index_lower = index.lower()
if "fp7" in index_lower:
return "fp7"
if "horizon_2020" in index_lower:
return "h2020"
if "heu" in index_lower or "horizon_europe" in index_lower:
return "heu"
return "unknown"
async def _fetch_openalex_author_data_for_project_ids(
project_ids: List[str],
) -> Tuple[Dict[str, AuthorPage], Dict[str, Dict[str, List[Author]]]]:
"""
Single batched fetch that returns, per project_id:
- an AuthorPage of all OpenAlex authors across all of the project's publications
- a map of raw DOI -> List[Author] for attaching authors to individual publications
"""
if not project_ids:
return {}, {}
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=["projectID", "doi", "qaProcessedDoi"],
size=10000,
)
dois_by_project: Dict[str, Set[str]] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
pid = source.get("projectID")
if not pid:
continue
dois_by_project.setdefault(pid, set())
doi = source.get("doi")
qa_processed_doi = source.get("qaProcessedDoi")
if doi:
dois_by_project[pid].add(doi)
elif qa_processed_doi:
dois_by_project[pid].add(qa_processed_doi)
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
# single ES call for the whole batch, keyed by raw DOI
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
all_author_ids = list({aid for ids in author_ids_by_doi.values() for aid in ids})
# single ES call to fetch all Author objects across every project
author_page = await get_authors_by_ids(author_ids=all_author_ids)
authors_by_id = {author.id: author for author in author_page.elements}
author_page_by_project: Dict[str, AuthorPage] = {}
doi_author_map_by_project: Dict[str, Dict[str, List[Author]]] = {}
for pid in project_ids:
dois = dois_by_project.get(pid, set())
doi_authors: Dict[str, List[Author]] = {}
project_author_ids: Set[str] = set()
for doi in dois:
ids_for_doi = author_ids_by_doi.get(doi, [])
doi_authors[doi] = [authors_by_id[aid] for aid in ids_for_doi if aid in authors_by_id]
project_author_ids.update(ids_for_doi)
doi_author_map_by_project[pid] = doi_authors
authors_for_project = [authors_by_id[aid] for aid in project_author_ids if aid in authors_by_id]
author_page_by_project[pid] = AuthorPage(
elements=authors_for_project,
total=len(authors_for_project),
page=0,
size=len(authors_for_project),
)
return author_page_by_project, doi_author_map_by_project
async def get_openalex_authors_for_cordis_project_ids(
project_ids: List[str],
) -> Dict[str, AuthorPage]:
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
author_page_by_project, _ = await _fetch_openalex_author_data_for_project_ids(project_ids)
return author_page_by_project
async def _fetch_authors_and_topics_for_project(
project_id: str,
project_type: EuCordisProjectType,
) -> Tuple[Optional[AuthorPage], List[Topic], Dict[str, List[Author]]]:
"""Fetches OpenAlex authors (project-level + per-DOI map) and mapped topics for a single project."""
(author_page_by_project, doi_author_map_by_project), topics_lookup = await asyncio.gather(
_fetch_openalex_author_data_for_project_ids([project_id]),
get_openalex_topics_for_eu_projects({project_type: [project_id]}),
)
author_page = author_page_by_project.get(project_id)
doi_author_map = doi_author_map_by_project.get(project_id, {})
raw_topic_matches = sorted(
topics_lookup.get((project_type, project_id), []),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [
EuCordisProjectSummary.topic_from_match(match)
for match in raw_topic_matches
if isinstance(match, dict)
]
return author_page, topics, doi_author_map
def _attach_authors_to_publications(
publications: List[Any],
doi_author_map: Dict[str, List[Author]],
) -> List[Any]:
"""Sets oa_authors on each publication by matching its doi/qaProcessedDoi against doi_author_map."""
for pub in publications:
doi = getattr(pub, "doi", None)
qa_processed_doi = getattr(pub, "qa_processed_doi", None)
authors = doi_author_map.get(doi) if doi else None
if not authors and qa_processed_doi:
authors = doi_author_map.get(qa_processed_doi)
pub.oa_authors = authors or []
return publications
async def _fetch_related_entities_parallel(
@@ -244,10 +344,10 @@ async def _fetch_related_entities(
return grouped
async def _enrich_fp7_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[Fp7ProjectDetails]:
"""Enriches a single FP7 project with all related data."""
try:
@@ -256,42 +356,68 @@ async def _enrich_fp7_project(
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return Fp7ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[H2020ProjectDetails]:
"""Enriches a single H2020 project with all related data."""
try:
project = H2020Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return H2020ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[HEUProjectDetails]:
"""Enriches a single Horizon Europe project with all related data."""
try:
project = HEUProject.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return HEUProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return HEUProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
@@ -432,7 +558,6 @@ async def get_eu_project_ids_by_organization_filters(
for org_name in organization_names:
if name and org_name.lower() in name.lower():
project_org_matches[project_id].add(f"name:{org_name.lower()}")
print(f"Project organization matches for {project_type}: {project_org_matches}")
required_orgs = set()
# Add ID requirements
@@ -454,7 +579,6 @@ async def get_eu_project_ids_by_organization_filters(
continue
result[project_type].append(project_id)
print(f"Final project IDs by type: {result}")
return result
async def get_eu_organizations_for_projects(
@@ -580,9 +704,13 @@ async def get_eu_euroscivoc_for_projects(
return lookup
async def search_eu_cordis_projects(
page: int,
size: int,
class _NoMatchingEuProjects(Exception):
"""Internal sentinel: some filter resolved to zero matching project IDs,
so the overall query can short-circuit to an empty result without
hitting Elasticsearch again."""
async def _build_eu_cordis_search_query(
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
@@ -597,16 +725,16 @@ async def search_eu_cordis_projects(
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
) -> Tuple[Dict[str, Any], List[EuCordisProjectType], List[Any]]:
"""
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
Mirrors DFG behavior:
- fuzzy=True + topic_ids => OpenAlex topic mapping lookup
- filter_topic_ids are always applied independently
- selected organizations/topics must ALL match
Builds the (query, project_types, indices) tuple shared by every EU CORDIS
project search/aggregation. Centralizing this means the filters applied to
the results table and to any derived aggregation (e.g. funding-over-time)
can never drift apart.
Raises _NoMatchingEuProjects if any filter resolves to zero project IDs,
so callers can short-circuit to an empty result without a wasted query.
"""
if not project_types:
project_types = [
@@ -622,7 +750,7 @@ async def search_eu_cordis_projects(
# === Author filter resolved in service layer ===
if author_project_ids is not None:
if not author_project_ids:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append({"terms": {"id": author_project_ids}})
@@ -635,7 +763,7 @@ async def search_eu_cordis_projects(
topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type)
if not topic_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(topic_filter)
@@ -690,7 +818,7 @@ async def search_eu_cordis_projects(
topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type)
if not topic_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(topic_filter)
@@ -704,7 +832,7 @@ async def search_eu_cordis_projects(
org_filter = _eu_project_type_index_filter(org_project_ids_by_type)
if not org_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(org_filter)
@@ -767,12 +895,64 @@ async def search_eu_cordis_projects(
country_filter = _eu_project_type_index_filter(country_project_ids_by_type)
if not country_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(country_filter)
query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
return query, project_types, indices
async def search_eu_cordis_projects(
page: int,
size: int,
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
author_project_ids: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
"""
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
Mirrors DFG behavior:
- fuzzy=True + topic_ids => OpenAlex topic mapping lookup
- filter_topic_ids are always applied independently
- selected organizations/topics must ALL match
"""
try:
query, project_types, indices = await _build_eu_cordis_search_query(
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
except _NoMatchingEuProjects:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
sort_direction = sort_direction.lower()
if sort_direction not in ["asc", "desc"]:
sort_direction = "asc"
@@ -862,7 +1042,108 @@ async def search_eu_cordis_projects(
page=page,
size=size,
)
async def get_eu_cordis_projects_funding_data(
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
author_project_ids: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
fuzzy: bool = False,
) -> List[Dict[str, Any]]:
"""
Fetches ONLY the fields needed for a funding-over-time aggregation
(id, startDate, endDate, ecMaxContribution) for every EU CORDIS project
matching the given filters.
This intentionally skips the author/organization/CORDIS-topic/EuroSciVoc/
OpenAlex-topic enrichment that `search_eu_cordis_projects` performs per
project, since none of that is needed to compute funding totals. That
enrichment is what makes the funding-over-time endpoint slow for
institutions with many projects - this function avoids it entirely.
"""
try:
query, _, indices = await _build_eu_cordis_search_query(
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
except _NoMatchingEuProjects:
return []
results: List[Dict[str, Any]] = []
page_size = 5000
search_after: Optional[List[Any]] = None
while True:
body: Dict[str, Any] = {
"size": page_size,
"track_total_hits": False,
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
"query": query,
# "id" is unique per project and used elsewhere as a term-filter
# field, so it's mapped as keyword - safe + deterministic sort
# key for search_after pagination across an arbitrarily large
# result set.
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
}
if search_after is not None:
body["search_after"] = search_after
response = await elasticsearch.search(
index=indices,
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit.get("_source", {})
results.append(
{
"id": source.get("id"),
"start_date": source.get("startDate"),
"end_date": source.get("endDate"),
"ec_max_contribution": source.get("ecMaxContribution"),
}
)
if len(hits) < page_size:
break
search_after = hits[-1].get("sort")
if not search_after:
break
return results
def _to_openalex_doi_url(raw_doi: str) -> str:
"""CORDIS stores bare DOIs (e.g. '10.1093/toxsci/kfs018');
OpenAlex works index stores full URLs ('https://doi.org/10.1093/toxsci/kfs018')."""
+168 -51
View File
@@ -46,7 +46,45 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option
except Exception as e:
logger.exception(f"Error fetching institution names for ids {institution_ids}: {str(e)}")
return []
async def get_institution_ids_by_institution_aliases(institution_aliases: list[str]) -> list[int]:
if not institution_aliases:
return []
response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES,
cluster=ESCluster.INSE,
body={
"size": 10000,
"_source": ["institute_id"],
"query": {
"bool": {
"should": [
clause
for name in institution_aliases
for clause in (
# {"match": {"root_name_de": {"query": name, "operator": "and"}}},
# {"match": {"root_name_en": {"query": name, "operator": "and"}}},
# {"match": {"institute_name_de": {"query": name, "operator": "and"}}},
# {"match": {"institute_name_en": {"query": name, "operator": "and"}}},
{"match_phrase": {"root_name_de":name}},
{"match_phrase": {"root_name_en":name}},
{"match_phrase": {"institute_name_de":name}},
{"match_phrase": {"institute_name_en": name}},
)
],
"minimum_should_match": 1,
}
}
},
)
return list(
{
hit["_source"]["institute_id"]
for hit in response.get("hits", {}).get("hits", [])
if hit.get("_source", {}).get("institute_id") is not None
}
)
async def get_person_ids_by_institution_ids(
institution_ids: list[int],
) -> list[int]:
@@ -59,10 +97,13 @@ async def get_person_ids_by_institution_ids(
body={
"size": 10000,
"_source": ["person_id"],
"query": {
"terms": {
"institute_id": institution_ids
}
"query": { "bool":{
"should": [
{"terms": {"institute_id": institution_ids}},
{"terms": {"root_id": institution_ids}},
],
"minimum_should_match": 1,
}
}
},
)
@@ -74,6 +115,72 @@ async def get_person_ids_by_institution_ids(
if hit.get("_source", {}).get("person_id") is not None
}
)
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, Set[str]] = defaultdict(set)
page_size = 1000
from_ = 0
while True:
body = {
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"topic_matches.topic_id.keyword": topic_ids
}
},
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit["_source"]
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if len(hits) < page_size:
break
from_ += page_size
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
even if the topics are distributed across multiple documents for the same project.
@@ -137,63 +244,73 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[int, List[Dict[str, Any]]]:
"""Fetches OpenAlex topic matches for the given DFG project IDs.
Args:
project_ids (List[str]): The DFG project IDs to fetch topics for.
Returns:
Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts,
each containing topic_id, topic_display_name, domain, field, subfield, rank.
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
topic_lookup: Dict[int, List[Dict[str, Any]]] = {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
page_size = 1000
from_ = 0
# print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}")
while True:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
cluster=ESCluster.INSE,
body={
"size": page_size,
"from": from_,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
},
)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of DFG project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
for hit in hits:
source = hit["_source"]
project_id = int(source.get("project_id"))
if project_id is None:
continue
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
body=body,
cluster=ESCluster.INSE
)
topic_lookup.setdefault(project_id, []).extend(topic_matches)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[str(pid)] = src.get("topic_matches", [])
if len(hits) < page_size:
break
from_ += page_size
#logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.")
return topic_lookup
return lookup
async def get_person_institutes(
person_ids: list[int],
+29 -8
View File
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from inse.projects.bund_institutions.model import BundInstitutionSummary
from typing import Union
class ProjectType(StrEnum):
@@ -75,6 +76,11 @@ class BundProjectSummary(BundProject):
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
institution: Optional[BundInstitutionSummary] = Field(
default=None,
description="The executing agency / recipient institution for this project, "
"derived from the project's own agency fields.",
)
@classmethod
def from_hit(cls, hit: dict) -> "BundProjectSummary":
@@ -91,7 +97,6 @@ class BundProjectSummary(BundProject):
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
print(f"oa_topics: {oa_topics}")
return cls(
funding_code=source.get("Förderkennzeichen"),
department=source.get("Ressort"),
@@ -110,8 +115,8 @@ class BundProjectSummary(BundProject):
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
funding_start=source.get("Förderbeginn"),
funding_end=source.get("Förderende"),
funding_start=source.get("funding_start"),
funding_end=source.get("funding_end"),
grant_amount=source.get("Fördersumme"),
funding_profile=source.get("Förderprofil"),
joint_project=source.get("Verbundprojekt"),
@@ -122,6 +127,7 @@ class BundProjectSummary(BundProject):
new=source.get("neu"),
duration=source.get("Laufzeit"),
oa_topics=oa_topics,
institution=BundInstitutionSummary.from_source(source),
)
@staticmethod
@@ -258,19 +264,33 @@ class DfgProjectSummary(BaseModel):
institution = None
if person.get("institute_id") is not None:
institution = DfgInstitutionSummary(
institute = DfgInstitutionSummary(
id=person["institute_id"],
institute_name_de=person.get("institute_name_de"),
institute_name_en=person.get("institute_name_en"),
address_country_de=person.get("address_country_de"),
address_country_en=person.get("address_country_en"),
root_id=person["root_id"],
root_name_de=person.get("root_name_de"),
root_name_en=person.get("root_name_en"),
root_id=None,
root_name_de=None,
root_name_en=None,
)
institutions[person["institute_id"]] = institution
institutions[f"institute:{person['institute_id']}"] = institute
if person.get("root_id") is not None:
root_institution = DfgInstitutionSummary(
id=person["root_id"],
institute_name_de=person.get("root_name_de"),
institute_name_en=person.get("root_name_en"),
address_country_de=person.get("address_country_de"),
address_country_en=person.get("address_country_en"),
root_id=None,
root_name_de=None,
root_name_en=None,
)
institutions[f"root:{person['root_id']}"] = root_institution
if person.get("person_id") is not None:
project_persons.append(
DfgPersonSummary(
@@ -284,6 +304,7 @@ class DfgProjectSummary(BaseModel):
)
)
topics_raw = source.get("topics") or []
print(f"Raw topics for DFG project {hit.get('_id', '')}: {topics_raw}")
topics = None
if isinstance(topics_raw, list) and topics_raw:
# Sort by rank if present, so the most relevant topic comes first
@@ -1,6 +1,6 @@
import json
import logging
from typing import Any, Dict, List, Optional, Set, Tuple
from typing import Any, Dict, List, Optional, Set
import urllib
from inse.config import get_settings
@@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects, get_institution_ids_by_institution_aliases
settings = get_settings()
@@ -29,66 +29,6 @@ logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
DFG_PERSON_FIELDS: List[str] = [
"Antragsteller",
"Antragstellerin",
"Antragstellerinnen",
"Antragstellerinnen / Antragsteller",
"Beteiligte Person",
"Beteiligte Personen",
"Co-Sprecher",
"Co-Sprecherinnen / Co-Sprecher",
"Ehemalige Antragsteller",
"Ehemalige Antragstellerin",
"Ehemalige Antragstellerinnen",
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
"Ehemaliger Antragsteller",
"Gastgeber",
"Gastgeberin",
"Gastgeberinnen",
"Gastgeberinnen / Gastgeber",
"Kooperationspartner",
"Kooperationspartnerin",
"Kooperationspartnerinnen",
"Kooperationspartnerinnen / Kooperationspartner",
"Leiter",
"Leiterin",
"Leiterinnen",
"Leiterinnen / Leiter",
"Mitantragsteller",
"Mitantragstellerin",
"Mitantragstellerinnen",
"Mitantragstellerinnen / Mitantragsteller",
"Mitverantwortlich",
"Mitverantwortlich(e)",
"Mitverantwortliche",
"Sprecher",
"Sprecher (IGK-Partner)",
"Sprecherin",
"Sprecherin (IGK-Partner)",
"Sprecherinnen",
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
"Sprecherinnen / Sprecher",
"Teilprojektleiter",
"Teilprojektleiterin",
"Teilprojektleiterinnen",
"Teilprojektleiterinnen / Teilprojektleiter",
"ausländ. Mitantragstellerin",
"ausländ. Mitantragstellerinnen",
"ausländ. Mitantragstellerinnen / ausländische Mitantragsteller",
"ausländische Mitantragsteller",
"ausländischer Mitantragsteller",
"beteiligte Wissenschaftler",
"beteiligte Wissenschaftlerin",
"beteiligte Wissenschaftlerinnen",
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
"beteiligter Wissenschaftler",
"person_creater_name",
"stellvertr. Sprecher",
"stellvertr. Sprecherin",
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
]
# BUND
@@ -204,10 +144,13 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
query=query,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
elastic_id = hit["_id"]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=[elastic_id])
hit["_source"]["oa_topics"] = topic_lookup.get(elastic_id, [])
details = BundProjectDetails.from_elastic_hit(hit=hit)
return details
return None
@@ -380,7 +323,6 @@ async def get_dfg_project_ids_by_names(names: List[str]) -> List[str]:
for project in hit.get("_source", {}).get("projects", [])
if "project_id" in project
}
print(f"Retrieved project IDs for names {len(project_ids)}: {project_ids}")
return list(project_ids)
async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]:
@@ -405,8 +347,9 @@ async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]:
async def search_dfg_projects(
page: int,
size: int,
institution_aliases: Optional[List[str]] = None,
project_ids: Optional[List[int]] = None,
institution_ids: Optional[List[int]] = None,
institution_ids: Optional[List[int]] = [],
names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
@@ -466,7 +409,7 @@ async def search_dfg_projects(
"query": {},
}
must_clauses: List[Dict[str, Any]] = []
must_clauses: List[Dict[str, Any]] = []
if project_ids:
must_clauses.append({"terms": {"id": project_ids}})
# === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search ===
@@ -567,6 +510,24 @@ async def search_dfg_projects(
if name_must_clauses:
must_clauses.append({"bool": {"must": name_must_clauses}})
if institution_aliases:
matching_institution_ids = await get_institution_ids_by_institution_aliases(
institution_aliases=institution_aliases
)
if not matching_institution_ids:
return DfgProjectPage(elements=[], total=0, page=page, size=size)
matching_person_ids = await get_person_ids_by_institution_ids(
institution_ids=matching_institution_ids
)
must_clauses.append(
{
"nested": {
"path": "persons",
"query": {"terms": {"persons.person_id": matching_person_ids}},
}
}
)
if institution_ids:
matching_person_ids = await get_person_ids_by_institution_ids(
institution_ids=institution_ids
@@ -607,7 +568,7 @@ async def search_dfg_projects(
sort_config = {"id": {"order": sort_direction}}
body["sort"] = [sort_config]
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
@@ -631,9 +592,7 @@ async def search_dfg_projects(
for hit in hits:
source = hit["_source"]
project_id = source["id"]
source["topics"] = topic_lookup.get(project_id, [])
source["topics"] = topic_lookup.get(str(project_id), [])
persons = source.get("persons", [])
for person in persons:
person_id = person.get("person_id")
@@ -679,6 +638,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
Returns:
Optional[DfgProjectDetails]: The project details or None if not found.
"""
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
query = {"ids": {"values": [project_id]}}
response = await elasticsearch.search(
@@ -690,79 +650,43 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
if hits:
hit = hits[0]
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
details = DfgProjectDetails.from_elastic_hit(hit=hit)
return details
return None
#BUND
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"terms": {
"topic_matches.topic_id": topic_ids
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "project_id.keyword",
"size": 10000
def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]:
should = []
for year in years:
year = str(year).strip()
if not year:
continue
should.append(
{
"range": {
field: {
"gte": f"01.01.{year}",
"lte": f"31.12.{year}",
}
}
}
)
return {
"bool": {
"should": should,
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
return [bucket["key"] for bucket in buckets]
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def search_bund_projects_with_filters(
executing_agency: Optional[List[str]] = None,
institution_ids: Optional[List[int]] = None,
oa_institution_aliases: Optional[List[str]] = None,
raw_oa_institution_id: Optional[str] = None,
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
@@ -776,12 +700,18 @@ async def search_bund_projects_with_filters(
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
"""
from_ = page * size
skip_topic_enrichment: when True, skips the extra OpenAlex-topics lookup
used to populate `oa_topics` on each result. Callers that only need core
project fields (e.g. funding-over-time aggregation) should set this to
avoid the unnecessary ES round trip.
"""
from_ = page * size
#institution_ids = ["I62318514"]
# Fields we need to build BundProject objects (validation aliases match these exact names)
source_fields = [
"Förderkennzeichen",
@@ -812,7 +742,6 @@ async def search_bund_projects_with_filters(
"datum",
"neu",
"Laufzeit",
# Also include funding_start/end for sorting and filtering (they may also be needed)
"funding_start",
"funding_end",
]
@@ -825,13 +754,28 @@ async def search_bund_projects_with_filters(
}
must_clauses: List[Dict[str, Any]] = []
if oa_institution_aliases:
must_clauses.append(
{
"bool": {
"should": [
clause
for name in oa_institution_aliases
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
}
)
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
must_clauses.append({"terms": {"_id": matching_project_ids}})
elif keywords:
keyword_clauses = []
@@ -841,7 +785,7 @@ async def search_bund_projects_with_filters(
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt"], # searching title/acronym field
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
"type": "phrase_prefix",
"max_expansions": 100,
}
@@ -854,21 +798,38 @@ async def search_bund_projects_with_filters(
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
must_clauses.append({"terms": {"_id": matching_filter_ids}})
if title:
must_clauses.append({
"multi_match": {
"query": title,
"fields": ["Verbundprojekt"],
"fields": ["Verbundprojekt","Thema"], # searching title field
"type": "phrase_prefix",
"max_expansions": 100,
}
})
# print(f"Executing BUND project search with institution_ids: {institution_ids}, executing_agency: {executing_agency}, funding_arts: {funding_arts}, countries: {countries}, funding_start_years: {funding_start_years}, funding_end_years: {funding_end_years}")
if executing_agency:
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
# institution_names = await institutions_search_client.get_institution_aliases_by_oa_institution_id(executing_agency[0].split("/")[-1])
# institution_page = await institutions_search_client.get_institutions_by_alias(alias=institution_names[0])
# print(f"Retrieved institution names for IDs {executing_agency}: {institution_names}")
# print(f"Retrieved institution page for names {institution_names}: {institution_page}")
# if not institution_names:
# return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({
"bool": {
"should": [
clause
for name in executing_agency
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
})
if funding_arts:
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
@@ -876,13 +837,12 @@ async def search_bund_projects_with_filters(
must_clauses.append({"terms": {"Staat.keyword": countries}})
if funding_start_years:
must_clauses.append({"terms": {"funding_start": funding_start_years}})
must_clauses.append(_bund_year_filters("funding_start", funding_start_years))
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
# === Sorting ===
sort_by = sort_by.strip().lower()
sort_direction = sort_direction.strip().lower()
@@ -900,7 +860,7 @@ async def search_bund_projects_with_filters(
sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}}
body["sort"] = [sort_config]
# print(f"Executing BUND project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
@@ -911,12 +871,13 @@ async def search_bund_projects_with_filters(
hits = response.get("hits", {}).get("hits", [])
# Enrich with OpenAlex topics
project_ids = [hit["_id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
# Enrich with OpenAlex topics (skipped for callers that don't need them,
# e.g. funding-over-time aggregation, to avoid an unnecessary ES call)
if not skip_topic_enrichment:
project_ids = [hit["_id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
return _complete_response_to_bund_project_page(response, page, size)
@@ -1084,4 +1045,4 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject:
else:
raise ValueError(
"The provided hit does not belong to a recognized project index."
)
)
+162 -12
View File
@@ -100,7 +100,9 @@ async def get_single_dfg_project(
response_model_by_alias=False,
)
async def search_bund_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
executing_agency: Annotated[
Optional[List[str]],
Query(description="Executing Agencies (Ausführende Stellen) to filter by."),
@@ -137,9 +139,9 @@ async def search_bund_projects(
Optional[List[str]],
Query(description="Organization countries."),
] = None,
institution_ids: Annotated[
Optional[List[str]],
Query(description="Institution IDs to filter by."),
raw_oa_institution_id: Annotated[
Optional[str],
Query(description="The ID of the institution to filter by."),
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
@@ -154,6 +156,7 @@ async def search_bund_projects(
] = False,
) -> BundProjectPage:
return await projects_service.search_bund_projects_with_filters(
institutions_search_client=institutions_search_client,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
@@ -163,7 +166,7 @@ async def search_bund_projects(
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
institution_ids=institution_ids,
raw_oa_institution_id=raw_oa_institution_id,
page=page,
size=size,
sort_by=sort_by,
@@ -432,7 +435,11 @@ async def get_single_eu_cordis_project(
@router.get(
"/institution/bund/funding-over-time",
summary="Get funding over time for bund projects.",
description="Returns the funding over time for bund projects associated with the specified institution.",
description=(
"Returns the funding over time for BUND projects. Accepts the same "
"filters as /bund/search, so the funding total can be made to match "
"whatever the results table is currently filtered to."
),
operation_id="getInstitutionBundProjectsFundingOverTime",
responses={
status.HTTP_200_OK: {
@@ -448,19 +455,73 @@ async def get_institution_bund_projects_funding_over_time(
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str, Query(description="The institution ID to filter by.")
],
Optional[str], Query(description="The institution ID to filter by.")
] = None,
executing_agency: Annotated[
Optional[List[str]],
Query(description="Executing Agencies (Ausführende Stellen) to filter by."),
] = None,
funding_arts: Annotated[
Optional[List[str]],
Query(description="Project types to include: fp7, h2020, heu."),
] = None,
title: Annotated[
Optional[str],
Query(description="Project title/acronym search."),
] = None,
keywords: Annotated[
Optional[List[str]],
Query(description="Raw keywords to search in title/objective/keywords/topics."),
] = None,
topic_ids: Annotated[
Optional[List[str]],
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
] = None,
filter_topic_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
] = None,
funding_start_years: Annotated[
Optional[List[str]],
Query(description="Funding start years."),
] = None,
funding_end_years: Annotated[
Optional[List[str]],
Query(description="Funding end years."),
] = None,
countries: Annotated[
Optional[List[str]],
Query(description="Organization countries."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
fuzzy=fuzzy,
)
@router.get(
"/institution/eu/funding-over-time",
summary="Get funding over time for EU projects.",
description="Returns the funding over time for EU projects associated with the specified institution.",
description=(
"Returns the funding over time for EU CORDIS projects. Accepts the "
"same filters as /eu/search, so the funding total can be made to "
"match whatever the results table is currently filtered to."
),
operation_id="getInstitutionCordisEuProjectsFundingOverTime",
responses={
status.HTTP_200_OK: {
@@ -476,12 +537,93 @@ async def get_institution_cordis_eu_projects_funding_over_time(
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str, Query(description="The institution ID to filter by.")
],
Optional[str],
Query(description="OpenAlex institution ID to filter by."),
] = None,
author_id: Annotated[
Optional[str],
Query(description="OpenAlex author ID to filter by."),
] = None,
author_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."),
] = None,
organization_ids: Annotated[
Optional[List[str]],
Query(description="CORDIS organisation IDs. All selected organizations must match."),
] = None,
organization_names: Annotated[
Optional[List[str]],
Query(description="CORDIS organization names. All selected organizations must match."),
] = None,
project_types: Annotated[
Optional[List[EuCordisProjectType]],
Query(description="Project types to include: fp7, h2020, heu."),
] = None,
title: Annotated[
Optional[str],
Query(description="Project title/acronym search."),
] = None,
keywords: Annotated[
Optional[List[str]],
Query(description="Raw keywords to search in title/objective/keywords/topics."),
] = None,
topic_ids: Annotated[
Optional[List[str]],
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
] = None,
filter_topic_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
] = None,
funding_start_years: Annotated[
Optional[List[str]],
Query(description="Funding start years."),
] = None,
funding_end_years: Annotated[
Optional[List[str]],
Query(description="Funding end years."),
] = None,
countries: Annotated[
Optional[List[str]],
Query(description="Organization countries."),
] = None,
framework_programmes: Annotated[
Optional[List[str]],
Query(description="Framework programme filters."),
] = None,
funding_schemes: Annotated[
Optional[List[str]],
Query(description="Funding scheme filters."),
] = None,
statuses: Annotated[
Optional[List[str]],
Query(description="Project status filters."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_ids=author_ids,
organization_ids=organization_ids,
organization_names=organization_names,
project_types=project_types,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
@@ -500,6 +642,12 @@ async def get_institution_cordis_eu_projects_funding_over_time(
response_model_by_alias=False,
)
async def get_dfg_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
Optional[str], Query(description="The openalex institution ID to filter by.")
] = None,
author_id: Annotated[Optional[str], Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[Optional[List[int]], Query(description="The dfg author IDs to filter by.")] = None,
institution_ids: Annotated[
@@ -557,6 +705,8 @@ async def get_dfg_projects(
fuzzy,
)
return await projects_service.get_dfg_projects_by_author_id(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
@@ -612,4 +762,4 @@ async def search_projects(
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
)
+183 -50
View File
@@ -29,6 +29,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from inse.projects.eu_cordis_projects_client import (
get_enriched_cordis_project_by_id,
get_eu_cordis_projects_funding_data,
search_eu_cordis_projects as _search_eu_cordis_projects_es,
)
from typing import Union
@@ -148,6 +149,8 @@ async def _get_dfg_project_ids_for_openalex_authors(
return list(set.intersection(*project_sets))
async def get_dfg_projects_by_author_id(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: Optional[str],
author_id: Optional[str],
author_filter_ids: Optional[List[int]],
institution_ids: Optional[List[int]],
@@ -206,16 +209,24 @@ async def get_dfg_projects_by_author_id(
"No author names found for author_filter_ids=%s",
author_filter_ids,
)
if institution_ids:
logger.debug(
"No institutions found for institution_ids=%s",
institution_ids,
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_aliases:
return DfgProjectPage(
elements=[],
page=page,
size=size,
total=0,
)
return await projects_search_client.search_dfg_projects(
page=page,
size=size,
institution_aliases=institution_aliases,
project_ids=author_project_ids,
names=filter_names or [],
institution_ids=institution_ids,
@@ -232,60 +243,164 @@ async def get_dfg_projects_by_author_id(
async def get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
raw_oa_institution_id: Optional[str] = None,
project_types: Optional[List[EuCordisProjectType]] = None,
author_id: Optional[str] = None,
author_ids: Optional[List[str]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
fuzzy: bool = False,
) -> InstitutionFunderSummary:
page = await search_eu_cordis_projects(
page=0,
size=10000,
raw_oa_institution_id=raw_oa_institution_id,
institutions_search_client=institutions_search_client,
"""
Computes funding-over-time for EU CORDIS projects, applying the exact same
filters as `search_eu_cordis_projects` (the table search). Uses a
lightweight, fully-paginated fetch of just id/dates/amount - no author,
organization or topic enrichment - so this stays fast even when a filter
combination matches many thousands of projects.
"""
resolved_organization_names: List[str] = list(organization_names or [])
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
resolved_organization_names.extend(institution_aliases)
all_author_ids: List[str] = []
if author_id:
all_author_ids.append(author_id)
all_author_ids.extend(author_ids or [])
author_project_ids = await _get_eu_project_ids_for_openalex_authors(
author_ids=all_author_ids
)
funding_data = await get_eu_cordis_projects_funding_data(
project_types=project_types,
organization_ids=organization_ids,
organization_names=resolved_organization_names or None,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
return _calculate_funding_over_time(
project_type=ProjectType.EU,
projects=page.elements,
funding_start_attr="start_date",
funding_end_attr="end_date",
funding_amount_attr="ec_max_contribution",
funding_entries=[
(entry.get("start_date"), entry.get("end_date"), entry.get("ec_max_contribution"))
for entry in funding_data
],
)
async def get_institution_bund_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
raw_oa_institution_id: Optional[str] = None,
executing_agency: Optional[List[str]] = None,
funding_arts: Optional[List[str]] = None,
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
fuzzy: bool = False,
) -> InstitutionFunderSummary:
"""
Computes funding-over-time for BUND projects, applying the exact same
filters as `search_bund_projects_with_filters` (the table search).
Skips the OpenAlex-topic enrichment step (irrelevant to a funding sum)
and pages through ALL matches rather than a single capped size=10000
request, so totals stay correct and fast for large result sets.
"""
logger.info(
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
f"Fetching funding over time for institution_id={raw_oa_institution_id}, "
f"executing_agency={executing_agency}, funding_arts={funding_arts}, "
f"title={title}, keywords={keywords}, topic_ids={topic_ids}, "
f"filter_topic_ids={filter_topic_ids}, funding_start_years={funding_start_years}, "
f"funding_end_years={funding_end_years}, countries={countries}, fuzzy={fuzzy}"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = await projects_search_client.search_bund_projects(
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
size=10000,
),
institution_names=institution_aliases,
)
if not institution_aliases:
return _calculate_funding_over_time(
project_type=ProjectType.BUND,
funding_entries=[],
)
page_size = 5000
page = 0
funding_entries: List[Any] = []
while True:
response = await projects_search_client.search_bund_projects_with_filters(
oa_institution_aliases=institution_aliases,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
page=page,
size=page_size,
fuzzy=fuzzy,
skip_topic_enrichment=True,
)
funding_entries.extend(
(element.funding_start, element.funding_end, element.grant_amount)
for element in response.elements
)
if len(response.elements) < page_size:
break
page += 1
return _calculate_funding_over_time(
project_type=ProjectType.BUND,
projects=response.elements,
funding_start_attr="funding_start",
funding_end_attr="funding_end",
funding_amount_attr="grant_amount",
funding_entries=funding_entries,
)
#Bund
async def search_bund_projects_with_filters(
institutions_search_client: InstitutionsSearchClient,
executing_agency: Optional[str],
institution_ids: Optional[List[str]],
raw_oa_institution_id: Optional[str],
title: Optional[str],
keywords: Optional[List[str]],
funding_arts: Optional[List[str]],
@@ -300,9 +415,24 @@ async def search_bund_projects_with_filters(
sort_direction: str = "asc",
fuzzy: bool = False,
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_aliases:
return BundProjectPage(
elements=[],
page=page,
size=size,
total=0,
)
return await projects_search_client.search_bund_projects_with_filters(
oa_institution_aliases=institution_aliases,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
institution_ids=[],
funding_arts=funding_arts,
title=title,
keywords=keywords,
@@ -320,20 +450,24 @@ async def search_bund_projects_with_filters(
def _calculate_funding_over_time(
project_type: ProjectType,
projects: List[Any],
funding_start_attr: str,
funding_end_attr: str,
funding_amount_attr: str,
funding_entries: List[Any],
) -> InstitutionFunderSummary:
"""
funding_entries: list of (funding_start, funding_end, funding_amount)
tuples. Each date value may be a date/datetime, an ISO date string, or
None; amount may be numeric or None.
"""
funding_per_year: Dict[int, float] = {}
for project in projects:
funding_start = getattr(project, funding_start_attr)
funding_end = getattr(project, funding_end_attr)
funding_amount = getattr(project, funding_amount_attr)
for funding_start, funding_end, funding_amount in funding_entries:
if not funding_start or not funding_end or not funding_amount:
continue
if isinstance(funding_start, str):
funding_start = datetime.date.fromisoformat(funding_start[:10])
if isinstance(funding_end, str):
funding_end = datetime.date.fromisoformat(funding_end[:10])
if hasattr(funding_start, "date"):
funding_start = funding_start.date()
if hasattr(funding_end, "date"):
@@ -511,7 +645,7 @@ async def search_eu_cordis_projects(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
resolved_organization_names.extend(institution_aliases)
print("Resolved organization names:", resolved_organization_names)
all_author_ids: List[str] = []
if author_id:
@@ -520,7 +654,6 @@ async def search_eu_cordis_projects(
author_project_ids = await _get_eu_project_ids_for_openalex_authors(
author_ids=all_author_ids
)
return await _search_eu_cordis_projects_es(
page=page,
size=size,
@@ -7,7 +7,7 @@ async def test_search_dfg_projects():
res = await projects_search_client.search_dfg_projects(
page=0,
size=5,
names=["Wolfgang Ahrens"],
names=["Bovensiepen"],
)
assert res is not None
assert res.total > 0
@@ -15,23 +15,19 @@ async def test_search_dfg_projects():
for element in res.elements:
assert element.id is not None
assert any(
all(part.lower() in name.lower() for part in "Wolfgang Ahrens".split())
all(part.lower() in name.lower() for part in "Bovensiepen".split())
for name in element.names
)
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
known_id = "164008977"
known_id = 164008977
project = await projects_search_client.get_dfg_project_by_id(known_id)
assert project is not None
assert project.id == known_id
assert project.title is not None
assert project.title_de is not None
assert any(
all(part.lower() in person.lower() for part in "Wolfgang Ahrens".split())
for person in project.associated_persons
)
assert any(
"Leibniz" in inst
for inst in project.institutions
all(part.lower() in person.full_name.lower() for part in "Wolfgang Ahrens".split())
for person in project.persons
)
@@ -0,0 +1,241 @@
from decimal import Decimal, ROUND_HALF_UP
from typing import Any
from inse.authors.v2.service import authors_currently_belong_to_institution
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfileStatus,
)
_SCORE_FIELD = "classification.applied_orientation_score"
_PRIMARY_CATEGORY_VALUES = {
category.value for category in WorkPrimaryCategory
}
def _author_filter(author_ids: list[str]) -> dict[str, Any]:
return {
"nested": {
"path": "authors",
"query": {"terms": {"authors.id": author_ids}},
}
}
def _orientation_profile_query(
author_ids: list[str],
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> dict[str, Any]:
filters: list[dict[str, Any]] = [_author_filter(author_ids)]
if publication_types:
filters.append(
{
"terms": {
"publication_type": [
publication_type.value
for publication_type in publication_types
]
}
}
)
if timespan:
filters.append(
{
"range": {
"publication_year": {
"gte": timespan.from_year,
"lte": timespan.to_year,
}
}
}
)
return {
"size": 0,
"query": {"bool": {"filter": filters}},
"aggs": {
"authors": {
"nested": {"path": "authors"},
"aggs": {
"selected": {
"filter": {"terms": {"authors.id": author_ids}},
"aggs": {
"by_author": {
"terms": {
"field": "authors.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"works": {
"reverse_nested": {},
"aggs": {
"classified": {
"filter": {
"exists": {
"field": (
"classification."
"primary_category"
)
}
},
"aggs": {
"by_primary_category": {
"terms": {
"field": (
"classification."
"primary_category"
),
"size": len(
WorkPrimaryCategory
),
}
}
},
},
"scored": {
"filter": {
"exists": {
"field": _SCORE_FIELD
}
},
"aggs": {
"average_score": {
"avg": {
"field": _SCORE_FIELD
}
}
},
},
},
}
},
}
},
}
},
}
},
}
def _rounded_score(value: float) -> int:
return int(Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def _profile_from_bucket(
author_id: str,
bucket: dict[str, Any] | None,
) -> AuthorOrientationProfile:
works = (bucket or {}).get("works", {})
classified_count = works.get("classified", {}).get("doc_count", 0)
category_buckets = (
works.get("classified", {})
.get("by_primary_category", {})
.get("buckets", [])
)
category_counts = {
WorkPrimaryCategory(category_bucket["key"]): category_bucket["doc_count"]
for category_bucket in category_buckets
if category_bucket.get("key") in _PRIMARY_CATEGORY_VALUES
}
scored = works.get("scored", {})
scored_count = scored.get("doc_count", 0)
average_score = scored.get("average_score", {}).get("value")
if classified_count == 0:
status = AuthorOrientationProfileStatus.NO_CLASSIFIED_PUBLICATIONS
elif scored_count == 0 or average_score is None:
status = AuthorOrientationProfileStatus.NO_ORIENTATION_SCORE
else:
score = _rounded_score(average_score)
return AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.AVAILABLE,
orientation_score=score,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
return AuthorOrientationProfile(
author_id=author_id,
status=status,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
async def orientation_profiles_for_authors(
author_ids: list[str],
institution_id: str | None,
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> list[AuthorOrientationProfile]:
"""Return protected orientation profiles in the requested author order.
Institution membership is checked for all authors in one query. Only
matching active members are included in the work-classification
aggregation, so restricted classification data is never retrieved.
"""
if not institution_id:
allowed_author_ids: set[str] = set()
else:
allowed_author_ids = await authors_currently_belong_to_institution(
author_ids,
institution_id,
)
restricted_profiles = {
author_id: AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.RESTRICTED,
)
for author_id in author_ids
if author_id not in allowed_author_ids
}
allowed_in_request_order = [
author_id for author_id in author_ids if author_id in allowed_author_ids
]
profiles_by_id: dict[str, AuthorOrientationProfile] = restricted_profiles
if allowed_in_request_order:
response = await elasticsearch.search(
index=ESIndex.WORK_CLASSIFICATIONS,
body=_orientation_profile_query(
allowed_in_request_order,
publication_types,
timespan,
),
)
buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
buckets_by_author = {
bucket.get("key"): bucket
for bucket in buckets
if isinstance(bucket.get("key"), str)
}
for author_id in allowed_in_request_order:
profiles_by_id[author_id] = _profile_from_bucket(
author_id,
buckets_by_author.get(author_id),
)
return [profiles_by_id[author_id] for author_id in author_ids]
@@ -0,0 +1,78 @@
from enum import StrEnum
from pydantic import BaseModel, Field, field_validator
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
class AuthorOrientationProfileStatus(StrEnum):
AVAILABLE = "available"
INSUFFICIENT_SCORED_PUBLICATIONS = "insufficient_scored_publications"
NO_CLASSIFIED_PUBLICATIONS = "no_classified_publications"
NO_ORIENTATION_SCORE = "no_orientation_score"
RESTRICTED = "restricted"
class AuthorOrientationProfilesRequest(BaseModel):
"""Filters used to compare the research orientation of selected authors."""
author_ids: list[str] = Field(
min_length=1,
max_length=4,
description="One to four unique OpenAlex author IDs.",
)
publication_types: list[PublicationType] = Field(
default_factory=list,
description="Optional publication-type filter. Empty means all types.",
)
timespan: Timespan | None = Field(
default=None,
description="Optional inclusive publication-year filter.",
)
@field_validator("author_ids")
@classmethod
def normalize_author_ids(cls, values: list[str]) -> list[str]:
normalized: list[str] = []
for value in values:
author_id = value.strip()
if not author_id:
raise ValueError("author IDs must not be empty")
if not author_id.startswith("https://openalex.org/"):
author_id = f"https://openalex.org/{author_id}"
if author_id in normalized:
raise ValueError("author IDs must be unique")
normalized.append(author_id)
return normalized
class AuthorOrientationProfile(BaseModel):
"""Aggregated research-orientation result for one selected author."""
author_id: str = Field(description="The full OpenAlex author ID.")
status: AuthorOrientationProfileStatus
orientation_score: int | None = Field(
default=None,
ge=0,
le=100,
description="Rounded mean score, available when at least one work has a score.",
)
primary_category_counts: dict[WorkPrimaryCategory, int] | None = Field(
default=None,
description=(
"Matching work counts grouped by primary category; hidden when "
"access is restricted."
),
)
classified_work_count: int | None = Field(
default=None,
ge=0,
description="Matching classified works; hidden when access is restricted.",
)
scored_work_count: int | None = Field(
default=None,
ge=0,
description="Matching works with an orientation score; hidden when restricted.",
)
+25
View File
@@ -7,6 +7,11 @@ from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.tags import Tags
from . import logic
from .orientation_profile_logic import orientation_profiles_for_authors
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfilesRequest,
)
from .model import (
AuthorMetricsRequest,
AuthorStaticStats,
@@ -117,3 +122,23 @@ async def static_stats(request: AuthorMetricsRequest):
request.author_ids,
request.company_status,
)
@router.post(
"/orientation-profiles",
response_model=List[AuthorOrientationProfile],
)
async def orientation_profiles(
request: AuthorOrientationProfilesRequest,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
):
"""Compare orientation scores for active members of the account institution."""
return await orientation_profiles_for_authors(
author_ids=request.author_ids,
institution_id=access_token_metadata.effective_institution_id,
publication_types=request.publication_types,
timespan=request.timespan,
)
+2
View File
@@ -24,3 +24,5 @@ class Tags(StrEnum):
DFG_INSTITUTIONS = "DFG Institutions"
DFG_PERSONS = "DFG Persons"
BACKGROUND_JOBS = "Background Jobs"
BUND_INSTITUTIONS = "BUND Institutions"
+8
View File
@@ -1,6 +1,14 @@
from enum import StrEnum
from inse.model import Page
from inse.models.openalex.topic import Topic
class TopicSortBy(StrEnum):
DISPLAY_NAME = "display_name"
WORKS_COUNT = "works_count"
CITED_BY_COUNT = "cited_by_count"
class TopicPageV2(Page[Topic]):
pass
+67 -2
View File
@@ -2,10 +2,12 @@ import logging
from typing import Annotated
import inse.topics.v2.service as topics_service
from fastapi import APIRouter, Query
from fastapi import APIRouter, Path, Query
from inse.model import SortDirection
from inse.models.openalex.topic import Topic
from inse.router_prefixes import RouterPrefixes
from inse.tags import Tags
from inse.topics.v2.model import TopicPageV2
from inse.topics.v2.model import TopicPageV2, TopicSortBy
logger = logging.getLogger(__name__)
@@ -13,6 +15,69 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.TOPICS_V2, tags=[Tags.TOPICS_V2])
@router.get(
"/search",
operation_id="searchTopics",
summary="Searches for topics based on the provided criteria.",
)
async def search_topics(
search_term: Annotated[
str | None,
Query(description="The term to search for in topic display names."),
] = None,
page: Annotated[
int,
Query(
description="The page number to retrieve.",
ge=0,
),
] = 0,
size: Annotated[
int,
Query(
description="The number of topics to retrieve per page.",
ge=1,
le=100,
),
] = 10,
sort_by: Annotated[
TopicSortBy,
Query(
description="The field to sort by.",
),
] = TopicSortBy.WORKS_COUNT,
sort_direction: Annotated[
SortDirection,
Query(
description="The direction to sort.",
),
] = SortDirection.DESCENDING,
) -> TopicPageV2:
return await topics_service.search_topics(
search_term=search_term,
page=page,
size=size,
sort_by=sort_by,
sort_direction=sort_direction,
)
@router.get(
"/single/{raw_oa_topic_id}",
operation_id="getTopicById",
summary="Returns a topic for a given topic ID.",
)
async def get_topic_by_id(
raw_oa_topic_id: Annotated[
str,
Path(description="The ID of the topic to retrieve."),
],
) -> Topic:
return await topics_service.get_topic_by_id_or_raise(
raw_oa_topic_id=raw_oa_topic_id
)
@router.get(
"/topics/id",
operation_id="getTopicsByIds",
+123 -7
View File
@@ -1,11 +1,11 @@
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.model import ESIndex, SortDirection
from inse.models.openalex.topic import Topic
from inse.topics.v2.model import TopicPageV2
from inse.topics.v2.model import TopicPageV2, TopicSortBy
async def search_topics(
async def _search_topics(
page: int = 0,
size: int = 10,
query: dict | None = None,
@@ -38,11 +38,80 @@ async def search_topics(
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
total_hits = hits_block.get("total", {}).get("value", 0)
topics: list[Topic] = []
for hit in hits:
_source = hit.get("_source", {})
topics.append(Topic.from_dict(_source)) # type: ignore
return TopicPageV2(elements=topics, total=len(topics), page=page, size=size)
return TopicPageV2(elements=topics, total=total_hits, page=page, size=size)
async def search_topics(
search_term: str | None = None,
page: int = 0,
size: int = 10,
sort_by: TopicSortBy = TopicSortBy.WORKS_COUNT,
sort_direction: SortDirection = SortDirection.DESCENDING,
) -> TopicPageV2:
"""Searches for topics based on a search term.
Args:
search_term (str | None): The term to search for in topic display names. Defaults to None.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of topics to retrieve per page. Defaults to 10.
sort_by (TopicSortBy, optional): The field to sort by. Defaults to TopicSortBy.WORKS_COUNT.
sort_direction (SortDirection, optional): The direction to sort. Defaults to SortDirection.DESCENDING.
Returns:
TopicPageV2: A page of topics matching the search term.
"""
sort = None
if sort_by in [TopicSortBy.DISPLAY_NAME]:
sort = [{f"{sort_by.value}.keyword": {"order": sort_direction.value}}]
else:
sort = [{sort_by.value: {"order": sort_direction.value}}]
query = None
if search_term:
search_terms = [
term.strip() for term in search_term.split(",") if term.strip()
]
if len(search_terms) == 1:
query = {
"match_phrase_prefix": {"display_name": search_terms[0]}
}
elif search_terms:
query = {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": search_term
}
}
for search_term in search_terms
],
"minimum_should_match": 1,
}
}
return await _search_topics(
page=page,
size=size,
query=query,
source=[
"id",
"display_name",
"description",
"subfield",
"field",
"domain",
"works_count",
"cited_by_count",
],
sort=sort,
)
async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
@@ -54,7 +123,7 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
Returns:
TopicPageV2: A page of topics matching the autocomplete criteria.
"""
return await search_topics(
return await _search_topics(
page=0,
size=10,
query={"match_phrase_prefix": {"display_name": query}},
@@ -68,6 +137,53 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
)
async def get_topic_by_id(raw_oa_topic_id: str) -> Topic | None:
"""Retrieves a topic based on its ID.
Args:
raw_oa_topic_id (str): The ID of the topic to retrieve.
Returns:
Topic | None: The topic matching the provided ID, or None if not found.
"""
response = await elasticsearch.get(
index=ESIndex.OPENALEX_TOPICS,
doc_id=raw_oa_topic_id,
source=[
"id",
"display_name",
"description",
"subfield",
"field",
"domain",
"works_count",
"cited_by_count",
],
)
if response.get("found"):
_source = response.get("_source", {})
return Topic.from_dict(_source) # type: ignore
return None
async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
"""Retrieves a topic based on its ID, raising an exception if not found.
Args:
raw_oa_topic_id (str): The ID of the topic to retrieve.
Raises:
NotFoundException: If the topic with the specified ID is not found.
Returns:
Topic: The topic matching the provided ID.
"""
topic = await get_topic_by_id(raw_oa_topic_id)
if topic is None:
raise NotFoundException(f"Topic with ID {raw_oa_topic_id} not found.")
return topic
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
"""Retrieves topics based on a list of topic IDs.
@@ -80,7 +196,7 @@ async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
if not topic_ids:
return TopicPageV2(elements=[], total=0, page=0, size=0)
return await search_topics(
return await _search_topics(
page=0,
size=len(topic_ids),
query={"terms": {"id": topic_ids}},
@@ -0,0 +1,41 @@
from unittest.mock import AsyncMock, patch
import pytest
from inse.topics.v2.service import search_topics
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_search_topics_treats_comma_separated_terms_as_alternatives():
with patch(
"inse.topics.v2.service.elasticsearch.search",
new=AsyncMock(
return_value={
"hits": {"hits": [], "total": {"value": 0}}
}
),
) as search:
await search_topics("Artificial Intelligence, Machine Learning")
assert search.await_args.kwargs["query"] == {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": "Artificial Intelligence"
}
},
{
"match_phrase_prefix": {
"display_name": "Machine Learning"
}
},
],
"minimum_should_match": 1,
}
}
@@ -3,6 +3,7 @@ from typing import List, Optional
from fastapi import APIRouter, Query, Depends
from inse.tags import Tags
from inse.exceptions import BadRequestException
from . import logic, trend_logic
from .model import (
RankingResponse,
@@ -43,7 +44,7 @@ def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBL
return NewsTrendStrategy()
elif search_type == TrendSearchType.ALL:
return AllTrendStrategy()
raise ValueError(f"Unknown search type: {search_type}")
raise BadRequestException(f"Unknown search type: {search_type}")
@router.get(
"",
@@ -74,6 +75,8 @@ async def get_trend(
authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"),
strategy: TrendStrategy = Depends(get_trend_strategy)
):
if not topics or len(topics) == 0:
raise BadRequestException("Topics list cannot be empty")
return await strategy.get_trend(
topics=topics,
keywords=keywords,
@@ -170,6 +170,19 @@ async def test_get_top_topics_for_entity_projects():
assert "items" in res
@pytest.mark.anyio
async def test_get_top_topics_for_entity_news():
res = await get_top_topics_for_entity(
entity_id="UDE",
entity_type="institution",
start_year=2018,
end_year=2024,
search_type="news",
)
assert isinstance(res, dict)
assert "items" in res
@pytest.mark.anyio
async def test_get_trend_data_delegation():
res = await get_trend_data(
@@ -128,12 +128,23 @@ async def get_top_institutions_by_region(
meta_top = await TrendMetadataResolver.resolve_all(topics=[topic])
topic_id = meta_top.get("resolved_topic_ids", {}).get(topic)
topic_display_name = meta_top.get("resolved_topic_names", {}).get(topic, topic)
topic_filter = (
{"term": {"topics.id.keyword": topic_id}}
if topic_id
else {"match_phrase": {"topics.display_name": topic}}
)
if not topic_id and (topic.startswith("https://openalex.org/") or (topic.startswith("T") and topic[1:].isdigit())):
topic_id = topic if topic.startswith("https://openalex.org/") else f"https://openalex.org/{topic}"
if topic_id:
topic_filter = {
"bool": {
"should": [
{"term": {"topics.id.keyword": topic_id}},
{"term": {"topics.id": topic_id}},
],
"minimum_should_match": 1,
}
}
else:
topic_filter = {"match_phrase": {"topics.display_name": topic_display_name}}
must_clauses: List[Dict[str, Any]] = [
{"term": {"type": "education"}},
@@ -456,31 +467,99 @@ async def get_top_topics_for_entity(
if search_type == "news":
try:
res = await elasticsearch.search(
index=ESIndex.AKTUELLES_POSTPROC.value,
body={
"query": {"match_all": {}},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topics.display_name.keyword",
"size": DEFAULT_TOP_TOPICS_SIZE,
date_filter = TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year)
news_ids = []
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query={"bool": {"filter": [date_filter]}},
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.append(str(nid))
except Exception as e:
logger.warning("Failed scanning aktuell for news IDs in date range: %s", e)
topic_counts: Dict[str, int] = {}
if news_ids:
msearch_queries = []
for i in range(0, len(news_ids), 2000):
chunk = news_ids[i : i + 2000]
payload = {
"query": {
"bool": {
"should": [
{"ids": {"values": chunk}},
{"terms": {"news_id.keyword": chunk}},
{"terms": {"news_id": chunk}},
],
"minimum_should_match": 1,
}
}
},
},
cluster=ESCluster.INSE,
)
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets]
total_hits = res.get("hits", {}).get("total", {})
total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0)
sum_top = sum(b["count"] for b in items)
other_count = max(0, total_val - sum_top)
},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topic_matches.topic_display_name.keyword",
"size": 100,
}
}
},
}
msearch_queries.append((ESIndex.AKTUELLES_OPENALEX_TOPICS.value, payload))
if msearch_queries:
try:
responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
for res in responses:
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to aggregate news top topics via msearch: %s", e)
else:
# If no year filter bounds active or scan returned no IDs, aggregate all topics directly from openalex_topics
try:
res = await elasticsearch.search(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
body={
"query": {"match_all": {}},
"size": 0,
"_source": False,
"aggs": {
"top_topics": {
"terms": {
"field": "topic_matches.topic_display_name.keyword",
"size": 100,
}
}
},
},
cluster=ESCluster.INSE,
)
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to fallback query news top topics: %s", e)
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top news topics for entity: %s", e)
@@ -12,15 +12,18 @@ DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
def clean_inst_id(id_str: str) -> str:
"""Extracts short OpenAlex ID from full URL or returns as-is."""
"""Extracts short OpenAlex ID from full URL or returns as-is, ensuring uppercase prefix."""
if not id_str:
return ""
s = id_str.strip()
return s.split("/")[-1] if "/" in s else s
raw_id = s.split("/")[-1] if "/" in s else s
if len(raw_id) > 1 and raw_id[0].isalpha():
return raw_id[0].upper() + raw_id[1:]
return raw_id.upper()
def to_full_inst_url(id_str: str) -> str:
"""Ensures institution ID is formatted as a full OpenAlex URL."""
"""Ensures institution ID is formatted as a full OpenAlex URL with proper capitalization."""
cleaned = clean_inst_id(id_str)
return f"https://openalex.org/{cleaned}" if cleaned else id_str
@@ -85,8 +88,9 @@ class TrendMetadataResolver:
alias_results = await asyncio.gather(*(get_alias(i) for i in inst_full_ids))
for short_id, alias_list in alias_results:
aliases_map[short_id] = alias_list
aliases_map[f"https://openalex.org/{short_id}"] = alias_list
s_upper = clean_inst_id(short_id)
aliases_map[s_upper] = alias_list
aliases_map[f"https://openalex.org/{s_upper}"] = alias_list
except Exception as e:
logger.warning("Failed to resolve institutions from ES: %s", e)
@@ -142,31 +146,65 @@ class TrendMetadataResolver:
async def fetch_topics():
topic_ids: Dict[str, str] = {}
topic_display_names: Dict[str, str] = {}
if not topic_names:
return topic_ids
return topic_ids, topic_display_names
should_clauses = []
for t in topic_names:
if not t:
continue
clean_id = clean_inst_id(t)
canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t
if t.startswith("https://openalex.org/") or (clean_id.startswith("T") and clean_id[1:].isdigit()):
should_clauses.extend([
{"term": {"id": canonical_id}},
{"term": {"id.keyword": canonical_id}},
{"term": {"id": clean_id}},
{"term": {"id.keyword": clean_id}},
])
else:
should_clauses.append({"match_phrase": {"display_name": t}})
try:
res = await elasticsearch.search(
index=ESIndex.OPENALEX_TOPICS.value,
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
size=len(topic_names) * 2,
query={"bool": {"should": should_clauses, "minimum_should_match": 1}},
size=max(10, len(topic_names) * 3),
source=["id", "display_name"],
cluster="nes",
)
for hit in res.get("hits", {}).get("hits", []):
src = hit["_source"]
full_id = src.get("id", "")
short_id = clean_inst_id(full_id)
canonical_id = f"https://openalex.org/{short_id}" if short_id.startswith("T") else full_id
d_name = src.get("display_name", "")
for t in topic_names:
if t.lower() in d_name.lower():
topic_ids[t] = src["id"]
t_clean = clean_inst_id(t)
t_canonical = f"https://openalex.org/{t_clean}" if t_clean.startswith("T") else t
if (
t == full_id
or t == short_id
or t == canonical_id
or t_canonical == canonical_id
or t_clean == short_id
or t.lower() in d_name.lower()
or d_name.lower() in t.lower()
):
topic_ids[t] = canonical_id
topic_display_names[t] = d_name
topic_display_names[canonical_id] = d_name
topic_display_names[short_id] = d_name
topic_display_names[full_id] = d_name
except Exception as e:
logger.warning("Failed to resolve topic IDs from ES: %s", e)
return topic_ids
return topic_ids, topic_display_names
(
(inst_names, inst_country_codes, inst_aliases),
country_names,
(continent_names, continent_country_codes),
resolved_topic_ids,
(resolved_topic_ids, resolved_topic_names),
) = await asyncio.gather(
fetch_institutions(),
fetch_countries(),
@@ -182,6 +220,7 @@ class TrendMetadataResolver:
"continent_names": continent_names,
"continent_country_codes": continent_country_codes,
"resolved_topic_ids": resolved_topic_ids,
"resolved_topic_names": resolved_topic_names,
}
@@ -196,6 +235,12 @@ class TrendQueryBuilder:
fuzzy: bool = True,
) -> Dict[str, Any]:
"""Builds a topic or keyword matching clause."""
target_id = resolved_topic_id
if not target_id and topic_display_name:
c_id = clean_inst_id(topic_display_name)
if c_id.startswith("T") and c_id[1:].isdigit():
target_id = f"https://openalex.org/{c_id}"
if not fuzzy and keyword:
return {
"bool": {
@@ -208,12 +253,15 @@ class TrendQueryBuilder:
"minimum_should_match": 1,
}
}
elif resolved_topic_id:
elif target_id:
c_id = clean_inst_id(target_id)
canonical_id = f"https://openalex.org/{c_id}" if c_id.startswith("T") else target_id
target_ids = list(dict.fromkeys([canonical_id, target_id, c_id]))
return {
"bool": {
"should": [
{"nested": {"path": "topics", "query": {"term": {"topics.id": resolved_topic_id}}}},
{"term": {"primary_topic.id": resolved_topic_id}},
{"nested": {"path": "topics", "query": {"terms": {"topics.id": target_ids}}}},
{"terms": {"primary_topic.id": target_ids}},
],
"minimum_should_match": 1,
}
@@ -316,7 +316,7 @@ class AuthorsTrendStrategy(TrendStrategy):
if not query_authors:
return TrendResponse(series=[], years=years_range)
query_authors_clean = [clean_inst_id(a).upper() for a in query_authors if a]
query_authors_clean = [clean_inst_id(a) for a in query_authors if a]
# Resolve author display names
resolved_names: Dict[str, str] = {}
@@ -329,7 +329,7 @@ class AuthorsTrendStrategy(TrendStrategy):
cluster=ESCluster.NES,
)
for hit in res.get("hits", {}).get("hits", []):
short_id = hit["_id"]
short_id = clean_inst_id(hit["_id"])
full_id = f"https://openalex.org/{short_id}"
display_name = hit["_source"].get("display_name", short_id)
resolved_names[short_id] = display_name
@@ -340,14 +340,12 @@ class AuthorsTrendStrategy(TrendStrategy):
meta = await TrendMetadataResolver.resolve_all(topics=topics)
resolved_topic_ids = meta["resolved_topic_ids"]
query_authors_full = [
a if a.startswith("https://openalex.org/") else f"https://openalex.org/{clean_inst_id(a).upper()}"
for a in query_authors
]
query_authors_full = [to_full_inst_url(a) for a in query_authors if a]
filters_map: Dict[str, Dict[str, Any]] = {}
for auth_id, auth_url in zip(query_authors, query_authors_full):
filters_map[f"author_{auth_id}"] = {
clean_id = clean_inst_id(auth_id)
filters_map[f"author_{clean_id}"] = {
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": auth_url}},
@@ -508,16 +506,17 @@ class PatentsTrendStrategy(TrendStrategy):
def matches_patent(patent, topic: str, keyword: Optional[str], is_fuzzy: bool) -> bool:
if matches_topic(patent, topic):
return True
if not is_fuzzy and keyword:
t_lower = topic.lower()
if patent.title and t_lower in patent.title.lower():
return True
if patent.abstract and t_lower in patent.abstract.lower():
return True
if keyword:
kw_lower = keyword.lower()
if patent.title and kw_lower in patent.title.lower():
return True
if patent.abstract and kw_lower in patent.abstract.lower():
return True
if patent.openalex_topics:
for ot in patent.openalex_topics:
if ot.topic_display_name and kw_lower in ot.topic_display_name.lower():
return True
return False
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
@@ -1066,11 +1065,24 @@ class NewsTrendStrategy(TrendStrategy):
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
# Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]:
news_ids: Set[str] = set()
if fuzzy:
term = t_name
es_query = {"match": {"topics.display_name": term}}
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
query=es_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_source", {}).get("news_id") or hit.get("_id")
if nid:
news_ids.add(str(nid))
except Exception as e:
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
else:
if keywords and idx < len(keywords) and keywords[idx]:
raw_kw = keywords[idx]
@@ -1079,43 +1091,28 @@ class NewsTrendStrategy(TrendStrategy):
term = t_name
else:
term = t_name
es_query = {"match": {"keywords": term}}
news_ids: Set[str] = set()
try:
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES_POSTPROC.value,
query=es_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to scan UDE news postproc: %s", e)
# If non-fuzzy keyword search, also search article content fields in 'aktuell' index
if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND",
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
try:
content_query = {
"query_string": {
"query": term,
"fields": AKTUELLES_SEARCH_FIELDS,
"default_operator": "AND",
}
}
}
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query=content_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(nid)
except Exception as e:
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
async for hit in elasticsearch.scan(
index=ESIndex.AKTUELLES.value,
query=content_query,
source=["news_id"],
cluster=ESCluster.INSE,
):
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
if nid:
news_ids.add(str(nid))
except Exception as e:
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
return list(news_ids)
@@ -1134,7 +1131,16 @@ class NewsTrendStrategy(TrendStrategy):
"query": {
"bool": {
"filter": [
{"ids": {"values": chunk}},
{
"bool": {
"should": [
{"ids": {"values": chunk}},
{"terms": {"news_id.keyword": chunk}},
{"terms": {"news_id": chunk}},
],
"minimum_should_match": 1,
}
},
TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year),
]
}
+72 -60
View File
@@ -1,60 +1,72 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HUB_OFFLINE"] = "1"
else:
# If it is set to /models, enforce offline mode as it is baked into the image
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
_model = SentenceTransformer(model_name)
return _model
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# Determine offline mode
is_offline = os.environ.get("HF_HUB_OFFLINE") == "1"
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HOME"] = "/models"
is_offline = True
elif os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
is_offline = True
if is_offline:
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
try:
if is_offline:
_model = SentenceTransformer(model_name, local_files_only=True)
else:
_model = SentenceTransformer(model_name)
except Exception:
# Fallback if local_files_only fails in unexpected local dev environments
_model = SentenceTransformer(model_name)
return _model
+121
View File
@@ -22,6 +22,68 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2])
@router.get(
"/search",
operation_id="searchWorks",
summary="Search works with filters.",
)
async def search_works(
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
title: Annotated[
str, Query(description="A title to filter by (partial matches allowed).")
] = "",
publication_years: Annotated[
list[int] | None,
Query(description="A list of publication years to filter by."),
] = None,
publication_types: Annotated[
list[str] | None,
Query(description="A list of publication types to filter by."),
] = None,
author_ids: Annotated[
list[str] | None,
Query(description="A list of author IDs to filter by."),
] = None,
institution_ids: Annotated[
list[str] | None,
Query(description="A list of institution IDs to filter by."),
] = None,
topic_ids: Annotated[
list[str] | None,
Query(description="A list of topic IDs to filter by."),
] = None,
language_codes: Annotated[
list[str] | None,
Query(description="A list of language codes to filter by."),
] = None,
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
return await works_service.search_works(
page=page,
size=size,
title=title,
publication_years=publication_years or [],
publication_types=publication_types or [],
author_ids=author_ids or [],
institution_ids=institution_ids or [],
topic_ids=topic_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/author/{raw_oa_author_id}",
operation_id="getAuthorWorkPage",
@@ -218,6 +280,65 @@ async def get_institution_works(
)
@router.get(
"/topic/{raw_oa_topic_id}",
operation_id="getTopicWorkPage",
summary="Returns a paginated list of works for a given topic based on its ID.",
)
async def get_topic_works(
raw_oa_topic_id: Annotated[str, Path(description="The raw OpenAlex topic id.")],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
title: Annotated[
str, Query(description="A title to filter by (partial matches allowed).")
] = "",
publication_years: Annotated[
list[int] | None,
Query(description="A list of publication years to filter by."),
] = None,
publication_types: Annotated[
list[str] | None,
Query(description="A list of publication types to filter by."),
] = None,
author_ids: Annotated[
list[str] | None,
Query(description="A list of author IDs to filter by."),
] = None,
institution_ids: Annotated[
list[str] | None,
Query(description="A list of institution IDs to filter by."),
] = None,
language_codes: Annotated[
list[str] | None,
Query(description="A list of language codes to filter by."),
] = None,
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> WorkPageV2:
return await works_service.get_topic_works(
raw_oa_topic_id=raw_oa_topic_id,
page=page,
size=size,
title=title,
publication_years=publication_years or [],
publication_types=publication_types or [],
author_ids=author_ids or [],
institution_ids=institution_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/classification/work/{raw_oa_work_id}",
operation_id="getWorkClassificationByWorkId",
+128 -33
View File
@@ -60,6 +60,19 @@ def _institutions_nested_query(institution_ids: list[str]) -> dict:
}
def _topics_nested_query(topic_ids: list[str]) -> dict:
"""Returns a nested query for filtering works by a list of topic IDs.
Args:
topic_ids (list[str]): A list of topic IDs to filter by.
Returns:
dict: A nested query for filtering works by the specified topic IDs.
"""
prefixed = [_prefix_id(tid) for tid in topic_ids]
return {"nested": {"path": "topics", "query": {"terms": {"topics.id": prefixed}}}}
def _title_query(title: str) -> dict:
"""Returns a query for filtering works by title using a multi-match query.
@@ -87,7 +100,6 @@ def _apply_common_filters(
publication_years: list[int] | None,
publication_types: list[str] | None,
language_codes: list[str] | None,
topic_ids: list[str] | None,
title: str | None = None,
) -> None:
"""Applies common filters to the provided list of must conditions for filtering works.
@@ -106,10 +118,6 @@ def _apply_common_filters(
must.append({"terms": {"type": publication_types}})
if language_codes:
must.append({"terms": {"language": language_codes}})
if topic_ids:
must.append(
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
)
if title and len(title.strip()) > 0:
must.append(_title_query(title))
@@ -148,7 +156,7 @@ async def _execute_works_search(
Returns:
WorkPageV2: The page of works matching the search criteria.
"""
return await search_works(
return await _search_works(
source=[
"id",
"title",
@@ -172,8 +180,6 @@ async def _execute_works_search(
async def get_works(
page: int,
size: int,
raw_oa_author_id: str | None = None,
raw_oa_institution_id: str | None = None,
title: str | None = None,
author_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
@@ -189,8 +195,6 @@ async def get_works(
Args:
page (int): The page number for pagination.
size (int): The number of results per page.
raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None.
raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None.
title (Optional[str], optional): The title of the works to filter by. Defaults to None.
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
@@ -201,34 +205,31 @@ async def get_works(
sort_by (WorkSortBy, optional): The field to sort by. Defaults to WorkSortBy.PUBLICATION_YEAR.
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
Raises:
ValueError: If neither raw_oa_author_id nor raw_oa_institution_id is provided.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
if not raw_oa_author_id and not raw_oa_institution_id:
raise ValueError(
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id"
)
must: list = []
if raw_oa_author_id:
must.append(_authors_nested_query([raw_oa_author_id]))
elif author_ids:
must.append(_authors_nested_query(author_ids))
if author_ids:
must.append(_authors_nested_query(author_ids=author_ids))
if raw_oa_institution_id:
must.append(_institutions_nested_query([raw_oa_institution_id]))
elif institution_ids:
must.append(_institutions_nested_query(institution_ids))
if institution_ids:
must.append(_institutions_nested_query(institution_ids=institution_ids))
if topic_ids:
must.append(_topics_nested_query(topic_ids=topic_ids))
_apply_common_filters(
must, publication_years, publication_types, language_codes, topic_ids, title
must=must,
publication_years=publication_years,
publication_types=publication_types,
language_codes=language_codes,
title=title,
)
return await _execute_works_search(must, page, size, sort_by, sort_order)
return await _execute_works_search(
must=must, page=page, size=size, sort_by=sort_by, sort_order=sort_order
)
async def get_works_by_keywords(
@@ -427,7 +428,7 @@ async def get_author_works(
return await get_works(
page=page,
size=size,
raw_oa_author_id=raw_oa_author_id,
author_ids=[raw_oa_author_id],
title=title,
institution_ids=institution_ids,
publication_years=publication_years,
@@ -474,7 +475,7 @@ async def get_institution_works(
return await get_works(
page=page,
size=size,
raw_oa_institution_id=raw_oa_institution_id,
institution_ids=[raw_oa_institution_id],
author_ids=author_ids,
title=title,
publication_years=publication_years,
@@ -486,6 +487,100 @@ async def get_institution_works(
)
async def get_topic_works(
raw_oa_topic_id: str,
page: int,
size: int,
title: str = "",
publication_years: list[int] | None = None,
publication_types: list[str] | None = None,
institution_ids: list[str] | None = None,
author_ids: list[str] | None = None,
language_codes: list[str] | None = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> WorkPageV2:
"""Retrieves works for a specific topic based on the provided criteria.
Args:
raw_oa_topic_id (str): The ID of the topic for whom to retrieve works.
page (int): The page number of the results to retrieve.
size (int): The number of results per page.
title (str, optional): The title of the works to filter by. Defaults to "".
publication_years (Optional[List[int]], optional): A list of publication years to filter by. Defaults to None.
publication_types (Optional[List[str]], optional): A list of publication types to filter by. Defaults to None.
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
language_codes (Optional[List[str]], optional): A list of language codes to filter by. Defaults to None.
sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR.
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
return await get_works(
page=page,
size=size,
topic_ids=[raw_oa_topic_id],
title=title,
institution_ids=institution_ids,
author_ids=author_ids,
publication_years=publication_years,
publication_types=publication_types,
language_codes=language_codes,
sort_by=sort_by,
sort_order=sort_order,
)
async def search_works(
page: int,
size: int,
title: str | None = None,
author_ids: list[str] | None = None,
institution_ids: list[str] | None = None,
publication_years: list[int] | None = None,
publication_types: list[str] | None = None,
topic_ids: list[str] | None = None,
language_codes: list[str] | None = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> WorkPageV2:
"""Searches for works based on the provided criteria.
Args:
page (int): The page number of the results to retrieve.
size (int): The number of results per page.
title (str | None, optional): The title of the works to filter by. Defaults to None.
author_ids (list[str] | None, optional): A list of author IDs to filter by. Defaults to None.
institution_ids (list[str] | None, optional): A list of institution IDs to filter by. Defaults to None.
publication_years (list[int] | None, optional): A list of publication years to filter by. Defaults to None.
publication_types (list[str] | None, optional): A list of publication types to filter by. Defaults to None.
topic_ids (list[str] | None, optional): A list of topic IDs to filter by. Defaults to None.
language_codes (list[str] | None, optional): A list of language codes to filter by. Defaults to None.
sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR.
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
Returns:
WorkPageV2: The page of works matching the criteria.
"""
return await get_works(
page=page,
size=size,
title=title,
author_ids=author_ids,
institution_ids=institution_ids,
publication_years=publication_years,
publication_types=publication_types,
topic_ids=topic_ids,
language_codes=language_codes,
sort_by=sort_by,
sort_order=sort_order,
)
async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None:
"""Retrieves a work based on its OpenAlex ID.
@@ -498,7 +593,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work
"""
# search instead of get, because multiple indices are used for works
work_page = await search_works(
work_page = await _search_works(
query={"term": {"id": _prefix_id(raw_oa_work_id)}},
source=source,
page=0,
@@ -510,7 +605,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work
return None
async def search_works(
async def _search_works(
query: dict | None = None,
source: list[str] | None = None,
page: int = 0,
@@ -568,7 +663,7 @@ async def _get_works_by_work_ids_and_institution_id(
prefixed_work_ids = [_prefix_id(wid) for wid in work_ids]
prefixed_institution_id = _prefix_id(raw_oa_institution_id)
return await search_works(
return await _search_works(
query={
"bool": {
"must": [
+4 -10
View File
@@ -25,10 +25,7 @@
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"styles": ["src/styles.scss"],
"scripts": []
},
"configurations": {
@@ -41,8 +38,8 @@
},
{
"type": "anyComponentStyle",
"maximumWarning": "5kb",
"maximumError": "10kb"
"maximumWarning": "10kb",
"maximumError": "20kb"
}
],
"outputHashing": "all"
@@ -83,10 +80,7 @@
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"styles": ["src/styles.scss"],
"scripts": []
}
}
@@ -6,6 +6,7 @@ api.module.ts
api/api.ts
api/auth.service.ts
api/authorsV2.service.ts
api/bUNDInstitutions.service.ts
api/backgroundJobs.service.ts
api/bookmarks.service.ts
api/companyConnections.service.ts
@@ -43,6 +44,9 @@ model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNode.ts
model/authorOrientationProfile.ts
model/authorOrientationProfileStatus.ts
model/authorOrientationProfilesRequest.ts
model/authorPage.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
@@ -66,6 +70,8 @@ model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundInstitutionSummary.ts
model/bundInstitutionSummaryPage.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/bundProjectSummary.ts
@@ -96,7 +102,13 @@ model/dfgInstitutionSummaryPage.ts
model/dfgPersonSummary.ts
model/dfgPersonSummaryPage.ts
model/dfgProjectDetails.ts
model/dfgProjectInstitutionRole.ts
model/dfgProjectPage.ts
model/dfgProjectPersonRole.ts
model/dfgProjectPublicationSummary.ts
model/dfgProjectStatusStatistics.ts
model/dfgProjectSubjectArea.ts
model/dfgProjectSubprojectSummary.ts
model/dfgProjectSummary.ts
model/dfgProjectTopic.ts
model/dfgProjectTopics.ts
@@ -249,6 +261,7 @@ model/topicHeatmapTopic.ts
model/topicHeatmapValue.ts
model/topicIds.ts
model/topicPageV2.ts
model/topicSortBy.ts
model/topicSubfield.ts
model/topicWordCloud.ts
model/topicWordCloudWord.ts
+29 -1
View File
@@ -2,6 +2,8 @@ export * from './auth.service';
import { AuthService } from './auth.service';
export * from './authorsV2.service';
import { AuthorsV2Service } from './authorsV2.service';
export * from './bUNDInstitutions.service';
import { BUNDInstitutionsService } from './bUNDInstitutions.service';
export * from './backgroundJobs.service';
import { BackgroundJobsService } from './backgroundJobs.service';
export * from './bookmarks.service';
@@ -46,4 +48,30 @@ export * from './works.service';
import { WorksService } from './works.service';
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BackgroundJobsService, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
export const APIS = [
AuthService,
AuthorsV2Service,
BUNDInstitutionsService,
BackgroundJobsService,
BookmarksService,
CompanyConnectionsService,
DFGInstitutionsService,
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonsService,
ProjectsService,
RankingService,
TopicsService,
TopicsV2Service,
UniversityRankingsService,
WorksService,
WorksV2Service,
];
@@ -16,6 +16,8 @@ import { HttpClient, HttpHeaders, HttpParams,
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { Author } from '../model/author';
// @ts-ignore
import { AuthorPage } from '../model/authorPage';
// @ts-ignore
@@ -98,6 +100,61 @@ export class AuthorsV2Service extends BaseService {
);
}
/**
* Returns an author for a given author ID.
* @endpoint get /api/authors/v2/{raw_oa_author_id}
* @param rawOaAuthorId The ID of the author to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getAuthorById(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Author>;
public getAuthorById(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Author>>;
public getAuthorById(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Author>>;
public getAuthorById(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorById.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/authors/v2/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Author>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a paginated list of authors for a given list of author IDs.
* @endpoint get /api/authors/v2/authors/id
@@ -0,0 +1,258 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { BundInstitutionSummaryPage } from '../model/bundInstitutionSummaryPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
})
export class BUNDInstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/bund/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bund/institutions/autocomplete/selector`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a list of institutions based on their names.
* @endpoint get /api/bund/institutions/names
* @param institutionNames A list of institution names to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionNames) {
institutionNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_names',
);
});
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bund/institutions/names`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -19,6 +19,8 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { Institution } from '../model/institution';
// @ts-ignore
import { InstitutionPageV2 } from '../model/institutionPageV2';
// @ts-ignore
@@ -94,9 +96,64 @@ export class InstitutionsV2Service extends BaseService {
);
}
/**
* Returns an institution based on its ID.
* @endpoint get /api/institutions/v2/single/{institution_id}
* @param institutionId The ID of the institution to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInstitutionById2(institutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Institution>;
public getInstitutionById2(institutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Institution>>;
public getInstitutionById2(institutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Institution>>;
public getInstitutionById2(institutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (institutionId === null || institutionId === undefined) {
throw new Error('Required parameter institutionId was null or undefined when calling getInstitutionById2.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/institutions/v2/single/${this.configuration.encodeParam({name: "institutionId", value: institutionId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Institution>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of institutions based on their IDs.
* @endpoint get /api/institutions/v2/ids
* @endpoint get /api/institutions/v2/multiple/ids
* @param institutionIds A list of institution IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
@@ -139,7 +196,7 @@ export class InstitutionsV2Service extends BaseService {
}
}
let localVarPath = `/api/institutions/v2/ids`;
let localVarPath = `/api/institutions/v2/multiple/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPageV2>('get', `${basePath}${localVarPath}`,
{
File diff suppressed because it is too large Load Diff
+620 -265
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,16 +9,26 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
// @ts-ignore
import { AuthorOrientationProfile } from '../model/authorOrientationProfile';
// @ts-ignore
import { AuthorOrientationProfilesRequest } from '../model/authorOrientationProfilesRequest';
// @ts-ignore
import { AuthorStaticStats } from '../model/authorStaticStats';
// @ts-ignore
import { AuthorTopicProfile } from '../model/authorTopicProfile';
@@ -34,283 +44,628 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class RankingService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
/**
* Orientation Profiles
* Compare orientation scores for active members of the account institution.
* @endpoint post /api/rank/orientation-profiles
* @param authorOrientationProfilesRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorOrientationProfile>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
authorOrientationProfilesRequest === null ||
authorOrientationProfilesRequest === undefined
) {
throw new Error(
'Required parameter authorOrientationProfilesRequest was null or undefined when calling orientationProfilesApiRankOrientationProfilesPost.',
);
}
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (keywordToAuthorRequest === null || keywordToAuthorRequest === undefined) {
throw new Error('Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error('Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.');
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
let localVarHeaders = this.defaultHeaders;
const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.');
}
let localVarPath = `/api/rank/orientation-profiles`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorOrientationProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorOrientationProfilesRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
keywordToAuthorRequest === null ||
keywordToAuthorRequest === undefined
) {
throw new Error(
'Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error(
'Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
+130
View File
@@ -19,7 +19,13 @@ import { Observable } from 'rxjs';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { SortDirection } from '../model/sortDirection';
// @ts-ignore
import { Topic } from '../model/topic';
// @ts-ignore
import { TopicPageV2 } from '../model/topicPageV2';
// @ts-ignore
import { TopicSortBy } from '../model/topicSortBy';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -94,6 +100,61 @@ export class TopicsV2Service extends BaseService {
);
}
/**
* Returns a topic for a given topic ID.
* @endpoint get /api/topics/v2/single/{raw_oa_topic_id}
* @param rawOaTopicId The ID of the topic to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicById(rawOaTopicId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Topic>;
public getTopicById(rawOaTopicId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Topic>>;
public getTopicById(rawOaTopicId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Topic>>;
public getTopicById(rawOaTopicId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaTopicId === null || rawOaTopicId === undefined) {
throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicById.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/topics/v2/single/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Topic>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a paginated list of topics for a given list of topic IDs.
* @endpoint get /api/topics/v2/topics/id
@@ -155,4 +216,73 @@ export class TopicsV2Service extends BaseService {
);
}
/**
* Searches for topics based on the provided criteria.
* @endpoint get /api/topics/v2/search
* @param searchTerm The term to search for in topic display names.
* @param page The page number to retrieve.
* @param size The number of topics to retrieve per page.
* @param sortBy The field to sort by.
* @param sortDirection The direction to sort.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicPageV2>;
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicPageV2>>;
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicPageV2>>;
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>searchTerm, 'search_term');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortDirection, 'sort_direction');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/topics/v2/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopicPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+219
View File
@@ -399,6 +399,114 @@ export class WorksV2Service extends BaseService {
);
}
/**
* Returns a paginated list of works for a given topic based on its ID.
* @endpoint get /api/works/v2/topic/{raw_oa_topic_id}
* @param rawOaTopicId The raw OpenAlex topic id.
* @param page The page number to retrieve. (0-based)
* @param size The number of works to retrieve per page.
* @param title A title to filter by (partial matches allowed).
* @param publicationYears A list of publication years to filter by.
* @param publicationTypes A list of publication types to filter by.
* @param authorIds A list of author IDs to filter by.
* @param institutionIds A list of institution IDs to filter by.
* @param languageCodes A list of language codes to filter by.
* @param sortBy The field to sort by.
* @param sortOrder The order to sort by.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPageV2>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPageV2>>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPageV2>>;
public getTopicWorkPage(rawOaTopicId: string, page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaTopicId === null || rawOaTopicId === undefined) {
throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicWorkPage.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
if (publicationYears) {
publicationYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_years');
})
}
if (publicationTypes) {
publicationTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_types');
})
}
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'author_ids');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
if (languageCodes) {
languageCodes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language_codes');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sort_order');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/works/v2/topic/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<WorkPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns the classifications of a work based on its ID.
* @endpoint get /api/works/v2/classification/work/{raw_oa_work_id}
@@ -670,4 +778,115 @@ export class WorksV2Service extends BaseService {
);
}
/**
* Search works with filters.
* @endpoint get /api/works/v2/search
* @param page The page number to retrieve. (0-based)
* @param size The number of works to retrieve per page.
* @param title A title to filter by (partial matches allowed).
* @param publicationYears A list of publication years to filter by.
* @param publicationTypes A list of publication types to filter by.
* @param authorIds A list of author IDs to filter by.
* @param institutionIds A list of institution IDs to filter by.
* @param topicIds A list of topic IDs to filter by.
* @param languageCodes A list of language codes to filter by.
* @param sortBy The field to sort by.
* @param sortOrder The order to sort by.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkPageV2>;
public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkPageV2>>;
public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkPageV2>>;
public searchWorks(page?: number, size?: number, title?: string, publicationYears?: Array<number>, publicationTypes?: Array<string>, authorIds?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>title, 'title');
if (publicationYears) {
publicationYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_years');
})
}
if (publicationTypes) {
publicationTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_types');
})
}
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'author_ids');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (languageCodes) {
languageCodes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language_codes');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sort_order');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/works/v2/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<WorkPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -0,0 +1,27 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { AuthorOrientationProfileStatus } from './authorOrientationProfileStatus';
import { WorkPrimaryCategory } from './workPrimaryCategory';
/**
* Aggregated research-orientation result for one selected author.
*/
export interface AuthorOrientationProfile {
/**
* The full OpenAlex author ID.
*/
author_id: string;
status: AuthorOrientationProfileStatus;
orientation_score?: number | null;
primary_category_counts?: Partial<Record<WorkPrimaryCategory, number>> | null;
classified_work_count?: number | null;
scored_work_count?: number | null;
}
export namespace AuthorOrientationProfile {}
@@ -0,0 +1,19 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const AuthorOrientationProfileStatus = {
available: 'available',
insufficient_scored_publications: 'insufficient_scored_publications',
no_classified_publications: 'no_classified_publications',
no_orientation_score: 'no_orientation_score',
restricted: 'restricted',
} as const;
export type AuthorOrientationProfileStatus =
(typeof AuthorOrientationProfileStatus)[keyof typeof AuthorOrientationProfileStatus];
@@ -0,0 +1,26 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Timespan } from './timespan';
import { PublicationType } from './publicationType';
/**
* Filters used to compare the research orientation of selected authors.
*/
export interface AuthorOrientationProfilesRequest {
/**
* One to four unique OpenAlex author IDs.
*/
author_ids: Array<string>;
/**
* Optional publication-type filter. Empty means all types.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | null;
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A single institution entry derived from a BUND project record. Note: this index has no dedicated institution entity — each entry is reconstructed from the agency/recipient fields on a single project hit, so the same institution may appear multiple times (once per project).
*/
export interface BundInstitutionSummary {
department?: string | null;
department_fullname?: string | null;
name?: string | null;
recepient?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
}
@@ -0,0 +1,32 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { BundInstitutionSummary } from './bundInstitutionSummary';
/**
* A paginated response containing a list of institutions.
*/
export interface BundInstitutionSummaryPage {
/**
* The elements of the page.
*/
elements?: Array<BundInstitutionSummary>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
+44 -44
View File
@@ -1,57 +1,57 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Topic } from './topic';
/**
* Clean summary model for a Bund (federal) project, consolidating all fields into semantic English names with proper native types.
*/
export interface BundProjectDetails {
/**
* The ID of the Bund project
*/
id: string;
funding_reference?: string | null;
title?: string | null;
description?: string | null;
joint_project?: string | null;
funding_type?: string | null;
funding_profile?: string | null;
funding_amount?: number | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
duration?: string | null;
performance_plan_code?: string | null;
performance_plan_fullname?: string | null;
executing_agency?: string | null;
funding_recipient?: string | null;
project_agency?: string | null;
project_agency_fullname?: string | null;
department?: string | null;
department_fullname?: string | null;
division?: string | null;
location?: string | null;
municipality?: string | null;
state?: string | null;
country?: string | null;
municipality_code?: string | null;
publication_date?: string | null;
is_new?: boolean | null;
record_date?: string | null;
unix_timestamp?: number | null;
/**
* All persons associated with the Bund project (from nested Arb object)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
export interface BundProjectDetails {
/**
* The ID of the Bund project
*/
id: string;
funding_reference?: string | null;
title?: string | null;
description?: string | null;
joint_project?: string | null;
funding_type?: string | null;
funding_profile?: string | null;
funding_amount?: number | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
duration?: string | null;
performance_plan_code?: string | null;
performance_plan_fullname?: string | null;
executing_agency?: string | null;
funding_recipient?: string | null;
project_agency?: string | null;
project_agency_fullname?: string | null;
department?: string | null;
department_fullname?: string | null;
division?: string | null;
location?: string | null;
municipality?: string | null;
state?: string | null;
country?: string | null;
municipality_code?: string | null;
publication_date?: string | null;
is_new?: boolean | null;
record_date?: string | null;
unix_timestamp?: number | null;
/**
* All persons associated with the Bund project (from nested Arb object)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
oa_topics?: Array<Topic> | null;
}
+33 -33
View File
@@ -1,44 +1,44 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Topic } from './topic';
import { BundInstitutionSummary } from './bundInstitutionSummary';
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
'new'?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
new?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
institution?: BundInstitutionSummary | null;
}
+70 -29
View File
@@ -1,41 +1,82 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { DfgProjectPersonRole } from './dfgProjectPersonRole';
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
import { DfgProjectSubjectArea } from './dfgProjectSubjectArea';
import { Topic } from './topic';
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
/**
* Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists.
* Clean, enriched summary model for a DFG project.
*/
export interface DfgProjectDetails {
/**
* The ID of the DFG project
*/
id: string;
link?: string | null;
title?: string | null;
description?: string | null;
project_identifier?: string | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
dfg_procedure?: string | null;
subject_area?: string | null;
funding_type?: string | null;
international_reference?: string | null;
website?: string | null;
/**
* All persons associated with the DFG project (any role)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the DFG project
*/
institutions?: Array<string>;
subproject_of?: string | null;
export interface DfgProjectDetails {
id?: number | null;
link?: string | null;
page_url?: string | null;
external_link?: string | null;
title_de?: string | null;
title_en?: string | null;
description_de?: string | null;
description_en?: string | null;
final_report_abstract_de?: string | null;
final_report_abstract_en?: string | null;
project_identifier_de?: string | null;
project_identifier_en?: string | null;
funding_start?: number | null;
funding_end?: number | null;
funding_period_de?: string | null;
funding_period_en?: string | null;
funding_type_de?: string | null;
funding_type_en?: string | null;
funding_type_key?: string | null;
dfg_procedure?: string | null;
is_transfer_project?: boolean | null;
website_html_de?: string | null;
website_html_en?: string | null;
equipment_group?: string | null;
equipment_name?: string | null;
subject_area_de?: string | null;
subject_area_en?: string | null;
/**
* Detailed DFG subject-area classification entries (Fachsystematik)
*/
subject_classifications?: Array<DfgProjectSubjectArea>;
international_relation_de?: string | null;
international_relation_en?: string | null;
/**
* All persons associated with the project, each with their role
*/
persons?: Array<DfgProjectPersonRole>;
/**
* All institutions associated with the project, each with their role
*/
institutions?: Array<DfgProjectInstitutionRole>;
/**
* Flat, de-duplicated list of all person full names (convenience view)
*/
associated_persons?: Array<string>;
/**
* Flat, de-duplicated list of all institution names (convenience view)
*/
associated_institutions?: Array<string>;
parent_project_id?: number | null;
parent_title_de?: string | null;
parent_title_en?: string | null;
/**
* Sub-projects of this project, if any
*/
subprojects?: Array<DfgProjectSubprojectSummary>;
/**
* Publications resulting from the project
*/
publications?: Array<DfgProjectPublicationSummary>;
topics?: Array<Topic> | null;
}
@@ -0,0 +1,25 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* An institution associated with the project, together with its role.
*/
export interface DfgProjectInstitutionRole {
institute_id?: number | null;
name_de?: string | null;
name_en?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
is_dissolved?: boolean | null;
is_head?: boolean | null;
}
@@ -0,0 +1,27 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A person associated with the project, together with their role.
*/
export interface DfgProjectPersonRole {
person_id?: number | null;
full_name?: string | null;
orcid_id?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
affiliation_de?: string | null;
affiliation_en?: string | null;
is_deceased?: boolean | null;
is_head?: boolean | null;
}
@@ -0,0 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A lightweight reference to a publication resulting from the project.
*/
export interface DfgProjectPublicationSummary {
publication_id?: number | null;
title?: string | null;
authors_editors?: string | null;
doi?: string | null;
publication_year?: number | null;
}
@@ -0,0 +1,17 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
@@ -0,0 +1,21 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A single subject-area classification entry (DFG \'Fachsystematik\').
*/
export interface DfgProjectSubjectArea {
fach?: string | null;
fachgebiet?: string | null;
fachkollegium?: string | null;
wissenschaftsbereich?: string | null;
}
@@ -0,0 +1,26 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A lightweight reference to a sub-project of this project.
*/
export interface DfgProjectSubprojectSummary {
subproject_id?: number | null;
title_de?: string | null;
title_en?: string | null;
short_title?: string | null;
role_label_de?: string | null;
person_full_name?: string | null;
status_de?: string | null;
funding_start?: number | null;
funding_end?: number | null;
}
+45 -43
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -13,6 +13,7 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUPublication } from './hEUPublication';
import { Fp7WebLink } from './fp7WebLink';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUDeliverable } from './hEUDeliverable';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { HEUEurosciVoc } from './hEUEurosciVoc';
@@ -21,51 +22,52 @@ import { HEULegalBasis } from './hEULegalBasis';
import { HEUTopic } from './hEUTopic';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { HEUReportSummary } from './hEUReportSummary';
import { Topic } from './topic';
import { HEUProjectDetails } from './hEUProjectDetails';
/**
* The project data
*/
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
oaTopics?: Array<Topic>;
oaAuthors?: AuthorPage;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { Fp7WebLink } from './fp7WebLink';
import { Fp7Publication } from './fp7Publication';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { Fp7Topic } from './fp7Topic';
import { AuthorPage } from './authorPage';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { Topic } from './topic';
import { Fp7Organization } from './fp7Organization';
import { Fp7LegalBasis } from './fp7LegalBasis';
/**
* Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data.
*/
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Author } from './author';
/**
* Fp7Publication
*/
export interface Fp7Publication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface Fp7Publication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+41 -39
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -11,51 +11,53 @@ import { H2020LegalBasis } from './h2020LegalBasis';
import { H2020ErcPI } from './h2020ErcPI';
import { H2020Deliverable } from './h2020Deliverable';
import { H2020WebLink } from './h2020WebLink';
import { AuthorPage } from './authorPage';
import { H2020Publication } from './h2020Publication';
import { H2020ReportSummary } from './h2020ReportSummary';
import { H2020Topic } from './h2020Topic';
import { H2020EurosciVoc } from './h2020EurosciVoc';
import { Topic } from './topic';
import { H2020Organization } from './h2020Organization';
/**
* Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data.
*/
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Author } from './author';
/**
* H2020Publication
*/
export interface H2020Publication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface H2020Publication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUTopic } from './hEUTopic';
import { HEUPublication } from './hEUPublication';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUReportSummary } from './hEUReportSummary';
import { HEUDeliverable } from './hEUDeliverable';
import { Topic } from './topic';
import { HEUEurosciVoc } from './hEUEurosciVoc';
/**
* Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data.
*/
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Author } from './author';
/**
* HEUPublication
*/
export interface HEUPublication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface HEUPublication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+12
View File
@@ -9,6 +9,9 @@ export * from './authorCountsByYearInner';
export * from './authorIds';
export * from './authorMetricsRequest';
export * from './authorNode';
export * from './authorOrientationProfile';
export * from './authorOrientationProfileStatus';
export * from './authorOrientationProfilesRequest';
export * from './authorPage';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
@@ -32,6 +35,8 @@ export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundInstitutionSummary';
export * from './bundInstitutionSummaryPage';
export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './bundProjectSummary';
@@ -62,7 +67,13 @@ export * from './dfgInstitutionSummaryPage';
export * from './dfgPersonSummary';
export * from './dfgPersonSummaryPage';
export * from './dfgProjectDetails';
export * from './dfgProjectInstitutionRole';
export * from './dfgProjectPage';
export * from './dfgProjectPersonRole';
export * from './dfgProjectPublicationSummary';
export * from './dfgProjectStatusStatistics';
export * from './dfgProjectSubjectArea';
export * from './dfgProjectSubprojectSummary';
export * from './dfgProjectSummary';
export * from './dfgProjectTopic';
export * from './dfgProjectTopics';
@@ -214,6 +225,7 @@ export * from './topicHeatmapTopic';
export * from './topicHeatmapValue';
export * from './topicIds';
export * from './topicPageV2';
export * from './topicSortBy';
export * from './topicSubfield';
export * from './topicWordCloud';
export * from './topicWordCloudWord';
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -13,6 +13,7 @@ import { TopAuthor } from './topAuthor';
export interface TopAuthorStatistics {
institution_id: string;
works: Array<TopAuthor>;
projects: Array<TopAuthor>;
eu_projects: Array<TopAuthor>;
patents: Array<TopAuthor>;
news: Array<TopAuthor>;
+18
View File
@@ -0,0 +1,18 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export const TopicSortBy = {
DisplayName: 'display_name',
WorksCount: 'works_count',
CitedByCount: 'cited_by_count'
} as const;
export type TopicSortBy = typeof TopicSortBy[keyof typeof TopicSortBy];
+190 -23
View File
@@ -35,9 +35,11 @@ import { UniTrendParentComponent } from './modules/university-ranking/uni-trend-
import {
RESOLVING_WORK_PAGE_FOR,
workPageResolver,
workQueryParamKeys,
} from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
@@ -58,6 +60,11 @@ import {
collaborationGraphQueryParamKeys,
collaborationGraphResolver,
} from './resolvers/collaboration-graph.resolver';
import {
topicPageResolver,
topicQueryParamKeys,
} from './resolvers/topic-page.resolver';
import { topicResolver } from './resolvers/topic.resolver';
export const routes: Routes = [
{
path: '',
@@ -235,6 +242,20 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
@@ -264,6 +285,7 @@ export const routes: Routes = [
'search_type',
'topic',
'topics',
'trend_topics',
'keyword',
'keywords',
'institutions',
@@ -273,7 +295,9 @@ export const routes: Routes = [
'fuzzy',
];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
@@ -520,20 +544,6 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{
@@ -683,17 +693,71 @@ export const routes: Routes = [
(mod) => mod.InstitutionProjectsComponent,
),
resolve: {
bundProjectPage: bundProjectPageResolver,
bundProjectsFunding: bundProjectsFundingResolver,
cordisEuProjectPage: euCordisProjectsResolver,
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
runGuardsAndResolvers: 'always',
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dfg',
},
{
path: 'dfg',
component: DfgProjectsComponent,
resolve: {
dfgProjectPage: dfgProjectsResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
{
path: 'eu',
component: EuProjectsComponent,
resolve: {
euCordisProjectPage: euCordisProjectsResolver,
selectedEuInstitutionsPage: selectedEuInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
],
// resolve: {
// bundProjectPage: bundProjectPageResolver,
// bundProjectsFunding: bundProjectsFundingResolver,
// cordisEuProjectPage: euCordisProjectsResolver,
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
// },
// runGuardsAndResolvers: (from, to) => {
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
// return keys.some(
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
// );
// },
},
{
path: 'patents',
@@ -704,6 +768,109 @@ export const routes: Routes = [
},
],
},
{
path: 'publications',
canActivate: [
roleGuard([
UserRole.User,
UserRole.Manager,
UserRole.Admin,
UserRole.SuperAdmin,
]),
],
loadComponent: () =>
import('./modules/publications/publications.component').then(
(mod) => mod.PublicationsComponent,
),
resolve: {
workPage: workPageResolver,
selectedAuthorsPage: selectedAuthorsResolver,
selectedInstitutionsPage: selectedInstitutionsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
data: {
resolvingFor: RESOLVING_WORK_PAGE_FOR.PUBLICATION_SEARCH,
},
runGuardsAndResolvers: (from, to) => {
return Object.values(workQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'topics',
canActivate: [
roleGuard([
UserRole.User,
UserRole.Manager,
UserRole.Admin,
UserRole.SuperAdmin,
]),
],
loadComponent: () =>
import('./modules/topics/topics.component').then(
(mod) => mod.TopicsComponent,
),
resolve: {
topicPage: topicPageResolver,
},
runGuardsAndResolvers: (from, to) => {
return Object.values(topicQueryParamKeys).some((key) => {
const fromValues = from.queryParamMap.getAll(key);
const toValues = to.queryParamMap.getAll(key);
return (
fromValues.length !== toValues.length ||
fromValues.some((value, index) => value !== toValues[index])
);
});
},
},
{
path: 'topic/:topicId',
canActivate: [
roleGuard([
UserRole.User,
UserRole.Manager,
UserRole.Admin,
UserRole.SuperAdmin,
]),
],
loadComponent: () =>
import('./modules/topic/topic.component').then(
(mod) => mod.TopicComponent,
),
resolve: {
topic: topicResolver,
},
runGuardsAndResolvers: 'paramsChange',
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'publications',
},
{
path: 'publications',
loadComponent: () =>
import('./modules/topic-publications/topic-publications.component').then(
(mod) => mod.TopicPublicationsComponent,
),
runGuardsAndResolvers: (from, to) => {
return Object.values(workQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
resolve: {
workPage: workPageResolver,
selectedAuthorsPage: selectedAuthorsResolver,
selectedInstitutionsPage: selectedInstitutionsResolver,
},
data: {
resolvingFor: RESOLVING_WORK_PAGE_FOR.TOPIC,
},
},
],
},
{
path: 'projects',
canActivate: [
@@ -0,0 +1,195 @@
import {
Directive,
ElementRef,
OnDestroy,
Injector,
ComponentRef,
HostListener,
input,
inject,
effect,
InputSignal,
} from '@angular/core';
import {
Overlay,
OverlayRef,
OverlayPositionBuilder,
ConnectedPosition,
} from '@angular/cdk/overlay';
import { ComponentPortal, ComponentType } from '@angular/cdk/portal';
type UnwrapInputSignals<T> = {
[K in keyof T]: T[K] extends InputSignal<infer V> ? V : T[K];
};
@Directive({
selector: '[appComponentTooltip]',
standalone: true,
})
export class ComponentTooltipDirective<T extends object> implements OnDestroy {
readonly component = input.required<ComponentType<T>>({
alias: 'appComponentTooltip',
});
readonly tooltipInputs = input<Partial<UnwrapInputSignals<T>> | null>(null);
readonly tooltipShowDelay = input(150);
readonly tooltipHideDelay = input(100);
readonly tooltipDisabled = input(false);
readonly tooltipMaxWidth = input<string | number | null>(null);
private readonly elementRef = inject(ElementRef);
private readonly overlay = inject(Overlay);
private readonly overlayPositionBuilder = inject(OverlayPositionBuilder);
private readonly injector = inject(Injector);
private overlayRef: OverlayRef | null = null;
private componentRef: ComponentRef<T> | null = null;
private showTimeout?: ReturnType<typeof setTimeout>;
private hideTimeout?: ReturnType<typeof setTimeout>;
private isOverHost = false;
private isOverOverlay = false;
constructor() {
effect(() => {
const inputs = this.tooltipInputs();
if (this.componentRef && inputs) {
for (const [key, value] of Object.entries(inputs)) {
this.componentRef.setInput(key, value);
}
}
});
effect(() => {
const maxWidth = this.tooltipMaxWidth();
if (this.overlayRef?.hasAttached()) {
this.applyMaxWidth(this.overlayRef.overlayElement, maxWidth);
}
});
}
@HostListener('mouseenter')
@HostListener('focus')
onEnter(): void {
if (this.tooltipDisabled()) return;
this.isOverHost = true;
clearTimeout(this.hideTimeout);
this.showTimeout = setTimeout(() => this.show(), this.tooltipShowDelay());
}
@HostListener('mouseleave')
@HostListener('blur')
onLeave(): void {
this.isOverHost = false;
clearTimeout(this.showTimeout);
this.scheduleHide();
}
private scheduleHide(): void {
this.hideTimeout = setTimeout(() => {
if (!this.isOverHost && !this.isOverOverlay) {
this.hide();
}
}, this.tooltipHideDelay());
}
private show(): void {
if (this.overlayRef?.hasAttached()) return;
const positions: ConnectedPosition[] = [
{
originX: 'center',
originY: 'top',
overlayX: 'center',
overlayY: 'bottom',
offsetY: -8,
},
{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
offsetY: 8,
},
{
originX: 'end',
originY: 'center',
overlayX: 'start',
overlayY: 'center',
offsetX: 8,
},
{
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: -8,
},
];
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions(positions)
.withFlexibleDimensions(false)
.withPush(true);
this.overlayRef = this.overlay.create({
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.reposition(),
panelClass: 'app-tooltip-panel',
});
const portal = new ComponentPortal(this.component(), null, this.injector);
this.componentRef = this.overlayRef.attach(portal);
const inputs = this.tooltipInputs();
if (inputs) {
for (const [key, value] of Object.entries(inputs)) {
this.componentRef!.setInput(key, value);
}
}
const overlayElement = this.overlayRef.overlayElement;
this.applyMaxWidth(overlayElement, this.tooltipMaxWidth());
overlayElement.addEventListener('mouseenter', this.onOverlayEnter);
overlayElement.addEventListener('mouseleave', this.onOverlayLeave);
}
private applyMaxWidth(
element: HTMLElement,
maxWidth: string | number | null,
): void {
if (maxWidth === null) {
element.style.maxWidth = '';
return;
}
element.style.maxWidth =
typeof maxWidth === 'number' ? `${maxWidth}px` : maxWidth;
}
private readonly onOverlayEnter = (): void => {
this.isOverOverlay = true;
clearTimeout(this.hideTimeout);
};
private readonly onOverlayLeave = (): void => {
this.isOverOverlay = false;
this.scheduleHide();
};
private hide(): void {
if (this.overlayRef) {
const overlayElement = this.overlayRef.overlayElement;
overlayElement.removeEventListener('mouseenter', this.onOverlayEnter);
overlayElement.removeEventListener('mouseleave', this.onOverlayLeave);
this.overlayRef.detach();
}
this.componentRef = null;
}
ngOnDestroy(): void {
clearTimeout(this.showTimeout);
clearTimeout(this.hideTimeout);
this.overlayRef?.dispose();
}
}
@@ -0,0 +1,136 @@
import {
ConnectedPosition,
Overlay,
OverlayPositionBuilder,
OverlayRef,
} from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import {
Directive,
effect,
ElementRef,
HostListener,
inject,
input,
OnDestroy,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
@Directive({
selector: '[appTooltip]',
standalone: true,
})
export class TooltipDirective<T> implements OnDestroy {
readonly template = input.required<TemplateRef<T>>({ alias: 'appTooltip' });
readonly tooltipContext = input<T | null>(null);
readonly tooltipShowDelay = input<number>(150);
readonly tooltipHideDelay = input<number>(150);
readonly tooltipDisabled = input<boolean>(false);
private readonly elementRef = inject(ElementRef);
private readonly overlay = inject(Overlay);
private readonly overlayPositionBuilder = inject(OverlayPositionBuilder);
private readonly viewContainerRef = inject(ViewContainerRef);
private overlayRef: OverlayRef | null = null;
private portal: TemplatePortal<T> | null = null;
private showTimeout?: ReturnType<typeof setTimeout>;
private hideTimeout?: ReturnType<typeof setTimeout>;
constructor() {
effect(() => {
const context = this.tooltipContext();
if (this.portal?.isAttached) {
Object.assign(this.portal.context as object, context ?? {});
}
});
}
@HostListener('mouseenter')
@HostListener('focus')
onEnter(): void {
if (this.tooltipDisabled()) {
return;
}
clearTimeout(this.hideTimeout);
this.showTimeout = setTimeout(() => this.show(), this.tooltipShowDelay());
}
@HostListener('mouseleave')
@HostListener('blur')
onLeave(): void {
clearTimeout(this.showTimeout);
this.hideTimeout = setTimeout(() => this.hide(), this.tooltipHideDelay());
}
private show(): void {
if (this.overlayRef?.hasAttached()) return;
const positions: ConnectedPosition[] = [
{
originX: 'center',
originY: 'top',
overlayX: 'center',
overlayY: 'bottom',
offsetY: -8,
},
{
originX: 'center',
originY: 'bottom',
overlayX: 'center',
overlayY: 'top',
offsetY: 8,
},
{
originX: 'end',
originY: 'center',
overlayX: 'start',
overlayY: 'center',
offsetX: 8,
},
{
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: -8,
},
];
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions(positions)
.withFlexibleDimensions(false)
.withPush(true);
this.overlayRef = this.overlay.create({
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.reposition(),
panelClass: 'app-tooltip-panel',
});
this.portal = new TemplatePortal(
this.template(),
this.viewContainerRef,
(this.tooltipContext() ?? {}) as T,
);
this.overlayRef.attach(this.portal);
}
private hide(): void {
this.overlayRef?.detach();
this.portal = null;
}
ngOnDestroy(): void {
clearTimeout(this.showTimeout);
clearTimeout(this.hideTimeout);
this.overlayRef?.dispose();
}
}
@@ -23,10 +23,11 @@ h1,
h2,
p {
margin: 0;
color: var(--sg-text);
}
.page-header p {
color: #64748b;
color: var(--sg-text-muted);
margin-top: 6px;
}
@@ -46,19 +47,19 @@ p {
}
.table-panel {
border: 1px solid #d7dde6;
border: 1px solid var(--sg-border);
border-radius: 8px;
background: #fff;
background: var(--sg-card-bg);
}
.table-header {
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid #e5e7eb;
border-bottom: 1px solid var(--sg-border);
}
.table-header span {
color: #64748b;
color: var(--sg-text-muted);
}
.table-wrap {
@@ -74,29 +75,29 @@ th,
td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid #edf1f7;
border-bottom: 1px solid var(--sg-border);
white-space: nowrap;
}
th {
color: #475569;
color: var(--sg-text);
font-weight: 700;
background: #f8fafc;
background: var(--sg-surface-muted);
}
tr.deleted {
color: #94a3b8;
color: var(--sg-text-soft);
}
tr.deactivated:not(.deleted) {
color: #64748b;
background: #f8fafc;
color: var(--sg-text-muted);
background: var(--sg-surface-soft);
}
.link-button {
border: 0;
background: transparent;
color: #1d4ed8;
color: var(--sg-blue-highlight);
padding: 0;
font: inherit;
cursor: pointer;
@@ -109,25 +110,25 @@ tr.deactivated:not(.deleted) {
min-height: 24px;
border-radius: 999px;
padding: 2px 10px;
background: #eef2ff;
color: #3730a3;
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
font-size: 12px;
font-weight: 700;
}
.status {
background: #dcfce7;
color: #166534;
background: var(--sg-success-soft);
color: var(--sg-success);
}
.status--deleted {
background: #fee2e2;
color: #991b1b;
background: var(--sg-error-soft);
color: var(--sg-error);
}
.status--deactivated {
background: #fef3c7;
color: #92400e;
background: var(--sg-warning-soft);
color: var(--sg-warning);
}
.row-actions {
@@ -135,7 +136,7 @@ tr.deactivated:not(.deleted) {
}
.empty {
color: #64748b;
color: var(--sg-text-muted);
text-align: center;
}
@@ -6,10 +6,14 @@
background:
radial-gradient(
circle at top left,
rgba(61, 124, 255, 0.12),
color-mix(in srgb, var(--sg-primary) 15%, transparent),
transparent 34%
),
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
linear-gradient(
160deg,
var(--sg-surface-muted) 0%,
var(--sg-background) 64%
);
}
.login-panel {
@@ -80,7 +84,7 @@ p {
.step--active span {
background: var(--sg-primary);
border-color: var(--sg-primary);
color: #ffffff;
color: var(--sg-background);
}
.step-line {
@@ -158,7 +162,7 @@ p {
}
.expiry--expired {
color: #ba1a1a;
color: var(--sg-error);
}
@media (max-width: 560px) {
@@ -16,15 +16,16 @@
h1 {
margin: 2px 0 6px;
font-size: 2rem;
color: var(--sg-text);
}
p {
margin: 0;
color: #667085;
color: var(--sg-text-muted);
}
.eyebrow {
color: #3f51b5;
color: var(--sg-primary);
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.12em;
@@ -38,21 +39,22 @@
align-items: center;
gap: 0 10px;
padding: 14px 18px;
border: 1px solid #e4e7ec;
border: 1px solid var(--sg-border);
border-radius: 14px;
background: white;
background: var(--sg-surface);
mat-icon {
grid-row: 1 / 3;
color: #3f51b5;
color: var(--sg-primary);
}
strong {
font-size: 1.25rem;
color: var(--sg-text);
}
span {
color: #667085;
color: var(--sg-text-muted);
font-size: 0.75rem;
}
}
@@ -71,19 +73,19 @@
align-items: center;
justify-content: center;
text-align: center;
color: #667085;
color: var(--sg-text-muted);
}
.empty-state mat-icon {
width: 54px;
height: 54px;
font-size: 54px;
color: #98a2b3;
color: var(--sg-text-soft);
}
.empty-state h2 {
margin: 16px 0 6px;
color: #1d2939;
color: var(--sg-text);
}
@media (max-width: 700px) {

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