yashbyname commited on
Commit
aff9b10
·
verified ·
1 Parent(s): 55dab18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -4
app.py CHANGED
@@ -39,9 +39,168 @@ def load_model():
39
  logger.error(f"Error loading model: {str(e)}")
40
  raise
41
 
42
- # Rest of the functions remain the same until the Gradio interface...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  iface = gr.Interface(
46
  fn=gradio_interface,
47
  inputs=[
@@ -71,8 +230,6 @@ if __name__ == "__main__":
71
 
72
 
73
 
74
-
75
-
76
  # import requests
77
  # import gradio as gr
78
  # import logging
 
39
  logger.error(f"Error loading model: {str(e)}")
40
  raise
41
 
42
+ # Preprocess image for model
43
+ def preprocess_image(image):
44
+ try:
45
+ # Convert to numpy array if needed
46
+ if isinstance(image, Image.Image):
47
+ image = np.array(image)
48
+
49
+ # Ensure image has 3 channels (RGB)
50
+ if len(image.shape) == 2: # Grayscale image
51
+ image = np.stack((image,) * 3, axis=-1)
52
+ elif len(image.shape) == 3 and image.shape[2] == 4: # RGBA image
53
+ image = image[:, :, :3]
54
+
55
+ # Resize image to match model's expected input shape
56
+ target_size = (224, 224) # Change this to match your model's input size
57
+ image = tf.image.resize(image, target_size)
58
+
59
+ # Normalize pixel values
60
+ image = image / 255.0
61
+
62
+ # Add batch dimension
63
+ image = np.expand_dims(image, axis=0)
64
+
65
+ return image
66
+ except Exception as e:
67
+ logger.error(f"Error preprocessing image: {str(e)}")
68
+ raise
69
+
70
+ def create_chat_session():
71
+ try:
72
+ create_session_url = 'https://api.on-demand.io/chat/v1/sessions'
73
+ create_session_headers = {
74
+ 'apikey': api_key,
75
+ 'Content-Type': 'application/json'
76
+ }
77
+ create_session_body = {
78
+ "pluginIds": [],
79
+ "externalUserId": external_user_id
80
+ }
81
+
82
+ response = requests.post(create_session_url, headers=create_session_headers, json=create_session_body)
83
+ response.raise_for_status()
84
+ return response.json()['data']['id']
85
+
86
+ except requests.exceptions.RequestException as e:
87
+ logger.error(f"Error creating chat session: {str(e)}")
88
+ raise
89
+
90
+ def submit_query(session_id, query, image_analysis=None):
91
+ try:
92
+ submit_query_url = f'https://api.on-demand.io/chat/v1/sessions/{session_id}/query'
93
+ submit_query_headers = {
94
+ 'apikey': api_key,
95
+ 'Content-Type': 'application/json'
96
+ }
97
+
98
+ # Include image analysis in the query if available
99
+ query_with_image = query
100
+ if image_analysis:
101
+ query_with_image += f"\n\nImage Analysis Results: {image_analysis}"
102
+
103
+ structured_query = f"""
104
+ Based on the following patient information and image analysis, provide a detailed medical analysis in JSON format:
105
+ {query_with_image}
106
+ Return only valid JSON with these fields:
107
+ - diagnosis_details
108
+ - probable_diagnoses (array)
109
+ - treatment_plans (array)
110
+ - lifestyle_modifications (array)
111
+ - medications (array of objects with name and dosage)
112
+ - additional_tests (array)
113
+ - precautions (array)
114
+ - follow_up (string)
115
+ - image_findings (object with prediction and confidence)
116
+ """
117
+
118
+ submit_query_body = {
119
+ "endpointId": "predefined-openai-gpt4o",
120
+ "query": structured_query,
121
+ "pluginIds": ["plugin-1712327325", "plugin-1713962163"],
122
+ "responseMode": "sync"
123
+ }
124
+
125
+ response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
126
+ response.raise_for_status()
127
+ return response.json()
128
+
129
+ except requests.exceptions.RequestException as e:
130
+ logger.error(f"Error submitting query: {str(e)}")
131
+ raise
132
+
133
+ def extract_json_from_answer(answer):
134
+ """Extract and clean JSON from the LLM response"""
135
+ try:
136
+ return json.loads(answer)
137
+ except json.JSONDecodeError:
138
+ try:
139
+ # Find the first occurrence of '{' and last occurrence of '}'
140
+ start_idx = answer.find('{')
141
+ end_idx = answer.rfind('}') + 1
142
+ if start_idx != -1 and end_idx != 0:
143
+ json_str = answer[start_idx:end_idx]
144
+ return json.loads(json_str)
145
+ except (json.JSONDecodeError, ValueError):
146
+ logger.error("Failed to parse JSON from response")
147
+ raise
148
+
149
+ def format_prediction(prediction):
150
+ """Format model prediction into a standardized structure"""
151
+ try:
152
+ # Adjust this based on your model's output format
153
+ confidence = float(prediction[0][0])
154
+ return {
155
+ "prediction": "abnormal" if confidence > 0.5 else "normal",
156
+ "confidence": round(confidence * 100, 2)
157
+ }
158
+ except Exception as e:
159
+ logger.error(f"Error formatting prediction: {str(e)}")
160
+ raise
161
 
162
+ # Initialize the model
163
+ try:
164
+ model = load_model()
165
+ except Exception as e:
166
+ logger.error(f"Failed to initialize model: {str(e)}")
167
+ model = None
168
+
169
+ def gradio_interface(patient_info, image):
170
+ try:
171
+ if model is None:
172
+ raise ValueError("Model not properly initialized")
173
+
174
+ # Process image if provided
175
+ image_analysis = None
176
+ if image is not None:
177
+ # Preprocess image
178
+ processed_image = preprocess_image(image)
179
+
180
+ # Get model prediction
181
+ prediction = model.predict(processed_image)
182
+
183
+ # Format prediction results
184
+ image_analysis = format_prediction(prediction)
185
+
186
+ # Create chat session and submit query
187
+ session_id = create_chat_session()
188
+ llm_response = submit_query(session_id, patient_info,
189
+ json.dumps(image_analysis) if image_analysis else None)
190
+
191
+ if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
192
+ raise ValueError("Invalid response structure from LLM")
193
+
194
+ # Extract and clean JSON from the response
195
+ json_data = extract_json_from_answer(llm_response['data']['answer'])
196
+
197
+ # Format output for better readability
198
+ return json.dumps(json_data, indent=2)
199
+
200
+ except Exception as e:
201
+ logger.error(f"Error in gradio_interface: {str(e)}")
202
+ return json.dumps({"error": str(e)}, indent=2)
203
+
204
  iface = gr.Interface(
205
  fn=gradio_interface,
206
  inputs=[
 
230
 
231
 
232
 
 
 
233
  # import requests
234
  # import gradio as gr
235
  # import logging