imurra commited on
Commit
15c714e
·
verified ·
1 Parent(s): 6c121ca

The issue: Missing launch() call or wrong server setup for Gradio.

Browse files

I see the issue! The app initializes perfectly (twice even!), but then exits with code 0 instead of staying running. The problem is that Hugging Face Spaces expects the app to keep running, but it's completing and exiting.
The issue: Missing launch() call or wrong server setup for Gradio.

Key Fix: Removed the if __name__ == "__main__" block that was causing the script to exit. Hugging Face Spaces will automatically run the mounted Gradio app.

Files changed (1) hide show
  1. app.py +25 -75
app.py CHANGED
@@ -8,7 +8,7 @@ import chromadb
8
  from sentence_transformers import SentenceTransformer
9
  import gradio as gr
10
 
11
- # Database path
12
  DB_PATH = "./medqa_db"
13
  ZIP_PATH = "./medqa_db.zip"
14
 
@@ -19,88 +19,34 @@ if not os.path.exists(DB_PATH) and os.path.exists(ZIP_PATH):
19
  zip_ref.extractall(".")
20
  print("Database extracted successfully!")
21
 
22
- # Initialize
23
  print(f"Loading database from: {DB_PATH}")
24
  client = chromadb.PersistentClient(path=DB_PATH)
25
  collection = client.get_collection("medqa")
26
  print(f"Collection loaded with {collection.count()} items")
27
- print(f"Loading MedCPT model...")
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(
@@ -121,20 +67,16 @@ class SearchResponse(BaseModel):
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])):
@@ -142,16 +84,24 @@ async def search_medqa(request: SearchRequest):
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 SearchResponse(results=formatted_results)
149
  except Exception as e:
150
  raise HTTPException(status_code=500, detail=str(e))
151
 
152
- @app.get("/health")
153
- async def health():
154
- return {"status": "healthy", "items": collection.count()}
 
 
 
 
 
 
 
 
 
155
 
156
- # Mount Gradio on FastAPI
157
  app = gr.mount_gradio_app(app, demo, path="/")
 
8
  from sentence_transformers import SentenceTransformer
9
  import gradio as gr
10
 
11
+ # Database setup
12
  DB_PATH = "./medqa_db"
13
  ZIP_PATH = "./medqa_db.zip"
14
 
 
19
  zip_ref.extractall(".")
20
  print("Database extracted successfully!")
21
 
22
+ # Load database and model
23
  print(f"Loading database from: {DB_PATH}")
24
  client = chromadb.PersistentClient(path=DB_PATH)
25
  collection = client.get_collection("medqa")
26
  print(f"Collection loaded with {collection.count()} items")
27
+ print("Loading MedCPT model...")
28
  model = SentenceTransformer('ncbi/MedCPT-Query-Encoder')
29
  print("Initialization complete!")
30
 
31
+ # Search function for Gradio
32
+ def search_gradio(query, num_results=3):
 
33
  if not query.strip():
34
+ return "Please enter a query."
 
35
  try:
36
  embedding = model.encode(query).tolist()
37
+ results = collection.query(query_embeddings=[embedding], n_results=int(num_results))
 
 
 
 
 
 
38
 
39
  output = ""
40
  for i in range(len(results['documents'][0])):
41
+ output += f"\n{'='*60}\nExample {i+1}\n{'='*60}\n"
 
 
42
  output += results['documents'][0][i] + "\n"
43
  output += f"\nAnswer: {results['metadatas'][0][i].get('answer', 'N/A')}\n"
44
  output += f"Similarity: {1 - results['distances'][0][i]:.3f}\n"
 
45
  return output
46
  except Exception as e:
47
  return f"Error: {str(e)}"
48
 
49
+ # FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  app = FastAPI(title="MedQA Search API")
51
 
52
  app.add_middleware(
 
67
  @app.get("/")
68
  async def root():
69
  return {
70
+ "message": "MedQA Search API",
71
  "status": "running",
72
  "collection_count": collection.count()
73
  }
74
 
75
  @app.post("/search_medqa", response_model=SearchResponse)
76
  async def search_medqa(request: SearchRequest):
 
77
  try:
78
  embedding = model.encode(request.query).tolist()
79
+ results = collection.query(query_embeddings=[embedding], n_results=request.num_results)
 
 
 
80
 
81
  formatted_results = []
82
  for i in range(len(results['documents'][0])):
 
84
  "example_number": i + 1,
85
  "question": results['documents'][0][i],
86
  "answer": results['metadatas'][0][i].get('answer', 'N/A'),
87
+ "distance": results['distances'][0][i]
88
  })
 
89
  return SearchResponse(results=formatted_results)
90
  except Exception as e:
91
  raise HTTPException(status_code=500, detail=str(e))
92
 
93
+ # Gradio interface
94
+ demo = gr.Interface(
95
+ fn=search_gradio,
96
+ inputs=[
97
+ gr.Textbox(label="Medical Query", placeholder="e.g., hyponatremia", lines=2),
98
+ gr.Slider(1, 5, value=3, step=1, label="Number of Results")
99
+ ],
100
+ outputs=gr.Textbox(label="Similar USMLE Questions", lines=20),
101
+ title="MedQA Search - USMLE Question Database",
102
+ description="Search for similar USMLE Step 1 questions using semantic similarity",
103
+ examples=[["hyponatremia", 3], ["myocardial infarction", 2]]
104
+ )
105
 
106
+ # Mount Gradio to FastAPI
107
  app = gr.mount_gradio_app(app, demo, path="/")