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
farajollahi 345dffaa9b implement treemap
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 11:54:10 +02:00
581 changed files with 13891 additions and 12184 deletions
@@ -5,7 +5,6 @@ from typing import Any
from openalex_client import get_all_author_works from openalex_client import get_all_author_works
BASE_DIR = Path(__file__).resolve().parent BASE_DIR = Path(__file__).resolve().parent
INPUT_FILE = BASE_DIR / "career_stage_sample.csv" INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv" OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
@@ -1,10 +1,10 @@
from collections.abc import Callable
from pathlib import Path from pathlib import Path
from typing import Callable, Literal from typing import Literal
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import pandas as pd import pandas as pd
BASE_DIR = Path(__file__).resolve().parent BASE_DIR = Path(__file__).resolve().parent
INPUT_FILE = BASE_DIR / "career_stage_results.csv" INPUT_FILE = BASE_DIR / "career_stage_results.csv"
PLOTS_DIR = BASE_DIR / "plots" 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.parse import urlencode
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
OPENALEX_WORKS_URL = "https://api.openalex.org/works" OPENALEX_WORKS_URL = "https://api.openalex.org/works"
REQUEST_TIMEOUT_SECONDS = 30 REQUEST_TIMEOUT_SECONDS = 30
PER_PAGE = 200 PER_PAGE = 200
+3 -2
View File
@@ -1,8 +1,9 @@
import os import os
import requests
from requests.adapters import HTTPAdapter
from urllib.parse import quote from urllib.parse import quote
import requests
from dotenv import load_dotenv from dotenv import load_dotenv
from requests.adapters import HTTPAdapter
load_dotenv() load_dotenv()
+2 -2
View File
@@ -1,7 +1,7 @@
import os import os
import requests
from openai import OpenAI, APIConnectionError
from dotenv import load_dotenv from dotenv import load_dotenv
from openai import APIConnectionError, OpenAI
load_dotenv() 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 argparse
import time import json
import logging import logging
import threading import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed 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") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -3,7 +3,6 @@ from pathlib import Path
from llama_parse import LlamaParse from llama_parse import LlamaParse
BASE_DIR = Path(__file__).resolve().parent BASE_DIR = Path(__file__).resolve().parent
AD_PATH = BASE_DIR / "AD.pdf" AD_PATH = BASE_DIR / "AD.pdf"
@@ -1,7 +1,7 @@
import pymupdf4llm import pymupdf4llm
AD_PATH = "188274\AD.pdf" AD_PATH = r"188274\AD.pdf"
CD_PATH = "188274\СD.pdf" CD_PATH = r"188274\СD.pdf"
ad_md = pymupdf4llm.to_markdown(AD_PATH) ad_md = pymupdf4llm.to_markdown(AD_PATH)
cd_md = pymupdf4llm.to_markdown(CD_PATH) cd_md = pymupdf4llm.to_markdown(CD_PATH)
+2 -2
View File
@@ -1,7 +1,7 @@
from pathlib import Path
import getpass import getpass
import json import json
import os import os
from pathlib import Path
import pymupdf import pymupdf
import requests import requests
@@ -206,7 +206,7 @@ def make_debug_data(
) -> dict: ) -> dict:
choice = {} choice = {}
if "choices" in data and data["choices"]: if data.get("choices"):
choice = data["choices"][0] choice = data["choices"][0]
message = choice.get("message", {}) message = choice.get("message", {})
+2 -2
View File
@@ -1,7 +1,7 @@
from pathlib import Path
import getpass import getpass
import json import json
import os import os
from pathlib import Path
import requests import requests
@@ -181,7 +181,7 @@ def make_debug_data(
): ):
choice = {} choice = {}
if "choices" in data and data["choices"]: if data.get("choices"):
choice = data["choices"][0] choice = data["choices"][0]
message = choice.get("message", {}) message = choice.get("message", {})
@@ -1,5 +1,5 @@
from pathlib import Path
import json import json
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR ROOT_DIR = SCRIPT_DIR
@@ -1,5 +1,5 @@
from pathlib import Path
import re import re
from pathlib import Path
import pymupdf import pymupdf
@@ -1,4 +1,5 @@
from pathlib import Path from pathlib import Path
import pymupdf # PyMuPDF import pymupdf # PyMuPDF
try: try:
@@ -7,7 +8,7 @@ except ImportError:
MarkItDown = None MarkItDown = None
AD_PATH = Path("154115\AD.pdf") AD_PATH = Path(r"154115\AD.pdf")
OUT_DIR = Path("ad_extraction_outputs3") OUT_DIR = Path("ad_extraction_outputs3")
OUT_DIR.mkdir(exist_ok=True) OUT_DIR.mkdir(exist_ok=True)
@@ -3,9 +3,9 @@ from __future__ import annotations
import argparse import argparse
import json import json
from collections import Counter from collections import Counter
from statistics import mean, median
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from statistics import mean, median
from typing import Any from typing import Any
import requests import requests
@@ -17,7 +17,7 @@ SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
if str(SERVICE_SOURCE_ROOT) not in sys.path: if str(SERVICE_SOURCE_ROOT) not in sys.path:
sys.path.insert(0, str(SERVICE_SOURCE_ROOT)) 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, build_institution_membership_query,
current_affiliation_year_cutoff, current_affiliation_year_cutoff,
) )
@@ -852,9 +852,7 @@ def validate(result: dict[str, Any]) -> list[str]:
if score is None: if score is None:
errors.append("basic_research_score_missing") errors.append("basic_research_score_missing")
elif score_is_usable: elif score_is_usable:
if quadrant == "pure_basic" and not 0 <= score <= 30: 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")
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
errors.append("basic_research_quadrant_score_mismatch") errors.append("basic_research_quadrant_score_mismatch")
if quadrant not in {"pure_basic", "use_inspired_basic"}: if quadrant not in {"pure_basic", "use_inspired_basic"}:
errors.append("basic_research_quadrant_mismatch") errors.append("basic_research_quadrant_mismatch")
@@ -26,12 +26,12 @@ import json
import os import os
import sys import sys
from collections import defaultdict from collections import defaultdict
from collections.abc import Iterable
from pathlib import Path from pathlib import Path
from typing import Any, Iterable from typing import Any
import requests import requests
DEFAULT_AUTHOR_ID = "A5034365278" DEFAULT_AUTHOR_ID = "A5034365278"
DEFAULT_WORK_YEAR_GTE = 1950 DEFAULT_WORK_YEAR_GTE = 1950
SOURCE_INDEX = "openalex-works*" SOURCE_INDEX = "openalex-works*"
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
def safe_rate( def safe_rate(
numerator: int | float, numerator: float,
denominator: int | float, denominator: float,
) -> float | None: ) -> float | None:
if not denominator: if not denominator:
return None return None
@@ -13,7 +13,6 @@ from typing import Any
from openai import OpenAI from openai import OpenAI
ROOT = Path(__file__).resolve().parent ROOT = Path(__file__).resolve().parent
PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt" PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt"
CONSENSUS_FILE = ROOT / "consensus_reference.json" CONSENSUS_FILE = ROOT / "consensus_reference.json"
@@ -282,7 +281,7 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
return 0.0 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: if not denominator:
return None return None
return numerator / denominator return numerator / denominator
@@ -3,13 +3,13 @@ from __future__ import annotations
import argparse import argparse
import json import json
from collections import Counter from collections import Counter
from collections.abc import Callable, Iterable
from datetime import datetime, timezone from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Callable, Iterable from typing import Any
import requests import requests
ROOT = Path(__file__).resolve().parent ROOT = Path(__file__).resolve().parent
ES_BASE_URL = "https://project.nes.uni-due.de/elastic" 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 from ollama import Client
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/") ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16") MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
DATA_FOLDER = "data" DATA_FOLDER = "data"
@@ -1,9 +1,9 @@
import os
import json import json
import os
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from time import time from time import time
from openai import OpenAI, APIConnectionError from openai import APIConnectionError, OpenAI
DATA_FOLDER = "data2" DATA_FOLDER = "data2"
BATCH_SIZE = 6 BATCH_SIZE = 6
+3 -1
View File
@@ -1,5 +1,7 @@
import requests, json import json
import helpers import helpers
import requests
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen") AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
#AUTHOR_OPEN_ALEXID = ["A5047117780"] #AUTHOR_OPEN_ALEXID = ["A5047117780"]
+3 -1
View File
@@ -1,5 +1,7 @@
import requests, json import json
import helpers import helpers
import requests
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen") AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"] #AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
@@ -1,4 +1,5 @@
import os import os
import requests import requests
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic") 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 concurrent.futures import ThreadPoolExecutor
from time import time from time import time
from openai import OpenAI, APIConnectionError
import helpers import helpers
from openai import APIConnectionError, OpenAI
DATA_FOLDER = "data2" DATA_FOLDER = "data2"
BATCH_SIZE = 6 BATCH_SIZE = 6
@@ -1,9 +1,11 @@
from typing import Any, Iterator
from elasticsearch import Elasticsearch
from collections import defaultdict
import json import json
from collections import defaultdict
from collections.abc import Iterator
from pathlib import Path 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 # elasticseach library required. Here used elasticsearch==8.0.0
# estimated execution time: 3-5 Minutes # estimated execution time: 3-5 Minutes
@@ -1,5 +1,5 @@
import os
import json import json
import os
from time import time from time import time
from llm_classify_news import call, parse_label, parse_persons 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. 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). llm_persons, darunter der full_content als reiner Text (kein Parsing).
""" """
import os
import json import json
import os
DATA_FOLDER = "validation_data" DATA_FOLDER = "validation_data"
OUTPUT_FILE = "viewer.html" OUTPUT_FILE = "viewer.html"
@@ -1,5 +1,5 @@
import os
import json import json
import os
import random import random
import requests import requests
@@ -1,10 +1,9 @@
import os
import json import json
import os
import random import random
import requests import requests
from openai import OpenAI, APIConnectionError from openai import APIConnectionError, OpenAI
INSE_URL = "https://inse.nes.uni-due.de/elastic" INSE_URL = "https://inse.nes.uni-due.de/elastic"
INDEX_URL = f"{INSE_URL}/aktuell" INDEX_URL = f"{INSE_URL}/aktuell"
@@ -1,5 +1,5 @@
import os
import json import json
import os
DATA_FOLDER = "data2" DATA_FOLDER = "data2"
@@ -1,4 +1,5 @@
import json import json
from tabulate import tabulate from tabulate import tabulate
result_files = [ result_files = [
@@ -1,6 +1,7 @@
from urllib.parse import quote
import requests import requests
from requests.adapters import HTTPAdapter from requests.adapters import HTTPAdapter
from urllib.parse import quote
INSE_URL = "https://inse.nes.uni-due.de/elastic" INSE_URL = "https://inse.nes.uni-due.de/elastic"
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==" INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
@@ -1,5 +1,4 @@
import requests from openai import APIConnectionError, OpenAI
from openai import OpenAI, APIConnectionError
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/" LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212" 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 elastic.client as es_client
import llm.client as llm_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): def print_pretty_json(data):
print(json.dumps(data, indent=2)) print(json.dumps(data, indent=2))
@@ -1,10 +1,10 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os
import sys
import json
import time
import asyncio import asyncio
import json
import sys
import time
from pathlib import Path from pathlib import Path
import httpx import httpx
import numpy as np import numpy as np
@@ -14,6 +14,7 @@ project_root = current_dir.parent.parent.resolve()
env_path = project_root / "service" / "src" / "main" / "inse" / ".env" env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
from dotenv import load_dotenv from dotenv import load_dotenv
load_dotenv(dotenv_path=env_path) load_dotenv(dotenv_path=env_path)
sys.path.append(str(project_root / "service" / "src" / "main")) sys.path.append(str(project_root / "service" / "src" / "main"))
@@ -311,7 +312,7 @@ async def evaluate():
try: try:
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers) resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
resp.raise_for_status() resp.raise_for_status()
except Exception as exc: except Exception:
# Log error but don't crash # Log error but don't crash
pass pass
t1 = time.perf_counter() 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, on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
Taxonomy Clustering metrics, and operational performance metrics. Taxonomy Clustering metrics, and operational performance metrics.
""" """
import os
import sys
import json
import time
import argparse import argparse
import json
import random import random
import sys
import time
from pathlib import Path from pathlib import Path
import httpx import httpx
import numpy as np
from dotenv import load_dotenv from dotenv import load_dotenv
# Add service/src/main to python path to load settings # Add service/src/main to python path to load settings
@@ -30,8 +29,8 @@ API_KEY = settings.elasticsearch_api_key
# Import evaluation libraries # Import evaluation libraries
from sentence_transformers import SentenceTransformer from sentence_transformers import SentenceTransformer
from sentence_transformers.evaluation import InformationRetrievalEvaluator from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sklearn.cluster import KMeans
from sklearn import metrics from sklearn import metrics
from sklearn.cluster import KMeans
DEFAULT_MODELS = [ DEFAULT_MODELS = [
"paraphrase-multilingual-mpnet-base-v2", "paraphrase-multilingual-mpnet-base-v2",
@@ -161,9 +160,9 @@ def evaluate_model(model_name, data, output_dir):
model_safe_name = model_name.replace("/", "_").replace("-", "_") model_safe_name = model_name.replace("/", "_").replace("-", "_")
report_file = output_dir / f"model_report_{model_safe_name}.json" report_file = output_dir / f"model_report_{model_safe_name}.json"
print(f"\n==================================================") print("\n==================================================")
print(f"Evaluating Model: '{model_name}'") print(f"Evaluating Model: '{model_name}'")
print(f"==================================================") print("==================================================")
start_load = time.time() start_load = time.time()
try: try:
+1 -1
View File
@@ -1,6 +1,6 @@
import logging
import sys import sys
import time import time
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
""" """
map_news_topics.py — Map news keywords to OpenAlex topics. map_news_topics.py — Map news keywords to OpenAlex topics.
@@ -37,7 +37,7 @@ import json
import logging import logging
import os import os
import sys import sys
from datetime import datetime, timezone from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from dotenv import load_dotenv 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: 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") model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await base.check_backend(args.api_base_url) await base.check_backend(args.api_base_url)
@@ -3,10 +3,8 @@
# See documentation in: # See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface # useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter from scrapy import signals
class AktuellSpiderMiddleware: class AktuellSpiderMiddleware:
@@ -5,7 +5,6 @@
# useful for handling different item types with a single interface # useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class AktuellPipeline: class AktuellPipeline:
@@ -1,5 +1,6 @@
import scrapy import scrapy
class LinksCrawler(scrapy.Spider): class LinksCrawler(scrapy.Spider):
name = "aktuell-links" name = "aktuell-links"
@@ -1,8 +1,10 @@
import scrapy
import json import json
from scrapy.linkextractors import LinkExtractor
import os import os
import scrapy
from scrapy.linkextractors import LinkExtractor
class MetaDataCrawler(scrapy.Spider): class MetaDataCrawler(scrapy.Spider):
name = "aktuell-metadata" 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 sys
import time
from random import randint
from elasticsearch import Elasticsearch 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() 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 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": if elem == "Zurück zum Gesamtüberblick":
break break
except NoSuchElementException as nsee: except NoSuchElementException:
break break
# get date # get date
@@ -45,7 +46,7 @@ def getLinks(link, driver):
link = "" link = ""
try: 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') 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 continue
links.append(link) links.append(link)
@@ -67,17 +68,17 @@ def getData(driver, link, date, date_year, date_num):
subtitle = "" subtitle = ""
try: try:
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text 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 pass
maintitle = "" maintitle = ""
try: try:
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text 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 pass
redaktion = "" redaktion = ""
try: try:
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text 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 pass
author = "" author = ""
if redaktion != "": if redaktion != "":
@@ -86,7 +87,7 @@ def getData(driver, link, date, date_year, date_num):
main_content = "" main_content = ""
try: try:
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text 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 pass
full_content = main_content 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 argparse
import logging import logging
import os
import shutil
import subprocess
import sys
import time
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+3 -3
View File
@@ -1,8 +1,8 @@
import sys
import os
import json import json
import time
import logging import logging
import os
import sys
import time
from urllib.parse import quote from urllib.parse import quote
import requests import requests
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
""" """
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches. 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. evaluate_keyword_patent_search.py — Systematic evaluation for keyword → patent search.
@@ -23,14 +23,14 @@ import asyncio
import json import json
import logging import logging
import sys import sys
from datetime import datetime, timezone from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
current_dir = Path(__file__).resolve().parent current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent.parent / "src" / "main")) 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, analyze_family_duplicates_in_top_k,
average_precision, average_precision,
ipc_prefix_hit_rate, ipc_prefix_hit_rate,
@@ -43,13 +43,13 @@ from inse.patents.keywords.eval_metrics import ( # noqa: E402
recall_at_k, recall_at_k,
unique_family_precision_at_k, unique_family_precision_at_k,
) )
from inse.patents.keywords.logic import ( # noqa: E402 from inse.patents.keywords.logic import (
_DEFAULT_SCORE_WEIGHTS, _DEFAULT_SCORE_WEIGHTS,
_MAX_PATENTS, _MAX_PATENTS,
_compute_final_score, _compute_final_score,
get_patents_by_keywords, get_patents_by_keywords,
) )
from inse.patents.keywords.model import ( # noqa: E402 from inse.patents.keywords.model import (
KeywordPatentMatch, KeywordPatentMatch,
KeywordPatentSearchDiagnostics, KeywordPatentSearchDiagnostics,
KeywordPatentSearchItem, KeywordPatentSearchItem,
@@ -721,9 +721,7 @@ def _load_prior_candidate_grades(
if existing is None: if existing is None:
bucket[patent_id] = dict(candidate) bucket[patent_id] = dict(candidate)
continue continue
if existing.get("grade") is None and grade is not None: if existing.get("grade") is None and grade is not None or existing.get("grade") is None:
bucket[patent_id] = dict(candidate)
elif existing.get("grade") is None:
bucket[patent_id] = dict(candidate) bucket[patent_id] = dict(candidate)
return by_case 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" labeling_path = out_dir / f"labeling_{stamp}.json"
report_path = out_dir / f"bootstrap_report_{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 if presentation
else _aggregate(case_reports, ks) 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_name = "presentation_eval_report" if presentation else "eval_report"
report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json" report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json"
_write_json( _write_json(
@@ -1071,7 +1069,7 @@ async def cmd_ablation(args: argparse.Namespace) -> int:
f"P@10={p10}" 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" report_path = Path(args.out_dir) / f"ablation_report_{stamp}.json"
_write_json( _write_json(
report_path, 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. 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 import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service 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 selenium.webdriver.common.alert import Alert
from random import randint from selenium.webdriver.common.by import By
import time from selenium.webdriver.support import expected_conditions as EC
import pandas as pd from selenium.webdriver.support.ui import WebDriverWait
import json
from datetime import datetime
import sys
import os
import math
import requests
import hashlib
import argparse
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
""" """
map_project_topics.py — Map project keywords to OpenAlex topics. map_project_topics.py — Map project keywords to OpenAlex topics.
@@ -52,9 +52,10 @@ import json
import logging import logging
import os import os
import sys import sys
from datetime import datetime, timezone from collections.abc import AsyncIterator
from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from typing import Any, AsyncIterator from typing import Any
import httpx import httpx
from dotenv import load_dotenv 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: 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") model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await check_backend(args.api_base_url) await check_backend(args.api_base_url)
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
""" """
test_keywords_matching.py test_keywords_matching.py
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
""" """
Download the sentence-transformers model to the default cache directory Download the sentence-transformers model to the default cache directory
so it is available for local runs or testing. so it is available for local runs or testing.
+3 -3
View File
@@ -1,12 +1,13 @@
#!/usr/bin/env python3
""" """
Script to fetch all topics from 'openalex-topics', Script to fetch all topics from 'openalex-topics',
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model, vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector mapping. and push them to the 'topicvectors' index with multi-vector mapping.
""" """
import sys
import json import json
import sys
from pathlib import Path from pathlib import Path
import httpx import httpx
from dotenv import load_dotenv from dotenv import load_dotenv
@@ -26,7 +27,6 @@ API_KEY = settings.elasticsearch_api_key
MODEL_NAME = settings.sentence_transformers_model_name MODEL_NAME = settings.sentence_transformers_model_name
# Import sentence-transformers # Import sentence-transformers
from sentence_transformers import SentenceTransformer
headers = { headers = {
"Authorization": f"ApiKey {API_KEY}", "Authorization": f"ApiKey {API_KEY}",
@@ -1,5 +1,4 @@
import uuid import uuid
from typing import List, Optional
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
@@ -9,14 +8,14 @@ from inse.auth.model import UserRole, normalize_roles
class OrganizationProfile(BaseModel): class OrganizationProfile(BaseModel):
id: uuid.UUID id: uuid.UUID
name: str name: str
openalex_institution_id: Optional[str] = None openalex_institution_id: str | None = None
class AccountProfile(BaseModel): class AccountProfile(BaseModel):
id: uuid.UUID id: uuid.UUID
email: str email: str
name: str name: str
roles: List[UserRole] roles: list[UserRole]
organization_id: uuid.UUID organization_id: uuid.UUID
organization_name: str organization_name: str
deleted: bool deleted: bool
@@ -27,7 +26,7 @@ class AccountProfile(BaseModel):
class AccountPage(BaseModel): class AccountPage(BaseModel):
items: List[AccountProfile] items: list[AccountProfile]
total: int total: int
page: int page: int
page_size: int page_size: int
@@ -43,10 +42,10 @@ class CreateAccountRequest(BaseModel):
email: str = Field(min_length=3) email: str = Field(min_length=3)
name: str = Field(min_length=1) 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 organization_id: uuid.UUID
password: str = Field(min_length=8) password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None openalex_person_id: str | None = None
@model_validator(mode="after") @model_validator(mode="after")
def _normalize_roles(self): def _normalize_roles(self):
@@ -62,14 +61,14 @@ class UpdateAccountRequest(BaseModel):
values = {**values, "roles": [values["role"]]} values = {**values, "roles": [values["role"]]}
return values return values
email: Optional[str] = Field(default=None, min_length=3) email: str | None = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1) name: str | None = Field(default=None, min_length=1)
roles: Optional[List[UserRole]] = None roles: list[UserRole] | None = None
organization_id: Optional[uuid.UUID] = None organization_id: uuid.UUID | None = None
password: Optional[str] = Field(default=None, min_length=8) password: str | None = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None openalex_person_id: str | None = None
deleted: Optional[bool] = None deleted: bool | None = None
activated: Optional[bool] = None activated: bool | None = None
@model_validator(mode="after") @model_validator(mode="after")
def _normalize_roles(self): def _normalize_roles(self):
@@ -1,5 +1,5 @@
import uuid import uuid
from typing import Annotated, Optional from typing import Annotated
from fastapi import APIRouter, Query, Response, status from fastapi import APIRouter, Query, Response, status
@@ -40,8 +40,8 @@ async def list_accounts(
page: Annotated[int, Query(ge=0)] = 0, page: Annotated[int, Query(ge=0)] = 0,
page_size: Annotated[int, Query(ge=1, le=100)] = 10, page_size: Annotated[int, Query(ge=1, le=100)] = 10,
offset: Annotated[int, Query(ge=0)] = 0, offset: Annotated[int, Query(ge=0)] = 0,
search: Annotated[Optional[str], Query()] = None, search: Annotated[str | None, Query()] = None,
organization_id: Annotated[Optional[uuid.UUID], Query()] = None, organization_id: Annotated[uuid.UUID | None, Query()] = None,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AccountPage: ) -> AccountPage:
return service.list_accounts( return service.list_accounts(
@@ -1,5 +1,4 @@
import uuid import uuid
from typing import Optional
from fastapi import HTTPException, status from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select 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( def _ensure_email_available(
session: Session, session: Session,
email: str, email: str,
excluded_account_id: Optional[uuid.UUID] = None, excluded_account_id: uuid.UUID | None = None,
) -> None: ) -> None:
normalized_email = email.lower().strip() normalized_email = email.lower().strip()
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]: if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
@@ -115,9 +114,9 @@ def list_accounts(
access_token: AccessTokenMetadata, access_token: AccessTokenMetadata,
page: int, page: int,
page_size: int, page_size: int,
offset: Optional[int] = None, offset: int | None = None,
search: Optional[str] = None, search: str | None = None,
organization_id: Optional[uuid.UUID] = None, organization_id: uuid.UUID | None = None,
) -> AccountPage: ) -> AccountPage:
if access_token.effective_role not in { if access_token.effective_role not in {
UserRole.SUPER_ADMIN, UserRole.SUPER_ADMIN,
+7 -8
View File
@@ -1,7 +1,6 @@
import uuid import uuid
from datetime import datetime from datetime import datetime
from enum import StrEnum from enum import StrEnum
from typing import List
from pydantic import BaseModel, model_validator from pydantic import BaseModel, model_validator
from sqlalchemy import JSON, Column, UniqueConstraint from sqlalchemy import JSON, Column, UniqueConstraint
@@ -24,8 +23,8 @@ ROLE_PRIORITY = {
def normalize_roles( def normalize_roles(
roles: List[UserRole] | List[str] | UserRole | str | None, roles: list[UserRole] | list[str] | UserRole | str | None,
) -> List[UserRole]: ) -> list[UserRole]:
if roles is None: if roles is None:
return [UserRole.USER] return [UserRole.USER]
if isinstance(roles, (str, UserRole)): if isinstance(roles, (str, UserRole)):
@@ -43,7 +42,7 @@ def normalize_roles(
def effective_role_for_roles( def effective_role_for_roles(
roles: List[UserRole] | List[str] | UserRole | str | None, roles: list[UserRole] | list[str] | UserRole | str | None,
) -> UserRole: ) -> UserRole:
return normalize_roles(roles)[0] 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.", 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): class Account(Durable, table=True):
@@ -141,7 +140,7 @@ class Account(Durable, table=True):
nullable=False, nullable=False,
description="The unique identifier of the organization strictly associated with this account.", 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], default_factory=lambda: [UserRole.USER],
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]), sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
description="The roles this account holds within its organization.", description="The roles this account holds within its organization.",
@@ -249,7 +248,7 @@ class AccessTokenMetadata(BaseTokenData):
default=UserRole.USER, default=UserRole.USER,
description="The specific role this access token grants within its organization.", 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], default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.", description="The roles this access token grants within its organization.",
) )
@@ -300,7 +299,7 @@ class RefreshTokenMetadata(BaseTokenData):
default=UserRole.USER, default=UserRole.USER,
description="The specific role this access token grants within its organization.", 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], default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.", description="The roles this access token grants within its organization.",
) )
+3 -4
View File
@@ -1,14 +1,11 @@
import logging import logging
from typing import Annotated
import uuid import uuid
from typing import Annotated
from fastapi import APIRouter, Body, Depends, Response, status from fastapi import APIRouter, Body, Depends, Response, status
from sqlmodel import Session from sqlmodel import Session
from inse.tags import Tags
import inse.auth.service as auth_service import inse.auth.service as auth_service
from inse.database import SessionDep, get_session
from inse.auth.model import ( from inse.auth.model import (
AccessResponse, AccessResponse,
AccessToken, AccessToken,
@@ -18,6 +15,8 @@ from inse.auth.model import (
OtkResponse, OtkResponse,
RefreshTokenMetadata, RefreshTokenMetadata,
) )
from inse.database import SessionDep, get_session
from inse.tags import Tags
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+30 -34
View File
@@ -4,7 +4,7 @@ import json
import logging import logging
import secrets import secrets
import uuid import uuid
from typing import Annotated, Any, Dict, Optional from typing import Annotated, Any
import jwt import jwt
from argon2 import PasswordHasher from argon2 import PasswordHasher
@@ -95,7 +95,7 @@ def create_predefined_accounts(session: Session, file_path: str):
try: try:
with open(file_path, "r") as file: 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", []): for organization_data in data.get("organizations", []):
organization_id = organization_data.get("id") organization_id = organization_data.get("id")
if organization_id is not None: if organization_id is not None:
@@ -215,7 +215,7 @@ def request_otk(session: Session, email: str, password: str):
account = session.exec( account = session.exec(
select(Account).where( select(Account).where(
Account.email == email, Account.email == email,
Account.deleted == False, # noqa: E712 Account.deleted == False,
) )
).first() ).first()
@@ -254,7 +254,7 @@ def request_otk(session: Session, email: str, password: str):
) )
).first() ).first()
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=OTK_EXPIRATION_MINUTES 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) 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. """Requests a one-time password reset link for the given email address.
For security reasons, this function always returns a successful response and For security reasons, this function always returns a successful response and
does not reveal whether the email address belongs to an active account. does not reveal whether the email address belongs to an active account.
""" """
email = email.lower().strip() email = email.lower().strip()
now = datetime.datetime.now(datetime.timezone.utc) now = datetime.datetime.now(datetime.UTC)
account = session.exec( account = session.exec(
select(Account).where( select(Account).where(
Account.email == email, Account.email == email,
Account.deleted == False, # noqa: E712 Account.deleted == False,
) )
).first() ).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: if secret.request_window_started_at is not None:
window_started_at = secret.request_window_started_at window_started_at = secret.request_window_started_at
if getattr(window_started_at, "tzinfo", None) is None: if getattr(window_started_at, "tzinfo", None) is None:
window_started_at = window_started_at.replace( window_started_at = window_started_at.replace(tzinfo=datetime.UTC)
tzinfo=datetime.timezone.utc
)
window_ends_at = window_started_at + datetime.timedelta( window_ends_at = window_started_at + datetime.timedelta(
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
@@ -435,7 +433,7 @@ def reset_password(
session: Session, session: Session,
reset_token: str, reset_token: str,
new_password: str, new_password: str,
) -> Dict[str, str]: ) -> dict[str, str]:
"""Resets an account password using a one-time password reset token. """Resets an account password using a one-time password reset token.
Args: Args:
@@ -449,7 +447,7 @@ def reset_password(
Returns: Returns:
Dict[str, str]: A status response. 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()) reset_token_hash = _hash_reset_token(reset_token.strip())
secret = session.exec( secret = session.exec(
@@ -467,7 +465,7 @@ def reset_password(
secret_expires = secret.expires_at secret_expires = secret.expires_at
if getattr(secret_expires, "tzinfo", None) is None: 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: if secret_expires <= now:
session.delete(secret) session.delete(secret)
@@ -515,7 +513,7 @@ def login(
Returns: Returns:
LoginResponse: The response containing the ID token issued upon successful login. 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( secret = session.exec(
select(Secret).where( select(Secret).where(
@@ -536,7 +534,7 @@ def login(
secret_expires = secret.expires_at secret_expires = secret.expires_at
if getattr(secret_expires, "tzinfo", None) is None: 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: if secret_expires <= now:
logger.warning("Login failed: invalid or expired code %s", email_code) 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]), real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( 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], epoch=access_token_payload[EPOCH_KEY],
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_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]), real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]), effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( 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], epoch=refresh_token_payload[EPOCH_KEY],
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]), effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
@@ -708,7 +706,7 @@ def _get_current_user_id_token_payload(
return IdTokenMetadata( return IdTokenMetadata(
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]), real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
expires_at=datetime.datetime.fromtimestamp( 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], 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 return account.organization_id
def _get_account_institution_id( def _get_account_institution_id(session: Session, account_id: uuid.UUID) -> str | None:
session: Session, account_id: uuid.UUID
) -> Optional[str]:
"""Retrieves the OpenAlex institution ID for the given account ID. """Retrieves the OpenAlex institution ID for the given account ID.
Args: Args:
@@ -872,7 +868,7 @@ def get_access_token(
session: Session, session: Session,
id_token: IdTokenMetadata, id_token: IdTokenMetadata,
real_account_id: uuid.UUID, real_account_id: uuid.UUID,
effective_account_id: Optional[uuid.UUID] = None, effective_account_id: uuid.UUID | None = None,
) -> AccessResponse: ) -> AccessResponse:
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here. # 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: Returns:
IdToken: The generated ID token object. 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 minutes=ID_TOKEN_EXPIRATION_MINUTES
) )
payload = { payload = {
@@ -1082,7 +1078,7 @@ def _set_refresh_token(
effective_organization_id: uuid.UUID, effective_organization_id: uuid.UUID,
epoch: int, epoch: int,
effective_roles: list[UserRole] | None = None, effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None, effective_institution_id: str | None = None,
) -> RefreshTokenMetadata: ) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. """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: Returns:
RefreshTokenMetadata: The generated refresh token object. 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 minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
) )
effective_roles = normalize_roles(effective_roles or effective_role) effective_roles = normalize_roles(effective_roles or effective_role)
@@ -1137,7 +1133,7 @@ def _build_access_token(
epoch: int, epoch: int,
user_fingerprint_hash: str, user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None, effective_roles: list[UserRole] | None = None,
effective_institution_id: Optional[str] = None, effective_institution_id: str | None = None,
) -> AccessToken: ) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash. """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: Returns:
AccessToken: The generated access token object. 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 minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
) )
effective_roles = normalize_roles(effective_roles or effective_role) effective_roles = normalize_roles(effective_roles or effective_role)
@@ -1189,7 +1185,7 @@ def _build_access_token(
def _build_token( def _build_token(
payload: Dict[str, Any], payload: dict[str, Any],
expiration_datetime: datetime.datetime, expiration_datetime: datetime.datetime,
token_type: TokenType, token_type: TokenType,
) -> str: ) -> str:
@@ -1203,7 +1199,7 @@ def _build_token(
Returns: Returns:
str: The encoded JWT token. str: The encoded JWT token.
""" """
now = datetime.datetime.now(datetime.timezone.utc) now = datetime.datetime.now(datetime.UTC)
payload.update( payload.update(
{ {
"exp": expiration_datetime, "exp": expiration_datetime,
@@ -1219,7 +1215,7 @@ def _build_token(
return 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. """Verifies the provided ID token and returns the decoded payload if valid.
Args: Args:
@@ -1239,7 +1235,7 @@ def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
return payload 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. """Verifies the provided refresh token and returns the decoded payload if valid.
Args: Args:
@@ -1263,7 +1259,7 @@ def _verify_access_token_fp(
secure_fgp: str, secure_fgp: str,
raw_access_token: str, raw_access_token: str,
session: Session, 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. """Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
Args: Args:
@@ -1381,7 +1377,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
return 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. """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: Args:
@@ -1408,7 +1404,7 @@ def change_password(
access_token: AccessTokenMetadata, access_token: AccessTokenMetadata,
current_password: str, current_password: str,
new_password: str, new_password: str,
) -> Dict[str, str]: ) -> dict[str, str]:
"""Change the password for the user associated with the provided access token. """Change the password for the user associated with the provided access token.
Args: 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 datetime as _dt
import uuid
from datetime import timedelta 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 import service as auth_service
from inse.auth.model import ( from inse.auth.model import (
AccessToken,
AccessTokenMetadata,
Account, Account,
IdTokenMetadata,
Organization, Organization,
RefreshTokenMetadata,
Secret, Secret,
SecretPurpose, SecretPurpose,
AccessToken,
IdTokenMetadata,
AccessTokenMetadata,
RefreshTokenMetadata,
UserRole, 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] refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
), ),
expires_at=_dt.datetime.fromtimestamp( 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], epoch=refresh_payload[auth_service.EPOCH_KEY],
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_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) org, acc = create_org_and_account(in_memory_session, email, password)
assert acc.id is not None 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( secret = Secret(
account_id=acc.id, account_id=acc.id,
purpose=SecretPurpose.LOGIN_OTK, 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 assert acc.id is not None
response = Response() 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) access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
payload = { payload = {
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id), 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): with pytest.raises(ValueError):
auth_service._build_token( auth_service._build_token(
payload={}, payload={},
expiration_datetime=_dt.datetime.now(_dt.timezone.utc), expiration_datetime=_dt.datetime.now(_dt.UTC),
token_type=auth_service.TokenType.ID_TOKEN, token_type=auth_service.TokenType.ID_TOKEN,
) )
config_module.settings.token_hmac_key = saved 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, account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET, purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token), 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.add(secret)
in_memory_session.commit() in_memory_session.commit()
@@ -753,7 +751,7 @@ def test_reset_password_rejects_reused_token(in_memory_session):
account_id=acc.id, account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET, purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token), 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.add(secret)
in_memory_session.commit() in_memory_session.commit()
@@ -792,7 +790,7 @@ def test_reset_password_rejects_expired_token(in_memory_session):
account_id=acc.id, account_id=acc.id,
purpose=SecretPurpose.PASSWORD_RESET, purpose=SecretPurpose.PASSWORD_RESET,
secret_value=auth_service._hash_reset_token(reset_token), 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.add(secret)
in_memory_session.commit() in_memory_session.commit()
@@ -1,13 +1,12 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Iterable from collections.abc import Iterable
from datetime import datetime, timezone from datetime import UTC, datetime
from typing import Any, Literal from typing import Any, Literal
AFFILIATION_LOOKBACK_YEARS = 2 AFFILIATION_LOOKBACK_YEARS = 2
OPENALEX_ID_PREFIX = "https://openalex.org/" OPENALEX_ID_PREFIX = "https://openalex.org/"
AffiliationYearMode = Literal["all", "in", "from"] AffiliationYearMode = Literal["all", "in", "from", "between"]
def current_affiliation_year_cutoff( def current_affiliation_year_cutoff(
@@ -21,7 +20,7 @@ def current_affiliation_year_cutoff(
when needed. 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 return current_time.year - AFFILIATION_LOOKBACK_YEARS
@@ -29,17 +28,20 @@ def build_institution_affiliation_query(
institution_id: str, institution_id: str,
year_mode: AffiliationYearMode = "all", year_mode: AffiliationYearMode = "all",
year: int | None = None, year: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Build an affiliation query for an institution and optional year rule. """Build an affiliation query for an institution and optional year rule.
``all`` accepts an affiliation from any year and requires ``year=None``. ``all`` accepts an affiliation from any year and requires ``year=None``.
``in`` requires an affiliation in exactly ``year``. ``in`` requires an affiliation in exactly ``year``.
``from`` requires an affiliation in ``year`` or any later 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. Institution IDs are normalized to their full OpenAlex URL.
""" """
normalized_institution_id = _normalize_openalex_id(institution_id) 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]] = [ affiliation_filters: list[dict[str, Any]] = [
{ {
@@ -56,6 +58,17 @@ def build_institution_affiliation_query(
affiliation_filters.append( affiliation_filters.append(
{"range": {"affiliations.years": {"gte": year}}} {"range": {"affiliations.years": {"gte": year}}}
) )
elif year_mode == "between":
affiliation_filters.append(
{
"range": {
"affiliations.years": {
"gte": year,
"lte": year_to,
}
}
}
)
return { return {
"nested": { "nested": {
@@ -69,6 +82,7 @@ def build_institution_membership_query(
institution_id: str, institution_id: str,
year_mode: AffiliationYearMode = "all", year_mode: AffiliationYearMode = "all",
year: int | None = None, year: int | None = None,
year_to: int | None = None,
author_ids: Iterable[str] | None = None, author_ids: Iterable[str] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Build an institution membership query for the selected year mode. """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. last-known institution IDs are available.
``in`` deliberately excludes condition 2 because an exact year requires ``in`` deliberately excludes condition 2 because an exact year requires
explicit affiliation evidence for that year. When ``author_ids`` are explicit affiliation evidence for that year. ``between`` applies the same
supplied, the query is restricted to those authors in the same rule to its bounded period. When ``author_ids`` are supplied, the query is
Elasticsearch request. Empty ``author_ids`` produce ``match_none``. restricted to those authors in the same Elasticsearch request. Empty
Institution and author IDs are normalized to full OpenAlex URLs. ``author_ids`` produce ``match_none``. Institution and author IDs are
normalized to full OpenAlex URLs.
""" """
normalized_institution_id = _normalize_openalex_id(institution_id) normalized_institution_id = _normalize_openalex_id(institution_id)
@@ -94,6 +109,7 @@ def build_institution_membership_query(
normalized_institution_id, normalized_institution_id,
year_mode=year_mode, year_mode=year_mode,
year=year, year=year,
year_to=year_to,
) )
author_filters: list[dict[str, Any]] = [] 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. # Last-known is the fallback only when affiliation IDs are unavailable.
membership_branches.insert( membership_branches.insert(
1, 1,
@@ -213,15 +229,28 @@ def build_active_institution_membership_query(
def _validate_year_mode( def _validate_year_mode(
year_mode: AffiliationYearMode, year_mode: AffiliationYearMode,
year: int | None, year: int | None,
year_to: int | None,
) -> 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}") raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
if year_mode == "all": if year_mode == "all":
if year is not None: if year is not None or year_to is not None:
raise ValueError("year must be omitted when year_mode is 'all'") raise ValueError(
"year and year_to must be omitted when year_mode is 'all'"
)
return return
if isinstance(year, bool) or not isinstance(year, int): if isinstance(year, bool) or not isinstance(year, int):
raise ValueError(f"year is required when year_mode is '{year_mode}'") 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: def _normalize_openalex_id(raw_id: str) -> str:
@@ -65,7 +65,7 @@ def mark_collaboration_graph_job_completed(
return return
job.status = CollaborationGraphStatus.COMPLETED job.status = CollaborationGraphStatus.COMPLETED
job.set_result(result) 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.add(job)
session.commit() session.commit()
@@ -86,7 +86,7 @@ def mark_collaboration_graph_job_failed(
return return
job.status = CollaborationGraphStatus.FAILED job.status = CollaborationGraphStatus.FAILED
job.error_message = error_message 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.add(job)
session.commit() session.commit()
@@ -103,7 +103,7 @@ def cleanup_old_collaboration_graph_jobs(
Returns: Returns:
int: The number of stale jobs that were cleaned up. 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( statement = select(CollaborationGraphJob).where(
CollaborationGraphJob.created_at < cutoff_time CollaborationGraphJob.created_at < cutoff_time
) )
+1 -1
View File
@@ -142,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
return await search_authors( return await search_authors(
page=0, page=0,
size=len(author_ids) if len(author_ids) <10000 else 10000, size=min(10000, len(author_ids)),
query={"terms": {"id": author_ids}}, query={"terms": {"id": author_ids}},
source=[ source=[
"id", "id",
+28 -29
View File
@@ -2,9 +2,8 @@
Database tables and API schemas for the background job runner. 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 enum import StrEnum
from typing import Optional
from pydantic import BaseModel from pydantic import BaseModel
from sqlmodel import JSON, Column, Field, SQLModel from sqlmodel import JSON, Column, Field, SQLModel
@@ -23,13 +22,13 @@ class JobTriggeredBy(StrEnum):
def utcnow() -> datetime: def utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None) return datetime.now(UTC).replace(tzinfo=None)
class JobDefinition(SQLModel, table=True): class JobDefinition(SQLModel, table=True):
__tablename__ = "background_job_definition" __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( name: str = Field(
index=True, unique=True, description="Human-readable job name shown in the UI." 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( target_index: str = Field(
default="", description="Elasticsearch index the job writes to (UI info)." default="", description="Elasticsearch index the job writes to (UI info)."
) )
image: Optional[str] = Field( image: str | None = Field(
default=None, default=None,
description="Docker image to run. Null falls back to the configured " description="Docker image to run. Null falls back to the configured "
"background-jobs image.", "background-jobs image.",
) )
command: Optional[str] = Field( command: str | None = Field(
default=None, default=None,
description="Command passed to the image. Null uses the job name (for " description="Command passed to the image. Null uses the job name (for "
"known jobs) or the image's default entrypoint.", "known jobs) or the image's default entrypoint.",
@@ -52,14 +51,14 @@ class JobDefinition(SQLModel, table=True):
sa_column=Column(JSON), sa_column=Column(JSON),
description="Extra environment variables passed to the container.", description="Extra environment variables passed to the container.",
) )
schedule: Optional[str] = Field( schedule: str | None = Field(
default=None, default=None,
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.", description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
) )
enabled: bool = Field( enabled: bool = Field(
default=True, description="Disabled definitions are never scheduled." 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." default=None, description="Computed by the scheduler from the cron expression."
) )
created_at: datetime = Field(default_factory=utcnow) created_at: datetime = Field(default_factory=utcnow)
@@ -68,19 +67,19 @@ class JobDefinition(SQLModel, table=True):
class JobRun(SQLModel, table=True): class JobRun(SQLModel, table=True):
__tablename__ = "background_job_run" __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( definition_id: int = Field(
foreign_key="background_job_definition.id", index=True 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) status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
triggered_by: JobTriggeredBy = Field( triggered_by: JobTriggeredBy = Field(
description="Whether the scheduler or a superadmin started this run." description="Whether the scheduler or a superadmin started this run."
) )
started_at: datetime = Field(default_factory=utcnow) started_at: datetime = Field(default_factory=utcnow)
finished_at: Optional[datetime] = Field(default=None) finished_at: datetime | None = Field(default=None)
exit_code: Optional[int] = Field(default=None) exit_code: int | None = Field(default=None)
logs: Optional[str] = Field( logs: str | None = Field(
default=None, default=None,
description="Captured stdout/stderr, filled in when the run finishes " description="Captured stdout/stderr, filled in when the run finishes "
"(the container itself is removed afterwards).", "(the container itself is removed afterwards).",
@@ -89,24 +88,24 @@ class JobRun(SQLModel, table=True):
class JobDefinitionCreateRequest(BaseModel): class JobDefinitionCreateRequest(BaseModel):
name: str name: str
image: Optional[str] = None image: str | None = None
command: Optional[str] = None command: str | None = None
env: dict[str, str] = {} env: dict[str, str] = {}
description: str = "" description: str = ""
target_index: str = "" target_index: str = ""
schedule: Optional[str] = None schedule: str | None = None
enabled: bool = True enabled: bool = True
class JobDefinitionUpdateRequest(BaseModel): class JobDefinitionUpdateRequest(BaseModel):
name: Optional[str] = None name: str | None = None
image: Optional[str] = None image: str | None = None
command: Optional[str] = None command: str | None = None
env: Optional[dict[str, str]] = None env: dict[str, str] | None = None
description: Optional[str] = None description: str | None = None
target_index: Optional[str] = None target_index: str | None = None
schedule: Optional[str] = None schedule: str | None = None
enabled: Optional[bool] = None enabled: bool | None = None
class BackgroundJobTask(BaseModel): class BackgroundJobTask(BaseModel):
@@ -114,13 +113,13 @@ class BackgroundJobTask(BaseModel):
name: str name: str
description: str description: str
target_index: str target_index: str
image: Optional[str] image: str | None
command: Optional[str] command: str | None
env: dict[str, str] env: dict[str, str]
schedule: Optional[str] schedule: str | None
enabled: bool enabled: bool
next_run_at: Optional[datetime] next_run_at: datetime | None
last_run: Optional[JobRun] last_run: JobRun | None
status: str status: str
@@ -11,11 +11,11 @@ from .model import (
AvailableImages, AvailableImages,
BackgroundJobTask, BackgroundJobTask,
DockerHealth, DockerHealth,
RegistryHealth,
JobDefinitionCreateRequest, JobDefinitionCreateRequest,
JobDefinitionUpdateRequest, JobDefinitionUpdateRequest,
JobRun, JobRun,
JobRunLogs, JobRunLogs,
RegistryHealth,
) )
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS]) router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
+16 -17
View File
@@ -8,7 +8,6 @@ import logging
import re import re
from datetime import datetime from datetime import datetime
from threading import RLock from threading import RLock
from typing import Optional
import docker import docker
import httpx import httpx
@@ -28,7 +27,7 @@ settings = config.get_settings()
RUN_STATE_LOCK = RLock() RUN_STATE_LOCK = RLock()
_client: Optional[docker.DockerClient] = None _client: docker.DockerClient | None = None
def get_docker_client() -> docker.DockerClient: def get_docker_client() -> docker.DockerClient:
@@ -42,7 +41,7 @@ def docker_reachable() -> tuple[bool, str]:
try: try:
get_docker_client().ping() get_docker_client().ping()
return True, "ok" return True, "ok"
except Exception as error: # noqa: BLE001 except Exception as error:
return False, str(error) return False, str(error)
@@ -59,7 +58,7 @@ def registry_reachable() -> tuple[bool, str]:
if response.status_code == 401: if response.status_code == 401:
return False, "authentication failed (401)" return False, "authentication failed (401)"
return False, f"unexpected status {response.status_code}" return False, f"unexpected status {response.status_code}"
except Exception as error: # noqa: BLE001 except Exception as error:
return False, str(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 = client.get(f"{base}/v2/{repository}/tags/list")
response.raise_for_status() response.raise_for_status()
tags = response.json().get("tags") or [] tags = response.json().get("tags") or []
except Exception: # noqa: BLE001 except Exception:
tags = [] tags = []
if tags: if tags:
images.extend(f"{host}/{repository}:{tag}" for tag in tags) images.extend(f"{host}/{repository}:{tag}" for tag in tags)
else: else:
images.append(f"{host}/{repository}") images.append(f"{host}/{repository}")
return sorted(images), "" return sorted(images), ""
except Exception as error: # noqa: BLE001 except Exception as error:
logger.warning("Could not list registry images.", exc_info=True) logger.warning("Could not list registry images.", exc_info=True)
return [], str(error) return [], str(error)
def resolve_image(definition: JobDefinition) -> Optional[str]: def resolve_image(definition: JobDefinition) -> str | None:
return definition.image or 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() 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 {})} return {**base, **(definition.env or {})}
def registry_auth() -> Optional[dict[str, str]]: def registry_auth() -> dict[str, str] | None:
if ( if (
settings.background_jobs_registry_username settings.background_jobs_registry_username
and settings.background_jobs_registry_password 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): if settings.background_jobs_pull_before_run and is_registry_image(image):
try: try:
pull_image(image) pull_image(image)
except Exception as error: # noqa: BLE001 except Exception as error:
run.status = JobRunStatus.FAILED run.status = JobRunStatus.FAILED
run.finished_at = utcnow() run.finished_at = utcnow()
run.logs = ( run.logs = (
@@ -211,7 +210,7 @@ def start_run(
remove=False, remove=False,
) )
run.container_id = container.id run.container_id = container.id
except Exception as error: # noqa: BLE001 except Exception as error:
run.status = JobRunStatus.FAILED run.status = JobRunStatus.FAILED
run.finished_at = utcnow() run.finished_at = utcnow()
run.logs = ( run.logs = (
@@ -241,8 +240,8 @@ def schedule_due_jobs(session: Session) -> None:
now = utcnow() now = utcnow()
scheduled = session.exec( scheduled = session.exec(
select(JobDefinition).where( select(JobDefinition).where(
JobDefinition.enabled == True, # noqa: E712 JobDefinition.enabled == True,
JobDefinition.schedule != None, # noqa: E711 JobDefinition.schedule != None,
) )
).all() ).all()
@@ -276,8 +275,8 @@ def finalize_run(
*, *,
new_status: JobRunStatus, new_status: JobRunStatus,
expected_status: JobRunStatus = JobRunStatus.RUNNING, expected_status: JobRunStatus = JobRunStatus.RUNNING,
exit_code: Optional[int] = None, exit_code: int | None = None,
logs: Optional[str] = None, logs: str | None = None,
) -> bool: ) -> bool:
values: dict = {"status": new_status, "finished_at": utcnow()} values: dict = {"status": new_status, "finished_at": utcnow()}
if exit_code is not None: 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: def remove_container(container, run_id: int) -> None:
try: try:
container.remove() container.remove()
except Exception: # noqa: BLE001 except Exception:
logger.warning( logger.warning(
"Could not remove container for run %s.", run_id, exc_info=True "Could not remove container for run %s.", run_id, exc_info=True
) )
@@ -371,6 +370,6 @@ async def scheduler_loop() -> None:
while True: while True:
try: try:
await asyncio.to_thread(tick) await asyncio.to_thread(tick)
except Exception: # noqa: BLE001 except Exception:
logger.exception("Background job scheduler tick failed.") logger.exception("Background job scheduler tick failed.")
await asyncio.sleep(settings.background_jobs_tick_seconds) await asyncio.sleep(settings.background_jobs_tick_seconds)
@@ -17,7 +17,6 @@ from .model import (
AvailableImages, AvailableImages,
BackgroundJobTask, BackgroundJobTask,
DockerHealth, DockerHealth,
RegistryHealth,
JobDefinition, JobDefinition,
JobDefinitionCreateRequest, JobDefinitionCreateRequest,
JobDefinitionUpdateRequest, JobDefinitionUpdateRequest,
@@ -25,6 +24,7 @@ from .model import (
JobRunLogs, JobRunLogs,
JobRunStatus, JobRunStatus,
JobTriggeredBy, JobTriggeredBy,
RegistryHealth,
utcnow, utcnow,
) )
@@ -289,7 +289,7 @@ def get_run_logs(
"utf-8", errors="replace" "utf-8", errors="replace"
), ),
) )
except Exception: # noqa: BLE001 except Exception:
pass pass
return JobRunLogs( return JobRunLogs(
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "") 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, status_code=status.HTTP_409_CONFLICT,
detail=f"Container for run {run_id} no longer exists.", detail=f"Container for run {run_id} no longer exists.",
) from error ) from error
except Exception as error: # noqa: BLE001 except Exception as error:
logger.warning( logger.warning(
"Could not inspect run %s before stopping.", run_id, exc_info=True "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, status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.", detail=f"Could not stop container for run {run_id}.",
) from error ) from error
except Exception as error: # noqa: BLE001 except Exception as error:
logger.warning("Could not stop run %s.", run_id, exc_info=True) logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException( raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY, status_code=status.HTTP_502_BAD_GATEWAY,
+4 -3
View File
@@ -1,7 +1,8 @@
import uuid 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 sqlalchemy import UniqueConstraint
from sqlmodel import Field, SQLModel from sqlmodel import Field, SQLModel
@@ -21,7 +22,7 @@ class PersonBookmark(SQLModel, table=True):
person_id: str = Field(nullable=False, index=True) person_id: str = Field(nullable=False, index=True)
person_name: str | None = Field(default=None) person_name: str | None = Field(default=None)
created_at: datetime = Field( 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 . import service
from .model import CreatePersonBookmark, PersonBookmarkResponse from .model import CreatePersonBookmark, PersonBookmarkResponse
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"]) router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
@@ -1,9 +1,10 @@
import logging import logging
from typing import Any from typing import Any
from . import model
from inse.authors.v2.service import author_currently_belongs_to_institution from inse.authors.v2.service import author_currently_belongs_to_institution
from inse.exceptions import NotFoundException from inse.exceptions import NotFoundException
from . import model
from .search_client import CompanyConnectionsSearchClient from .search_client import CompanyConnectionsSearchClient
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -1,14 +1,10 @@
from typing import Any from typing import Any
from .. import config from inse.exceptions import ElasticsearchNotFoundException
from inse.integrations import elasticsearch from inse.integrations import elasticsearch
from inse.model import ESCluster from inse.model import ESCluster
from inse.exceptions import ElasticsearchNotFoundException
from .. import config
from inse.exceptions import MissingApiKeyError
class CompanyConnectionsSearchClient: class CompanyConnectionsSearchClient:
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
REST API for possible company connections of OpenAlex authors. REST API for possible company connections of OpenAlex authors.
""" """
+21 -22
View File
@@ -1,17 +1,16 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
This module contains the configuration properties This module contains the configuration properties
that can be adjusted via environment variables. that can be adjusted via environment variables.
""" """
from functools import lru_cache
import logging import logging
from functools import lru_cache
from pathlib import Path from pathlib import Path
from typing import Dict, List, Literal, Optional from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv
from dotenv import load_dotenv
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -35,17 +34,17 @@ class Settings(BaseSettings):
openalex_works_search_timeout_seconds: float = 30.0 openalex_works_search_timeout_seconds: float = 30.0
# OpenAlex public API config # OpenAlex public API config
openalex_api_base_url: str = "https://api.openalex.org" 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 openalex_api_timeout_seconds: float = 30.0
# Patent Elasticsearch config # Patent Elasticsearch config
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic" 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 config
llm_api_url: Optional[str] = None llm_api_url: str | None = None
llm_api_key: Optional[str] = None llm_api_key: str | None = None
llm_model: Optional[str] = None llm_model: str | None = None
# Background job runner config (Docker-out-of-Docker) # Background job runner config (Docker-out-of-Docker)
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest" background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
@@ -58,25 +57,25 @@ class Settings(BaseSettings):
# Credentials for pulling the job image from a private registry (e.g. the # 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 # 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. # Docker SDK inside the service container, which has no `docker login` creds.
background_jobs_registry_username: Optional[str] = None background_jobs_registry_username: str | None = None
background_jobs_registry_password: Optional[str] = None background_jobs_registry_password: str | None = None
# Sentence Transformers config # Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
# Elasticsearch config # Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic" elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
elasticsearch_api_key: Optional[str] = None elasticsearch_api_key: str | None = None
elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_url: str | None = None
elasticsearch_inse_api_key: Optional[str] = None elasticsearch_inse_api_key: str | None = None
print_es_queries: bool = False print_es_queries: bool = False
print_es_timings: bool = False print_es_timings: bool = False
model_config = SettingsConfigDict(env_file=str(ENV_FILE)) 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"}, {"url": "http://localhost:8000", "description": "Local development server"},
] ]
@@ -84,8 +83,8 @@ class Settings(BaseSettings):
environment: Literal["dev", "prod"] = "dev" environment: Literal["dev", "prod"] = "dev"
token_issuer_id: Optional[str] = None token_issuer_id: str | None = None
token_hmac_key: Optional[str] = None token_hmac_key: str | None = None
skip_otk_validation: bool = True skip_otk_validation: bool = True
# SMTP / email config # SMTP / email config
@@ -95,8 +94,8 @@ class Settings(BaseSettings):
smtp_server: str = "localhost" smtp_server: str = "localhost"
smtp_port: int = 25 smtp_port: int = 25
smtp_sender: str = "no-reply@smartguide.local" smtp_sender: str = "no-reply@smartguide.local"
smtp_username: Optional[str] = None smtp_username: str | None = None
smtp_password: Optional[str] = None smtp_password: str | None = None
smtp_use_tls: bool = False smtp_use_tls: bool = False
+6
View File
@@ -42,6 +42,11 @@ class DfgProjectStatusStatistics(BaseModel):
completed: int completed: int
class DfgProjectKeyword(BaseModel):
name: str
project_count: int
class DfgProjectTopic(BaseModel): class DfgProjectTopic(BaseModel):
id: str id: str
name: str name: str
@@ -49,6 +54,7 @@ class DfgProjectTopic(BaseModel):
field: str | None = None field: str | None = None
domain: str | None = None domain: str | None = None
project_count: int project_count: int
keywords: list[DfgProjectKeyword]
class DfgProjectTopics(BaseModel): class DfgProjectTopics(BaseModel):
+7 -3
View File
@@ -10,8 +10,8 @@ from inse.tags import Tags
from .model import ( from .model import (
BmbfProjectStatusStatistics, BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics, DashboardStatistics,
DashboardStatisticValue,
DfgProjectStatusStatistics, DfgProjectStatusStatistics,
DfgProjectTopics, DfgProjectTopics,
EuProjectStatusStatistics, EuProjectStatusStatistics,
@@ -22,11 +22,11 @@ from .model import (
from .service import ( from .service import (
get_dashboard_bmbf_project_statuses, get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects, get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_dfg_project_statuses, get_dashboard_dfg_project_statuses,
get_dashboard_dfg_projects,
get_dashboard_dfg_topics, get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses, get_dashboard_eu_project_statuses,
get_dashboard_eu_projects,
get_dashboard_organization, get_dashboard_organization,
get_dashboard_patents, get_dashboard_patents,
get_dashboard_persons, get_dashboard_persons,
@@ -82,6 +82,8 @@ async def dashboard_publications(
response_model=DashboardStatisticValue, response_model=DashboardStatisticValue,
) )
async def dashboard_persons( 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), session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DashboardStatisticValue: ) -> DashboardStatisticValue:
@@ -89,6 +91,8 @@ async def dashboard_persons(
return await get_dashboard_persons( return await get_dashboard_persons(
organization.openalex_institution_id, organization.openalex_institution_id,
organization.name, organization.name,
from_year=from_year,
to_year=to_year,
) )
+53 -16
View File
@@ -1,9 +1,9 @@
import asyncio import asyncio
import logging import logging
import re import re
from types import SimpleNamespace
from collections import defaultdict from collections import defaultdict
from datetime import datetime from datetime import datetime
from types import SimpleNamespace
from typing import Any, Literal from typing import Any, Literal
from fastapi import HTTPException, status from fastapi import HTTPException, status
@@ -12,22 +12,33 @@ from sqlmodel import Session
from inse import config from inse import config
from inse.auth.model import AccessToken, Organization from inse.auth.model import AccessToken, Organization
from inse.authors.institution_membership_query import ( from inse.authors.institution_membership_query import (
build_active_institution_membership_query, build_institution_membership_query,
) )
from inse.integrations import elasticsearch
from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector from inse.projects.dfg_institutions.service import (
autocomplete_institutions_for_selector,
)
from inse.projects.eu_cordis_projects_client import (
get_eu_project_ids_by_organization_filters,
)
from inse.projects.logic import get_person_ids_by_institution_ids from inse.projects.logic import get_person_ids_by_institution_ids
from inse.projects.model import (
EuCordisProjectType,
ProjectsFilteringProperties,
ProjectType,
)
from .institute_helper import get_openalex_institution from .institute_helper import get_openalex_institution
from .model import ( from .model import (
BmbfProjectStatusStatistics, BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics, DashboardStatistics,
DfgProjectTopic, DfgProjectKeyword,
DashboardStatisticValue,
DfgProjectStatusStatistics, DfgProjectStatusStatistics,
DfgProjectTopic,
DfgProjectTopics, DfgProjectTopics,
EuProjectStatusStatistics, EuProjectStatusStatistics,
TopAuthor, TopAuthor,
@@ -40,14 +51,6 @@ from .model import (
TopicWordCloud, TopicWordCloud,
TopicWordCloudWord, TopicWordCloudWord,
) )
from inse.projects.eu_cordis_projects_client import (
get_eu_project_ids_by_organization_filters,
)
from inse.projects.model import (
EuCordisProjectType,
ProjectType,
ProjectsFilteringProperties,
)
TOP_AUTHOR_LIMIT = 10 TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25 TOPIC_HEATMAP_LIMIT = 25
@@ -257,11 +260,25 @@ async def get_dashboard_publications(
async def get_dashboard_persons( async def get_dashboard_persons(
institution_id: str, institution_id: str,
organization_name: str, organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DashboardStatisticValue: ) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id) normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
if (period[0] is None) != (period[1] is None):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="from_year and to_year must either both be provided or both omitted.",
)
membership_query = build_institution_membership_query(
institution_id=normalized_id,
year_mode="between" if period[0] is not None else "all",
year=period[0],
year_to=period[1],
)
response = await elasticsearch.search( response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS, index=ESIndex.OPENALEX_AUTHORS,
query=build_active_institution_membership_query(normalized_id), query=membership_query,
size=0, size=0,
track_total_hits=True, track_total_hits=True,
cluster=ESCluster.NES, cluster=ESCluster.NES,
@@ -644,6 +661,12 @@ async def get_dashboard_dfg_topics(
from_year=from_year, from_year=from_year,
to_year=to_year, to_year=to_year,
) )
print(
"Dashboard DFG project topics "
f"for institution {normalized_id}: "
f"{len(project_ids)} project IDs={project_ids}",
flush=True,
)
topics: dict[str, dict[str, Any]] = {} topics: dict[str, dict[str, Any]] = {}
matched_project_ids: set[str] = set() matched_project_ids: set[str] = set()
@@ -651,7 +674,7 @@ async def get_dashboard_dfg_topics(
async for hit in elasticsearch.scan( async for hit in elasticsearch.scan(
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS), index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
query={"terms": {"project_id": project_ids}}, query={"terms": {"project_id": project_ids}},
source=["project_id", "topic_matches"], source=["project_id", "keyword", "topic_matches"],
page_size=1000, page_size=1000,
cluster=ESCluster.INSE, cluster=ESCluster.INSE,
): ):
@@ -659,6 +682,7 @@ async def get_dashboard_dfg_topics(
project_id = str(source.get("project_id") or "") project_id = str(source.get("project_id") or "")
if not project_id: if not project_id:
continue continue
keyword = str(source.get("keyword") or "").strip()
matched_project_ids.add(project_id) matched_project_ids.add(project_id)
for match in source.get("topic_matches", []): for match in source.get("topic_matches", []):
topic_id = str(match.get("topic_id") or "") topic_id = str(match.get("topic_id") or "")
@@ -673,9 +697,12 @@ async def get_dashboard_dfg_topics(
"field": match.get("field"), "field": match.get("field"),
"domain": match.get("domain"), "domain": match.get("domain"),
"project_ids": set(), "project_ids": set(),
"keywords": {},
}, },
) )
topic["project_ids"].add(project_id) topic["project_ids"].add(project_id)
if keyword:
topic["keywords"].setdefault(keyword, set()).add(project_id)
topic_list = [ topic_list = [
DfgProjectTopic( DfgProjectTopic(
@@ -685,6 +712,16 @@ async def get_dashboard_dfg_topics(
field=topic["field"], field=topic["field"],
domain=topic["domain"], domain=topic["domain"],
project_count=len(topic["project_ids"]), project_count=len(topic["project_ids"]),
keywords=sorted(
[
DfgProjectKeyword(
name=keyword,
project_count=len(keyword_project_ids),
)
for keyword, keyword_project_ids in topic["keywords"].items()
],
key=lambda entry: (-entry.project_count, entry.name),
),
) )
for topic in topics.values() for topic in topics.values()
] ]
@@ -1,6 +1,6 @@
from unittest.mock import AsyncMock, patch
from datetime import datetime from datetime import datetime
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest import pytest
from fastapi import HTTPException from fastapi import HTTPException
@@ -116,10 +116,10 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
) )
person_query = person_call.kwargs["query"] person_query = person_call.kwargs["query"]
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1] affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
assert recent_affiliation["nested"]["path"] == "affiliations" assert affiliation["nested"]["path"] == "affiliations"
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == { assert affiliation["nested"]["query"]["bool"]["filter"][0] == {
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID} "term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
} }
eu_call = next( eu_call = next(
-5
View File
@@ -10,22 +10,18 @@ class NotFoundException(Exception):
class ElasticsearchException(Exception): class ElasticsearchException(Exception):
"""Base exception for all Elasticsearch integrations.""" """Base exception for all Elasticsearch integrations."""
pass
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException): class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
"""Raised when an Elasticsearch document or index is not found.""" """Raised when an Elasticsearch document or index is not found."""
pass
class ElasticsearchConnectionException(ElasticsearchException): class ElasticsearchConnectionException(ElasticsearchException):
"""Raised when connecting to Elasticsearch fails.""" """Raised when connecting to Elasticsearch fails."""
pass
class MissingApiKeyError(Exception): class MissingApiKeyError(Exception):
"""Raised when a required API key is missing.""" """Raised when a required API key is missing."""
pass
class UpstreamAPIException(Exception): class UpstreamAPIException(Exception):
@@ -38,4 +34,3 @@ class UpstreamAPIException(Exception):
class BadRequestException(Exception): class BadRequestException(Exception):
"""Raised when request parameters are invalid or validation fails.""" """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. 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. HTTP client for funded-publication searches in the OpenAlex works index.
""" """
from typing import Any from typing import Any
from .. import config from inse.exceptions import MissingApiKeyError
from inse.integrations import elasticsearch from inse.integrations import elasticsearch
from inse.model import ESCluster from inse.model import ESCluster
from .. import config
from inse.exceptions import MissingApiKeyError
class FundedPublicationsSearchClient: 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. Business logic for author funding based on publication works.
""" """
@@ -7,10 +6,14 @@ import logging
from typing import Any from typing import Any
from pydantic import ValidationError from pydantic import ValidationError
from inse.exceptions import (
UpstreamAPIException,
)
from ..persons import logic as person_logic from ..persons import logic as person_logic
from . import model from . import model
from .elastic_search_client import FundedPublicationsSearchClient from .elastic_search_client import FundedPublicationsSearchClient
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+1 -2
View File
@@ -1,7 +1,6 @@
from typing import Any from typing import Any
from pydantic import BaseModel from pydantic import BaseModel, Field
from pydantic import Field
class PublicationsByAuthorResponse(BaseModel): 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. REST API for author publications and funding.
""" """
from typing import Annotated from typing import Annotated
from fastapi import APIRouter from fastapi import APIRouter, Query
from fastapi import Query
from . import logic
from . import model
from . import logic, model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"]) 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 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 import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@@ -1,13 +1,10 @@
import logging import logging
from typing import List, Set from typing import Any, Literal
from typing import Any, Dict, Literal, Optional
from inse.models.openalex.institution import Institution
from inse.exceptions import NotFoundException from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.institutions.model import InstitutionPage from inse.institutions.model import InstitutionPage
from inse.integrations import elasticsearch
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -18,7 +15,6 @@ class InstitutionsSearchClient:
Initializes the client. Credentials and URLs are handled by the Initializes the client. Credentials and URLs are handled by the
centralized elasticsearch integration. centralized elasticsearch integration.
""" """
pass
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution: async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
"""Retrieves an institution by its raw OpenAlex institution ID. """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( async def get_eu_organisation_id_by_oa_institution_id(
self, raw_institution_id: str self, raw_institution_id: str
) -> Optional[str]: ) -> str | None:
"""Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available. """Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available.
Args: Args:
@@ -99,7 +95,7 @@ class InstitutionsSearchClient:
else: else:
sort_config.append({"display_name.keyword": {"order": sorting_direction}}) 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: if len(name) > 0:
query = { query = {
@@ -136,7 +132,7 @@ class InstitutionsSearchClient:
return self.response_to_institution_page(response, page, size) return self.response_to_institution_page(response, page, size)
def response_to_institution_page( def response_to_institution_page(
self, response: Dict[str, Any], page: int, size: int self, response: dict[str, Any], page: int, size: int
) -> InstitutionPage: ) -> InstitutionPage:
hits = response.get("hits", {}).get("hits", []) hits = response.get("hits", {}).get("hits", [])
@@ -250,7 +246,7 @@ class InstitutionsSearchClient:
async def get_institution_aliases_by_oa_institution_id( async def get_institution_aliases_by_oa_institution_id(
self, raw_oa_institution_id: str 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. """Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
Args: Args:
@@ -273,7 +269,7 @@ class InstitutionsSearchClient:
def get_predefined_institution_aliases( def get_predefined_institution_aliases(
self, raw_oa_institution_id: str self, raw_oa_institution_id: str
) -> Set[str]: ) -> set[str]:
"""Get predefined aliases for a given institution ID. """Get predefined aliases for a given institution ID.
Args: Args:
@@ -297,7 +293,7 @@ class InstitutionsSearchClient:
set(predefined_aliases.get(raw_oa_institution_id, [])) 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. """Augment a set of aliases by applying the augment_alias function to each alias.
Args: Args:
@@ -311,7 +307,7 @@ class InstitutionsSearchClient:
augmented_aliases.update(self.augment_alias(alias)) augmented_aliases.update(self.augment_alias(alias))
return augmented_aliases 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. """Augment an alias by replacing German umlauts and ß with their alternative spellings.
Args: Args:
@@ -343,7 +339,7 @@ class InstitutionsSearchClient:
aliases.append(alias.replace("-", " ")) aliases.append(alias.replace("-", " "))
return aliases 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. """Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
Args: Args:
@@ -388,7 +384,7 @@ class InstitutionsSearchClient:
async def get_cordis_eu_organisation_ids_by_oa_institution_id( async def get_cordis_eu_organisation_ids_by_oa_institution_id(
self, raw_oa_institution_id: str 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. """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: Args:
+6 -6
View File
@@ -1,26 +1,26 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
Business logic for OpenAlex institutions. Business logic for OpenAlex institutions.
""" """
import logging import logging
from copy import deepcopy from copy import deepcopy
from typing import Any, Optional from typing import Any
import httpx import httpx
from pydantic import ValidationError 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 import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
from inse.models.openalex.autocomplete_response_results_inner import ( from inse.models.openalex.autocomplete_response_results_inner import (
AutocompleteResponseResultsInner, AutocompleteResponseResultsInner,
) )
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.models.openalex.institution import Institution from inse.models.openalex.institution import Institution
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from .search_client import OpenAlexInstitutionsClient from .search_client import OpenAlexInstitutionsClient
from inse.institutions.institutions_search_client import InstitutionsSearchClient
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+1 -2
View File
@@ -1,4 +1,3 @@
from typing import List
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -6,7 +5,7 @@ from inse.models.openalex.institution import Institution
class InstitutionPage(BaseModel): class InstitutionPage(BaseModel):
elements: List[Institution] = Field( elements: list[Institution] = Field(
default_factory=list, description="List of institutions in the current page." default_factory=list, description="List of institutions in the current page."
) )
page: int = Field(default=0, description="Current page number. (0-indexed)") 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. REST API for OpenAlex institutions.
""" """
@@ -7,16 +6,16 @@ REST API for OpenAlex institutions.
from functools import lru_cache from functools import lru_cache
from typing import Annotated, Literal 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.autocomplete_response import AutocompleteResponse
from inse.models.openalex.institution import Institution
from inse.models.openalex.institutions_list_response import InstitutionsListResponse from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags 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]) 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. HTTP client for OpenAlex institutions.
""" """
@@ -1,7 +1,7 @@
import httpx import httpx
import pytest import pytest
from inse.exceptions import BadRequestException
from inse.exceptions import BadRequestException
from inse.institutions import logic from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient from inse.institutions.search_client import OpenAlexInstitutionsClient
@@ -1,22 +1,24 @@
import json import json
import logging import logging
import time import time
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple from collections.abc import AsyncIterator
from typing import Any
import httpx import httpx
from inse.exceptions import ( from inse.exceptions import (
ElasticsearchConnectionException,
ElasticsearchException, ElasticsearchException,
ElasticsearchNotFoundException, ElasticsearchNotFoundException,
ElasticsearchConnectionException,
MissingApiKeyError, MissingApiKeyError,
) )
from inse.model import ESCluster, ESIndex from inse.model import ESCluster, ESIndex
from .. import config from .. import config
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_client: Optional[httpx.AsyncClient] = None _client: httpx.AsyncClient | None = None
_loop = None _loop = None
@@ -35,7 +37,7 @@ def get_client() -> httpx.AsyncClient:
return _client 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. """Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
Args: Args:
@@ -75,7 +77,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')") 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. """Determines the Elasticsearch cluster to use based on the specified index.
Args: Args:
@@ -111,7 +113,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
return None return None
def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]: def _headers(api_key: str, content_type: str = "application/json") -> dict[str, str]:
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
@@ -135,9 +137,9 @@ async def _request(
cluster: ESCluster, cluster: ESCluster,
path: str, path: str,
*, *,
json_body: Optional[Any] = None, json_body: Any | None = None,
params: Optional[Dict[str, Any]] = None, params: dict[str, Any] | None = None,
content: Optional[bytes] = None, content: bytes | None = None,
content_type: str = "application/json", content_type: str = "application/json",
) -> httpx.Response: ) -> httpx.Response:
"""Sends an authenticated request to cluster and returns the raw response. """Sends an authenticated request to cluster and returns the raw response.
@@ -188,18 +190,18 @@ async def _request(
async def search( async def search(
index: ESIndex | List[ESIndex] | str | List[str], index: ESIndex | list[ESIndex] | str | list[str],
query: Optional[Dict] = None, query: dict | None = None,
source: Optional[List] = None, source: list | None = None,
size: Optional[int] = None, size: int | None = None,
offset: Optional[int] = None, offset: int | None = None,
sort: Optional[List] = None, sort: list | None = None,
aggs: Optional[Dict] = None, aggs: dict | None = None,
body: Optional[Dict] = None, body: dict | None = None,
track_total_hits=False, track_total_hits=False,
highlight: Optional[Dict] = None, highlight: dict | None = None,
cluster: ESCluster = ESCluster.NES, 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. """Searches the specified Elasticsearch index using either a simple query string or a full query body.
Args: Args:
@@ -237,7 +239,7 @@ async def search(
elif len(clusters) == 1: elif len(clusters) == 1:
cluster = clusters.pop() cluster = clusters.pop()
payload: Dict[str, Any] = {} payload: dict[str, Any] = {}
if body is not None: if body is not None:
payload = body payload = body
@@ -300,22 +302,22 @@ async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
async def scan( async def scan(
index: str, index: str,
query: Dict, query: dict,
source: Optional[List] = None, source: list | None = None,
page_size: int = 1000, page_size: int = 1000,
keep_alive: str = "1m", keep_alive: str = "1m",
cluster: str = "nes", cluster: str = "nes",
) -> AsyncIterator[Dict[str, Any]]: ) -> AsyncIterator[dict[str, Any]]:
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``. """Yields every hit matching ``query`` using a point-in-time + ``search_after``.
Unlike ``from``/``size`` pagination, this is not bounded by Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k. ``index.max_result_window``, so it can stream result sets larger than 10k.
""" """
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster) 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: try:
while True: while True:
payload: Dict[str, Any] = { payload: dict[str, Any] = {
"size": page_size, "size": page_size,
"query": query, "query": query,
"pit": {"id": pit_id, "keep_alive": keep_alive}, "pit": {"id": pit_id, "keep_alive": keep_alive},
@@ -351,7 +353,7 @@ async def scan(
async def get( async def get(
index: ESIndex | str, index: ESIndex | str,
doc_id: str, doc_id: str,
source: Optional[list] = None, source: list | None = None,
cluster: ESCluster = ESCluster.NES, cluster: ESCluster = ESCluster.NES,
) -> dict[str, Any]: ) -> dict[str, Any]:
@@ -370,9 +372,9 @@ async def get(
async def update( async def update(
index: str, index: str,
doc_id: str, doc_id: str,
doc: Dict[str, Any], doc: dict[str, Any],
cluster: ESCluster = ESCluster.NES, cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]: ) -> dict[str, Any]:
response = await _request( response = await _request(
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc} "POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
) )
@@ -383,9 +385,9 @@ async def update(
async def index_doc( async def index_doc(
index: str, index: str,
doc_id: str, doc_id: str,
document: Dict[str, Any], document: dict[str, Any],
cluster: ESCluster = ESCluster.NES, cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]: ) -> dict[str, Any]:
response = await _request( response = await _request(
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document "PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
) )
@@ -394,8 +396,8 @@ async def index_doc(
async def count( async def count(
index: ESIndex | List[ESIndex] | str | List[str], index: ESIndex | list[ESIndex] | str | list[str],
query: Optional[Dict[str, Any]] = None, query: dict[str, Any] | None = None,
cluster: ESCluster = ESCluster.NES, cluster: ESCluster = ESCluster.NES,
) -> int: ) -> int:
"""Performs a count request (_count) on the specified Elasticsearch index. """Performs a count request (_count) on the specified Elasticsearch index.
@@ -435,9 +437,9 @@ async def count(
async def msearch( 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, cluster: ESCluster = ESCluster.NES,
) -> List[Dict[str, Any]]: ) -> list[dict[str, Any]]:
"""Performs a multi-search request (_msearch) on Elasticsearch. """Performs a multi-search request (_msearch) on Elasticsearch.
Args: Args:
+8 -5
View File
@@ -1,8 +1,11 @@
from openai import APIConnectionError
from openai import AsyncOpenAI
from .. import config
from typing import Optional, Dict, Any
import asyncio import asyncio
from typing import Any
from openai import APIConnectionError, AsyncOpenAI
from .. import config
async def call( async def call(
system_prompt: str, system_prompt: str,
user_prompt: str, user_prompt: str,
@@ -45,7 +48,7 @@ async def call(
"Etwas ist schiefgelaufen. Bitte versuche es erneut." "Etwas ist schiefgelaufen. Bitte versuche es erneut."
) )
def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]: def _get_response_format(schema, schema_name: str | None = None) -> dict[str, Any]:
response_format = { response_format = {
"type": "json_schema", "type": "json_schema",
"json_schema": { "json_schema": {
@@ -1,10 +1,10 @@
# inse/keywords/file_extraction.py # inse/keywords/file_extraction.py
import base64 import base64
import logging
import httpx
from bs4 import BeautifulSoup
# import fitz # import fitz
import io import io
import logging
from pypdf import PdfReader from pypdf import PdfReader
from pypdf.errors import PdfReadError from pypdf.errors import PdfReadError
+24 -23
View File
@@ -1,39 +1,40 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
Business logic for persons / authors. Business logic for persons / authors.
""" """
import asyncio import asyncio
from typing import Any, Dict, List
import partial_json_parser
import json import json
import logging import logging
import time import time
from collections.abc import Awaitable, Callable
from typing import Any
import httpx import httpx
import partial_json_parser
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from pydantic import ValidationError from pydantic import ValidationError
from typing import Awaitable, Callable
from inse.keywords.prompts import KeywordsPrompt
from inse.integrations import llm from inse.integrations import llm
from inse.keywords.extract_text import extract_text_from_upload
from inse.keywords.model import ( from inse.keywords.model import (
ExtractedKeywords, ExtractedKeywords,
ExtractedKeywordsLLM, ExtractedKeywordsLLM,
ExtractedKeywordsResponse, ExtractedKeywordsResponse,
FileUpload,
KeywordEntry, KeywordEntry,
KeywordEntryWithTopic, KeywordEntryWithTopic,
KeywordsWsEvent, KeywordsWsEvent,
FileUpload,
) )
from inse.keywords.extract_text import extract_text_from_upload from inse.keywords.prompts import KeywordsPrompt
from inse.topics.logic import vector_search_topics_batch from inse.topics.logic import vector_search_topics_batch
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
EventCallback = Callable[[dict], Awaitable[None]] EventCallback = Callable[[dict], Awaitable[None]]
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained") LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
def _build_enriched_snapshot( def _build_enriched_snapshot(
confirmed: Dict[str, List[KeywordEntryWithTopic]], confirmed: dict[str, list[KeywordEntryWithTopic]],
) -> ExtractedKeywords: ) -> ExtractedKeywords:
return ExtractedKeywords.model_validate( return ExtractedKeywords.model_validate(
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS} {level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
@@ -41,13 +42,13 @@ def _build_enriched_snapshot(
async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords: async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords:
confirmed: Dict[str, List[KeywordEntryWithTopic]] = { confirmed: dict[str, list[KeywordEntryWithTopic]] = {
level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)] level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)]
for level in LEVELS for level in LEVELS
} }
keywords: List[str] = [] keywords: list[str] = []
positions: List[tuple[str, int]] = [] positions: list[tuple[str, int]] = []
for level in LEVELS: for level in LEVELS:
for idx, entry in enumerate(getattr(results, level)): for idx, entry in enumerate(getattr(results, level)):
keywords.append(entry.keyword) keywords.append(entry.keyword)
@@ -74,7 +75,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
text = query text = query
user_prompt = f""" user_prompt = """
Now analyze the following text and return ONLY the JSON object.\n""" Now analyze the following text and return ONLY the JSON object.\n"""
if limit: if limit:
@@ -105,15 +106,15 @@ async def extract_keywords_stream_enriched(
mode: str, mode: str,
limit: int, limit: int,
emit: EventCallback, emit: EventCallback,
files: List[FileUpload] | None = None, files: list[FileUpload] | None = None,
) -> ExtractedKeywordsResponse: ) -> ExtractedKeywordsResponse:
start_time = time.time() start_time = time.time()
timeout_seconds = 120 timeout_seconds = 120
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump()) await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained") LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS} confirmed: dict[str, list[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
enrichment_tasks: List[asyncio.Task] = [] enrichment_tasks: list[asyncio.Task] = []
async def emit_full_results() -> None: async def emit_full_results() -> None:
try: try:
@@ -136,7 +137,7 @@ async def extract_keywords_stream_enriched(
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}") logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results() await emit_full_results()
def make_on_chunk(base_offset: Dict[str, int]): def make_on_chunk(base_offset: dict[str, int]):
""" """
Builds an on_chunk callback for a single streaming LLM call. Builds an on_chunk callback for a single streaming LLM call.
@@ -147,7 +148,7 @@ async def extract_keywords_stream_enriched(
(one per file). (one per file).
""" """
async def on_chunk(event: Dict[str, Any]) -> None: async def on_chunk(event: dict[str, Any]) -> None:
if event["type"] != "llm_chunk": if event["type"] != "llm_chunk":
await emit(event) await emit(event)
return return
@@ -206,7 +207,7 @@ async def extract_keywords_stream_enriched(
on_chunk = make_on_chunk(base_offset) on_chunk = make_on_chunk(base_offset)
full_content_holder = {"value": ""} full_content_holder = {"value": ""}
async def emit_wrapper(event: Dict[str, Any]) -> None: async def emit_wrapper(event: dict[str, Any]) -> None:
if event["type"] == "llm_chunk": if event["type"] == "llm_chunk":
full_content_holder["value"] += event["content"] full_content_holder["value"] += event["content"]
event = {**event, "_full_content": full_content_holder["value"]} event = {**event, "_full_content": full_content_holder["value"]}
@@ -232,7 +233,7 @@ async def extract_keywords_stream_enriched(
), ),
timeout=timeout_seconds, timeout=timeout_seconds,
) )
except asyncio.TimeoutError: except TimeoutError:
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s{suffix}").model_dump()) await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call timed out{suffix}") raise RuntimeError(f"LLM streaming call timed out{suffix}")
except asyncio.CancelledError: except asyncio.CancelledError:
@@ -278,8 +279,8 @@ async def extract_keywords_stream_enriched(
).model_dump() ).model_dump()
) )
file_texts: List[str] = [] file_texts: list[str] = []
failed_files: List[str] = [] failed_files: list[str] = []
for i, f in enumerate(provided_files, start=1): for i, f in enumerate(provided_files, start=1):
text = await asyncio.to_thread( text = await asyncio.to_thread(
+8 -9
View File
@@ -1,14 +1,13 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
Data models for persons / authors. Data models for persons / authors.
""" """
from typing import List, Literal
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from inse.topics.model import KeywordTopicMatch from inse.topics.model import KeywordTopicMatch
class FileUpload(BaseModel): class FileUpload(BaseModel):
filename: str = Field(description="The name of the uploaded file.") filename: str = Field(description="The name of the uploaded file.")
content_base64: str = Field(description="The base64-encoded content of the uploaded file.") content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
@@ -36,14 +35,14 @@ class KeywordEntryWithTopic(BaseModel):
) )
class ExtractedKeywords(BaseModel): class ExtractedKeywords(BaseModel):
broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.") broad_keywords: list[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.") coarse_grained: list[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.") fine_grained: list[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
class ExtractedKeywordsLLM(BaseModel): class ExtractedKeywordsLLM(BaseModel):
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.") broad_keywords: list[KeywordEntry] = Field(description="The extracted broad keywords from text.")
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.") coarse_grained: list[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.") fine_grained: list[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
class ExtractedKeywordsResponse(BaseModel): class ExtractedKeywordsResponse(BaseModel):
results_llm: ExtractedKeywordsLLM | None = None results_llm: ExtractedKeywordsLLM | None = None
@@ -1,4 +1,6 @@
from enum import StrEnum from enum import StrEnum
class KeywordsPrompt(StrEnum): class KeywordsPrompt(StrEnum):
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst. EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
+4 -4
View File
@@ -1,18 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
REST API for persons / authors. REST API for persons / authors.
""" """
import asyncio import asyncio
import logging
from typing import Annotated from typing import Annotated
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
from uvicorn.protocols.utils import ClientDisconnected from uvicorn.protocols.utils import ClientDisconnected
from . import logic
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
import logging
from . import logic
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
+6 -12
View File
@@ -1,23 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" """
This module defines the business logic for our This module defines the business logic for our
web service. web service.
""" """
from typing import List
import logging
import json import json
import logging
from . import config
from inse.integrations import elasticsearch from inse.integrations import elasticsearch
from inse.models.openalex.topic import Topic from inse.models.openalex.topic import Topic
from inse.models.openalex.topic_subfield import TopicSubfield
from inse.models.openalex.topic_field import TopicField
from inse.models.openalex.topic_domain import TopicDomain from inse.models.openalex.topic_domain import TopicDomain
from inse.models.openalex.topic_field import TopicField
from inse.models.openalex.topic_subfield import TopicSubfield
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -91,7 +85,7 @@ async def build_topic_cache(save_json: bool = True) -> dict:
return taxonomy_cache return taxonomy_cache
def get_topics_from_cache(topic_names: List[str]) -> List[Topic]: def get_topics_from_cache(topic_names: list[str]) -> list[Topic]:
""" """
Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models. Given a list of topic names, retrieves their hierarchy information from the cache and returns a list of Topic models.
Arguments: Arguments:
@@ -123,7 +117,7 @@ def get_topics_from_cache(topic_names: List[str]) -> List[Topic]:
return topics return topics
def count_topic_hierarchy(topic_names: List[str]) -> dict: def count_topic_hierarchy(topic_names: list[str]) -> dict:
""" """
Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache. Given a list of topic names, counts the occurrences of each topic and their hierarchy levels (subfield, field, domain) using the cache.
Arguments: Arguments:
+2 -2
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
""" """
This module contains the bootstrapping code This module contains the bootstrapping code
for fastapi that loads the service and the for fastapi that loads the service and the
@@ -51,8 +51,8 @@ from inse.patents.service import (
router as patents_service_router, router as patents_service_router,
) )
from inse.persons.service import router as persons_service_router from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router from inse.projects.router import router as projects_router

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