Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f498bb754 | ||
|
|
0ea7713f05 | ||
|
|
7613569711 | ||
|
|
63db1c9564 | ||
|
|
cac2d81b5c | ||
|
|
0b9f325045 | ||
|
|
d1255deaec | ||
|
|
6dd57bfe2b | ||
|
|
25988d6c46 | ||
|
|
f8228c5ea7 | ||
|
|
f19059164e | ||
|
|
aaab04596d | ||
|
|
6c4688185f | ||
|
|
647eb55a88 | ||
|
|
2603580587 | ||
|
|
42ecebb27f | ||
|
|
f383952547 | ||
|
|
6db4c80258 | ||
|
|
f0173cbf8a | ||
|
|
7bd8659638 | ||
|
|
074e237c84 | ||
|
|
7e8a796623 | ||
|
|
5432d814c6 | ||
|
|
9e5b2c1a21 | ||
|
|
1fa755769b | ||
|
|
cfac12e218 | ||
|
|
2ec9047565 | ||
|
|
b499fd2877 | ||
|
|
e5599845ba | ||
|
|
249fb080e9 | ||
|
|
050c68ea5e | ||
|
|
67d5306c6e | ||
|
|
64ab9325a0 | ||
|
|
1113a6a2be | ||
|
|
3702b216a0 | ||
|
|
dbaabeb9a5 | ||
|
|
677ef59440 | ||
|
|
c259635bdf | ||
|
|
17931a82b0 | ||
|
|
0502a9a553 | ||
|
|
4b8256b56e | ||
|
|
095a4c8bac | ||
|
|
473bc96e90 | ||
|
|
642fda7542 | ||
|
|
1fdd5339fa | ||
|
|
0817640449 | ||
|
|
569d73aa9f | ||
|
|
0873d25345 | ||
|
|
6c13415b1e | ||
|
|
56015846b0 | ||
|
|
7602fef243 | ||
|
|
81539d5dbd | ||
|
|
f5991ef660 | ||
|
|
6fc491fd87 | ||
|
|
163fdfaa39 | ||
|
|
e37de88cc8 |
+4
-1
@@ -12,8 +12,11 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"uvicorn~=0.29.0" \
|
||||
"pytest~=8.1.0" \
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"python-multipart~=0.0.19" \
|
||||
"beautifulsoup4==4.12.3" \
|
||||
"openai~=2.41.0" \
|
||||
"websockets==12.0" \
|
||||
"partial-json-parser==0.2.1.1.post7" \
|
||||
"sqlmodel~=0.0.33" \
|
||||
"argon2-cffi~=25.1.0"
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Index org_patents for an institution."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
|
||||
|
||||
from inse.patents.org.logic import index_org_patents_for_institution
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Index org_patents for an institution.")
|
||||
parser.add_argument(
|
||||
"--institution-id",
|
||||
required=True,
|
||||
help="OpenAlex institution ID, e.g. I62318514",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
count = await index_org_patents_for_institution(args.institution_id)
|
||||
logger.info("Finished indexing %d patents for institution %s", count, args.institution_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"organizations": [
|
||||
{
|
||||
"id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"name": "The Super Admin Organization"
|
||||
},
|
||||
{
|
||||
"name": "Universität Duisburg-Essen",
|
||||
"openalex_instution_id": "https://openalex.org/I62318514"
|
||||
},
|
||||
{
|
||||
"name": "Ruhr-Universität Bochum",
|
||||
"openalex_instution_id": "https://openalex.org/I904495901"
|
||||
},
|
||||
{
|
||||
"name": "TU Dortmund",
|
||||
"openalex_instution_id": "https://openalex.org/I200332995"
|
||||
}
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"email": "super@admin.com",
|
||||
"password": "superadmin",
|
||||
"name": "Super Admin",
|
||||
"organization_id": "b3d61e33-ef7a-42bf-b4b5-4b96e153b67c",
|
||||
"role": "SUPER_ADMIN"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.auth.model import UserRole
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
openalex_institution_id: Optional[str] = None
|
||||
|
||||
|
||||
class AccountProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
name: str
|
||||
role: UserRole
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
is_current: bool = False
|
||||
is_real_account: bool = False
|
||||
is_impersonating: bool = False
|
||||
|
||||
|
||||
class AccountPage(BaseModel):
|
||||
items: List[AccountProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateAccountRequest(BaseModel):
|
||||
email: str = Field(min_length=3)
|
||||
name: str = Field(min_length=1)
|
||||
role: UserRole = UserRole.USER
|
||||
organization_id: uuid.UUID
|
||||
password: str = Field(min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateAccountRequest(BaseModel):
|
||||
email: Optional[str] = Field(default=None, min_length=3)
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
role: Optional[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
|
||||
@@ -20,6 +20,7 @@ class AccountProfile(BaseModel):
|
||||
organization_id: uuid.UUID
|
||||
organization_name: str
|
||||
deleted: bool
|
||||
activated: bool
|
||||
is_current: bool = False
|
||||
is_real_account: bool = False
|
||||
is_impersonating: bool = False
|
||||
@@ -49,3 +50,4 @@ class UpdateAccountRequest(BaseModel):
|
||||
password: Optional[str] = Field(default=None, min_length=8)
|
||||
openalex_person_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
activated: Optional[bool] = None
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/accounts", tags=[Tags.AUTH])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/me",
|
||||
operation_id="getCurrentAccount",
|
||||
response_model=AccountProfile,
|
||||
)
|
||||
async def get_current_account(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.get_current_account(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
operation_id="listAccounts",
|
||||
response_model=AccountPage,
|
||||
)
|
||||
async def list_accounts(
|
||||
page: int = Query(default=0, ge=0),
|
||||
page_size: int = Query(default=25, ge=1, le=100),
|
||||
offset: Optional[int] = Query(default=None, ge=0),
|
||||
search: Optional[str] = Query(default=None),
|
||||
organization_id: Optional[uuid.UUID] = Query(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountPage:
|
||||
return service.list_accounts(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
search=search,
|
||||
organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
operation_id="createAccount",
|
||||
response_model=AccountProfile,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_account(
|
||||
payload: CreateAccountRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.create_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/organizations",
|
||||
operation_id="listAccountOrganizations",
|
||||
response_model=list[OrganizationProfile],
|
||||
)
|
||||
async def list_organizations(
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> list[OrganizationProfile]:
|
||||
return service.list_organizations(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{account_id}",
|
||||
operation_id="updateAccount",
|
||||
response_model=AccountProfile,
|
||||
)
|
||||
async def update_account(
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> AccountProfile:
|
||||
return service.update_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{account_id}",
|
||||
operation_id="deleteAccount",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_account(
|
||||
account_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_account(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
account_id=account_id,
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -1,311 +0,0 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, or_, select
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
||||
|
||||
from .model import (
|
||||
AccountPage,
|
||||
AccountProfile,
|
||||
CreateAccountRequest,
|
||||
OrganizationProfile,
|
||||
UpdateAccountRequest,
|
||||
)
|
||||
|
||||
|
||||
def _is_admin(role: UserRole) -> bool:
|
||||
return role in {UserRole.SUPER_ADMIN, UserRole.ADMIN}
|
||||
|
||||
|
||||
def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
|
||||
if editor_role == UserRole.SUPER_ADMIN:
|
||||
return True
|
||||
if editor_role == UserRole.ADMIN:
|
||||
return role in {UserRole.MANAGER, UserRole.USER}
|
||||
return False
|
||||
|
||||
|
||||
def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
||||
organization_name = account.organization.name if account.organization else ""
|
||||
return AccountProfile(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
name=account.name,
|
||||
role=account.role,
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
is_current=account.id == token.effective_account_id,
|
||||
is_real_account=account.id == token.real_account_id,
|
||||
is_impersonating=token.is_impersonating(),
|
||||
)
|
||||
|
||||
|
||||
def _get_account_or_404(session: Session, account_id: uuid.UUID) -> Account:
|
||||
account = session.get(Account, account_id)
|
||||
if account is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found.",
|
||||
)
|
||||
return account
|
||||
|
||||
|
||||
def _ensure_account_in_editor_scope(account: Account, token: AccessToken) -> None:
|
||||
if token.effective_role == UserRole.SUPER_ADMIN:
|
||||
return
|
||||
if (
|
||||
token.effective_role == UserRole.ADMIN
|
||||
and account.organization_id == token.effective_organization_id
|
||||
):
|
||||
return
|
||||
if account.id == token.effective_account_id:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is outside your scope.",
|
||||
)
|
||||
|
||||
|
||||
def _ensure_email_available(
|
||||
session: Session,
|
||||
email: str,
|
||||
excluded_account_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
normalized_email = email.lower().strip()
|
||||
if "@" not in normalized_email or "." not in normalized_email.rsplit("@", 1)[-1]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Invalid email address.",
|
||||
)
|
||||
|
||||
statement = select(Account).where(Account.email == normalized_email)
|
||||
if excluded_account_id is not None:
|
||||
statement = statement.where(Account.id != excluded_account_id)
|
||||
|
||||
existing = session.exec(statement).first()
|
||||
if existing is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Email address is already used by another account.",
|
||||
)
|
||||
|
||||
|
||||
def get_current_account(session: Session, access_token: AccessToken) -> AccountProfile:
|
||||
account = _get_account_or_404(session, access_token.effective_account_id)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def list_accounts(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
) -> AccountPage:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can list accounts.",
|
||||
)
|
||||
|
||||
statement = select(Account)
|
||||
count_statement = select(func.count()).select_from(Account)
|
||||
|
||||
filters = []
|
||||
if access_token.effective_role == UserRole.ADMIN:
|
||||
filters.append(Account.organization_id == access_token.effective_organization_id)
|
||||
elif organization_id is not None:
|
||||
filters.append(Account.organization_id == organization_id)
|
||||
|
||||
if search:
|
||||
pattern = f"%{search.lower().strip()}%"
|
||||
filters.append(
|
||||
or_(
|
||||
func.lower(Account.name).like(pattern),
|
||||
func.lower(Account.email).like(pattern),
|
||||
)
|
||||
)
|
||||
|
||||
for filter_expression in filters:
|
||||
statement = statement.where(filter_expression)
|
||||
count_statement = count_statement.where(filter_expression)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
accounts = session.exec(
|
||||
statement.order_by(Account.name).offset(effective_offset).limit(page_size)
|
||||
).all()
|
||||
|
||||
return AccountPage(
|
||||
items=[_account_to_profile(account, access_token) for account in accounts],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can create accounts.",
|
||||
)
|
||||
|
||||
if (
|
||||
access_token.effective_role == UserRole.ADMIN
|
||||
and payload.organization_id != access_token.effective_organization_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admins can only create accounts in their own organization.",
|
||||
)
|
||||
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email)
|
||||
|
||||
account = Account(
|
||||
email=email,
|
||||
name=payload.name.strip(),
|
||||
role=payload.role,
|
||||
organization_id=payload.organization_id,
|
||||
password_hash=auth_service._hash_password(payload.password),
|
||||
openalex_person_id=payload.openalex_person_id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def list_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
) -> list[OrganizationProfile]:
|
||||
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
||||
organizations = session.exec(
|
||||
select(Organization)
|
||||
.where(Organization.deleted == False) # noqa: E712
|
||||
.order_by(Organization.name)
|
||||
).all()
|
||||
elif access_token.effective_role == UserRole.ADMIN:
|
||||
organization = session.get(Organization, access_token.effective_organization_id)
|
||||
organizations = [organization] if organization and not organization.deleted else []
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return [
|
||||
OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
openalex_institution_id=organization.openalex_institution_id,
|
||||
)
|
||||
for organization in organizations
|
||||
]
|
||||
|
||||
|
||||
def update_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
payload: UpdateAccountRequest,
|
||||
) -> AccountProfile:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
is_self_update = account.id == access_token.effective_account_id
|
||||
can_admin_update = _is_admin(access_token.effective_role)
|
||||
|
||||
if not can_admin_update and not is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if payload.email is not None:
|
||||
email = payload.email.lower().strip()
|
||||
_ensure_email_available(session, email, excluded_account_id=account.id)
|
||||
account.email = email
|
||||
|
||||
if payload.name is not None:
|
||||
account.name = payload.name.strip()
|
||||
|
||||
if payload.password is not None:
|
||||
account.password_hash = auth_service._hash_password(payload.password)
|
||||
account.epoch += 1
|
||||
|
||||
if payload.openalex_person_id is not None:
|
||||
account.openalex_person_id = payload.openalex_person_id
|
||||
|
||||
if payload.role is not None:
|
||||
if not can_admin_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You cannot assign this role.",
|
||||
)
|
||||
account.role = payload.role
|
||||
account.epoch += 1
|
||||
|
||||
if payload.organization_id is not None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
organization = session.get(Organization, payload.organization_id)
|
||||
if organization is None or organization.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
account.organization_id = payload.organization_id
|
||||
account.epoch += 1
|
||||
|
||||
if payload.deleted is not None:
|
||||
if not can_admin_update or is_self_update:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
account.deleted = payload.deleted
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return _account_to_profile(account, access_token)
|
||||
|
||||
|
||||
def delete_account(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
account_id: uuid.UUID,
|
||||
) -> None:
|
||||
account = _get_account_or_404(session, account_id)
|
||||
_ensure_account_in_editor_scope(account, access_token)
|
||||
|
||||
if (
|
||||
not _is_admin(access_token.effective_role)
|
||||
or account.id == access_token.effective_account_id
|
||||
):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
account.deleted = True
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
session.commit()
|
||||
@@ -38,6 +38,7 @@ def _account_to_profile(account: Account, token: AccessToken) -> AccountProfile:
|
||||
organization_id=account.organization_id,
|
||||
organization_name=organization_name,
|
||||
deleted=account.deleted,
|
||||
activated=account.activated,
|
||||
is_current=account.id == token.effective_account_id,
|
||||
is_real_account=account.id == token.real_account_id,
|
||||
is_impersonating=token.is_impersonating(),
|
||||
@@ -108,17 +109,21 @@ def list_accounts(
|
||||
search: Optional[str] = None,
|
||||
organization_id: Optional[uuid.UUID] = None,
|
||||
) -> AccountPage:
|
||||
if not _is_admin(access_token.effective_role):
|
||||
if access_token.effective_role not in {
|
||||
UserRole.SUPER_ADMIN,
|
||||
UserRole.ADMIN,
|
||||
UserRole.MANAGER,
|
||||
}:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only admins can list accounts.",
|
||||
detail="Only managers and admins can list accounts.",
|
||||
)
|
||||
|
||||
statement = select(Account)
|
||||
count_statement = select(func.count()).select_from(Account)
|
||||
|
||||
filters = []
|
||||
if access_token.effective_role == UserRole.ADMIN:
|
||||
if access_token.effective_role in {UserRole.ADMIN, UserRole.MANAGER}:
|
||||
filters.append(Account.organization_id == access_token.effective_organization_id)
|
||||
elif organization_id is not None:
|
||||
filters.append(Account.organization_id == organization_id)
|
||||
@@ -207,7 +212,7 @@ def list_organizations(
|
||||
if access_token.effective_role == UserRole.SUPER_ADMIN:
|
||||
organizations = session.exec(
|
||||
select(Organization)
|
||||
.where(Organization.deleted == False) # noqa: E712
|
||||
.where(Organization.deleted.is_not(True))
|
||||
.order_by(Organization.name)
|
||||
).all()
|
||||
elif access_token.effective_role == UserRole.ADMIN:
|
||||
@@ -285,6 +290,15 @@ def update_account(
|
||||
account.deleted = payload.deleted
|
||||
account.epoch += 1
|
||||
|
||||
if payload.activated is not None and payload.activated != account.activated:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN or is_self_update:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only super admins can activate or deactivate other accounts.",
|
||||
)
|
||||
account.activated = payload.activated
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.account_management import service
|
||||
from inse.account_management.model import UpdateAccountRequest
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as database_session:
|
||||
yield database_session
|
||||
|
||||
|
||||
def access_token(role, account_id, organization_id):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_account_id=account_id,
|
||||
real_account_id=account_id,
|
||||
effective_organization_id=organization_id,
|
||||
is_impersonating=lambda: False,
|
||||
)
|
||||
|
||||
|
||||
def create_accounts(session):
|
||||
organization = Organization(name="Test organization")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
superadmin = Account(
|
||||
email="superadmin@example.org",
|
||||
name="Superadmin",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.SUPER_ADMIN,
|
||||
)
|
||||
user = Account(
|
||||
email="user@example.org",
|
||||
name="User",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(superadmin)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return organization, superadmin, user
|
||||
|
||||
|
||||
def test_accounts_are_activated_by_default(session):
|
||||
_, _, user = create_accounts(session)
|
||||
assert user.activated is True
|
||||
|
||||
|
||||
def test_superadmin_can_deactivate_and_reactivate_account(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
token = access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id)
|
||||
|
||||
profile = service.update_account(
|
||||
session, token, user.id, UpdateAccountRequest(activated=False)
|
||||
)
|
||||
assert profile.activated is False
|
||||
assert user.epoch == 1
|
||||
|
||||
profile = service.update_account(
|
||||
session, token, user.id, UpdateAccountRequest(activated=True)
|
||||
)
|
||||
assert profile.activated is True
|
||||
assert user.epoch == 2
|
||||
|
||||
|
||||
def test_non_superadmin_cannot_change_activation(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
admin = Account(
|
||||
email="admin@example.org",
|
||||
name="Admin",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.ADMIN,
|
||||
)
|
||||
session.add(admin)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.update_account(
|
||||
session,
|
||||
access_token(UserRole.ADMIN, admin.id, organization.id),
|
||||
user.id,
|
||||
UpdateAccountRequest(activated=False),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert user.activated is True
|
||||
|
||||
|
||||
def test_superadmin_cannot_deactivate_own_account(session):
|
||||
organization, superadmin, _ = create_accounts(session)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.update_account(
|
||||
session,
|
||||
access_token(UserRole.SUPER_ADMIN, superadmin.id, organization.id),
|
||||
superadmin.id,
|
||||
UpdateAccountRequest(activated=False),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert superadmin.activated is True
|
||||
|
||||
|
||||
def test_manager_only_lists_accounts_from_own_organization(session):
|
||||
organization, superadmin, user = create_accounts(session)
|
||||
manager = Account(
|
||||
email="manager@example.org",
|
||||
name="Manager",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
role=UserRole.MANAGER,
|
||||
)
|
||||
other_organization = Organization(name="Other organization")
|
||||
session.add(other_organization)
|
||||
session.flush()
|
||||
other_user = Account(
|
||||
email="other@example.org",
|
||||
name="Other User",
|
||||
password_hash="hash",
|
||||
organization_id=other_organization.id,
|
||||
)
|
||||
session.add(manager)
|
||||
session.add(other_user)
|
||||
session.commit()
|
||||
|
||||
result = service.list_accounts(
|
||||
session,
|
||||
access_token(UserRole.MANAGER, manager.id, organization.id),
|
||||
page=0,
|
||||
page_size=25,
|
||||
organization_id=other_organization.id,
|
||||
)
|
||||
|
||||
assert {profile.id for profile in result.items} == {
|
||||
account.id for account in [superadmin, user, manager]
|
||||
}
|
||||
assert other_user.id not in {profile.id for profile in result.items}
|
||||
|
||||
|
||||
def test_user_cannot_list_accounts(session):
|
||||
organization, _, user = create_accounts(session)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.list_accounts(
|
||||
session,
|
||||
access_token(UserRole.USER, user.id, organization.id),
|
||||
page=0,
|
||||
page_size=25,
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_superadmin_lists_all_active_organizations_for_selectbox(session):
|
||||
first = Organization(name="Alpha")
|
||||
second = Organization(name="Beta")
|
||||
deleted = Organization(name="Deleted", deleted=True)
|
||||
session.add(first)
|
||||
session.add(second)
|
||||
session.add(deleted)
|
||||
session.commit()
|
||||
|
||||
organizations = service.list_organizations(
|
||||
session,
|
||||
access_token(UserRole.SUPER_ADMIN, first.id, first.id),
|
||||
)
|
||||
|
||||
assert [organization.name for organization in organizations] == ["Alpha", "Beta"]
|
||||
@@ -1,29 +0,0 @@
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
|
||||
|
||||
def send_email(
|
||||
recipient: str,
|
||||
subject: str,
|
||||
body: str,
|
||||
smtp_server: str = "localhost",
|
||||
smtp_port: int = 25,
|
||||
sender: str = "no-reply@smartguide.local",
|
||||
username: str | None = None,
|
||||
password: str | None = None,
|
||||
use_tls: bool = False,
|
||||
):
|
||||
msg = EmailMessage()
|
||||
msg["From"] = sender
|
||||
msg["To"] = recipient
|
||||
msg["Subject"] = subject
|
||||
msg.set_content(body)
|
||||
|
||||
with smtplib.SMTP(smtp_server, smtp_port) as server:
|
||||
if use_tls:
|
||||
server.starttls()
|
||||
|
||||
if username and password:
|
||||
server.login(username, password)
|
||||
|
||||
server.send_message(msg)
|
||||
@@ -1,212 +0,0 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import Field, Relationship, SQLModel
|
||||
|
||||
|
||||
class UserRole(StrEnum):
|
||||
SUPER_ADMIN = "SUPER_ADMIN"
|
||||
ADMIN = "ADMIN"
|
||||
MANAGER = "MANAGER"
|
||||
USER = "USER"
|
||||
|
||||
|
||||
class TokenType(StrEnum):
|
||||
ID_TOKEN = "ID"
|
||||
REFRESH_TOKEN = "REFRESH"
|
||||
ACCESS_TOKEN = "ACCESS"
|
||||
|
||||
|
||||
class Durable(SQLModel):
|
||||
deleted: bool = Field(
|
||||
default=False,
|
||||
nullable=False,
|
||||
index=True,
|
||||
description="Indicates whether the record is marked as deleted.",
|
||||
)
|
||||
|
||||
|
||||
class Organization(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The unique name of the organization.",
|
||||
)
|
||||
openalex_institution_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the institution associated with the organization.",
|
||||
)
|
||||
|
||||
accounts: List["Account"] = Relationship(back_populates="organization")
|
||||
|
||||
|
||||
class Account(Durable, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the account. Generated automatically if not provided.",
|
||||
)
|
||||
email: str = Field(
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The email address associated with the account.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The name of the account holder.",
|
||||
)
|
||||
openalex_person_id: str | None = Field(
|
||||
default=None,
|
||||
index=True,
|
||||
description="The OpenAlex ID of the person associated with the account.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the account. Used for versioning of tokens.",
|
||||
)
|
||||
password_hash: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The hashed password for the account using Argon2id algorithm.",
|
||||
# https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
|
||||
)
|
||||
|
||||
organization_id: uuid.UUID = Field(
|
||||
foreign_key="organization.id",
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization strictly associated with this account.",
|
||||
)
|
||||
role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this account holds within its organization.",
|
||||
)
|
||||
|
||||
organization: Organization = Relationship(back_populates="accounts")
|
||||
|
||||
|
||||
class Secret(SQLModel, table=True):
|
||||
id: uuid.UUID | None = Field(
|
||||
default_factory=uuid.uuid4,
|
||||
primary_key=True,
|
||||
description="Unique identifier for the secret. Generated automatically if not provided.",
|
||||
)
|
||||
account_id: uuid.UUID = Field(
|
||||
foreign_key="account.id",
|
||||
unique=True, # Ensure that each account can have only one associated secret
|
||||
nullable=False,
|
||||
description="The unique identifier of the account associated with this secret.",
|
||||
)
|
||||
secret_value: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The actual secret value. This should be stored securely and encrypted.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the secret will expire.",
|
||||
)
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
token_type: TokenType = Field(
|
||||
description="The type of the token (ID, Refresh, or Access).",
|
||||
)
|
||||
real_account_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the real account associated with this token.",
|
||||
)
|
||||
expires_at: datetime = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The timestamp indicating when the token will expire.",
|
||||
)
|
||||
epoch: int = Field(
|
||||
default=0,
|
||||
nullable=False,
|
||||
description="The epoch value for the token. Used for versioning of tokens.",
|
||||
)
|
||||
user_fingerprint_hash: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||
)
|
||||
raw_token: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
description="The raw token string.",
|
||||
)
|
||||
|
||||
|
||||
class IdToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ID_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ID_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class AccessToken(Token):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.ACCESS_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always ACCESS_TOKEN for this class.",
|
||||
)
|
||||
effective_account_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.",
|
||||
)
|
||||
effective_role: UserRole = Field(
|
||||
default=UserRole.USER,
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="The specific role this access token grants within its organization.",
|
||||
)
|
||||
effective_organization_id: uuid.UUID = Field(
|
||||
nullable=False,
|
||||
description="The unique identifier of the organization associated with this access token.",
|
||||
)
|
||||
|
||||
def is_impersonating(self) -> bool:
|
||||
"""Determine if the access token is being used for impersonation.
|
||||
|
||||
Returns:
|
||||
bool: True if the effective account ID differs from the real account ID, indicating impersonation; False otherwise.
|
||||
"""
|
||||
return self.effective_account_id != self.real_account_id
|
||||
|
||||
|
||||
class RefreshToken(AccessToken):
|
||||
token_type: TokenType = Field(
|
||||
default=TokenType.REFRESH_TOKEN,
|
||||
const=True,
|
||||
description="The type of the token, which is always REFRESH_TOKEN for this class.",
|
||||
)
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
id_token: IdToken = Field(description="The ID token issued upon successful login.")
|
||||
|
||||
|
||||
class AccessResponse(BaseModel):
|
||||
access_token: AccessToken = Field(
|
||||
description="The access token issued upon successful authentication."
|
||||
)
|
||||
refresh_token: RefreshToken = Field(
|
||||
description="The refresh token issued alongside the access token for obtaining new access tokens."
|
||||
)
|
||||
@@ -77,6 +77,12 @@ class Account(Durable, table=True):
|
||||
nullable=False,
|
||||
description="The epoch value for the account. Used for versioning of tokens.",
|
||||
)
|
||||
activated: bool = Field(
|
||||
default=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
description="Indicates whether the account is allowed to authenticate.",
|
||||
)
|
||||
password_hash: str = Field(
|
||||
index=False,
|
||||
nullable=False,
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, 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,
|
||||
IdToken,
|
||||
LoginResponse,
|
||||
RefreshToken,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/auth/v2", tags=[Tags.AUTH])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/request-otk",
|
||||
summary="Request One-Time Key",
|
||||
description="Request a one-time key (OTK) for authentication using email and password.",
|
||||
operation_id="requestOtk",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "One-time key requested successfully."}
|
||||
},
|
||||
)
|
||||
async def request_otk(
|
||||
session: SessionDep,
|
||||
email: Annotated[str, Body(description="User's email address")],
|
||||
password: Annotated[str, Body(description="User's password")],
|
||||
):
|
||||
return auth_service.request_otk(session=session, email=email, password=password)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
summary="Login with One-Time Key",
|
||||
description="Login using a one-time key (OTK) sent to the user's email.",
|
||||
operation_id="login",
|
||||
responses={status.HTTP_200_OK: {"description": "Login successful."}},
|
||||
)
|
||||
async def login(
|
||||
session: SessionDep,
|
||||
response: Response,
|
||||
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
email_code: Annotated[
|
||||
str, Body(embed=True, description="One-time code sent to user's email")
|
||||
],
|
||||
) -> LoginResponse:
|
||||
return auth_service.login(
|
||||
session=session, response=response, account_id=account_id, email_code=email_code
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/access",
|
||||
summary="Get Access Token",
|
||||
description="Retrieve an access token for the authenticated user.",
|
||||
operation_id="getAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||
},
|
||||
)
|
||||
async def get_action_tokens(
|
||||
response: Response,
|
||||
session: SessionDep,
|
||||
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
effective_account_id: Annotated[
|
||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||
],
|
||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||
) -> AccessResponse:
|
||||
logger.debug(
|
||||
"Generating access token for real_account_id=%s, effective_account_id=%s, id_token=%s",
|
||||
real_account_id,
|
||||
effective_account_id,
|
||||
id_token,
|
||||
)
|
||||
|
||||
return auth_service.get_access_token(
|
||||
response=response,
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
id_token=id_token,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/refresh",
|
||||
summary="Refresh Access Token",
|
||||
description="Refresh the access token using a valid refresh token.",
|
||||
operation_id="refreshAccessToken",
|
||||
responses={
|
||||
status.HTTP_200_OK: {"description": "Access token refreshed successfully."}
|
||||
},
|
||||
)
|
||||
async def refresh_access_token(
|
||||
refresh_token: Annotated[
|
||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||
],
|
||||
) -> AccessToken:
|
||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
summary="Logout",
|
||||
description="Logout the authenticated user.",
|
||||
operation_id="logout",
|
||||
responses={status.HTTP_200_OK: {"description": "Logout successful."}},
|
||||
)
|
||||
async def logout(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.logout(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/change-password",
|
||||
summary="Change Password",
|
||||
description="Change the user's password and invalidate existing tokens.",
|
||||
operation_id="changePassword",
|
||||
responses={status.HTTP_200_OK: {"description": "Password changed successfully."}},
|
||||
)
|
||||
async def change_password(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
current_password: Annotated[
|
||||
str,
|
||||
Body(description="Current password"),
|
||||
],
|
||||
new_password: Annotated[
|
||||
str,
|
||||
Body(description="New password", min_length=8),
|
||||
],
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.change_password(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -180,7 +180,11 @@ def request_otk(session: Session, email: str, password: str):
|
||||
|
||||
logger.debug("OTK request for email %s: account found: %s", email, account)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
if (
|
||||
account is None
|
||||
or account.deleted
|
||||
or account.id is None
|
||||
):
|
||||
logger.warning("OTK request failed for email %s: account not found", email)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -196,6 +200,13 @@ def request_otk(session: Session, email: str, password: str):
|
||||
detail="Invalid email or password",
|
||||
)
|
||||
|
||||
if not account.activated:
|
||||
logger.warning("OTK request rejected for deactivated account %s", account.id)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is deactivated and cannot log in.",
|
||||
)
|
||||
|
||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||
print(otk_code)
|
||||
|
||||
@@ -300,7 +311,7 @@ def login(
|
||||
)
|
||||
|
||||
account = _get_active_account(session, account_id)
|
||||
if not account or account.deleted or account.id is None:
|
||||
if not account or account.deleted or not account.activated or account.id is None:
|
||||
logger.warning("Login failed: account is not active %s", account_id)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
@@ -469,7 +480,12 @@ def _get_account_epoch(
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
if (
|
||||
account is None
|
||||
or account.deleted
|
||||
or not account.activated
|
||||
or account.id is None
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.epoch
|
||||
@@ -487,7 +503,7 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
if not account or account.deleted or not account.activated or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.role
|
||||
@@ -505,7 +521,7 @@ def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.U
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
if not account or account.deleted or not account.activated or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.organization_id
|
||||
@@ -525,12 +541,18 @@ def _is_valid_impersonation(
|
||||
bool: True if impersonation is allowed, False otherwise.
|
||||
"""
|
||||
real_account = session.get(Account, real_account_id)
|
||||
if not real_account or real_account.deleted or real_account.id is None:
|
||||
if (
|
||||
not real_account
|
||||
or real_account.deleted
|
||||
or not real_account.activated
|
||||
or real_account.id is None
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
effective_account = session.get(Account, effective_account_id)
|
||||
if (
|
||||
not effective_account
|
||||
or effective_account.deleted
|
||||
or not effective_account.activated
|
||||
or effective_account.id is None
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
@@ -980,6 +1002,9 @@ def _verify_fp_token(
|
||||
account_id=epoch_account_id,
|
||||
)
|
||||
|
||||
if uuid.UUID(real_account_id) != epoch_account_id:
|
||||
_get_active_account(session, uuid.UUID(real_account_id))
|
||||
|
||||
token_epoch = payload.get(EPOCH_KEY)
|
||||
if token_epoch is None or token_epoch != current_account_epoch:
|
||||
raise HTTPException(
|
||||
@@ -1016,7 +1041,12 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted or account.id is None:
|
||||
if (
|
||||
account is None
|
||||
or account.deleted
|
||||
or not account.activated
|
||||
or account.id is None
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
@@ -1071,15 +1101,31 @@ def change_password(
|
||||
account = _get_active_account(session, access_token.effective_account_id)
|
||||
|
||||
if not _verify_password(current_password, account.password_hash):
|
||||
logger.warning(
|
||||
"Password change failed: current password is incorrect for account %s",
|
||||
account.id,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
|
||||
if current_password == new_password:
|
||||
logger.warning(
|
||||
"Password change failed: new password is the same as the current password for account %s",
|
||||
account.id,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="New password cannot be the same as the current password.",
|
||||
)
|
||||
|
||||
account.password_hash = _hash_password(new_password)
|
||||
account.epoch += 1
|
||||
|
||||
session.add(account)
|
||||
session.commit()
|
||||
|
||||
logger.info("Password changed successfully for account %s", account.id)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -1,517 +0,0 @@
|
||||
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
|
||||
from datetime import timedelta
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import (
|
||||
Account,
|
||||
Organization,
|
||||
Secret,
|
||||
IdToken,
|
||||
AccessToken,
|
||||
RefreshToken,
|
||||
UserRole,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def settings_backup():
|
||||
orig = config_module.get_settings()
|
||||
backup = config_module.Settings(**orig.model_dump())
|
||||
yield backup
|
||||
for k, v in backup.model_dump().items():
|
||||
setattr(config_module.settings, k, v)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def in_memory_session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
def create_org_and_account(
|
||||
session: Session, email: str, password: str, role=UserRole.USER
|
||||
):
|
||||
org = Organization(name=f"Test Org {email}")
|
||||
session.add(org)
|
||||
session.flush()
|
||||
assert org.id is not None
|
||||
pwd_hash = auth_service._hash_password(password)
|
||||
acc = Account(
|
||||
email=email,
|
||||
name="Tester",
|
||||
organization_id=org.id,
|
||||
password_hash=pwd_hash,
|
||||
role=role,
|
||||
)
|
||||
session.add(acc)
|
||||
session.commit()
|
||||
session.refresh(acc)
|
||||
return org, acc
|
||||
|
||||
|
||||
def test_hash_and_verify_password():
|
||||
pw = "s3cret-password"
|
||||
h = auth_service._hash_password(pw)
|
||||
assert auth_service._verify_password(pw, h) is True
|
||||
assert auth_service._verify_password("wrong", h) is False
|
||||
|
||||
|
||||
def test_request_otk_and_login_flow(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "test-hmac-key"
|
||||
config_module.settings.token_issuer_id = "test-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "user@example.com"
|
||||
password = "hunter2"
|
||||
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
resp = auth_service.request_otk(in_memory_session, email, password)
|
||||
assert resp["status"] == "ok"
|
||||
assert resp["account_id"] == str(acc.id)
|
||||
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
response = Response()
|
||||
|
||||
login_result = auth_service.login(
|
||||
in_memory_session, response, acc.id, secret.secret_value
|
||||
)
|
||||
assert isinstance(login_result.id_token, IdToken)
|
||||
assert login_result.id_token.real_account_id == acc.id
|
||||
assert login_result.id_token.user_fingerprint_hash is not None
|
||||
|
||||
|
||||
def test_token_build_verify_and_fp_checks(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "another-key"
|
||||
config_module.settings.token_issuer_id = "issuer-2"
|
||||
|
||||
email = "fp@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
assert isinstance(id_token, IdToken)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
assert cookie_header is not None
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0]
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
req = DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value})
|
||||
payload = auth_service._verify_fp_token(
|
||||
request=req,
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id)
|
||||
|
||||
with pytest.raises(Exception):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({}),
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_access_and_refresh_token_flow(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "flow-key"
|
||||
config_module.settings.token_issuer_id = "flow-issuer"
|
||||
|
||||
email = "flow@example.com"
|
||||
password = "pwflow"
|
||||
org, acc = create_org_and_account(
|
||||
in_memory_session, email, password, role=UserRole.ADMIN
|
||||
)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
access_response = auth_service.get_access_token(
|
||||
response, in_memory_session, id_token, acc.id
|
||||
)
|
||||
assert isinstance(access_response.access_token, AccessToken)
|
||||
assert isinstance(access_response.refresh_token, RefreshToken)
|
||||
|
||||
refreshed = auth_service.refresh_access_token(access_response.refresh_token)
|
||||
assert isinstance(refreshed, AccessToken)
|
||||
assert refreshed.real_account_id == access_response.access_token.real_account_id
|
||||
|
||||
|
||||
def test_logout_and_change_password(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "logout-key"
|
||||
config_module.settings.token_issuer_id = "logout-issuer"
|
||||
|
||||
email = "logout@example.com"
|
||||
password = "oldpw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
access_resp = auth_service.get_access_token(
|
||||
response, in_memory_session, id_token, acc.id
|
||||
)
|
||||
|
||||
before_epoch = acc.epoch
|
||||
out = auth_service.logout(in_memory_session, access_resp.access_token)
|
||||
assert out["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert acc.epoch == before_epoch + 1
|
||||
|
||||
new_pw = "newpw123"
|
||||
acc.password_hash = auth_service._hash_password(password)
|
||||
in_memory_session.add(acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
change_out = auth_service.change_password(
|
||||
in_memory_session, access_resp.access_token, password, new_pw
|
||||
)
|
||||
assert change_out["status"] == "ok"
|
||||
in_memory_session.refresh(acc)
|
||||
assert auth_service._verify_password(new_pw, acc.password_hash)
|
||||
|
||||
|
||||
def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
||||
email = "nope@example.com"
|
||||
password = "rightpw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||
|
||||
|
||||
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "expired-key"
|
||||
config_module.settings.token_issuer_id = "expired-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "expired@example.com"
|
||||
password = "pw"
|
||||
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)
|
||||
secret = Secret(account_id=acc.id, secret_value="000000", expires_at=expired_at)
|
||||
in_memory_session.add(secret)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.login(in_memory_session, Response(), acc.id, "000000")
|
||||
|
||||
|
||||
def test_verify_fp_token_cookie_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "cookie-key"
|
||||
config_module.settings.token_issuer_id = "cookie-issuer"
|
||||
|
||||
email = "cookie@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: "badcookie"}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_token_epoch_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "epoch-key"
|
||||
config_module.settings.token_issuer_id = "epoch-issuer"
|
||||
|
||||
email = "epoch@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
acc.epoch += 1
|
||||
in_memory_session.add(acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=id_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_token_signature_raises(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "sig-key"
|
||||
config_module.settings.token_issuer_id = "sig-issuer"
|
||||
|
||||
email = "sig@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, acc.id, acc.epoch)
|
||||
|
||||
cookie_header = None
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() == "set-cookie":
|
||||
cookie_header = value
|
||||
break
|
||||
cookie_value = cookie_header.split("=")[1].split(";")[0] # type: ignore
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
bad_token = id_token.raw_token + "x"
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ID_FP_COOKIE_KEY: cookie_value}), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=bad_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_impersonation_rules(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "imp-key"
|
||||
config_module.settings.token_issuer_id = "imp-issuer"
|
||||
|
||||
org_a, real_acc = create_org_and_account(in_memory_session, "real@a.test", "pw")
|
||||
assert real_acc.id is not None
|
||||
org_b, eff_acc = create_org_and_account(in_memory_session, "eff@b.test", "pw")
|
||||
assert eff_acc.id is not None
|
||||
|
||||
response = Response()
|
||||
id_token = auth_service._build_id_token(response, real_acc.id, real_acc.epoch)
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.get_access_token(
|
||||
response,
|
||||
in_memory_session,
|
||||
id_token,
|
||||
real_acc.id,
|
||||
effective_account_id=eff_acc.id,
|
||||
)
|
||||
|
||||
real_acc.role = UserRole.SUPER_ADMIN
|
||||
in_memory_session.add(real_acc)
|
||||
in_memory_session.commit()
|
||||
|
||||
access_resp = auth_service.get_access_token(
|
||||
response,
|
||||
in_memory_session,
|
||||
id_token,
|
||||
real_acc.id,
|
||||
effective_account_id=eff_acc.id,
|
||||
)
|
||||
assert isinstance(access_resp.access_token, AccessToken)
|
||||
|
||||
|
||||
def test_otk_regeneration_and_reuse(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "regen-key"
|
||||
config_module.settings.token_issuer_id = "regen-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "regen@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret1 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret1 is not None
|
||||
first_value = secret1.secret_value
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret2 = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
|
||||
assert secret2 is not None
|
||||
assert first_value != secret2.secret_value
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service.login(in_memory_session, Response(), acc.id, first_value)
|
||||
|
||||
login_res = auth_service.login(
|
||||
in_memory_session, Response(), acc.id, secret2.secret_value
|
||||
)
|
||||
assert isinstance(login_res.id_token, IdToken)
|
||||
|
||||
|
||||
def test_otk_deleted_after_login(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "del-key"
|
||||
config_module.settings.token_issuer_id = "del-issuer"
|
||||
config_module.settings.skip_otk_validation = False
|
||||
|
||||
email = "single@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
secret = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert secret is not None
|
||||
|
||||
auth_service.login(in_memory_session, Response(), acc.id, secret.secret_value)
|
||||
post = in_memory_session.exec(
|
||||
select(Secret).where(Secret.account_id == acc.id)
|
||||
).first()
|
||||
assert post is None
|
||||
|
||||
|
||||
def test_access_token_fp_mismatch(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "act-key"
|
||||
config_module.settings.token_issuer_id = "act-issuer"
|
||||
|
||||
email = "act@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
raw = auth_service._set_act_fp_cookie(response)
|
||||
|
||||
access_token = auth_service._build_access_token(
|
||||
real_account_id=acc.id,
|
||||
effective_account_id=acc.id,
|
||||
effective_role=acc.role,
|
||||
effective_organization_id=acc.organization_id,
|
||||
epoch=acc.epoch,
|
||||
user_fingerprint_hash=raw,
|
||||
)
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq({auth_service.ACT_FP_COOKIE_KEY: "wrongcookie"}), # type: ignore
|
||||
cookie_key=auth_service.ACT_FP_COOKIE_KEY,
|
||||
token=access_token.raw_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_expired_jwt_token_raises(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "exp-key"
|
||||
config_module.settings.token_issuer_id = "exp-issuer"
|
||||
|
||||
email = "exp@example.com"
|
||||
password = "pw"
|
||||
org, acc = create_org_and_account(in_memory_session, email, password)
|
||||
assert acc.id is not None
|
||||
|
||||
response = Response()
|
||||
cookie_raw = auth_service._set_id_fp_cookie(response)
|
||||
past = _dt.datetime.now(_dt.timezone.utc) - timedelta(minutes=5)
|
||||
payload = {
|
||||
auth_service.REAL_ACCOUNT_ID_KEY: str(acc.id),
|
||||
auth_service.EPOCH_KEY: acc.epoch,
|
||||
auth_service.USER_FINGERPRINT_HASH_KEY: cookie_raw,
|
||||
}
|
||||
bad_token = auth_service._build_token(
|
||||
payload=payload,
|
||||
expiration_datetime=past,
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
|
||||
class DummyReq:
|
||||
def __init__(self, cookies):
|
||||
self.cookies = cookies
|
||||
|
||||
with pytest.raises(HTTPException):
|
||||
auth_service._verify_fp_token(
|
||||
request=DummyReq(
|
||||
{
|
||||
auth_service.ID_FP_COOKIE_KEY: response.headers["set-cookie"]
|
||||
.split("=")[1]
|
||||
.split(";")[0]
|
||||
}
|
||||
), # type: ignore
|
||||
cookie_key=auth_service.ID_FP_COOKIE_KEY,
|
||||
token=bad_token,
|
||||
session=in_memory_session,
|
||||
)
|
||||
|
||||
|
||||
def test_missing_hmac_key_raises_value_error(settings_backup):
|
||||
orig = config_module.get_settings()
|
||||
saved = orig.token_hmac_key
|
||||
config_module.settings.token_hmac_key = None
|
||||
with pytest.raises(ValueError):
|
||||
auth_service._build_token(
|
||||
payload={},
|
||||
expiration_datetime=_dt.datetime.now(_dt.timezone.utc),
|
||||
token_type=auth_service.TokenType.ID_TOKEN,
|
||||
)
|
||||
config_module.settings.token_hmac_key = saved
|
||||
|
||||
|
||||
def test_get_account_epoch_not_found(in_memory_session):
|
||||
random_id = uuid.uuid4()
|
||||
with pytest.raises(Exception):
|
||||
auth_service._get_account_epoch(in_memory_session, random_id)
|
||||
@@ -210,6 +210,35 @@ def test_request_otk_invalid_credentials(in_memory_session, settings_backup):
|
||||
auth_service.request_otk(in_memory_session, email, "wrongpw")
|
||||
|
||||
|
||||
def test_deactivated_account_cannot_request_otk(in_memory_session):
|
||||
email = "inactive@example.com"
|
||||
password = "rightpw"
|
||||
_, account = create_org_and_account(in_memory_session, email, password)
|
||||
account.activated = False
|
||||
in_memory_session.add(account)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
auth_service.request_otk(in_memory_session, email, password)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
assert error.value.detail == "Account is deactivated and cannot log in."
|
||||
|
||||
|
||||
def test_deactivated_account_is_rejected_by_active_account_lookup(in_memory_session):
|
||||
_, account = create_org_and_account(
|
||||
in_memory_session, "inactive-lookup@example.com", "password"
|
||||
)
|
||||
account.activated = False
|
||||
in_memory_session.add(account)
|
||||
in_memory_session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
auth_service._get_active_account(in_memory_session, account.id)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_login_with_expired_secret(in_memory_session, settings_backup):
|
||||
config_module.settings.token_hmac_key = "expired-key"
|
||||
config_module.settings.token_issuer_id = "expired-issuer"
|
||||
|
||||
@@ -30,6 +30,7 @@ class Settings(BaseSettings):
|
||||
openalex_works_search_index: str = "openalex-works*"
|
||||
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_timeout_seconds: float = 30.0
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlmodel import SQLModel, Session, create_engine
|
||||
|
||||
from inse import config
|
||||
@@ -18,6 +19,15 @@ engine = create_engine(
|
||||
def create_db_and_tables():
|
||||
"""Creates the database and tables based on the SQLModel metadata."""
|
||||
SQLModel.metadata.create_all(engine)
|
||||
columns = {column["name"] for column in inspect(engine).get_columns("account")}
|
||||
if "activated" not in columns:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"ALTER TABLE account ADD COLUMN activated "
|
||||
"BOOLEAN NOT NULL DEFAULT TRUE"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def get_session():
|
||||
|
||||
@@ -8,6 +8,7 @@ import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
@@ -59,17 +60,34 @@ async def list_institutions(
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
data = await openalex_client.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
try:
|
||||
data = await openalex_client.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex institutions request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_institutions_response(data)
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Elasticsearch client for OpenAlex institutions."""
|
||||
"""
|
||||
HTTP client for OpenAlex institutions.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class OpenAlexInstitutionsClient:
|
||||
def __init__(self, index: str | ESIndex = ESIndex.OPENALEX_INSTITUTIONS):
|
||||
self.index = index
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = (
|
||||
api_key if api_key is not None else config.settings.openalex_api_key
|
||||
)
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
|
||||
def list_institutions_query(
|
||||
def list_institutions_params(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -25,144 +43,60 @@ class OpenAlexInstitutionsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
must: list[dict[str, Any]] = []
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
if search:
|
||||
must.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": [
|
||||
"display_name^3",
|
||||
"display_name_alternatives^2",
|
||||
"display_name_acronyms^2",
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must or [{"match_all": {}}],
|
||||
"filter": self._filters(filter),
|
||||
}
|
||||
}
|
||||
if sample is not None:
|
||||
query = {
|
||||
"function_score": {
|
||||
"query": query,
|
||||
"random_score": {"seed": sample},
|
||||
}
|
||||
}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"from": max((page or 1) - 1, 0) * per_page,
|
||||
"size": per_page,
|
||||
"track_total_hits": True,
|
||||
}
|
||||
if select:
|
||||
body["_source"] = [
|
||||
field.strip() for field in select.split(",") if field.strip()
|
||||
]
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
body["sort"] = self._sort(sort)
|
||||
if cursor and cursor != "*":
|
||||
body["search_after"] = cursor.split(",")
|
||||
body.pop("from", None)
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {
|
||||
"field": self._keyword_field(group_by),
|
||||
"size": per_page,
|
||||
}
|
||||
}
|
||||
}
|
||||
return body
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
async def list_institutions(self, **kwargs: Any) -> dict[str, Any]:
|
||||
response = await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=self.list_institutions_query(**kwargs),
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_value = hits_block.get("total", 0)
|
||||
total = (
|
||||
total_value.get("value", 0)
|
||||
if isinstance(total_value, dict)
|
||||
else total_value
|
||||
)
|
||||
result: dict[str, Any] = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": kwargs.get("page", 1),
|
||||
"per_page": kwargs.get("per_page", 25),
|
||||
"next_cursor": self._next_cursor(hits),
|
||||
},
|
||||
"results": [hit.get("_source", {}) for hit in hits],
|
||||
}
|
||||
return params
|
||||
|
||||
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||
if buckets is not None:
|
||||
result["group_by"] = [
|
||||
{
|
||||
"key": bucket.get("key"),
|
||||
"key_display_name": bucket.get(
|
||||
"key_as_string", bucket.get("key")
|
||||
),
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
for bucket in buckets
|
||||
]
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
for item in (value or "").split(","):
|
||||
if not item or ":" not in item:
|
||||
continue
|
||||
field, raw_value = item.split(":", 1)
|
||||
field = field.strip()
|
||||
raw_value = raw_value.strip()
|
||||
if raw_value.startswith((">", "<")):
|
||||
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||
clauses.append({"range": {field: {operator: raw_value[1:]}}})
|
||||
else:
|
||||
clauses.append(
|
||||
{"term": {OpenAlexInstitutionsClient._keyword_field(field): raw_value}}
|
||||
)
|
||||
return clauses
|
||||
|
||||
@staticmethod
|
||||
def _sort(value: str) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for item in value.split(","):
|
||||
field, _, direction = item.partition(":")
|
||||
result.append(
|
||||
{
|
||||
OpenAlexInstitutionsClient._sortable_field(field.strip()): {
|
||||
"order": direction or "desc",
|
||||
"missing": "_last",
|
||||
}
|
||||
}
|
||||
async def list_institutions(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/institutions",
|
||||
params=self.list_institutions_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _keyword_field(field: str) -> str:
|
||||
if field in {"id", "ror", "display_name"}:
|
||||
return f"{field}.keyword"
|
||||
return field
|
||||
|
||||
@staticmethod
|
||||
def _sortable_field(field: str) -> str:
|
||||
return "display_name.keyword" if field == "display_name" else field
|
||||
|
||||
@staticmethod
|
||||
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||
if not hits or not hits[-1].get("sort"):
|
||||
return None
|
||||
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -9,72 +11,166 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
class StubInstitutionsClient:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.kwargs = None
|
||||
|
||||
async def list_institutions(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_maps_elasticsearch_response_to_model():
|
||||
client = StubInstitutionsClient(
|
||||
{
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/012345678",
|
||||
"display_name": "Example University",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"geo": {"city": "Essen", "country": "Germany"},
|
||||
"ids": {"openalex": "https://openalex.org/I123"},
|
||||
}
|
||||
],
|
||||
}
|
||||
async def test_list_institutions_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"homepage_url": "https://www.uni-due.de",
|
||||
"image_url": "https://example.org/image.jpg",
|
||||
"image_thumbnail_url": "https://example.org/thumb.jpg",
|
||||
"display_name_acronyms": ["UDE"],
|
||||
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": 1.5,
|
||||
"h_index": 42,
|
||||
"i10_index": 99,
|
||||
},
|
||||
"geo": {
|
||||
"city": "Duisburg",
|
||||
"geonames_city_id": "2934691",
|
||||
"region": "North Rhine-Westphalia",
|
||||
"country_code": "DE",
|
||||
"country": "Germany",
|
||||
"latitude": 51.4344,
|
||||
"longitude": 6.7623,
|
||||
},
|
||||
"lineage": ["https://openalex.org/I123"],
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"mag": 123,
|
||||
"grid": "grid.12345.6",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
|
||||
"wikidata": "https://www.wikidata.org/wiki/Q317070",
|
||||
},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": 2024,
|
||||
"works_count": 12,
|
||||
"cited_by_count": 34,
|
||||
}
|
||||
],
|
||||
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "DE",
|
||||
"key_display_name": "Germany",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(search="Example", client=client)
|
||||
result = await logic.list_institutions(search="Duisburg Essen", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.results[0].display_name == "Example University"
|
||||
assert result.results[0].geo.city == "Essen"
|
||||
assert client.kwargs["search"] == "Example"
|
||||
institution = result.results[0]
|
||||
assert institution.display_name == "University of Duisburg-Essen"
|
||||
assert institution.summary_stats.h_index == 42
|
||||
assert institution.geo.country == "Germany"
|
||||
assert institution.ids.mag == 123
|
||||
assert institution.counts_by_year[0].year == 2024
|
||||
assert result.group_by[0].key_display_name == "Germany"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException):
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_normalizes_elasticsearch_values():
|
||||
client = StubInstitutionsClient(
|
||||
{
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"type": "unknown-type",
|
||||
"works_count": "12.0",
|
||||
"ids": {"openalex": 123, "mag": "123"},
|
||||
}
|
||||
],
|
||||
}
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"ror": 456,
|
||||
"display_name": "Example Institute",
|
||||
"country_code": 789,
|
||||
"type": "unknown-openalex-type",
|
||||
"display_name_acronyms": ["EI", 123],
|
||||
"display_name_alternatives": "not-a-list",
|
||||
"works_count": "12",
|
||||
"cited_by_count": "34.0",
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": "1.25",
|
||||
"h_index": "10.0",
|
||||
"i10_index": True,
|
||||
},
|
||||
"geo": {
|
||||
"city": 123,
|
||||
"geonames_city_id": 12345,
|
||||
"latitude": "51.4",
|
||||
"longitude": "6",
|
||||
},
|
||||
"ids": {"openalex": 123, "mag": "123"},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": "2024",
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
}
|
||||
],
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": 1}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(client=client)
|
||||
|
||||
assert result.results[0].id == "123"
|
||||
assert result.results[0].display_name == "456"
|
||||
assert result.results[0].ror == "456"
|
||||
assert result.results[0].country_code == "789"
|
||||
assert result.results[0].type is None
|
||||
assert result.results[0].display_name_acronyms == ["EI", "123"]
|
||||
assert result.results[0].display_name_alternatives is None
|
||||
assert result.results[0].works_count == 12
|
||||
assert result.results[0].cited_by_count == 34
|
||||
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
|
||||
assert result.results[0].summary_stats.h_index == 10
|
||||
assert result.results[0].summary_stats.i10_index is None
|
||||
assert result.results[0].geo.city == "123"
|
||||
assert result.results[0].geo.geonames_city_id == "12345"
|
||||
assert result.results[0].geo.latitude == 51.4
|
||||
assert result.results[0].geo.longitude == 6
|
||||
assert result.results[0].ids.openalex == "123"
|
||||
assert result.results[0].ids.mag == 123
|
||||
assert result.results[0].counts_by_year[0].year == 2024
|
||||
assert result.results[0].counts_by_year[0].works_count == 12
|
||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@@ -11,47 +9,69 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_institutions_query_builds_elasticsearch_query():
|
||||
body = OpenAlexInstitutionsClient().list_institutions_query(
|
||||
def test_list_institutions_params_include_openalex_query_parameters():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(
|
||||
search="Duisburg Essen",
|
||||
filter="country_code:DE,type:education,works_count:>1000",
|
||||
filter="country_code:DE,type:education",
|
||||
sort="works_count:desc",
|
||||
group_by="country_code",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert body["from"] == 10
|
||||
assert body["size"] == 10
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "Duisburg Essen"
|
||||
assert {"term": {"country_code": "DE"}} in body["query"]["bool"]["filter"]
|
||||
assert {"term": {"type": "education"}} in body["query"]["bool"]["filter"]
|
||||
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||
assert params == {
|
||||
"search": "Duisburg Essen",
|
||||
"filter": "country_code:DE,type:education",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "country_code",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_institutions_params_prefers_cursor_over_page():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_calls_elasticsearch_and_maps_hits():
|
||||
response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
async def test_list_institutions_calls_openalex_institutions_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/institutions"
|
||||
assert request.url.params["search"] == "Duisburg Essen"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"display_name": "Example University",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||
search.return_value = response
|
||||
result = await OpenAlexInstitutionsClient().list_institutions(search="Example")
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_institutions(search="Duisburg Essen")
|
||||
|
||||
search.assert_awaited_once()
|
||||
assert search.await_args.kwargs["index"] == ESIndex.OPENALEX_INSTITUTIONS
|
||||
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Example University"
|
||||
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
from openai import OpenAI, APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
model: str = None,
|
||||
timeout: int = 30,
|
||||
json_schema = None,
|
||||
schema_name = None,
|
||||
timeout: int = 120,
|
||||
temperature: float = 1.0,
|
||||
top_p: float = 0.95,
|
||||
) -> str:
|
||||
|
||||
if model is None:
|
||||
model = config.settings.llm_model
|
||||
|
||||
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = _get_response_format(schema = json_schema,schema_name=schema_name)
|
||||
|
||||
client = OpenAI(
|
||||
base_url=config.settings.llm_api_url,
|
||||
api_key=config.settings.llm_api_key,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
try:
|
||||
response = client.chat.completions.create(
|
||||
model=model,
|
||||
@@ -27,10 +33,10 @@ def call(
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
response_format=response_format
|
||||
)
|
||||
except APIConnectionError:
|
||||
return "Etwas ist schiefgelaufen. Bitte versuche es später erneut."
|
||||
@@ -38,3 +44,73 @@ def call(
|
||||
return response.choices[0].message.content or (
|
||||
"Etwas ist schiefgelaufen. Bitte versuche es erneut."
|
||||
)
|
||||
|
||||
def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str, Any]:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": schema_name or "response",
|
||||
"strict": True,
|
||||
"schema": schema,
|
||||
},
|
||||
}
|
||||
return response_format
|
||||
|
||||
|
||||
|
||||
|
||||
async def call_stream(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
emit, # EventCallback
|
||||
model: str = None,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
timeout: int = 120,
|
||||
temperature: float = 1.0,
|
||||
top_p: float = 0.95,
|
||||
) -> str:
|
||||
if model is None:
|
||||
model = config.settings.llm_model
|
||||
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = _get_response_format(schema=json_schema, schema_name=schema_name)
|
||||
|
||||
client = AsyncOpenAI(
|
||||
base_url=config.settings.llm_api_url,
|
||||
api_key=config.settings.llm_api_key,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
full_content = ""
|
||||
try:
|
||||
stream = await client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
response_format=response_format,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
|
||||
except APIConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
return ""
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||
traceback.print_exc()
|
||||
return ""
|
||||
|
||||
return full_content
|
||||
@@ -0,0 +1,444 @@
|
||||
#!/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
|
||||
import httpx
|
||||
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.model import (
|
||||
ExtractedKeywords,
|
||||
ExtractedKeywordsLLM,
|
||||
ExtractedKeywordsResponse,
|
||||
KeywordEntry,
|
||||
KeywordEntryWithTopic,
|
||||
KeywordsWsEvent,
|
||||
)
|
||||
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]],
|
||||
) -> ExtractedKeywords:
|
||||
return ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
|
||||
async def _enrich_llm_keywords(results: ExtractedKeywordsLLM) -> ExtractedKeywords:
|
||||
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]] = []
|
||||
for level in LEVELS:
|
||||
for idx, entry in enumerate(getattr(results, level)):
|
||||
keywords.append(entry.keyword)
|
||||
positions.append((level, idx))
|
||||
|
||||
if keywords:
|
||||
matches = await vector_search_topics_batch(keywords=keywords, search_type="hybrid")
|
||||
for (level, idx), match in zip(positions, matches.results):
|
||||
confirmed[level][idx].topic_mapping = match
|
||||
|
||||
return _build_enriched_snapshot(confirmed)
|
||||
|
||||
async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse:
|
||||
"""
|
||||
Extracts keywords from the given text or URL using a language model.
|
||||
"""
|
||||
start_time = time.time()
|
||||
if mode == "url":
|
||||
text = await _get_text_content(query)
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
|
||||
else:
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
text = query
|
||||
|
||||
|
||||
user_prompt = f"""
|
||||
Now analyze the following text and return ONLY the JSON object.\n"""
|
||||
|
||||
if limit:
|
||||
user_prompt +=f"Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n"
|
||||
|
||||
user_prompt += f"""Input:{text}"""
|
||||
|
||||
keywords = llm.call(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema = ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name = "extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
)
|
||||
keywords_json = json.loads(keywords)
|
||||
validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||
enriched = await _enrich_llm_keywords(validated)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds")
|
||||
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
|
||||
|
||||
|
||||
async def _get_text_content(url: str) -> str:
|
||||
"""
|
||||
Fetches the HTML content from the given URL using httpx and extracts visible text.
|
||||
"""
|
||||
try:
|
||||
headers = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/91.0.4472.124 Safari/537.36"
|
||||
)
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
soup = BeautifulSoup(response.text, "html.parser")
|
||||
for element in soup(["script", "style"]):
|
||||
element.decompose()
|
||||
text = soup.get_text(separator=" ", strip=True)
|
||||
text = " ".join(text.split())
|
||||
return text
|
||||
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"HTTP error for {url}: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing {url}: {e}")
|
||||
|
||||
|
||||
async def extract_keywords_stream(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 60 # configurable
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
user_prompt = "\nNow analyze the following text and return ONLY the JSON object.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level (broad, coarse, fine).\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds only fully validated KeywordEntry dicts for each level
|
||||
confirmed: Dict[str, List[Dict[str, Any]]] = {level: [] for level in LEVELS}
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and validate the full ExtractedKeywordsLLM model and emit it."""
|
||||
# Build a dict with all three fields, using empty lists for missing ones
|
||||
data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
validated = ExtractedKeywordsLLM.model_validate(data)
|
||||
except ValidationError:
|
||||
# Should not happen if all items are valid, but guard against it
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
# adds completed keyword chunks to the confirmed dict and emits the full results when new valid items are found
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
idx = len(confirmed[level])
|
||||
|
||||
while idx < len(current):
|
||||
raw_item = current[idx]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
confirmed[level].append(validated_item.model_dump())
|
||||
idx += 1
|
||||
grew = True
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# Accumulate full_content for incremental parsing
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
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"]}
|
||||
await on_chunk(event)
|
||||
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
if not keywords:
|
||||
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
|
||||
raise RuntimeError("LLM streaming call returned empty content")
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# Final emission of the full results (in case the last chunk didn't trigger it)
|
||||
final_data = {level: confirmed.get(level, []) for level in LEVELS}
|
||||
try:
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(keywords_json)
|
||||
except ValidationError:
|
||||
# Fallback: use our confirmed data
|
||||
final_validated = ExtractedKeywordsLLM.model_validate(final_data)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def extract_keywords_stream_enriched(
|
||||
query: str,
|
||||
mode: str,
|
||||
limit: int,
|
||||
emit: EventCallback,
|
||||
) -> ExtractedKeywordsResponse:
|
||||
start_time = time.time()
|
||||
timeout_seconds = 120
|
||||
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
|
||||
|
||||
if mode == "url":
|
||||
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
|
||||
text = await _get_text_content(query)
|
||||
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
else:
|
||||
text = query
|
||||
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
|
||||
user_prompt = "\nNow analyze the following text.\n"
|
||||
if limit:
|
||||
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
|
||||
user_prompt += f"\nInput:\n{text}"
|
||||
|
||||
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
|
||||
|
||||
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
|
||||
|
||||
# Holds enriched keyword wrappers for each level
|
||||
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
|
||||
|
||||
# Track background enrichment tasks
|
||||
enrichment_tasks: List[asyncio.Task] = []
|
||||
|
||||
async def emit_full_results() -> None:
|
||||
"""Attempt to build and emit the full enriched keyword model."""
|
||||
try:
|
||||
validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
return
|
||||
await emit(KeywordsWsEvent(type="keywords", keywords=validated.model_dump()).model_dump())
|
||||
|
||||
async def get_openalex_topic(level: str, idx: int, item: KeywordEntry) -> None:
|
||||
"""
|
||||
Fetch/enrich metadata for a single keyword.
|
||||
Runs concurrently without blocking the LLM stream.
|
||||
"""
|
||||
try:
|
||||
topic = await vector_search_topics_batch(
|
||||
keywords=[item.keyword],
|
||||
search_type="hybrid",
|
||||
)
|
||||
# Update the shared confirmed list in-place (safe in asyncio)
|
||||
confirmed[level][idx].topic_mapping = topic.results[0] if topic.results else None
|
||||
|
||||
# Emit the full updated set after each enrichment so the frontend sees progress.
|
||||
await emit_full_results()
|
||||
|
||||
except asyncio.CancelledError:
|
||||
# If the whole request is cancelled, we can just re-raise
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- on_chunk: parses LLM stream and appends new keywords ----------
|
||||
async def on_chunk(event: Dict[str, Any]) -> None:
|
||||
if event["type"] != "llm_chunk":
|
||||
await emit(event)
|
||||
return
|
||||
|
||||
try:
|
||||
partial = partial_json_parser.loads(event.get("_full_content", ""))
|
||||
except Exception:
|
||||
return
|
||||
|
||||
if not isinstance(partial, dict):
|
||||
return
|
||||
|
||||
grew = False
|
||||
|
||||
for level in LEVELS:
|
||||
current = partial.get(level) or []
|
||||
start_idx = len(confirmed[level]) # Where we start appending
|
||||
|
||||
while len(confirmed[level]) < len(current):
|
||||
raw_item = current[len(confirmed[level])]
|
||||
try:
|
||||
validated_item = KeywordEntry.model_validate(raw_item)
|
||||
except ValidationError:
|
||||
break # item not complete yet
|
||||
|
||||
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
|
||||
grew = True
|
||||
|
||||
# Launch openalex topic mapping
|
||||
for idx in range(start_idx, len(confirmed[level])):
|
||||
keyword_text = confirmed[level][idx].llm_keyword.keyword
|
||||
await emit(
|
||||
KeywordsWsEvent(
|
||||
type="status",
|
||||
step="enriching",
|
||||
message=f"Extracting topic for keyword '{keyword_text}'",
|
||||
).model_dump()
|
||||
)
|
||||
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
|
||||
enrichment_tasks.append(task)
|
||||
|
||||
if grew:
|
||||
await emit_full_results()
|
||||
|
||||
# ---------- Accumulate full_content for incremental parsing ----------
|
||||
full_content_holder = {"value": ""}
|
||||
|
||||
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"]}
|
||||
await on_chunk(event)
|
||||
|
||||
# ---------- Call the LLM ----------
|
||||
try:
|
||||
keywords = await asyncio.wait_for(
|
||||
llm.call_stream(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=ExtractedKeywordsLLM.model_json_schema(),
|
||||
schema_name="extracted_keywords",
|
||||
temperature=0.0,
|
||||
top_p=0.95,
|
||||
emit=emit_wrapper,
|
||||
),
|
||||
timeout=timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
|
||||
raise RuntimeError("LLM streaming call timed out")
|
||||
except asyncio.CancelledError:
|
||||
# Cancel all pending enrichment tasks to avoid dangling background work
|
||||
for task in enrichment_tasks:
|
||||
task.cancel()
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
|
||||
raise
|
||||
|
||||
# ---------- Finalize ----------
|
||||
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
|
||||
|
||||
try:
|
||||
keywords_json = json.loads(keywords)
|
||||
except json.JSONDecodeError as e:
|
||||
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
|
||||
raise RuntimeError("LLM response is not valid JSON")
|
||||
|
||||
# ---------- Wait for ALL pending enrichments to complete ----------
|
||||
if enrichment_tasks:
|
||||
await asyncio.gather(*enrichment_tasks, return_exceptions=True)
|
||||
|
||||
await emit_full_results()
|
||||
|
||||
# Build final response
|
||||
try:
|
||||
final_validated = _build_enriched_snapshot(confirmed)
|
||||
except ValidationError:
|
||||
final_validated = ExtractedKeywords.model_validate(
|
||||
{level: [item.model_dump() for item in confirmed.get(level, [])] for level in LEVELS}
|
||||
)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
result = ExtractedKeywordsResponse(
|
||||
results=final_validated,
|
||||
source=mode,
|
||||
source_url=query if mode == "url" else None,
|
||||
source_content=text,
|
||||
duration=elapsed_time,
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/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 KeywordsRequest(BaseModel):
|
||||
query: str = Field(description="The input text from which to extract keywords.")
|
||||
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||
|
||||
class KeywordEntry(BaseModel):
|
||||
keyword: str = Field(description="The extracted keyword.")
|
||||
relevance_score: float = Field(description="The relevance score of the keyword.")
|
||||
|
||||
class KeywordEntryWithTopic(BaseModel):
|
||||
llm_keyword: KeywordEntry = Field(description="The keyword extracted by the LLM.")
|
||||
topic_mapping: KeywordTopicMatch | None = Field(
|
||||
default=None,
|
||||
description="The corresponding OpenAlex topic match for the keyword, if any.",
|
||||
)
|
||||
|
||||
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.")
|
||||
|
||||
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.")
|
||||
|
||||
class ExtractedKeywordsResponse(BaseModel):
|
||||
results_llm: ExtractedKeywordsLLM | None = None
|
||||
results: ExtractedKeywords | None = None
|
||||
source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.")
|
||||
source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.")
|
||||
source_content: str = Field(description="The actual content from which keywords were extracted.")
|
||||
duration: float | None = Field(default=None, description="The time taken to extract keywords, in seconds.")
|
||||
|
||||
class KeywordsWsEvent(BaseModel):
|
||||
type: str
|
||||
step: str | None = None
|
||||
message: str | None = None
|
||||
result: ExtractedKeywordsResponse | None = None
|
||||
keywords: ExtractedKeywords | ExtractedKeywordsLLM | None = None
|
||||
duration: float | None = None
|
||||
completed: str | None = None
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
from enum import StrEnum
|
||||
class KeywordsPrompt(StrEnum):
|
||||
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
|
||||
|
||||
Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval.
|
||||
|
||||
The extracted keywords should prioritize:
|
||||
|
||||
* Scientific domains
|
||||
* Technologies
|
||||
* Research fields
|
||||
* Methods
|
||||
* Applications
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Industrial sectors
|
||||
* Technical concepts
|
||||
|
||||
Avoid generic business terms unless they are core topics of the text.
|
||||
|
||||
Examples of terms to avoid:
|
||||
|
||||
* Solution
|
||||
* Platform
|
||||
* Improvement
|
||||
* Capability
|
||||
* Innovation
|
||||
* Process
|
||||
* Service
|
||||
* Performance
|
||||
* Efficiency
|
||||
|
||||
unless they represent an actual searchable concept.
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## 1. broad_keywords
|
||||
|
||||
High-level domains, disciplines, industries, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Biotechnology
|
||||
* Renewable Energy
|
||||
* Materials Science
|
||||
* Robotics
|
||||
|
||||
These should represent the major themes of the document.
|
||||
|
||||
---
|
||||
|
||||
## 2. coarse_grained
|
||||
|
||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Drug Discovery
|
||||
* Computer Vision
|
||||
* Predictive Maintenance
|
||||
* Smart Manufacturing
|
||||
* Gene Editing
|
||||
|
||||
These should provide more specific context within the broad domains.
|
||||
|
||||
---
|
||||
|
||||
## 3. fine_grained
|
||||
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* Retrieval-Augmented Generation
|
||||
* Lithium Iron Phosphate
|
||||
* YOLOv8
|
||||
* OPC UA
|
||||
|
||||
These should be the most specific and actionable concepts for literature retrieval.
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Each keyword must include a relevance score.
|
||||
|
||||
Definition:
|
||||
|
||||
* 1.0 = central concept of the text
|
||||
* 0.9 = extremely important concept
|
||||
* 0.8 = highly relevant concept
|
||||
* 0.7 = important supporting concept
|
||||
* 0.6 = relevant secondary concept
|
||||
* below 0.6 = use sparingly
|
||||
|
||||
Guidelines:
|
||||
|
||||
* Scores must be between 0.0 and 1.0.
|
||||
* Use decimal precision up to 3 digits.
|
||||
* Rank keywords by importance.
|
||||
* The most important keywords should appear first.
|
||||
* Broad keywords generally receive higher scores than secondary topics.
|
||||
* Only include keywords with meaningful relevance.
|
||||
|
||||
---
|
||||
|
||||
# Extraction Rules
|
||||
|
||||
* Extract only concepts explicitly mentioned or strongly implied.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across levels whenever possible.
|
||||
* Do not invent technologies not supported by the text.
|
||||
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
|
||||
---
|
||||
|
||||
# Output Schema
|
||||
|
||||
Return ONLY valid JSON.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Example 1
|
||||
|
||||
Input:
|
||||
|
||||
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]}
|
||||
|
||||
---
|
||||
|
||||
# Example 2
|
||||
|
||||
Input:
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
|
||||
Output:
|
||||
|
||||
{"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]}
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
|
||||
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||
|
||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
|
||||
The extracted text may contain:
|
||||
|
||||
* Navigation menus
|
||||
* Headers and footers
|
||||
* Cookie notices
|
||||
* Marketing language
|
||||
* Contact information
|
||||
* Repeated sections
|
||||
* Calls to action
|
||||
* Legal disclaimers
|
||||
* Product pages
|
||||
* Blog articles
|
||||
* News articles
|
||||
* Landing pages
|
||||
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
|
||||
Ignore:
|
||||
|
||||
* Navigation elements
|
||||
* Cookie banners
|
||||
* Legal notices
|
||||
* Copyright text
|
||||
* Generic marketing statements
|
||||
* Contact information
|
||||
* Login/signup content
|
||||
* Careers pages unless they contain relevant technical information
|
||||
* Repeated website boilerplate
|
||||
|
||||
Focus only on content that helps identify:
|
||||
|
||||
* Technologies
|
||||
* Scientific concepts
|
||||
* Research areas
|
||||
* Technical methods
|
||||
* Products
|
||||
* Applications
|
||||
* Industrial sectors
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Engineering disciplines
|
||||
* Innovation domains
|
||||
|
||||
---
|
||||
|
||||
# Step 1: Determine Page Type
|
||||
|
||||
Determine which type of page is represented:
|
||||
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
|
||||
Use this classification internally only.
|
||||
|
||||
Do not include it in the output.
|
||||
|
||||
---
|
||||
|
||||
# Step 2: Extract Searchable Concepts
|
||||
|
||||
Prioritize concepts that are useful for:
|
||||
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
|
||||
Prefer canonical scientific terminology over marketing language.
|
||||
|
||||
Examples:
|
||||
|
||||
Prefer:
|
||||
|
||||
* Large Language Models
|
||||
|
||||
Instead of:
|
||||
|
||||
* AI Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Smart Manufacturing
|
||||
|
||||
Instead of:
|
||||
|
||||
* Factory Optimization Solution
|
||||
|
||||
Prefer:
|
||||
|
||||
* Retrieval-Augmented Generation
|
||||
|
||||
Instead of:
|
||||
|
||||
* Intelligent Knowledge Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Predictive Maintenance
|
||||
|
||||
Instead of:
|
||||
|
||||
* Equipment Performance Optimization
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## broad_keywords
|
||||
|
||||
High-level domains, industries, disciplines, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Manufacturing
|
||||
* Energy Storage
|
||||
* Biotechnology
|
||||
* Robotics
|
||||
|
||||
---
|
||||
|
||||
## coarse_grained
|
||||
|
||||
Technologies, methods, research fields, and applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Computer Vision
|
||||
* Clinical Decision Support
|
||||
|
||||
---
|
||||
|
||||
## fine_grained
|
||||
|
||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* OPC UA
|
||||
* Retrieval-Augmented Generation
|
||||
* YOLOv8
|
||||
* Lithium Iron Phosphate
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
|
||||
Guidelines:
|
||||
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
|
||||
---
|
||||
|
||||
# Additional Rules
|
||||
|
||||
* Extract only concepts supported by the page content.
|
||||
* Do not hallucinate technologies.
|
||||
* Avoid generic company descriptions.
|
||||
* Avoid generic business terminology.
|
||||
* Prefer terminology suitable for scientific literature search.
|
||||
* Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
|
||||
* Remove duplicates across hierarchy levels whenever possible.
|
||||
* Rank keywords by importance.
|
||||
|
||||
---
|
||||
# Example 3 — News Article
|
||||
|
||||
## Input
|
||||
|
||||
Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 4 — Product Page
|
||||
|
||||
## Input
|
||||
|
||||
The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 5 — Technical Documentation
|
||||
|
||||
## Input
|
||||
|
||||
FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
# Example 6 — Company Website
|
||||
|
||||
## Input
|
||||
|
||||
Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations.
|
||||
|
||||
## Output
|
||||
|
||||
```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}```
|
||||
|
||||
---
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
"""
|
||||
|
||||
SIMPLE_TEXT_PROMPT = """
|
||||
You are a scientific and technology intelligence expert. Extract keywords from the given text into three hierarchical levels. Each keyword must include a relevance_score (0.0–1.0) indicating centrality.
|
||||
|
||||
**Levels:**
|
||||
- **broad_keywords** – high‑level domains/industries (e.g., Artificial Intelligence, Healthcare, Renewable Energy).
|
||||
- **coarse_grained** – mid‑level technologies/methods/applications (e.g., Machine Learning, Drug Discovery, Smart Manufacturing).
|
||||
- **fine_grained** – specific technical concepts, algorithms, materials, protocols (e.g., Transformer Architecture, CRISPR‑Cas9, Retrieval‑Augmented Generation).
|
||||
|
||||
**Guidelines:**
|
||||
- Prioritize scientific, technical, and research‑oriented terminology.
|
||||
- Avoid generic business fluff: "solution", "platform", "improvement", "service", "performance" – unless they are explicit searchable concepts.
|
||||
- Prefer noun phrases; avoid complete sentences.
|
||||
- Extract 5–15 keywords per level when possible.
|
||||
- Rank by importance (higher scores first).
|
||||
|
||||
**Relevance scores:**
|
||||
- 1.0 = central topic
|
||||
- 0.9 = extremely important
|
||||
- 0.8 = highly relevant
|
||||
- 0.7 = supporting concept
|
||||
- 0.6 = secondary
|
||||
- Below 0.6 – use sparingly.
|
||||
|
||||
**Output schema (JSON only):**
|
||||
{
|
||||
"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],
|
||||
"coarse_grained": [...],
|
||||
"fine_grained": [...]
|
||||
}
|
||||
|
||||
**Example:**
|
||||
Input: Researchers developed a transformer-based ML framework for predictive maintenance in smart factories using sensor fusion and anomaly detection.
|
||||
Output:
|
||||
{
|
||||
"broad_keywords": [{"keyword": "Artificial Intelligence", "relevance_score": 0.98}, {"keyword": "Manufacturing", "relevance_score": 0.94}],
|
||||
"coarse_grained": [{"keyword": "Predictive Maintenance", "relevance_score": 0.95}, {"keyword": "Anomaly Detection", "relevance_score": 0.85}],
|
||||
"fine_grained": [{"keyword": "Transformer Architecture", "relevance_score": 0.95}, {"keyword": "Sensor Fusion", "relevance_score": 0.82}]
|
||||
}
|
||||
|
||||
Return ONLY the JSON object, nothing else.
|
||||
"""
|
||||
SIMPLE_WEBSITE_PROMPT = """
|
||||
You are a technology scout and scientific analyst. The input is text scraped from a webpage (using BeautifulSoup or similar). Your goal: extract keywords into three hierarchical levels, just like the text prompt, but with extra care to ignore website boilerplate.
|
||||
|
||||
**Ignore:**
|
||||
- Navigation menus, headers/footers, cookie banners, legal disclaimers, copyright notices.
|
||||
- Generic marketing language, calls-to-action, contact details, login/signup content.
|
||||
- Repeated site templates or boilerplate.
|
||||
|
||||
**Focus only on:**
|
||||
- Technologies, research areas, scientific methods, products, applications, industrial sectors, materials, standards, diseases, engineering disciplines, innovation domains.
|
||||
- Prefer canonical scientific terms over marketing buzzwords (e.g., "Large Language Models" instead of "AI Assistant").
|
||||
|
||||
**Hierarchy and relevance scores** are the same as in the text prompt (broad → coarse → fine, scores 0.0–1.0).
|
||||
|
||||
**Output schema (JSON only):**
|
||||
'''{"broad_keywords": [{"keyword": "string", "relevance_score": 0.0}, ...],"coarse_grained": [...],"fine_grained": [...]}'''
|
||||
|
||||
**Example (company website):**
|
||||
Input: Stripe provides payment infrastructure for businesses, supporting processing, billing, fraud prevention, and global commerce.
|
||||
Output:
|
||||
{"broad_keywords": [{"keyword": "Financial Technology", "relevance_score": 0.98}, {"keyword": "Business Services", "relevance_score": 0.91}],"coarse_grained": [{"keyword": "Payment Processing", "relevance_score": 0.97}, {"keyword": "Digital Payments", "relevance_score": 0.95}],"fine_grained": [{"keyword": "Stripe Platform", "relevance_score": 0.99}, {"keyword": "Fraud Prevention", "relevance_score": 0.91}]}
|
||||
|
||||
**Return ONLY the JSON object, nothing else.**
|
||||
- Nno leading/trailing spaces, newlines, or any text before or after. NO IDENTATION, justa stringified JSON
|
||||
"""
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for persons / authors.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, WebSocket, WebSocketDisconnect
|
||||
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
tags=["Keywords"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
@router.websocket("/keywords/extract/ws")
|
||||
async def extract_keywords_ws(websocket: WebSocket):
|
||||
print("WebSocket connection established for keyword extraction.")
|
||||
await websocket.accept()
|
||||
try:
|
||||
raw = await websocket.receive_json()
|
||||
request = KeywordsRequest(**raw)
|
||||
disconnected = asyncio.Event()
|
||||
|
||||
async def emit(event: dict):
|
||||
if disconnected.is_set():
|
||||
return
|
||||
await websocket.send_json(event)
|
||||
|
||||
async def watch_disconnect() -> None:
|
||||
while True:
|
||||
message = await websocket.receive()
|
||||
if message["type"] == "websocket.disconnect":
|
||||
disconnected.set()
|
||||
return
|
||||
|
||||
extraction_task = asyncio.create_task(
|
||||
logic.extract_keywords_stream_enriched(
|
||||
query=request.query,
|
||||
mode=request.mode,
|
||||
limit=request.limit,
|
||||
emit=emit,
|
||||
)
|
||||
)
|
||||
disconnect_task = asyncio.create_task(watch_disconnect())
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
{extraction_task, disconnect_task},
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
|
||||
if disconnect_task in done:
|
||||
disconnected.set()
|
||||
extraction_task.cancel()
|
||||
try:
|
||||
await extraction_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
return
|
||||
|
||||
disconnect_task.cancel()
|
||||
try:
|
||||
await disconnect_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
result = extraction_task.result()
|
||||
|
||||
await websocket.send_json({"type": "completed", "result": result.model_dump()})
|
||||
|
||||
except WebSocketDisconnect:
|
||||
print("WebSocket disconnected.")
|
||||
pass
|
||||
except Exception as e:
|
||||
await websocket.send_json({"type": "error", "message": str(e)})
|
||||
finally:
|
||||
if websocket.application_state.name != "DISCONNECTED":
|
||||
await websocket.close()
|
||||
|
||||
# @router.post(
|
||||
# "/keywords/extract",
|
||||
# operation_id="extractKeywords",
|
||||
# response_model=ExtractedKeywordsResponse,
|
||||
# )
|
||||
# async def extract_keywords(
|
||||
# request: Annotated[
|
||||
# KeywordsRequest,
|
||||
# Body(description="Input text for keyword extraction"),
|
||||
# ],
|
||||
# ):
|
||||
# async def noop(_: dict):
|
||||
# pass
|
||||
|
||||
# return await logic.extract_keywords_stream(
|
||||
# query=request.query,
|
||||
# mode=request.mode,
|
||||
# limit=request.limit,
|
||||
# emit=noop,
|
||||
# )
|
||||
|
||||
@router.post(
|
||||
"/keywords/extract",
|
||||
operation_id="extractKeywords",
|
||||
response_model=ExtractedKeywordsResponse,
|
||||
summary="Extracts keywords from text.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
async def extract_keywords(
|
||||
request: Annotated[
|
||||
KeywordsRequest,
|
||||
Body(description="Input text for keyword extraction")
|
||||
],
|
||||
|
||||
):
|
||||
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
|
||||
@@ -33,6 +33,7 @@ from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
@@ -45,7 +46,12 @@ from inse.auth.service import create_predefined_accounts
|
||||
from . import config
|
||||
|
||||
from .service import router as service_router
|
||||
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
|
||||
from inse.patents.org.service import router as org_patents_router
|
||||
from inse.patents.service import (
|
||||
institution_patents_router,
|
||||
patents_router as patents_all_router,
|
||||
router as patents_service_router,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -73,6 +79,8 @@ app = FastAPI(
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institution_patents_router)
|
||||
app.include_router(org_patents_router)
|
||||
app.include_router(institutions_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_service_router)
|
||||
@@ -84,6 +92,7 @@ app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
app.include_router(keywords_service_router)
|
||||
|
||||
app.include_router(service_router)
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ class ESIndex(StrEnum):
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
ORG_PATENTS = "org_patents"
|
||||
|
||||
PROJECTS_BUND_V1 = "projects_bund_v1"
|
||||
PROJECTS_DFG_ALL = "projects_dfg_all"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Organization management API."""
|
||||
@@ -1,30 +0,0 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: bool
|
||||
member_count: int
|
||||
|
||||
|
||||
class OrganizationPage(BaseModel):
|
||||
items: List[OrganizationProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateOrganizationRequest(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateOrganizationRequest(BaseModel):
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
@@ -1,81 +0,0 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
|
||||
|
||||
|
||||
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
|
||||
async def get_organizations(
|
||||
page: int = Query(default=0, ge=0),
|
||||
page_size: int = Query(default=25, ge=1, le=100),
|
||||
offset: Optional[int] = Query(default=None, ge=0),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationPage:
|
||||
return service.get_organizations(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
operation_id="createOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_organization(
|
||||
payload: CreateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.create_organization(session, access_token, payload)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{organization_id}",
|
||||
operation_id="updateOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
)
|
||||
async def update_organization(
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.update_organization(
|
||||
session, access_token, organization_id, payload
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{organization_id}",
|
||||
operation_id="deleteOrganisation",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_organization(
|
||||
organization_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_organization(session, access_token, organization_id)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -1,183 +0,0 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
||||
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
def _require_super_admin(access_token: AccessToken) -> None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only superadmins can manage organizations.",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
normalized_name = name.strip()
|
||||
if not normalized_name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Organization name must not be empty.",
|
||||
)
|
||||
return normalized_name
|
||||
|
||||
|
||||
def _ensure_name_available(
|
||||
session: Session,
|
||||
name: str,
|
||||
excluded_organization_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
statement = select(Organization).where(
|
||||
func.lower(Organization.name) == name.lower()
|
||||
)
|
||||
if excluded_organization_id is not None:
|
||||
statement = statement.where(Organization.id != excluded_organization_id)
|
||||
|
||||
if session.exec(statement).first() is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="An organization with this name already exists.",
|
||||
)
|
||||
|
||||
|
||||
def _get_organization_or_404(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> Organization:
|
||||
organization = session.get(Organization, organization_id)
|
||||
if organization is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
return organization
|
||||
|
||||
|
||||
def _member_counts(
|
||||
session: Session, organization_ids: list[uuid.UUID]
|
||||
) -> dict[uuid.UUID, int]:
|
||||
if not organization_ids:
|
||||
return {}
|
||||
|
||||
rows = session.exec(
|
||||
select(Account.organization_id, func.count(Account.id))
|
||||
.where(
|
||||
Account.organization_id.in_(organization_ids),
|
||||
Account.deleted == False, # noqa: E712
|
||||
)
|
||||
.group_by(Account.organization_id)
|
||||
).all()
|
||||
return {organization_id: count for organization_id, count in rows}
|
||||
|
||||
|
||||
def _to_profile(
|
||||
organization: Organization, member_count: int
|
||||
) -> OrganizationProfile:
|
||||
return OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
other_inst_id=organization.openalex_institution_id,
|
||||
deleted=organization.deleted,
|
||||
member_count=member_count,
|
||||
)
|
||||
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
) -> OrganizationPage:
|
||||
statement = select(Organization)
|
||||
count_statement = select(func.count()).select_from(Organization)
|
||||
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
scope_filter = Organization.id == access_token.effective_organization_id
|
||||
statement = statement.where(scope_filter)
|
||||
count_statement = count_statement.where(scope_filter)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
organizations = session.exec(
|
||||
statement.order_by(Organization.name)
|
||||
.offset(effective_offset)
|
||||
.limit(page_size)
|
||||
).all()
|
||||
organization_ids = [organization.id for organization in organizations]
|
||||
counts = _member_counts(session, organization_ids)
|
||||
|
||||
return OrganizationPage(
|
||||
items=[
|
||||
_to_profile(organization, counts.get(organization.id, 0))
|
||||
for organization in organizations
|
||||
],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name)
|
||||
|
||||
organization = Organization(
|
||||
name=name,
|
||||
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
|
||||
)
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
return _to_profile(organization, 0)
|
||||
|
||||
|
||||
def update_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
|
||||
if payload.name is not None:
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name, organization.id)
|
||||
organization.name = name
|
||||
if payload.other_inst_id is not None:
|
||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||
if payload.deleted is not None:
|
||||
organization.deleted = payload.deleted
|
||||
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
counts = _member_counts(session, [organization.id])
|
||||
return _to_profile(organization, counts.get(organization.id, 0))
|
||||
|
||||
|
||||
def delete_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
@@ -73,6 +73,7 @@ def _member_counts(
|
||||
.where(
|
||||
Account.organization_id.in_(organization_ids),
|
||||
Account.deleted == False, # noqa: E712
|
||||
Account.activated == True, # noqa: E712
|
||||
)
|
||||
.group_by(Account.organization_id)
|
||||
).all()
|
||||
@@ -91,6 +92,21 @@ def _to_profile(
|
||||
)
|
||||
|
||||
|
||||
def _deactivate_organization_accounts(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> None:
|
||||
accounts = session.exec(
|
||||
select(Account).where(
|
||||
Account.organization_id == organization_id,
|
||||
Account.activated == True, # noqa: E712
|
||||
)
|
||||
).all()
|
||||
for account in accounts:
|
||||
account.activated = False
|
||||
account.epoch += 1
|
||||
session.add(account)
|
||||
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
@@ -162,6 +178,8 @@ def update_organization(
|
||||
if payload.other_inst_id is not None:
|
||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||
if payload.deleted is not None:
|
||||
if payload.deleted and not organization.deleted:
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = payload.deleted
|
||||
|
||||
session.add(organization)
|
||||
@@ -178,6 +196,8 @@ def delete_organization(
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
if not organization.deleted:
|
||||
_deactivate_organization_accounts(session, organization.id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
from inse.organization_management import service
|
||||
from inse.organization_management.model import (
|
||||
CreateOrganizationRequest,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as database_session:
|
||||
yield database_session
|
||||
|
||||
|
||||
def token(role: UserRole, organization_id):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
def test_superadmin_lists_all_organizations_with_active_member_count(session):
|
||||
first = Organization(name="Alpha")
|
||||
second = Organization(name="Beta", deleted=True)
|
||||
session.add(first)
|
||||
session.add(second)
|
||||
session.flush()
|
||||
session.add(
|
||||
Account(
|
||||
email="active@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
)
|
||||
)
|
||||
session.add(
|
||||
Account(
|
||||
email="deleted@example.org",
|
||||
name="Deleted",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
deleted=True,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.SUPER_ADMIN, first.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert [item.name for item in result.items] == ["Alpha", "Beta"]
|
||||
assert result.items[0].member_count == 1
|
||||
assert result.items[1].deleted is True
|
||||
|
||||
|
||||
def test_non_superadmin_only_sees_own_organization(session):
|
||||
own = Organization(name="Own")
|
||||
session.add(own)
|
||||
session.add(Organization(name="Other"))
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.USER, own.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].id == own.id
|
||||
|
||||
|
||||
def test_superadmin_can_create_update_and_soft_delete(session):
|
||||
scope = Organization(name="Scope")
|
||||
session.add(scope)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, scope.id)
|
||||
|
||||
created = service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" New tenant ", other_inst_id="I123"),
|
||||
)
|
||||
assert created.name == "New tenant"
|
||||
assert created.other_inst_id == "I123"
|
||||
|
||||
updated = service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
created.id,
|
||||
UpdateOrganizationRequest(name="Renamed", other_inst_id=""),
|
||||
)
|
||||
assert updated.name == "Renamed"
|
||||
assert updated.other_inst_id is None
|
||||
|
||||
service.delete_organization(session, access_token, created.id)
|
||||
assert session.get(Organization, created.id).deleted is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||
def test_only_superadmin_can_create_organizations(session, role):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(role, organization.id),
|
||||
CreateOrganizationRequest(name="Forbidden"),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_organization_name_must_not_be_blank(session):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
CreateOrganizationRequest(name=" "),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 422
|
||||
|
||||
|
||||
def test_organization_name_is_unique_ignoring_case(session):
|
||||
existing = Organization(name="Unique tenant")
|
||||
session.add(existing)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, existing.id)
|
||||
|
||||
with pytest.raises(HTTPException) as create_error:
|
||||
service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" unique TENANT "),
|
||||
)
|
||||
|
||||
assert create_error.value.status_code == 409
|
||||
|
||||
other = Organization(name="Other tenant")
|
||||
session.add(other)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as update_error:
|
||||
service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
other.id,
|
||||
UpdateOrganizationRequest(name="UNIQUE TENANT"),
|
||||
)
|
||||
|
||||
assert update_error.value.status_code == 409
|
||||
|
||||
|
||||
def test_organization_can_keep_its_name_when_updating(session):
|
||||
organization = Organization(name="Same tenant")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
result = service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(name="same TENANT"),
|
||||
)
|
||||
|
||||
assert result.name == "same TENANT"
|
||||
@@ -105,6 +105,66 @@ def test_superadmin_can_create_update_and_soft_delete(session):
|
||||
assert session.get(Organization, created.id).deleted is True
|
||||
|
||||
|
||||
def test_deleting_organization_deactivates_all_its_accounts(session):
|
||||
organization = Organization(name="Organization to delete")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
active_account = Account(
|
||||
email="active-delete@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
epoch=3,
|
||||
)
|
||||
inactive_account = Account(
|
||||
email="inactive-delete@example.org",
|
||||
name="Inactive",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
activated=False,
|
||||
epoch=5,
|
||||
)
|
||||
session.add(active_account)
|
||||
session.add(inactive_account)
|
||||
session.commit()
|
||||
|
||||
service.delete_organization(
|
||||
session, token(UserRole.SUPER_ADMIN, organization.id), organization.id
|
||||
)
|
||||
|
||||
session.refresh(active_account)
|
||||
session.refresh(inactive_account)
|
||||
assert active_account.activated is False
|
||||
assert active_account.epoch == 4
|
||||
assert inactive_account.activated is False
|
||||
assert inactive_account.epoch == 5
|
||||
|
||||
|
||||
def test_marking_organization_deleted_deactivates_its_accounts(session):
|
||||
organization = Organization(name="Organization to update")
|
||||
session.add(organization)
|
||||
session.flush()
|
||||
account = Account(
|
||||
email="active-update@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=organization.id,
|
||||
)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
|
||||
service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(deleted=True),
|
||||
)
|
||||
|
||||
session.refresh(account)
|
||||
assert account.activated is False
|
||||
assert account.epoch == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||
def test_only_superadmin_can_create_organizations(session, role):
|
||||
organization = Organization(name="Scope")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Global patent listing."""
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Business logic for global patent listing."""
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.parsing import (
|
||||
enrich_patents_classifications,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
)
|
||||
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.AllPatentsResponse:
|
||||
all_patents_client = AllPatentsSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
try:
|
||||
if source == "EPO":
|
||||
epo_data = await all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, size, search, sort_direction, year_from, year_to)
|
||||
)
|
||||
patents = parse_epo_hits(epo_data)
|
||||
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
elif source == "USPTO":
|
||||
uspto_data = await all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, size, search, sort_direction, year_from, year_to)
|
||||
)
|
||||
patents = parse_uspto_hits(uspto_data)
|
||||
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
else:
|
||||
half = size // 2
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, half, search, sort_direction, year_from, year_to)
|
||||
),
|
||||
all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to)
|
||||
),
|
||||
)
|
||||
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
total = (
|
||||
epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
+ uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
)
|
||||
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
await enrich_patents_classifications(patents, ipc_search_client)
|
||||
|
||||
return model.AllPatentsResponse(
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Business logic for global patent listing."""
|
||||
from fastapi import APIRouter
|
||||
|
||||
from inse.patents.all import logic
|
||||
from inse.patents.common import model
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/patents",
|
||||
operation_id="getAllPatents",
|
||||
response_model=model.AllPatentsResponse,
|
||||
summary="Get all patents with pagination and search.",
|
||||
)
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
):
|
||||
return await logic.get_all_patents(
|
||||
page=page,
|
||||
size=size,
|
||||
search=search,
|
||||
source=source,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""Patent lookup by inventor."""
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Business logic for patent lookup by inventor."""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse.patents.authors.name_matching import name_matches
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.parsing import (
|
||||
deduplicate_patents,
|
||||
enrich_patents_classifications,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
)
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
from inse.persons import logic as person_logic
|
||||
from inse.models.openalex.author import Author
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
try:
|
||||
epo_data, uspto_data = await _search_both_indices(
|
||||
search_client, last_name, first_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
all_patents = deduplicate_patents(all_patents)
|
||||
await enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name, first_name):
|
||||
return await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||
)
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[model.PatentEntry]:
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||
]
|
||||
|
||||
|
||||
def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Inventor name normalization and matching."""
|
||||
import re
|
||||
|
||||
from inse.patents.common.text_normalization import (
|
||||
name_token_variants,
|
||||
normalize_name_part,
|
||||
patent_transliteration_expansions,
|
||||
)
|
||||
|
||||
|
||||
def tokens_equal(
|
||||
left: str | None,
|
||||
right: str | None,
|
||||
*,
|
||||
allow_initial: bool = True,
|
||||
) -> bool:
|
||||
left_variants = name_token_variants(left)
|
||||
right_variants = name_token_variants(right)
|
||||
if not left_variants or not right_variants:
|
||||
return False
|
||||
if left_variants & right_variants:
|
||||
return True
|
||||
|
||||
if not allow_initial:
|
||||
return False
|
||||
|
||||
return _initial_tokens_match(left, right)
|
||||
|
||||
|
||||
def _initial_letter(token: str | None) -> str | None:
|
||||
normalized = normalize_name_part(token)
|
||||
if len(normalized) == 1 and normalized.isalpha():
|
||||
return normalized
|
||||
return None
|
||||
|
||||
|
||||
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
|
||||
left_initial = _initial_letter(left)
|
||||
right_initial = _initial_letter(right)
|
||||
left_full = normalize_name_part(left)
|
||||
right_full = normalize_name_part(right)
|
||||
|
||||
if left_initial and right_full and len(right_full) > 1:
|
||||
return right_full.startswith(left_initial)
|
||||
if right_initial and left_full and len(left_full) > 1:
|
||||
return left_full.startswith(right_initial)
|
||||
if left_initial and right_initial:
|
||||
return left_initial == right_initial
|
||||
return False
|
||||
|
||||
|
||||
def _inventor_first_token(inventor_name: str) -> str:
|
||||
if "," in inventor_name:
|
||||
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
|
||||
return first_part.split()[0] if first_part else ""
|
||||
parts = inventor_name.split()
|
||||
return parts[0] if parts else ""
|
||||
|
||||
|
||||
def first_name_match_kind(
|
||||
inventor_name: str,
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> str:
|
||||
if not name_matches(inventor_name, first_name, last_name):
|
||||
return "none"
|
||||
|
||||
inventor_first = _inventor_first_token(inventor_name)
|
||||
if tokens_equal(inventor_first, first_name, allow_initial=False):
|
||||
return "full"
|
||||
return "initial"
|
||||
|
||||
|
||||
def search_name_variants(value: str | None) -> list[str]:
|
||||
if not value or not value.strip():
|
||||
return []
|
||||
|
||||
seen: set[str] = set()
|
||||
ordered: list[str] = []
|
||||
|
||||
def _add(candidate: str) -> None:
|
||||
key = candidate.casefold()
|
||||
if candidate.strip() and key not in seen:
|
||||
seen.add(key)
|
||||
ordered.append(candidate.strip())
|
||||
|
||||
_add(value.strip())
|
||||
|
||||
normalized = normalize_name_part(value)
|
||||
if normalized:
|
||||
_add(normalized.title())
|
||||
|
||||
for variant in name_token_variants(value):
|
||||
_add(variant.title())
|
||||
|
||||
for variant in patent_transliteration_expansions(normalized):
|
||||
_add(variant.title())
|
||||
|
||||
if normalized and len(normalized) > 1:
|
||||
_add(normalized[0].upper())
|
||||
|
||||
return ordered
|
||||
|
||||
|
||||
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
|
||||
if not inventor_name or not last_name:
|
||||
return False
|
||||
|
||||
name = inventor_name.strip()
|
||||
|
||||
if "," in name:
|
||||
last_part, first_part = [p.strip() for p in name.split(",", 1)]
|
||||
first_token = first_part.split()[0] if first_part else ""
|
||||
return (
|
||||
tokens_equal(last_part, last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(first_token, first_name)
|
||||
)
|
||||
|
||||
parts = name.split()
|
||||
if len(parts) < 2:
|
||||
return False
|
||||
|
||||
return (
|
||||
tokens_equal(parts[-1], last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(parts[0], first_name)
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Elasticsearch query builders for inventor-based patent search."""
|
||||
from typing import Any
|
||||
|
||||
from inse.patents.authors.name_matching import search_name_variants
|
||||
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
|
||||
|
||||
|
||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
variants = search_name_variants(name)
|
||||
if len(variants) <= 1:
|
||||
return {"match": {field: variants[0] if variants else name}}
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: variant}} for variant in variants],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class InventorSearchQueries:
|
||||
def epo_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors_name_nested.inventor", last_name),
|
||||
_match_name_field("inventors_name_nested.inventor", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": _match_name_field("inventors_name_nested.inventor", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors.name", last_name),
|
||||
_match_name_field("inventors.name", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": _match_name_field("inventors.name", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from inse.patents.authors import logic
|
||||
from inse.patents.common import model
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/patents",
|
||||
operation_id="getPatentsByAuthor",
|
||||
response_model=model.PatentsByAuthorResponse,
|
||||
summary="Get patents matched to an author by name.",
|
||||
)
|
||||
async def get_patents_by_author(author_id: str):
|
||||
return await logic.get_patents_by_author_id(author_id)
|
||||
@@ -0,0 +1 @@
|
||||
"""Shared patent infrastructure."""
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Base HTTP client for patent Elasticsearch indices."""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ... import config
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
DEFAULT_SEARCH_SIZE = 100
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BasePatentSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{index}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -0,0 +1,55 @@
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class IpcClassification(BaseModel):
|
||||
symbol: str
|
||||
section: str | None = None
|
||||
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
||||
subclass: str | None = None
|
||||
main_group: str | None = None
|
||||
subgroup: str | None = None
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
|
||||
class PatentEntry(BaseModel):
|
||||
patent_id: str
|
||||
source: str
|
||||
title: str | None = None
|
||||
abstract: str | None = None
|
||||
publication_date: str | None = None
|
||||
publication_year: str | None = None
|
||||
application_number: str | None = None
|
||||
application_date: str | None = None
|
||||
kind: str | None = None
|
||||
application_type: str | None = None
|
||||
number_of_claims: int | None = None
|
||||
status: str | None = None
|
||||
inventors: list[str] = Field(default_factory=list)
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = Field(default_factory=list)
|
||||
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
cpc: list[str] = Field(default_factory=list)
|
||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
author_id: str
|
||||
author_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
|
||||
|
||||
class PatentsByInstitutionResponse(BaseModel):
|
||||
institution_id: str
|
||||
institution_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
|
||||
|
||||
class AllPatentsResponse(BaseModel):
|
||||
total: int
|
||||
page: int
|
||||
size: int
|
||||
patents: list[PatentEntry]
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Shared patent hit parsing, deduplication, and classification enrichment."""
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.ipc_lookup import extract_ipc_symbol
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=src.get("application_filing_date"),
|
||||
kind=src.get("kind"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||
application_type=src.get("application_type"),
|
||||
number_of_claims=src.get("number_of_claims"),
|
||||
status=src.get("status"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.PatentEntry] = []
|
||||
|
||||
for patent in patents:
|
||||
key = patent_dedup_key(patent)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
deduplicated.append(patent)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
stage = patent.kind or patent.application_type or ""
|
||||
return (
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date or "",
|
||||
stage,
|
||||
)
|
||||
|
||||
|
||||
async def enrich_patents_classifications(
|
||||
patents: list[model.PatentEntry],
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> None:
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
try:
|
||||
resolved = await ipc_client.resolve_symbols(symbols)
|
||||
except MissingApiKeyError:
|
||||
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||
return
|
||||
except httpx.HTTPError as exc:
|
||||
logger.warning("Classification enrichment failed: %s", exc)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||
return
|
||||
|
||||
for patent in patents:
|
||||
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
items = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||
|
||||
|
||||
def _descriptions_for_raw_codes(
|
||||
raw_codes: list[str],
|
||||
resolved: dict[str, model.IpcClassification],
|
||||
) -> list[model.IpcClassification]:
|
||||
return [
|
||||
resolved[extract_ipc_symbol(raw)]
|
||||
for raw in raw_codes
|
||||
if extract_ipc_symbol(raw) in resolved
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Shared text normalization for patent name matching."""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
_CHAR_REPLACEMENTS: dict[str, str] = {
|
||||
"ß": "ss",
|
||||
"ẞ": "ss",
|
||||
"æ": "ae",
|
||||
"Æ": "ae",
|
||||
"œ": "oe",
|
||||
"Œ": "oe",
|
||||
"ø": "o",
|
||||
"Ø": "o",
|
||||
"đ": "d",
|
||||
"Đ": "d",
|
||||
"ð": "d",
|
||||
"Ð": "d",
|
||||
"þ": "th",
|
||||
"Þ": "th",
|
||||
"ł": "l",
|
||||
"Ł": "l",
|
||||
"ı": "i",
|
||||
"ſ": "s",
|
||||
}
|
||||
|
||||
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
|
||||
("ae", "a"),
|
||||
("oe", "o"),
|
||||
("ue", "u"),
|
||||
)
|
||||
|
||||
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
|
||||
(r"u([lmnrt])", r"ue\1"),
|
||||
(r"o([lmnrt])", r"oe\1"),
|
||||
(r"a([lmnrt])", r"ae\1"),
|
||||
)
|
||||
|
||||
|
||||
def normalize_name_part(value: str | None) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
text = value.strip()
|
||||
for src, dst in _CHAR_REPLACEMENTS.items():
|
||||
text = text.replace(src, dst)
|
||||
|
||||
text = unicodedata.normalize("NFKD", text)
|
||||
text = "".join(c for c in text if not unicodedata.combining(c))
|
||||
text = text.lower()
|
||||
text = re.sub(r"[''`´]", "", text)
|
||||
text = re.sub(r"[^\w\s-]", "", text)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text
|
||||
|
||||
|
||||
def name_token_variants(value: str | None) -> set[str]:
|
||||
base = normalize_name_part(value)
|
||||
if not base:
|
||||
return set()
|
||||
|
||||
variants = {base}
|
||||
|
||||
for src, dst in _DIGRAPH_COLLAPSES:
|
||||
if src in base:
|
||||
variants.add(base.replace(src, dst))
|
||||
|
||||
if "-" in base:
|
||||
variants.add(base.replace("-", ""))
|
||||
variants.add(base.replace("-", " "))
|
||||
|
||||
return {v for v in variants if v}
|
||||
|
||||
|
||||
def patent_transliteration_expansions(normalized: str) -> set[str]:
|
||||
expanded = {normalized}
|
||||
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
|
||||
if re.search(pattern, normalized):
|
||||
expanded.add(re.sub(pattern, repl, normalized))
|
||||
return expanded
|
||||
@@ -36,24 +36,45 @@ class AllPatentsSearchClient:
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
sort_direction: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||
|
||||
if search and search.strip():
|
||||
term = search.strip()
|
||||
doc_number = term.upper().removeprefix("EP")
|
||||
query: dict[str, Any] = {
|
||||
search_query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": {"query": term}}},
|
||||
{"match_phrase": {"title_de": {"query": term}}},
|
||||
{"match": {"title_en": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||
{"match": {"title_de": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||
{"term": {"doc_number": doc_number}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
search_query = {"match_all": {}}
|
||||
|
||||
filters = []
|
||||
if year_from or year_to:
|
||||
date_range: dict[str, Any] = {}
|
||||
if year_from:
|
||||
date_range["gte"] = year_from * 10000
|
||||
if year_to:
|
||||
date_range["lte"] = (year_to * 10000) + 9999
|
||||
filters.append({"range": {"date_publication": date_range}})
|
||||
|
||||
if filters:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": search_query,
|
||||
"filter": filters,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = search_query
|
||||
|
||||
return {
|
||||
"from": page * size,
|
||||
@@ -68,30 +89,54 @@ class AllPatentsSearchClient:
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
|
||||
def remove_year(self, patent_id: str) -> str:
|
||||
return patent_id[4:].strip()
|
||||
def uspto_query(
|
||||
self,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
sort_direction: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
|
||||
|
||||
if search and search.strip():
|
||||
term = search.strip()
|
||||
pub_number = term.upper().removeprefix("US")
|
||||
query: dict[str, Any] = {
|
||||
search_query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title": {"query": term}}},
|
||||
{"match": {"title": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
|
||||
{"term": {"publication_number": pub_number}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {"match_all": {}}
|
||||
search_query = {"match_all": {}}
|
||||
|
||||
filters = []
|
||||
if year_from or year_to:
|
||||
date_range: dict[str, Any] = {}
|
||||
if year_from:
|
||||
date_range["gte"] = year_from * 10000
|
||||
if year_to:
|
||||
date_range["lte"] = (year_to * 10000) + 9999
|
||||
filters.append({"range": {"publication_date": date_range}})
|
||||
|
||||
if filters:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": search_query,
|
||||
"filter": filters,
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = search_query
|
||||
|
||||
return {
|
||||
"from": page * size,
|
||||
@@ -107,6 +152,103 @@ class AllPatentsSearchClient:
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"doc_number": doc_number}},
|
||||
{"term": {"doc_number": self.remove_year(doc_number)}},
|
||||
{"term": {"application_number": self.remove_year(doc_number)}},
|
||||
{"term": {"application_number": doc_number}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": 1,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de",
|
||||
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"publication_number": number}},
|
||||
{"term": {"publication_number": self.remove_year(number)}},
|
||||
{"term": {"application_number": number}},
|
||||
{"term": {"application_number": self.remove_year(number)}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": 1,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": 1,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de",
|
||||
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [{"match_phrase": {"title": title}}],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": 1,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(EPO_INDEX, payload)
|
||||
|
||||
|
||||
@@ -6,21 +6,27 @@
|
||||
from typing import Any
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
import httpx
|
||||
import asyncio
|
||||
from .. import config
|
||||
from .name_matching import search_name_variants
|
||||
|
||||
DEFAULT_SEARCH_SIZE = 100
|
||||
|
||||
def remove_year(patent_number: str) -> str:
|
||||
"""Remove a 4-digit year from the end of a patent number, if present."""
|
||||
if len(patent_number) > 4 and patent_number[-4:].isdigit():
|
||||
return patent_number[:-4]
|
||||
return patent_number
|
||||
|
||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
||||
variants = search_name_variants(name)
|
||||
if len(variants) <= 1:
|
||||
return {"match": {field: variants[0] if variants else name}}
|
||||
return {"match_phrase": {field: variants[0] if variants else name}}
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: variant}} for variant in variants],
|
||||
"should": [{"match_phrase": {field: variant}} for variant in variants],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
@@ -32,9 +38,15 @@ from inse.exceptions import MissingApiKeyError
|
||||
class PatentSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
@@ -158,9 +170,11 @@ class PatentSearchClient:
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
print("Searching EPO with payload:", payload)
|
||||
return await self._search(ESIndex.EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
print("Searching USPTO with payload:", payload)
|
||||
return await self._search(ESIndex.USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -172,9 +186,10 @@ class PatentSearchClient:
|
||||
patent_id: str,
|
||||
prefix: str,
|
||||
title: str,
|
||||
filling_date: str | None = None,
|
||||
size: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
|
||||
"""Search EPO and USPTO by ID; fall back to match on title if no hits.
|
||||
|
||||
Args:
|
||||
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
||||
@@ -202,16 +217,28 @@ class PatentSearchClient:
|
||||
return epo_result if epo_hits > 0 else uspto_result
|
||||
|
||||
if prefix.upper() == "US":
|
||||
payload = self._uspto_query_by_title(title, size)
|
||||
payload = self._uspto_query_by_title(title, filling_date, size)
|
||||
return await self.search_uspto(payload)
|
||||
|
||||
payload = self._epo_query_by_title(title, size)
|
||||
payload = self._epo_query_by_title(title,filling_date, size)
|
||||
return await self.search_epo(payload)
|
||||
|
||||
#query builders
|
||||
|
||||
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
||||
raw_id = patent_id.upper().removeprefix("EP")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"doc_number": raw_id}},
|
||||
{"term": {"doc_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": raw_id}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
@@ -220,11 +247,23 @@ class PatentSearchClient:
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {"term": {"doc_number": raw_id}},
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against publication_number; tries the ID as-is."""
|
||||
raw_id = patent_id.upper().removeprefix("US")
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"term": {"publication_number": raw_id}},
|
||||
{"term": {"publication_number": remove_year(raw_id)}},
|
||||
{"term": {"application_number": raw_id}},
|
||||
{"term": {"application_number": remove_year(raw_id)}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
@@ -235,11 +274,24 @@ class PatentSearchClient:
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"term": {"publication_number": patent_id}},
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title_en (and title_de as a should clause)."""
|
||||
def _epo_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||
"""match fallback on title_en (and title_de as a should clause)."""
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
{"match_phrase": {"title_fr": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
@@ -248,20 +300,19 @@ class PatentSearchClient:
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
{"match_phrase": {"title_fr": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
"query": query
|
||||
}
|
||||
|
||||
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title."""
|
||||
def _uspto_query_by_title(self, title: str, filling_date: str | None, size: int) -> dict[str, Any]:
|
||||
"""match fallback on title."""
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"should": [{"match_phrase": {"title": title}}],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
if filling_date:
|
||||
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
@@ -270,5 +321,5 @@ class PatentSearchClient:
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"match_phrase": {"title": title}},
|
||||
}
|
||||
"query": query,
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Patent lookup by institution assignee."""
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Business logic for patent lookup by institution assignee."""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.patents.common import model
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.parsing import (
|
||||
deduplicate_patents,
|
||||
enrich_patents_classifications,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
)
|
||||
from inse.patents.institutions.name_matching import (
|
||||
MIN_INSTITUTION_ACRONYM_LEN,
|
||||
assignee_matches_institution_name,
|
||||
institution_search_variants,
|
||||
)
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_patents_by_institution_id(
|
||||
institution_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
institutions_client: InstitutionsSearchClient | None = None,
|
||||
) -> model.PatentsByInstitutionResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
institution_client = institutions_client or InstitutionsSearchClient()
|
||||
|
||||
short_id = institution_id.replace("https://openalex.org/", "")
|
||||
institution = institution_client.get_institution_by_id(short_id)
|
||||
search_names = _institution_search_names(institution)
|
||||
|
||||
if not search_names:
|
||||
return model.PatentsByInstitutionResponse(
|
||||
institution_id=short_id,
|
||||
institution_name=institution.display_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
try:
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
search_client.search_epo(
|
||||
search_client.epo_query_by_applicant(search_names)
|
||||
),
|
||||
search_client.search_uspto(
|
||||
search_client.uspto_query_by_assignee(search_names)
|
||||
),
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Patent search request failed.",
|
||||
) from exc
|
||||
|
||||
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
all_patents = filter_patents_by_institution(all_patents, institution)
|
||||
all_patents = deduplicate_patents(all_patents)
|
||||
|
||||
await enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByInstitutionResponse(
|
||||
institution_id=short_id,
|
||||
institution_name=institution.display_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
def _institution_search_names(institution: Institution) -> list[str]:
|
||||
names: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _add(name: str | None) -> None:
|
||||
if not name or not name.strip():
|
||||
return
|
||||
for variant in institution_search_variants(name.strip()):
|
||||
key = variant.casefold()
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
names.append(variant)
|
||||
|
||||
_add(institution.display_name)
|
||||
for alternative in institution.display_name_alternatives or []:
|
||||
_add(alternative)
|
||||
for acronym in institution.display_name_acronyms or []:
|
||||
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
|
||||
_add(acronym)
|
||||
|
||||
return names
|
||||
|
||||
|
||||
def _institution_canonical_names(institution: Institution) -> list[str]:
|
||||
names: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _add(name: str | None) -> None:
|
||||
if not name or not name.strip():
|
||||
return
|
||||
key = name.strip().casefold()
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
names.append(name.strip())
|
||||
|
||||
_add(institution.display_name)
|
||||
for alternative in institution.display_name_alternatives or []:
|
||||
_add(alternative)
|
||||
for acronym in institution.display_name_acronyms or []:
|
||||
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
|
||||
_add(acronym)
|
||||
|
||||
return names
|
||||
|
||||
|
||||
def filter_patents_by_institution(
|
||||
patents: list[model.PatentEntry],
|
||||
institution: Institution,
|
||||
) -> list[model.PatentEntry]:
|
||||
canonical_names = _institution_canonical_names(institution)
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(
|
||||
assignee_matches_institution_name(assignee, name)
|
||||
for assignee in patent.assignees
|
||||
for name in canonical_names
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Institution assignee name normalization and matching."""
|
||||
from inse.patents.common.text_normalization import (
|
||||
name_token_variants,
|
||||
normalize_name_part,
|
||||
patent_transliteration_expansions,
|
||||
)
|
||||
|
||||
_INSTITUTION_GENERIC_TOKENS = frozenset({
|
||||
"university", "universitat", "universitaet", "universiteit", "college",
|
||||
"institute", "institut", "institution", "national", "sciences", "science",
|
||||
"school", "center", "centre", "laboratory", "department", "academy",
|
||||
"the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und",
|
||||
"fur", "von",
|
||||
})
|
||||
|
||||
MIN_INSTITUTION_SUBSTRING_LEN = 6
|
||||
MIN_INSTITUTION_VARIANT_LEN = 4
|
||||
MIN_INSTITUTION_ACRONYM_LEN = 3
|
||||
|
||||
|
||||
def institution_search_variants(value: str | None) -> list[str]:
|
||||
if not value or not value.strip():
|
||||
return []
|
||||
|
||||
stripped = value.strip()
|
||||
min_len = (
|
||||
MIN_INSTITUTION_ACRONYM_LEN
|
||||
if stripped.isupper() and " " not in stripped
|
||||
else MIN_INSTITUTION_VARIANT_LEN
|
||||
)
|
||||
|
||||
seen: set[str] = set()
|
||||
ordered: list[str] = []
|
||||
|
||||
def _add(candidate: str) -> None:
|
||||
candidate = candidate.strip()
|
||||
if len(candidate) < min_len:
|
||||
return
|
||||
key = candidate.casefold()
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
ordered.append(candidate)
|
||||
|
||||
_add(stripped)
|
||||
|
||||
normalized = normalize_name_part(value)
|
||||
if normalized:
|
||||
_add(normalized.title())
|
||||
|
||||
for variant in name_token_variants(value):
|
||||
_add(variant.title())
|
||||
|
||||
for variant in patent_transliteration_expansions(normalized):
|
||||
_add(variant.title())
|
||||
|
||||
return ordered
|
||||
|
||||
|
||||
def _significant_institution_tokens(text: str) -> set[str]:
|
||||
return {
|
||||
token
|
||||
for token in normalize_name_part(text).split()
|
||||
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
|
||||
and token not in _INSTITUTION_GENERIC_TOKENS
|
||||
}
|
||||
|
||||
|
||||
def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool:
|
||||
norm_assignee = normalize_name_part(assignee)
|
||||
norm_name = normalize_name_part(institution_name)
|
||||
if not norm_assignee or not norm_name:
|
||||
return False
|
||||
|
||||
original = institution_name.strip()
|
||||
assignee_tokens = set(norm_assignee.split())
|
||||
|
||||
if len(original) <= 6 and " " not in original:
|
||||
return norm_name in assignee_tokens
|
||||
|
||||
if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN:
|
||||
if norm_name in norm_assignee or norm_assignee in norm_name:
|
||||
return True
|
||||
|
||||
significant = _significant_institution_tokens(institution_name)
|
||||
if not significant:
|
||||
return False
|
||||
|
||||
matched = significant & assignee_tokens
|
||||
if len(significant) >= 2:
|
||||
return len(matched) >= 2
|
||||
return bool(matched)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Elasticsearch query builders for institution assignee patent search."""
|
||||
from typing import Any
|
||||
|
||||
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
|
||||
from inse.patents.institutions.name_matching import institution_search_variants
|
||||
|
||||
|
||||
class AssigneeSearchQueries:
|
||||
def _match_organization_names(self, field: str, names: list[str]) -> dict[str, Any]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
for name in names:
|
||||
for variant in institution_search_variants(name):
|
||||
key = variant.casefold()
|
||||
if not variant or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
clauses.append({"match_phrase": {field: {"query": variant}}})
|
||||
|
||||
if not clauses:
|
||||
return {"match_none": {}}
|
||||
|
||||
return {
|
||||
"bool": {
|
||||
"should": clauses,
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
def epo_query_by_applicant(
|
||||
self,
|
||||
institution_names: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"cpc",
|
||||
],
|
||||
"query": self._match_organization_names("applicants_name", institution_names),
|
||||
}
|
||||
|
||||
def uspto_query_by_assignee(
|
||||
self,
|
||||
institution_names: list[str],
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": self._match_organization_names("assignees_orgs", institution_names),
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
from functools import lru_cache
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.patents.common import model
|
||||
from inse.patents.institutions import logic
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||
return InstitutionsSearchClient()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{id}/patents",
|
||||
operation_id="getPatentsByInstitution",
|
||||
response_model=model.PatentsByInstitutionResponse,
|
||||
summary="Get patents matched to an institution by assignee name.",
|
||||
)
|
||||
async def get_patents_by_institution(
|
||||
id: str,
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
) -> model.PatentsByInstitutionResponse:
|
||||
return await logic.get_patents_by_institution_id(
|
||||
institution_id=id,
|
||||
institutions_client=client,
|
||||
)
|
||||
@@ -1,8 +1,12 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for patent matching by author name.
|
||||
"""
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.all.logic import get_all_patents
|
||||
from inse.patents.authors.logic import get_patents_by_author_id
|
||||
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
|
||||
from inse.patents.institutions.logic import (
|
||||
filter_patents_by_institution as _filter_patents_by_institution,
|
||||
get_patents_by_institution_id,
|
||||
)
|
||||
|
||||
import logging
|
||||
import asyncio
|
||||
|
||||
@@ -16,22 +20,28 @@ from .elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from .ipc_search_client import IpcSearchClient
|
||||
from .ipc_lookup import extract_ipc_symbol
|
||||
from .name_matching import name_matches
|
||||
|
||||
from datetime import datetime
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def normalize_patent_date(date_str: str) -> str:
|
||||
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
|
||||
|
||||
async def get_patent(
|
||||
patent_id: str,
|
||||
title: str,
|
||||
prefix: str,
|
||||
filling_date: str | None = None,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentEntry:
|
||||
search_client = client or PatentSearchClient()
|
||||
|
||||
if filling_date:
|
||||
filling_date = normalize_patent_date(filling_date)
|
||||
data = await search_client.get_by_id_or_title(
|
||||
patent_id=patent_id,
|
||||
prefix=prefix,
|
||||
title=title,
|
||||
filling_date=filling_date,
|
||||
)
|
||||
|
||||
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
||||
@@ -309,4 +319,4 @@ async def get_all_patents(
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1,47 +1,2 @@
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class IpcClassification(BaseModel):
|
||||
symbol: str
|
||||
section: str | None = None
|
||||
ipc_class: str | None = Field(default=None, serialization_alias="class")
|
||||
subclass: str | None = None
|
||||
main_group: str | None = None
|
||||
subgroup: str | None = None
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
|
||||
class PatentEntry(BaseModel):
|
||||
patent_id: str
|
||||
source: str # "EPO" or "USPTO"
|
||||
title: str | None = None
|
||||
abstract: str | None = None
|
||||
publication_date: str | None = None
|
||||
publication_year: str | None = None
|
||||
application_number: str | None = None
|
||||
application_date: str | None = None
|
||||
kind: str | None = None # EPO only
|
||||
application_type: str | None = None # USPTO only
|
||||
number_of_claims: int | None = None # USPTO only
|
||||
status: str | None = None # USPTO only
|
||||
inventors: list[str] = Field(default_factory=list)
|
||||
assignees: list[str] = Field(default_factory=list)
|
||||
ipc: list[str] = Field(default_factory=list)
|
||||
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
cpc: list[str] = Field(default_factory=list)
|
||||
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
|
||||
country: str | None = None
|
||||
|
||||
|
||||
class PatentsByAuthorResponse(BaseModel):
|
||||
author_id: str
|
||||
author_name: str | None = None
|
||||
patent_count: int
|
||||
patents: list[PatentEntry]
|
||||
|
||||
class AllPatentsResponse(BaseModel):
|
||||
total: int
|
||||
page: int
|
||||
size: int
|
||||
patents: list[PatentEntry]
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.common.model import * # noqa: F403
|
||||
|
||||
@@ -1,242 +1,18 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Name normalization and matching for patent inventor lookup.
|
||||
|
||||
Handles umlauts, diacritics, and common Latin transliterations so that
|
||||
e.g. 'Müller' matches 'Mueller' and 'Muller'.
|
||||
"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
# Characters that NFKD does not map to ASCII-friendly forms.
|
||||
_CHAR_REPLACEMENTS: dict[str, str] = {
|
||||
"ß": "ss",
|
||||
"ẞ": "ss",
|
||||
"æ": "ae",
|
||||
"Æ": "ae",
|
||||
"œ": "oe",
|
||||
"Œ": "oe",
|
||||
"ø": "o",
|
||||
"Ø": "o",
|
||||
"đ": "d",
|
||||
"Đ": "d",
|
||||
"ð": "d",
|
||||
"Ð": "d",
|
||||
"þ": "th",
|
||||
"Þ": "th",
|
||||
"ł": "l",
|
||||
"Ł": "l",
|
||||
"ı": "i",
|
||||
"ſ": "s",
|
||||
}
|
||||
|
||||
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
|
||||
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
|
||||
("ae", "a"),
|
||||
("oe", "o"),
|
||||
("ue", "u"),
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.authors.name_matching import ( # noqa: F401
|
||||
first_name_match_kind,
|
||||
name_matches,
|
||||
search_name_variants,
|
||||
tokens_equal,
|
||||
)
|
||||
|
||||
# Common ASCII spellings in patent records for umlaut-derived vowels.
|
||||
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
|
||||
(r"u([lmnrt])", r"ue\1"),
|
||||
(r"o([lmnrt])", r"oe\1"),
|
||||
(r"a([lmnrt])", r"ae\1"),
|
||||
from inse.patents.common.text_normalization import ( # noqa: F401
|
||||
name_token_variants,
|
||||
normalize_name_part,
|
||||
)
|
||||
from inse.patents.institutions.name_matching import ( # noqa: F401
|
||||
MIN_INSTITUTION_ACRONYM_LEN,
|
||||
MIN_INSTITUTION_SUBSTRING_LEN,
|
||||
MIN_INSTITUTION_VARIANT_LEN,
|
||||
assignee_matches_institution_name,
|
||||
institution_search_variants,
|
||||
)
|
||||
|
||||
|
||||
def normalize_name_part(value: str | None) -> str:
|
||||
"""
|
||||
Normalize a single name token for comparison.
|
||||
|
||||
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
|
||||
-> remove apostrophes/punctuation -> collapse whitespace.
|
||||
"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
text = value.strip()
|
||||
for src, dst in _CHAR_REPLACEMENTS.items():
|
||||
text = text.replace(src, dst)
|
||||
|
||||
text = unicodedata.normalize("NFKD", text)
|
||||
text = "".join(c for c in text if not unicodedata.combining(c))
|
||||
text = text.lower()
|
||||
text = re.sub(r"[''`´]", "", text)
|
||||
text = re.sub(r"[^\w\s-]", "", text)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text
|
||||
|
||||
|
||||
def name_token_variants(value: str | None) -> set[str]:
|
||||
"""
|
||||
Return equivalent forms of a name token.
|
||||
|
||||
Includes the normalized base plus German digraph collapses
|
||||
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
|
||||
"""
|
||||
base = normalize_name_part(value)
|
||||
if not base:
|
||||
return set()
|
||||
|
||||
variants = {base}
|
||||
|
||||
for src, dst in _DIGRAPH_COLLAPSES:
|
||||
if src in base:
|
||||
variants.add(base.replace(src, dst))
|
||||
|
||||
if "-" in base:
|
||||
variants.add(base.replace("-", ""))
|
||||
variants.add(base.replace("-", " "))
|
||||
|
||||
return {v for v in variants if v}
|
||||
|
||||
|
||||
def _patent_transliteration_expansions(normalized: str) -> set[str]:
|
||||
"""
|
||||
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
|
||||
|
||||
Used for Elasticsearch recall only; post-filter applies stricter matching.
|
||||
"""
|
||||
expanded = {normalized}
|
||||
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
|
||||
if re.search(pattern, normalized):
|
||||
expanded.add(re.sub(pattern, repl, normalized))
|
||||
return expanded
|
||||
|
||||
|
||||
def tokens_equal(
|
||||
left: str | None,
|
||||
right: str | None,
|
||||
*,
|
||||
allow_initial: bool = True,
|
||||
) -> bool:
|
||||
"""True when two name tokens are equivalent after normalization."""
|
||||
left_variants = name_token_variants(left)
|
||||
right_variants = name_token_variants(right)
|
||||
if not left_variants or not right_variants:
|
||||
return False
|
||||
if left_variants & right_variants:
|
||||
return True
|
||||
|
||||
if not allow_initial:
|
||||
return False
|
||||
|
||||
return _initial_tokens_match(left, right)
|
||||
|
||||
|
||||
def _initial_letter(token: str | None) -> str | None:
|
||||
normalized = normalize_name_part(token)
|
||||
if len(normalized) == 1 and normalized.isalpha():
|
||||
return normalized
|
||||
return None
|
||||
|
||||
|
||||
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
|
||||
"""True when one token is a single-letter initial matching the other token."""
|
||||
left_initial = _initial_letter(left)
|
||||
right_initial = _initial_letter(right)
|
||||
left_full = normalize_name_part(left)
|
||||
right_full = normalize_name_part(right)
|
||||
|
||||
if left_initial and right_full and len(right_full) > 1:
|
||||
return right_full.startswith(left_initial)
|
||||
if right_initial and left_full and len(left_full) > 1:
|
||||
return left_full.startswith(right_initial)
|
||||
if left_initial and right_initial:
|
||||
return left_initial == right_initial
|
||||
return False
|
||||
|
||||
|
||||
def _inventor_first_token(inventor_name: str) -> str:
|
||||
if "," in inventor_name:
|
||||
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
|
||||
return first_part.split()[0] if first_part else ""
|
||||
parts = inventor_name.split()
|
||||
return parts[0] if parts else ""
|
||||
|
||||
|
||||
def first_name_match_kind(
|
||||
inventor_name: str,
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> str:
|
||||
"""
|
||||
Match quality for the inventor first name: 'full', 'initial', or 'none'.
|
||||
"""
|
||||
if not name_matches(inventor_name, first_name, last_name):
|
||||
return "none"
|
||||
|
||||
inventor_first = _inventor_first_token(inventor_name)
|
||||
if tokens_equal(inventor_first, first_name, allow_initial=False):
|
||||
return "full"
|
||||
return "initial"
|
||||
|
||||
|
||||
def search_name_variants(value: str | None) -> list[str]:
|
||||
"""
|
||||
Distinct search strings for Elasticsearch, preserving original casing
|
||||
where useful but including normalized and transliterated forms.
|
||||
"""
|
||||
if not value or not value.strip():
|
||||
return []
|
||||
|
||||
seen: set[str] = set()
|
||||
ordered: list[str] = []
|
||||
|
||||
def _add(candidate: str) -> None:
|
||||
key = candidate.casefold()
|
||||
if candidate.strip() and key not in seen:
|
||||
seen.add(key)
|
||||
ordered.append(candidate.strip())
|
||||
|
||||
_add(value.strip())
|
||||
|
||||
normalized = normalize_name_part(value)
|
||||
if normalized:
|
||||
_add(normalized.title())
|
||||
|
||||
for variant in name_token_variants(value):
|
||||
_add(variant.title())
|
||||
|
||||
for variant in _patent_transliteration_expansions(normalized):
|
||||
_add(variant.title())
|
||||
|
||||
if normalized and len(normalized) > 1:
|
||||
_add(normalized[0].upper())
|
||||
|
||||
return ordered
|
||||
|
||||
|
||||
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
|
||||
"""
|
||||
True when an inventor entry matches first_name + last_name.
|
||||
|
||||
Supports:
|
||||
- USPTO: 'Christian Weber', 'Christian Hans Weber'
|
||||
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
|
||||
"""
|
||||
if not inventor_name or not last_name:
|
||||
return False
|
||||
|
||||
name = inventor_name.strip()
|
||||
|
||||
if "," in name:
|
||||
last_part, first_part = [p.strip() for p in name.split(",", 1)]
|
||||
first_token = first_part.split()[0] if first_part else ""
|
||||
return (
|
||||
tokens_equal(last_part, last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(first_token, first_name)
|
||||
)
|
||||
|
||||
parts = name.split()
|
||||
if len(parts) < 2:
|
||||
return False
|
||||
|
||||
return (
|
||||
tokens_equal(parts[-1], last_name, allow_initial=False)
|
||||
and bool(first_name)
|
||||
and tokens_equal(parts[0], first_name)
|
||||
)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Org patents index: institution-scoped patent aggregation."""
|
||||
@@ -0,0 +1,199 @@
|
||||
"""HTTP client for the org_patents Elasticsearch index."""
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING
|
||||
from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry
|
||||
from inse import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PAGE_SIZE = 20
|
||||
|
||||
|
||||
class OrgPatentsSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 60.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self, content_type: str = "application/json") -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": content_type,
|
||||
}
|
||||
|
||||
async def ensure_index(self) -> None:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.head(
|
||||
f"/{ORG_PATENTS_INDEX}",
|
||||
headers=self._headers(),
|
||||
)
|
||||
if response.status_code == 404:
|
||||
create_response = await client.put(
|
||||
f"/{ORG_PATENTS_INDEX}",
|
||||
headers=self._headers(),
|
||||
json={"mappings": ORG_PATENTS_MAPPING},
|
||||
)
|
||||
create_response.raise_for_status()
|
||||
logger.info("Created index %s", ORG_PATENTS_INDEX)
|
||||
return
|
||||
|
||||
response.raise_for_status()
|
||||
mapping_response = await client.put(
|
||||
f"/{ORG_PATENTS_INDEX}/_mapping",
|
||||
headers=self._headers(),
|
||||
json=ORG_PATENTS_MAPPING,
|
||||
)
|
||||
mapping_response.raise_for_status()
|
||||
|
||||
async def delete_by_institution(self, institution_id: str) -> int:
|
||||
payload = {
|
||||
"query": {"term": {"institution_id": institution_id.upper()}},
|
||||
}
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{ORG_PATENTS_INDEX}/_delete_by_query",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
params={"refresh": "true"},
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return 0
|
||||
response.raise_for_status()
|
||||
return response.json().get("deleted", 0)
|
||||
|
||||
async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None:
|
||||
if not documents:
|
||||
return
|
||||
|
||||
batch_size = 500
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
for start in range(0, len(documents), batch_size):
|
||||
batch = documents[start : start + batch_size]
|
||||
bulk_lines: list[str] = []
|
||||
for doc_id, source in batch:
|
||||
bulk_lines.append(json.dumps({"index": {"_index": ORG_PATENTS_INDEX, "_id": doc_id}}))
|
||||
bulk_lines.append(json.dumps(source))
|
||||
|
||||
payload = "\n".join(bulk_lines) + "\n"
|
||||
response = await client.post(
|
||||
"/_bulk",
|
||||
content=payload,
|
||||
headers=self._headers("application/x-ndjson"),
|
||||
params={"refresh": "true"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
if result.get("errors"):
|
||||
failed = [
|
||||
item
|
||||
for item in result.get("items", [])
|
||||
if item.get("index", {}).get("status", 200) >= 400
|
||||
]
|
||||
logger.error("Bulk index errors: %s", failed[:3])
|
||||
raise RuntimeError("Bulk indexing into org_patents failed.")
|
||||
|
||||
async def search_by_institution(
|
||||
self,
|
||||
institution_id: str,
|
||||
match_type: MatchTypeFilter = "all",
|
||||
page: int = 0,
|
||||
size: int = DEFAULT_PAGE_SIZE,
|
||||
source: str | None = None,
|
||||
) -> tuple[list[OrgPatentEntry], int]:
|
||||
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
||||
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
|
||||
|
||||
if match_type == "institution":
|
||||
filters.append({"terms": {"match_type": ["institution", "both"]}})
|
||||
elif match_type == "name":
|
||||
filters.append({"terms": {"match_type": ["name", "both"]}})
|
||||
elif match_type == "both":
|
||||
filters.append({"term": {"match_type": "both"}})
|
||||
|
||||
if source in ("EPO", "USPTO"):
|
||||
filters.append({"term": {"source": source}})
|
||||
|
||||
payload = {
|
||||
"from": page * size,
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"query": {"bool": {"filter": filters}},
|
||||
"sort": [
|
||||
{"publication_year": {"order": "desc", "missing": "_last"}},
|
||||
{"patent_id": {"order": "asc"}},
|
||||
],
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{ORG_PATENTS_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return [], 0
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
total = data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])]
|
||||
return patents, total
|
||||
|
||||
|
||||
def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
|
||||
source = hit.get("_source", {})
|
||||
publication_year = source.get("publication_year")
|
||||
return OrgPatentEntry(
|
||||
institution_id=source.get("institution_id", ""),
|
||||
institution_name=source.get("institution_name"),
|
||||
patent_id=source.get("patent_id", ""),
|
||||
source=source.get("source", ""),
|
||||
match_type=source.get("match_type", "institution"),
|
||||
title=source.get("title"),
|
||||
abstract=source.get("abstract"),
|
||||
publication_date=source.get("publication_date"),
|
||||
publication_year=str(publication_year) if publication_year is not None else None,
|
||||
application_number=source.get("application_number"),
|
||||
application_date=source.get("application_date"),
|
||||
kind=source.get("kind"),
|
||||
application_type=source.get("application_type"),
|
||||
number_of_claims=source.get("number_of_claims"),
|
||||
status=source.get("status"),
|
||||
inventors=source.get("inventors") or [],
|
||||
assignees=source.get("assignees") or [],
|
||||
ipc=source.get("ipc") or [],
|
||||
cpc=source.get("cpc") or [],
|
||||
country=source.get("country"),
|
||||
matched_authors=source.get("matched_authors") or [],
|
||||
)
|
||||
@@ -0,0 +1,429 @@
|
||||
"""Business logic for org_patents index build and retrieval."""
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.patents.authors.name_matching import name_matches
|
||||
from inse.patents.common.elastic_search_client import MissingApiKeyError
|
||||
from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.common.parsing import (
|
||||
deduplicate_patents,
|
||||
enrich_patents_classifications,
|
||||
parse_epo_hits,
|
||||
parse_uspto_hits,
|
||||
patent_dedup_key,
|
||||
)
|
||||
from inse.patents.institutions.logic import get_patents_by_institution_id
|
||||
from inse.patents.ipc_search_client import IpcSearchClient
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
from inse.patents.org.model import (
|
||||
MatchType,
|
||||
MatchTypeFilter,
|
||||
MatchedAuthor,
|
||||
OrgPatentEntry,
|
||||
OrgPatentsResponse,
|
||||
)
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
AUTHOR_PAGE_SIZE = 500
|
||||
ORG_PATENT_SEARCH_SIZE = 500
|
||||
AUTHOR_SEARCH_CONCURRENCY = 8
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[PatentEntry]:
|
||||
return [
|
||||
patent
|
||||
for patent in patents
|
||||
if any(
|
||||
name_matches(inventor, first_name, last_name)
|
||||
for inventor in patent.inventors
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _AccumulatedPatent:
|
||||
patent: PatentEntry
|
||||
institution_match: bool = False
|
||||
matched_authors: dict[str, MatchedAuthor] = field(default_factory=dict)
|
||||
|
||||
|
||||
def normalize_institution_id(institution_id: str) -> str:
|
||||
return institution_id.replace("https://openalex.org/", "").upper()
|
||||
|
||||
|
||||
def normalize_author_id(author_id: str | None) -> str:
|
||||
if not author_id:
|
||||
return ""
|
||||
return author_id.replace("https://openalex.org/", "").upper()
|
||||
|
||||
|
||||
def org_patent_document_id(institution_id: str, patent: PatentEntry) -> str:
|
||||
stage = patent.kind or patent.application_type or "none"
|
||||
safe_patent_id = re.sub(r"[^A-Za-z0-9_-]", "_", patent.patent_id)
|
||||
safe_date = patent.publication_date or "none"
|
||||
safe_stage = re.sub(r"[^A-Za-z0-9_-]", "_", stage)
|
||||
return f"{normalize_institution_id(institution_id)}_{patent.source}_{safe_patent_id}_{safe_date}_{safe_stage}"
|
||||
|
||||
|
||||
def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchType:
|
||||
if institution_match and has_name_match:
|
||||
return "both"
|
||||
if institution_match:
|
||||
return "institution"
|
||||
return "name"
|
||||
|
||||
|
||||
def merge_org_patents(
|
||||
institution_id: str,
|
||||
institution_name: str | None,
|
||||
institution_patents: list[PatentEntry],
|
||||
author_patents: list[tuple[Author, list[PatentEntry]]],
|
||||
) -> list[OrgPatentEntry]:
|
||||
accumulated: dict[tuple[str, str, str, str], _AccumulatedPatent] = {}
|
||||
|
||||
for patent in institution_patents:
|
||||
key = patent_dedup_key(patent)
|
||||
entry = accumulated.get(key)
|
||||
if entry is None:
|
||||
accumulated[key] = _AccumulatedPatent(patent=patent, institution_match=True)
|
||||
else:
|
||||
entry.institution_match = True
|
||||
|
||||
for author, patents in author_patents:
|
||||
author_id = normalize_author_id(author.id)
|
||||
author_name = author.display_name or ""
|
||||
if not author_id or not author_name:
|
||||
continue
|
||||
|
||||
matched_author = MatchedAuthor(
|
||||
openalex_author_id=author_id,
|
||||
author_name=author_name,
|
||||
)
|
||||
for patent in patents:
|
||||
key = patent_dedup_key(patent)
|
||||
entry = accumulated.get(key)
|
||||
if entry is None:
|
||||
accumulated[key] = _AccumulatedPatent(
|
||||
patent=patent,
|
||||
matched_authors={author_id: matched_author},
|
||||
)
|
||||
else:
|
||||
entry.matched_authors[author_id] = matched_author
|
||||
|
||||
org_patents: list[OrgPatentEntry] = []
|
||||
short_institution_id = normalize_institution_id(institution_id)
|
||||
|
||||
for entry in accumulated.values():
|
||||
has_name_match = bool(entry.matched_authors)
|
||||
match_type = resolve_match_type(entry.institution_match, has_name_match)
|
||||
org_patents.append(
|
||||
OrgPatentEntry(
|
||||
institution_id=short_institution_id,
|
||||
institution_name=institution_name,
|
||||
match_type=match_type,
|
||||
matched_authors=list(entry.matched_authors.values()),
|
||||
**entry.patent.model_dump(),
|
||||
)
|
||||
)
|
||||
|
||||
org_patents.sort(
|
||||
key=lambda patent: (
|
||||
patent.publication_year or "",
|
||||
patent.patent_id,
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
return org_patents
|
||||
|
||||
|
||||
def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
|
||||
publication_year = None
|
||||
if patent.publication_year:
|
||||
try:
|
||||
publication_year = int(patent.publication_year)
|
||||
except ValueError:
|
||||
publication_year = None
|
||||
|
||||
return {
|
||||
"institution_id": patent.institution_id,
|
||||
"institution_name": patent.institution_name,
|
||||
"patent_id": patent.patent_id,
|
||||
"source": patent.source,
|
||||
"match_type": patent.match_type,
|
||||
"title": patent.title,
|
||||
"abstract": patent.abstract,
|
||||
"publication_date": patent.publication_date,
|
||||
"publication_year": publication_year,
|
||||
"application_number": patent.application_number,
|
||||
"application_date": patent.application_date,
|
||||
"kind": patent.kind,
|
||||
"application_type": patent.application_type,
|
||||
"number_of_claims": patent.number_of_claims,
|
||||
"status": patent.status,
|
||||
"inventors": patent.inventors,
|
||||
"assignees": patent.assignees,
|
||||
"ipc": patent.ipc,
|
||||
"cpc": patent.cpc,
|
||||
"country": patent.country,
|
||||
"matched_authors": [
|
||||
author.model_dump() for author in patent.matched_authors
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def fetch_authors_for_institution(institution_id: str) -> list[Author]:
|
||||
short_id = normalize_institution_id(institution_id)
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"term": {
|
||||
"last_known_institutions.id": f"https://openalex.org/{short_id}",
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
authors: list[Author] = []
|
||||
search_after: list | None = None
|
||||
sort = [
|
||||
{"works_count": {"order": "desc"}},
|
||||
{"id": {"order": "asc"}},
|
||||
]
|
||||
|
||||
while True:
|
||||
body: dict = {
|
||||
"size": AUTHOR_PAGE_SIZE,
|
||||
"query": query,
|
||||
"sort": sort,
|
||||
}
|
||||
if search_after:
|
||||
body["search_after"] = search_after
|
||||
|
||||
response = elasticsearch.search(index="openalex-authors", body=body)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
source = dict(hit.get("_source", {}))
|
||||
source["id"] = source.get("id") or hit.get("_id", "")
|
||||
author = Author.from_dict(source)
|
||||
if author:
|
||||
authors.append(author)
|
||||
|
||||
if len(hits) < AUTHOR_PAGE_SIZE:
|
||||
break
|
||||
search_after = hits[-1].get("sort")
|
||||
if not search_after:
|
||||
break
|
||||
|
||||
return authors
|
||||
|
||||
|
||||
async def _search_patents_by_author(
|
||||
author: Author,
|
||||
search_client: PatentSearchClient,
|
||||
) -> list[PatentEntry]:
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
if not last_name:
|
||||
return []
|
||||
|
||||
try:
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
search_client.search_epo(
|
||||
search_client.epo_query_by_inventor(
|
||||
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
|
||||
)
|
||||
),
|
||||
search_client.search_uspto(
|
||||
search_client.uspto_query_by_inventor(
|
||||
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
|
||||
)
|
||||
),
|
||||
)
|
||||
except (MissingApiKeyError, httpx.HTTPError):
|
||||
raise
|
||||
|
||||
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
|
||||
if first_name and last_name:
|
||||
patents = _filter_patents_by_name(patents, first_name, last_name)
|
||||
return deduplicate_patents(patents)
|
||||
|
||||
|
||||
async def build_org_patents_for_institution(
|
||||
institution_id: str,
|
||||
search_client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
institutions_client: InstitutionsSearchClient | None = None,
|
||||
) -> list[OrgPatentEntry]:
|
||||
patent_client = search_client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
institution_client = institutions_client or InstitutionsSearchClient()
|
||||
|
||||
short_id = normalize_institution_id(institution_id)
|
||||
institution = institution_client.get_institution_by_id(short_id)
|
||||
institution_name = institution.display_name
|
||||
|
||||
institution_response = await get_patents_by_institution_id(
|
||||
institution_id=short_id,
|
||||
client=patent_client,
|
||||
ipc_client=ipc_search_client,
|
||||
institutions_client=institution_client,
|
||||
)
|
||||
institution_patents = institution_response.patents
|
||||
|
||||
authors = fetch_authors_for_institution(short_id)
|
||||
logger.info(
|
||||
"Building org_patents for %s (%s): %d authors, %d institution patents",
|
||||
institution_name,
|
||||
short_id,
|
||||
len(authors),
|
||||
len(institution_patents),
|
||||
)
|
||||
|
||||
semaphore = asyncio.Semaphore(AUTHOR_SEARCH_CONCURRENCY)
|
||||
|
||||
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
|
||||
async with semaphore:
|
||||
patents = await _search_patents_by_author(author, patent_client)
|
||||
return author, patents
|
||||
|
||||
author_results = await asyncio.gather(
|
||||
*[_fetch_for_author(author) for author in authors],
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
author_patents: list[tuple[Author, list[PatentEntry]]] = []
|
||||
for result in author_results:
|
||||
if isinstance(result, Exception):
|
||||
logger.warning("Author patent search failed: %s", result)
|
||||
continue
|
||||
author_patents.append(result)
|
||||
|
||||
org_patents = merge_org_patents(
|
||||
institution_id=short_id,
|
||||
institution_name=institution_name,
|
||||
institution_patents=institution_patents,
|
||||
author_patents=author_patents,
|
||||
)
|
||||
|
||||
await enrich_patents_classifications(
|
||||
[patent for patent in org_patents],
|
||||
ipc_search_client,
|
||||
)
|
||||
return org_patents
|
||||
|
||||
|
||||
async def index_org_patents_for_institution(
|
||||
institution_id: str,
|
||||
search_client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
institutions_client: InstitutionsSearchClient | None = None,
|
||||
org_client: OrgPatentsSearchClient | None = None,
|
||||
) -> int:
|
||||
short_id = normalize_institution_id(institution_id)
|
||||
org_patents_client = org_client or OrgPatentsSearchClient()
|
||||
|
||||
org_patents = await build_org_patents_for_institution(
|
||||
institution_id=short_id,
|
||||
search_client=search_client,
|
||||
ipc_client=ipc_client,
|
||||
institutions_client=institutions_client,
|
||||
)
|
||||
|
||||
await org_patents_client.ensure_index()
|
||||
deleted = await org_patents_client.delete_by_institution(short_id)
|
||||
logger.info("Deleted %d existing org_patents documents for %s", deleted, short_id)
|
||||
|
||||
documents = [
|
||||
(
|
||||
org_patent_document_id(short_id, patent),
|
||||
org_patent_to_es_document(patent),
|
||||
)
|
||||
for patent in org_patents
|
||||
]
|
||||
await org_patents_client.bulk_index(documents)
|
||||
logger.info("Indexed %d org_patents documents for %s", len(documents), short_id)
|
||||
return len(documents)
|
||||
|
||||
|
||||
async def get_org_patents_by_institution_id(
|
||||
institution_id: str,
|
||||
match_type: MatchTypeFilter = "all",
|
||||
page: int = 0,
|
||||
size: int = 20,
|
||||
source: str | None = None,
|
||||
org_client: OrgPatentsSearchClient | None = None,
|
||||
institutions_client: InstitutionsSearchClient | None = None,
|
||||
) -> OrgPatentsResponse:
|
||||
short_id = normalize_institution_id(institution_id)
|
||||
org_patents_client = org_client or OrgPatentsSearchClient()
|
||||
institution_client = institutions_client or InstitutionsSearchClient()
|
||||
|
||||
try:
|
||||
institution = institution_client.get_institution_by_id(short_id)
|
||||
institution_name = institution.display_name
|
||||
except Exception:
|
||||
institution_name = None
|
||||
|
||||
try:
|
||||
await org_patents_client.ensure_index()
|
||||
patents, total = await org_patents_client.search_by_institution(
|
||||
institution_id=short_id,
|
||||
match_type=match_type,
|
||||
page=page,
|
||||
size=size,
|
||||
source=source,
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Patent search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="org_patents search request failed.",
|
||||
) from exc
|
||||
|
||||
return OrgPatentsResponse(
|
||||
institution_id=short_id,
|
||||
institution_name=institution_name,
|
||||
patent_count=total,
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
ORG_PATENTS_INDEX = "org_patents"
|
||||
|
||||
ORG_PATENTS_MAPPING = {
|
||||
"properties": {
|
||||
"institution_id": {"type": "keyword"},
|
||||
"institution_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"patent_id": {"type": "keyword"},
|
||||
"source": {"type": "keyword"},
|
||||
"match_type": {"type": "keyword"},
|
||||
"title": {"type": "text"},
|
||||
"abstract": {"type": "text"},
|
||||
"publication_date": {"type": "keyword"},
|
||||
"publication_year": {"type": "integer"},
|
||||
"application_number": {"type": "keyword"},
|
||||
"application_date": {"type": "keyword"},
|
||||
"kind": {"type": "keyword"},
|
||||
"application_type": {"type": "keyword"},
|
||||
"number_of_claims": {"type": "integer"},
|
||||
"status": {"type": "keyword"},
|
||||
"inventors": {"type": "keyword"},
|
||||
"assignees": {"type": "keyword"},
|
||||
"ipc": {"type": "keyword"},
|
||||
"cpc": {"type": "keyword"},
|
||||
"country": {"type": "keyword"},
|
||||
"matched_authors": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"openalex_author_id": {"type": "keyword"},
|
||||
"author_name": {"type": "keyword"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.patents.common.model import PatentEntry
|
||||
|
||||
MatchType = Literal["institution", "name", "both"]
|
||||
MatchTypeFilter = Literal["institution", "name", "both", "all"]
|
||||
|
||||
|
||||
class MatchedAuthor(BaseModel):
|
||||
openalex_author_id: str
|
||||
author_name: str
|
||||
|
||||
|
||||
class OrgPatentEntry(PatentEntry):
|
||||
institution_id: str
|
||||
institution_name: str | None = None
|
||||
match_type: MatchType
|
||||
matched_authors: list[MatchedAuthor] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OrgPatentsResponse(BaseModel):
|
||||
institution_id: str
|
||||
institution_name: str | None = None
|
||||
patent_count: int
|
||||
page: int = 0
|
||||
size: int = 20
|
||||
patents: list[OrgPatentEntry]
|
||||
@@ -0,0 +1,44 @@
|
||||
from functools import lru_cache
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.patents.org import logic
|
||||
from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse
|
||||
|
||||
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_institutions_search_client() -> InstitutionsSearchClient:
|
||||
return InstitutionsSearchClient()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{id}/org-patents",
|
||||
operation_id="getOrgPatentsByInstitution",
|
||||
response_model=OrgPatentsResponse,
|
||||
summary="Get pre-indexed org patents for an institution.",
|
||||
)
|
||||
async def get_org_patents_by_institution(
|
||||
id: str,
|
||||
client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
match_type: Annotated[
|
||||
MatchTypeFilter,
|
||||
Query(description="Filter patents by match type."),
|
||||
] = "all",
|
||||
page: int = 0,
|
||||
size: int = 20,
|
||||
source: str | None = None,
|
||||
) -> OrgPatentsResponse:
|
||||
return await logic.get_org_patents_by_institution_id(
|
||||
institution_id=id,
|
||||
match_type=match_type,
|
||||
page=page,
|
||||
size=size,
|
||||
source=source,
|
||||
institutions_client=client,
|
||||
)
|
||||
@@ -0,0 +1,100 @@
|
||||
from inse.patents.common.model import PatentEntry
|
||||
from inse.patents.org.logic import merge_org_patents, org_patent_document_id, resolve_match_type
|
||||
from inse.patents.org.model import MatchedAuthor
|
||||
from inse.models.openalex.author import Author
|
||||
|
||||
|
||||
def _patent(
|
||||
patent_id: str = "EP1234567",
|
||||
source: str = "EPO",
|
||||
) -> PatentEntry:
|
||||
return PatentEntry(
|
||||
patent_id=patent_id,
|
||||
source=source,
|
||||
title="Example patent",
|
||||
publication_year="2024",
|
||||
)
|
||||
|
||||
|
||||
def _author(author_id: str, name: str) -> Author:
|
||||
return Author(
|
||||
id=f"https://openalex.org/{author_id}",
|
||||
display_name=name,
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_match_type() -> None:
|
||||
assert resolve_match_type(True, True) == "both"
|
||||
assert resolve_match_type(True, False) == "institution"
|
||||
assert resolve_match_type(False, True) == "name"
|
||||
|
||||
|
||||
def test_merge_org_patents_keeps_institution_only_patents() -> None:
|
||||
result = merge_org_patents(
|
||||
institution_id="I62318514",
|
||||
institution_name="University of Duisburg-Essen",
|
||||
institution_patents=[_patent("EP111")],
|
||||
author_patents=[],
|
||||
)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].match_type == "institution"
|
||||
assert result[0].matched_authors == []
|
||||
|
||||
|
||||
def test_merge_org_patents_keeps_name_only_patents() -> None:
|
||||
author = _author("A123", "Max Mustermann")
|
||||
result = merge_org_patents(
|
||||
institution_id="I62318514",
|
||||
institution_name="University of Duisburg-Essen",
|
||||
institution_patents=[],
|
||||
author_patents=[(author, [_patent("EP222")])],
|
||||
)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].match_type == "name"
|
||||
assert result[0].matched_authors[0].openalex_author_id == "A123"
|
||||
|
||||
|
||||
def test_merge_org_patents_marks_both_when_same_patent_found_twice() -> None:
|
||||
author = _author("A123", "Max Mustermann")
|
||||
patent = _patent("EP333")
|
||||
result = merge_org_patents(
|
||||
institution_id="I62318514",
|
||||
institution_name="University of Duisburg-Essen",
|
||||
institution_patents=[patent],
|
||||
author_patents=[(author, [patent])],
|
||||
)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].match_type == "both"
|
||||
assert len(result[0].matched_authors) == 1
|
||||
|
||||
|
||||
def test_merge_org_patents_deduplicates_and_collects_multiple_authors() -> None:
|
||||
author_one = _author("A111", "Max Mustermann")
|
||||
author_two = _author("A222", "Maria Muster")
|
||||
patent = _patent("EP444")
|
||||
result = merge_org_patents(
|
||||
institution_id="I62318514",
|
||||
institution_name="University of Duisburg-Essen",
|
||||
institution_patents=[],
|
||||
author_patents=[
|
||||
(author_one, [patent]),
|
||||
(author_two, [patent]),
|
||||
],
|
||||
)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].match_type == "name"
|
||||
assert {author.openalex_author_id for author in result[0].matched_authors} == {"A111", "A222"}
|
||||
|
||||
|
||||
def test_org_patent_document_id_is_stable() -> None:
|
||||
patent = _patent("EP1234567")
|
||||
patent.kind = "A1"
|
||||
patent.publication_date = "20240101"
|
||||
|
||||
doc_id = org_patent_document_id("I62318514", patent)
|
||||
|
||||
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Combined patent Elasticsearch client."""
|
||||
from inse.patents.authors.search_queries import InventorSearchQueries
|
||||
from inse.patents.common.elastic_search_client import (
|
||||
DEFAULT_SEARCH_SIZE,
|
||||
EPO_INDEX,
|
||||
USPTO_INDEX,
|
||||
BasePatentSearchClient,
|
||||
MissingApiKeyError,
|
||||
)
|
||||
from inse.patents.institutions.search_queries import AssigneeSearchQueries
|
||||
|
||||
|
||||
class PatentSearchClient(
|
||||
InventorSearchQueries,
|
||||
AssigneeSearchQueries,
|
||||
BasePatentSearchClient,
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_SEARCH_SIZE",
|
||||
"EPO_INDEX",
|
||||
"MissingApiKeyError",
|
||||
"PatentSearchClient",
|
||||
"USPTO_INDEX",
|
||||
]
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Aggregates patent API routers."""
|
||||
from fastapi import APIRouter
|
||||
from . import logic
|
||||
from . import model
|
||||
@@ -11,6 +10,10 @@ router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
|
||||
|
||||
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
|
||||
|
||||
from inse.patents.all.service import router as all_patents_router
|
||||
from inse.patents.authors.service import router as author_patents_router
|
||||
from inse.patents.institutions.service import router as institution_patents_router
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{author_id}/patents",
|
||||
@@ -37,8 +40,11 @@ async def get_patent_by_identifier(
|
||||
description="Do we want to fallback to title search if ID and DOI dont work?"
|
||||
),
|
||||
] = "",
|
||||
filling_date: Annotated[
|
||||
Optional[str], Query(description="Filling date in YYYY-MM-DD format")
|
||||
] = "",
|
||||
) -> model.PatentEntry | None:
|
||||
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title)
|
||||
return await logic.get_patent(patent_id=identifier, prefix=prefix, title=title,filling_date=filling_date)
|
||||
|
||||
|
||||
@patents_router.get(
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
from inse.patents import model
|
||||
from inse.patents.institutions.logic import filter_patents_by_institution
|
||||
from inse.patents.institutions.name_matching import (
|
||||
assignee_matches_institution_name,
|
||||
institution_search_variants,
|
||||
)
|
||||
|
||||
|
||||
def test_institution_search_variants_exclude_single_letter_initials() -> None:
|
||||
variants = institution_search_variants("Harvard University")
|
||||
|
||||
assert "H" not in variants
|
||||
assert "U" not in variants
|
||||
assert any("Harvard" in variant for variant in variants)
|
||||
|
||||
|
||||
def test_assignee_matches_institution_name_accepts_valid_university() -> None:
|
||||
assert assignee_matches_institution_name(
|
||||
"Universitaet Duisburg-Essen",
|
||||
"University of Duisburg-Essen",
|
||||
)
|
||||
assert assignee_matches_institution_name(
|
||||
"President and Fellows of Harvard College",
|
||||
"Harvard University",
|
||||
)
|
||||
|
||||
|
||||
def test_assignee_matches_institution_name_rejects_false_positives() -> None:
|
||||
assert not assignee_matches_institution_name("u-blox AG", "Harvard University")
|
||||
assert not assignee_matches_institution_name(
|
||||
"LG H&H CO., LTD.",
|
||||
"Harvard University",
|
||||
)
|
||||
assert not assignee_matches_institution_name(
|
||||
"K & N Engineering, Inc.",
|
||||
"National Institute for Fusion Science",
|
||||
)
|
||||
assert not assignee_matches_institution_name(
|
||||
"K&K INC.",
|
||||
"National Institute for Fusion Science",
|
||||
)
|
||||
|
||||
|
||||
def test_filter_patents_by_institution_removes_unrelated_assignees() -> None:
|
||||
institution = _institution(
|
||||
display_name="Harvard University",
|
||||
alternatives=["Universidad de Harvard"],
|
||||
)
|
||||
patents = [
|
||||
model.PatentEntry(
|
||||
patent_id="US1",
|
||||
source="USPTO",
|
||||
assignees=["President and Fellows of Harvard College"],
|
||||
),
|
||||
model.PatentEntry(
|
||||
patent_id="US2",
|
||||
source="USPTO",
|
||||
assignees=["u-blox AG"],
|
||||
),
|
||||
model.PatentEntry(
|
||||
patent_id="US3",
|
||||
source="USPTO",
|
||||
assignees=["LG H&H CO., LTD."],
|
||||
),
|
||||
]
|
||||
|
||||
result = filter_patents_by_institution(patents, institution)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].patent_id == "US1"
|
||||
|
||||
|
||||
def _institution(
|
||||
display_name: str,
|
||||
alternatives: list[str] | None = None,
|
||||
):
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
return Institution(
|
||||
id="https://openalex.org/I123",
|
||||
display_name=display_name,
|
||||
display_name_alternatives=alternatives,
|
||||
)
|
||||
@@ -1,4 +1,6 @@
|
||||
from inse.patents import logic, model
|
||||
from inse.patents import model
|
||||
from inse.patents.common.parsing import deduplicate_patents
|
||||
from inse.patents.institutions.logic import filter_patents_by_institution
|
||||
|
||||
|
||||
def _uspto_patent(
|
||||
@@ -34,7 +36,7 @@ def _epo_patent(
|
||||
def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
||||
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
result = deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].patent_id == "US12508845"
|
||||
@@ -43,7 +45,7 @@ def test_deduplicate_patents_removes_exact_duplicates() -> None:
|
||||
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
|
||||
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
|
||||
|
||||
result = logic._deduplicate_patents(patents)
|
||||
result = deduplicate_patents(patents)
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
|
||||
@@ -55,7 +57,7 @@ def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None
|
||||
duplicate = _uspto_patent()
|
||||
duplicate.abstract = "Second abstract"
|
||||
|
||||
result = logic._deduplicate_patents([first, duplicate])
|
||||
result = deduplicate_patents([first, duplicate])
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].abstract == "First abstract"
|
||||
@@ -65,7 +67,7 @@ def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
|
||||
application = _epo_patent(publication_date="20161005", kind="A1")
|
||||
grant = _epo_patent(publication_date="20180411", kind="B1")
|
||||
|
||||
result = logic._deduplicate_patents([application, grant])
|
||||
result = deduplicate_patents([application, grant])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.kind for patent in result] == ["A1", "B1"]
|
||||
@@ -75,7 +77,7 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() ->
|
||||
earlier = _uspto_patent(publication_date="20241230")
|
||||
later = _uspto_patent(publication_date="20251230")
|
||||
|
||||
result = logic._deduplicate_patents([earlier, later])
|
||||
result = deduplicate_patents([earlier, later])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
|
||||
@@ -85,7 +87,58 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types
|
||||
utility = _uspto_patent(application_type="utility")
|
||||
reissue = _uspto_patent(application_type="reissue")
|
||||
|
||||
result = logic._deduplicate_patents([utility, reissue])
|
||||
result = deduplicate_patents([utility, reissue])
|
||||
|
||||
assert len(result) == 2
|
||||
assert [patent.application_type for patent in result] == ["utility", "reissue"]
|
||||
|
||||
|
||||
def test_assignee_matches_institution_name_accepts_alternative_names() -> None:
|
||||
from inse.patents.name_matching import assignee_matches_institution_name
|
||||
|
||||
assert assignee_matches_institution_name(
|
||||
"Universitaet Duisburg-Essen",
|
||||
"University of Duisburg-Essen",
|
||||
)
|
||||
assert not assignee_matches_institution_name(
|
||||
"Harvard University",
|
||||
"University of Duisburg-Essen",
|
||||
)
|
||||
|
||||
|
||||
def test_filter_patents_by_institution_keeps_matching_assignees() -> None:
|
||||
institution = _institution(
|
||||
display_name="University of Duisburg-Essen",
|
||||
alternatives=["Universität Duisburg-Essen"],
|
||||
)
|
||||
matching = model.PatentEntry(
|
||||
patent_id="EP123",
|
||||
source="EPO",
|
||||
assignees=["University of Duisburg-Essen"],
|
||||
)
|
||||
other = model.PatentEntry(
|
||||
patent_id="EP456",
|
||||
source="EPO",
|
||||
assignees=["Harvard University"],
|
||||
)
|
||||
|
||||
result = filter_patents_by_institution(
|
||||
[matching, other],
|
||||
institution,
|
||||
)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0].patent_id == "EP123"
|
||||
|
||||
|
||||
def _institution(
|
||||
display_name: str,
|
||||
alternatives: list[str] | None = None,
|
||||
):
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
return Institution(
|
||||
id="https://openalex.org/I123",
|
||||
display_name=display_name,
|
||||
display_name_alternatives=alternatives,
|
||||
)
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from pydantic import ValidationError
|
||||
from inse.exceptions import (
|
||||
UpstreamAPIException,
|
||||
@@ -45,17 +47,34 @@ async def list_topics(
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
data = await openalex_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
try:
|
||||
data = await openalex_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex topics request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
@@ -260,34 +279,16 @@ K = 500
|
||||
NUM_CANDIDATES = 500
|
||||
|
||||
|
||||
async def vector_search_topics(
|
||||
def _build_vector_search_body(
|
||||
*,
|
||||
query: str,
|
||||
limit: int = 25,
|
||||
query_vector: list[float],
|
||||
search_type: str = "hybrid",
|
||||
) -> TopicsListResponse:
|
||||
limit: int = 25,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Perform a semantic similarity search on the topicvectors index.
|
||||
Construct the Elasticsearch request body for topic vector/hybrid search.
|
||||
"""
|
||||
try:
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.util import get_model
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise ElasticsearchException(
|
||||
f"Failed to load elasticsearch integration: {exc}"
|
||||
) from exc
|
||||
|
||||
# 1. Vectorize query
|
||||
try:
|
||||
model = get_model()
|
||||
query_vector = model.encode(query).tolist()
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
should_clauses = []
|
||||
|
||||
# Lexical multi_match search (only in hybrid mode)
|
||||
@@ -334,7 +335,7 @@ async def vector_search_topics(
|
||||
]
|
||||
)
|
||||
|
||||
body = {
|
||||
return {
|
||||
"query": {"bool": {"should": should_clauses}},
|
||||
"_source": {
|
||||
"excludes": [
|
||||
@@ -349,6 +350,42 @@ async def vector_search_topics(
|
||||
"size": limit,
|
||||
}
|
||||
|
||||
|
||||
async def vector_search_topics(
|
||||
*,
|
||||
query: str,
|
||||
limit: int = 25,
|
||||
search_type: str = "hybrid",
|
||||
) -> TopicsListResponse:
|
||||
"""
|
||||
Perform a semantic similarity search on the topicvectors index.
|
||||
"""
|
||||
try:
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.util import get_model
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise ElasticsearchException(
|
||||
f"Failed to load elasticsearch integration: {exc}"
|
||||
) from exc
|
||||
|
||||
# 1. Vectorize query
|
||||
try:
|
||||
model = get_model()
|
||||
query_vector = model.encode(query).tolist()
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
body = _build_vector_search_body(
|
||||
query=query,
|
||||
query_vector=query_vector,
|
||||
search_type=search_type,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
try:
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
@@ -375,3 +412,97 @@ async def vector_search_topics(
|
||||
raise ElasticsearchException(
|
||||
f"Vector search response could not be parsed: {exc}"
|
||||
) from exc
|
||||
|
||||
|
||||
async def vector_search_topics_batch(
|
||||
*,
|
||||
keywords: list[str],
|
||||
search_type: str = "hybrid",
|
||||
) -> Any:
|
||||
"""
|
||||
Perform concurrent semantic/hybrid search for a list of keywords.
|
||||
"""
|
||||
from inse.topics.model import KeywordsTopicsResponse, KeywordTopicMatch
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
if not keywords:
|
||||
return KeywordsTopicsResponse(results=[])
|
||||
|
||||
try:
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.util import get_model
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise ElasticsearchException(
|
||||
f"Failed to load elasticsearch integration: {exc}"
|
||||
) from exc
|
||||
|
||||
# 1. Vectorize queries on CPU in batch
|
||||
try:
|
||||
model = get_model()
|
||||
vectors = model.encode(keywords)
|
||||
query_vectors = [v.tolist() for v in vectors]
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode batch queries.")
|
||||
raise ElasticsearchException(f"Failed to encode batch queries: {exc}") from exc
|
||||
|
||||
# 2. Construct search bodies and query Elasticsearch concurrently
|
||||
tasks = []
|
||||
for kw, qv in zip(keywords, query_vectors):
|
||||
body = _build_vector_search_body(
|
||||
query=kw,
|
||||
query_vector=qv,
|
||||
search_type=search_type,
|
||||
limit=1,
|
||||
)
|
||||
tasks.append(
|
||||
elasticsearch.search(
|
||||
index="topicvectors", body=body, cluster=ESCluster.NES
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
raw_results_list = await asyncio.gather(*tasks)
|
||||
except Exception as exc:
|
||||
logger.exception("Batch Elasticsearch vector search failed with unexpected error.")
|
||||
raise ElasticsearchException(
|
||||
f"Unexpected batch vector search failure: {exc}"
|
||||
) from exc
|
||||
|
||||
# 3. Align and map raw results to KeywordTopicMatch objects
|
||||
results_by_index = [None] * len(keywords)
|
||||
keywords_with_topics = []
|
||||
topics_to_normalize = []
|
||||
index_mapping = []
|
||||
|
||||
for i, (keyword, raw_res) in enumerate(zip(keywords, raw_results_list)):
|
||||
hits = raw_res.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
topic_dict = hits[0].get("_source", {})
|
||||
keywords_with_topics.append(keyword)
|
||||
topics_to_normalize.append(topic_dict)
|
||||
index_mapping.append(i)
|
||||
else:
|
||||
results_by_index[i] = KeywordTopicMatch(keyword=keyword, topic=None)
|
||||
|
||||
if topics_to_normalize:
|
||||
data = {"results": topics_to_normalize}
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
normalized_topics = normalized_data.get("results", [])
|
||||
|
||||
for keyword, topic_dict, orig_idx in zip(keywords_with_topics, normalized_topics, index_mapping):
|
||||
try:
|
||||
topic = Topic.from_dict(topic_dict)
|
||||
except Exception as e:
|
||||
logger.exception(f"Failed to parse normalized topic dictionary for keyword '{keyword}': {e}")
|
||||
topic = None
|
||||
results_by_index[orig_idx] = KeywordTopicMatch(keyword=keyword, topic=topic)
|
||||
|
||||
# Fallback to fill any unfilled slots
|
||||
for i, res in enumerate(results_by_index):
|
||||
if res is None:
|
||||
results_by_index[i] = KeywordTopicMatch(keyword=keywords[i], topic=None)
|
||||
|
||||
return KeywordsTopicsResponse(results=results_by_index)
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
# Vector search for Keyword list
|
||||
class KeywordsTopicsRequest(BaseModel):
|
||||
keywords: List[str] = Field(..., description="List of keywords/sentences to query by similarity.")
|
||||
|
||||
|
||||
class KeywordTopicMatch(BaseModel):
|
||||
keyword: str
|
||||
topic: Optional[Topic] = Field(None, description="The top matching topic from OpenAlex, or None if no match is found.")
|
||||
|
||||
|
||||
class KeywordsTopicsResponse(BaseModel):
|
||||
results: List[KeywordTopicMatch] = Field(..., description="Top matching topics for each keyword in the requested list.")
|
||||
@@ -1,18 +1,33 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Elasticsearch client for OpenAlex topics."""
|
||||
|
||||
"""
|
||||
HTTP client for OpenAlex topics.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class OpenAlexTopicsClient:
|
||||
def __init__(self, index: str = "topicvectors"):
|
||||
self.index = index
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
|
||||
def list_topics_query(
|
||||
def list_topics_params(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
@@ -25,118 +40,60 @@ class OpenAlexTopicsClient:
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
filters = self._filters(filter)
|
||||
must: list[dict[str, Any]] = []
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
if search:
|
||||
must.append(
|
||||
{
|
||||
"multi_match": {
|
||||
"query": search,
|
||||
"fields": ["display_name^3", "keywords^2", "description"],
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
query: dict[str, Any] = {
|
||||
"bool": {
|
||||
"must": must or [{"match_all": {}}],
|
||||
"filter": filters,
|
||||
}
|
||||
}
|
||||
if sample is not None:
|
||||
query = {"function_score": {"query": query, "random_score": {"seed": sample}}}
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"query": query,
|
||||
"from": max((page or 1) - 1, 0) * per_page,
|
||||
"size": per_page,
|
||||
"track_total_hits": True,
|
||||
"_source": (
|
||||
[field.strip() for field in select.split(",") if field.strip()]
|
||||
if select
|
||||
else {"excludes": ["display_name_vector", "keyword_vectors"]}
|
||||
),
|
||||
}
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
body["sort"] = self._sort(sort)
|
||||
if cursor and cursor != "*":
|
||||
body["search_after"] = cursor.split(",")
|
||||
body.pop("from", None)
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
body["aggs"] = {
|
||||
"group_by": {
|
||||
"terms": {"field": self._keyword_field(group_by), "size": per_page}
|
||||
}
|
||||
}
|
||||
return body
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
async def list_topics(self, **kwargs: Any) -> dict[str, Any]:
|
||||
body = self.list_topics_query(**kwargs)
|
||||
response = await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=body,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_value = hits_block.get("total", 0)
|
||||
total = total_value.get("value", 0) if isinstance(total_value, dict) else total_value
|
||||
per_page = kwargs.get("per_page", 25)
|
||||
page = kwargs.get("page", 1)
|
||||
return params
|
||||
|
||||
result: dict[str, Any] = {
|
||||
"meta": {
|
||||
"count": total,
|
||||
"page": page,
|
||||
"per_page": per_page,
|
||||
"next_cursor": self._next_cursor(hits),
|
||||
},
|
||||
"results": [hit.get("_source", {}) for hit in hits],
|
||||
}
|
||||
buckets = response.get("aggregations", {}).get("group_by", {}).get("buckets")
|
||||
if buckets is not None:
|
||||
result["group_by"] = [
|
||||
{
|
||||
"key": bucket.get("key"),
|
||||
"key_display_name": bucket.get("key_as_string", bucket.get("key")),
|
||||
"count": bucket.get("doc_count"),
|
||||
}
|
||||
for bucket in buckets
|
||||
]
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _filters(value: str | None) -> list[dict[str, Any]]:
|
||||
clauses: list[dict[str, Any]] = []
|
||||
for item in (value or "").split(","):
|
||||
if not item or ":" not in item:
|
||||
continue
|
||||
field, raw_value = item.split(":", 1)
|
||||
field = OpenAlexTopicsClient._keyword_field(field.strip())
|
||||
raw_value = raw_value.strip()
|
||||
if raw_value.startswith((">", "<")):
|
||||
operator = "gt" if raw_value[0] == ">" else "lt"
|
||||
clauses.append({"range": {field.removesuffix(".keyword"): {operator: raw_value[1:]}}})
|
||||
else:
|
||||
clauses.append({"term": {field: raw_value}})
|
||||
return clauses
|
||||
|
||||
@staticmethod
|
||||
def _sort(value: str) -> list[dict[str, Any]]:
|
||||
result = []
|
||||
for item in value.split(","):
|
||||
field, _, direction = item.partition(":")
|
||||
result.append({field.strip(): {"order": direction or "desc", "missing": "_last"}})
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _keyword_field(field: str) -> str:
|
||||
if field in {"id", "display_name", "domain.id", "field.id", "subfield.id"}:
|
||||
return f"{field}.keyword"
|
||||
return field
|
||||
|
||||
@staticmethod
|
||||
def _next_cursor(hits: list[dict[str, Any]]) -> str | None:
|
||||
if not hits or not hits[-1].get("sort"):
|
||||
return None
|
||||
return ",".join(str(value) for value in hits[-1]["sort"])
|
||||
async def list_topics(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/topics",
|
||||
params=self.list_topics_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -12,6 +12,7 @@ from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.topics_list_response import TopicsListResponse
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
from .model import KeywordsTopicsRequest, KeywordsTopicsResponse
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
|
||||
@@ -140,3 +141,22 @@ async def vector_search_topics(
|
||||
search_type=search_type,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/vector-search/batch",
|
||||
operation_id="vectorSearchTopicsBatch",
|
||||
response_model=KeywordsTopicsResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Batch semantic / vector search for multiple keywords.",
|
||||
)
|
||||
async def vector_search_topics_batch(
|
||||
request_body: KeywordsTopicsRequest,
|
||||
search_type: Annotated[
|
||||
str,
|
||||
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
|
||||
] = "hybrid",
|
||||
):
|
||||
return await logic.vector_search_topics_batch(
|
||||
keywords=request_body.keywords,
|
||||
search_type=search_type,
|
||||
)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -9,71 +11,183 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
class StubTopicsClient:
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
self.kwargs = None
|
||||
|
||||
async def list_topics(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_elasticsearch_response_to_model():
|
||||
client = StubTopicsClient(
|
||||
{
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
}
|
||||
async def test_list_topics_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_display_name": "Physical Sciences",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_topics(search="machine learning", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.results[0].var_field.display_name == "Computer Science"
|
||||
assert client.kwargs["search"] == "machine learning"
|
||||
topic = result.results[0]
|
||||
assert topic.display_name == "Machine learning"
|
||||
assert topic.var_field.display_name == "Computer Science"
|
||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||
assert topic.domain.display_name == "Physical Sciences"
|
||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(BadRequestException):
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
client = StubTopicsClient(
|
||||
{
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
}
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": "1"}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(query="machine learning", limit=5, client=client)
|
||||
result = await logic.list_topics(client=client)
|
||||
|
||||
assert result.results[0].hint == "Computer Science · Artificial Intelligence · Physical Sciences"
|
||||
assert result.results[0].entity_type == "topic"
|
||||
assert client.kwargs["sort"] == "works_count:desc"
|
||||
topic = result.results[0]
|
||||
assert topic.id == "123"
|
||||
assert topic.display_name == "456"
|
||||
assert topic.description == "true"
|
||||
assert topic.keywords == ["topic", "123"]
|
||||
assert topic.works_count == 12
|
||||
assert topic.cited_by_count is None
|
||||
assert topic.var_field.id == "3"
|
||||
assert topic.domain.display_name == "6"
|
||||
assert topic.ids.wikipedia == "456"
|
||||
assert topic.created_date.isoformat() == "2023-12-25"
|
||||
assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00"
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(
|
||||
query="machine learning",
|
||||
domain_id="https://openalex.org/domains/4",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
subfield_id="https://openalex.org/subfields/1702",
|
||||
limit=5,
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/T12419"
|
||||
assert option.display_name == "Machine learning"
|
||||
assert option.hint == (
|
||||
"Computer Science · Artificial Intelligence · Physical Sciences"
|
||||
)
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "topic"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.model import ESCluster
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@@ -11,39 +9,67 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_topics_query_builds_elasticsearch_query():
|
||||
body = OpenAlexTopicsClient().list_topics_query(
|
||||
def test_list_topics_params_include_openalex_query_parameters():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(
|
||||
search="machine learning",
|
||||
filter="domain.id:https://openalex.org/domains/4,works_count:>1000",
|
||||
filter="domain.id:4,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
group_by="domain.id",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert body["from"] == 10
|
||||
assert body["size"] == 10
|
||||
assert body["_source"] == ["id", "display_name"]
|
||||
assert body["query"]["bool"]["must"][0]["multi_match"]["query"] == "machine learning"
|
||||
assert {"term": {"domain.id.keyword": "https://openalex.org/domains/4"}} in body["query"]["bool"]["filter"]
|
||||
assert {"range": {"works_count": {"gt": "1000"}}} in body["query"]["bool"]["filter"]
|
||||
assert body["sort"] == [{"works_count": {"order": "desc", "missing": "_last"}}]
|
||||
assert params == {
|
||||
"search": "machine learning",
|
||||
"filter": "domain.id:4,works_count:>1000",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "domain.id",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_topics_params_prefers_cursor_over_page():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_calls_elasticsearch_and_maps_hits():
|
||||
response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [{"_source": {"id": "T1", "display_name": "Machine learning"}}],
|
||||
}
|
||||
}
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as search:
|
||||
search.return_value = response
|
||||
result = await OpenAlexTopicsClient(index="topicvectors").list_topics(search="machine")
|
||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/topics"
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_topics(search="machine learning")
|
||||
|
||||
search.assert_awaited_once()
|
||||
assert search.await_args.kwargs["index"] == "topicvectors"
|
||||
assert search.await_args.kwargs["cluster"] == ESCluster.NES
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Machine learning"
|
||||
|
||||
@@ -1,94 +1,176 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.works import logic
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
# @pytest.fixture
|
||||
# def anyio_backend():
|
||||
# return "asyncio"
|
||||
|
||||
|
||||
def work_hit(identifier: str, title: str) -> dict:
|
||||
return {
|
||||
"_source": {
|
||||
"id": f"https://openalex.org/{identifier}",
|
||||
"doi": f"https://doi.org/10.1234/{identifier.lower()}",
|
||||
"title": title,
|
||||
"display_name": title,
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"publication_year": 2024,
|
||||
"publication_date": "2024-01-01",
|
||||
"cited_by_count": 42,
|
||||
"topics": [
|
||||
{
|
||||
"id": "https://openalex.org/T10102",
|
||||
"display_name": "Machine learning",
|
||||
"score": 0.91,
|
||||
}
|
||||
],
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5023888391",
|
||||
"display_name": "Example Author",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# return httpx.Response(
|
||||
# 200,
|
||||
# json={
|
||||
# "hits": {
|
||||
# "total": {"value": 1},
|
||||
# "hits": [
|
||||
# {
|
||||
# "_source": {
|
||||
# "id": "https://openalex.org/W2741809807",
|
||||
# "doi": "https://doi.org/10.7717/peerj.4375",
|
||||
# "display_name": "Example work",
|
||||
# "type": "article",
|
||||
# "language": "en",
|
||||
# "publication_year": 2023,
|
||||
# "cited_by_count": 42,
|
||||
# "topics": [
|
||||
# {
|
||||
# "id": "https://openalex.org/T10102",
|
||||
# "display_name": "Machine learning",
|
||||
# "score": 0.91,
|
||||
# }
|
||||
# ],
|
||||
# "primary_location": {
|
||||
# "source": {
|
||||
# "id": "https://openalex.org/S123",
|
||||
# "display_name": "Example Source",
|
||||
# "issn": None,
|
||||
# }
|
||||
# },
|
||||
# "authorships": [
|
||||
# {
|
||||
# "author": {
|
||||
# "id": "https://openalex.org/A5023888391",
|
||||
# "display_name": "Example Author",
|
||||
# }
|
||||
# }
|
||||
# ],
|
||||
# }
|
||||
# }
|
||||
# ],
|
||||
# },
|
||||
# },
|
||||
# )
|
||||
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
|
||||
# page = await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
# assert page.total == 1
|
||||
# assert page.elements[0].doi == "https://doi.org/10.7717/peerj.4375"
|
||||
# assert page.elements[0].title == "Example work"
|
||||
# assert page.elements[0].type == "article"
|
||||
# assert page.elements[0].language == "en"
|
||||
# assert page.elements[0].publication_year == 2023
|
||||
# assert page.elements[0].cited_by_count == 42
|
||||
# assert page.elements[0].topics == ["Machine learning"]
|
||||
|
||||
|
||||
class StubWorksSearchClient:
|
||||
def __init__(self, pages: list[list[dict]], total: int):
|
||||
self.pages = pages
|
||||
self.total = total
|
||||
self.calls: list[dict] = []
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_all_author_works_collects_all_pages():
|
||||
# requested_pages = []
|
||||
|
||||
async def search_author_works(self, author_id, page, size, **filters):
|
||||
self.calls.append(
|
||||
{
|
||||
"author_id": author_id,
|
||||
"page": page,
|
||||
"size": size,
|
||||
**filters,
|
||||
}
|
||||
)
|
||||
hits = self.pages[page - 1] if page <= len(self.pages) else []
|
||||
return {"hits": {"total": {"value": self.total}, "hits": hits}}
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# payload = json_from_request(request)
|
||||
# requested_pages.append(payload["from"] // payload["size"] + 1)
|
||||
# page = requested_pages[-1]
|
||||
# hits = [
|
||||
# {
|
||||
# "_source": {
|
||||
# "id": f"https://openalex.org/W{page}",
|
||||
# "doi": f"https://doi.org/10.1234/example-{page}",
|
||||
# "title": f"Example work {page}",
|
||||
# "display_name": f"Example work {page}",
|
||||
# "type": "article",
|
||||
# "language": "en",
|
||||
# "publication_year": 2024,
|
||||
# "publication_date": "2024-01-01",
|
||||
# "cited_by_count": page,
|
||||
# "primary_location": {
|
||||
# "is_oa": True,
|
||||
# "source": {
|
||||
# "id": "https://openalex.org/S123",
|
||||
# "display_name": "Example Source",
|
||||
# },
|
||||
# },
|
||||
# "authorships": [
|
||||
# {
|
||||
# "author": {
|
||||
# "id": "https://openalex.org/A5023888391",
|
||||
# "display_name": "Example Author",
|
||||
# },
|
||||
# },
|
||||
# ],
|
||||
# "topics": [],
|
||||
# }
|
||||
# }
|
||||
# ]
|
||||
# return httpx.Response(
|
||||
# 200,
|
||||
# json={
|
||||
# "hits": {
|
||||
# "total": {"value": 2},
|
||||
# "hits": hits,
|
||||
# },
|
||||
# },
|
||||
# )
|
||||
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
|
||||
# works = await logic.get_all_author_works("A5023888391", client=client)
|
||||
|
||||
# assert requested_pages == [1, 2]
|
||||
# assert works.total == 2
|
||||
# assert [work.title for work in works.elements] == ["Example work 1", "Example work 2"]
|
||||
# assert works.elements[0].id == "https://openalex.org/W1"
|
||||
# assert works.elements[0].display_name == "Example work 1"
|
||||
# assert works.elements[0].publication_date == "2024-01-01"
|
||||
# assert works.elements[0].primary_location.is_oa is True
|
||||
# assert works.elements[0].authorships[0].author.id == "https://openalex.org/A5023888391"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
client = StubWorksSearchClient(
|
||||
pages=[[work_hit("W2741809807", "Example work")]],
|
||||
total=1,
|
||||
)
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_missing_api_key_to_service_unavailable():
|
||||
# client = OpenAlexWorksSearchClient(api_key="")
|
||||
|
||||
page = await logic.get_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
publication_year=[2024],
|
||||
client=client,
|
||||
)
|
||||
# with pytest.raises(HTTPException) as exc:
|
||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
assert page.total == 1
|
||||
assert page.last_page is True
|
||||
assert page.elements[0].title == "Example work"
|
||||
assert page.elements[0].doi == "https://doi.org/10.1234/w2741809807"
|
||||
assert client.calls[0]["publication_year"] == [2024]
|
||||
# assert exc.value.status_code == 503
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_all_author_works_collects_all_elasticsearch_pages():
|
||||
first_page = [work_hit(f"W{number}", f"Example work {number}") for number in range(100)]
|
||||
second_page = [work_hit("W100", "Example work 100")]
|
||||
client = StubWorksSearchClient(pages=[first_page, second_page], total=101)
|
||||
# @pytest.mark.anyio
|
||||
# async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway():
|
||||
# def handler(request: httpx.Request) -> httpx.Response:
|
||||
# return httpx.Response(500, json={"error": "upstream failed"})
|
||||
|
||||
response = await logic.get_all_author_works("A5023888391", client=client)
|
||||
# client = OpenAlexWorksSearchClient(
|
||||
# base_url="https://project.nes.uni-due.de/elastic",
|
||||
# api_key="test-key",
|
||||
# transport=httpx.MockTransport(handler),
|
||||
# )
|
||||
|
||||
assert response.meta.count == 101
|
||||
assert len(response.results) == 101
|
||||
assert response.results[-1].title == "Example work 100"
|
||||
assert [call["page"] for call in client.calls] == [1, 2]
|
||||
# with pytest.raises(HTTPException) as exc:
|
||||
# await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
# assert exc.value.status_code == 502
|
||||
|
||||
|
||||
# def json_from_request(request: httpx.Request) -> dict:
|
||||
# return json.loads(request.content.decode("utf-8"))
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
"ngVersion": "21.2.14",
|
||||
"providedInRoot": true,
|
||||
"serviceSuffix": "Service",
|
||||
"withInterfaces": true,
|
||||
"withInterfaces": false,
|
||||
"enumPropertyNaming": "original",
|
||||
"fileNaming": "kebab-case"
|
||||
"fileNaming": "camelCase"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ api/companyConnections.service.ts
|
||||
api/funding.service.ts
|
||||
api/iNSEService.service.ts
|
||||
api/institutions.service.ts
|
||||
api/keywords.service.ts
|
||||
api/news.service.ts
|
||||
api/organization.service.ts
|
||||
api/patents.service.ts
|
||||
@@ -72,6 +73,9 @@ model/euCordisProjectResponse.ts
|
||||
model/euOrganizationProjectSummary.ts
|
||||
model/euOrganizationProjectSummaryPage.ts
|
||||
model/euProjectData.ts
|
||||
model/extractedKeywords.ts
|
||||
model/extractedKeywordsLLM.ts
|
||||
model/extractedKeywordsResponse.ts
|
||||
model/filterInformation.ts
|
||||
model/filterProperties.ts
|
||||
model/fp7EurosciVoc.ts
|
||||
@@ -121,11 +125,18 @@ model/institutionNetworkNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/ipcClassification.ts
|
||||
model/keywordEntry.ts
|
||||
model/keywordEntryWithTopic.ts
|
||||
model/keywordTopicMatch.ts
|
||||
model/keywords.ts
|
||||
model/keywordsRequest.ts
|
||||
model/keywordsTopicsRequest.ts
|
||||
model/keywordsTopicsResponse.ts
|
||||
model/latitude.ts
|
||||
model/location.ts
|
||||
model/loginResponse.ts
|
||||
model/longitude.ts
|
||||
model/matchedAuthor.ts
|
||||
model/matchedOfficer.ts
|
||||
model/mentionedPerson.ts
|
||||
model/meta.ts
|
||||
@@ -135,9 +146,12 @@ model/newsArticle.ts
|
||||
model/newsArticleDetail.ts
|
||||
model/newsPage.ts
|
||||
model/openAccess.ts
|
||||
model/orgPatentEntry.ts
|
||||
model/orgPatentsResponse.ts
|
||||
model/organizationPage.ts
|
||||
model/patentEntry.ts
|
||||
model/patentsByAuthorResponse.ts
|
||||
model/patentsByInstitutionResponse.ts
|
||||
model/personBio.ts
|
||||
model/projectType.ts
|
||||
model/projectsFilteringProperties.ts
|
||||
|
||||
@@ -8,6 +8,8 @@ export * from './iNSEService.service';
|
||||
import { INSEServiceService } from './iNSEService.service';
|
||||
export * from './institutions.service';
|
||||
import { InstitutionsService } from './institutions.service';
|
||||
export * from './keywords.service';
|
||||
import { KeywordsService } from './keywords.service';
|
||||
export * from './news.service';
|
||||
import { NewsService } from './news.service';
|
||||
export * from './organization.service';
|
||||
@@ -24,4 +26,19 @@ export * from './topics.service';
|
||||
import { TopicsService } from './topics.service';
|
||||
export * from './works.service';
|
||||
import { WorksService } from './works.service';
|
||||
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
|
||||
export const APIS = [
|
||||
AuthService,
|
||||
CompanyConnectionsService,
|
||||
FundingService,
|
||||
INSEServiceService,
|
||||
InstitutionsService,
|
||||
KeywordsService,
|
||||
NewsService,
|
||||
OrganizationService,
|
||||
PatentsService,
|
||||
PersonNetworkService,
|
||||
PersonsService,
|
||||
ProjectsService,
|
||||
TopicsService,
|
||||
WorksService,
|
||||
];
|
||||
|
||||
@@ -1,871 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AccessResponse } from '../model/accessResponse';
|
||||
// @ts-ignore
|
||||
import { AccessToken } from '../model/accessToken';
|
||||
// @ts-ignore
|
||||
import { AccountPage } from '../model/accountPage';
|
||||
// @ts-ignore
|
||||
import { AccountProfile } from '../model/accountProfile';
|
||||
// @ts-ignore
|
||||
import { BodyChangePassword } from '../model/bodyChangePassword';
|
||||
// @ts-ignore
|
||||
import { BodyGetAccessToken } from '../model/bodyGetAccessToken';
|
||||
// @ts-ignore
|
||||
import { BodyLogin } from '../model/bodyLogin';
|
||||
// @ts-ignore
|
||||
import { BodyRequestOtk } from '../model/bodyRequestOtk';
|
||||
// @ts-ignore
|
||||
import { CreateAccountRequest } from '../model/createAccountRequest';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { LoginResponse } from '../model/loginResponse';
|
||||
// @ts-ignore
|
||||
import { OrganizationProfile } from '../model/organizationProfile';
|
||||
// @ts-ignore
|
||||
import { UpdateAccountRequest } from '../model/updateAccountRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change Password
|
||||
* Change the user\'s password and invalidate existing tokens.
|
||||
* @endpoint post /api/auth/v2/change-password
|
||||
* @param bodyChangePassword
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public changePassword(bodyChangePassword: BodyChangePassword, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyChangePassword === null || bodyChangePassword === undefined) {
|
||||
throw new Error('Required parameter bodyChangePassword was null or undefined when calling changePassword.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/change-password`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyChangePassword,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Account
|
||||
* @endpoint post /api/accounts
|
||||
* @param createAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public createAccount(createAccountRequest: CreateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (createAccountRequest === null || createAccountRequest === undefined) {
|
||||
throw new Error('Required parameter createAccountRequest was null or undefined when calling createAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: createAccountRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Account
|
||||
* @endpoint delete /api/accounts/{account_id}
|
||||
* @param accountId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public deleteAccount(accountId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public deleteAccount(accountId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public deleteAccount(accountId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public deleteAccount(accountId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling deleteAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Access Token
|
||||
* Retrieve an access token for the authenticated user.
|
||||
* @endpoint post /api/auth/v2/access
|
||||
* @param bodyGetAccessToken
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessResponse>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessResponse>>;
|
||||
public getAccessToken(bodyGetAccessToken: BodyGetAccessToken, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyGetAccessToken === null || bodyGetAccessToken === undefined) {
|
||||
throw new Error('Required parameter bodyGetAccessToken was null or undefined when calling getAccessToken.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/access`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyGetAccessToken,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Current Account
|
||||
* @endpoint get /api/accounts/me
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getCurrentAccount(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public getCurrentAccount(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public getCurrentAccount(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public getCurrentAccount(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/me`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Health Check
|
||||
* @endpoint get /api/auth/v2/health
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public healthCheckApiAuthV2HealthGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/health`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Organizations
|
||||
* @endpoint get /api/accounts/organizations
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public listAccountOrganizations(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<OrganizationProfile>>;
|
||||
public listAccountOrganizations(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<OrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<OrganizationProfile>>>;
|
||||
public listAccountOrganizations(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/organizations`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<OrganizationProfile>>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Accounts
|
||||
* @endpoint get /api/accounts
|
||||
* @param page
|
||||
* @param pageSize
|
||||
* @param offset
|
||||
* @param search
|
||||
* @param organizationId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountPage>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountPage>>;
|
||||
public listAccounts(page?: number, pageSize?: number, offset?: number, search?: string, organizationId?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>offset, 'offset');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>search, 'search');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>organizationId, 'organization_id');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountPage>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Login with One-Time Key
|
||||
* Login using a one-time key (OTK) sent to the user\'s email.
|
||||
* @endpoint post /api/auth/v2/login
|
||||
* @param bodyLogin
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public login(bodyLogin: BodyLogin, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<LoginResponse>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<LoginResponse>>;
|
||||
public login(bodyLogin: BodyLogin, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<LoginResponse>>;
|
||||
public login(bodyLogin: BodyLogin, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyLogin === null || bodyLogin === undefined) {
|
||||
throw new Error('Required parameter bodyLogin was null or undefined when calling login.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/login`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<LoginResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyLogin,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout
|
||||
* Logout the authenticated user.
|
||||
* @endpoint post /api/auth/v2/logout
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public logout(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public logout(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public logout(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public logout(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/logout`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Access Token
|
||||
* Refresh the access token using a valid refresh token.
|
||||
* @endpoint post /api/auth/v2/refresh
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public refreshAccessToken(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccessToken>;
|
||||
public refreshAccessToken(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccessToken>>;
|
||||
public refreshAccessToken(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccessToken>>;
|
||||
public refreshAccessToken(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/refresh`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccessToken>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request One-Time Key
|
||||
* Request a one-time key (OTK) for authentication using email and password.
|
||||
* @endpoint post /api/auth/v2/request-otk
|
||||
* @param bodyRequestOtk
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
|
||||
public requestOtk(bodyRequestOtk: BodyRequestOtk, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (bodyRequestOtk === null || bodyRequestOtk === undefined) {
|
||||
throw new Error('Required parameter bodyRequestOtk was null or undefined when calling requestOtk.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/auth/v2/request-otk`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<any>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: bodyRequestOtk,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Account
|
||||
* @endpoint put /api/accounts/{account_id}
|
||||
* @param accountId
|
||||
* @param updateAccountRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AccountProfile>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AccountProfile>>;
|
||||
public updateAccount(accountId: string, updateAccountRequest: UpdateAccountRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (accountId === null || accountId === undefined) {
|
||||
throw new Error('Required parameter accountId was null or undefined when calling updateAccount.');
|
||||
}
|
||||
if (updateAccountRequest === null || updateAccountRequest === undefined) {
|
||||
throw new Error('Required parameter updateAccountRequest was null or undefined when calling updateAccount.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/accounts/${this.configuration.encodeParam({name: "accountId", value: accountId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AccountProfile>('put', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: updateAccountRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,205 +9,355 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class INSEServiceService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
* @param pageSize Page size for each search page.
|
||||
* @param saveJson Persist cache JSON to data folder.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public buildTopicCache(
|
||||
pageSize?: number,
|
||||
saveJson?: boolean,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>pageSize,
|
||||
'page_size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>saveJson,
|
||||
'save_json',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the topic hierarchy cache.
|
||||
* @endpoint get /api/inse-service/topics/cache
|
||||
* @param pageSize Page size for each search page.
|
||||
* @param saveJson Persist cache JSON to data folder.
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>saveJson, 'save_json');
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
let localVarPath = `/api/inse-service/topics/cache`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Counts topic hierarchy occurrences from cache.
|
||||
* @endpoint get /api/inse-service/topics/count
|
||||
* @param topic Topic names (repeat parameter).
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public countTopicHierarchy(
|
||||
topic: Array<string>,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter topic was null or undefined when calling countTopicHierarchy.',
|
||||
);
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/cache`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'topic',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts topic hierarchy occurrences from cache.
|
||||
* @endpoint get /api/inse-service/topics/count
|
||||
* @param topic Topic names (repeat parameter).
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public countTopicHierarchy(topic: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public countTopicHierarchy(topic: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (topic === null || topic === undefined) {
|
||||
throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.');
|
||||
}
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topic');
|
||||
})
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/count`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
|
||||
* @endpoint get /api/inse-service/topics/hierarchy
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
|
||||
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
|
||||
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
|
||||
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/hierarchy`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/count`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> Topics).
|
||||
* @endpoint get /api/inse-service/topics/hierarchy
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getTopicHierarchy(
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<object>;
|
||||
public getTopicHierarchy(
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<object>>;
|
||||
public getTopicHierarchy(
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<object>>;
|
||||
public getTopicHierarchy(
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/topics/hierarchy`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<object>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { KeywordsRequest } from '../model/keywordsRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class KeywordsService extends BaseService {
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts keywords from text.
|
||||
* @endpoint post /api/inse-service/keywords/extract
|
||||
* @param keywordsRequest
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ExtractedKeywordsResponse>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ExtractedKeywordsResponse>>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ExtractedKeywordsResponse>>;
|
||||
public extractKeywords(keywordsRequest: KeywordsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (keywordsRequest === null || keywordsRequest === undefined) {
|
||||
throw new Error('Required parameter keywordsRequest was null or undefined when calling extractKeywords.');
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
// to determine the Content-Type header
|
||||
const consumes: string[] = [
|
||||
'application/json'
|
||||
];
|
||||
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
|
||||
if (httpContentTypeSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
|
||||
}
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/keywords/extract`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<ExtractedKeywordsResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: keywordsRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,227 +9,684 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AllPatentsResponse } from '../model/allPatentsResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { OrgPatentsResponse } from '../model/orgPatentsResponse';
|
||||
// @ts-ignore
|
||||
import { PatentEntry } from '../model/patentEntry';
|
||||
// @ts-ignore
|
||||
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
|
||||
// @ts-ignore
|
||||
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class PatentsService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
/**
|
||||
* Get all patents with pagination and search.
|
||||
* @endpoint get /api/inse-service/patents
|
||||
* @param page
|
||||
* @param size
|
||||
* @param search
|
||||
* @param source
|
||||
* @param sortBy
|
||||
* @param sortDirection
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<AllPatentsResponse>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<AllPatentsResponse>>;
|
||||
public getAllPatents(
|
||||
page?: number,
|
||||
size?: number,
|
||||
search?: string,
|
||||
source?: string,
|
||||
sortBy?: string,
|
||||
sortDirection?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>size,
|
||||
'size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>search,
|
||||
'search',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>source,
|
||||
'source',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortBy,
|
||||
'sort_by',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>sortDirection,
|
||||
'sort_direction',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all patents with pagination and search.
|
||||
* @endpoint get /api/inse-service/patents
|
||||
* @param page
|
||||
* @param size
|
||||
* @param search
|
||||
* @param source
|
||||
* @param sortBy
|
||||
* @param sortDirection
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AllPatentsResponse>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AllPatentsResponse>>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AllPatentsResponse>>;
|
||||
public getAllPatents(page?: number, size?: number, search?: string, source?: string, sortBy?: string, sortDirection?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>size, 'size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>search, 'search');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>source, 'source');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortBy, 'sort_by');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>sortDirection, 'sort_direction');
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AllPatentsResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one publication by OpenAlex ID or DOI.
|
||||
* @endpoint get /api/inse-service/patents/{identifier}
|
||||
* @param identifier
|
||||
* @param prefix Application Prefix (EP or US)
|
||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentEntry>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(identifier: string, prefix?: string, title?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error('Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.');
|
||||
}
|
||||
let localVarPath = `/api/inse-service/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<AllPatentsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>prefix, 'prefix');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>title, 'title');
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({name: "identifier", value: identifier, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentEntry>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
/**
|
||||
* Get pre-indexed org patents for an institution.
|
||||
* @endpoint get /api/inse-service/institutions/{id}/org-patents
|
||||
* @param id
|
||||
* @param matchType Filter patents by match type.
|
||||
* @param page
|
||||
* @param size
|
||||
* @param source
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getOrgPatentsByInstitution(
|
||||
id: string,
|
||||
matchType?: 'institution' | 'name' | 'both' | 'all',
|
||||
page?: number,
|
||||
size?: number,
|
||||
source?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<OrgPatentsResponse>;
|
||||
public getOrgPatentsByInstitution(
|
||||
id: string,
|
||||
matchType?: 'institution' | 'name' | 'both' | 'all',
|
||||
page?: number,
|
||||
size?: number,
|
||||
source?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<OrgPatentsResponse>>;
|
||||
public getOrgPatentsByInstitution(
|
||||
id: string,
|
||||
matchType?: 'institution' | 'name' | 'both' | 'all',
|
||||
page?: number,
|
||||
size?: number,
|
||||
source?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<OrgPatentsResponse>>;
|
||||
public getOrgPatentsByInstitution(
|
||||
id: string,
|
||||
matchType?: 'institution' | 'name' | 'both' | 'all',
|
||||
page?: number,
|
||||
size?: number,
|
||||
source?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling getOrgPatentsByInstitution.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
|
||||
}
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>matchType,
|
||||
'match_type',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>page,
|
||||
'page',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>size,
|
||||
'size',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>source,
|
||||
'source',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/org-patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<OrgPatentsResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one publication by OpenAlex ID or DOI.
|
||||
* @endpoint get /api/inse-service/patents/{identifier}
|
||||
* @param identifier
|
||||
* @param prefix Application Prefix (EP or US)
|
||||
* @param title Do we want to fallback to title search if ID and DOI dont work?
|
||||
* @param fillingDate Filling date in YYYY-MM-DD format
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentEntry>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentEntry>>;
|
||||
public getPatentByIdOrTitle(
|
||||
identifier: string,
|
||||
prefix?: string,
|
||||
title?: string,
|
||||
fillingDate?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (identifier === null || identifier === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>prefix,
|
||||
'prefix',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>title,
|
||||
'title',
|
||||
);
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>fillingDate,
|
||||
'filling_date',
|
||||
);
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentEntry>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an author by name.
|
||||
* @endpoint get /api/inse-service/authors/{author_id}/patents
|
||||
* @param authorId
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentsByAuthorResponse>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentsByAuthorResponse>>;
|
||||
public getPatentsByAuthor(
|
||||
authorId: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (authorId === null || authorId === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByAuthorResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get patents matched to an institution by assignee name.
|
||||
* @endpoint get /api/inse-service/institutions/{id}/patents
|
||||
* @param id
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<PatentsByInstitutionResponse>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<PatentsByInstitutionResponse>>;
|
||||
public getPatentsByInstitution(
|
||||
id: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (id === null || id === undefined) {
|
||||
throw new Error(
|
||||
'Required parameter id was null or undefined when calling getPatentsByInstitution.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
|
||||
let responseType_: 'text' | 'json' | 'blob' = 'json';
|
||||
if (localVarHttpHeaderAcceptSelected) {
|
||||
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
|
||||
responseType_ = 'text';
|
||||
} else if (
|
||||
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
|
||||
) {
|
||||
responseType_ = 'json';
|
||||
} else {
|
||||
responseType_ = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<PatentsByInstitutionResponse>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+197
-171
@@ -1,193 +1,219 @@
|
||||
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||
import {
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpParameterCodec,
|
||||
} from '@angular/common/http';
|
||||
import { Param } from './param';
|
||||
|
||||
export interface ConfigurationParameters {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Override the default method for encoding path parameters in various
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: {[ key: string ]: string | (() => string | undefined)};
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Override the default method for encoding path parameters in various
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: { [key: string]: string | (() => string | undefined) };
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: {[ key: string ]: string | (() => string | undefined)};
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: { [key: string]: string | (() => string | undefined) };
|
||||
|
||||
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
if (basePath !== undefined) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
if (withCredentials !== undefined) {
|
||||
this.withCredentials = withCredentials;
|
||||
}
|
||||
if (encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param));
|
||||
this.credentials = credentials ?? {};
|
||||
constructor({
|
||||
accessToken,
|
||||
apiKeys,
|
||||
basePath,
|
||||
credentials,
|
||||
encodeParam,
|
||||
encoder,
|
||||
password,
|
||||
username,
|
||||
withCredentials,
|
||||
}: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
if (basePath !== undefined) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
if (withCredentials !== undefined) {
|
||||
this.withCredentials = withCredentials;
|
||||
}
|
||||
if (encoder) {
|
||||
this.encoder = encoder;
|
||||
}
|
||||
this.encodeParam =
|
||||
encodeParam ?? ((param) => this.defaultEncodeParam(param));
|
||||
this.credentials = credentials ?? {};
|
||||
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
};
|
||||
}
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param contentTypes - the array of content types that are available for selection
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderContentType(contentTypes: string[]): string | undefined {
|
||||
if (contentTypes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param contentTypes - the array of content types that are available for selection
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderContentType (contentTypes: string[]): string | undefined {
|
||||
if (contentTypes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param accepts - the array of content types that are available for selection.
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderAccept(accepts: string[]): string | undefined {
|
||||
if (accepts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
|
||||
* If no content type is found return the first found type if the contentTypes is not empty
|
||||
* @param accepts - the array of content types that are available for selection.
|
||||
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
|
||||
*/
|
||||
public selectHeaderAccept(accepts: string[]): string | undefined {
|
||||
if (accepts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return accepts[0];
|
||||
}
|
||||
return type;
|
||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return accepts[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
|
||||
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
|
||||
}
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp(
|
||||
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
|
||||
'i',
|
||||
);
|
||||
return (
|
||||
mime !== null &&
|
||||
(jsonMime.test(mime) ||
|
||||
mime.toLowerCase() === 'application/json-patch+json')
|
||||
);
|
||||
}
|
||||
|
||||
public lookupCredential(key: string): string | undefined {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function'
|
||||
? value()
|
||||
: value;
|
||||
}
|
||||
public lookupCredential(key: string): string | undefined {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function' ? value() : value;
|
||||
}
|
||||
|
||||
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value
|
||||
? headers.set(headerName, (prefix ?? '') + value)
|
||||
: headers;
|
||||
}
|
||||
public addCredentialToHeaders(
|
||||
credentialKey: string,
|
||||
headerName: string,
|
||||
headers: HttpHeaders,
|
||||
prefix?: string,
|
||||
): HttpHeaders {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
|
||||
}
|
||||
|
||||
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value
|
||||
? query.set(paramName, value)
|
||||
: query;
|
||||
}
|
||||
public addCredentialToQuery(
|
||||
credentialKey: string,
|
||||
paramName: string,
|
||||
query: HttpParams,
|
||||
): HttpParams {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? query.set(paramName, value) : query;
|
||||
}
|
||||
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// All other styles and Date-formats are probably handled incorrectly.
|
||||
//
|
||||
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// All other styles and Date-formats are probably handled incorrectly.
|
||||
//
|
||||
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
|
||||
|
||||
const value = param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
const value =
|
||||
param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { RefreshToken } from './refreshToken';
|
||||
import { AccessToken } from './accessToken';
|
||||
|
||||
|
||||
export interface AccessResponse {
|
||||
/**
|
||||
* The access token issued upon successful authentication.
|
||||
*/
|
||||
access_token: AccessToken;
|
||||
/**
|
||||
* The refresh token issued alongside the access token for obtaining new access tokens.
|
||||
*/
|
||||
refresh_token: RefreshToken;
|
||||
}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { TokenType } from './tokenType';
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface AccessToken {
|
||||
/**
|
||||
* The type of the token, which is always ACCESS_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* A hash of the user\'s fingerprint to ensure the token is used by the same user.
|
||||
*/
|
||||
user_fingerprint_hash: string;
|
||||
/**
|
||||
* The raw token string.
|
||||
*/
|
||||
raw_token: string;
|
||||
/**
|
||||
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
|
||||
*/
|
||||
effective_account_id: string;
|
||||
/**
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
effective_organization_id: string;
|
||||
}
|
||||
export namespace AccessToken {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { AccountProfile } from './accountProfile';
|
||||
|
||||
|
||||
export interface AccountPage {
|
||||
items: Array<AccountProfile>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
is_current?: boolean;
|
||||
is_real_account?: boolean;
|
||||
is_impersonating?: boolean;
|
||||
}
|
||||
export namespace AccountProfile {
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface AccountProfile {
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
activated: boolean;
|
||||
is_current?: boolean;
|
||||
is_real_account?: boolean;
|
||||
is_impersonating?: boolean;
|
||||
@@ -25,4 +26,3 @@ export interface AccountProfile {
|
||||
export namespace AccountProfile {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyGetAccessToken {
|
||||
/**
|
||||
* User\'s account ID
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* Effective account ID for the access token
|
||||
*/
|
||||
effective_account_id: string;
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyLogin {
|
||||
/**
|
||||
* User\'s account ID
|
||||
*/
|
||||
account_id: string;
|
||||
/**
|
||||
* One-time code sent to user\'s email
|
||||
*/
|
||||
email_code: string;
|
||||
}
|
||||
|
||||
@@ -1,22 +1,20 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
export interface BodyRequestOtk {
|
||||
/**
|
||||
* User\'s email address
|
||||
*/
|
||||
email: string;
|
||||
/**
|
||||
* User\'s password
|
||||
*/
|
||||
password: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
|
||||
export interface CreateAccountRequest {
|
||||
email: string;
|
||||
name: string;
|
||||
role?: UserRole;
|
||||
organization_id: string;
|
||||
password: string;
|
||||
openalex_person_id?: string | null;
|
||||
}
|
||||
export namespace CreateAccountRequest {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
export interface CreateOrganizationRequest {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user