added get_person_by_id and search_person_by_name endpoints + pytests
aiis/pipeline/head This commit looks good

This commit is contained in:
2026-05-27 18:40:38 +02:00
parent cec0b220dc
commit 78e6b371e5
5 changed files with 250 additions and 3 deletions
+2 -1
View File
@@ -14,7 +14,8 @@ RUN mkdir /test && \
"uvicorn~=0.29.0" \
"pytest~=8.1.0" \
"httpx~=0.27.0" \
"python-multipart~=0.0.19"
"python-multipart~=0.0.19"\
"elasticsearch~=9.4.0"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+1
View File
@@ -23,6 +23,7 @@ class Settings(BaseSettings):
llm_api_token: str = 'c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212'
llm_model: str = 'gemma4:e4b'
elasticsearch_url: str = 'https://project.nes.uni-due.de/elastic/openalex-authors/_search'
elasticsearch_instance: str = 'https://project.nes.uni-due.de/elastic'
elasticsearch_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=='
settings = Settings()
+126
View File
@@ -14,15 +14,21 @@ from sqlalchemy import delete
from sqlalchemy import insert
from sqlalchemy import update
from sqlalchemy import func
from fastapi import HTTPException
import logging
import httpx
import json
from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError
from . import schema
from . import model
from . import config
logger = logging.getLogger(__name__)
es_client = Elasticsearch(
hosts=[config.settings.elasticsearch_instance],
api_key=config.settings.elasticsearch_api_key,
)
S = TypeVar('S', bound=schema.Base)
M = TypeVar('M', bound=model.BaseModel)
@@ -141,3 +147,123 @@ def generate_person_bio(author_id: str) -> str:
response.raise_for_status()
data = response.json()
return data.get("response", "")
def get_person_by_id(author_id: str) -> model.Person:
try:
hit = es_client.get(
index="openalex-authors",
id=author_id
)
except NotFoundError:
raise HTTPException(
status_code=404,
detail=f"Person with id {author_id} not found"
)
except ApiError as e:
raise HTTPException(
status_code=500,
detail=f"Elasticsearch error: {str(e)}"
)
source = hit.get("_source", {}) or {}
affiliations = [
model.Affiliation(
institution=aff.get("institution", {}).get("display_name", ""),
country_code=aff.get("institution", {}).get("country_code", "")
)
for aff in source.get("affiliations") or []
]
topics = [
t.get("display_name", "")
for t in source.get("topics") or []
]
return model.Person(
id=author_id,
name=source.get("display_name", ""),
works_count=source.get("works_count", 0),
cited_by_count=source.get("cited_by_count", 0),
affiliations=affiliations,
topics=topics
)
def search_persons_by_name(author_name: str, limit: Optional[int] = 10) -> model.PersonSearchResult:
if not author_name:
raise HTTPException(
status_code=400,
detail="name must be provided"
)
search_query = {
"bool": {
"should": [
{
"match_phrase": {
"display_name": {
"query": author_name,
"boost": 5
}
}
},
{
"match": {
"display_name": {
"query": author_name,
"fuzziness": 1
}
}
}
],
"minimum_should_match": 1
}
}
try:
response = es_client.search(
index="openalex-authors",
query=search_query,
size=limit
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
persons = []
for hit in hits:
source = hit.get("_source", {}) or {}
affiliations = [
model.Affiliation(
institution=aff.get("institution", {}).get("display_name", ""),
country_code=aff.get("institution", {}).get("country_code", "")
)
for aff in source.get("affiliations") or []
]
topics = [
t.get("display_name", "")
for t in source.get("topics") or []
]
persons.append(
model.Person(
id=hit.get("_id", ""),
name=source.get("display_name", ""),
works_count=source.get("works_count", 0),
cited_by_count=source.get("cited_by_count", 0),
affiliations=affiliations,
topics=topics
)
)
return model.PersonSearchResult(persons=persons)
+17
View File
@@ -113,6 +113,23 @@ def delete_item(id: Annotated[int, Path(description='The item id.', ge=0)],
finally:
db.commit()
@app.get('/persons/id',
operation_id='getPersonByID',
response_model=model.Person,
summary='Searches for person by ID.',
tags=[ 'Persons' ])
def get_person_by_id(author_id: Annotated[str, Query(description="OpenAlex author ID (e.g., A5093075883)")]):
return logic.get_person_by_id(author_id)
@app.get('/persons/searchByName',
operation_id='searchPersonsByName',
response_model=model.PersonSearchResult,
summary='Searches for person by name.',
tags=[ 'Persons' ])
def search_persons_by_name(author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")]):
return logic.search_persons_by_name(author_name)
@app.get('/persons/search',
operation_id='searchPersons',
response_model=model.PersonSearchResult,
+104 -2
View File
@@ -1,9 +1,111 @@
from fastapi.testclient import TestClient
from fastapi import HTTPException
from inse.main import app
from . import model
from unittest.mock import patch
client = TestClient(app)
URL_SERVICE_PREFIX="/inse-service"
def test_redirect_root():
response = client.get("/", follow_redirects=False)
assert response.status_code == 307
def test_get_person_by_id_success():
mock_person = model.Person(
id="A5093075883",
name="Arman Arzani",
works_count=6,
cited_by_count=4,
affiliations=[],
topics=[]
)
with patch("inse.logic.get_person_by_id", return_value=mock_person):
response = client.get(
URL_SERVICE_PREFIX + "/persons/id",
params={"author_id": "A5093075883"}
)
assert response.status_code == 200
data = response.json()
assert data["id"] == "A5093075883"
assert data["name"] == "Arman Arzani"
assert data["works_count"] == 6
assert data["cited_by_count"] == 4
def test_get_person_by_id_not_found():
invalid_id = "INVALID"
with patch(
"inse.logic.get_person_by_id",
side_effect=HTTPException(
status_code=404,
detail="Person with id INVALID not found"
)
):
response = client.get(
URL_SERVICE_PREFIX + "/persons/id",
params={"author_id": invalid_id}
)
assert response.status_code == 404
def test_get_person_by_id_missing_query_param():
response = client.get(URL_SERVICE_PREFIX + "/persons/id")
assert response.status_code == 422
def test_search_persons_by_name_success():
mock_result = model.PersonSearchResult(
persons=[
model.Person(
id="A5047117780",
name="Pedro José Marrón",
works_count=285,
cited_by_count=2638,
)
]
)
with patch(
"inse.logic.search_persons_by_name",
return_value=mock_result
):
response = client.get(
URL_SERVICE_PREFIX + "/persons/searchByName",
params={"author_name": "Pedro José Marrón"}
)
assert response.status_code == 200
data = response.json()
assert "persons" in data
assert data["persons"][0]["name"] == "Pedro José Marrón"
def test_search_persons_by_name_empty_result():
response = client.get(
URL_SERVICE_PREFIX + "/persons/searchByName",
params={"author_name": "zzzz_nonexistent_name_123"}
)
assert response.status_code == 200
data = response.json()
assert data["persons"] == []
def test_search_persons_by_name_missing_query_param():
response = client.get(URL_SERVICE_PREFIX + "/persons/searchByName")
assert response.status_code == 422