Compare commits
241
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1a6c32e0c | ||
|
|
cf5a3e7d3d | ||
|
|
89f45082fb | ||
|
|
0ad6ac70ff | ||
|
|
e8e0decc6c | ||
|
|
57aaf77162 | ||
|
|
07ce24143b | ||
|
|
bf5e065520 | ||
|
|
08178e74d2 | ||
|
|
c66fcff906 | ||
|
|
b0dd0e509d | ||
|
|
719da6e921 | ||
|
|
e4b3d0a9a9 | ||
|
|
c0e231a32b | ||
|
|
af9f9a25da | ||
|
|
0a465bc7e1 | ||
|
|
aec735e09e | ||
|
|
9ce6d5f26e | ||
|
|
f4b4fb0562 | ||
|
|
aa22fad67d | ||
|
|
548bb4ce70 | ||
|
|
b6871b3618 | ||
|
|
fe5e816551 | ||
|
|
20d2a281b1 | ||
|
|
e2ae0c660a | ||
|
|
9e8ae16597 | ||
|
|
e5284a79c9 | ||
|
|
79dad5dfb0 | ||
|
|
a511c16fb1 | ||
|
|
98a1214a4d | ||
|
|
be459c45cf | ||
|
|
328ef2938c | ||
|
|
21f3f49078 | ||
|
|
882ad3b8cf | ||
|
|
d8b7d8bc2e | ||
|
|
c1692535a5 | ||
|
|
af0e326747 | ||
|
|
6cdaa9738a | ||
|
|
1e5d0c4517 | ||
|
|
127f5ca287 | ||
|
|
f51b775fd9 | ||
|
|
0015b92591 | ||
|
|
37e1f1811f | ||
|
|
daa4f79ea0 | ||
|
|
c70a566514 | ||
|
|
b99d3a7ff1 | ||
|
|
30cbb080b0 | ||
|
|
d8eec59d5d | ||
|
|
be89e2986b | ||
|
|
916af84651 | ||
|
|
4e5ab529de | ||
|
|
3b1ffda3b2 | ||
|
|
cdf58044a8 | ||
|
|
e9fdf7d538 | ||
|
|
57f221868d | ||
|
|
ae7d1a54cb | ||
|
|
71b075b365 | ||
|
|
fb40bc548e | ||
|
|
d06c1954a5 | ||
|
|
545d487fea | ||
|
|
62f0812aae | ||
|
|
e0dda3ea0c | ||
|
|
7628f219e2 | ||
|
|
1d7a54c866 | ||
|
|
6c55493acb | ||
|
|
42bcac251b | ||
|
|
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 | ||
|
|
641f40ff45 | ||
|
|
6f0d17a991 | ||
|
|
2d1155d46b | ||
|
|
a1cf6e06af | ||
|
|
2e4a861e9c | ||
|
|
70e4ad71a6 | ||
|
|
dc27b49f63 | ||
|
|
b8707c7619 | ||
|
|
b251abb79f | ||
|
|
14be6c1a6c | ||
|
|
7addfe2a71 | ||
|
|
2474700473 | ||
|
|
0150f81a24 | ||
|
|
8a801d0bb5 | ||
|
|
496d2c88f0 | ||
|
|
9d8b287c13 | ||
|
|
94e0cad2d0 | ||
|
|
8be123bf3a | ||
|
|
570da1b47c | ||
|
|
02dd286d55 | ||
|
|
58199760de | ||
|
|
17b59213d3 | ||
|
|
06e2785914 | ||
|
|
0aea390e5e | ||
|
|
c33a900c66 | ||
|
|
f36e9a7d54 | ||
|
|
7259e3a0c0 | ||
|
|
b0581ad452 | ||
|
|
813953f1f5 | ||
|
|
288b21d407 | ||
|
|
01453f73dc | ||
|
|
410f1ade01 | ||
|
|
621a9dd2a1 | ||
|
|
18b9b8bf67 | ||
|
|
3f1ea0a418 | ||
|
|
211f7b82dc | ||
|
|
6675976feb | ||
|
|
034d3ee453 | ||
|
|
faa866f4e1 | ||
|
|
9c3e36930c | ||
|
|
d4daecd921 | ||
|
|
9f10e9e7af | ||
|
|
fa9def349c | ||
|
|
4073214131 | ||
|
|
03fac2a656 | ||
|
|
a204584ddd | ||
|
|
25de01c7be | ||
|
|
176235689f | ||
|
|
f27ee8b295 | ||
|
|
32616fe6aa | ||
|
|
9a5cb9e9b0 | ||
|
|
d11869c70b | ||
|
|
abb8c9dbb5 | ||
|
|
b8442213f8 | ||
|
|
0d19abb293 | ||
|
|
6ea3e79087 | ||
|
|
ba72b146a2 | ||
|
|
0f360c86b2 | ||
|
|
ecf7a6f905 | ||
|
|
345dffaa9b | ||
|
|
7b912196e9 | ||
|
|
6e4742206f | ||
|
|
a28ecc9d02 | ||
|
|
53397f844e | ||
|
|
818398ccda | ||
|
|
a6c7068ca6 | ||
|
|
4785bb4d40 | ||
|
|
1a9f9496fd | ||
|
|
78f35daa58 | ||
|
|
b2e70c2bb3 | ||
|
|
3d8ceeb5b6 | ||
|
|
0b8540d70b | ||
|
|
e9ccfe6796 | ||
|
|
e20f2732b3 | ||
|
|
4da4ea1bff | ||
|
|
93ba39f9b0 | ||
|
|
0642a3704d | ||
|
|
57e1bafa8b | ||
|
|
3d5eb524aa | ||
|
|
c15afed0aa | ||
|
|
b133ce80c9 | ||
|
|
ae8332dc3d | ||
|
|
026a35dd90 | ||
|
|
5fdc1cdce3 | ||
|
|
02bb8b8fb8 | ||
|
|
27f289f4a0 | ||
|
|
4fe78c2b88 | ||
|
|
2e8dd00aa6 | ||
|
|
127eed5c49 | ||
|
|
7a84fc2b12 | ||
|
|
96e0925054 | ||
|
|
730ee7f89a | ||
|
|
e62d1ca458 | ||
|
|
6bca5643ee | ||
|
|
db20b23ff3 | ||
|
|
66f34668a9 | ||
|
|
ceadc26741 | ||
|
|
3a74dc9b7b | ||
|
|
4a47d752cb | ||
|
|
46aee46ea3 | ||
|
|
3a78519655 | ||
|
|
c6de85d4a0 | ||
|
|
0dd2023224 | ||
|
|
d4880b417b | ||
|
|
a7ced052dd | ||
|
|
9ac618ebec | ||
|
|
de6339586f | ||
|
|
97c9e2eec3 | ||
|
|
167913aa85 | ||
|
|
18c9785325 | ||
|
|
f4e0888ce2 | ||
|
|
d3266ee50e | ||
|
|
410bcdec4b |
@@ -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:
|
||||
|
||||
+10
-1
@@ -6,5 +6,14 @@ RUN mkdir /test && \
|
||||
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
|
||||
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
|
||||
|
||||
ARG MODEL_NAME=intfloat/multilingual-e5-base
|
||||
ENV MODEL_NAME=${MODEL_NAME}
|
||||
ENV SENTENCE_TRANSFORMERS_HOME=/models
|
||||
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
|
||||
ENV HF_HOME=/models
|
||||
|
||||
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
|
||||
|
||||
ENV HF_HUB_OFFLINE=1
|
||||
ENV TRANSFORMERS_OFFLINE=1
|
||||
ENV HF_DATASETS_OFFLINE=1
|
||||
|
||||
|
||||
@@ -1,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.
|
||||
@@ -6,9 +6,28 @@ so it is available for local runs or testing.
|
||||
Usage (run once from project root):
|
||||
python service/sentence_transformer/download_model.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure service/src/main is in sys.path
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
src_main_dir = current_dir.parent / "src" / "main"
|
||||
if str(src_main_dir) not in sys.path:
|
||||
sys.path.insert(0, str(src_main_dir))
|
||||
|
||||
from inse.config import settings
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
MODEL_NAME = "intfloat/multilingual-e5-base"
|
||||
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
print(f"Downloading '{MODEL_NAME}' to cache directory...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
print("Done.")
|
||||
|
||||
print(f"Verifying offline model loading for '{MODEL_NAME}'...")
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
||||
os.environ["HF_DATASETS_OFFLINE"] = "1"
|
||||
|
||||
offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True)
|
||||
print("Done. Model downloaded and verified for 100% offline usage.")
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Script to fetch all topics from 'openalex-topics',
|
||||
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model,
|
||||
and push them to the 'topicvectors' index with multi-vector mapping.
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
@@ -26,7 +27,6 @@ API_KEY = settings.elasticsearch_api_key
|
||||
MODEL_NAME = settings.sentence_transformers_model_name
|
||||
|
||||
# Import sentence-transformers
|
||||
from sentence_transformers import SentenceTransformer
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
@@ -169,8 +169,9 @@ def main():
|
||||
print("No topics found. Exiting.")
|
||||
return
|
||||
|
||||
from inse.util import get_model
|
||||
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
|
||||
model = SentenceTransformer(MODEL_NAME)
|
||||
model = get_model()
|
||||
|
||||
# 1. Gather all texts to embed
|
||||
keywords_by_topic = []
|
||||
|
||||
@@ -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),
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -34,6 +34,19 @@ class BmbfProjectStatusStatistics(BaseModel):
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectStatusStatistics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
ongoing: int
|
||||
upcoming: int
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectKeyword(BaseModel):
|
||||
name: str
|
||||
project_count: int
|
||||
|
||||
|
||||
class DfgProjectTopic(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
@@ -41,6 +54,7 @@ class DfgProjectTopic(BaseModel):
|
||||
field: str | None = None
|
||||
domain: str | None = None
|
||||
project_count: int
|
||||
keywords: list[DfgProjectKeyword]
|
||||
|
||||
|
||||
class DfgProjectTopics(BaseModel):
|
||||
|
||||
@@ -10,8 +10,9 @@ from inse.tags import Tags
|
||||
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DashboardStatisticValue,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthorStatistics,
|
||||
@@ -21,10 +22,11 @@ from .model import (
|
||||
from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
@@ -80,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:
|
||||
@@ -87,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -210,6 +216,26 @@ async def dashboard_dfg_projects(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/dfg/status",
|
||||
operation_id="getDashboardDfgProjectStatuses",
|
||||
response_model=DfgProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_dfg_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_dfg_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/dfg/topics",
|
||||
operation_id="getDashboardDfgProjectTopics",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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:
|
||||
@@ -94,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
ESIndex.OPENALEX_INSTITUTIONS,
|
||||
ESIndex.OPENALEX_PUBLICATIONS,
|
||||
ESIndex.WORK_CLASSIFICATIONS,
|
||||
ESIndex.CC_NEWS_WILDCARD,
|
||||
}:
|
||||
return ESCluster.NES
|
||||
elif index in {
|
||||
@@ -111,7 +114,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 +138,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 +191,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 +240,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
|
||||
@@ -258,11 +261,10 @@ async def search(
|
||||
payload["sort"] = sort
|
||||
if aggs is not None:
|
||||
payload["aggs"] = aggs
|
||||
if track_total_hits:
|
||||
payload["track_total_hits"] = True
|
||||
if highlight is not None:
|
||||
payload["highlight"] = highlight
|
||||
|
||||
|
||||
payload["track_total_hits"] = True # always track total hits for accurate pagination and counts
|
||||
if len(payload) == 0:
|
||||
raise ValueError(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
||||
@@ -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,14 +437,18 @@ 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]]:
|
||||
request_cache: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
||||
|
||||
Args:
|
||||
searches: A list of tuples, each containing (index, payload_dict).
|
||||
cluster: The Elasticsearch cluster to execute searches on.
|
||||
request_cache: Whether to enable the shard request cache for each search.
|
||||
Elasticsearch rejects `request_cache` as an _msearch URL parameter, so
|
||||
it goes into the per-search header line instead.
|
||||
|
||||
Returns:
|
||||
List[Dict[str, Any]]: List of response dictionaries for each search in order.
|
||||
@@ -462,7 +468,9 @@ async def msearch(
|
||||
idx_str = ",".join(str(i) for i in idx)
|
||||
else:
|
||||
idx_str = str(idx)
|
||||
header_obj = {"index": idx_str}
|
||||
header_obj: dict[str, Any] = {"index": idx_str}
|
||||
if request_cache:
|
||||
header_obj["request_cache"] = True
|
||||
lines.append(json.dumps(header_obj))
|
||||
lines.append(json.dumps(body))
|
||||
|
||||
|
||||
@@ -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__)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user