File size: 13,992 Bytes
a149a7b
 
6eb0efb
 
c07a771
c00355e
f3a1e2d
 
fd482de
dfaf276
6eb0efb
dfaf276
aa3dc7a
 
 
 
6eb0efb
e7f38cd
dfaf276
 
 
 
c15f3d1
1b6df32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c15f3d1
1b6df32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8983f2e
c15f3d1
a32bf71
5ba94a9
a5e5c8f
5ba94a9
 
a5e5c8f
 
7c8eb62
a5e5c8f
5ba94a9
a5e5c8f
 
5ba94a9
 
 
 
 
a5e5c8f
5ba94a9
 
 
 
 
 
 
 
 
 
a5e5c8f
dfaf276
 
 
aa3dc7a
dfaf276
 
 
c00355e
dfaf276
 
 
 
 
 
 
aa3dc7a
dfaf276
ef3808c
dfaf276
f7e3b0e
ef3808c
dfaf276
 
f7e3b0e
dfaf276
 
 
 
ef3808c
dfaf276
 
 
 
 
 
 
 
 
f3a1e2d
dfaf276
 
 
 
 
 
 
 
 
 
aff9b10
dfaf276
dad3de7
dfaf276
b76fcf3
fd7fd22
dfaf276
 
 
 
 
 
 
 
 
 
 
aff9b10
dfaf276
aff9b10
 
dfaf276
 
 
 
ef3808c
dfaf276
 
ef3808c
633dcc8
a32bf71
dfaf276
 
 
 
 
 
 
 
 
 
 
 
 
 
5ba94a9
b9bef1f
dfaf276
 
633dcc8
a638f30
dfaf276
 
633dcc8
dfaf276
 
 
 
 
7c8eb62
 
 
c7096a1
dfaf276
 
 
 
 
 
 
 
 
aa3dc7a
e7f38cd
7c8eb62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8983f2e
7c8eb62
 
 
 
 
aa3dc7a
7c8eb62
 
 
 
f3a1e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import requests
import gradio as gr
import logging
import json
import tf_keras
import tensorflow_hub as hub
import numpy as np
from PIL import Image
import io
import os

# Set up logging with more detailed format
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# API key and user ID for on-demand
api_key = 'KGSjxB1uptfSk8I8A7ciCuNT9Xa3qWC3'
external_user_id = 'plugin-1717464304'

def create_chat_session():
    try:
        create_session_url = 'https://api.on-demand.io/chat/v1/sessions'
        create_session_headers = {
            'apikey': api_key,
            'Content-Type': 'application/json'
        }
        create_session_body = {
            "pluginIds": [],
            "externalUserId": external_user_id
        }
        
        response = requests.post(create_session_url, headers=create_session_headers, json=create_session_body)
        response.raise_for_status()
        return response.json()['data']['id']
    
    except requests.exceptions.RequestException as e:
        logger.error(f"Error creating chat session: {str(e)}")
        raise
        
def submit_query(session_id, query):
    try:
        submit_query_url = f'https://api.on-demand.io/chat/v1/sessions/{session_id}/query'
        submit_query_headers = {
            'apikey': api_key,
            'Content-Type': 'application/json'
        }
        
        structured_query = f"""
        Based on the following patient information, provide a detailed medical analysis in JSON format:

        {query}

        Return only valid JSON with these fields:
        - diagnosis_details
        - probable_diagnoses (array)
        - treatment_plans (array)
        - lifestyle_modifications (array)
        - medications (array of objects with name and dosage)
        - additional_tests (array)
        - precautions (array)
        - follow_up (string)
        """
        
        submit_query_body = {
            "endpointId": "predefined-openai-gpt4o",
            "query": structured_query,
            "pluginIds": ["plugin-1712327325", "plugin-1713962163"],
            "responseMode": "sync"
        }
        
        response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
        response.raise_for_status()
        return response.json()
    
    except requests.exceptions.RequestException as e:
        logger.error(f"Error submitting query: {str(e)}")
        raise


def extract_json_from_answer(answer, image_analysis):
    """Extract and clean JSON from the LLM response and append image analysis results."""
    try:
        # Try to parse the JSON answer directly
        json_data = json.loads(answer)
    except json.JSONDecodeError:
        try:
            # If that fails, try to find JSON content and parse it
            start_idx = answer.find('{')
            end_idx = answer.rfind('}') + 1
            if start_idx != -1 and end_idx != 0:
                json_str = answer[start_idx:end_idx]
                json_data = json.loads(json_str)
            else:
                raise ValueError("Failed to locate JSON in the answer")
        except (json.JSONDecodeError, ValueError) as e:
            logger.error(f"Failed to parse JSON from response: {str(e)}")
            raise
    
    # Append the image analysis data
    if image_analysis:
        json_data["image_analysis"] = {
            "prediction": image_analysis["prediction"],
            "confidence": f"{image_analysis['confidence']:.2f}%"  # Format confidence as percentage
        }

    return json_data


