File size: 16,498 Bytes
87fdfe1
 
 
 
 
 
 
 
 
 
 
236f289
 
 
 
 
 
 
 
 
87fdfe1
 
236f289
87fdfe1
 
 
 
236f289
 
87fdfe1
 
 
 
236f289
 
87fdfe1
 
236f289
87fdfe1
 
 
236f289
 
 
 
 
 
 
 
87fdfe1
 
 
236f289
 
 
 
87fdfe1
 
 
236f289
 
87fdfe1
236f289
 
87fdfe1
236f289
 
 
87fdfe1
 
 
236f289
 
 
 
 
 
87fdfe1
 
 
 
 
 
 
 
 
236f289
87fdfe1
 
 
 
236f289
 
 
 
87fdfe1
 
236f289
 
 
 
 
 
 
 
 
 
 
87fdfe1
 
 
236f289
87fdfe1
236f289
 
87fdfe1
 
 
236f289
 
 
 
 
 
 
87fdfe1
 
 
236f289
87fdfe1
 
 
 
236f289
87fdfe1
 
 
 
 
 
 
 
236f289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87fdfe1
 
 
 
236f289
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131f0c3
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae6054f
 
 
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131f0c3
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131f0c3
87fdfe1
 
 
 
131f0c3
87fdfe1
 
131f0c3
87fdfe1
 
131f0c3
87fdfe1
 
131f0c3
87fdfe1
 
131f0c3
87fdfe1
 
131f0c3
87fdfe1
 
 
 
 
 
ae6054f
 
 
87fdfe1
 
ae6054f
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131f0c3
87fdfe1
 
 
131f0c3
87fdfe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131f0c3
9ed2f84
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import streamlit as st
import os
from groq import Groq
from datetime import datetime

# Set page config FIRST
st.set_page_config(page_title="AI Medical Consultancy", layout="wide")

