File size: 9,400 Bytes
0eaad25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from groq import Groq
import base64
from PIL import Image
import io
import os
from dotenv import load_dotenv
from io import BytesIO
import requests
import streamlit.components.v1 as components

st.set_page_config(page_title="My App", page_icon="", layout="wide", initial_sidebar_state="collapsed")
import streamlit as st

# Initialize session state for dark mode (default: True)
if "dark_mode" not in st.session_state:
    st.session_state.dark_mode = True

# Icon switch
icon = "☀️" if st.session_state.dark_mode else "🌙"

# Toggle button (tap to switch modes)
if st.button(icon, key="dark_mode_toggle"):
    st.session_state.dark_mode = not st.session_state.dark_mode
    st.rerun()

# Apply styles for dark & light modes
if st.session_state.dark_mode:
    st.markdown(
        """
        <style>
        body, .stApp { background-color: #121212; color: white; }
        h1, h2, h3, p, label { color: white !important; }
        .stTextInput, .stButton > button, .stSelectbox, .stTextArea {
            background-color: #222; 
            color: white; 
            border-radius: 10px;
            border: 1px solid #444;
        }
        .stMarkdown a { color: #4db8ff; }
        .stAlert { background-color: #222; color: white; }
        </style>
        """,
        unsafe_allow_html=True,
    )
else:
    st.markdown(
        """
        <style>
        body, .stApp { background-color: #ffffff; color: #333; }
        h1, h2, h3, p, label { color: #333 !important; }
        .stTextInput, .stButton > button, .stSelectbox, .stTextArea {
            background-color: #f8f9fa; 
            color: #333; 
            border-radius: 10px; 
            border: 1px solid #ccc;
        }
        .stMarkdown a { color: #007bff; }
        .stAlert { background-color: #f8f9fa; color: #333; }
        </style>
        """,
        unsafe_allow_html=True,
    )


