Compare commits

...
Author SHA1 Message Date
farajollahi 470b9095c4 implement multi language function
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-08-04 08:50:07 +02:00
farajollahi a25d70466f Merge pull request 'dfg-topics-treemap' (#259) from dfg-topics-treemap into dev
LocationBasedServices/smartguide/pipeline/head Build queued...
Reviewed-on: #259
2026-08-03 14:09:35 +02:00
farajollahi 4270dafd6a Merge branch 'dev' into dfg-topics-treemap
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-03 13:56:38 +02:00
Mats Paul Tončik fc3baef406 fix: executed ruff check --fix
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-02 14:13:53 +02:00
Mats Paul Tončik be20407238 feat: added publication tooltip; added tooltips for person network tables
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-02 14:01:08 +02:00
Mats Paul Tončik 26c4dc8fe7 feat(theming): changed theme selector from cycling to menu
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-02 13:34:21 +02:00
Mats Paul Tončik 4dd124d003 fix(person-network): deactivated legend hover link emphasis and justified graph center
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-02 12:55:23 +02:00
Roman ee40f1386a fix(institution-membership): apply dashboard year ranges to person membership
LocationBasedServices/smartguide/pipeline/head This commit looks good
- add bounded affiliation year-range support
- apply dashboard period filters to person counts and navigation
- use active institution membership directly in ranking
- remove the obsolete author filter helper
- move the Personen card before Patente
2026-08-02 01:46:26 +02:00
Roman 4f116d3ca2 fix(echarts): align research and company charts with dark mode
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-02 00:34:31 +02:00
kuzko 9ef1ce7ce1 Merge pull request 'refactor/trend_visual' (#258) from refactor/trend_visual into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #258
2026-08-01 21:57:20 +02:00
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 345dffaa9b implement treemap
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 11:54:10 +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
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
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
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
1056 changed files with 38411 additions and 187618 deletions
@@ -5,7 +5,6 @@ from typing import Any
from openalex_client import get_all_author_works
BASE_DIR = Path(__file__).resolve().parent
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
@@ -1,10 +1,10 @@
from collections.abc import Callable
from pathlib import Path
from typing import Callable, Literal
from typing import Literal
import matplotlib.pyplot as plt
import pandas as pd
BASE_DIR = Path(__file__).resolve().parent
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
PLOTS_DIR = BASE_DIR / "plots"
-1
View File
@@ -4,7 +4,6 @@ from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
REQUEST_TIMEOUT_SECONDS = 30
PER_PAGE = 200
+3 -2
View File
@@ -1,8 +1,9 @@
import os
import requests
from requests.adapters import HTTPAdapter
from urllib.parse import quote
import requests
from dotenv import load_dotenv
from requests.adapters import HTTPAdapter
load_dotenv()
+2 -2
View File
@@ -1,7 +1,7 @@
import os
import requests
from openai import OpenAI, APIConnectionError
from dotenv import load_dotenv
from openai import APIConnectionError, OpenAI
load_dotenv()
+5 -4
View File
@@ -1,12 +1,13 @@
import elastic.client as es_client
import llm.client as llm_client
import json
import argparse
import time
import json
import logging
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import elastic.client as es_client
import llm.client as llm_client
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
@@ -3,7 +3,6 @@ from pathlib import Path
from llama_parse import LlamaParse
BASE_DIR = Path(__file__).resolve().parent
AD_PATH = BASE_DIR / "AD.pdf"
@@ -1,7 +1,7 @@
import pymupdf4llm
AD_PATH = "188274\AD.pdf"
CD_PATH = "188274\СD.pdf"
AD_PATH = r"188274\AD.pdf"
CD_PATH = r"188274\СD.pdf"
ad_md = pymupdf4llm.to_markdown(AD_PATH)
cd_md = pymupdf4llm.to_markdown(CD_PATH)
+2 -2
View File
@@ -1,7 +1,7 @@
from pathlib import Path
import getpass
import json
import os
from pathlib import Path
import pymupdf
import requests
@@ -206,7 +206,7 @@ def make_debug_data(
) -> dict:
choice = {}
if "choices" in data and data["choices"]:
if data.get("choices"):
choice = data["choices"][0]
message = choice.get("message", {})
+2 -2
View File
@@ -1,7 +1,7 @@
from pathlib import Path
import getpass
import json
import os
from pathlib import Path
import requests
@@ -181,7 +181,7 @@ def make_debug_data(
):
choice = {}
if "choices" in data and data["choices"]:
if data.get("choices"):
choice = data["choices"][0]
message = choice.get("message", {})
@@ -1,5 +1,5 @@
from pathlib import Path
import json
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR
@@ -1,5 +1,5 @@
from pathlib import Path
import re
from pathlib import Path
import pymupdf
@@ -1,4 +1,5 @@
from pathlib import Path
import pymupdf # PyMuPDF
try:
@@ -7,7 +8,7 @@ except ImportError:
MarkItDown = None
AD_PATH = Path("154115\AD.pdf")
AD_PATH = Path(r"154115\AD.pdf")
OUT_DIR = Path("ad_extraction_outputs3")
OUT_DIR.mkdir(exist_ok=True)
@@ -3,9 +3,9 @@ from __future__ import annotations
import argparse
import json
from collections import Counter
from statistics import mean, median
from datetime import datetime, timezone
from pathlib import Path
from statistics import mean, median
from typing import Any
import requests
@@ -17,7 +17,7 @@ SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
if str(SERVICE_SOURCE_ROOT) not in sys.path:
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
from inse.authors.institution_membership_query import ( # noqa: E402
from inse.authors.institution_membership_query import (
build_institution_membership_query,
current_affiliation_year_cutoff,
)
@@ -852,9 +852,7 @@ def validate(result: dict[str, Any]) -> list[str]:
if score is None:
errors.append("basic_research_score_missing")
elif score_is_usable:
if quadrant == "pure_basic" and not 0 <= score <= 30:
errors.append("basic_research_quadrant_score_mismatch")
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
if quadrant == "pure_basic" and not 0 <= score <= 30 or quadrant == "use_inspired_basic" and not 25 <= score <= 45:
errors.append("basic_research_quadrant_score_mismatch")
if quadrant not in {"pure_basic", "use_inspired_basic"}:
errors.append("basic_research_quadrant_mismatch")
@@ -26,12 +26,12 @@ import json
import os
import sys
from collections import defaultdict
from collections.abc import Iterable
from pathlib import Path
from typing import Any, Iterable
from typing import Any
import requests
DEFAULT_AUTHOR_ID = "A5034365278"
DEFAULT_WORK_YEAR_GTE = 1950
SOURCE_INDEX = "openalex-works*"
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
def safe_rate(
numerator: int | float,
denominator: int | float,
numerator: float,
denominator: float,
) -> float | None:
if not denominator:
return None
@@ -13,7 +13,6 @@ from typing import Any
from openai import OpenAI
ROOT = Path(__file__).resolve().parent
PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt"
CONSENSUS_FILE = ROOT / "consensus_reference.json"
@@ -282,7 +281,7 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
return 0.0
def safe_rate(numerator: int | float, denominator: int | float) -> float | None:
def safe_rate(numerator: float, denominator: float) -> float | None:
if not denominator:
return None
return numerator / denominator
@@ -3,13 +3,13 @@ from __future__ import annotations
import argparse
import json
from collections import Counter
from collections.abc import Callable, Iterable
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Iterable
from typing import Any
import requests
ROOT = Path(__file__).resolve().parent
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from ollama import Client
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
DATA_FOLDER = "data"
@@ -1,9 +1,9 @@
import os
import json
import os
from concurrent.futures import ThreadPoolExecutor
from time import time
from openai import OpenAI, APIConnectionError
from openai import APIConnectionError, OpenAI
DATA_FOLDER = "data2"
BATCH_SIZE = 6
+3 -1
View File
@@ -1,5 +1,7 @@
import requests, json
import json
import helpers
import requests
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
#AUTHOR_OPEN_ALEXID = ["A5047117780"]
+3 -1
View File
@@ -1,5 +1,7 @@
import requests, json
import json
import helpers
import requests
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
@@ -1,4 +1,5 @@
import os
import requests
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic")
+1 -1
View File
@@ -2,8 +2,8 @@ import os
from concurrent.futures import ThreadPoolExecutor
from time import time
from openai import OpenAI, APIConnectionError
import helpers
from openai import APIConnectionError, OpenAI
DATA_FOLDER = "data2"
BATCH_SIZE = 6
@@ -1,9 +1,11 @@
from typing import Any, Iterator
from elasticsearch import Elasticsearch
from collections import defaultdict
import json
from collections import defaultdict
from collections.abc import Iterator
from pathlib import Path
from elasticsearch import NotFoundError
from typing import Any
from elasticsearch import Elasticsearch, NotFoundError
# elasticseach library required. Here used elasticsearch==8.0.0
# estimated execution time: 3-5 Minutes
@@ -1,5 +1,5 @@
import os
import json
import os
from time import time
from llm_classify_news import call, parse_label, parse_persons
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Baut aus den JSON-Dateien in data2/ eine eigenstaendige viewer.html.
@@ -8,8 +7,8 @@ mit Vor/Zurueck durch die News blaettern. Oben stehen _id, llm_label und
llm_persons, darunter der full_content als reiner Text (kein Parsing).
"""
import os
import json
import os
DATA_FOLDER = "validation_data"
OUTPUT_FILE = "viewer.html"
@@ -1,5 +1,5 @@
import os
import json
import os
import random
import requests
@@ -1,10 +1,9 @@
import os
import json
import os
import random
import requests
from openai import OpenAI, APIConnectionError
from openai import APIConnectionError, OpenAI
INSE_URL = "https://inse.nes.uni-due.de/elastic"
INDEX_URL = f"{INSE_URL}/aktuell"
@@ -1,5 +1,5 @@
import os
import json
import os
DATA_FOLDER = "data2"
@@ -1,4 +1,5 @@
import json
from tabulate import tabulate
result_files = [
@@ -1,6 +1,7 @@
from urllib.parse import quote
import requests
from requests.adapters import HTTPAdapter
from urllib.parse import quote
INSE_URL = "https://inse.nes.uni-due.de/elastic"
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
@@ -1,5 +1,4 @@
import requests
from openai import OpenAI, APIConnectionError
from openai import APIConnectionError, OpenAI
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
@@ -1,10 +1,12 @@
import argparse
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import elastic.client as es_client
import llm.client as llm_client
import json
import argparse
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
def print_pretty_json(data):
print(json.dumps(data, indent=2))
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
import os
import sys
import json
import time
import asyncio
import json
import sys
import time
from pathlib import Path
import httpx
import numpy as np
@@ -14,6 +14,7 @@ project_root = current_dir.parent.parent.resolve()
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
from dotenv import load_dotenv
load_dotenv(dotenv_path=env_path)
sys.path.append(str(project_root / "service" / "src" / "main"))
@@ -311,7 +312,7 @@ async def evaluate():
try:
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
resp.raise_for_status()
except Exception as exc:
except Exception:
# Log error but don't crash
pass
t1 = time.perf_counter()
@@ -4,15 +4,14 @@ Professional evaluation pipeline to benchmark different Sentence Transformer mod
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
Taxonomy Clustering metrics, and operational performance metrics.
"""
import os
import sys
import json
import time
import argparse
import json
import random
import sys
import time
from pathlib import Path
import httpx
import numpy as np
from dotenv import load_dotenv
# Add service/src/main to python path to load settings
@@ -30,8 +29,8 @@ API_KEY = settings.elasticsearch_api_key
# Import evaluation libraries
from sentence_transformers import SentenceTransformer
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sklearn.cluster import KMeans
from sklearn import metrics
from sklearn.cluster import KMeans
DEFAULT_MODELS = [
"paraphrase-multilingual-mpnet-base-v2",
@@ -161,9 +160,9 @@ def evaluate_model(model_name, data, output_dir):
model_safe_name = model_name.replace("/", "_").replace("-", "_")
report_file = output_dir / f"model_report_{model_safe_name}.json"
print(f"\n==================================================")
print("\n==================================================")
print(f"Evaluating Model: '{model_name}'")
print(f"==================================================")
print("==================================================")
start_load = time.time()
try:
+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
+1 -1
View File
@@ -1,6 +1,6 @@
import logging
import sys
import time
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
map_news_topics.py — Map news keywords to OpenAlex topics.
@@ -37,7 +37,7 @@ import json
import logging
import os
import sys
from datetime import datetime, timezone
from datetime import UTC, datetime
from pathlib import Path
from dotenv import load_dotenv
@@ -121,7 +121,7 @@ async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str,
async def run(args: argparse.Namespace) -> None:
built_at = datetime.now(timezone.utc).isoformat()
built_at = datetime.now(UTC).isoformat()
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await base.check_backend(args.api_base_url)
@@ -3,10 +3,8 @@
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy import signals
class AktuellSpiderMiddleware:
@@ -5,7 +5,6 @@
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class AktuellPipeline:
@@ -1,5 +1,6 @@
import scrapy
class LinksCrawler(scrapy.Spider):
name = "aktuell-links"
@@ -1,8 +1,10 @@
import scrapy
import json
from scrapy.linkextractors import LinkExtractor
import os
import scrapy
from scrapy.linkextractors import LinkExtractor
class MetaDataCrawler(scrapy.Spider):
name = "aktuell-metadata"
@@ -1,11 +1,12 @@
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from random import randint
import time
import sys
import time
from random import randint
from elasticsearch import Elasticsearch
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
es = Elasticsearch()
@@ -32,7 +33,7 @@ def getLinks(link, driver):
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
if elem == "Zurück zum Gesamtüberblick":
break
except NoSuchElementException as nsee:
except NoSuchElementException:
break
# get date
@@ -45,7 +46,7 @@ def getLinks(link, driver):
link = ""
try:
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
except NoSuchElementException as nsee:
except NoSuchElementException:
continue
links.append(link)
@@ -67,17 +68,17 @@ def getData(driver, link, date, date_year, date_num):
subtitle = ""
try:
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
except NoSuchElementException as nsee:
except NoSuchElementException:
pass
maintitle = ""
try:
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
except NoSuchElementException as nsee:
except NoSuchElementException:
pass
redaktion = ""
try:
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
except NoSuchElementException as nsee:
except NoSuchElementException:
pass
author = ""
if redaktion != "":
@@ -86,7 +87,7 @@ def getData(driver, link, date, date_year, date_num):
main_content = ""
try:
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
except NoSuchElementException as nsee:
except NoSuchElementException:
pass
full_content = main_content
+5 -5
View File
@@ -1,10 +1,10 @@
import subprocess
import sys
import os
import shutil
import time
import argparse
import logging
import os
import shutil
import subprocess
import sys
import time
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
+3 -3
View File
@@ -1,8 +1,8 @@
import sys
import os
import json
import time
import logging
import os
import sys
import time
from urllib.parse import quote
import requests
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
evaluate_keyword_patent_search.py — Systematic evaluation for keyword → patent search.
@@ -23,14 +23,14 @@ import asyncio
import json
import logging
import sys
from datetime import datetime, timezone
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent.parent / "src" / "main"))
from inse.patents.keywords.eval_metrics import ( # noqa: E402
from inse.patents.keywords.eval_metrics import (
analyze_family_duplicates_in_top_k,
average_precision,
ipc_prefix_hit_rate,
@@ -43,13 +43,13 @@ from inse.patents.keywords.eval_metrics import ( # noqa: E402
recall_at_k,
unique_family_precision_at_k,
)
from inse.patents.keywords.logic import ( # noqa: E402
from inse.patents.keywords.logic import (
_DEFAULT_SCORE_WEIGHTS,
_MAX_PATENTS,
_compute_final_score,
get_patents_by_keywords,
)
from inse.patents.keywords.model import ( # noqa: E402
from inse.patents.keywords.model import (
KeywordPatentMatch,
KeywordPatentSearchDiagnostics,
KeywordPatentSearchItem,
@@ -721,9 +721,7 @@ def _load_prior_candidate_grades(
if existing is None:
bucket[patent_id] = dict(candidate)
continue
if existing.get("grade") is None and grade is not None:
bucket[patent_id] = dict(candidate)
elif existing.get("grade") is None:
if existing.get("grade") is None and grade is not None or existing.get("grade") is None:
bucket[patent_id] = dict(candidate)
return by_case
@@ -884,7 +882,7 @@ async def cmd_bootstrap(args: argparse.Namespace) -> int:
}
)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
labeling_path = out_dir / f"labeling_{stamp}.json"
report_path = out_dir / f"bootstrap_report_{stamp}.json"
@@ -979,7 +977,7 @@ async def cmd_eval(args: argparse.Namespace) -> int:
if presentation
else _aggregate(case_reports, ks)
)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
report_name = "presentation_eval_report" if presentation else "eval_report"
report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json"
_write_json(
@@ -1071,7 +1069,7 @@ async def cmd_ablation(args: argparse.Namespace) -> int:
f"P@10={p10}"
)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
report_path = Path(args.out_dir) / f"ablation_report_{stamp}.json"
_write_json(
report_path,
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
+14 -16
View File
@@ -1,23 +1,21 @@
import argparse
import hashlib
import json
import logging
import math
import os
import time
from datetime import datetime
import pandas as pd
import requests
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
from random import randint
import time
import pandas as pd
import json
from datetime import datetime
import sys
import os
import math
import requests
import hashlib
import argparse
import logging
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
map_project_topics.py — Map project keywords to OpenAlex topics.
@@ -52,9 +52,10 @@ import json
import logging
import os
import sys
from datetime import datetime, timezone
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, AsyncIterator
from typing import Any
import httpx
from dotenv import load_dotenv
@@ -396,7 +397,7 @@ async def bulk_index(index: str, cluster: str, documents: list[tuple[str, dict]]
async def run(args: argparse.Namespace) -> None:
built_at = datetime.now(timezone.utc).isoformat()
built_at = datetime.now(UTC).isoformat()
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await check_backend(args.api_base_url)
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
test_keywords_matching.py
+23 -4
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
"""
Download the sentence-transformers model to the default cache directory
so it is available for local runs or testing.
@@ -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.")
+5 -4
View File
@@ -1,12 +1,13 @@
#!/usr/bin/env python3
"""
Script to fetch all topics from 'openalex-topics',
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector mapping.
"""
import sys
import json
import sys
from pathlib import Path
import httpx
from dotenv import load_dotenv
@@ -26,7 +27,6 @@ API_KEY = settings.elasticsearch_api_key
MODEL_NAME = settings.sentence_transformers_model_name
# Import sentence-transformers
from sentence_transformers import SentenceTransformer
headers = {
"Authorization": f"ApiKey {API_KEY}",
@@ -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
@@ -1,5 +1,4 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field, model_validator
@@ -9,14 +8,14 @@ from inse.auth.model import UserRole, normalize_roles
class OrganizationProfile(BaseModel):
id: uuid.UUID
name: str
openalex_institution_id: Optional[str] = None
openalex_institution_id: str | None = None
class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
roles: List[UserRole]
roles: list[UserRole]
organization_id: uuid.UUID
organization_name: str
deleted: bool
@@ -27,7 +26,7 @@ class AccountProfile(BaseModel):
class AccountPage(BaseModel):
items: List[AccountProfile]
items: list[AccountProfile]
total: int
page: int
page_size: int
@@ -43,10 +42,10 @@ class CreateAccountRequest(BaseModel):
email: str = Field(min_length=3)
name: str = Field(min_length=1)
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
roles: list[UserRole] = Field(default_factory=lambda: [UserRole.USER])
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
openalex_person_id: str | None = None
@model_validator(mode="after")
def _normalize_roles(self):
@@ -62,14 +61,14 @@ class UpdateAccountRequest(BaseModel):
values = {**values, "roles": [values["role"]]}
return values
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
roles: Optional[List[UserRole]] = None
organization_id: Optional[uuid.UUID] = None
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
activated: Optional[bool] = None
email: str | None = Field(default=None, min_length=3)
name: str | None = Field(default=None, min_length=1)
roles: list[UserRole] | None = None
organization_id: uuid.UUID | None = None
password: str | None = Field(default=None, min_length=8)
openalex_person_id: str | None = None
deleted: bool | None = None
activated: bool | None = None
@model_validator(mode="after")
def _normalize_roles(self):
@@ -1,5 +1,5 @@
import uuid
from typing import Annotated, Optional
from typing import Annotated
from fastapi import APIRouter, Query, Response, status
@@ -40,8 +40,8 @@ async def list_accounts(
page: Annotated[int, Query(ge=0)] = 0,
page_size: Annotated[int, Query(ge=1, le=100)] = 10,
offset: Annotated[int, Query(ge=0)] = 0,
search: Annotated[Optional[str], Query()] = None,
organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
search: Annotated[str | None, Query()] = None,
organization_id: Annotated[uuid.UUID | None, Query()] = None,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage:
return service.list_accounts(
@@ -1,5 +1,4 @@
import uuid
from typing import Optional
from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
@@ -84,7 +83,7 @@ def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata
def _ensure_email_available(
session: Session,
email: str,
excluded_account_id: Optional[uuid.UUID] = None,
excluded_account_id: uuid.UUID | None = None,
) -> None:
normalized_email = email.lower().strip()
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
@@ -115,9 +114,9 @@ def list_accounts(
access_token: AccessTokenMetadata,
page: int,
page_size: int,
offset: Optional[int] = None,
search: Optional[str] = None,
organization_id: Optional[uuid.UUID] = None,
offset: int | None = None,
search: str | None = None,
organization_id: uuid.UUID | None = None,
) -> AccountPage:
if access_token.effective_role not in {
UserRole.SUPER_ADMIN,
+7 -8
View File
@@ -1,7 +1,6 @@
import uuid
from datetime import datetime
from enum import StrEnum
from typing import List
from pydantic import BaseModel, model_validator
from sqlalchemy import JSON, Column, UniqueConstraint
@@ -24,8 +23,8 @@ ROLE_PRIORITY = {
def normalize_roles(
roles: List[UserRole] | List[str] | UserRole | str | None,
) -> List[UserRole]:
roles: list[UserRole] | list[str] | UserRole | str | None,
) -> list[UserRole]:
if roles is None:
return [UserRole.USER]
if isinstance(roles, (str, UserRole)):
@@ -43,7 +42,7 @@ def normalize_roles(
def effective_role_for_roles(
roles: List[UserRole] | List[str] | UserRole | str | None,
roles: list[UserRole] | list[str] | UserRole | str | None,
) -> UserRole:
return normalize_roles(roles)[0]
@@ -86,7 +85,7 @@ class Organization(Durable, table=True):
description="The OpenAlex ID of the institution associated with the organization.",
)
accounts: List["Account"] = Relationship(back_populates="organization")
accounts: list["Account"] = Relationship(back_populates="organization")
class Account(Durable, table=True):
@@ -141,7 +140,7 @@ class Account(Durable, table=True):
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
roles: List[UserRole] = Field(
roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
description="The roles this account holds within its organization.",
@@ -249,7 +248,7 @@ class AccessTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
effective_roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
@@ -300,7 +299,7 @@ class RefreshTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
effective_roles: list[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
+3 -4
View File
@@ -1,14 +1,11 @@
import logging
from typing import Annotated
import uuid
from typing import Annotated
from fastapi import APIRouter, Body, Depends, Response, status
from sqlmodel import Session
from inse.tags import Tags
import inse.auth.service as auth_service
from inse.database import SessionDep, get_session
from inse.auth.model import (
AccessResponse,
AccessToken,
@@ -18,6 +15,8 @@ from inse.auth.model import (
OtkResponse,
RefreshTokenMetadata,
)
from inse.database import SessionDep, get_session
from inse.tags import Tags
logger = logging.getLogger(__name__)
+30 -34
View File
@@ -4,7 +4,7 @@ import json
import logging
import secrets
import uuid
from typing import Annotated, Any, Dict, Optional
from typing import Annotated, Any
import jwt
from argon2 import PasswordHasher
@@ -95,7 +95,7 @@ def create_predefined_accounts(session: Session, file_path: str):
try:
with open(file_path, "r") as file:
data: Dict[str, Any] = json.loads(file.read())
data: dict[str, Any] = json.loads(file.read())
for organization_data in data.get("organizations", []):
organization_id = organization_data.get("id")
if organization_id is not None:
@@ -215,7 +215,7 @@ def request_otk(session: Session, email: str, password: str):
account = session.exec(
select(Account).where(
Account.email == email,
Account.deleted == False, # noqa: E712
Account.deleted == False,
)
).first()
@@ -254,7 +254,7 @@ def request_otk(session: Session, email: str, password: str):
)
).first()
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=OTK_EXPIRATION_MINUTES
)
@@ -293,19 +293,19 @@ def request_otk(session: Session, email: str, password: str):
return OtkResponse(status="success", account_id=account.id)
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
def request_password_reset(session: Session, email: str) -> dict[str, Any]:
"""Requests a one-time password reset link for the given email address.
For security reasons, this function always returns a successful response and
does not reveal whether the email address belongs to an active account.
"""
email = email.lower().strip()
now = datetime.datetime.now(datetime.timezone.utc)
now = datetime.datetime.now(datetime.UTC)
account = session.exec(
select(Account).where(
Account.email == email,
Account.deleted == False, # noqa: E712
Account.deleted == False,
)
).first()
@@ -328,9 +328,7 @@ def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
if secret.request_window_started_at is not None:
window_started_at = secret.request_window_started_at
if getattr(window_started_at, "tzinfo", None) is None:
window_started_at = window_started_at.replace(
tzinfo=datetime.timezone.utc
)
window_started_at = window_started_at.replace(tzinfo=datetime.UTC)
window_ends_at = window_started_at + datetime.timedelta(
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
@@ -435,7 +433,7 @@ def reset_password(
session: Session,
reset_token: str,
new_password: str,
) -> Dict[str, str]:
) -> dict[str, str]:
"""Resets an account password using a one-time password reset token.
Args:
@@ -449,7 +447,7 @@ def reset_password(
Returns:
Dict[str, str]: A status response.
"""
now = datetime.datetime.now(datetime.timezone.utc)
now = datetime.datetime.now(datetime.UTC)
reset_token_hash = _hash_reset_token(reset_token.strip())
secret = session.exec(
@@ -467,7 +465,7 @@ def reset_password(
secret_expires = secret.expires_at
if getattr(secret_expires, "tzinfo", None) is None:
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
if secret_expires <= now:
session.delete(secret)
@@ -515,7 +513,7 @@ def login(
Returns:
LoginResponse: The response containing the ID token issued upon successful login.
"""
now = datetime.datetime.now(datetime.timezone.utc)
now = datetime.datetime.now(datetime.UTC)
secret = session.exec(
select(Secret).where(
@@ -536,7 +534,7 @@ def login(
secret_expires = secret.expires_at
if getattr(secret_expires, "tzinfo", None) is None:
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
if secret_expires <= now:
logger.warning("Login failed: invalid or expired code %s", email_code)
@@ -611,7 +609,7 @@ def _get_current_user_access_token_payload(
real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
access_token_payload["exp"], tz=datetime.timezone.utc
access_token_payload["exp"], tz=datetime.UTC
),
epoch=access_token_payload[EPOCH_KEY],
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
@@ -657,7 +655,7 @@ def _get_current_user_refresh_token_payload(
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
refresh_token_payload["exp"], tz=datetime.timezone.utc
refresh_token_payload["exp"], tz=datetime.UTC
),
epoch=refresh_token_payload[EPOCH_KEY],
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
@@ -708,7 +706,7 @@ def _get_current_user_id_token_payload(
return IdTokenMetadata(
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp(
id_token_payload["exp"], tz=datetime.timezone.utc
id_token_payload["exp"], tz=datetime.UTC
),
epoch=id_token_payload[EPOCH_KEY],
)
@@ -784,9 +782,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
return account.organization_id
def _get_account_institution_id(
session: Session, account_id: uuid.UUID
) -> Optional[str]:
def _get_account_institution_id(session: Session, account_id: uuid.UUID) -> str | None:
"""Retrieves the OpenAlex institution ID for the given account ID.
Args:
@@ -872,7 +868,7 @@ def get_access_token(
session: Session,
id_token: IdTokenMetadata,
real_account_id: uuid.UUID,
effective_account_id: Optional[uuid.UUID] = None,
effective_account_id: uuid.UUID | None = None,
) -> AccessResponse:
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
@@ -1054,7 +1050,7 @@ def _build_id_token(
Returns:
IdToken: The generated ID token object.
"""
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=ID_TOKEN_EXPIRATION_MINUTES
)
payload = {
@@ -1082,7 +1078,7 @@ def _set_refresh_token(
effective_organization_id: uuid.UUID,
epoch: int,
effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None,
effective_institution_id: str | None = None,
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1098,7 +1094,7 @@ def _set_refresh_token(
Returns:
RefreshTokenMetadata: The generated refresh token object.
"""
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
@@ -1137,7 +1133,7 @@ def _build_access_token(
epoch: int,
user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None,
effective_institution_id: str | None = None,
) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1153,7 +1149,7 @@ def _build_access_token(
Returns:
AccessToken: The generated access token object.
"""
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
@@ -1189,7 +1185,7 @@ def _build_access_token(
def _build_token(
payload: Dict[str, Any],
payload: dict[str, Any],
expiration_datetime: datetime.datetime,
token_type: TokenType,
) -> str:
@@ -1203,7 +1199,7 @@ def _build_token(
Returns:
str: The encoded JWT token.
"""
now = datetime.datetime.now(datetime.timezone.utc)
now = datetime.datetime.now(datetime.UTC)
payload.update(
{
"exp": expiration_datetime,
@@ -1219,7 +1215,7 @@ def _build_token(
return token
def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
def _verify_id_token(raw_id_token: str, session: Session) -> dict[str, Any]:
"""Verifies the provided ID token and returns the decoded payload if valid.
Args:
@@ -1239,7 +1235,7 @@ def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
return payload
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]:
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> dict[str, Any]:
"""Verifies the provided refresh token and returns the decoded payload if valid.
Args:
@@ -1263,7 +1259,7 @@ def _verify_access_token_fp(
secure_fgp: str,
raw_access_token: str,
session: Session,
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
Args:
@@ -1381,7 +1377,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
return account
def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]:
def logout(session: Session, access_token: AccessTokenMetadata) -> dict[str, str]:
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
Args:
@@ -1408,7 +1404,7 @@ def change_password(
access_token: AccessTokenMetadata,
current_password: str,
new_password: str,
) -> Dict[str, str]:
) -> dict[str, str]:
"""Change the password for the user associated with the provided access token.
Args:
+17 -19
View File
@@ -1,24 +1,22 @@
import inse.config as config_module
import uuid
import pytest
from sqlmodel import Session, SQLModel, create_engine, select
from fastapi import Response, HTTPException
import datetime as _dt
import uuid
from datetime import timedelta
import pytest
from fastapi import HTTPException, Response
from sqlmodel import Session, SQLModel, create_engine, select
import inse.config as config_module
from inse.auth import service as auth_service
from inse.auth.model import (
AccessToken,
AccessTokenMetadata,
Account,
IdTokenMetadata,
Organization,
RefreshTokenMetadata,
Secret,
SecretPurpose,
AccessToken,
IdTokenMetadata,
AccessTokenMetadata,
RefreshTokenMetadata,
UserRole,
)
@@ -188,7 +186,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
),
expires_at=_dt.datetime.fromtimestamp(
refresh_payload["exp"], tz=_dt.timezone.utc
refresh_payload["exp"], tz=_dt.UTC
),
epoch=refresh_payload[auth_service.EPOCH_KEY],
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
@@ -346,7 +344,7 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
expired_at = _dt.datetime.now(_dt.UTC) - timedelta(minutes=10)
secret = Secret(
account_id=acc.id,
purpose=SecretPurpose.LOGIN_OTK,
@@ -593,7 +591,7 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup):
assert acc.id is not None
response = Response()
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
past = _dt.datetime.now(_dt.UTC) - timedelta(minutes=5)
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
payload = {
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
@@ -624,7 +622,7 @@ def test_missing_hmac_key_raises_value_error(settings_backup):
with pytest.raises(ValueError):
auth_service._build_token(
payload={},
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
expiration_datetime=_dt.datetime.now(_dt.UTC),
token_type=auth_service.TokenType.ID_TOKEN,
)
config_module.settings.token_hmac_key = saved
@@ -715,7 +713,7 @@ def test_reset_password_changes_password_and_increments_epoch(in_memory_session)
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
)
in_memory_session.add(secret)
in_memory_session.commit()
@@ -753,7 +751,7 @@ def test_reset_password_rejects_reused_token(in_memory_session):
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
)
in_memory_session.add(secret)
in_memory_session.commit()
@@ -792,7 +790,7 @@ def test_reset_password_rejects_expired_token(in_memory_session):
account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token),
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
expires_at=_dt.datetime.now(_dt.UTC) - timedelta(minutes=1),
)
in_memory_session.add(secret)
in_memory_session.commit()
@@ -1,13 +1,12 @@
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime, timezone
from datetime import UTC, datetime
from typing import Any, Literal
AFFILIATION_LOOKBACK_YEARS = 2
OPENALEX_ID_PREFIX = "https://openalex.org/"
AffiliationYearMode = Literal["all", "in", "from"]
AffiliationYearMode = Literal["all", "in", "from", "between"]
def current_affiliation_year_cutoff(
@@ -21,7 +20,7 @@ def current_affiliation_year_cutoff(
when needed.
"""
current_time = reference_time or datetime.now(timezone.utc)
current_time = reference_time or datetime.now(UTC)
return current_time.year - AFFILIATION_LOOKBACK_YEARS
@@ -29,17 +28,20 @@ def build_institution_affiliation_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]:
"""Build an affiliation query for an institution and optional year rule.
``all`` accepts an affiliation from any year and requires ``year=None``.
``in`` requires an affiliation in exactly ``year``.
``from`` requires an affiliation in ``year`` or any later year.
``between`` requires an affiliation between ``year`` and ``year_to``,
including both boundary years.
Institution IDs are normalized to their full OpenAlex URL.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
_validate_year_mode(year_mode, year)
_validate_year_mode(year_mode, year, year_to)
affiliation_filters: list[dict[str, Any]] = [
{
@@ -56,6 +58,17 @@ def build_institution_affiliation_query(
affiliation_filters.append(
{"range": {"affiliations.years": {"gte": year}}}
)
elif year_mode == "between":
affiliation_filters.append(
{
"range": {
"affiliations.years": {
"gte": year,
"lte": year_to,
}
}
}
)
return {
"nested": {
@@ -69,6 +82,7 @@ def build_institution_membership_query(
institution_id: str,
year_mode: AffiliationYearMode = "all",
year: int | None = None,
year_to: int | None = None,
author_ids: Iterable[str] | None = None,
) -> dict[str, Any]:
"""Build an institution membership query for the selected year mode.
@@ -83,10 +97,11 @@ def build_institution_membership_query(
last-known institution IDs are available.
``in`` deliberately excludes condition 2 because an exact year requires
explicit affiliation evidence for that year. When ``author_ids`` are
supplied, the query is restricted to those authors in the same
Elasticsearch request. Empty ``author_ids`` produce ``match_none``.
Institution and author IDs are normalized to full OpenAlex URLs.
explicit affiliation evidence for that year. ``between`` applies the same
rule to its bounded period. When ``author_ids`` are supplied, the query is
restricted to those authors in the same Elasticsearch request. Empty
``author_ids`` produce ``match_none``. Institution and author IDs are
normalized to full OpenAlex URLs.
"""
normalized_institution_id = _normalize_openalex_id(institution_id)
@@ -94,6 +109,7 @@ def build_institution_membership_query(
normalized_institution_id,
year_mode=year_mode,
year=year,
year_to=year_to,
)
author_filters: list[dict[str, Any]] = []
@@ -158,7 +174,7 @@ def build_institution_membership_query(
}
},
]
if year_mode != "in":
if year_mode in {"all", "from"}:
# Last-known is the fallback only when affiliation IDs are unavailable.
membership_branches.insert(
1,
@@ -213,15 +229,28 @@ def build_active_institution_membership_query(
def _validate_year_mode(
year_mode: AffiliationYearMode,
year: int | None,
year_to: int | None,
) -> None:
if year_mode not in {"all", "in", "from"}:
if year_mode not in {"all", "in", "from", "between"}:
raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
if year_mode == "all":
if year is not None:
raise ValueError("year must be omitted when year_mode is 'all'")
if year is not None or year_to is not None:
raise ValueError(
"year and year_to must be omitted when year_mode is 'all'"
)
return
if isinstance(year, bool) or not isinstance(year, int):
raise ValueError(f"year is required when year_mode is '{year_mode}'")
if year_mode != "between":
if year_to is not None:
raise ValueError(
f"year_to must be omitted when year_mode is '{year_mode}'"
)
return
if isinstance(year_to, bool) or not isinstance(year_to, int):
raise ValueError("year_to is required when year_mode is 'between'")
if year > year_to:
raise ValueError("year must be less than or equal to year_to")
def _normalize_openalex_id(raw_id: str) -> str:
@@ -65,7 +65,7 @@ def mark_collaboration_graph_job_completed(
return
job.status = CollaborationGraphStatus.COMPLETED
job.set_result(result)
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
job.updated_at = datetime.datetime.now(datetime.UTC)
session.add(job)
session.commit()
@@ -86,7 +86,7 @@ def mark_collaboration_graph_job_failed(
return
job.status = CollaborationGraphStatus.FAILED
job.error_message = error_message
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
job.updated_at = datetime.datetime.now(datetime.UTC)
session.add(job)
session.commit()
@@ -103,7 +103,7 @@ def cleanup_old_collaboration_graph_jobs(
Returns:
int: The number of stale jobs that were cleaned up.
"""
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
cutoff_time = datetime.datetime.now(datetime.UTC) - max_age
statement = select(CollaborationGraphJob).where(
CollaborationGraphJob.created_at < cutoff_time
)
@@ -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=min(10000, len(author_ids)),
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,
+28 -29
View File
@@ -2,9 +2,8 @@
Database tables and API schemas for the background job runner.
"""
from datetime import datetime, timezone
from datetime import UTC, datetime
from enum import StrEnum
from typing import Optional
from pydantic import BaseModel
from sqlmodel import JSON, Column, Field, SQLModel
@@ -23,13 +22,13 @@ class JobTriggeredBy(StrEnum):
def utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
return datetime.now(UTC).replace(tzinfo=None)
class JobDefinition(SQLModel, table=True):
__tablename__ = "background_job_definition"
id: Optional[int] = Field(default=None, primary_key=True)
id: int | None = Field(default=None, primary_key=True)
name: str = Field(
index=True, unique=True, description="Human-readable job name shown in the UI."
)
@@ -37,12 +36,12 @@ class JobDefinition(SQLModel, table=True):
target_index: str = Field(
default="", description="Elasticsearch index the job writes to (UI info)."
)
image: Optional[str] = Field(
image: str | None = Field(
default=None,
description="Docker image to run. Null falls back to the configured "
"background-jobs image.",
)
command: Optional[str] = Field(
command: str | None = Field(
default=None,
description="Command passed to the image. Null uses the job name (for "
"known jobs) or the image's default entrypoint.",
@@ -52,14 +51,14 @@ class JobDefinition(SQLModel, table=True):
sa_column=Column(JSON),
description="Extra environment variables passed to the container.",
)
schedule: Optional[str] = Field(
schedule: str | None = Field(
default=None,
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
)
enabled: bool = Field(
default=True, description="Disabled definitions are never scheduled."
)
next_run_at: Optional[datetime] = Field(
next_run_at: datetime | None = Field(
default=None, description="Computed by the scheduler from the cron expression."
)
created_at: datetime = Field(default_factory=utcnow)
@@ -68,19 +67,19 @@ class JobDefinition(SQLModel, table=True):
class JobRun(SQLModel, table=True):
__tablename__ = "background_job_run"
id: Optional[int] = Field(default=None, primary_key=True)
id: int | None = Field(default=None, primary_key=True)
definition_id: int = Field(
foreign_key="background_job_definition.id", index=True
)
container_id: Optional[str] = Field(default=None)
container_id: str | None = Field(default=None)
status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
triggered_by: JobTriggeredBy = Field(
description="Whether the scheduler or a superadmin started this run."
)
started_at: datetime = Field(default_factory=utcnow)
finished_at: Optional[datetime] = Field(default=None)
exit_code: Optional[int] = Field(default=None)
logs: Optional[str] = Field(
finished_at: datetime | None = Field(default=None)
exit_code: int | None = Field(default=None)
logs: str | None = Field(
default=None,
description="Captured stdout/stderr, filled in when the run finishes "
"(the container itself is removed afterwards).",
@@ -89,24 +88,24 @@ class JobRun(SQLModel, table=True):
class JobDefinitionCreateRequest(BaseModel):
name: str
image: Optional[str] = None
command: Optional[str] = None
image: str | None = None
command: str | None = None
env: dict[str, str] = {}
description: str = ""
target_index: str = ""
schedule: Optional[str] = None
schedule: str | None = None
enabled: bool = True
class JobDefinitionUpdateRequest(BaseModel):
name: Optional[str] = None
image: Optional[str] = None
command: Optional[str] = None
env: Optional[dict[str, str]] = None
description: Optional[str] = None
target_index: Optional[str] = None
schedule: Optional[str] = None
enabled: Optional[bool] = None
name: str | None = None
image: str | None = None
command: str | None = None
env: dict[str, str] | None = None
description: str | None = None
target_index: str | None = None
schedule: str | None = None
enabled: bool | None = None
class BackgroundJobTask(BaseModel):
@@ -114,13 +113,13 @@ class BackgroundJobTask(BaseModel):
name: str
description: str
target_index: str
image: Optional[str]
command: Optional[str]
image: str | None
command: str | None
env: dict[str, str]
schedule: Optional[str]
schedule: str | None
enabled: bool
next_run_at: Optional[datetime]
last_run: Optional[JobRun]
next_run_at: datetime | None
last_run: JobRun | None
status: str
@@ -11,11 +11,11 @@ from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
JobRun,
JobRunLogs,
RegistryHealth,
)
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
+16 -17
View File
@@ -8,7 +8,6 @@ import logging
import re
from datetime import datetime
from threading import RLock
from typing import Optional
import docker
import httpx
@@ -28,7 +27,7 @@ settings = config.get_settings()
RUN_STATE_LOCK = RLock()
_client: Optional[docker.DockerClient] = None
_client: docker.DockerClient | None = None
def get_docker_client() -> docker.DockerClient:
@@ -42,7 +41,7 @@ def docker_reachable() -> tuple[bool, str]:
try:
get_docker_client().ping()
return True, "ok"
except Exception as error: # noqa: BLE001
except Exception as error:
return False, str(error)
@@ -59,7 +58,7 @@ def registry_reachable() -> tuple[bool, str]:
if response.status_code == 401:
return False, "authentication failed (401)"
return False, f"unexpected status {response.status_code}"
except Exception as error: # noqa: BLE001
except Exception as error:
return False, str(error)
@@ -110,23 +109,23 @@ def list_registry_images() -> tuple[list[str], str]:
response = client.get(f"{base}/v2/{repository}/tags/list")
response.raise_for_status()
tags = response.json().get("tags") or []
except Exception: # noqa: BLE001
except Exception:
tags = []
if tags:
images.extend(f"{host}/{repository}:{tag}" for tag in tags)
else:
images.append(f"{host}/{repository}")
return sorted(images), ""
except Exception as error: # noqa: BLE001
except Exception as error:
logger.warning("Could not list registry images.", exc_info=True)
return [], str(error)
def resolve_image(definition: JobDefinition) -> Optional[str]:
def resolve_image(definition: JobDefinition) -> str | None:
return definition.image or None
def is_registry_image(image: Optional[str]) -> bool:
def is_registry_image(image: str | None) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host()
@@ -151,7 +150,7 @@ def resolve_environment(definition: JobDefinition) -> dict[str, str]:
return {**base, **(definition.env or {})}
def registry_auth() -> Optional[dict[str, str]]:
def registry_auth() -> dict[str, str] | None:
if (
settings.background_jobs_registry_username
and settings.background_jobs_registry_password
@@ -189,7 +188,7 @@ def start_run(
if settings.background_jobs_pull_before_run and is_registry_image(image):
try:
pull_image(image)
except Exception as error: # noqa: BLE001
except Exception as error:
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
@@ -211,7 +210,7 @@ def start_run(
remove=False,
)
run.container_id = container.id
except Exception as error: # noqa: BLE001
except Exception as error:
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
@@ -241,8 +240,8 @@ def schedule_due_jobs(session: Session) -> None:
now = utcnow()
scheduled = session.exec(
select(JobDefinition).where(
JobDefinition.enabled == True, # noqa: E712
JobDefinition.schedule != None, # noqa: E711
JobDefinition.enabled == True,
JobDefinition.schedule != None,
)
).all()
@@ -276,8 +275,8 @@ def finalize_run(
*,
new_status: JobRunStatus,
expected_status: JobRunStatus = JobRunStatus.RUNNING,
exit_code: Optional[int] = None,
logs: Optional[str] = None,
exit_code: int | None = None,
logs: str | None = None,
) -> bool:
values: dict = {"status": new_status, "finished_at": utcnow()}
if exit_code is not None:
@@ -300,7 +299,7 @@ def append_system_log(logs: str, message: str) -> str:
def remove_container(container, run_id: int) -> None:
try:
container.remove()
except Exception: # noqa: BLE001
except Exception:
logger.warning(
"Could not remove container for run %s.", run_id, exc_info=True
)
@@ -371,6 +370,6 @@ async def scheduler_loop() -> None:
while True:
try:
await asyncio.to_thread(tick)
except Exception: # noqa: BLE001
except Exception:
logger.exception("Background job scheduler tick failed.")
await asyncio.sleep(settings.background_jobs_tick_seconds)
@@ -17,7 +17,6 @@ from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinition,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
@@ -25,6 +24,7 @@ from .model import (
JobRunLogs,
JobRunStatus,
JobTriggeredBy,
RegistryHealth,
utcnow,
)
@@ -289,7 +289,7 @@ def get_run_logs(
"utf-8", errors="replace"
),
)
except Exception: # noqa: BLE001
except Exception:
pass
return JobRunLogs(
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "")
@@ -319,7 +319,7 @@ def stop_run(
status_code=status.HTTP_409_CONFLICT,
detail=f"Container for run {run_id} no longer exists.",
) from error
except Exception as error: # noqa: BLE001
except Exception as error:
logger.warning(
"Could not inspect run %s before stopping.", run_id, exc_info=True
)
@@ -340,7 +340,7 @@ def stop_run(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.",
) from error
except Exception as error: # noqa: BLE001
except Exception as error:
logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
+4 -3
View File
@@ -1,7 +1,8 @@
import uuid
from datetime import datetime, timezone
from datetime import UTC, datetime
from pydantic import BaseModel, Field as PydanticField
from pydantic import BaseModel
from pydantic import Field as PydanticField
from sqlalchemy import UniqueConstraint
from sqlmodel import Field, SQLModel
@@ -21,7 +22,7 @@ class PersonBookmark(SQLModel, table=True):
person_id: str = Field(nullable=False, index=True)
person_name: str | None = Field(default=None)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
default_factory=lambda: datetime.now(UTC), nullable=False, index=True
)
@@ -7,7 +7,6 @@ from inse.database import SessionDep
from . import service
from .model import CreatePersonBookmark, PersonBookmarkResponse
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
@@ -1,9 +1,10 @@
import logging
from typing import Any
from . import model
from inse.authors.v2.service import author_currently_belongs_to_institution
from inse.exceptions import NotFoundException
from . import model
from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__)
@@ -1,14 +1,10 @@
from typing import Any
from .. import config
from inse.exceptions import ElasticsearchNotFoundException
from inse.integrations import elasticsearch
from inse.model import ESCluster
from inse.exceptions import ElasticsearchNotFoundException
from inse.exceptions import MissingApiKeyError
from .. import config
class CompanyConnectionsSearchClient:
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for possible company connections of OpenAlex authors.
"""
+23 -22
View File
@@ -1,17 +1,16 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains the configuration properties
that can be adjusted via environment variables.
"""
from functools import lru_cache
import logging
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Literal, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
from typing import Literal
from dotenv import load_dotenv
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__)
@@ -35,17 +34,17 @@ class Settings(BaseSettings):
openalex_works_search_timeout_seconds: float = 30.0
# OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org"
openalex_api_key: Optional[str] = None
openalex_api_key: str | None = None
openalex_api_timeout_seconds: float = 30.0
# Patent Elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
patent_elasticsearch_api_key: Optional[str] = None
patent_elasticsearch_api_key: str | None = None
# LLM config
llm_api_url: Optional[str] = None
llm_api_key: Optional[str] = None
llm_model: Optional[str] = None
llm_api_url: str | None = None
llm_api_key: str | None = None
llm_model: str | None = None
# Background job runner config (Docker-out-of-Docker)
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
@@ -58,23 +57,25 @@ class Settings(BaseSettings):
# Credentials for pulling the job image from a private registry (e.g. the
# Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the
# Docker SDK inside the service container, which has no `docker login` creds.
background_jobs_registry_username: Optional[str] = None
background_jobs_registry_password: Optional[str] = None
background_jobs_registry_username: str | None = None
background_jobs_registry_password: str | None = None
# Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
# Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
elasticsearch_api_key: Optional[str] = None
elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None
elasticsearch_api_key: str | None = None
elasticsearch_inse_url: str | None = None
elasticsearch_inse_api_key: str | None = None
print_es_queries: bool = False
print_es_timings: bool = False
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
allowed_origins: List[str] = ["http://localhost:4200"]
allowed_origins: list[str] = ["http://localhost:4200"]
servers: List[Dict[str, str]] = [
servers: list[dict[str, str]] = [
{"url": "http://localhost:8000", "description": "Local development server"},
]
@@ -82,8 +83,8 @@ class Settings(BaseSettings):
environment: Literal["dev", "prod"] = "dev"
token_issuer_id: Optional[str] = None
token_hmac_key: Optional[str] = None
token_issuer_id: str | None = None
token_hmac_key: str | None = None
skip_otk_validation: bool = True
# SMTP / email config
@@ -93,8 +94,8 @@ class Settings(BaseSettings):
smtp_server: str = "localhost"
smtp_port: int = 25
smtp_sender: str = "no-reply@smartguide.local"
smtp_username: Optional[str] = None
smtp_password: Optional[str] = None
smtp_username: str | None = None
smtp_password: str | None = None
smtp_use_tls: bool = False
+14
View File
@@ -34,6 +34,19 @@ class BmbfProjectStatusStatistics(BaseModel):
completed: int
class DfgProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectKeyword(BaseModel):
name: str
project_count: int
class DfgProjectTopic(BaseModel):
id: str
name: str
@@ -41,6 +54,7 @@ class DfgProjectTopic(BaseModel):
field: str | None = None
domain: str | None = None
project_count: int
keywords: list[DfgProjectKeyword]
class DfgProjectTopics(BaseModel):
+64 -2
View File
@@ -10,8 +10,9 @@ from inse.tags import Tags
from .model import (
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
@@ -21,10 +22,11 @@ from .model import (
from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_projects,
get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses,
get_dashboard_eu_projects,
get_dashboard_organization,
get_dashboard_patents,
get_dashboard_persons,
@@ -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,
)
@@ -76,6 +82,8 @@ async def dashboard_publications(
response_model=DashboardStatisticValue,
)
async def dashboard_persons(
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:
@@ -83,6 +91,8 @@ async def dashboard_persons(
return await get_dashboard_persons(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@@ -92,6 +102,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 +111,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 +122,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 +131,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 +142,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 +151,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 +162,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 +171,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 +182,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 +191,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 +202,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 +211,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 +242,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 +251,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 +266,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 +276,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
+431 -344
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from datetime import datetime
import pytest
from fastapi import HTTPException
@@ -9,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,
@@ -30,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 {
@@ -183,6 +66,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
}
}
}
return {"hits": {"total": {"value": 3}}}
with patch(
@@ -201,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,
@@ -213,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"]
affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
assert affiliation["nested"]["path"] == "affiliations"
assert 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": [
@@ -250,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_eu_dfg_and_news():
async def test_top_authors_maps_works_patents_news_and_eu_projects():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -409,76 +187,120 @@ async def test_top_authors_maps_works_patents_eu_dfg_and_news():
]
}
}
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.DFG_PROJECTS:
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
return {
"hits": {
"total": {"value": 2},
"hits": [
{
"_source": {
"id": "P1",
"persons": [
{"person_id": 2, "full_name": "Grace Example"},
"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": [
{
"person_id": 99,
"full_name": "Outside Collaborator",
"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": {
"id": "P2",
"persons": [
{"person_id": 2, "full_name": "Grace Example"},
{"person_id": 2, "full_name": "Grace Example"},
"doi": "https://doi.org/10.1234/p2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
}
},
],
]
}
}
if kwargs["index"] == ESIndex.DFG_PERSONS:
return {"hits": {"hits": []}}
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=[
{"id": "A1", "name": "Ada Example", "count": 4},
]
),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[SimpleNamespace(id=101)])),
), patch(
"inse.dashboard.service.get_person_ids_by_institution_ids",
new=AsyncMock(return_value=[2]),
):
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",
@@ -491,40 +313,295 @@ async def test_top_authors_maps_works_patents_eu_dfg_and_news():
"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.projects[0].model_dump() == {
"id": "A2",
"name": "Grace Example",
"count": 2,
}
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"] == ESIndex.DFG_PROJECTS
if call.kwargs["index"]
in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["body"]["query"] == {
"nested": {
"path": "persons",
"query": {"terms": {"persons.person_id": [2]}},
},
}
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
@@ -545,22 +622,34 @@ 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=[]),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
):
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.projects == []
assert result.eu_projects == []
assert result.patents == []
assert result.news == []
@@ -608,12 +697,12 @@ 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=[]),
), patch(
"inse.dashboard.service.autocomplete_institutions_for_selector",
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
):
result = await get_top_authors(
ORG_INSTITUTION_ID,
@@ -771,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"]
@@ -789,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 {
@@ -809,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
-5
View File
@@ -10,22 +10,18 @@ class NotFoundException(Exception):
class ElasticsearchException(Exception):
"""Base exception for all Elasticsearch integrations."""
pass
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
"""Raised when an Elasticsearch document or index is not found."""
pass
class ElasticsearchConnectionException(ElasticsearchException):
"""Raised when connecting to Elasticsearch fails."""
pass
class MissingApiKeyError(Exception):
"""Raised when a required API key is missing."""
pass
class UpstreamAPIException(Exception):
@@ -38,4 +34,3 @@ class UpstreamAPIException(Exception):
class BadRequestException(Exception):
"""Raised when request parameters are invalid or validation fails."""
pass
+1 -2
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Funders domain package.
"""
@@ -1,16 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for funded-publication searches in the OpenAlex works index.
"""
from typing import Any
from .. import config
from inse.exceptions import MissingApiKeyError
from inse.integrations import elasticsearch
from inse.model import ESCluster
from inse.exceptions import MissingApiKeyError
from .. import config
class FundedPublicationsSearchClient:
+6 -3
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for author funding based on publication works.
"""
@@ -7,10 +6,14 @@ import logging
from typing import Any
from pydantic import ValidationError
from inse.exceptions import (
UpstreamAPIException,
)
from ..persons import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
logger = logging.getLogger(__name__)
+1 -2
View File
@@ -1,7 +1,6 @@
from typing import Any
from pydantic import BaseModel
from pydantic import Field
from pydantic import BaseModel, Field
class PublicationsByAuthorResponse(BaseModel):
+3 -7
View File
@@ -1,16 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for author publications and funding.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from . import logic
from . import model
from fastapi import APIRouter, Query
from . import logic, model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
+3 -2
View File
@@ -1,7 +1,8 @@
import pytest
from unittest.mock import AsyncMock, patch
from inse.exceptions import MissingApiKeyError
import pytest
from inse.exceptions import MissingApiKeyError
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@@ -1,13 +1,10 @@
import logging
from typing import List, Set
from typing import Any, Dict, Literal, Optional
from typing import Any, Literal
from inse.models.openalex.institution import Institution
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.institutions.model import InstitutionPage
from inse.integrations import elasticsearch
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
@@ -18,7 +15,6 @@ class InstitutionsSearchClient:
Initializes the client. Credentials and URLs are handled by the
centralized elasticsearch integration.
"""
pass
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
"""Retrieves an institution by its raw OpenAlex institution ID.
@@ -56,7 +52,7 @@ class InstitutionsSearchClient:
async def get_eu_organisation_id_by_oa_institution_id(
self, raw_institution_id: str
) -> Optional[str]:
) -> str | None:
"""Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available.
Args:
@@ -99,7 +95,7 @@ class InstitutionsSearchClient:
else:
sort_config.append({"display_name.keyword": {"order": sorting_direction}})
query: Dict[str, Any] = {"match_all": {}}
query: dict[str, Any] = {"match_all": {}}
if len(name) > 0:
query = {
@@ -136,7 +132,7 @@ class InstitutionsSearchClient:
return self.response_to_institution_page(response, page, size)
def response_to_institution_page(
self, response: Dict[str, Any], page: int, size: int
self, response: dict[str, Any], page: int, size: int
) -> InstitutionPage:
hits = response.get("hits", {}).get("hits", [])
@@ -250,7 +246,7 @@ class InstitutionsSearchClient:
async def get_institution_aliases_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> List[str]:
) -> list[str]:
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
Args:
@@ -273,7 +269,7 @@ class InstitutionsSearchClient:
def get_predefined_institution_aliases(
self, raw_oa_institution_id: str
) -> Set[str]:
) -> set[str]:
"""Get predefined aliases for a given institution ID.
Args:
@@ -297,7 +293,7 @@ class InstitutionsSearchClient:
set(predefined_aliases.get(raw_oa_institution_id, []))
)
def augment_aliases(self, aliases: Set[str]) -> Set[str]:
def augment_aliases(self, aliases: set[str]) -> set[str]:
"""Augment a set of aliases by applying the augment_alias function to each alias.
Args:
@@ -311,7 +307,7 @@ class InstitutionsSearchClient:
augmented_aliases.update(self.augment_alias(alias))
return augmented_aliases
def augment_alias(self, alias: str) -> List[str]:
def augment_alias(self, alias: str) -> list[str]:
"""Augment an alias by replacing German umlauts and ß with their alternative spellings.
Args:
@@ -343,7 +339,7 @@ class InstitutionsSearchClient:
aliases.append(alias.replace("-", " "))
return aliases
def _convert_hit_to_institution(self, hit: Dict[str, Any]) -> Optional[Institution]:
def _convert_hit_to_institution(self, hit: dict[str, Any]) -> Institution | None:
"""Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
Args:
@@ -388,7 +384,7 @@ class InstitutionsSearchClient:
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
self, raw_oa_institution_id: str
) -> Optional[List[str]]:
) -> list[str] | None:
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
Args:
+6 -6
View File
@@ -1,26 +1,26 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for OpenAlex institutions.
"""
import logging
from copy import deepcopy
from typing import Any, Optional
from typing import Any
import httpx
from pydantic import ValidationError
from inse.exceptions import UpstreamAPIException, BadRequestException
from inse.exceptions import BadRequestException, UpstreamAPIException
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.openalex.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner,
)
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.models.openalex.institution import Institution
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from .search_client import OpenAlexInstitutionsClient
from inse.institutions.institutions_search_client import InstitutionsSearchClient
logger = logging.getLogger(__name__)
+1 -2
View File
@@ -1,4 +1,3 @@
from typing import List
from pydantic import BaseModel, Field
@@ -6,7 +5,7 @@ from inse.models.openalex.institution import Institution
class InstitutionPage(BaseModel):
elements: List[Institution] = Field(
elements: list[Institution] = Field(
default_factory=list, description="List of institutions in the current page."
)
page: int = Field(default=0, description="Current page number. (0-indexed)")
+6 -7
View File
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for OpenAlex institutions.
"""
@@ -7,16 +6,16 @@ REST API for OpenAlex institutions.
from functools import lru_cache
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, status, Query
from fastapi import APIRouter, Depends, Query, status
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.institutions.model import InstitutionPage
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.institution import Institution
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from inse.models.openalex.institution import Institution
from inse.institutions.model import InstitutionPage
from . import logic
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from . import logic
router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS])
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for OpenAlex institutions.
"""
@@ -1,7 +1,7 @@
import httpx
import pytest
from inse.exceptions import BadRequestException
from inse.exceptions import BadRequestException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@@ -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,21 +1,24 @@
import json
import logging
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
import time
from collections.abc import AsyncIterator
from typing import Any
import httpx
from inse.exceptions import (
ElasticsearchConnectionException,
ElasticsearchException,
ElasticsearchNotFoundException,
ElasticsearchConnectionException,
MissingApiKeyError,
)
from inse.model import ESCluster, ESIndex
from .. import config
logger = logging.getLogger(__name__)
_client: Optional[httpx.AsyncClient] = None
_client: httpx.AsyncClient | None = None
_loop = None
@@ -34,7 +37,7 @@ def get_client() -> httpx.AsyncClient:
return _client
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
def _cluster_credentials(cluster: ESCluster) -> tuple[str, str]:
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
Args:
@@ -74,7 +77,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
def _index_to_cluster(index: ESIndex) -> ESCluster | None:
"""Determines the Elasticsearch cluster to use based on the specified index.
Args:
@@ -110,6 +113,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,19 +132,76 @@ def _wrap_exception(e: Exception) -> Exception:
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
async def _request(
method: str,
cluster: ESCluster,
path: str,
*,
json_body: Any | None = None,
params: dict[str, Any] | None = None,
content: bytes | None = 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,
source: Optional[List] = None,
size: Optional[int] = None,
offset: Optional[int] = None,
sort: Optional[List] = None,
aggs: Optional[Dict] = None,
body: Optional[Dict] = None,
index: ESIndex | list[ESIndex] | str | list[str],
query: dict | None = None,
source: list | None = None,
size: int | None = None,
offset: int | None = None,
sort: list | None = None,
aggs: dict | None = None,
body: dict | None = None,
track_total_hits=False,
highlight: Optional[Dict] = None,
highlight: dict | None = None,
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
Args:
@@ -175,11 +239,7 @@ 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] = {}
payload: dict[str, Any] = {}
if body is not None:
payload = body
@@ -210,85 +270,54 @@ 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(
index: str,
query: Dict,
source: Optional[List] = None,
query: dict,
source: list | None = None,
page_size: int = 1000,
keep_alive: str = "1m",
cluster: str = "nes",
) -> AsyncIterator[Dict[str, Any]]:
) -> AsyncIterator[dict[str, Any]]:
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
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
search_after: list | None = None
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
payload: dict[str, Any] = {
"size": page_size,
"query": query,
"pit": {"id": pit_id, "keep_alive": keep_alive},
@@ -299,14 +328,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", [])
@@ -331,79 +353,51 @@ async def scan(
async def get(
index: ESIndex | str,
doc_id: str,
source: Optional[list] = None,
source: list | None = None,
cluster: ESCluster = ESCluster.NES,
) -> dict[str, Any]:
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
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(
index: str,
doc_id: str,
doc: Dict[str, Any],
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"}
) -> dict[str, Any]:
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(
index: str,
doc_id: str,
document: Dict[str, Any],
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"}
) -> dict[str, Any]:
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(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict[str, Any]] = None,
index: ESIndex | list[ESIndex] | str | list[str],
query: dict[str, Any] | None = None,
cluster: ESCluster = ESCluster.NES,
) -> int:
"""Performs a count request (_count) on the specified Elasticsearch index.
@@ -431,30 +425,21 @@ 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(
searches: List[Tuple[ESIndex | str | List[str], Dict[str, Any]]],
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
cluster: ESCluster = ESCluster.NES,
) -> List[Dict[str, Any]]:
) -> list[dict[str, Any]]:
"""Performs a multi-search request (_msearch) on Elasticsearch.
Args:
@@ -473,9 +458,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 +470,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", [])

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