File size: 928 Bytes
e26d32e 5914320 3ab82e8 3eec3b2 00a8910 3ab82e8 3eec3b2 3f61915 5914320 3ab82e8 ac9faef 2b6d798 3ab82e8 5914320 ac9faef 2b6d798 5914320 |
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 |
from fastapi import FastAPI, Request, Query
from fastapi.templating import Jinja2Templates
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
app = FastAPI()
model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
index = faiss.IndexFlatL2(384) # 384 is the dimensionality of the MiniLM model
templates = Jinja2Templates(directory=".")
@app.get("/")
def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/embed")
def embed_string(text: str):
embedding = model.encode([text])
index.add(np.array(embedding))
return {"message": "String embedded and added to FAISS database"}
@app.get("/search")
def search_string(text: str, n: int = 5):
embedding = model.encode([text])
distances, indices = index.search(np.array(embedding), n)
return {"distances": distances[0].tolist(), "indices": indices[0].tolist()}
|