File size: 6,768 Bytes
0932864
f138602
 
 
 
 
4d2cf9c
 
f138602
 
6ec20b3
 
 
f138602
 
4d2cf9c
04628ac
5990792
4d2cf9c
8948fa6
f138602
 
 
 
789dfab
f138602
 
 
4d2cf9c
f138602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d2cf9c
 
f138602
 
 
4d2cf9c
f138602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8948fa6
f138602
6ec20b3
6be5397
 
6ec20b3
36e9979
7908208
 
6ec20b3
 
 
 
7908208
6ec20b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7908208
 
 
 
 
 
 
 
 
 
6ec20b3
7908208
 
 
 
6ec20b3
7908208
 
6ec20b3
 
7908208
 
6ec20b3
f138602
 
 
6ec20b3
69595bd
6ec20b3
4d2cf9c
f138602
 
 
4d2cf9c
f138602
 
 
 
 
4d2cf9c
6ec20b3
 
f138602
 
 
 
6ec20b3
 
f138602
 
 
 
 
6ec20b3
f138602
7908208
f138602
4d2cf9c
f138602
 
6ec20b3
 
f138602
4d2cf9c
f138602
6ec20b3
 
f138602
 
 
 
7908208
 
f138602
 
4d2cf9c
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
import gradio as gr
import requests
import os
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from transformers import pipeline
import torch

# === Groq API Setup ===
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY environment variable is not set.")
GROQ_MODEL = "llama3-8b-8192"

# === Medical Classifier ===
# Removed classifier usage, so no filtering/warnings.

def doctor_twin_light(prompt, category):
    # Removed the medical classifier check here

    system_prompt = (
        "You are Doctor Twin, a virtual AI health assistant. "
        "You provide friendly, general health and wellness advice. "
        "Also check if question is not medical related, do give warning that it is not relevant to medical."
        "You never diagnose or prescribe. Always include a disclaimer to consult a real doctor."
    )

    user_prompt = f"Category: {category}\nPatient: {prompt}\nAdvice:"

    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json"
    }

    data = {
        "model": GROQ_MODEL,
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}
        ],
        "temperature": 0.7,
        "max_tokens": 256
    }

    try:
        response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
        response.raise_for_status()
        reply = response.json()["choices"][0]["message"]["content"]
        return f"{reply}\n\n⚠️ Disclaimer: AI-generated advice. Always consult a licensed doctor."
    except Exception as e:
        return f"❌ Error: {str(e)}"

# === OTC Prescription Generator ===
def generate_otc_prescription(name, symptoms):
    date = datetime.now().strftime('%Y-%m-%d')
    content = f"""πŸ“„ Prescription Note
Patient: {name}
Date: {date}
Symptoms: {symptoms}
Suggested OTC Medicine: Cetirizine 10mg (once at night)
Instructions: Take after food. Stay hydrated.
Caution: This is an AI-generated suggestion. Please consult a licensed doctor if symptoms persist."""

    filename = f"prescription_{datetime.now().strftime('%Y%m%d%H%M%S')}.pdf"
    filepath = os.path.join("prescriptions", filename)
    os.makedirs("prescriptions", exist_ok=True)

    c = canvas.Canvas(filepath, pagesize=letter)
    textobject = c.beginText(50, 750)
    textobject.setFont("Helvetica", 12)
    for line in content.splitlines():
        textobject.textLine(line)
    c.drawText(textobject)
    c.save()

    return content, filepath

# === Gradio UI with updated background color and styling ===
with gr.Blocks(css="""
body {
    background: #2A7B9B;
    background: linear-gradient(90deg,rgba(42, 123, 155, 1) 0%, rgba(87, 199, 133, 1) 50%, rgba(237, 221, 83, 1) 100%);
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: #f0f0f0;
    margin: 0;
    min-height: 100vh;
}
.gr-box {
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    padding: 1rem 1.5rem;
    margin-bottom: 1rem;
}
.gr-button {
    border-radius: 10px;
    font-weight: 600;
    background-color: #0d6efd;
    color: white;
    transition: background-color 0.3s ease;
}
.gr-button:hover {
    background-color: #084298 !important;
    color: #fff !important;
}
h1, h2, h3, label, .gr-tab-label {
    color: #212529 !important;
    font-weight: 700;
}
/* Tabs title */
.gr-tabs .gr-tab-label {
    color: #0d6efd !important;
    font-weight: 700 !important;
    background-color: #e7f1ff !important;
    border-radius: 8px 8px 0 0 !important;
    padding: 10px 16px !important;
    margin-right: 4px !important;
    user-select: none;
    cursor: pointer;
}
.gr-tabs .gr-tab-label[aria-selected="true"] {
    background-color: #0d6efd !important;
    color: white !important;
    box-shadow: 0 4px 6px rgba(13, 110, 253, 0.4);
}
/* Input elements */
.gr-textbox, .gr-dropdown, .gr-file {
    border: 1.5px solid #ced4da;
    border-radius: 8px;
    padding: 0.5rem;
    font-size: 1rem;
}
""") as demo:

    gr.Markdown("""
    <div style="text-align: center; margin-bottom: 20px;">
        <h1>🩺 Doctor TWIN – Your Virtual Healthcare Companion</h1>
        <p>A lightweight AI assistant for quick medical Q&A and OTC prescription generation</p>
    </div>
    """)

    with gr.Tabs():
        with gr.TabItem("πŸ’¬ Doctor Twin Advice"):
            with gr.Row():
                with gr.Column(scale=1, min_width=300):
                    gr.Markdown("### πŸ‘€ Enter Your Query", elem_classes=["gr-box"])
                    user_input = gr.Textbox(
                        lines=4,
                        label="Describe your symptom or question",
                        placeholder="e.g., I have a mild fever and fatigue",
                        elem_classes=["gr-textbox"]
                    )
                    category = gr.Dropdown(
                        label="Symptom Category",
                        choices=["General", "Skin", "Mental Health", "Respiratory", "Digestive"],
                        value="General",
                        elem_classes=["gr-dropdown"]
                    )
                    submit = gr.Button("Get Advice", elem_classes=["gr-button"])

                with gr.Column(scale=2):
                    gr.Markdown("### πŸ€– Doctor Twin Says", elem_classes=["gr-box"])
                    output = gr.Textbox(label="AI Response", lines=8, interactive=False, show_copy_button=True, elem_classes=["gr-textbox"])

            submit.click(fn=doctor_twin_light, inputs=[user_input, category], outputs=output, show_progress=True)

        with gr.TabItem("πŸ“„ OTC Prescription"):
            with gr.Row():
                with gr.Column(scale=1):
                    patient_name = gr.Textbox(label="Patient Name", placeholder="e.g., John Doe", elem_classes=["gr-textbox"])
                    symptoms_input = gr.Textbox(label="Symptoms", placeholder="e.g., cough, runny nose", elem_classes=["gr-textbox"])
                    gen_button = gr.Button("Generate Prescription", elem_classes=["gr-button"])

                with gr.Column(scale=2):
                    prescription_output = gr.Textbox(label="Generated Prescription", lines=10, interactive=False, show_copy_button=True, elem_classes=["gr-textbox"])
                    pdf_file = gr.File(label="Download Prescription PDF", elem_classes=["gr-file"])

            gen_button.click(
                fn=generate_otc_prescription,
                inputs=[patient_name, symptoms_input],
                outputs=[prescription_output, pdf_file],
                show_progress=True
            )

demo.launch()