59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
This module contains utility functions
|
|
for the service implementation.
|
|
"""
|
|
from typing import Optional
|
|
from typing import TypeVar
|
|
from inse.models.openalex import Author
|
|
from . import model
|
|
from fastapi import HTTPException
|
|
from starlette.status import HTTP_404_NOT_FOUND
|
|
|
|
T = TypeVar('T')
|
|
|
|
def raise_not_found_if_none(value: Optional[T]) -> T:
|
|
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
|
|
if value == None:
|
|
raise HTTPException(HTTP_404_NOT_FOUND)
|
|
else:
|
|
return value
|
|
|
|
def get_persons_data(hit:dict):
|
|
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 = {}
|
|
orcid_val = ids.get("orcid")
|
|
if orcid_val:
|
|
ids_copy["orcid"] = str(orcid_val)
|
|
source_copy["ids"] = ids_copy
|
|
|
|
author = Author.from_dict(source_copy)
|
|
return author
|
|
|
|
from sentence_transformers import SentenceTransformer
|
|
# Sentence Transformer Model
|
|
_model: SentenceTransformer | None = None
|
|
|
|
def get_model():
|
|
global _model
|
|
if _model is None:
|
|
import os
|
|
# If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available
|
|
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
|
|
if os.path.exists("/models"):
|
|
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
|
|
os.environ["HF_HUB_OFFLINE"] = "1"
|
|
else:
|
|
# If it is set to /models, enforce offline mode as it is baked into the image
|
|
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
|
|
os.environ["HF_HUB_OFFLINE"] = "1"
|
|
|
|
_model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2")
|
|
return _model |