File size: 7,523 Bytes
0d6cae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18c4235
0d6cae6
 
 
 
 
18c4235
0d6cae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from mistralai import Mistral
import gradio as gr
import os
from datetime import datetime
api_key = os.environ["MISTRAL_API_KEY"]
model = "mistral-large-latest"
client = Mistral(api_key=api_key)
def interaction_check(prompt):
    """
    Check for drug interactions and provide pharmacist guidance
    """
    try:
        # Input validation
        if not prompt or prompt.strip() == "":
            return "⚠️ Please enter your medications or questions about drug interactions."

        if len(prompt.strip()) < 5:
            return "⚠️ Please provide more details about your medications for a proper assessment."

        # Enhanced system prompt with better instructions
        system_prompt = f"""You are a knowledgeable pharmacist assistant specializing in drug interaction detection and medication safety.

Your responsibilities:
1. Analyze potential drug interactions from the user's medication list
2. Identify contraindications and warnings
3. Provide clear, actionable advice
4. Always recommend consulting with a licensed pharmacist or healthcare provider
5. Use appropriate medical terminology while remaining accessible
6. Structure your response clearly with sections if multiple interactions are found

Important guidelines:
- Always emphasize that this is preliminary guidance only
- Recommend professional consultation for all medication concerns
- Be specific about interaction severity (minor, moderate, major)
- Include timing recommendations when relevant
- Mention food interactions if applicable
- Note any special monitoring requirements

Format your response with clear sections and use emojis for visual clarity where appropriate."""

        chat_response = client.chat.complete(
            model=model,
            messages=[
                {
                    "role": "system",
                    "content": system_prompt
                },
                {
                    "role": "user",
                    "content": f"Please analyze the following for drug interactions: {prompt}",
                },
            ],
            temperature=0.1,  # Lower temperature for more consistent medical advice
            max_tokens=1000   # Ensure comprehensive responses
        )

        response = chat_response.choices[0].message.content

        # Add disclaimer footer
        disclaimer = "\n\n---\n⚠️ **IMPORTANT DISCLAIMER**: This information is for educational purposes only and should not replace professional medical advice. Always consult with a licensed pharmacist or healthcare provider before making any changes to your medications."

        return response + disclaimer

    except Exception as e:
        error_msg = f"❌ **Error occurred**: {str(e)}\n\nPlease try again or contact support if the issue persists."
        return error_msg

def clear_inputs():
    """Clear the input field"""
    return ""

def get_example_interactions():
    """Return example drug interaction queries"""
    examples = [
        "I'm taking warfarin and my doctor prescribed ibuprofen for pain. Are there any interactions?",
        "Can I take omeprazole with clopidogrel? I have both prescribed.",
        "I'm on metformin for diabetes and want to know if it's safe with alcohol",
        "Taking lisinopril and potassium supplements - any concerns?",
        "I have simvastatin and clarithromycin prescribed together"
    ]
    return examples

# Custom CSS for better styling
custom_css = """
#warning {
    background-color: #667eea;
    border: 1px solid #ffeaa7;
    border-radius: 8px;
    padding: 16px;
    margin: 10px 0;
}

#main-container {
    max-width: 900px;
    margin: 0 auto;
}

.gradio-container {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

#submit-btn {
    background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    font-weight: bold;
}

#clear-btn {
    background-color: #6c757d;
    border: none;
    color: white;
}
"""

# Create the Gradio interface
with gr.Blocks(css=custom_css, title="πŸ’Š PharmaSafe - Drug Interaction Checker") as demo:

    with gr.Column(elem_id="main-container"):
        # Header
        gr.Markdown(
            """
            # πŸ’Š πŸ’Š PharmaSafe - Drug Interaction Checker

            Get preliminary guidance on potential drug interactions and medication safety concerns.
            This tool helps identify possible interactions between medications.
            """,
            elem_id="header"
        )

        # Warning notice
        gr.Markdown(
            """
            ⚠️ **MEDICAL DISCLAIMER**: This tool provides educational information only.
            Always consult with a licensed pharmacist, doctor, or healthcare provider
            before making any decisions about your medications.
            """,
            elem_id="warning"
        )

        with gr.Row():
            with gr.Column(scale=2):
                # Input section
                gr.Markdown("### Enter Your Medications or Questions")

                medication_input = gr.Textbox(
                    label="Medications & Questions",
                    placeholder="Example: I'm taking warfarin and ibuprofen. Are there any interactions I should know about?",
                    lines=4,
                    max_lines=8
                )

                with gr.Row():
                    submit_btn = gr.Button("πŸ” Check Interactions", variant="primary", elem_id="submit-btn")
                    clear_btn = gr.Button("πŸ—‘οΈ Clear", elem_id="clear-btn")

            with gr.Column(scale=1):
                # Examples section
                gr.Markdown("### Example Questions")
                example_queries = get_example_interactions()
                for i, example in enumerate(example_queries[:3]):  # Show first 3 examples
                    gr.Markdown(f"**Example {i+1}:** {example}")

        # Output section
        gr.Markdown("### πŸ“‹ Analysis Results")
        output_display = gr.Markdown(
            value="Enter your medications above and click 'Check Interactions' to get started.",
            elem_id="output"
        )

        # Usage tips
        with gr.Accordion("πŸ’‘ Usage Tips", open=False):
            gr.Markdown(
                """
                **For best results:**
                - List all medications you're taking (prescription and over-the-counter)
                - Include dosages if known
                - Mention any supplements or herbal products
                - Be specific about your concerns
                - Include timing of when you take each medication

                **This tool can help with:**
                - Drug-drug interactions
                - Food-drug interactions
                - Timing recommendations
                - General medication safety concerns

                **Remember:** Always verify with a healthcare professional!
                """
            )

        # Event handlers
        submit_btn.click(
            fn=interaction_check,
            inputs=medication_input,
            outputs=output_display
        )

        clear_btn.click(
            fn=clear_inputs,
            outputs=medication_input
        )

        medication_input.submit(
            fn=interaction_check,
            inputs=medication_input,
            outputs=output_display
        )

# Add footer with timestamp
footer_text = f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"

if __name__ == "__main__":
    demo.launch()