Merge branch 'ts-82-author-overview-and-description' of https://project.nes.uni-due.de/gitea/lbs/smartguide into ts-82-author-overview-and-description
This commit is contained in:
@@ -52,22 +52,23 @@ def search(
|
||||
return response.json()
|
||||
def get(
|
||||
index: str,
|
||||
doc_id:str,
|
||||
body: dict = None,
|
||||
|
||||
doc_id: str,
|
||||
source: list = None,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
payload = body
|
||||
|
||||
# get document directly
|
||||
|
||||
params = {}
|
||||
if source is not None:
|
||||
params["_source_includes"] = ",".join(source)
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
json=payload,
|
||||
params=params,
|
||||
headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -12,23 +12,16 @@ from typing import Type
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func
|
||||
from fastapi import HTTPException
|
||||
import logging
|
||||
import httpx
|
||||
import json
|
||||
import time
|
||||
from . import schema
|
||||
from . import model
|
||||
from . import config
|
||||
from .integrations import elasticsearch
|
||||
from .integrations import llm
|
||||
from . import util
|
||||
from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
|
||||
from inse.models.author import Author
|
||||
from inse.models.authors_list_response import AuthorsListResponse
|
||||
from inse.models.meta import Meta
|
||||
from inse.models.topic import Topic
|
||||
from inse.models.topic_subfield import TopicSubfield
|
||||
from inse.models.topic_field import TopicField
|
||||
@@ -343,195 +336,4 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
|
||||
)
|
||||
|
||||
return bio
|
||||
|
||||
def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse:
|
||||
body = {
|
||||
"_source":include.split(",") if include else True,
|
||||
}
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
body=body,
|
||||
doc_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)}")
|
||||
persons = [util.get_persons_data(hit)]
|
||||
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
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_phrase_prefix": {
|
||||
"display_name": {"query": author_name, "boost": 3}
|
||||
}
|
||||
},
|
||||
# {
|
||||
# "match": {
|
||||
# "display_name": {
|
||||
# "query": author_name,
|
||||
# "fuzziness": 1
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
offset=page_offset,
|
||||
source=include.split(",") if include else True,
|
||||
size=limit,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
total_found = response.get("hits",{}).get("total",{}).get("value",0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
|
||||
return AuthorsListResponse(results=persons,meta=Meta(count=total_found,page=page_offset))
|
||||
|
||||
|
||||
def search_persons_autocomplete(author_name: str, limit: Optional[int] = 5, include: Optional[str] = None) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="name must be provided"
|
||||
)
|
||||
search_query = {
|
||||
"function_score": {
|
||||
"query": {
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": author_name + "*",
|
||||
"case_insensitive": True
|
||||
}
|
||||
}
|
||||
},
|
||||
"functions": [
|
||||
{
|
||||
"script_score": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": "String name = doc['display_name.keyword'].value.toLowerCase(); String[] parts = name.splitOnToken(' '); Set unique = new HashSet(); for (String p : parts) { unique.add(p); } return unique.size() > 1 ? 1.0 : 0.3;"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"boost_mode": "multiply"
|
||||
}
|
||||
}
|
||||
script_fields ={
|
||||
"affiliations": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": "def aff = params._source['affiliations']; if (aff != null && aff.size() > 0) { return aff[aff.size() - 1]; } return [];"
|
||||
}
|
||||
}
|
||||
}
|
||||
collapse ={
|
||||
"field":"display_name.keyword"
|
||||
}
|
||||
body = {
|
||||
"size":limit,
|
||||
"query":search_query,
|
||||
"script_fields":script_fields,
|
||||
"_source":include.split(",") if include else True,
|
||||
"sort":[{"works_count": {"order": "desc"}}],
|
||||
"collapse":collapse
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
body=body
|
||||
)
|
||||
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:
|
||||
fields = hit.get("fields",{})
|
||||
source = hit.get("_source",{})
|
||||
source_copy = dict (source)
|
||||
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
|
||||
|
||||
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
|
||||
ids = source_copy.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
ids_copy = dict(ids)
|
||||
for str_field in ["openalex", "orcid", "scopus"]:
|
||||
val = ids_copy.get(str_field)
|
||||
if val is not None and not isinstance(val, str):
|
||||
ids_copy[str_field] = str(val)
|
||||
source_copy["ids"] = ids_copy
|
||||
|
||||
for key,value in fields.items():
|
||||
source_copy[key] = value
|
||||
author = Author.from_dict(source_copy)
|
||||
persons.append(author)
|
||||
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
def search_persons_by_institution(
|
||||
institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
|
||||
if not institution_name:
|
||||
raise HTTPException(status_code=400, detail="institution_name must be provided")
|
||||
|
||||
search_query = {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": institution_name
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
source=include.split(",") if include else True,
|
||||
size=limit,
|
||||
offset=page_offset,
|
||||
sort=[{"works_count": {"order": "desc"}}],
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
total_found = response.get("hits",{}).get("total",{}).get("value",0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
return AuthorsListResponse(results=persons,meta=Meta(count=total_found,page=page_offset))
|
||||
return bio
|
||||
@@ -12,6 +12,7 @@ from fastapi.responses import RedirectResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
|
||||
from . import config
|
||||
from .service import router as service_router
|
||||
@@ -32,6 +33,7 @@ app = FastAPI(
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(service_router)
|
||||
app.include_router(account_router)
|
||||
|
||||
|
||||
@@ -36,8 +36,5 @@ class Page(BaseModel, Generic[T]):
|
||||
class ItemPage(Page[Item]):
|
||||
pass
|
||||
|
||||
class PersonBio(BaseModel):
|
||||
bio: str = Field(description="The generated biography.")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for persons / authors.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from .. import config
|
||||
from .. import util
|
||||
from ..integrations import elasticsearch
|
||||
|
||||
from inse.models.author import Author
|
||||
from inse.models.authors_list_response import AuthorsListResponse
|
||||
from inse.models.meta import Meta
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
include: Optional[set[str]] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if author_id:
|
||||
query_field = "_id"
|
||||
query_value = author_id
|
||||
elif query:
|
||||
query_field = "display_name"
|
||||
query_value = query
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(
|
||||
index="openalex-authors", query_field=query_field, query_value=query_value
|
||||
)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
source_copy = dict(source)
|
||||
source_copy["id"] = source_copy.get("id") or hit.get("_id", "")
|
||||
|
||||
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
|
||||
ids = source_copy.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
ids_copy = dict(ids)
|
||||
for str_field in ["openalex", "orcid", "scopus"]:
|
||||
val = ids_copy.get(str_field)
|
||||
if val is not None and not isinstance(val, str):
|
||||
ids_copy[str_field] = str(val)
|
||||
source_copy["ids"] = ids_copy
|
||||
|
||||
author = Author.from_dict(source_copy)
|
||||
if author:
|
||||
authors.append(author)
|
||||
|
||||
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
|
||||
|
||||
|
||||
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
start_time = time.time()
|
||||
search_result = search_persons(author_id=author_id)
|
||||
if not search_result.results:
|
||||
return "No person found."
|
||||
if len(search_result.results) > 1:
|
||||
return "Multiple persons found, cannot generate bio."
|
||||
|
||||
person = search_result.results[0]
|
||||
person_json = json.dumps(person.model_dump_json())
|
||||
|
||||
system_prompt = """\
|
||||
Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person.
|
||||
|
||||
Gehe dabei auf folgende drei Punkte ein:
|
||||
|
||||
1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema)
|
||||
2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung?
|
||||
3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend?
|
||||
|
||||
Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\
|
||||
"""
|
||||
|
||||
user_prompt = f"Daten zur Person:\n{person_json}"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {config.settings.llm_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
payload = {
|
||||
"model": config.settings.llm_model,
|
||||
"prompt": f"{system_prompt}\n{user_prompt}",
|
||||
"stream": False,
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
response = client.post(
|
||||
config.settings.llm_api_url, json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
bio = data.get("response", "")
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.info(
|
||||
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
|
||||
)
|
||||
|
||||
return bio
|
||||
|
||||
|
||||
def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse:
|
||||
body = {
|
||||
"_source":include.split(",") if include else True,
|
||||
}
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
body=body,
|
||||
doc_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)}")
|
||||
persons = [util.get_persons_data(hit)]
|
||||
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
author_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
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_phrase_prefix": {
|
||||
"display_name": {"query": author_name, "boost": 3}
|
||||
}
|
||||
},
|
||||
# {
|
||||
# "match": {
|
||||
# "display_name": {
|
||||
# "query": author_name,
|
||||
# "fuzziness": 1
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
offset=page_offset,
|
||||
source=include.split(",") if include else True,
|
||||
size=limit,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
total_found = response.get("hits",{}).get("total",{}).get("value",0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
|
||||
return AuthorsListResponse(results=persons,meta=Meta(count=total_found,page=page_offset))
|
||||
|
||||
|
||||
def search_persons_autocomplete(author_name: str, limit: Optional[int] = 5, include: Optional[str] = None) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="name must be provided"
|
||||
)
|
||||
search_query = {
|
||||
"function_score": {
|
||||
"query": {
|
||||
"wildcard": {
|
||||
"display_name.keyword": {
|
||||
"value": author_name + "*",
|
||||
"case_insensitive": True
|
||||
}
|
||||
}
|
||||
},
|
||||
"functions": [
|
||||
{
|
||||
"script_score": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": "String name = doc['display_name.keyword'].value.toLowerCase(); String[] parts = name.splitOnToken(' '); Set unique = new HashSet(); for (String p : parts) { unique.add(p); } return unique.size() > 1 ? 1.0 : 0.3;"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"boost_mode": "multiply"
|
||||
}
|
||||
}
|
||||
script_fields ={
|
||||
"affiliations": {
|
||||
"script": {
|
||||
"lang": "painless",
|
||||
"source": "def aff = params._source['affiliations']; if (aff != null && aff.size() > 0) { return aff[aff.size() - 1]; } return [];"
|
||||
}
|
||||
}
|
||||
}
|
||||
collapse ={
|
||||
"field":"display_name.keyword"
|
||||
}
|
||||
body = {
|
||||
"size":limit,
|
||||
"query":search_query,
|
||||
"script_fields":script_fields,
|
||||
"_source":include.split(",") if include else True,
|
||||
"sort":[{"works_count": {"order": "desc"}}],
|
||||
"collapse":collapse
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
body=body
|
||||
)
|
||||
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:
|
||||
fields = hit.get("fields",{})
|
||||
source = hit.get("_source",{})
|
||||
source_copy = dict (source)
|
||||
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
|
||||
|
||||
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
|
||||
ids = source_copy.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
ids_copy = dict(ids)
|
||||
for str_field in ["openalex", "orcid", "scopus"]:
|
||||
val = ids_copy.get(str_field)
|
||||
if val is not None and not isinstance(val, str):
|
||||
ids_copy[str_field] = str(val)
|
||||
source_copy["ids"] = ids_copy
|
||||
|
||||
for key,value in fields.items():
|
||||
source_copy[key] = value
|
||||
author = Author.from_dict(source_copy)
|
||||
persons.append(author)
|
||||
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
def search_persons_by_institution(
|
||||
institution_name: str, limit: Optional[int] = 10, page_offset: Optional[int] = 0, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
|
||||
if not institution_name:
|
||||
raise HTTPException(status_code=400, detail="institution_name must be provided")
|
||||
|
||||
search_query = {
|
||||
"nested": {
|
||||
"path": "affiliations",
|
||||
"query": {
|
||||
"match_phrase": {
|
||||
"affiliations.institution.display_name": institution_name
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
source=include.split(",") if include else True,
|
||||
size=limit,
|
||||
offset=page_offset,
|
||||
sort=[{"works_count": {"order": "desc"}}],
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
total_found = response.get("hits",{}).get("total",{}).get("value",0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
return AuthorsListResponse(results=persons,meta=Meta(count=total_found,page=page_offset))
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Data models for persons / authors.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
|
||||
|
||||
class PersonBio(BaseModel):
|
||||
bio: str = Field(description="The generated biography.")
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for persons / authors.
|
||||
"""
|
||||
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Path
|
||||
from fastapi import Query
|
||||
|
||||
from . import logic
|
||||
from . import model
|
||||
from inse.models.authors_list_response import AuthorsListResponse
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
tags=["Persons"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/search",
|
||||
operation_id="searchPersons",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for persons by ID or name.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
def search_persons(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
] = None,
|
||||
query: Annotated[
|
||||
str, Query(description="Search query (e.g., Arman AND Arzani)")
|
||||
] = None,
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Comma-separated include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, sources, counts_by_year, works_api_url, dates, "
|
||||
"cited_by_count_boost"
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
include_set = (
|
||||
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query, include_set)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/bio",
|
||||
operation_id="generatePersonBio",
|
||||
response_model=model.PersonBio,
|
||||
summary="Generates a bio for a person by author ID.",
|
||||
)
|
||||
def generate_person_bio(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=("Comma-separated list to include tags"),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
include_set = (
|
||||
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
|
||||
if include
|
||||
else None
|
||||
)
|
||||
bio = logic.generate_person_bio(author_id, include_set)
|
||||
return model.PersonBio(bio=bio)
|
||||
|
||||
@router.get(
|
||||
"/person/{id}",
|
||||
operation_id="getPersonByID",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def get_person_by_id(
|
||||
id: Annotated[
|
||||
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/searchByName",
|
||||
operation_id="searchPersonsByName",
|
||||
response_model=AuthorsListResponse,
|
||||
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)")],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
|
||||
|
||||
@router.get(
|
||||
'/persons/autocomplete',
|
||||
operation_id='searchPersonsAutocomplete',
|
||||
response_model=AuthorsListResponse,
|
||||
summary='Searches for person by name.',
|
||||
tags=[ 'Persons' ])
|
||||
def search_persons_autocomplete(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include : Annotated[Optional[str], Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return logic.search_persons_autocomplete(author_name=author_name,include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/searchByInstitution",
|
||||
operation_id="searchPersonsByInstitution",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for persons by institution name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_institution(
|
||||
institution_name: Annotated[
|
||||
str, Query(description="Institution name (e.g., MIT, Oxford University)")
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
|
||||
@@ -29,8 +29,6 @@ from . import security
|
||||
from . import util
|
||||
from .works import service as works_service
|
||||
|
||||
from inse.models.authors_list_response import AuthorsListResponse
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -210,164 +208,4 @@ def count_topic_hierarchy(
|
||||
),
|
||||
],
|
||||
):
|
||||
return logic.count_topic_hierarchy(topic_names)
|
||||
|
||||
|
||||
### persons
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/search",
|
||||
operation_id="searchPersons",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for persons by ID or name.",
|
||||
response_model_exclude_none=True,
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
] = None,
|
||||
query: Annotated[
|
||||
str, Query(description="Search query (e.g., Arman AND Arzani)")
|
||||
] = None,
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Comma-separated include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, sources, counts_by_year, works_api_url, dates, "
|
||||
"cited_by_count_boost"
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
include_set = (
|
||||
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query, include_set)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/bio",
|
||||
operation_id="generatePersonBio",
|
||||
response_model=model.PersonBio,
|
||||
summary="Generates a bio for a person by author ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def generate_person_bio(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=("Comma-separated list to include tags"),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
include_set = (
|
||||
{tag.strip().lower() for tag in include.split(",") if tag.strip()}
|
||||
if include
|
||||
else None
|
||||
)
|
||||
bio = logic.generate_person_bio(author_id, include_set)
|
||||
return model.PersonBio(bio=bio)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/person/{id}",
|
||||
operation_id="getPersonByID",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def get_person_by_id(
|
||||
id: Annotated[
|
||||
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/searchByName",
|
||||
operation_id="searchPersonsByName",
|
||||
response_model=AuthorsListResponse,
|
||||
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)")],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
|
||||
|
||||
@router.get(
|
||||
'/persons/autocomplete',
|
||||
operation_id='searchPersonsAutocomplete',
|
||||
response_model=AuthorsListResponse,
|
||||
summary='Searches for person by name.',
|
||||
tags=[ 'Persons' ])
|
||||
def search_persons_autocomplete(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include : Annotated[Optional[str], Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return logic.search_persons_autocomplete(author_name=author_name,include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/searchByInstitution",
|
||||
operation_id="searchPersonsByInstitution",
|
||||
response_model=AuthorsListResponse,
|
||||
summary="Searches for persons by institution name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_institution(
|
||||
institution_name: Annotated[
|
||||
str, Query(description="Institution name (e.g., MIT, Oxford University)")
|
||||
],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share",
|
||||
),
|
||||
],
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return logic.count_topic_hierarchy(topic_names)
|
||||
Reference in New Issue
Block a user