erfyhersr commited on
Commit
3b7a550
·
verified ·
1 Parent(s): 36334b8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -0
app.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+ from sentence_transformers import SentenceTransformer
4
+ import numpy as np
5
+ import json
6
+
7
+ # Load your JSON data
8
+ with open("data.json") as f:
9
+ data = json.load(f)
10
+
11
+ # Initialize model
12
+ model = SentenceTransformer('all-MiniLM-L6-v2')
13
+
14
+ # Precompute embeddings for all file names
15
+ file_names = [item["file_name"] for item in data]
16
+ file_embeddings = model.encode(file_names)
17
+
18
+ app = FastAPI()
19
+
20
+ class Query(BaseModel):
21
+ text: str
22
+
23
+ @app.post("/search")
24
+ async def search(query: Query):
25
+ # Encode query
26
+ query_embedding = model.encode([query.text])
27
+
28
+ # Compute cosine similarity
29
+ similarities = np.dot(file_embeddings, query_embedding.T).flatten()
30
+
31
+ # Find best match
32
+ best_match_idx = np.argmax(similarities)
33
+
34
+ return {
35
+ "best_match": data[best_match_idx]["file_name"],
36
+ "similarity_score": float(similarities[best_match_idx])
37
+ }