Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import faiss
|
| 2 |
+
import numpy as np
|
| 3 |
+
from FlagEmbedding import FlagModel
|
| 4 |
+
from flask import Flask, request, jsonify
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
from functools import lru_cache
|
| 10 |
+
|
| 11 |
+
# Initialize components
|
| 12 |
+
app = Flask(__name__)
|
| 13 |
+
model = None
|
| 14 |
+
index = None
|
| 15 |
+
corpus = None
|
| 16 |
+
|
| 17 |
+
def initialize_components():
|
| 18 |
+
global model, index, corpus
|
| 19 |
+
|
| 20 |
+
# Load model with safety checks
|
| 21 |
+
if model is None:
|
| 22 |
+
model = FlagModel(
|
| 23 |
+
"BAAI/bge-large-en-v1.5",
|
| 24 |
+
query_instruction_for_retrieval="Represent this sentence for searching relevant passages:",
|
| 25 |
+
use_fp16=True
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Load corpus from Hugging Face dataset
|
| 29 |
+
if corpus is None:
|
| 30 |
+
dataset = load_dataset("awinml/medrag_corpus_sampled", split='train')
|
| 31 |
+
corpus = [f"{row['id']}\t{row['contents']}" for row in dataset]
|
| 32 |
+
|
| 33 |
+
# Create FAISS index in memory
|
| 34 |
+
if index is None:
|
| 35 |
+
embeddings = model.encode([doc.split('\t', 1)[1] for doc in corpus])
|
| 36 |
+
dimension = embeddings.shape[1]
|
| 37 |
+
index = faiss.IndexFlatIP(dimension)
|
| 38 |
+
index.add(embeddings.astype('float32'))
|
| 39 |
+
|
| 40 |
+
@app.route("/retrieve", methods=["POST"])
|
| 41 |
+
def retrieve():
|
| 42 |
+
start_time = time.time()
|
| 43 |
+
|
| 44 |
+
# Validate request
|
| 45 |
+
data = request.json
|
| 46 |
+
if not data or "queries" not in data:
|
| 47 |
+
return jsonify({"error": "Missing 'queries' parameter"}), 400
|
| 48 |
+
|
| 49 |
+
# Initialize components if needed
|
| 50 |
+
initialize_components()
|
| 51 |
+
|
| 52 |
+
# Process queries
|
| 53 |
+
queries = data["queries"]
|
| 54 |
+
topk = data.get("topk", 3)
|
| 55 |
+
return_scores = data.get("return_scores", False)
|
| 56 |
+
|
| 57 |
+
# Batch processing
|
| 58 |
+
query_embeddings = model.encode_queries(queries)
|
| 59 |
+
scores, indices = index.search(query_embeddings.astype('float32'), topk)
|
| 60 |
+
|
| 61 |
+
# Format results
|
| 62 |
+
results = []
|
| 63 |
+
for i, query in enumerate(queries):
|
| 64 |
+
query_results = []
|
| 65 |
+
for j in range(topk):
|
| 66 |
+
doc_idx = indices[i][j]
|
| 67 |
+
doc = corpus[doc_idx]
|
| 68 |
+
doc_id, content = doc.split('\t', 1)
|
| 69 |
+
result = {
|
| 70 |
+
"document": {
|
| 71 |
+
"id": doc_id,
|
| 72 |
+
"contents": content
|
| 73 |
+
},
|
| 74 |
+
"score": float(scores[i][j])
|
| 75 |
+
}
|
| 76 |
+
query_results.append(result)
|
| 77 |
+
results.append(query_results)
|
| 78 |
+
|
| 79 |
+
return jsonify({
|
| 80 |
+
"result": results,
|
| 81 |
+
"time": f"{time.time() - start_time:.2f}s"
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
# Gradio UI for testing
|
| 85 |
+
def gradio_interface(query, topk):
|
| 86 |
+
response = requests.post(
|
| 87 |
+
"http://localhost:7860/retrieve",
|
| 88 |
+
json={"queries": [query], "topk": topk}
|
| 89 |
+
)
|
| 90 |
+
return response.json()["result"][0]
|
| 91 |
+
|
| 92 |
+
# Start server
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
# First-time initialization
|
| 95 |
+
initialize_components()
|
| 96 |
+
|
| 97 |
+
# Create Gradio interface
|
| 98 |
+
iface = gr.Interface(
|
| 99 |
+
fn=gradio_interface,
|
| 100 |
+
inputs=[
|
| 101 |
+
gr.Textbox(label="Medical Query", placeholder="Enter your medical question..."),
|
| 102 |
+
gr.Slider(1, 10, value=3, label="Top Results")
|
| 103 |
+
],
|
| 104 |
+
outputs=gr.JSON(label="Retrieval Results"),
|
| 105 |
+
title="Medical Retrieval System",
|
| 106 |
+
description="Search across medical literature using AI-powered semantic search"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Run both Flask and Gradio
|
| 110 |
+
iface.launch(server_name="0.0.0.0", server_port=7860, share=True)
|