# Custom CSS for styling
st.markdown("""
    <style>
    /* Color Variables */
    :root {
        --primary: #3498db;       /* Blue */
        --secondary: #2c3e50;     /* Dark accent */
        --accent: #f1c40f;        /* Yellow */
        --success: #2ecc71;       /* Positive actions */
        --light: #ffffff;         /* White backgrounds */
        --dark: #000000;          /* Black text/elements */
    }
    /* Main container styling */
    .stApp {
        background: linear-gradient(135deg, #3498db 0%, #e0e0e0 100%);
        font-family: 'Arial', sans-serif;
    }
    /* Headers styling */
    h1, h2, h3 {
        color: var(--dark) !important;
        border-bottom: 3px solid var(--primary);
        padding-bottom: 0.3em;
    }
    /* Form containers */
    .stForm {
        background: #000000;
        border: 1px solid rgba(44, 62, 80, 0.2);
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
        margin: 1rem 0;
    }
    /* Input fields */
    .stTextInput input, .stNumberInput input, 
    .stSelectbox select, .stTextArea textarea {
        border: 2px solid #00FFFF !important;
        border-radius: 10px !important;
        padding: 1rem !important;
        background: #00FFFF !important;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        color: var(--dark) !important;
    }
    .stTextInput input:focus, .stNumberInput input:focus, 
    .stSelectbox select:focus, .stTextArea textarea:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 12px rgba(52, 152, 219, 0.2) !important;
        background: white !important;
        color: var(--dark) !important;
    }
    /* Buttons styling */
    .stButton>button {
        background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%) !important;
        color: var(--dark) !important;
        border: none !important;
        border-radius: 10px !important;
        padding: 1rem 2rem !important;
        font-size: 1rem !important;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    .stButton>button:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 15px rgba(52, 152, 219, 0.3);
        opacity: 0.95;
    }
    .stButton>button:active {
        transform: translateY(0);
        opacity: 1;
    }
    /* Progress indicator */
    .progress-bar {
        display: flex;
        justify-content: space-between;
        margin: 2rem 0;
        padding: 1rem;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 10px;
        color: var(--dark) !important;
    }
    .step {
        flex: 1;
        text-align: center;
        padding: 1rem;
        font-weight: 600;
        color: #95a5a6;
        position: relative;
    }
    .step.active {
        color: var(--primary);
    }
    .step.active:after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 50%;
        transform: translateX(-50%);
        width: 40%;
        height: 3px;
        background: var(--primary);
    }
    /* Chat bubbles */
    .dr-message {
        background: linear-gradient(135deg, var(--primary) 0%, #2980b9 100%);
        color: white;
        border-radius: 20px 20px 20px 4px;
        padding: 1.2rem 1.5rem;
        margin: 1rem 0;
        max-width: 80%;
        width: fit-content;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }
    .user-message {
        background: linear-gradient(135deg, #f1c40f 0%, #e1b800 100%);
        margin-left: auto;
        border-radius: 20px 20px 4px 20px;
        color: var(--dark) !important;
    }
    /* Emergency alert */
    .emergency-alert {
        background: linear-gradient(135deg, var(--accent) 0%, #c0392b 100%);
        color: white;
        padding: 2rem;
        border-radius: 15px;
        animation: pulse 1.5s infinite;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.02); }
        100% { transform: scale(1); }
    }
    /* Download button */
    .download-btn {
        background: linear-gradient(135deg, var(--success) 0%, #27ae60 100%) !important;
    }
    /* Enhanced Data Visualization Contrast */
    .stDataFrame {
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: 12px;
        overflow: hidden;
        background: #f0f0f0;
        color: var(--dark) !important;
    }
    /* Tabbed Interface Styling */
    .stTabs [role="tablist"] {
        gap: 10px;
        padding: 8px;
        background: rgba(240, 240, 240, 0.9);
        border-radius: 12px;
        color: var(--dark) !important;
    }
    .stTabs [role="tab"] {
        background: #ffffff !important;
        border-radius: 8px !important;
        transition: all 0.3s ease;
        color: var(--dark) !important;
    }
    .stTabs [role="tab"][aria-selected="true"] {
        background: var(--primary) !important;
        color: white !important;
        transform: scale(1.05);
    }
    </style>
""", unsafe_allow_html=True)


# Initialize session state variables
if 'current_step' not in st.session_state:
    st.session_state.current_step = 0
if 'symptom_details' not in st.session_state:
    st.session_state.symptom_details = []  # Initialize as an empty list
if 'patient_info' not in st.session_state:
    st.session_state.patient_info = {}

def initialize_groq_client():
    try:
        # Try to get the API key from Streamlit secrets
        api_key = None
        try:
            api_key = st.secrets.get("GROQ_API_KEY", os.getenv("GROQ_API_KEY"))
        except FileNotFoundError:
            st.warning("No `secrets.toml` file found. Please create one in the `.streamlit` folder.")
        
        # If not found, prompt the user to enter it
        if not api_key:
            api_key = st.text_input("Enter your Groq API Key:", type="password")
            if not api_key:
                st.warning("Please provide a valid Groq API key to proceed.")
                return False
        
        # Initialize the Groq client
        client = Groq(api_key=api_key)
        st.session_state.client = client
        return True
    except Exception as e:
        st.error(f"Error initializing Groq client: {str(e)}")
        return False

