yashbyname commited on
Commit
10ac7ef
·
verified ·
1 Parent(s): a4acb7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -55
app.py CHANGED
@@ -184,20 +184,12 @@ def create_chat_session():
184
  "externalUserId": external_user_id
185
  }
186
 
187
- logger.info("Creating chat session...")
188
  response = requests.post(create_session_url, headers=create_session_headers, json=create_session_body)
189
  response.raise_for_status()
190
-
191
- response_data = response.json()
192
- logger.info(f"Session created successfully: {json.dumps(response_data, indent=2)}")
193
-
194
- session_id = response_data['data']['id']
195
- return session_id
196
 
197
  except requests.exceptions.RequestException as e:
198
  logger.error(f"Error creating chat session: {str(e)}")
199
- if hasattr(e.response, 'text'):
200
- logger.error(f"Response content: {e.response.text}")
201
  raise
202
 
203
  def submit_query(session_id, query):
@@ -208,21 +200,20 @@ def submit_query(session_id, query):
208
  'Content-Type': 'application/json'
209
  }
210
 
211
- # Structured prompt to get JSON response
212
  structured_query = f"""
213
  Based on the following patient information, provide a detailed medical analysis in JSON format:
214
 
215
  {query}
216
 
217
- Please structure your response in valid JSON format with the following fields:
218
- - diagnosis_details: Overall diagnosis analysis
219
- - probable_diagnoses: Array of most probable diagnoses, ordered by likelihood
220
- - treatment_plans: Array of recommended treatment plans
221
- - lifestyle_modifications: Array of recommended lifestyle changes
222
- - medications: Array of recommended medications with dosages
223
- - additional_tests: Array of recommended additional tests or examinations
224
- - precautions: Array of important precautions or warnings
225
- - follow_up: Recommended follow-up timeline and actions
226
  """
227
 
228
  submit_query_body = {
@@ -232,57 +223,48 @@ def submit_query(session_id, query):
232
  "responseMode": "sync"
233
  }
234
 
235
- logger.info(f"Submitting query for session {session_id}")
236
  response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
237
  response.raise_for_status()
238
-
239
- response_data = response.json()
240
- logger.info(f"Query response received: {json.dumps(response_data, indent=2)}")
241
- return response_data
242
 
243
  except requests.exceptions.RequestException as e:
244
  logger.error(f"Error submitting query: {str(e)}")
245
- if hasattr(e.response, 'text'):
246
- logger.error(f"Response content: {e.response.text}")
247
  raise
248
 
249
- def format_json_response(json_str):
250
- """Format the JSON response for better readability"""
251
  try:
252
- data = json.loads(json_str)
253
- return json.dumps(data, indent=2)
254
  except json.JSONDecodeError:
255
- return json_str
 
 
 
 
 
 
 
 
 
256
 
257
  def gradio_interface(patient_info):
258
  try:
259
- # Create session
260
  session_id = create_chat_session()
261
-
262
- # Submit query and get response
263
  llm_response = submit_query(session_id, patient_info)
264
 
265
- # Enhanced response handling
266
  if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
267
- logger.error("Invalid response structure")
268
- return "Error: Invalid response from the LLM service"
269
-
270
- # Get the answer and format it
271
- answer = llm_response['data']['answer']
272
- formatted_answer = format_json_response(answer)
273
-
274
- # Add processing metrics
275
- metrics = llm_response['data'].get('metrics', {})
276
- processing_time = metrics.get('totalTimeSec', 'N/A')
277
 
278
- # Combine the response
279
- full_response = f"Analysis Results (Processing Time: {processing_time} seconds):\n\n{formatted_answer}"
280
 
281
- return full_response
 
282
 
283
  except Exception as e:
284
- logger.error(f"Error in gradio_interface: {str(e)}", exc_info=True)
285
- return f"Error processing request: {str(e)}"
286
 
287
  # Gradio interface
288
  iface = gr.Interface(
@@ -297,14 +279,11 @@ iface = gr.Interface(
297
  ],
298
  outputs=gr.Textbox(
299
  label="Medical Analysis",
300
- placeholder="The analysis will appear here in JSON format...",
301
  lines=15
302
  ),
303
  title="Medical Diagnosis Assistant",
304
- description="""
305
- Enter detailed patient information to receive a structured medical analysis.
306
- The system will provide diagnosis possibilities, treatment recommendations, and other relevant medical advice in JSON format.
307
- """
308
  )
309
 
310
  if __name__ == "__main__":
 
184
  "externalUserId": external_user_id
185
  }
186
 
 
187
  response = requests.post(create_session_url, headers=create_session_headers, json=create_session_body)
188
  response.raise_for_status()
189
+ return response.json()['data']['id']
 
 
 
 
 
190
 
191
  except requests.exceptions.RequestException as e:
192
  logger.error(f"Error creating chat session: {str(e)}")
 
 
193
  raise
194
 
195
  def submit_query(session_id, query):
 
200
  'Content-Type': 'application/json'
201
  }
202
 
 
203
  structured_query = f"""
204
  Based on the following patient information, provide a detailed medical analysis in JSON format:
205
 
206
  {query}
207
 
208
+ Return only valid JSON with these fields:
209
+ - diagnosis_details
210
+ - probable_diagnoses (array)
211
+ - treatment_plans (array)
212
+ - lifestyle_modifications (array)
213
+ - medications (array of objects with name and dosage)
214
+ - additional_tests (array)
215
+ - precautions (array)
216
+ - follow_up (string)
217
  """
218
 
219
  submit_query_body = {
 
223
  "responseMode": "sync"
224
  }
225
 
 
226
  response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
227
  response.raise_for_status()
228
+ return response.json()
 
 
 
229
 
230
  except requests.exceptions.RequestException as e:
231
  logger.error(f"Error submitting query: {str(e)}")
 
 
232
  raise
233
 
234
+ def extract_json_from_answer(answer):
235
+ """Extract and clean JSON from the LLM response"""
236
  try:
237
+ # First try to parse the answer directly
238
+ return json.loads(answer)
239
  except json.JSONDecodeError:
240
+ try:
241
+ # If that fails, try to find JSON content and parse it
242
+ start_idx = answer.find('{')
243
+ end_idx = answer.rfind('}') + 1
244
+ if start_idx != -1 and end_idx != 0:
245
+ json_str = answer[start_idx:end_idx]
246
+ return json.loads(json_str)
247
+ except (json.JSONDecodeError, ValueError):
248
+ logger.error("Failed to parse JSON from response")
249
+ raise
250
 
251
  def gradio_interface(patient_info):
252
  try:
 
253
  session_id = create_chat_session()
 
 
254
  llm_response = submit_query(session_id, patient_info)
255
 
 
256
  if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
257
+ raise ValueError("Invalid response structure")
 
 
 
 
 
 
 
 
 
258
 
259
+ # Extract and clean JSON from the response
260
+ json_data = extract_json_from_answer(llm_response['data']['answer'])
261
 
262
+ # Return clean JSON string without extra formatting
263
+ return json.dumps(json_data)
264
 
265
  except Exception as e:
266
+ logger.error(f"Error in gradio_interface: {str(e)}")
267
+ return json.dumps({"error": str(e)})
268
 
269
  # Gradio interface
270
  iface = gr.Interface(
 
279
  ],
280
  outputs=gr.Textbox(
281
  label="Medical Analysis",
282
+ placeholder="JSON analysis will appear here...",
283
  lines=15
284
  ),
285
  title="Medical Diagnosis Assistant",
286
+ description="Enter detailed patient information to receive a structured medical analysis in JSON format."
 
 
 
287
  )
288
 
289
  if __name__ == "__main__":