|
| 1 | +from typing import Annotated |
| 2 | +import time |
| 3 | +import os |
| 4 | +import traceback |
| 5 | + |
| 6 | +# Import necessary types and classes from FastAPI and other libraries. |
| 7 | +from fastapi import FastAPI, Header, HTTPException, Query, Request |
| 8 | +from fastapi.middleware.cors import CORSMiddleware |
| 9 | + |
| 10 | +from src.WikidataTextifier import WikidataEntity |
| 11 | + |
| 12 | +# Start Fastapi app |
| 13 | +app = FastAPI( |
| 14 | + title="Wikidata Textifier", |
| 15 | + description="Transforms Wikidata entities into text representations.", |
| 16 | + version="1.0.0", |
| 17 | + docs_url="/docs", # Change the Swagger UI path if needed |
| 18 | + redoc_url="/redoc", # Change the ReDoc path if needed |
| 19 | + swagger_ui_parameters={"persistAuthorization": True}, |
| 20 | +) |
| 21 | + |
| 22 | +# Enable all Cors |
| 23 | +app.add_middleware( |
| 24 | + CORSMiddleware, |
| 25 | + allow_origins=["*"], |
| 26 | + allow_credentials=False, |
| 27 | + allow_methods=["GET"], |
| 28 | + allow_headers=["*"], |
| 29 | +) |
| 30 | + |
| 31 | +@app.get( |
| 32 | + "/", |
| 33 | + responses={ |
| 34 | + 200: { |
| 35 | + "description": "Returns a list of relevant Wikidata property PIDs with similarity scores", |
| 36 | + "content": { |
| 37 | + "application/json": { |
| 38 | + "example": [{ |
| 39 | + "Q42": "Douglas Adams (human), English writer, humorist, and dramatist...", |
| 40 | + }] |
| 41 | + } |
| 42 | + }, |
| 43 | + }, |
| 44 | + 422: { |
| 45 | + "description": "Missing or invalid query parameter", |
| 46 | + "content": { |
| 47 | + "application/json": { |
| 48 | + "example": {"detail": "ID is missing"} |
| 49 | + } |
| 50 | + }, |
| 51 | + }, |
| 52 | + }, |
| 53 | +) |
| 54 | +async def property_query_route( |
| 55 | + request: Request, |
| 56 | + id: str = Query(..., example="Q42"), |
| 57 | + lang: str = 'en', |
| 58 | + json: bool = True, |
| 59 | +): |
| 60 | + """ |
| 61 | + Retrieve a Wikidata item with all labels or textual representations for an LLM. |
| 62 | +
|
| 63 | + Args: |
| 64 | + id (str): The Wikidata item ID (e.g., "Q42"). |
| 65 | + json (bool): If True, returns the item in JSON format. Defaults to True. |
| 66 | +
|
| 67 | + Returns: |
| 68 | + list: A list of dictionaries containing QIDs and the similarity scores. |
| 69 | + """ |
| 70 | + if not id: |
| 71 | + response = "ID is missing" |
| 72 | + raise HTTPException(status_code=422, detail=response) |
| 73 | + |
| 74 | + try: |
| 75 | + entity = WikidataEntity.from_id(id, lang=lang) |
| 76 | + |
| 77 | + if json: |
| 78 | + results = entity.to_json() |
| 79 | + else: |
| 80 | + results = str(entity) |
| 81 | + |
| 82 | + return results |
| 83 | + except Exception as e: |
| 84 | + traceback.print_exc() |
| 85 | + raise HTTPException(status_code=500, detail="Internal Server Error") |
0 commit comments