def symptom_interrogation_step():
    client = st.session_state.client
    main_symptom = st.session_state.patient_info['main_symptom']
    step = len(st.session_state.symptom_details)  # Use the number of collected details as the step

    if step == 0:
        # First question: ask about the main symptom
        medical_focus = {
            'pain': "location/radiation/provoking factors",
            'fever': "pattern/associated symptoms/response to meds",
            'gi': "bowel changes/ingestion timing/associated symptoms",
            'respiratory': "exertion relationship/sputum/triggers"
        }
        focus = medical_focus.get(main_symptom.lower(), 
                "temporal pattern/severity progression/associated symptoms")

        prompt = f"""As an ER physician, ask ONE high-yield question about {main_symptom}
        focusing on {focus} to differentiate serious causes. Your task is to have a polite and simple conversation with a patient. 
        Start by asking ONE specific follow-up question about their initial symptom: {main_symptom}.
        Ask only one question at a time to avoid overwhelming the patient.
        Keep your language clear, professional, and easy to understand. 
        
        Dont display possibe symptoms or why you are asking questions."""
        
        messages = [
            {"role": "system", "content": "Ask focused clinical questions. One at a time."},
            {"role": "user", "content": prompt}
        ]
    else:
        # Subsequent questions: use the last Q&A to generate the next question
        last_qa = st.session_state.symptom_details[-1]
        prompt = f"""Last Q&A: {last_qa['question']} β†’ {last_qa['answer']}
        Based on this, ask the NEXT most critical question to differentiate between
        possible causes of {main_symptom}. Consider red flags and likelihood."""
        messages = [{"role": "user", "content": prompt}]

    try:
        response = client.chat.completions.create(
            messages=messages,
            model="mixtral-8x7b-32768",
            temperature=0.3
        )
        question = response.choices[0].message.content.strip()
        if not question.endswith('?'):
            question += '?'
        st.session_state.current_question = question
    except Exception as e:
        st.error(f"Error generating question: {str(e)}")
        st.stop()

def handle_symptom_interrogation():
    st.header("Symptom Analysis")
    
    if st.session_state.current_step == 1:
        symptom_interrogation_step()
        st.session_state.current_step = 2
    
    if 'current_question' in st.session_state:
        with st.form("symptom_qna"):
            st.markdown(f'<div class="dr-message">πŸ‘¨β€βš•οΈ {st.session_state.current_question}</div>', unsafe_allow_html=True)
            answer = st.text_input("Your answer:", key=f"answer_{len(st.session_state.symptom_details)}")
            
            if st.form_submit_button("Next"):
                if answer:
                    st.session_state.symptom_details.append({
                        "question": st.session_state.current_question,
                        "answer": answer
                    })
                    del st.session_state.current_question
                    
                    # Check for emergency after 3 questions
                    if len(st.session_state.symptom_details) >= 3:
                        last_answer = st.session_state.symptom_details[-1]['answer']
                        try:
                            urgency_check = st.session_state.client.chat.completions.create(
                                messages=[{"role": "user", "content": 
                                        f"Does '{last_answer}' indicate immediate emergency? Yes/No"}],
                                model="mixtral-8x7b-32768",
                                temperature=0
                            ).choices[0].message.content
                            
                            if 'YES' in urgency_check.upper():
                                st.markdown('<div class="emergency-alert">🚨 Emergency detected! Please seek immediate medical attention.</div>', unsafe_allow_html=True)
                                st.session_state.current_step = 4
                                return
                        except Exception as e:
                            st.error(f"Error checking urgency: {str(e)}")
                    
                    if len(st.session_state.symptom_details) < 7:
                        st.session_state.current_step = 1
                        st.rerun()
                    else:
                        st.session_state.current_step = 3
                        st.rerun()
                else:
                    st.warning("Please provide an answer")

def collect_basic_info():
    st.header("Patient Information")
    with st.form("basic_info"):
        st.session_state.patient_info['name'] = st.text_input("Full Name")
        st.session_state.patient_info['age'] = st.number_input("Age", min_value=0, max_value=120)
        st.session_state.patient_info['gender'] = st.selectbox("Gender", ["Male", "Female", "Other"])
        st.session_state.patient_info['main_symptom'] = st.text_input("Main Symptom")
        
        if st.form_submit_button("Next"):
            if all([st.session_state.patient_info.get(k) for k in ['name', 'age', 'gender', 'main_symptom']]):
                st.session_state.current_step = 1
                st.rerun()
            else:
                st.warning("Please fill all required fields")

