Spaces:
Sleeping
Sleeping
File size: 2,377 Bytes
5dfb339 88cc76c 5dfb339 88cc76c 5dfb339 80ad49a 5dfb339 80ad49a 5dfb339 88cc76c 5dfb339 80ad49a 68b63d6 88cc76c 5dfb339 68b63d6 |
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import asyncio
import io
from fastapi import APIRouter, Depends, UploadFile, File
from pydantic import BaseModel
from typing import List, Optional
from app.api.dto.kg_query import KGQueryRequest, QueryContext
from app.services.predict import PredictService, get_predict_service
router = APIRouter()
class QueryRequest(BaseModel):
question: str
context: Optional[List[str]] = None
class QueryResponse(BaseModel):
answer: str
sources: List[str]
@router.post("/analyze")
async def analyze(
image: UploadFile = File(None),
predict_service: PredictService = Depends(get_predict_service)
):
# Đọc content một lần và tạo 2 copy riêng biệt
image_content = await image.read()
# Tạo 2 UploadFile objects riêng biệt từ cùng content
image_copy1 = UploadFile(
file=io.BytesIO(image_content),
filename=image.filename,
headers=image.headers
)
image_copy2 = UploadFile(
file=io.BytesIO(image_content),
filename=image.filename,
headers=image.headers
)
predicted_label_task = asyncio.create_task(predict_service.predict_image(image_copy1))
caption_task = asyncio.create_task(predict_service.get_caption(image_copy2))
predicted_label, caption = await asyncio.gather(predicted_label_task, caption_task)
filtered_labels = [label for label in predicted_label if label.confidence > 0.05]
if not filtered_labels and predicted_label:
filtered_labels = [max(predicted_label, key=lambda x: x.confidence)]
return {
"crop_id": filtered_labels[0].crop_id if filtered_labels else None,
"predicted_labels": filtered_labels,
"caption": caption,
# "nodes": nodes,
# "final_labels": filtered_labels
}
@router.post("/kg-query")
async def query_kg(
request: KGQueryRequest,
predict_service: PredictService = Depends(get_predict_service),
):
return await predict_service.retrieve_kg(request)
@router.post("/kg-query-text")
async def query_kg_text(
request: KGQueryRequest,
predict_service: PredictService = Depends(get_predict_service),
):
return await predict_service.retrieve_kg_text(request)
# @router.post("/get-all-nodes")
# async def get_all_nodes(
# predict_service: PredictService = Depends(get_predict_service),
# ):
# return await predict_service.get_all_nodes()
|