def load_model():
    try:
        model_path = 'model_epoch_01.h5.keras'
        
        # Check if model file exists
        if not os.path.exists(model_path):
            raise FileNotFoundError(f"Model file not found at {model_path}")
            
        logger.info(f"Attempting to load model from {model_path}")
        
        # Define custom objects dictionary
        custom_objects = {
            'KerasLayer': hub.KerasLayer
            # Add more custom objects if needed
        }
        
        # Try loading with different configurations
        try:
            logger.info("Attempting to load model with custom objects...")
            model = tf_keras.models.load_model(model_path, custom_objects={'KerasLayer': hub.KerasLayer})
        except Exception as e:
            logger.error(f"Failed to load with custom objects: {str(e)}")
            logger.info("Attempting to load model without custom objects...")
            model = tf_keras.models.load_model(model_path)
        
        # Verify model loaded correctly
        if model is None:
            raise ValueError("Model loading returned None")
            
        # Print model summary for debugging
        model.summary()
        logger.info("Model loaded successfully")
        return model
        
    except Exception as e:
        logger.error(f"Error loading model: {str(e)}")
        logger.error(f"Model loading failed with exception type: {type(e)}")
        raise

# Initialize the model globally
try:
    logger.info("Initializing model...")
    model = load_model()
    logger.info("Model initialization completed")
except Exception as e:
    logger.error(f"Failed to initialize model: {str(e)}")
    model = None
    
def preprocess_image(image):
    try:
        # Log image shape and type for debugging
        #logger.info(f"Input image shape: {image.}, dtype: {image.dtype}")
        
        image = image.convert('RGB')
        image = image.resize((256, 256))
        image = np.array(image)
        
        # Normalize pixel values
        image = image / 255.0
        
        # Add batch dimension
        image = np.expand_dims(image, axis=0)
        logger.info(f"Final preprocessed image shape: {image.shape}")
        
        return image
        
    except Exception as e:
        logger.error(f"Error preprocessing image: {str(e)}")
        raise

def gradio_interface(patient_info, image):
    try:
        if model is None:
            logger.error("Model is not initialized")
            return json.dumps({
                "error": "Model initialization failed. Please check the logs for details.",
                "status": "error"
            }, indent=2)

        classes = ["Alzheimer's", "Normal", "Stroke", "Tumor"]
        # Process image if provided
        image_analysis = None
        if image is not None:
            logger.info("Processing uploaded image")
            # Preprocess image
            processed_image = preprocess_image(image)
            
            # Get model prediction
            logger.info("Running model prediction")
            prediction = model.predict(processed_image)
            logger.info(f"Raw prediction shape: {prediction.shape}")
            logger.info(f"Prediction: {prediction}")
            # Format prediction results
            image_analysis = {
                "prediction": classes[np.argmax(prediction[0])],
                "confidence": np.max(prediction[0]) * 100
            }
            logger.info(f"Image analysis results: {image_analysis}")

        patient_info += f"Prediction based on MRI images: {image_analysis['prediction']}, Confidence: {image_analysis['confidence']}"
        # Create chat session and submit query
        session_id = create_chat_session()
        llm_response = submit_query(session_id, patient_info)
        
        if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
            raise ValueError("Invalid response structure from LLM")
        
        # Extract and clean JSON from the response
        logger.info(f"llm_response: {llm_response}")
        logger.info(f"llm_response[data]: {llm_response['data']}")
        logger.info(f"llm_response[data][answer]: {llm_response['data']['answer']}")
        json_data = extract_json_from_answer(llm_response['data']['answer'], image_analysis)
        return json.dumps(json_data, indent=2)
        
    except Exception as e:
        logger.error(f"Error in gradio_interface: {str(e)}")
        return json.dumps({
            "error": str(e),
            "status": "error",
            "details": "Check the application logs for more information"
        }, indent=2)


