abuzarAli commited on
Commit
4265985
·
verified ·
1 Parent(s): 73464a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -50
app.py CHANGED
@@ -1,65 +1,84 @@
1
  import os
2
- import numpy as np
3
  import tensorflow as tf
4
- from tensorflow.keras.models import load_model
 
 
 
 
 
 
5
  from PIL import Image
6
- import streamlit as st
7
- from groq import Groq
8
 
9
  # Set Groq API key in environment variable
10
  os.environ['GROQ_API_KEY'] = "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"
11
  GROQ_API_KEY = os.getenv('GROQ_API_KEY')
12
 
13
- # Initialize Groq client
14
- client = Groq(api_key=GROQ_API_KEY)
 
 
 
 
 
15
 
16
- # Load the classification model (make sure the model is trained and saved)
17
- classification_model = load_model('classification_model.h5') # Model for normal/abnormal classification
18
 
19
- # Function to load the image and process it
20
- def load_image(image_file):
21
- img = Image.open(image_file)
22
- img = img.resize((224, 224)) # Resize image to match model input
23
- img_array = np.array(img) / 255.0 # Normalize the image
24
- return np.expand_dims(img_array, axis=0)
 
 
25
 
26
- # Function for AI-based knowledge generation using Groq API
27
- def generate_ai_insights(organ_name):
28
- chat_completion = client.chat.completions.create(
29
- messages=[
30
- {
31
- "role": "user",
32
- "content": f"Explain the diseases and treatments related to {organ_name}.",
33
- }
34
- ],
35
- model="llama-3.3-70b-versatile",
36
- )
37
- return chat_completion.choices[0].message.content
38
 
39
- # Streamlit UI
40
- st.title('Medical Image Classification and Insights')
41
- st.sidebar.title("Menu")
42
-
43
- uploaded_image = st.sidebar.file_uploader("Upload X-ray or MRI Image", type=["jpg", "png", "jpeg"])
44
-
45
- if uploaded_image is not None:
46
- image = load_image(uploaded_image)
47
-
48
- # Classify normal or abnormal
49
- prediction = classification_model.predict(image)
50
- if prediction[0] > 0.5:
51
- classification_result = "Normal"
52
  else:
53
- classification_result = "Abnormal"
54
 
55
- st.image(uploaded_image, caption="Uploaded Image", use_column_width=True)
56
- st.write(f"Image Classification: {classification_result}")
 
57
 
58
- # Recognize the organ (You can expand the model to predict organ type)
59
- organ_name = "Lung" # Placeholder
60
- st.write(f"Recognized Organ: {organ_name}")
61
-
62
- # Get AI insights for the recognized organ
63
- ai_insights = generate_ai_insights(organ_name)
64
- st.write("AI-Based Insights on Organ Diseases and Treatments:")
65
- st.write(ai_insights)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import streamlit as st
3
  import tensorflow as tf
4
+ from tensorflow.keras.applications import ResNet50
5
+ from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
6
+ from tensorflow.keras.models import Model
7
+ from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
8
+ from tensorflow.keras.preprocessing.image import img_to_array, load_img
9
+ import numpy as np
10
+ import requests
11
  from PIL import Image
 
 
12
 
13
  # Set Groq API key in environment variable
14
  os.environ['GROQ_API_KEY'] = "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"
15
  GROQ_API_KEY = os.getenv('GROQ_API_KEY')
16
 
17
+ # Load pre-trained ResNet50 for normal/abnormal classification
18
+ base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
19
+ x = base_model.output
20
+ x = GlobalAveragePooling2D()(x)
21
+ x = Dense(1024, activation='relu')(x)
22
+ predictions = Dense(1, activation='sigmoid')(x)
23
+ classification_model = Model(inputs=base_model.input, outputs=predictions)
24
 
25
+ # Load pre-trained ResNet50 for organ recognition
26
+ organ_model = ResNet50(weights='imagenet')
27
 
28
+ def classify_image(image_path):
29
+ """Classify the image as normal or abnormal."""
30
+ image = load_img(image_path, target_size=(224, 224))
31
+ image_array = img_to_array(image)
32
+ image_array = preprocess_input(image_array)
33
+ image_array = np.expand_dims(image_array, axis=0)
34
+ prediction = classification_model.predict(image_array)
35
+ return 'Abnormal' if prediction[0][0] > 0.5 else 'Normal'
36
 
37
+ def recognize_organ(image_path):
38
+ """Recognize the organ in the image."""
39
+ image = load_img(image_path, target_size=(224, 224))
40
+ image_array = img_to_array(image)
41
+ image_array = preprocess_input(image_array)
42
+ image_array = np.expand_dims(image_array, axis=0)
43
+ prediction = organ_model.predict(image_array)
44
+ decoded = decode_predictions(prediction, top=3)[0]
45
+ return decoded[0][1] # Top predicted class
 
 
 
46
 
47
+ def get_ai_insights(organ):
48
+ """Fetch AI-based insights about the organ using Groq API."""
49
+ url = "https://api.groq.com/v1/insights"
50
+ headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
51
+ data = {"query": f"Provide detailed insights about {organ} X-ray, its diseases, and treatments."}
52
+ response = requests.post(url, headers=headers, json=data)
53
+ if response.status_code == 200:
54
+ return response.json().get("insights", "No insights available.")
 
 
 
 
 
55
  else:
56
+ return "Failed to fetch insights. Please try again later."
57
 
58
+ def main():
59
+ st.title("Medical Image Classification App")
60
+ st.sidebar.title("Navigation")
61
 
62
+ uploaded_file = st.file_uploader("Upload an X-ray or MRI image", type=["jpg", "jpeg", "png"])
63
+
64
+ if uploaded_file:
65
+ image = Image.open(uploaded_file)
66
+ st.image(image, caption="Uploaded Image", use_column_width=True)
67
+
68
+ with open("temp_image.jpg", "wb") as f:
69
+ f.write(uploaded_file.getbuffer())
70
+
71
+ st.write("### Classification Result")
72
+ result = classify_image("temp_image.jpg")
73
+ st.write(f"The X-ray is classified as: **{result}**")
74
+
75
+ st.write("### Organ Recognition")
76
+ organ = recognize_organ("temp_image.jpg")
77
+ st.write(f"Recognized Organ: **{organ}**")
78
+
79
+ st.write("### AI-Based Insights")
80
+ insights = get_ai_insights(organ)
81
+ st.write(insights)
82
+
83
+ if __name__ == "__main__":
84
+ main()