imurra commited on
Commit
3a8e6a8
·
verified ·
1 Parent(s): bee6efe

runtime error Better Gradio interface with proper error handling Cleaner layout Examples for testing Proper FastAPI + Gradio mounting

Browse files
Files changed (1) hide show
  1. app.py +104 -3
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - Hugging Face Spaces version with auto-extract
2
  import os
3
  import zipfile
4
  from fastapi import FastAPI, HTTPException
@@ -28,7 +28,79 @@ print(f"Loading MedCPT model...")
28
  model = SentenceTransformer('ncbi/MedCPT-Query-Encoder')
29
  print("Initialization complete!")
30
 
31
- # FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  app = FastAPI(title="MedQA Search API")
33
 
34
  app.add_middleware(
@@ -44,4 +116,33 @@ class SearchRequest(BaseModel):
44
  num_results: int = 3
45
 
46
  class SearchResponse(BaseModel):
47
- results: list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - Hugging Face Spaces version - FIXED
2
  import os
3
  import zipfile
4
  from fastapi import FastAPI, HTTPException
 
28
  model = SentenceTransformer('ncbi/MedCPT-Query-Encoder')
29
  print("Initialization complete!")
30
 
31
+ # Gradio interface function
32
+ def search_interface(query: str, num_results: int = 3):
33
+ """Simple web interface for testing"""
34
+ if not query.strip():
35
+ return "Please enter a search query."
36
+
37
+ try:
38
+ embedding = model.encode(query).tolist()
39
+ results = collection.query(
40
+ query_embeddings=[embedding],
41
+ n_results=int(num_results)
42
+ )
43
+
44
+ if not results['documents'][0]:
45
+ return "No results found."
46
+
47
+ output = ""
48
+ for i in range(len(results['documents'][0])):
49
+ output += f"\n{'='*60}\n"
50
+ output += f"Example {i+1}\n"
51
+ output += f"{'='*60}\n"
52
+ output += results['documents'][0][i] + "\n"
53
+ output += f"\nAnswer: {results['metadatas'][0][i].get('answer', 'N/A')}\n"
54
+ output += f"Similarity: {1 - results['distances'][0][i]:.3f}\n"
55
+
56
+ return output
57
+ except Exception as e:
58
+ return f"Error: {str(e)}"
59
+
60
+ # Create Gradio interface
61
+ with gr.Blocks(title="MedQA Search") as demo:
62
+ gr.Markdown("# MedQA Search - USMLE Question Database")
63
+ gr.Markdown("Search for similar USMLE Step 1 questions using semantic similarity")
64
+
65
+ with gr.Row():
66
+ with gr.Column():
67
+ query_input = gr.Textbox(
68
+ label="Medical Topic or Clinical Scenario",
69
+ placeholder="e.g., hyponatremia",
70
+ lines=2
71
+ )
72
+ num_results_slider = gr.Slider(
73
+ minimum=1,
74
+ maximum=5,
75
+ value=3,
76
+ step=1,
77
+ label="Number of Examples"
78
+ )
79
+ search_btn = gr.Button("Search", variant="primary")
80
+
81
+ with gr.Column():
82
+ output_text = gr.Textbox(
83
+ label="Similar USMLE Questions",
84
+ lines=25,
85
+ max_lines=50
86
+ )
87
+
88
+ search_btn.click(
89
+ fn=search_interface,
90
+ inputs=[query_input, num_results_slider],
91
+ outputs=output_text
92
+ )
93
+
94
+ gr.Examples(
95
+ examples=[
96
+ ["hyponatremia", 3],
97
+ ["myocardial infarction", 2],
98
+ ["diabetic ketoacidosis", 3]
99
+ ],
100
+ inputs=[query_input, num_results_slider]
101
+ )
102
+
103
+ # FastAPI for API endpoints
104
  app = FastAPI(title="MedQA Search API")
105
 
106
  app.add_middleware(
 
116
  num_results: int = 3
117
 
118
  class SearchResponse(BaseModel):
119
+ results: list[dict]
120
+
121
+ @app.get("/")
122
+ async def root():
123
+ return {
124
+ "message": "MedQA Search API - Hugging Face Version",
125
+ "status": "running",
126
+ "collection_count": collection.count()
127
+ }
128
+
129
+ @app.post("/search_medqa", response_model=SearchResponse)
130
+ async def search_medqa(request: SearchRequest):
131
+ """Search MedQA database for similar USMLE questions"""
132
+ try:
133
+ embedding = model.encode(request.query).tolist()
134
+ results = collection.query(
135
+ query_embeddings=[embedding],
136
+ n_results=request.num_results
137
+ )
138
+
139
+ formatted_results = []
140
+ for i in range(len(results['documents'][0])):
141
+ formatted_results.append({
142
+ "example_number": i + 1,
143
+ "question": results['documents'][0][i],
144
+ "answer": results['metadatas'][0][i].get('answer', 'N/A'),
145
+ "distance": results['distances'][0][i] if 'distances' in results else None
146
+ })
147
+
148
+ return Sea