def collect_medical_history():
    st.header("Medical History")
    with st.form("medical_history"):
        st.session_state.patient_info['medical_history'] = st.text_area("Relevant Medical History")
        st.session_state.patient_info['medications'] = st.text_area("Current Medications")
        st.session_state.patient_info['allergies'] = st.text_input("Known Allergies")
        st.session_state.patient_info['last_meal'] = st.text_input("Last Meal Time")
        st.session_state.patient_info['recent_travel'] = st.text_input("Recent Travel History")
        
        if st.form_submit_button("Submit"):
            st.session_state.current_step = 4
            st.rerun()

def generate_risk_assessment():
    st.header("Risk Assessment")
    
    try:
        symptom_log = "\n".join(
            [f"Q: {q['question']}\nA: {q['answer']}"
            for q in st.session_state.symptom_details]
        )

        patient_profile = f"""
**Patient Profile**
Name: {st.session_state.patient_info['name']}
Age: {st.session_state.patient_info['age']}
Gender: {st.session_state.patient_info['gender']}

**Primary Complaint**
{st.session_state.patient_info['main_symptom']}

**Symptom Interrogation**
{symptom_log}

**Medical History**
{st.session_state.patient_info.get('medical_history', 'None reported')}

**Current Medications**
{st.session_state.patient_info.get('medications', 'None')}

**Allergies**
{st.session_state.patient_info.get('allergies', 'None reported')}

**Recent Context**
Last Meal: {st.session_state.patient_info.get('last_meal', 'Unknown')}
Recent Travel: {st.session_state.patient_info.get('recent_travel', 'None')}
        """

        analysis_prompt = f"""STRICTLY follow these instructions:
1. Analyze this case: {patient_profile}
2. *Include ONLY symptoms the patient is actively experiencing*. Exclude all negated symptoms (e.g., "no fever," "denies breathlessness").
3. Output *EXCLUSIVELY* in this format with NO additional text or explanations:
[Age]-year-old [gender] with [specific, present symptoms].
Example Output:
"45-year-old man with severe chest pain radiating to the jaw"
Your Output:"""


        response = st.session_state.client.chat.completions.create(
            messages=[
                {"role": "system", "content": "You are a medical AI that outputs ONLY patient descriptions."},
                {"role": "user", "content": analysis_prompt}
            ],
            model="mixtral-8x7b-32768",
            temperature=0.3,
            max_tokens=100
        )

        risk_prompt = response.choices[0].message.content.strip('"')
        
        st.subheader("Clinical Summary")
        st.markdown(f"```\n{risk_prompt}\n```")
        
        # Create download button
        timestamp = datetime.now().strftime('%Y%m%d%H%M')
        filename = f"{st.session_state.patient_info['name'].replace(' ', '_')}_assessment_{timestamp}.txt"
        st.download_button(
            label="Download Assessment",
            data=risk_prompt,
            file_name=filename,
            mime="text/plain"
        )
        
    except Exception as e:
        st.error(f"Error generating risk assessment: {str(e)}")

def main():
    st.title("πŸ₯ AI Medical Consultancy")
    
    # Progress indicator
    steps_titles = ["Patient Info", "Symptoms", "Medical History", "Assessment"]
    progress_html = """
    <div class="progress-bar">
        <div class="step {}">{}</div>
        <div class="step {}">{}</div>
        <div class="step {}">{}</div>
        <div class="step {}">{}</div>
    </div>
    """.format(
        'active' if st.session_state.current_step >= 0 else '',
        '1. Patient Info',
        'active' if st.session_state.current_step >= 1 else '',
        '2. Symptoms',
        'active' if st.session_state.current_step >= 3 else '',
        '3. History',
        'active' if st.session_state.current_step >= 4 else '',
        '4. Report'
    )
    st.markdown(progress_html, unsafe_allow_html=True)
    
    if not initialize_groq_client():
        return
    
    steps = {
        0: collect_basic_info,
        1: handle_symptom_interrogation,
        2: handle_symptom_interrogation,
        3: collect_medical_history,
        4: generate_risk_assessment
    }
    
    current_step = st.session_state.get('current_step', 0)
    if current_step in steps:
        steps[current_step]()

if __name__ == "__main__":
    main()