# Gradio interface
iface = gr.Interface(
    fn=gradio_interface,
    inputs=[
        gr.Textbox(
            label="Patient Information",
            placeholder="Enter patient details including: symptoms, medical history, current medications, age, gender, and any relevant test results...",
            lines=5,
            max_lines=10
        ),
        gr.Image(
            label="Medical Image",
            type="pil",
            interactive=True
        )
    ],
    outputs=gr.Textbox(
        label="Medical Analysis",
        placeholder="JSON analysis will appear here...",
        lines=15
    ),
    title="Medical Diagnosis Assistant",
    description="Enter patient information and optionally upload a medical image for analysis."
)

if __name__ == "__main__":
    # Add version information logging
    logger.info(f"TensorFlow Keras version: {tf_keras.__version__}")
    logger.info(f"TensorFlow Hub version: {hub.__version__}")
    logger.info(f"Gradio version: {gr.__version__}")
    
    iface.launch(
        server_name="0.0.0.0",
        debug=True
    )



# import requests
# import gradio as gr
# import logging
# import json

# # Set up logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # API key and user ID for on-demand
# api_key = 'KGSjxB1uptfSk8I8A7ciCuNT9Xa3qWC3'
# external_user_id = 'plugin-1717464304'

# def create_chat_session():
#     try:
#         create_session_url = 'https://api.on-demand.io/chat/v1/sessions'
#         create_session_headers = {
#             'apikey': api_key,
#             'Content-Type': 'application/json'
#         }
#         create_session_body = {
#             "pluginIds": [],
#             "externalUserId": external_user_id
#         }
        
#         response = requests.post(create_session_url, headers=create_session_headers, json=create_session_body)
#         response.raise_for_status()
#         return response.json()['data']['id']
    
#     except requests.exceptions.RequestException as e:
#         logger.error(f"Error creating chat session: {str(e)}")
#         raise

# def submit_query(session_id, query):
#     try:
#         submit_query_url = f'https://api.on-demand.io/chat/v1/sessions/{session_id}/query'
#         submit_query_headers = {
#             'apikey': api_key,
#             'Content-Type': 'application/json'
#         }
        
#         structured_query = f"""
#         Based on the following patient information, provide a detailed medical analysis in JSON format:

#         {query}

#         Return only valid JSON with these fields:
#         - diagnosis_details
#         - probable_diagnoses (array)
#         - treatment_plans (array)
#         - lifestyle_modifications (array)
#         - medications (array of objects with name and dosage)
#         - additional_tests (array)
#         - precautions (array)
#         - follow_up (string)
#         """
        
#         submit_query_body = {
#             "endpointId": "predefined-openai-gpt4o",
#             "query": structured_query,
#             "pluginIds": ["plugin-1712327325", "plugin-1713962163"],
#             "responseMode": "sync"
#         }
        
#         response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
#         response.raise_for_status()
#         return response.json()
    
#     except requests.exceptions.RequestException as e:
#         logger.error(f"Error submitting query: {str(e)}")
#         raise

# def extract_json_from_answer(answer):
#     """Extract and clean JSON from the LLM response"""
#     try:
#         # First try to parse the answer directly
#         return json.loads(answer)
#     except json.JSONDecodeError:
#         try:
#             # If that fails, try to find JSON content and parse it
#             start_idx = answer.find('{')
#             end_idx = answer.rfind('}') + 1
#             if start_idx != -1 and end_idx != 0:
#                 json_str = answer[start_idx:end_idx]
#                 return json.loads(json_str)
#         except (json.JSONDecodeError, ValueError):
#             logger.error("Failed to parse JSON from response")
#             raise

# def gradio_interface(patient_info):
#     try:
#         session_id = create_chat_session()
#         llm_response = submit_query(session_id, patient_info)
        
#         if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
#             raise ValueError("Invalid response structure")
        
#         # Extract and clean JSON from the response
#         json_data = extract_json_from_answer(llm_response['data']['answer'])
        
#         # Return clean JSON string without extra formatting
#         return json.dumps(json_data)
    
#     except Exception as e:
#         logger.error(f"Error in gradio_interface: {str(e)}")
#         return json.dumps({"error": str(e)})

# # Gradio interface
# iface = gr.Interface(
#     fn=gradio_interface,
#     inputs=[
#         gr.Textbox(
#             label="Patient Information",
#             placeholder="Enter patient details including: symptoms, medical history, current medications, age, gender, and any relevant test results...",
#             lines=5,
#             max_lines=10
#         )
#     ],
#     outputs=gr.Textbox(
#         label="Medical Analysis",
#         placeholder="JSON analysis will appear here...",
#         lines=15
#     ),
#     title="Medical Diagnosis Assistant",
#     description="Enter detailed patient information to receive a structured medical analysis in JSON format."
# )

# if __name__ == "__main__":
#     iface.launch()