File size: 2,406 Bytes
d17ca98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
import xml.etree.ElementTree as ET
from elasticsearch import Elasticsearch, helpers
import torch
import numpy as np


from fastapi import APIRouter, Depends, HTTPException, Body, UploadFile, File
from server.utils.database import get_db
from fastapi.encoders import jsonable_encoder
import json
from server.utils.insert_data import insert_data_from_xml
from server.utils.search_data import search_data_from_database

router = APIRouter(prefix="/patent_data")


@router.post("/insert")
async def insert_data_from_xml(

    xml_file: UploadFile = File(...),

    db: Elasticsearch = Depends(get_db),

    index_name: str = "patents"

):
    try:
        # Read the uploaded file as bytes and decode to string
        xml_content = await xml_file.read()
        import tempfile
        with tempfile.NamedTemporaryFile(delete=False, suffix='.xml') as tmp:
            tmp.write(xml_content)
            tmp_path = tmp.name
        result = insert_data_from_xml(tmp_path, db=db, index_name=index_name)
        return {"message": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/search_text/{query}")
async def search_text(

    query: str,

    top_k: int = 5,

    db: Elasticsearch = Depends(get_db),

    index_name: str = "patents"

):
    try:
        results = search_data_from_database(
            query=query,
            top_k=top_k,
            db=db,
            index_name=index_name
        )
        return {"results": results}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    


@router.post("/search_image")
async def search_image(

    image: UploadFile = File(...),

    top_k: int = 5,

    db: Elasticsearch = Depends(get_db),

    index_name: str = "patents"

):
    try:
        # Save the uploaded image to a temp file
        import tempfile
        image_bytes = await image.read()
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp:
            tmp.write(image_bytes)
            tmp_path = tmp.name
        results = search_data_from_database(
            image_path=tmp_path,
            top_k=top_k,
            db=db,
            index_name=index_name
        )
        return {"results": results}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))