# Hides Streamlit UI elements with CSS
hide_streamlit_style = """
    <style>
        #MainMenu {visibility: hidden;}
        footer {visibility: hidden;}
        header {visibility: hidden;}
        .stDeployButton {display: none !important;} 
        [data-testid="stProfileMenu"] {display: none !important;}  
    </style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)




# Load environment variables from .env file
load_dotenv()

# Retrieve Groq API key from environment variables
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

# Check if API key is loaded correctly
if not GROQ_API_KEY:
    st.error("Groq API key not found. Please set it in the .env file.")
    st.stop()

# Initialize Groq client
client = Groq(api_key=GROQ_API_KEY)

def encode_image(image):
    """Convert a PIL Image object to base64-encoded JPEG format"""
    # Convert RGBA to RGB if needed
    if image.mode == "RGBA":
        image = image.convert("RGB")

    # Save image as JPEG in memory
    buffer = BytesIO()
    image.save(buffer, format="JPEG")
    base64_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
    
    return base64_image

# Function to classify MRI image using Groq API
def classify_mri_image(image):
    base64_image = encode_image(image)
    
    # Prompt for the Groq API
    prompt = "Analyze this MRI image and determine if it shows a brain tumor. Provide a clear classification (e.g., 'Tumor detected' or 'No tumor detected') and a brief explanation."
    
    # Call Groq API with Llama 3.2-90B Vision Preview
    response = client.chat.completions.create(
        model="llama-3.2-90b-vision-preview",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
                ]
            }
        ],
        max_tokens=300
    )
    
    # Extract the response
    result = response.choices[0].message.content
    return result

# Streamlit app
def main():
    st.title("MRI Brain Tumor Classifier")
    st.write("Upload an MRI image to classify whether it contains a brain tumor.")

    uploaded_file = st.file_uploader("Choose an MRI image...", type=["jpg", "jpeg", "png"])
    
    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.image(image, caption="Uploaded MRI Image", use_container_width=True)

        if st.button("Classify Image"):
            with st.spinner("Classifying..."):
                try:
                    result = classify_mri_image(image)
                    st.success("Classification Complete!")
                    st.write("### Result:")
                    st.write(result)
                except Exception as e:
                    st.error(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    main()



st.markdown("---")


# Function to check if the question is related to brain tumors
def is_brain_tumor_question(user_input):
    keywords = [
    "brain tumor", "glioma", "meningioma", "astrocytoma", "medulloblastoma", 
    "ependymoma", "oligodendroglioma", "pituitary tumor", "schwannoma", "craniopharyngioma",
    "cancer", "brain cancer", "malignant tumor", "benign tumor", 
    "neurology", "oncology", "neurosurgeon", "brain MRI", "CT scan brain", "tumor diagnosis",
    "tumor treatment", "chemotherapy", "radiotherapy", "stereotactic radiosurgery", 
    "brain surgery", "craniotomy", "tumor removal", "brain biopsy",
    "symptoms of brain tumor", "headache and tumor", "seizures and tumor", 
    "brain tumor prognosis", "life expectancy brain tumor", "brain metastases",
    "tumor recurrence", "brain swelling", "intracranial pressure", "glioblastoma multiforme",
    "brain tumor in children", "brain tumor in adults", "radiation therapy for brain tumors", "brain",
    "brain-tumor"
]
    return any(keyword in user_input.lower() for keyword in keywords)

# Function to interact with Groq chatbot
def get_chatbot_response(user_input):
    if not is_brain_tumor_question(user_input):
        return "I can only answer brain tumor-related questions."

    url = "https://api.groq.com/openai/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "llama3-8b-8192",
        "messages": [
            {"role": "system", "content": "You are a helpful AI that answers only brain tumor-related questions. Keep responses a little bit brief if question doesn't demand explanations."},
            {"role": "user", "content": user_input}
        ]
    }
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response_data = response.json()
        if response.status_code == 200:
            return response_data.get("choices", [{}])[0].get("message", {}).get("content", "No response generated.")
        else:
            return f"Error {response.status_code}: {response_data.get('error', {}).get('message', 'Unknown error')}"
    except requests.exceptions.RequestException as e:
        return f"Request failed: {e}"

# Custom CSS for styling the input and send icon
import streamlit as st

st.markdown("""
    <style>
    .chat-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        border: 1px solid #444;
        border-radius: 20px;
        padding: 10px;
        background-color: #222;
        width: 100%;
        max-width: 400px;
        margin: auto;
    }
    .chat-input {
        height: 45px;
        font-size: 17px; /* Slightly increased */
        border: none;
        width: 100%;
        max-width: 400px;
        border-radius: 10px;
        padding: 10px;
        background-color: #333;
        color: white;
        outline: none;
    }
    .send-button {
        cursor: pointer;
        font-weight: bold;
        text-align: center;
         background-color: #111f3f;
        color: white;
        transition: background 0.3s ease-in-out;
        margin-top: 10px;
        border: none;
        border-radius: 10px;
        width: 100%;
        max-width: 400px;
        height: 45px;
        padding: 12px;
        font-size: 17px; /* Slightly increased */
    }
    .send-button:hover {
        background-color: #888888; /* Slightly darker gray on hover */
    }

    /* Mobile View */
    @media (max-width: 600px) {
        .chat-container {
            width: 90%;
        }
        .chat-input {
            width: 100%;
            font-size: 16px; /* Slightly increased */
            height: 40px;
            padding: 8px;
        }
        .send-button {
            width: 128px; /* 2 inches */
            font-size: 16px; /* Slightly increased */
            height: 40px;
            padding: 8px;
        }
    }
</style>

""", unsafe_allow_html=True)

st.write("Ask me any brain tumor-related questions")

user_input = st.text_input("", placeholder="Enter your question...", key="input_box", label_visibility="collapsed")

st.markdown("""  
    <div style="display: flex; justify-content: center; width: 100%; margin-top: 10px;">
        <button class="send-button" onclick="sendMessage()">Send</button>
    </div>
""", unsafe_allow_html=True)

if user_input:
    st.write("")  # Adds a space before generating the response
    with st.spinner("Thinking..."):
        response = get_chatbot_response(user_input)
    st.write(response)