File size: 1,072 Bytes
4f794f2
 
 
 
 
1a6d216
b7dc427
df02cd1
b7dc427
1a6d216
df02cd1
1a6d216
b7dc427
1a6d216
df02cd1
1a6d216
9e9178e
4f794f2
1a6d216
9e9178e
 
e0cb517
403610d
 
4f794f2
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import asyncio
import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.status import HTTP_504_GATEWAY_TIMEOUT
from neural_searcher import NeuralSearcher
from huggingface_hub import login
from config import HUGGING_FACE_API_KEY,COLLECTION_NAME
import os

login(HUGGING_FACE_API_KEY)

app = FastAPI()

neural_searcher = NeuralSearcher(collection_name=COLLECTION_NAME)

REQUEST_TIMEOUT_ERROR = 30

@app.get("/api/search")
async def search(q: str):
    data =  await neural_searcher.search(text=q)
    return data
    

@app.middleware("http")
async def timeout_middleware(request: Request, call_next):
    try:
        start_time = time.time()
        return await asyncio.wait_for(call_next(request), timeout=REQUEST_TIMEOUT_ERROR)

    except asyncio.TimeoutError:
        process_time = time.time() - start_time
        return JSONResponse({'detail': 'Request processing time excedeed limit',
                             'processing_time': process_time},
                            status_code=HTTP_504_GATEWAY_TIMEOUT)