Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d48435b948 | ||
|
|
c054cf99fe | ||
|
|
98a742f024 | ||
|
|
1fc509ea13 | ||
|
|
90a1b930a3 | ||
|
|
9011d58355 | ||
|
|
f2c0f203f6 | ||
|
|
3f5746dd7d | ||
|
|
adce95ead4 | ||
|
|
84d7ca0122 | ||
|
|
053af573fc | ||
|
|
06f34bec45 | ||
|
|
c1641fdb38 | ||
|
|
9115af350e | ||
|
|
77cf3612d9 | ||
|
|
07c7343f94 | ||
|
|
530f751f02 | ||
|
|
9a005cabe9 | ||
|
|
f7eb502d9d | ||
|
|
a407cfb514 | ||
|
|
ff43d07b6d | ||
|
|
340b5f22b7 | ||
|
|
b4a90131bb | ||
|
|
90149ddb4e | ||
|
|
1f09f0cf68 | ||
|
|
8035e7aecb | ||
|
|
cea32deba2 | ||
|
|
b02358e3a0 | ||
|
|
79320f27c9 | ||
|
|
52ca2f7339 | ||
|
|
78e54248e3 | ||
|
|
fc82604947 | ||
|
|
40bb0feaf8 | ||
|
|
0afb6a9481 | ||
|
|
57f72a473f | ||
|
|
876fbb9980 | ||
|
|
bee09f7c29 | ||
|
|
c31aef4131 | ||
|
|
53a36e7974 | ||
|
|
60e74c4916 | ||
|
|
1d24f912ae | ||
|
|
f9591c512c | ||
|
|
f74396e97b | ||
|
|
1127eeebb8 | ||
|
|
e9590e8b04 | ||
|
|
fd0bc89771 | ||
|
|
32a38b46fe | ||
|
|
e5f9d8cfdf | ||
|
|
ecd6b30626 | ||
|
|
31da701fe7 | ||
|
|
9d875b3935 | ||
|
|
8cab4ffb42 | ||
|
|
61aeb5bf86 | ||
|
|
0821008d6e | ||
|
|
a4a24b77b9 | ||
|
|
897edab3cf | ||
|
|
a25d70466f | ||
|
|
4270dafd6a | ||
|
|
fc3baef406 | ||
|
|
be20407238 | ||
|
|
26c4dc8fe7 | ||
|
|
4dd124d003 | ||
|
|
ee40f1386a | ||
|
|
4f116d3ca2 | ||
|
|
9ef1ce7ce1 | ||
|
|
345dffaa9b |
@@ -5,7 +5,6 @@ from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
from typing import Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
|
||||
@@ -4,7 +4,6 @@ from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import os
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
AD_PATH = BASE_DIR / "AD.pdf"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pymupdf4llm
|
||||
|
||||
AD_PATH = "188274\AD.pdf"
|
||||
CD_PATH = "188274\СD.pdf"
|
||||
AD_PATH = r"188274\AD.pdf"
|
||||
CD_PATH = r"188274\СD.pdf"
|
||||
|
||||
ad_md = pymupdf4llm.to_markdown(AD_PATH)
|
||||
cd_md = pymupdf4llm.to_markdown(CD_PATH)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
import requests
|
||||
@@ -206,7 +206,7 @@ def make_debug_data(
|
||||
) -> dict:
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
@@ -181,7 +181,7 @@ def make_debug_data(
|
||||
):
|
||||
choice = {}
|
||||
|
||||
if "choices" in data and data["choices"]:
|
||||
if data.get("choices"):
|
||||
choice = data["choices"][0]
|
||||
|
||||
message = choice.get("message", {})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
ROOT_DIR = SCRIPT_DIR
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf # PyMuPDF
|
||||
|
||||
try:
|
||||
@@ -7,7 +8,7 @@ except ImportError:
|
||||
MarkItDown = None
|
||||
|
||||
|
||||
AD_PATH = Path("154115\AD.pdf")
|
||||
AD_PATH = Path(r"154115\AD.pdf")
|
||||
OUT_DIR = Path("ad_extraction_outputs3")
|
||||
OUT_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from statistics import mean, median
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from statistics import mean, median
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
@@ -17,7 +17,7 @@ SERVICE_SOURCE_ROOT = ROOT.parents[1] / "service" / "src" / "main"
|
||||
if str(SERVICE_SOURCE_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(SERVICE_SOURCE_ROOT))
|
||||
|
||||
from inse.authors.institution_membership_query import ( # noqa: E402
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_institution_membership_query,
|
||||
current_affiliation_year_cutoff,
|
||||
)
|
||||
@@ -852,9 +852,7 @@ def validate(result: dict[str, Any]) -> list[str]:
|
||||
if score is None:
|
||||
errors.append("basic_research_score_missing")
|
||||
elif score_is_usable:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
elif quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
if quadrant == "pure_basic" and not 0 <= score <= 30 or quadrant == "use_inspired_basic" and not 25 <= score <= 45:
|
||||
errors.append("basic_research_quadrant_score_mismatch")
|
||||
if quadrant not in {"pure_basic", "use_inspired_basic"}:
|
||||
errors.append("basic_research_quadrant_mismatch")
|
||||
|
||||
@@ -26,12 +26,12 @@ import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
DEFAULT_AUTHOR_ID = "A5034365278"
|
||||
DEFAULT_WORK_YEAR_GTE = 1950
|
||||
SOURCE_INDEX = "openalex-works*"
|
||||
|
||||
@@ -373,8 +373,8 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
|
||||
|
||||
def safe_rate(
|
||||
numerator: int | float,
|
||||
denominator: int | float,
|
||||
numerator: float,
|
||||
denominator: float,
|
||||
) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
|
||||
+1
-2
@@ -13,7 +13,6 @@ from typing import Any
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PROMPT_FILE = ROOT.parent / "prompt_frascati_hard_ranges_v2.txt"
|
||||
CONSENSUS_FILE = ROOT / "consensus_reference.json"
|
||||
@@ -282,7 +281,7 @@ def interval_distance(value: float, minimum: float, maximum: float) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def safe_rate(numerator: int | float, denominator: int | float) -> float | None:
|
||||
def safe_rate(numerator: float, denominator: float) -> float | None:
|
||||
if not denominator:
|
||||
return None
|
||||
return numerator / denominator
|
||||
|
||||
+2
-2
@@ -3,13 +3,13 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
from collections import Counter
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
ES_BASE_URL = "https://project.nes.uni-due.de/elastic"
|
||||
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from ollama import Client
|
||||
|
||||
|
||||
ENDPOINT = os.environ.get("OLLAMA_HOST", "https://project.nes.uni-due.de/llm2/")
|
||||
MODEL = os.environ.get("OLLAMA_MODEL", "gemma4:e4b-it-bf16")
|
||||
DATA_FOLDER = "data"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5047117780"]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import requests, json
|
||||
import json
|
||||
|
||||
import helpers
|
||||
import requests
|
||||
|
||||
AUTHOR_OPEN_ALEXID = helpers.get_all_author_ids_from_specific_university("University of Duisburg-Essen")
|
||||
#AUTHOR_OPEN_ALEXID = ["A5093075883", "A5047117780", "A5007170803"]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://project.nes.uni-due.de/elastic")
|
||||
|
||||
@@ -2,8 +2,8 @@ import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import time
|
||||
|
||||
from openai import OpenAI, APIConnectionError
|
||||
import helpers
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
BATCH_SIZE = 6
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
from typing import Any, Iterator
|
||||
from elasticsearch import Elasticsearch
|
||||
from collections import defaultdict
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from elasticsearch import NotFoundError
|
||||
from typing import Any
|
||||
|
||||
from elasticsearch import Elasticsearch, NotFoundError
|
||||
|
||||
# elasticseach library required. Here used elasticsearch==8.0.0
|
||||
# estimated execution time: 3-5 Minutes
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
from time import time
|
||||
|
||||
from llm_classify_news import call, parse_label, parse_persons
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Baut aus den JSON-Dateien in data2/ eine eigenstaendige viewer.html.
|
||||
|
||||
@@ -8,8 +7,8 @@ mit Vor/Zurueck durch die News blaettern. Oben stehen _id, llm_label und
|
||||
llm_persons, darunter der full_content als reiner Text (kein Parsing).
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "validation_data"
|
||||
OUTPUT_FILE = "viewer.html"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INDEX_URL = f"{INSE_URL}/aktuell"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
import json
|
||||
import os
|
||||
|
||||
DATA_FOLDER = "data2"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
result_files = [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib.parse import quote
|
||||
|
||||
INSE_URL = "https://inse.nes.uni-due.de/elastic"
|
||||
INSE_API_KEY = "bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw=="
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import requests
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/"
|
||||
LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import argparse
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
import elastic.client as es_client
|
||||
import llm.client as llm_client
|
||||
import json
|
||||
import argparse
|
||||
import time
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
|
||||
def print_pretty_json(data):
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
@@ -14,6 +14,7 @@ project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
@@ -311,7 +312,7 @@ async def evaluate():
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
|
||||
@@ -4,15 +4,14 @@ Professional evaluation pipeline to benchmark different Sentence Transformer mod
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
@@ -30,8 +29,8 @@ API_KEY = settings.elasticsearch_api_key
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn import metrics
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
@@ -161,9 +160,9 @@ def evaluate_model(model_name, data, output_dir):
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print(f"\n==================================================")
|
||||
print("\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print(f"==================================================")
|
||||
print("==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
map_news_topics.py — Map news keywords to OpenAlex topics.
|
||||
|
||||
@@ -37,7 +37,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
@@ -121,7 +121,7 @@ async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str,
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(timezone.utc).isoformat()
|
||||
built_at = datetime.now(UTC).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await base.check_backend(args.api_base_url)
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
from scrapy import signals
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import is_item, ItemAdapter
|
||||
from scrapy import signals
|
||||
|
||||
|
||||
class AktuellSpiderMiddleware:
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class AktuellPipeline:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import scrapy
|
||||
|
||||
|
||||
class LinksCrawler(scrapy.Spider):
|
||||
name = "aktuell-links"
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import scrapy
|
||||
import json
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
import os
|
||||
|
||||
import scrapy
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
|
||||
|
||||
class MetaDataCrawler(scrapy.Spider):
|
||||
name = "aktuell-metadata"
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
import time
|
||||
from random import randint
|
||||
|
||||
from elasticsearch import Elasticsearch
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
|
||||
es = Elasticsearch()
|
||||
|
||||
@@ -32,7 +33,7 @@ def getLinks(link, driver):
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
|
||||
if elem == "Zurück zum Gesamtüberblick":
|
||||
break
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
break
|
||||
|
||||
# get date
|
||||
@@ -45,7 +46,7 @@ def getLinks(link, driver):
|
||||
link = ""
|
||||
try:
|
||||
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
continue
|
||||
|
||||
links.append(link)
|
||||
@@ -67,17 +68,17 @@ def getData(driver, link, date, date_year, date_num):
|
||||
subtitle = ""
|
||||
try:
|
||||
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
maintitle = ""
|
||||
try:
|
||||
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
redaktion = ""
|
||||
try:
|
||||
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
author = ""
|
||||
if redaktion != "":
|
||||
@@ -86,7 +87,7 @@ def getData(driver, link, date, date_year, date_num):
|
||||
main_content = ""
|
||||
try:
|
||||
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
|
||||
except NoSuchElementException as nsee:
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
full_content = main_content
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
build_patents_openalex_keywords.py — Build IPC/CPC → OpenAlex topic/keyword matches.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
evaluate_keyword_patent_search.py — Systematic evaluation for keyword → patent search.
|
||||
|
||||
@@ -23,14 +23,14 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent.parent / "src" / "main"))
|
||||
|
||||
from inse.patents.keywords.eval_metrics import ( # noqa: E402
|
||||
from inse.patents.keywords.eval_metrics import (
|
||||
analyze_family_duplicates_in_top_k,
|
||||
average_precision,
|
||||
ipc_prefix_hit_rate,
|
||||
@@ -43,13 +43,13 @@ from inse.patents.keywords.eval_metrics import ( # noqa: E402
|
||||
recall_at_k,
|
||||
unique_family_precision_at_k,
|
||||
)
|
||||
from inse.patents.keywords.logic import ( # noqa: E402
|
||||
from inse.patents.keywords.logic import (
|
||||
_DEFAULT_SCORE_WEIGHTS,
|
||||
_MAX_PATENTS,
|
||||
_compute_final_score,
|
||||
get_patents_by_keywords,
|
||||
)
|
||||
from inse.patents.keywords.model import ( # noqa: E402
|
||||
from inse.patents.keywords.model import (
|
||||
KeywordPatentMatch,
|
||||
KeywordPatentSearchDiagnostics,
|
||||
KeywordPatentSearchItem,
|
||||
@@ -721,9 +721,7 @@ def _load_prior_candidate_grades(
|
||||
if existing is None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
continue
|
||||
if existing.get("grade") is None and grade is not None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
elif existing.get("grade") is None:
|
||||
if existing.get("grade") is None and grade is not None or existing.get("grade") is None:
|
||||
bucket[patent_id] = dict(candidate)
|
||||
return by_case
|
||||
|
||||
@@ -884,7 +882,7 @@ async def cmd_bootstrap(args: argparse.Namespace) -> int:
|
||||
}
|
||||
)
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
labeling_path = out_dir / f"labeling_{stamp}.json"
|
||||
report_path = out_dir / f"bootstrap_report_{stamp}.json"
|
||||
|
||||
@@ -979,7 +977,7 @@ async def cmd_eval(args: argparse.Namespace) -> int:
|
||||
if presentation
|
||||
else _aggregate(case_reports, ks)
|
||||
)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
report_name = "presentation_eval_report" if presentation else "eval_report"
|
||||
report_path = Path(args.out_dir) / f"{report_name}_{stamp}.json"
|
||||
_write_json(
|
||||
@@ -1071,7 +1069,7 @@ async def cmd_ablation(args: argparse.Namespace) -> int:
|
||||
f"P@10={p10}"
|
||||
)
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
||||
report_path = Path(args.out_dir) / f"ablation_report_{stamp}.json"
|
||||
_write_json(
|
||||
report_path,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
|
||||
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.common.alert import Alert
|
||||
from random import randint
|
||||
import time
|
||||
import pandas as pd
|
||||
import json
|
||||
from datetime import datetime
|
||||
import sys
|
||||
import os
|
||||
import math
|
||||
import requests
|
||||
import hashlib
|
||||
import argparse
|
||||
import logging
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
map_project_topics.py — Map project keywords to OpenAlex topics.
|
||||
|
||||
@@ -52,9 +52,10 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
@@ -396,7 +397,7 @@ async def bulk_index(index: str, cluster: str, documents: list[tuple[str, dict]]
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> None:
|
||||
built_at = datetime.now(timezone.utc).isoformat()
|
||||
built_at = datetime.now(UTC).isoformat()
|
||||
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
|
||||
|
||||
await check_backend(args.api_base_url)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
test_keywords_matching.py
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Download the sentence-transformers model to the default cache directory
|
||||
so it is available for local runs or testing.
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Script to fetch all topics from 'openalex-topics',
|
||||
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
|
||||
and push them to the 'topicvectors' index with multi-vector mapping.
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -26,7 +27,6 @@ API_KEY = settings.elasticsearch_api_key
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
|
||||
# Import sentence-transformers
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
@@ -9,14 +8,14 @@ from inse.auth.model import UserRole, normalize_roles
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
openalex_institution_id: Optional[str] = None
|
||||
openalex_institution_id: str | None = None
|
||||
|
||||
|
||||
class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
roles: List[UserRole]
|
||||
roles: list[UserRole]
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
@@ -27,7 +26,7 @@ class AccountProfile(BaseModel):
|
||||
|
||||
|
||||
class AccountPage(BaseModel):
|
||||
items: List[AccountProfile]
|
||||
items: list[AccountProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
@@ -43,10 +42,10 @@ class CreateAccountRequest(BaseModel):
|
||||
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
|
||||
roles: list[UserRole] = Field(default_factory=lambda: [UserRole.USER])
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
openalex_person_id: str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
@@ -62,14 +61,14 @@ class UpdateAccountRequest(BaseModel):
|
||||
values = {**values, "roles": [values["role"]]}
|
||||
return values
|
||||
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
roles: Optional[List[UserRole]] = None
|
||||
organization_id: Optional[uuid.UUID] = None
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
activated: Optional[bool] = None
|
||||
email: str | None = Field(default=None, min_length=3)
|
||||
name: str | None = Field(default=None, min_length=1)
|
||||
roles: list[UserRole] | None = None
|
||||
organization_id: uuid.UUID | None = None
|
||||
password: str | None = Field(default=None, min_length=8)
|
||||
openalex_person_id: str | None = None
|
||||
deleted: bool | None = None
|
||||
activated: bool | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _normalize_roles(self):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import uuid
|
||||
from typing import Annotated, Optional
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query, Response, status
|
||||
|
||||
@@ -40,8 +40,8 @@ async def list_accounts(
|
||||
page: Annotated[int, Query(ge=0)] = 0,
|
||||
page_size: Annotated[int, Query(ge=1, le=100)] = 10,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
search: Annotated[Optional[str], Query()] = None,
|
||||
organization_id: Annotated[Optional[uuid.UUID], Query()] = None,
|
||||
search: Annotated[str | None, Query()] = None,
|
||||
organization_id: Annotated[uuid.UUID | None, Query()] = None,
|
||||
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountPage:
|
||||
return service.list_accounts(
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
@@ -84,7 +83,7 @@ def _ensure_account_in_editor_scope(account: Account, token: AccessTokenMetadata
|
||||
def _ensure_email_available(
|
||||
session: Session,
|
||||
email: str,
|
||||
excluded_account_id: Optional[uuid.UUID] = None,
|
||||
excluded_account_id: uuid.UUID | None = None,
|
||||
) -> None:
|
||||
normalized_email = email.lower().strip()
|
||||
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
|
||||
@@ -115,9 +114,9 @@ def list_accounts(
|
||||
access_token: AccessTokenMetadata,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
offset: int | None = None,
|
||||
search: str | None = None,
|
||||
organization_id: uuid.UUID | None = None,
|
||||
) -> AccountPage:
|
||||
if access_token.effective_role not in {
|
||||
UserRole.SUPER_ADMIN,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel, model_validator
|
||||
from sqlalchemy import JSON, Column, UniqueConstraint
|
||||
@@ -24,8 +23,8 @@ ROLE_PRIORITY = {
|
||||
|
||||
|
||||
def normalize_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
) -> List[UserRole]:
|
||||
roles: list[UserRole] | list[str] | UserRole | str | None,
|
||||
) -> list[UserRole]:
|
||||
if roles is None:
|
||||
return [UserRole.USER]
|
||||
if isinstance(roles, (str, UserRole)):
|
||||
@@ -43,7 +42,7 @@ def normalize_roles(
|
||||
|
||||
|
||||
def effective_role_for_roles(
|
||||
roles: List[UserRole] | List[str] | UserRole | str | None,
|
||||
roles: list[UserRole] | list[str] | UserRole | str | None,
|
||||
) -> UserRole:
|
||||
return normalize_roles(roles)[0]
|
||||
|
||||
@@ -86,7 +85,7 @@ class Organization(Durable, table=True):
|
||||
description="The OpenAlex ID of the institution associated with the organization.",
|
||||
)
|
||||
|
||||
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||
accounts: list["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
@@ -141,7 +140,7 @@ class Account(Durable, table=True):
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
roles: List[UserRole] = Field(
|
||||
roles: list[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
|
||||
description="The roles this account holds within its organization.",
|
||||
@@ -249,7 +248,7 @@ class AccessTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
effective_roles: list[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
@@ -300,7 +299,7 @@ class RefreshTokenMetadata(BaseTokenData):
|
||||
default=UserRole.USER,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_roles: List[UserRole] = Field(
|
||||
effective_roles: list[UserRole] = Field(
|
||||
default_factory=lambda: [UserRole.USER],
|
||||
description="The roles this access token grants within its organization.",
|
||||
)
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
from fastapi import APIRouter, Body, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import (
|
||||
AccessResponse,
|
||||
AccessToken,
|
||||
@@ -18,6 +15,8 @@ from inse.auth.model import (
|
||||
OtkResponse,
|
||||
RefreshTokenMetadata,
|
||||
)
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -205,3 +204,30 @@ async def change_password(
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/can-fetch-gdpr-relevant-data",
|
||||
summary="Check if user can fetch GDPR-relevant data",
|
||||
description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.",
|
||||
operation_id="canFetchGdprRelevantData",
|
||||
)
|
||||
async def can_fetch_gdpr_relevant_data(
|
||||
access_token: Annotated[
|
||||
AccessTokenMetadata,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
raw_oa_author_id: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex author ID to check access for"),
|
||||
] = None,
|
||||
raw_oa_institution_id: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex institution ID to check access for"),
|
||||
] = None,
|
||||
) -> bool:
|
||||
return await auth_service.can_fetch_gdpr_relevant_data(
|
||||
access_token=access_token,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import json
|
||||
import logging
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Annotated, Any, Dict, Optional
|
||||
from typing import Annotated, Any
|
||||
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
@@ -31,6 +31,7 @@ from inse.auth.model import (
|
||||
effective_role_for_roles,
|
||||
normalize_roles,
|
||||
)
|
||||
from inse.authors.v2 import service as authors_service
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
|
||||
@@ -95,7 +96,7 @@ def create_predefined_accounts(session: Session, file_path: str):
|
||||
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
data: Dict[str, Any] = json.loads(file.read())
|
||||
data: dict[str, Any] = json.loads(file.read())
|
||||
for organization_data in data.get("organizations", []):
|
||||
organization_id = organization_data.get("id")
|
||||
if organization_id is not None:
|
||||
@@ -215,7 +216,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.deleted == False,
|
||||
)
|
||||
).first()
|
||||
|
||||
@@ -254,7 +255,7 @@ def request_otk(session: Session, email: str, password: str):
|
||||
)
|
||||
).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
)
|
||||
|
||||
@@ -293,19 +294,19 @@ def request_otk(session: Session, email: str, password: str):
|
||||
return OtkResponse(status="success", account_id=account.id)
|
||||
|
||||
|
||||
def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
def request_password_reset(session: Session, email: str) -> dict[str, Any]:
|
||||
"""Requests a one-time password reset link for the given email address.
|
||||
|
||||
For security reasons, this function always returns a successful response and
|
||||
does not reveal whether the email address belongs to an active account.
|
||||
"""
|
||||
email = email.lower().strip()
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.deleted == False,
|
||||
)
|
||||
).first()
|
||||
|
||||
@@ -328,9 +329,7 @@ def request_password_reset(session: Session, email: str) -> Dict[str, Any]:
|
||||
if secret.request_window_started_at is not None:
|
||||
window_started_at = secret.request_window_started_at
|
||||
if getattr(window_started_at, "tzinfo", None) is None:
|
||||
window_started_at = window_started_at.replace(
|
||||
tzinfo=datetime.timezone.utc
|
||||
)
|
||||
window_started_at = window_started_at.replace(tzinfo=datetime.UTC)
|
||||
|
||||
window_ends_at = window_started_at + datetime.timedelta(
|
||||
minutes=PASSWORD_RESET_RATE_LIMIT_WINDOW_MINUTES
|
||||
@@ -435,7 +434,7 @@ def reset_password(
|
||||
session: Session,
|
||||
reset_token: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
) -> dict[str, str]:
|
||||
"""Resets an account password using a one-time password reset token.
|
||||
|
||||
Args:
|
||||
@@ -449,7 +448,7 @@ def reset_password(
|
||||
Returns:
|
||||
Dict[str, str]: A status response.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
reset_token_hash = _hash_reset_token(reset_token.strip())
|
||||
|
||||
secret = session.exec(
|
||||
@@ -467,7 +466,7 @@ def reset_password(
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
|
||||
|
||||
if secret_expires <= now:
|
||||
session.delete(secret)
|
||||
@@ -515,7 +514,7 @@ def login(
|
||||
Returns:
|
||||
LoginResponse: The response containing the ID token issued upon successful login.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(
|
||||
@@ -536,7 +535,7 @@ def login(
|
||||
|
||||
secret_expires = secret.expires_at
|
||||
if getattr(secret_expires, "tzinfo", None) is None:
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.timezone.utc)
|
||||
secret_expires = secret_expires.replace(tzinfo=datetime.UTC)
|
||||
|
||||
if secret_expires <= now:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
@@ -611,7 +610,7 @@ def _get_current_user_access_token_payload(
|
||||
real_account_id=uuid.UUID(access_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
effective_account_id=uuid.UUID(access_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
access_token_payload["exp"], tz=datetime.timezone.utc
|
||||
access_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=access_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
@@ -657,7 +656,7 @@ def _get_current_user_refresh_token_payload(
|
||||
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
refresh_token_payload["exp"], tz=datetime.timezone.utc
|
||||
refresh_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
@@ -708,7 +707,7 @@ def _get_current_user_id_token_payload(
|
||||
return IdTokenMetadata(
|
||||
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
id_token_payload["exp"], tz=datetime.timezone.utc
|
||||
id_token_payload["exp"], tz=datetime.UTC
|
||||
),
|
||||
epoch=id_token_payload[EPOCH_KEY],
|
||||
)
|
||||
@@ -784,9 +783,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
|
||||
return account.organization_id
|
||||
|
||||
|
||||
def _get_account_institution_id(
|
||||
session: Session, account_id: uuid.UUID
|
||||
) -> Optional[str]:
|
||||
def _get_account_institution_id(session: Session, account_id: uuid.UUID) -> str | None:
|
||||
"""Retrieves the OpenAlex institution ID for the given account ID.
|
||||
|
||||
Args:
|
||||
@@ -872,7 +869,7 @@ def get_access_token(
|
||||
session: Session,
|
||||
id_token: IdTokenMetadata,
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: Optional[uuid.UUID] = None,
|
||||
effective_account_id: uuid.UUID | None = None,
|
||||
) -> AccessResponse:
|
||||
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
@@ -1054,7 +1051,7 @@ def _build_id_token(
|
||||
Returns:
|
||||
IdToken: The generated ID token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=ID_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
payload = {
|
||||
@@ -1082,7 +1079,7 @@ def _set_refresh_token(
|
||||
effective_organization_id: uuid.UUID,
|
||||
epoch: int,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
effective_institution_id: Optional[str] = None,
|
||||
effective_institution_id: str | None = None,
|
||||
) -> RefreshTokenMetadata:
|
||||
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1098,7 +1095,7 @@ def _set_refresh_token(
|
||||
Returns:
|
||||
RefreshTokenMetadata: The generated refresh token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
@@ -1137,7 +1134,7 @@ def _build_access_token(
|
||||
epoch: int,
|
||||
user_fingerprint_hash: str,
|
||||
effective_roles: list[UserRole] | None = None,
|
||||
effective_institution_id: Optional[str] = None,
|
||||
effective_institution_id: str | None = None,
|
||||
) -> AccessToken:
|
||||
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
|
||||
|
||||
@@ -1153,7 +1150,7 @@ def _build_access_token(
|
||||
Returns:
|
||||
AccessToken: The generated access token object.
|
||||
"""
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
|
||||
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
)
|
||||
effective_roles = normalize_roles(effective_roles or effective_role)
|
||||
@@ -1189,7 +1186,7 @@ def _build_access_token(
|
||||
|
||||
|
||||
def _build_token(
|
||||
payload: Dict[str, Any],
|
||||
payload: dict[str, Any],
|
||||
expiration_datetime: datetime.datetime,
|
||||
token_type: TokenType,
|
||||
) -> str:
|
||||
@@ -1203,7 +1200,7 @@ def _build_token(
|
||||
Returns:
|
||||
str: The encoded JWT token.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
payload.update(
|
||||
{
|
||||
"exp": expiration_datetime,
|
||||
@@ -1219,7 +1216,7 @@ def _build_token(
|
||||
return token
|
||||
|
||||
|
||||
def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
|
||||
def _verify_id_token(raw_id_token: str, session: Session) -> dict[str, Any]:
|
||||
"""Verifies the provided ID token and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1239,7 +1236,7 @@ def _verify_id_token(raw_id_token: str, session: Session) -> Dict[str, Any]:
|
||||
return payload
|
||||
|
||||
|
||||
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> Dict[str, Any]:
|
||||
def _verify_refresh_token(raw_refresh_token: str, session: Session) -> dict[str, Any]:
|
||||
"""Verifies the provided refresh token and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1263,7 +1260,7 @@ def _verify_access_token_fp(
|
||||
secure_fgp: str,
|
||||
raw_access_token: str,
|
||||
session: Session,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
"""Verifies the provided accesstoken against the fingerprint stored in the specified cookie and returns the decoded payload if valid.
|
||||
|
||||
Args:
|
||||
@@ -1381,7 +1378,7 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
return account
|
||||
|
||||
|
||||
def logout(session: Session, access_token: AccessTokenMetadata) -> Dict[str, str]:
|
||||
def logout(session: Session, access_token: AccessTokenMetadata) -> dict[str, str]:
|
||||
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
|
||||
|
||||
Args:
|
||||
@@ -1408,7 +1405,7 @@ def change_password(
|
||||
access_token: AccessTokenMetadata,
|
||||
current_password: str,
|
||||
new_password: str,
|
||||
) -> Dict[str, str]:
|
||||
) -> dict[str, str]:
|
||||
"""Change the password for the user associated with the provided access token.
|
||||
|
||||
Args:
|
||||
@@ -1455,3 +1452,69 @@ def change_password(
|
||||
logger.info("Password changed successfully for account %s", account.id)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def can_fetch_gdpr_relevant_data(
|
||||
access_token: AccessTokenMetadata,
|
||||
raw_oa_author_id: str | None = None,
|
||||
raw_oa_institution_id: str | None = None,
|
||||
) -> bool:
|
||||
"""Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID.
|
||||
|
||||
Args:
|
||||
access_token (AccessTokenMetadata): The access token for the user.
|
||||
raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None.
|
||||
raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None.
|
||||
|
||||
Returns:
|
||||
bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise.
|
||||
"""
|
||||
|
||||
logger.debug(
|
||||
"Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s",
|
||||
access_token.effective_institution_id,
|
||||
raw_oa_author_id,
|
||||
raw_oa_institution_id,
|
||||
)
|
||||
|
||||
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||
logger.debug("No OpenAlex author ID or institution ID provided")
|
||||
return False
|
||||
|
||||
effective_institution_id = access_token.effective_institution_id
|
||||
# Current user does not belong to any institution
|
||||
if not effective_institution_id:
|
||||
logger.debug(
|
||||
"Current user does not belong to any institution, cannot fetch GDPR-relevant data"
|
||||
)
|
||||
return False
|
||||
|
||||
# Current user belongs to an institution, but the request is for a different institution
|
||||
if (
|
||||
raw_oa_institution_id
|
||||
and effective_institution_id
|
||||
and raw_oa_institution_id != effective_institution_id
|
||||
):
|
||||
logger.debug(
|
||||
"Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data",
|
||||
effective_institution_id,
|
||||
raw_oa_institution_id,
|
||||
)
|
||||
return False
|
||||
|
||||
# Current user belongs to an institution, but request is for author not belonging to that institution
|
||||
if raw_oa_author_id:
|
||||
author_belongs_to_institution = (
|
||||
await authors_service.author_currently_belongs_to_institution(
|
||||
raw_oa_author_id or "", effective_institution_id
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
"Author %s belongs to institution %s: %s",
|
||||
raw_oa_author_id,
|
||||
effective_institution_id,
|
||||
author_belongs_to_institution,
|
||||
)
|
||||
return author_belongs_to_institution
|
||||
|
||||
return True
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
import inse.config as config_module
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
|
||||
from fastapi import Response, HTTPException
|
||||
import datetime as _dt
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, Response
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
|
||||
import inse.config as config_module
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import (
|
||||
AccessToken,
|
||||
AccessTokenMetadata,
|
||||
Account,
|
||||
IdTokenMetadata,
|
||||
Organization,
|
||||
RefreshTokenMetadata,
|
||||
Secret,
|
||||
SecretPurpose,
|
||||
AccessToken,
|
||||
IdTokenMetadata,
|
||||
AccessTokenMetadata,
|
||||
RefreshTokenMetadata,
|
||||
UserRole,
|
||||
)
|
||||
|
||||
@@ -188,7 +186,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||
refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY]
|
||||
),
|
||||
expires_at=_dt.datetime.fromtimestamp(
|
||||
refresh_payload["exp"], tz=_dt.timezone.utc
|
||||
refresh_payload["exp"], tz=_dt.UTC
|
||||
),
|
||||
epoch=refresh_payload[auth_service.EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]),
|
||||
@@ -346,7 +344,7 @@ def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
expired_at = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=10)
|
||||
expired_at = _dt.datetime.now(_dt.UTC) - timedelta(minutes=10)
|
||||
secret = Secret(
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.LOGIN_OTK,
|
||||
@@ -593,7 +591,7 @@ def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||
past = _dt.datetime.now(_dt.UTC) - timedelta(minutes=5)
|
||||
access_fingerprint_hash = auth_service._set_access_fp_cookie(response)
|
||||
payload = {
|
||||
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||
@@ -624,7 +622,7 @@ def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||
with pytest.raises(ValueError):
|
||||
auth_service._build_token(
|
||||
payload={},
|
||||
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||
expiration_datetime=_dt.datetime.now(_dt.UTC),
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
config_module.settings.token_hmac_key = saved
|
||||
@@ -715,7 +713,7 @@ def test_reset_password_changes_password_and_increments_epoch(in_memory_session)
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
@@ -753,7 +751,7 @@ def test_reset_password_rejects_reused_token(in_memory_session):
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) + timedelta(minutes=5),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
@@ -792,7 +790,7 @@ def test_reset_password_rejects_expired_token(in_memory_session):
|
||||
account_id=acc.id,
|
||||
purpose=SecretPurpose.PASSWORD_RESET,
|
||||
secret_value=auth_service._hash_reset_token(reset_token),
|
||||
expires_at=_dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=1),
|
||||
expires_at=_dt.datetime.now(_dt.UTC) - timedelta(minutes=1),
|
||||
)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
AFFILIATION_LOOKBACK_YEARS = 2
|
||||
OPENALEX_ID_PREFIX = "https://openalex.org/"
|
||||
AffiliationYearMode = Literal["all", "in", "from"]
|
||||
AffiliationYearMode = Literal["all", "in", "from", "between"]
|
||||
|
||||
|
||||
def current_affiliation_year_cutoff(
|
||||
@@ -21,7 +20,7 @@ def current_affiliation_year_cutoff(
|
||||
when needed.
|
||||
"""
|
||||
|
||||
current_time = reference_time or datetime.now(timezone.utc)
|
||||
current_time = reference_time or datetime.now(UTC)
|
||||
return current_time.year - AFFILIATION_LOOKBACK_YEARS
|
||||
|
||||
|
||||
@@ -29,17 +28,20 @@ def build_institution_affiliation_query(
|
||||
institution_id: str,
|
||||
year_mode: AffiliationYearMode = "all",
|
||||
year: int | None = None,
|
||||
year_to: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build an affiliation query for an institution and optional year rule.
|
||||
|
||||
``all`` accepts an affiliation from any year and requires ``year=None``.
|
||||
``in`` requires an affiliation in exactly ``year``.
|
||||
``from`` requires an affiliation in ``year`` or any later year.
|
||||
``between`` requires an affiliation between ``year`` and ``year_to``,
|
||||
including both boundary years.
|
||||
Institution IDs are normalized to their full OpenAlex URL.
|
||||
"""
|
||||
|
||||
normalized_institution_id = _normalize_openalex_id(institution_id)
|
||||
_validate_year_mode(year_mode, year)
|
||||
_validate_year_mode(year_mode, year, year_to)
|
||||
|
||||
affiliation_filters: list[dict[str, Any]] = [
|
||||
{
|
||||
@@ -56,6 +58,17 @@ def build_institution_affiliation_query(
|
||||
affiliation_filters.append(
|
||||
{"range": {"affiliations.years": {"gte": year}}}
|
||||
)
|
||||
elif year_mode == "between":
|
||||
affiliation_filters.append(
|
||||
{
|
||||
"range": {
|
||||
"affiliations.years": {
|
||||
"gte": year,
|
||||
"lte": year_to,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"nested": {
|
||||
@@ -69,6 +82,7 @@ def build_institution_membership_query(
|
||||
institution_id: str,
|
||||
year_mode: AffiliationYearMode = "all",
|
||||
year: int | None = None,
|
||||
year_to: int | None = None,
|
||||
author_ids: Iterable[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build an institution membership query for the selected year mode.
|
||||
@@ -83,10 +97,11 @@ def build_institution_membership_query(
|
||||
last-known institution IDs are available.
|
||||
|
||||
``in`` deliberately excludes condition 2 because an exact year requires
|
||||
explicit affiliation evidence for that year. When ``author_ids`` are
|
||||
supplied, the query is restricted to those authors in the same
|
||||
Elasticsearch request. Empty ``author_ids`` produce ``match_none``.
|
||||
Institution and author IDs are normalized to full OpenAlex URLs.
|
||||
explicit affiliation evidence for that year. ``between`` applies the same
|
||||
rule to its bounded period. When ``author_ids`` are supplied, the query is
|
||||
restricted to those authors in the same Elasticsearch request. Empty
|
||||
``author_ids`` produce ``match_none``. Institution and author IDs are
|
||||
normalized to full OpenAlex URLs.
|
||||
"""
|
||||
|
||||
normalized_institution_id = _normalize_openalex_id(institution_id)
|
||||
@@ -94,6 +109,7 @@ def build_institution_membership_query(
|
||||
normalized_institution_id,
|
||||
year_mode=year_mode,
|
||||
year=year,
|
||||
year_to=year_to,
|
||||
)
|
||||
|
||||
author_filters: list[dict[str, Any]] = []
|
||||
@@ -158,7 +174,7 @@ def build_institution_membership_query(
|
||||
}
|
||||
},
|
||||
]
|
||||
if year_mode != "in":
|
||||
if year_mode in {"all", "from"}:
|
||||
# Last-known is the fallback only when affiliation IDs are unavailable.
|
||||
membership_branches.insert(
|
||||
1,
|
||||
@@ -213,15 +229,28 @@ def build_active_institution_membership_query(
|
||||
def _validate_year_mode(
|
||||
year_mode: AffiliationYearMode,
|
||||
year: int | None,
|
||||
year_to: int | None,
|
||||
) -> None:
|
||||
if year_mode not in {"all", "in", "from"}:
|
||||
if year_mode not in {"all", "in", "from", "between"}:
|
||||
raise ValueError(f"Unsupported affiliation year mode: {year_mode}")
|
||||
if year_mode == "all":
|
||||
if year is not None:
|
||||
raise ValueError("year must be omitted when year_mode is 'all'")
|
||||
if year is not None or year_to is not None:
|
||||
raise ValueError(
|
||||
"year and year_to must be omitted when year_mode is 'all'"
|
||||
)
|
||||
return
|
||||
if isinstance(year, bool) or not isinstance(year, int):
|
||||
raise ValueError(f"year is required when year_mode is '{year_mode}'")
|
||||
if year_mode != "between":
|
||||
if year_to is not None:
|
||||
raise ValueError(
|
||||
f"year_to must be omitted when year_mode is '{year_mode}'"
|
||||
)
|
||||
return
|
||||
if isinstance(year_to, bool) or not isinstance(year_to, int):
|
||||
raise ValueError("year_to is required when year_mode is 'between'")
|
||||
if year > year_to:
|
||||
raise ValueError("year must be less than or equal to year_to")
|
||||
|
||||
|
||||
def _normalize_openalex_id(raw_id: str) -> str:
|
||||
|
||||
@@ -65,7 +65,7 @@ def mark_collaboration_graph_job_completed(
|
||||
return
|
||||
job.status = CollaborationGraphStatus.COMPLETED
|
||||
job.set_result(result)
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
job.updated_at = datetime.datetime.now(datetime.UTC)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
@@ -86,7 +86,7 @@ def mark_collaboration_graph_job_failed(
|
||||
return
|
||||
job.status = CollaborationGraphStatus.FAILED
|
||||
job.error_message = error_message
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
job.updated_at = datetime.datetime.now(datetime.UTC)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
@@ -103,7 +103,7 @@ def cleanup_old_collaboration_graph_jobs(
|
||||
Returns:
|
||||
int: The number of stale jobs that were cleaned up.
|
||||
"""
|
||||
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
|
||||
cutoff_time = datetime.datetime.now(datetime.UTC) - max_age
|
||||
statement = select(CollaborationGraphJob).where(
|
||||
CollaborationGraphJob.created_at < cutoff_time
|
||||
)
|
||||
|
||||
@@ -142,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
|
||||
|
||||
return await search_authors(
|
||||
page=0,
|
||||
size=len(author_ids) if len(author_ids) <10000 else 10000,
|
||||
size=min(10000, len(author_ids)),
|
||||
query={"terms": {"id": author_ids}},
|
||||
source=[
|
||||
"id",
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
Database tables and API schemas for the background job runner.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from enum import StrEnum
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import JSON, Column, Field, SQLModel
|
||||
@@ -23,13 +22,13 @@ class JobTriggeredBy(StrEnum):
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
return datetime.now(UTC).replace(tzinfo=None)
|
||||
|
||||
|
||||
class JobDefinition(SQLModel, table=True):
|
||||
__tablename__ = "background_job_definition"
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
name: str = Field(
|
||||
index=True, unique=True, description="Human-readable job name shown in the UI."
|
||||
)
|
||||
@@ -37,12 +36,12 @@ class JobDefinition(SQLModel, table=True):
|
||||
target_index: str = Field(
|
||||
default="", description="Elasticsearch index the job writes to (UI info)."
|
||||
)
|
||||
image: Optional[str] = Field(
|
||||
image: str | None = Field(
|
||||
default=None,
|
||||
description="Docker image to run. Null falls back to the configured "
|
||||
"background-jobs image.",
|
||||
)
|
||||
command: Optional[str] = Field(
|
||||
command: str | None = Field(
|
||||
default=None,
|
||||
description="Command passed to the image. Null uses the job name (for "
|
||||
"known jobs) or the image's default entrypoint.",
|
||||
@@ -52,14 +51,14 @@ class JobDefinition(SQLModel, table=True):
|
||||
sa_column=Column(JSON),
|
||||
description="Extra environment variables passed to the container.",
|
||||
)
|
||||
schedule: Optional[str] = Field(
|
||||
schedule: str | None = Field(
|
||||
default=None,
|
||||
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
|
||||
)
|
||||
enabled: bool = Field(
|
||||
default=True, description="Disabled definitions are never scheduled."
|
||||
)
|
||||
next_run_at: Optional[datetime] = Field(
|
||||
next_run_at: datetime | None = Field(
|
||||
default=None, description="Computed by the scheduler from the cron expression."
|
||||
)
|
||||
created_at: datetime = Field(default_factory=utcnow)
|
||||
@@ -68,19 +67,19 @@ class JobDefinition(SQLModel, table=True):
|
||||
class JobRun(SQLModel, table=True):
|
||||
__tablename__ = "background_job_run"
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
definition_id: int = Field(
|
||||
foreign_key="background_job_definition.id", index=True
|
||||
)
|
||||
container_id: Optional[str] = Field(default=None)
|
||||
container_id: str | None = Field(default=None)
|
||||
status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
|
||||
triggered_by: JobTriggeredBy = Field(
|
||||
description="Whether the scheduler or a superadmin started this run."
|
||||
)
|
||||
started_at: datetime = Field(default_factory=utcnow)
|
||||
finished_at: Optional[datetime] = Field(default=None)
|
||||
exit_code: Optional[int] = Field(default=None)
|
||||
logs: Optional[str] = Field(
|
||||
finished_at: datetime | None = Field(default=None)
|
||||
exit_code: int | None = Field(default=None)
|
||||
logs: str | None = Field(
|
||||
default=None,
|
||||
description="Captured stdout/stderr, filled in when the run finishes "
|
||||
"(the container itself is removed afterwards).",
|
||||
@@ -89,24 +88,24 @@ class JobRun(SQLModel, table=True):
|
||||
|
||||
class JobDefinitionCreateRequest(BaseModel):
|
||||
name: str
|
||||
image: Optional[str] = None
|
||||
command: Optional[str] = None
|
||||
image: str | None = None
|
||||
command: str | None = None
|
||||
env: dict[str, str] = {}
|
||||
description: str = ""
|
||||
target_index: str = ""
|
||||
schedule: Optional[str] = None
|
||||
schedule: str | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class JobDefinitionUpdateRequest(BaseModel):
|
||||
name: Optional[str] = None
|
||||
image: Optional[str] = None
|
||||
command: Optional[str] = None
|
||||
env: Optional[dict[str, str]] = None
|
||||
description: Optional[str] = None
|
||||
target_index: Optional[str] = None
|
||||
schedule: Optional[str] = None
|
||||
enabled: Optional[bool] = None
|
||||
name: str | None = None
|
||||
image: str | None = None
|
||||
command: str | None = None
|
||||
env: dict[str, str] | None = None
|
||||
description: str | None = None
|
||||
target_index: str | None = None
|
||||
schedule: str | None = None
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
class BackgroundJobTask(BaseModel):
|
||||
@@ -114,13 +113,13 @@ class BackgroundJobTask(BaseModel):
|
||||
name: str
|
||||
description: str
|
||||
target_index: str
|
||||
image: Optional[str]
|
||||
command: Optional[str]
|
||||
image: str | None
|
||||
command: str | None
|
||||
env: dict[str, str]
|
||||
schedule: Optional[str]
|
||||
schedule: str | None
|
||||
enabled: bool
|
||||
next_run_at: Optional[datetime]
|
||||
last_run: Optional[JobRun]
|
||||
next_run_at: datetime | None
|
||||
last_run: JobRun | None
|
||||
status: str
|
||||
|
||||
|
||||
|
||||
@@ -11,11 +11,11 @@ from .model import (
|
||||
AvailableImages,
|
||||
BackgroundJobTask,
|
||||
DockerHealth,
|
||||
RegistryHealth,
|
||||
JobDefinitionCreateRequest,
|
||||
JobDefinitionUpdateRequest,
|
||||
JobRun,
|
||||
JobRunLogs,
|
||||
RegistryHealth,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
|
||||
|
||||
@@ -8,7 +8,6 @@ import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from threading import RLock
|
||||
from typing import Optional
|
||||
|
||||
import docker
|
||||
import httpx
|
||||
@@ -28,7 +27,7 @@ settings = config.get_settings()
|
||||
|
||||
RUN_STATE_LOCK = RLock()
|
||||
|
||||
_client: Optional[docker.DockerClient] = None
|
||||
_client: docker.DockerClient | None = None
|
||||
|
||||
|
||||
def get_docker_client() -> docker.DockerClient:
|
||||
@@ -42,7 +41,7 @@ def docker_reachable() -> tuple[bool, str]:
|
||||
try:
|
||||
get_docker_client().ping()
|
||||
return True, "ok"
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
return False, str(error)
|
||||
|
||||
|
||||
@@ -59,7 +58,7 @@ def registry_reachable() -> tuple[bool, str]:
|
||||
if response.status_code == 401:
|
||||
return False, "authentication failed (401)"
|
||||
return False, f"unexpected status {response.status_code}"
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
return False, str(error)
|
||||
|
||||
|
||||
@@ -110,23 +109,23 @@ def list_registry_images() -> tuple[list[str], str]:
|
||||
response = client.get(f"{base}/v2/{repository}/tags/list")
|
||||
response.raise_for_status()
|
||||
tags = response.json().get("tags") or []
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
tags = []
|
||||
if tags:
|
||||
images.extend(f"{host}/{repository}:{tag}" for tag in tags)
|
||||
else:
|
||||
images.append(f"{host}/{repository}")
|
||||
return sorted(images), ""
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning("Could not list registry images.", exc_info=True)
|
||||
return [], str(error)
|
||||
|
||||
|
||||
def resolve_image(definition: JobDefinition) -> Optional[str]:
|
||||
def resolve_image(definition: JobDefinition) -> str | None:
|
||||
return definition.image or None
|
||||
|
||||
|
||||
def is_registry_image(image: Optional[str]) -> bool:
|
||||
def is_registry_image(image: str | None) -> bool:
|
||||
return bool(image) and image.split("/", 1)[0] == registry_host()
|
||||
|
||||
|
||||
@@ -151,7 +150,7 @@ def resolve_environment(definition: JobDefinition) -> dict[str, str]:
|
||||
return {**base, **(definition.env or {})}
|
||||
|
||||
|
||||
def registry_auth() -> Optional[dict[str, str]]:
|
||||
def registry_auth() -> dict[str, str] | None:
|
||||
if (
|
||||
settings.background_jobs_registry_username
|
||||
and settings.background_jobs_registry_password
|
||||
@@ -189,7 +188,7 @@ def start_run(
|
||||
if settings.background_jobs_pull_before_run and is_registry_image(image):
|
||||
try:
|
||||
pull_image(image)
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
run.status = JobRunStatus.FAILED
|
||||
run.finished_at = utcnow()
|
||||
run.logs = (
|
||||
@@ -211,7 +210,7 @@ def start_run(
|
||||
remove=False,
|
||||
)
|
||||
run.container_id = container.id
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
run.status = JobRunStatus.FAILED
|
||||
run.finished_at = utcnow()
|
||||
run.logs = (
|
||||
@@ -241,8 +240,8 @@ def schedule_due_jobs(session: Session) -> None:
|
||||
now = utcnow()
|
||||
scheduled = session.exec(
|
||||
select(JobDefinition).where(
|
||||
JobDefinition.enabled == True, # noqa: E712
|
||||
JobDefinition.schedule != None, # noqa: E711
|
||||
JobDefinition.enabled == True,
|
||||
JobDefinition.schedule != None,
|
||||
)
|
||||
).all()
|
||||
|
||||
@@ -276,8 +275,8 @@ def finalize_run(
|
||||
*,
|
||||
new_status: JobRunStatus,
|
||||
expected_status: JobRunStatus = JobRunStatus.RUNNING,
|
||||
exit_code: Optional[int] = None,
|
||||
logs: Optional[str] = None,
|
||||
exit_code: int | None = None,
|
||||
logs: str | None = None,
|
||||
) -> bool:
|
||||
values: dict = {"status": new_status, "finished_at": utcnow()}
|
||||
if exit_code is not None:
|
||||
@@ -300,7 +299,7 @@ def append_system_log(logs: str, message: str) -> str:
|
||||
def remove_container(container, run_id: int) -> None:
|
||||
try:
|
||||
container.remove()
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Could not remove container for run %s.", run_id, exc_info=True
|
||||
)
|
||||
@@ -371,6 +370,6 @@ async def scheduler_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
await asyncio.to_thread(tick)
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
logger.exception("Background job scheduler tick failed.")
|
||||
await asyncio.sleep(settings.background_jobs_tick_seconds)
|
||||
|
||||
@@ -17,7 +17,6 @@ from .model import (
|
||||
AvailableImages,
|
||||
BackgroundJobTask,
|
||||
DockerHealth,
|
||||
RegistryHealth,
|
||||
JobDefinition,
|
||||
JobDefinitionCreateRequest,
|
||||
JobDefinitionUpdateRequest,
|
||||
@@ -25,6 +24,7 @@ from .model import (
|
||||
JobRunLogs,
|
||||
JobRunStatus,
|
||||
JobTriggeredBy,
|
||||
RegistryHealth,
|
||||
utcnow,
|
||||
)
|
||||
|
||||
@@ -289,7 +289,7 @@ def get_run_logs(
|
||||
"utf-8", errors="replace"
|
||||
),
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
except Exception:
|
||||
pass
|
||||
return JobRunLogs(
|
||||
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "")
|
||||
@@ -319,7 +319,7 @@ def stop_run(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Container for run {run_id} no longer exists.",
|
||||
) from error
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning(
|
||||
"Could not inspect run %s before stopping.", run_id, exc_info=True
|
||||
)
|
||||
@@ -340,7 +340,7 @@ def stop_run(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Could not stop container for run {run_id}.",
|
||||
) from error
|
||||
except Exception as error: # noqa: BLE001
|
||||
except Exception as error:
|
||||
logger.warning("Could not stop run %s.", run_id, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from pydantic import BaseModel, Field as PydanticField
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field as PydanticField
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
@@ -21,7 +22,7 @@ class PersonBookmark(SQLModel, table=True):
|
||||
person_id: str = Field(nullable=False, index=True)
|
||||
person_name: str | None = Field(default=None)
|
||||
created_at: datetime = Field(
|
||||
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
|
||||
default_factory=lambda: datetime.now(UTC), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ from inse.database import SessionDep
|
||||
from . import service
|
||||
from .model import CreatePersonBookmark, PersonBookmarkResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from . import model
|
||||
from inse.authors.v2.service import author_currently_belongs_to_institution
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
from typing import Any
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .. import config
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for possible company connections of OpenAlex authors.
|
||||
"""
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
This module contains the configuration properties
|
||||
that can be adjusted via environment variables.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Literal, Optional
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
from typing import Literal
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,17 +34,17 @@ class Settings(BaseSettings):
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
# OpenAlex public API config
|
||||
openalex_api_base_url: str = "https://api.openalex.org"
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_key: str | None = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
# Patent Elasticsearch config
|
||||
patent_elasticsearch_url: str = "https://inse.nes.uni-due.de/elastic"
|
||||
patent_elasticsearch_api_key: Optional[str] = None
|
||||
patent_elasticsearch_api_key: str | None = None
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
llm_api_key: Optional[str] = None
|
||||
llm_model: Optional[str] = None
|
||||
llm_api_url: str | None = None
|
||||
llm_api_key: str | None = None
|
||||
llm_model: str | None = None
|
||||
|
||||
# Background job runner config (Docker-out-of-Docker)
|
||||
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
|
||||
@@ -58,25 +57,25 @@ class Settings(BaseSettings):
|
||||
# Credentials for pulling the job image from a private registry (e.g. the
|
||||
# Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the
|
||||
# Docker SDK inside the service container, which has no `docker login` creds.
|
||||
background_jobs_registry_username: Optional[str] = None
|
||||
background_jobs_registry_password: Optional[str] = None
|
||||
background_jobs_registry_username: str | None = None
|
||||
background_jobs_registry_password: str | None = None
|
||||
|
||||
# Sentence Transformers config
|
||||
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
|
||||
|
||||
# Elasticsearch config
|
||||
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
|
||||
elasticsearch_api_key: Optional[str] = None
|
||||
elasticsearch_inse_url: Optional[str] = None
|
||||
elasticsearch_inse_api_key: Optional[str] = None
|
||||
elasticsearch_api_key: str | None = None
|
||||
elasticsearch_inse_url: str | None = None
|
||||
elasticsearch_inse_api_key: str | None = None
|
||||
print_es_queries: bool = False
|
||||
print_es_timings: bool = False
|
||||
|
||||
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
|
||||
|
||||
allowed_origins: List[str] = ["http://localhost:4200"]
|
||||
allowed_origins: list[str] = ["http://localhost:4200"]
|
||||
|
||||
servers: List[Dict[str, str]] = [
|
||||
servers: list[dict[str, str]] = [
|
||||
{"url": "http://localhost:8000", "description": "Local development server"},
|
||||
]
|
||||
|
||||
@@ -84,8 +83,8 @@ class Settings(BaseSettings):
|
||||
|
||||
environment: Literal["dev", "prod"] = "dev"
|
||||
|
||||
token_issuer_id: Optional[str] = None
|
||||
token_hmac_key: Optional[str] = None
|
||||
token_issuer_id: str | None = None
|
||||
token_hmac_key: str | None = None
|
||||
|
||||
skip_otk_validation: bool = True
|
||||
# SMTP / email config
|
||||
@@ -95,8 +94,8 @@ class Settings(BaseSettings):
|
||||
smtp_server: str = "localhost"
|
||||
smtp_port: int = 25
|
||||
smtp_sender: str = "no-reply@smartguide.local"
|
||||
smtp_username: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
smtp_username: str | None = None
|
||||
smtp_password: str | None = None
|
||||
smtp_use_tls: bool = False
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,11 @@ class DfgProjectStatusStatistics(BaseModel):
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectKeyword(BaseModel):
|
||||
name: str
|
||||
project_count: int
|
||||
|
||||
|
||||
class DfgProjectTopic(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
@@ -49,6 +54,7 @@ class DfgProjectTopic(BaseModel):
|
||||
field: str | None = None
|
||||
domain: str | None = None
|
||||
project_count: int
|
||||
keywords: list[DfgProjectKeyword]
|
||||
|
||||
|
||||
class DfgProjectTopics(BaseModel):
|
||||
|
||||
@@ -10,8 +10,8 @@ from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticValue,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
@@ -22,11 +22,11 @@ from .model import (
|
||||
from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
@@ -82,6 +82,8 @@ async def dashboard_publications(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_persons(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -89,6 +91,8 @@ async def dashboard_persons(
|
||||
return await get_dashboard_persons(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
@@ -11,23 +11,35 @@ from sqlmodel import Session
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_active_institution_membership_query,
|
||||
)
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.institutions.v2 import service as institutions_v2_service
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
from inse.projects.dfg_institutions.service import autocomplete_institutions_for_selector
|
||||
from inse.persons import service as persons_service
|
||||
from inse.projects import service as projects_service
|
||||
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.model import (
|
||||
EuCordisProjectType,
|
||||
ProjectsFilteringProperties,
|
||||
ProjectType,
|
||||
)
|
||||
from inse.works.v2 import service as works_v2_service
|
||||
|
||||
from .institute_helper import get_openalex_institution
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DfgProjectTopic,
|
||||
DfgProjectKeyword,
|
||||
DashboardStatisticValue,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopic,
|
||||
DfgProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthor,
|
||||
@@ -40,14 +52,6 @@ from .model import (
|
||||
TopicWordCloud,
|
||||
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
|
||||
TOPIC_HEATMAP_LIMIT = 25
|
||||
@@ -238,35 +242,66 @@ async def get_dashboard_publications(
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = []
|
||||
if year_filter := _publication_year_filter(period):
|
||||
filters.append(year_filter)
|
||||
query = _institution_works_query(normalized_id)
|
||||
if filters:
|
||||
query = {"bool": {"must": [query], "filter": filters}}
|
||||
must = [
|
||||
works_v2_service._institutions_nested_query([normalized_id]),
|
||||
]
|
||||
if publication_years := _dashboard_publication_years(period):
|
||||
must.append({"terms": {"publication_year": publication_years}})
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
query=query,
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
index=ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
"query": {"bool": {"must": must}},
|
||||
},
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=_total(response),
|
||||
)
|
||||
|
||||
|
||||
def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None:
|
||||
from_year, to_year = period
|
||||
if from_year is None and to_year is None:
|
||||
return None
|
||||
return list(range(from_year or 1900, (to_year or 2100) + 1))
|
||||
|
||||
|
||||
async def get_dashboard_persons(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query=build_active_institution_membership_query(normalized_id),
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
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.",
|
||||
)
|
||||
persons = await persons_service.search_persons_list(
|
||||
query=None,
|
||||
institution_id=normalized_id,
|
||||
sort_by=None,
|
||||
sort_order=None,
|
||||
topic=None,
|
||||
page=1,
|
||||
page_size=1,
|
||||
include="",
|
||||
year_filter_enabled=period[0] is not None,
|
||||
filter_mode="between" if period[0] is not None else None,
|
||||
filter_year=period[0],
|
||||
filter_year_to=period[1],
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(persons.meta.count or 0) if persons.meta else 0,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_patents(
|
||||
@@ -298,45 +333,43 @@ async def get_dashboard_eu_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
period_filter = _project_overlap_filter(
|
||||
"startDate",
|
||||
"endDate",
|
||||
_date_period(period, "iso"),
|
||||
)
|
||||
if period_filter:
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
value = await _count_eu_projects_in_period(project_ids, period_filter)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=value,
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _eu_organization_query(aliases),
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projectID",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(
|
||||
response.get("aggregations", {})
|
||||
.get("projects", {})
|
||||
.get("value", 0)
|
||||
),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -351,10 +384,18 @@ async def get_dashboard_eu_project_statuses(
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -409,12 +450,26 @@ async def get_dashboard_eu_project_statuses(
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
_project_status_count(aggregations, "upcoming"),
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=_project_status_count(aggregations, "upcoming"),
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -424,6 +479,32 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int
|
||||
)
|
||||
|
||||
|
||||
def _reconcile_project_status_counts(
|
||||
total: int,
|
||||
ongoing: int,
|
||||
upcoming: int,
|
||||
completed: int,
|
||||
) -> tuple[int, int, int]:
|
||||
"""Makes status buckets add up to the authoritative project-service total."""
|
||||
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||
difference = total - sum(counts)
|
||||
if difference >= 0:
|
||||
counts[0] += difference
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
# Defensive fallback for stale/duplicated status documents: reduce buckets
|
||||
# without ever returning negative values, preferring the inferred ongoing
|
||||
# bucket before changing explicit upcoming/completed classifications.
|
||||
excess = -difference
|
||||
for index in (0, 1, 2):
|
||||
reduction = min(counts[index], excess)
|
||||
counts[index] -= reduction
|
||||
excess -= reduction
|
||||
if excess == 0:
|
||||
break
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
@@ -431,23 +512,38 @@ async def get_dashboard_bmbf_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
||||
if period_filter := _project_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
_date_period(period, "de"),
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
@@ -481,12 +577,26 @@ async def get_dashboard_bmbf_project_statuses(
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_bmbf_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
)
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
completed=int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -518,15 +628,37 @@ async def get_dashboard_dfg_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.get_dfg_projects_by_author_id(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=len(project_ids),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -542,10 +674,18 @@ async def get_dashboard_dfg_project_statuses(
|
||||
normalized_id,
|
||||
)
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -623,12 +763,26 @@ async def get_dashboard_dfg_project_statuses(
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=0,
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -639,7 +793,7 @@ async def get_dashboard_dfg_topics(
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
@@ -651,7 +805,7 @@ async def get_dashboard_dfg_topics(
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "topic_matches"],
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
@@ -659,6 +813,7 @@ async def get_dashboard_dfg_topics(
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
@@ -673,9 +828,12 @@ async def get_dashboard_dfg_topics(
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
@@ -685,6 +843,16 @@ async def get_dashboard_dfg_topics(
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
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()
|
||||
]
|
||||
@@ -698,6 +866,53 @@ async def get_dashboard_dfg_topics(
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Returns every matching DFG project ID through the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.get_dfg_projects_by_author_id(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
@@ -974,9 +1189,11 @@ async def get_top_authors(
|
||||
from_year = datetime.now().year - 4
|
||||
to_year = datetime.now().year
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
authors = await _safe_institution_authors(normalized_id)
|
||||
works = _top_work_authors(authors, period)
|
||||
works = await _safe_top_authors(
|
||||
"works",
|
||||
_top_work_authors(normalized_id, period, authors),
|
||||
)
|
||||
projects = await _safe_top_authors(
|
||||
"projects",
|
||||
_top_project_authors(
|
||||
@@ -988,7 +1205,12 @@ async def get_top_authors(
|
||||
)
|
||||
eu_projects = await _safe_top_authors(
|
||||
"eu_projects",
|
||||
_top_eu_project_publication_authors(normalized_id, aliases, authors),
|
||||
_top_eu_project_publication_authors(
|
||||
normalized_id,
|
||||
authors,
|
||||
from_year=period[0],
|
||||
to_year=period[1],
|
||||
),
|
||||
)
|
||||
|
||||
patents = await _safe_top_authors(
|
||||
@@ -1383,51 +1605,81 @@ def _short_author_id(value: str) -> str:
|
||||
return value.replace("https://openalex.org/", "").strip().upper()
|
||||
|
||||
|
||||
def _top_work_authors(
|
||||
authors: list[dict[str, Any]],
|
||||
async def _top_work_authors(
|
||||
institution_id: str,
|
||||
period: DashboardPeriod,
|
||||
institution_authors: list[dict[str, Any]],
|
||||
) -> list[TopAuthor]:
|
||||
if period != (None, None):
|
||||
ranked_authors = sorted(
|
||||
(
|
||||
{
|
||||
**author,
|
||||
"selected_works_count": _works_count_in_period(author, period),
|
||||
}
|
||||
for author in authors
|
||||
),
|
||||
key=lambda author: author["selected_works_count"],
|
||||
reverse=True,
|
||||
)
|
||||
else:
|
||||
ranked_authors = [
|
||||
{**author, "selected_works_count": author["works_count"]}
|
||||
for author in authors
|
||||
]
|
||||
institution_author_ids = {
|
||||
_short_author_id(str(author["id"]))
|
||||
for author in institution_authors
|
||||
if author.get("id")
|
||||
}
|
||||
if not institution_author_ids:
|
||||
return []
|
||||
|
||||
must = [works_v2_service._institutions_nested_query([institution_id])]
|
||||
if publication_years := _dashboard_publication_years(period):
|
||||
must.append({"terms": {"publication_year": publication_years}})
|
||||
|
||||
author_counts: dict[str, int] = defaultdict(int)
|
||||
author_names: dict[str, str] = {}
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.OPENALEX_WORKS_WILDCARD),
|
||||
query={"bool": {"must": must}},
|
||||
source=[
|
||||
"id",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.institutions.id",
|
||||
],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.NES,
|
||||
):
|
||||
hit_author_ids: set[str] = set()
|
||||
for authorship in hit.get("_source", {}).get("authorships", []):
|
||||
if not any(
|
||||
_normalize_institution_id(institution.get("id")) == institution_id
|
||||
for institution in authorship.get("institutions") or []
|
||||
if institution.get("id")
|
||||
):
|
||||
continue
|
||||
author = authorship.get("author") or {}
|
||||
author_id = author.get("id")
|
||||
if not author_id:
|
||||
continue
|
||||
author_id = str(author_id)
|
||||
if _short_author_id(author_id) not in institution_author_ids:
|
||||
continue
|
||||
hit_author_ids.add(author_id)
|
||||
if author.get("display_name"):
|
||||
author_names.setdefault(author_id, str(author["display_name"]))
|
||||
for author_id in hit_author_ids:
|
||||
author_counts[author_id] += 1
|
||||
|
||||
ranked_authors = sorted(
|
||||
(
|
||||
{
|
||||
"id": author_id,
|
||||
"name": author_names.get(author_id, author_id),
|
||||
"count": count,
|
||||
}
|
||||
for author_id, count in author_counts.items()
|
||||
),
|
||||
key=lambda author: author["count"],
|
||||
reverse=True,
|
||||
)
|
||||
return [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author["id"]),
|
||||
name=author["name"],
|
||||
count=author["selected_works_count"],
|
||||
count=author["count"],
|
||||
)
|
||||
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
|
||||
if author["selected_works_count"] > 0
|
||||
if author["count"] > 0
|
||||
]
|
||||
|
||||
|
||||
def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int:
|
||||
from_year, to_year = period
|
||||
return sum(
|
||||
int(item.get("works_count", 0) or 0)
|
||||
for item in author.get("counts_by_year", [])
|
||||
if (
|
||||
(from_year is None or int(item.get("year", 0) or 0) >= from_year)
|
||||
and (to_year is None or int(item.get("year", 0) or 0) <= to_year)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
return await _institution_authors(institution_id)
|
||||
@@ -1961,8 +2213,9 @@ async def _top_patent_authors(
|
||||
|
||||
async def _top_eu_project_publication_authors(
|
||||
institution_id: str,
|
||||
organization_names: list[str],
|
||||
institution_authors: list[dict[str, Any]],
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[TopAuthor]:
|
||||
institution_author_ids = {
|
||||
author_id
|
||||
@@ -1972,17 +2225,12 @@ async def _top_eu_project_publication_authors(
|
||||
if not institution_author_ids:
|
||||
return []
|
||||
|
||||
project_page = await get_eu_organization_project_contributions(
|
||||
organization_names=organization_names,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
institution_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
project_ids = [project.project_id for project in project_page.elements]
|
||||
|
||||
if not project_ids:
|
||||
return []
|
||||
|
||||
@@ -1991,11 +2239,7 @@ async def _top_eu_project_publication_authors(
|
||||
body={
|
||||
"size": 10000,
|
||||
"_source": ["projectID", "qaProcessedDoi"],
|
||||
"query": {
|
||||
"terms": {
|
||||
"projectID": project_ids,
|
||||
}
|
||||
},
|
||||
"query": {"terms": {"projectID": project_ids}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
@@ -2029,12 +2273,83 @@ async def _top_eu_project_publication_authors(
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
return _openalex_work_authors_by_eu_projects(
|
||||
candidates = _openalex_work_authors_by_eu_projects(
|
||||
works_response,
|
||||
doi_project_ids,
|
||||
institution_id,
|
||||
institution_author_ids,
|
||||
limit=None,
|
||||
)
|
||||
counts = await asyncio.gather(
|
||||
*(
|
||||
_person_eu_project_count(
|
||||
candidate.id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
for candidate in candidates
|
||||
if candidate.id
|
||||
)
|
||||
)
|
||||
ranked = [
|
||||
TopAuthor(id=candidate.id, name=candidate.name, count=count)
|
||||
for candidate, count in zip(candidates, counts, strict=True)
|
||||
]
|
||||
ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
|
||||
return ranked[:TOP_AUTHOR_LIMIT]
|
||||
|
||||
|
||||
async def _get_eu_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Loads all organization EU project IDs from the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
def _cordis_publication_doi_project_ids(
|
||||
@@ -2071,6 +2386,7 @@ def _openalex_work_authors_by_eu_projects(
|
||||
doi_project_ids: dict[str, set[str]],
|
||||
institution_id: str,
|
||||
institution_author_ids: set[str],
|
||||
limit: int | None = TOP_AUTHOR_LIMIT,
|
||||
) -> list[TopAuthor]:
|
||||
# Count unique CORDIS projects per author, not publications. Multiple works
|
||||
# (and therefore multiple DOIs) can belong to the same project ID.
|
||||
@@ -2106,14 +2422,58 @@ def _openalex_work_authors_by_eu_projects(
|
||||
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
|
||||
)
|
||||
|
||||
return [
|
||||
authors = [
|
||||
TopAuthor(
|
||||
id=_short_author_id(author_id),
|
||||
name=author_names[author_id],
|
||||
count=len(project_ids),
|
||||
)
|
||||
for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT]
|
||||
for author_id, project_ids in ranked_authors
|
||||
]
|
||||
return authors[:limit] if limit is not None else authors
|
||||
|
||||
|
||||
async def _person_eu_project_count(
|
||||
author_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> int:
|
||||
"""Uses the same author-only EU project search as the person detail page."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
page=0,
|
||||
size=1,
|
||||
project_types=None,
|
||||
raw_oa_institution_id=None,
|
||||
institutions_search_client=None,
|
||||
author_id=_short_author_id(author_id),
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
sort_by="title",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
return projects.total
|
||||
|
||||
|
||||
def _normalize_author_id(value: Any) -> str | None:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
@@ -10,7 +10,14 @@ from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
_get_dfg_project_ids_from_projects_service,
|
||||
_reconcile_project_status_counts,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
@@ -18,6 +25,16 @@ from inse.dashboard.service import (
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.model import CustomAuthorsListResponse
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
DfgProjectPage,
|
||||
DfgProjectSummary,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectSummary,
|
||||
EuCordisProjectType,
|
||||
)
|
||||
|
||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||
|
||||
@@ -27,6 +44,47 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_project_status_counts_match_authoritative_total():
|
||||
assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5)
|
||||
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dfg_topic_project_ids_use_paginated_projects_service():
|
||||
pages = [
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")],
|
||||
total=3,
|
||||
page=0,
|
||||
size=1000,
|
||||
),
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="103")],
|
||||
total=3,
|
||||
page=1,
|
||||
size=1000,
|
||||
),
|
||||
]
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(side_effect=pages),
|
||||
) as mocked_get_projects:
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
ORG_INSTITUTION_ID,
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert project_ids == ["101", "102", "103"]
|
||||
assert mocked_get_projects.await_count == 2
|
||||
first_call = mocked_get_projects.await_args_list[0]
|
||||
assert first_call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert first_call.kwargs["skip_enrichment"] is True
|
||||
assert first_call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert first_call.kwargs["funding_end_years"][0] == "2020"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
@@ -84,6 +142,33 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
display_name_alternatives=["Example Universität"],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(
|
||||
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[], total=10, page=0, size=1
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(
|
||||
return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(
|
||||
return_value=CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=35, page=1, per_page=1)
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)),
|
||||
):
|
||||
result = await get_dashboard_statistics(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -101,64 +186,162 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
|
||||
publication_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == config.settings.openalex_works_search_index
|
||||
)
|
||||
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
|
||||
person_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
|
||||
)
|
||||
person_query = person_call.kwargs["query"]
|
||||
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
|
||||
|
||||
assert recent_affiliation["nested"]["path"] == "affiliations"
|
||||
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == {
|
||||
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
|
||||
}
|
||||
eu_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
|
||||
)
|
||||
assert eu_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert eu_call.kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"EXAMPLE ORG",
|
||||
"EXAMPLE UNI",
|
||||
"EXAMPLE UNIVERSITY",
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_publications_counts_matching_openalex_works():
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(
|
||||
side_effect=[
|
||||
{"hits": {"total": {"value": 250}}},
|
||||
{"hits": {"total": {"value": 22}}},
|
||||
]
|
||||
}
|
||||
}
|
||||
),
|
||||
) as mocked_search:
|
||||
all_time = await get_dashboard_publications(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
selected_period = await get_dashboard_publications(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2021,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
bund_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
assert all_time.value == 250
|
||||
assert selected_period.value == 22
|
||||
all_time_body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
selected_period_body = mocked_search.await_args_list[1].kwargs["body"]
|
||||
assert mocked_search.await_args_list[0].kwargs["index"] == (
|
||||
ESIndex.OPENALEX_WORKS_WILDCARD
|
||||
)
|
||||
assert bund_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
assert all_time_body["track_total_hits"] is True
|
||||
assert all_time_body["query"]["bool"]["must"] == [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [ORG_INSTITUTION_ID]
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dfg_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
||||
]
|
||||
assert len(dfg_calls) == 2
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
|
||||
assert selected_period_body["query"]["bool"]["must"] == [
|
||||
all_time_body["query"]["bool"]["must"][0],
|
||||
{"terms": {"publication_year": [2021, 2022]}},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_persons_uses_persons_service_for_organization():
|
||||
response = CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=64, page=1, per_page=1)
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search_persons:
|
||||
result = await get_dashboard_persons(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2023,
|
||||
)
|
||||
|
||||
assert result.value == 64
|
||||
call = mocked_search_persons.await_args
|
||||
assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID
|
||||
assert call.kwargs["filter_mode"] == "between"
|
||||
assert call.kwargs["filter_year"] == 2020
|
||||
assert call.kwargs["filter_year_to"] == 2023
|
||||
assert call.kwargs["page"] == 1
|
||||
assert call.kwargs["page_size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_dfg_projects_uses_projects_service_total():
|
||||
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_dfg_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert result.value == 42
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert call.kwargs["funding_end_years"][0] == "2020"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_bmbf_projects_uses_projects_service_total():
|
||||
project_page = BundProjectPage(elements=[], total=29, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_bmbf_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2018,
|
||||
to_year=2020,
|
||||
)
|
||||
|
||||
assert result.value == 29
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2020"
|
||||
assert call.kwargs["funding_end_years"][0] == "2018"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_eu_projects_uses_projects_service_total():
|
||||
project_page = EuCordisProjectSearchPage(
|
||||
elements=[], total=37, page=0, size=1
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_eu_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2019,
|
||||
to_year=2021,
|
||||
)
|
||||
|
||||
assert result.value == 37
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2021"
|
||||
assert call.kwargs["funding_end_years"][0] == "2019"
|
||||
assert call.kwargs["project_types"] == list(EuCordisProjectType)
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -272,23 +455,79 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
scan_calls = []
|
||||
|
||||
async def scan(**kwargs):
|
||||
scan_calls.append(kwargs)
|
||||
yield {
|
||||
"_id": "W1",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/W1",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
},
|
||||
"institutions": [{"id": "https://openalex.org/I999"}],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
yield {
|
||||
"_id": "W2",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/W2",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
async def eu_projects(**kwargs):
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU),
|
||||
],
|
||||
total=3,
|
||||
page=0,
|
||||
size=1000,
|
||||
)
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[],
|
||||
total={"A1": 3, "A2": 4}[kwargs["author_id"]],
|
||||
page=0,
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
SimpleNamespace(project_id="P3"),
|
||||
],
|
||||
)
|
||||
),
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
@@ -305,16 +544,17 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 42,
|
||||
"count": 2,
|
||||
}
|
||||
assert len(result.works) == 1
|
||||
assert result.patents[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 4,
|
||||
}
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": "A2", "name": "Grace Example", "count": 2},
|
||||
{"id": "A1", "name": "Ada Example", "count": 1},
|
||||
{"id": "A2", "name": "Grace Example", "count": 4},
|
||||
{"id": "A1", "name": "Ada Example", "count": 3},
|
||||
]
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
@@ -346,18 +586,44 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
|
||||
assert "aggs" not in eu_body
|
||||
|
||||
works_calls = [
|
||||
assert len(scan_calls) == 1
|
||||
assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
|
||||
assert scan_calls[0]["query"]["bool"]["must"] == [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [ORG_INSTITUTION_ID]
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
]
|
||||
assert scan_calls[0]["source"] == [
|
||||
"id",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.institutions.id",
|
||||
]
|
||||
|
||||
eu_work_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == "openalex-works"
|
||||
]
|
||||
assert len(works_calls) == 1
|
||||
works_body = works_calls[0].kwargs["body"]
|
||||
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
|
||||
assert len(eu_work_calls) == 1
|
||||
eu_works_body = eu_work_calls[0].kwargs["body"]
|
||||
assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
|
||||
"https://doi.org/10.1234/p1",
|
||||
"https://doi.org/10.1234/p2",
|
||||
]
|
||||
assert works_body["_source"] == [
|
||||
assert eu_works_body["_source"] == [
|
||||
"doi",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
@@ -573,6 +839,24 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
}
|
||||
return {"aggregations": {"authors": {"buckets": []}}}
|
||||
|
||||
async def eu_projects(**kwargs):
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
],
|
||||
total=2,
|
||||
page=0,
|
||||
size=1000,
|
||||
)
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[],
|
||||
total={"A1": 4, "A2": 1}[kwargs["author_id"]],
|
||||
page=0,
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
@@ -580,15 +864,8 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
],
|
||||
)
|
||||
),
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
@@ -599,7 +876,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
)
|
||||
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": "A1", "name": "Ada Example", "count": 2},
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
{"id": "A2", "name": "Grace Example", "count": 1},
|
||||
]
|
||||
|
||||
@@ -625,9 +902,29 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
|
||||
|
||||
raise RuntimeError("projects unavailable")
|
||||
|
||||
async def scan(**kwargs):
|
||||
yield {
|
||||
"_id": "W1",
|
||||
"_source": {
|
||||
"id": "https://openalex.org/W1",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
@@ -691,9 +988,47 @@ async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
}
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
scan_calls = []
|
||||
|
||||
async def scan(**kwargs):
|
||||
scan_calls.append(kwargs)
|
||||
for index in range(16):
|
||||
yield {
|
||||
"_id": f"W-grace-{index}",
|
||||
"_source": {
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
for index in range(2):
|
||||
yield {
|
||||
"_id": f"W-ada-{index}",
|
||||
"_source": {
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
@@ -721,6 +1056,11 @@ async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
"count": 2,
|
||||
}
|
||||
|
||||
assert len(scan_calls) == 1
|
||||
assert scan_calls[0]["query"]["bool"]["must"][1] == {
|
||||
"terms": {"publication_year": list(range(current_year - 4, current_year + 1))}
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
|
||||
@@ -10,22 +10,18 @@ class NotFoundException(Exception):
|
||||
|
||||
class ElasticsearchException(Exception):
|
||||
"""Base exception for all Elasticsearch integrations."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
|
||||
"""Raised when an Elasticsearch document or index is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchConnectionException(ElasticsearchException):
|
||||
"""Raised when connecting to Elasticsearch fails."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
"""Raised when a required API key is missing."""
|
||||
pass
|
||||
|
||||
|
||||
class UpstreamAPIException(Exception):
|
||||
@@ -38,4 +34,3 @@ class UpstreamAPIException(Exception):
|
||||
|
||||
class BadRequestException(Exception):
|
||||
"""Raised when request parameters are invalid or validation fails."""
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Funders domain package.
|
||||
"""
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
HTTP client for funded-publication searches in the OpenAlex works index.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from .. import config
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .. import config
|
||||
|
||||
|
||||
class FundedPublicationsSearchClient:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Business logic for author funding based on publication works.
|
||||
"""
|
||||
@@ -7,10 +6,14 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
)
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from . import model
|
||||
from .elastic_search_client import FundedPublicationsSearchClient
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PublicationsByAuthorResponse(BaseModel):
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for author publications and funding.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Query
|
||||
|
||||
from . import logic
|
||||
from . import model
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from . import logic, model
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Funding"])
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.funders import logic
|
||||
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
|
||||
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import logging
|
||||
from typing import List, Set
|
||||
from typing import Any, Dict, Literal, Optional
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.model import InstitutionPage
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -18,7 +15,6 @@ class InstitutionsSearchClient:
|
||||
Initializes the client. Credentials and URLs are handled by the
|
||||
centralized elasticsearch integration.
|
||||
"""
|
||||
pass
|
||||
|
||||
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
"""Retrieves an institution by its raw OpenAlex institution ID.
|
||||
@@ -56,7 +52,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
async def get_eu_organisation_id_by_oa_institution_id(
|
||||
self, raw_institution_id: str
|
||||
) -> Optional[str]:
|
||||
) -> str | None:
|
||||
"""Retrieves the corresponding EU organisation ID for a given OpenAlex institution ID, if available.
|
||||
|
||||
Args:
|
||||
@@ -99,7 +95,7 @@ class InstitutionsSearchClient:
|
||||
else:
|
||||
sort_config.append({"display_name.keyword": {"order": sorting_direction}})
|
||||
|
||||
query: Dict[str, Any] = {"match_all": {}}
|
||||
query: dict[str, Any] = {"match_all": {}}
|
||||
|
||||
if len(name) > 0:
|
||||
query = {
|
||||
@@ -136,7 +132,7 @@ class InstitutionsSearchClient:
|
||||
return self.response_to_institution_page(response, page, size)
|
||||
|
||||
def response_to_institution_page(
|
||||
self, response: Dict[str, Any], page: int, size: int
|
||||
self, response: dict[str, Any], page: int, size: int
|
||||
) -> InstitutionPage:
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -250,7 +246,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
async def get_institution_aliases_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> List[str]:
|
||||
) -> list[str]:
|
||||
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
|
||||
|
||||
Args:
|
||||
@@ -273,7 +269,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
def get_predefined_institution_aliases(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Set[str]:
|
||||
) -> set[str]:
|
||||
"""Get predefined aliases for a given institution ID.
|
||||
|
||||
Args:
|
||||
@@ -297,7 +293,7 @@ class InstitutionsSearchClient:
|
||||
set(predefined_aliases.get(raw_oa_institution_id, []))
|
||||
)
|
||||
|
||||
def augment_aliases(self, aliases: Set[str]) -> Set[str]:
|
||||
def augment_aliases(self, aliases: set[str]) -> set[str]:
|
||||
"""Augment a set of aliases by applying the augment_alias function to each alias.
|
||||
|
||||
Args:
|
||||
@@ -311,7 +307,7 @@ class InstitutionsSearchClient:
|
||||
augmented_aliases.update(self.augment_alias(alias))
|
||||
return augmented_aliases
|
||||
|
||||
def augment_alias(self, alias: str) -> List[str]:
|
||||
def augment_alias(self, alias: str) -> list[str]:
|
||||
"""Augment an alias by replacing German umlauts and ß with their alternative spellings.
|
||||
|
||||
Args:
|
||||
@@ -343,7 +339,7 @@ class InstitutionsSearchClient:
|
||||
aliases.append(alias.replace("-", " "))
|
||||
return aliases
|
||||
|
||||
def _convert_hit_to_institution(self, hit: Dict[str, Any]) -> Optional[Institution]:
|
||||
def _convert_hit_to_institution(self, hit: dict[str, Any]) -> Institution | None:
|
||||
"""Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
|
||||
|
||||
Args:
|
||||
@@ -365,6 +361,7 @@ class InstitutionsSearchClient:
|
||||
"government",
|
||||
"facility",
|
||||
"other",
|
||||
"funder",
|
||||
}
|
||||
|
||||
cleaned_source = {}
|
||||
@@ -388,7 +385,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Optional[List[str]]:
|
||||
) -> list[str] | None:
|
||||
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Business logic for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException, UpstreamAPIException
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.openalex.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
|
||||
from .search_client import OpenAlexInstitutionsClient
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
"government",
|
||||
"facility",
|
||||
"other",
|
||||
"funder",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -6,7 +5,7 @@ from inse.models.openalex.institution import Institution
|
||||
|
||||
|
||||
class InstitutionPage(BaseModel):
|
||||
elements: List[Institution] = Field(
|
||||
elements: list[Institution] = Field(
|
||||
default_factory=list, description="List of institutions in the current page."
|
||||
)
|
||||
page: int = Field(default=0, description="Current page number. (0-indexed)")
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for OpenAlex institutions.
|
||||
"""
|
||||
@@ -7,16 +6,16 @@ REST API for OpenAlex institutions.
|
||||
from functools import lru_cache
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.institutions.model import InstitutionPage
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
|
||||
from inse.tags import Tags
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.institutions.model import InstitutionPage
|
||||
from . import logic
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
from . import logic
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTIONS])
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
HTTP client for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
@@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_funder_institution_type():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I4210119759",
|
||||
"display_name": "Essen University Hospital",
|
||||
"country_code": "DE",
|
||||
"type": "funder",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(client=client)
|
||||
|
||||
assert result.results[0].id == "https://openalex.org/I4210119759"
|
||||
assert result.results[0].display_name == "Essen University Hospital"
|
||||
assert result.results[0].type == "funder"
|
||||
|
||||
|
||||
|
||||
@@ -142,20 +142,55 @@ async def autocomplete_institutions(
|
||||
if not query:
|
||||
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
|
||||
|
||||
stripped = query.strip()
|
||||
fields = [("display_name", 1.0), ("display_name_alternatives", 0.8)]
|
||||
should_clauses = []
|
||||
for field, weight in fields:
|
||||
should_clauses.extend([
|
||||
{
|
||||
"prefix": {
|
||||
f"{field}.keyword": {
|
||||
"value": stripped,
|
||||
"case_insensitive": True,
|
||||
"boost": 10.0 * weight,
|
||||
}
|
||||
}
|
||||
},
|
||||
{"match_phrase_prefix": {field: {"query": stripped, "boost": 5.0 * weight, "slop": 3}}},
|
||||
{"match_bool_prefix": {field: {"query": stripped, "boost": 2.0 * weight}}},
|
||||
{
|
||||
"constant_score": {
|
||||
"filter": {
|
||||
"wildcard": {
|
||||
f"{field}.keyword": {
|
||||
"value": f"*{stripped}*",
|
||||
"case_insensitive": True,
|
||||
}
|
||||
}
|
||||
},
|
||||
"boost": 1.0 * weight,
|
||||
}
|
||||
},
|
||||
])
|
||||
|
||||
return await search_institutions(
|
||||
page=page,
|
||||
size=size,
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase_prefix": {"display_name": query}},
|
||||
{"match_phrase_prefix": {"display_name_alternatives": query}},
|
||||
]
|
||||
"function_score": {
|
||||
"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}},
|
||||
"field_value_factor": {
|
||||
"field": "works_count",
|
||||
"modifier": "log1p",
|
||||
"factor": 0.05,
|
||||
"missing": 1.0,
|
||||
},
|
||||
"boost_mode": "multiply",
|
||||
}
|
||||
},
|
||||
source=source,
|
||||
)
|
||||
|
||||
|
||||
|
||||
async def autocomplete_institutions_for_selector(
|
||||
query: str, page: int = 0, size: int = 10
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.exceptions import (
|
||||
ElasticsearchConnectionException,
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
MissingApiKeyError,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .. import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[httpx.AsyncClient] = None
|
||||
_client: httpx.AsyncClient | None = None
|
||||
_loop = None
|
||||
|
||||
|
||||
@@ -35,7 +37,7 @@ def get_client() -> httpx.AsyncClient:
|
||||
return _client
|
||||
|
||||
|
||||
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
def _cluster_credentials(cluster: ESCluster) -> tuple[str, str]:
|
||||
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
|
||||
|
||||
Args:
|
||||
@@ -75,7 +77,7 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
|
||||
|
||||
|
||||
def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
def _index_to_cluster(index: ESIndex) -> ESCluster | None:
|
||||
"""Determines the Elasticsearch cluster to use based on the specified index.
|
||||
|
||||
Args:
|
||||
@@ -111,7 +113,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
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}
|
||||
|
||||
|
||||
@@ -135,9 +137,9 @@ async def _request(
|
||||
cluster: ESCluster,
|
||||
path: str,
|
||||
*,
|
||||
json_body: Optional[Any] = None,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
content: Optional[bytes] = None,
|
||||
json_body: Any | None = None,
|
||||
params: dict[str, Any] | None = None,
|
||||
content: bytes | None = None,
|
||||
content_type: str = "application/json",
|
||||
) -> httpx.Response:
|
||||
"""Sends an authenticated request to cluster and returns the raw response.
|
||||
@@ -188,18 +190,18 @@ async def _request(
|
||||
|
||||
|
||||
async def search(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
offset: Optional[int] = None,
|
||||
sort: Optional[List] = None,
|
||||
aggs: Optional[Dict] = None,
|
||||
body: Optional[Dict] = None,
|
||||
index: ESIndex | list[ESIndex] | str | list[str],
|
||||
query: dict | None = None,
|
||||
source: list | None = None,
|
||||
size: int | None = None,
|
||||
offset: int | None = None,
|
||||
sort: list | None = None,
|
||||
aggs: dict | None = None,
|
||||
body: dict | None = None,
|
||||
track_total_hits=False,
|
||||
highlight: Optional[Dict] = None,
|
||||
highlight: dict | None = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
|
||||
|
||||
Args:
|
||||
@@ -237,7 +239,7 @@ async def search(
|
||||
elif len(clusters) == 1:
|
||||
cluster = clusters.pop()
|
||||
|
||||
payload: Dict[str, Any] = {}
|
||||
payload: dict[str, Any] = {}
|
||||
|
||||
if body is not None:
|
||||
payload = body
|
||||
@@ -300,22 +302,22 @@ async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
|
||||
async def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
query: dict,
|
||||
source: list | None = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
) -> AsyncIterator[dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
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:
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
payload: dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
@@ -351,7 +353,7 @@ async def scan(
|
||||
async def get(
|
||||
index: ESIndex | str,
|
||||
doc_id: str,
|
||||
source: Optional[list] = None,
|
||||
source: list | None = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
@@ -370,9 +372,9 @@ async def get(
|
||||
async def update(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
doc: Dict[str, Any],
|
||||
doc: dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
response = await _request(
|
||||
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
|
||||
)
|
||||
@@ -383,9 +385,9 @@ async def update(
|
||||
async def index_doc(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
document: Dict[str, Any],
|
||||
document: dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
) -> dict[str, Any]:
|
||||
response = await _request(
|
||||
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
|
||||
)
|
||||
@@ -394,8 +396,8 @@ async def index_doc(
|
||||
|
||||
|
||||
async def count(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict[str, Any]] = None,
|
||||
index: ESIndex | list[ESIndex] | str | list[str],
|
||||
query: dict[str, Any] | None = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> int:
|
||||
"""Performs a count request (_count) on the specified Elasticsearch index.
|
||||
@@ -435,9 +437,9 @@ async def count(
|
||||
|
||||
|
||||
async def msearch(
|
||||
searches: List[Tuple[ESIndex | str | List[str], Dict[str, Any]]],
|
||||
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> List[Dict[str, Any]]:
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from openai import APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
from typing import Optional, Dict, Any
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from openai import APIConnectionError, AsyncOpenAI
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
async def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
@@ -45,7 +48,7 @@ async def call(
|
||||
"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 = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# inse/keywords/file_extraction.py
|
||||
import base64
|
||||
import logging
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
# import fitz
|
||||
import io
|
||||
import logging
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
|
||||
|
||||
@@ -1,39 +1,40 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Business logic for persons / authors.
|
||||
"""
|
||||
import asyncio
|
||||
from typing import Any, Dict, List
|
||||
|
||||
import partial_json_parser
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import partial_json_parser
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import ValidationError
|
||||
from typing import Awaitable, Callable
|
||||
from inse.keywords.prompts import KeywordsPrompt
|
||||
|
||||
from inse.integrations import llm
|
||||
from inse.keywords.extract_text import extract_text_from_upload
|
||||
from inse.keywords.model import (
|
||||
ExtractedKeywords,
|
||||
ExtractedKeywordsLLM,
|
||||
ExtractedKeywordsResponse,
|
||||
FileUpload,
|
||||
KeywordEntry,
|
||||
KeywordEntryWithTopic,
|
||||
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
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
EventCallback = Callable[[dict], Awaitable[None]]
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
|
||||
def _build_enriched_snapshot(
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]],
|
||||
confirmed: dict[str, list[KeywordEntryWithTopic]],
|
||||
) -> ExtractedKeywords:
|
||||
return ExtractedKeywords.model_validate(
|
||||
{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:
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {
|
||||
confirmed: dict[str, list[KeywordEntryWithTopic]] = {
|
||||
level: [KeywordEntryWithTopic(llm_keyword=item) for item in getattr(results, level)]
|
||||
for level in LEVELS
|
||||
}
|
||||
|
||||
keywords: List[str] = []
|
||||
positions: List[tuple[str, int]] = []
|
||||
keywords: list[str] = []
|
||||
positions: list[tuple[str, int]] = []
|
||||
for level in LEVELS:
|
||||
for idx, entry in enumerate(getattr(results, level)):
|
||||
keywords.append(entry.keyword)
|
||||
@@ -74,7 +75,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
|
||||
text = query
|
||||
|
||||
|
||||
user_prompt = f"""
|
||||
user_prompt = """
|
||||
Now analyze the following text and return ONLY the JSON object.\n"""
|
||||
|
||||
if limit:
|
||||
@@ -105,15 +106,15 @@ async def extract_keywords_stream_enriched(
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
files: List[FileUpload] | None = None,
|
||||
files: list[FileUpload] | None = None,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 120
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
enrichment_tasks: List[asyncio.Task] = []
|
||||
confirmed: dict[str, list[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
enrichment_tasks: list[asyncio.Task] = []
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
try:
|
||||
@@ -136,7 +137,7 @@ async def extract_keywords_stream_enriched(
|
||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||
await emit_full_results()
|
||||
|
||||
def make_on_chunk(base_offset: Dict[str, int]):
|
||||
def make_on_chunk(base_offset: dict[str, int]):
|
||||
"""
|
||||
Builds an on_chunk callback for a single streaming LLM call.
|
||||
|
||||
@@ -147,7 +148,7 @@ async def extract_keywords_stream_enriched(
|
||||
(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":
|
||||
await emit(event)
|
||||
return
|
||||
@@ -206,7 +207,7 @@ async def extract_keywords_stream_enriched(
|
||||
on_chunk = make_on_chunk(base_offset)
|
||||
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":
|
||||
full_content_holder["value"] += event["content"]
|
||||
event = {**event, "_full_content": full_content_holder["value"]}
|
||||
@@ -232,7 +233,7 @@ async def extract_keywords_stream_enriched(
|
||||
),
|
||||
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())
|
||||
raise RuntimeError(f"LLM streaming call timed out{suffix}")
|
||||
except asyncio.CancelledError:
|
||||
@@ -278,8 +279,8 @@ async def extract_keywords_stream_enriched(
|
||||
).model_dump()
|
||||
)
|
||||
|
||||
file_texts: List[str] = []
|
||||
failed_files: List[str] = []
|
||||
file_texts: list[str] = []
|
||||
failed_files: list[str] = []
|
||||
|
||||
for i, f in enumerate(provided_files, start=1):
|
||||
text = await asyncio.to_thread(
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Data models for persons / authors.
|
||||
"""
|
||||
from typing import List, Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.topics.model import KeywordTopicMatch
|
||||
|
||||
|
||||
class FileUpload(BaseModel):
|
||||
filename: str = Field(description="The name of the uploaded file.")
|
||||
content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
|
||||
@@ -36,14 +35,14 @@ class KeywordEntryWithTopic(BaseModel):
|
||||
)
|
||||
|
||||
class ExtractedKeywords(BaseModel):
|
||||
broad_keywords: List[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: List[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: List[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
|
||||
broad_keywords: list[KeywordEntryWithTopic] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: list[KeywordEntryWithTopic] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: list[KeywordEntryWithTopic] = Field(description="The extracted fine-grained keywords from text.")
|
||||
|
||||
class ExtractedKeywordsLLM(BaseModel):
|
||||
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
|
||||
broad_keywords: list[KeywordEntry] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: list[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: list[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
|
||||
|
||||
class ExtractedKeywordsResponse(BaseModel):
|
||||
results_llm: ExtractedKeywordsLLM | None = None
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class KeywordsPrompt(StrEnum):
|
||||
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
|
||||
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
REST API for persons / authors.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||
from uvicorn.protocols.utils import ClientDisconnected
|
||||
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
import logging
|
||||
|
||||
from . import logic
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
This module defines the business logic for our
|
||||
web service.
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
import logging
|
||||
import json
|
||||
import logging
|
||||
|
||||
from . import config
|
||||
from inse.integrations import elasticsearch
|
||||
|
||||
|
||||
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_field import TopicField
|
||||
from inse.models.openalex.topic_subfield import TopicSubfield
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -91,7 +85,7 @@ async def build_topic_cache(save_json: bool = True) -> dict:
|
||||
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.
|
||||
Arguments:
|
||||
@@ -123,7 +117,7 @@ def get_topics_from_cache(topic_names: List[str]) -> List[Topic]:
|
||||
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.
|
||||
Arguments:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user