File size: 11,155 Bytes
e8bdfe6
6f430b3
61045d7
3deccb7
 
61045d7
3deccb7
c446db8
e3e1abb
6f430b3
1328074
 
3deccb7
 
c446db8
 
1328074
6f430b3
3deccb7
c446db8
6f430b3
 
914056e
3deccb7
c446db8
1328074
 
c5417b4
61045d7
 
1328074
 
 
53622e4
e539c73
1328074
e539c73
 
3deccb7
c446db8
1328074
 
c5417b4
b2ae4e5
 
 
 
 
e539c73
b2ae4e5
 
edb1f8d
1328074
6f430b3
 
c5417b4
b2ae4e5
1328074
 
 
b2ae4e5
 
 
 
 
1328074
 
b2ae4e5
 
 
 
 
1328074
6f430b3
89fbd3f
1328074
b2ae4e5
 
 
 
89fbd3f
b2ae4e5
 
 
 
 
e539c73
b2ae4e5
 
 
 
 
e539c73
1328074
b2ae4e5
1328074
 
6f430b3
b2ae4e5
 
 
 
6f430b3
 
 
 
 
c446db8
6f430b3
 
 
 
 
 
 
 
 
 
 
 
 
 
2108566
6f430b3
2108566
6f430b3
 
 
 
 
1328074
6f430b3
b2ae4e5
6f430b3
 
 
1328074
c446db8
6f430b3
1328074
6f430b3
 
 
 
1328074
6f430b3
 
 
 
 
 
 
 
 
 
 
3deccb7
c446db8
3deccb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5417b4
3deccb7
 
 
 
 
7529265
3deccb7
c446db8
3deccb7
c446db8
3deccb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c446db8
3deccb7
c446db8
3deccb7
 
c446db8
3deccb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c446db8
a50b28b
 
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
import gradio as gr
import requests
import os
from datetime import date
import pandas as pd

# ---------------------- API Config ----------------------

API_KEY = os.getenv("AIML_API_KEY") or "your_aimlapi_key_here"
API_URL = "https://api.aimlapi.com/v1/chat/completions"
SYSTEM_PROMPT = (
    "You are a highly knowledgeable and friendly veterinary assistant AI. "
    "Provide clear, thorough, and helpful responses to users about pets (dogs and cats). "
    "Responses should be detailed, covering causes, symptoms, treatments, nutrition, precautions, "
    "recovery time, and practical advice. Use friendly, empathetic language and encourage consulting a vet for serious concerns. "
    "Avoid using markdown or special characters like asterisks. Use plain text and label sections clearly with headings such as 'Causes:', 'Symptoms:', etc."
)

# ---------------------- AI State ----------------------

chat_history = []
followup_count = 0

# ---------------------- Dropdowns ----------------------

breed_options = {
    "Cat": ["Persian", "Siamese", "Maine Coon", "British Shorthair", "Other"],
    "Dog": ["German Shepherd", "Labrador", "Bulldog", "Pomeranian", "Other"]
}

symptom_list = [
    "Vomiting", "Diarrhea", "Loss of Appetite", "Coughing", "Scratching", "Hair Loss", "Lethargy", "Other"
]

breed_info_topics = [
    "Favourite Food", "Most Common Diseases", "Precautions", "Allergies", "Favourite Activities", "Other"
]

# ---------------------- Helper Functions ----------------------

def update_breed(pet_type):
    return gr.update(choices=breed_options.get(pet_type, []), value=None, visible=True), gr.update(visible=False, value="")

def handle_breed_other(breed_choice):
    return gr.update(visible=(breed_choice == "Other"), value="")

def handle_symptom_other(symptom):
    return gr.update(visible=(symptom == "Other"), value="")

def handle_info_other(info):
    return gr.update(visible=(info == "Other"), value="")

def ask_ai(pet, breed, other_breed, age, gender, weight, topic, symptom, other_symptom, condition, info_topic, other_info, user_detail):
    global chat_history, followup_count
    followup_count = 0

    pet = pet.strip()
    final_breed = other_breed.strip() if breed == "Other" else breed
    final_symptom = other_symptom.strip() if symptom == "Other" else symptom
    final_info = other_info.strip() if info_topic == "Other" else info_topic
    age = age.strip()
    gender = gender.strip()
    weight = weight.strip()
    condition = condition.strip()
    user_detail = user_detail.strip()[:100]

    prompt_parts = [
        f"Pet: {pet}",
        f"Breed: {final_breed}",
        f"Age: {age}",
        f"Gender: {gender}",
        f"Weight: {weight}"
    ]

    if topic == "Symptom Checker":
        prompt_parts.append(f"Symptom: {final_symptom}")
        prompt_parts.append(
            "Please provide a detailed explanation including: typical causes, when and how this symptom usually appears, "
            "recommended treatments and home care, expected recovery timeline, preventive measures, and when to seek a vet."
        )
    elif topic == "Nutrition":
        prompt_parts.append(f"Condition: {condition if condition else 'None'}")
        prompt_parts.append(
            "Provide a comprehensive nutrition guide for this breed/condition: best foods available locally (Pakistan), benefits of each food, "
            "recommended feeding quantity and frequency, and tips for maintaining optimal health."
        )
    elif topic == "Breed Info":
        prompt_parts.append(f"Information Requested: {final_info}")
        prompt_parts.append(
            "Give detailed and interesting information on the selected topic related to the breed, covering key facts, practical tips, "
            "common concerns, and any special advice."
        )

    if user_detail:
        prompt_parts.append(f"User Detail: {user_detail}")

    user_prompt = "\n".join(prompt_parts)

    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": user_prompt}
    ]

    payload = {
        "model": "gpt-4o-mini-2024-07-18",
        "messages": messages,
        "temperature": 0.7,
        "max_tokens": 1200  # Increased token limit
    }

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

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        result = response.json()
        answer = result['choices'][0]['message']['content'].strip()
        chat_history.clear()
        chat_history.extend(messages + [{"role": "assistant", "content": answer}])
        return answer
    except Exception as e:
        return f"❌ Error: {str(e)}"

def handle_followup(user_input):
    global chat_history, followup_count
    if followup_count >= 5:
        return "⚠️ Max of 5 follow-up questions reached."

    chat_history.append({"role": "user", "content": user_input})

    payload = {
        "model": "gpt-4o-mini-2024-07-18",
        "messages": chat_history,
        "temperature": 0.6,
        "max_tokens": 600
    }

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

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        result = response.json()
        reply = result['choices'][0]['message']['content'].strip()
        chat_history.append({"role": "assistant", "content": reply})
        followup_count += 1
        return reply
    except Exception as e:
        return f"❌ Error: {str(e)}"

# ---------------------- Vaccination Tracker ----------------------

vaccination_records = []

def save_vaccination_record(pet_type, breed, pet_name, age, last_date, total_doses, upcoming_date, vaccine_type, notes):
    record = {
        "Pet Type": pet_type,
        "Breed": breed,
        "Pet Name": pet_name,
        "Age": age,
        "Last Vaccination Date": last_date,
        "Total Doses": total_doses,
        "Upcoming Dose Date": upcoming_date,
        "Vaccine Type": vaccine_type,
        "Notes": notes
    }
    vaccination_records.append(record)
    return f"βœ… Record saved for {pet_name} ({breed})"

def view_all_vaccination_records():
    if not vaccination_records:
        return "πŸ“­ No records saved yet."
    df = pd.DataFrame(vaccination_records)
    return df

# ---------------------- UI ----------------------

with gr.Blocks() as demo:
    gr.Markdown("# 🐾 Smart Paws: AI Assistant + Vaccination Tracker")

    with gr.Tabs():
        # --- Tab 1: AI Assistant ---
        with gr.TabItem("🧠 Smart Paws AI Assistant"):
            with gr.Row():
                pet = gr.Dropdown(["Cat", "Dog"], label="πŸ• Pet Type")
                breed = gr.Dropdown(label="🐾 Select Breed", visible=False)
                other_breed = gr.Textbox(label="✍️ Enter Breed", visible=False)
            pet.change(update_breed, pet, [breed, other_breed])
            breed.change(handle_breed_other, breed, other_breed)

            with gr.Row():
                age = gr.Textbox(label="πŸŽ‚ Age (e.g. 2 years or 8 months)")
                gender = gr.Dropdown(["Male", "Female", "Unknown"], label="🚻 Gender")
                weight = gr.Textbox(label="βš–οΈ Weight (e.g. 10 kg)")

            topic = gr.Dropdown(["Symptom Checker", "Nutrition", "Breed Info"], label="πŸ“š Select Topic")

            with gr.Column(visible=False) as symptom_section:
                symptom = gr.Dropdown(symptom_list, label="πŸ€’ Select Symptom")
                other_symptom = gr.Textbox(label="✍️ Enter Symptom", visible=False)
                symptom.change(handle_symptom_other, symptom, other_symptom)

            with gr.Column(visible=False) as nutrition_section:
                condition = gr.Textbox(label="🩺 Condition (Optional, e.g. slim, weak)")

            with gr.Column(visible=False) as breed_info_section:
                info_topic = gr.Dropdown(breed_info_topics, label="ℹ️ Select Info Type")
                other_info = gr.Textbox(label="✍️ Enter Info Topic", visible=False)
                info_topic.change(handle_info_other, info_topic, other_info)

            user_detail = gr.Textbox(label="πŸ“ Extra Detail (optional, max 100 chars)", max_lines=2)

            def show_topic_fields(selected_topic):
                return [
                    gr.update(visible=(selected_topic == "Symptom Checker")),
                    gr.update(visible=(selected_topic == "Nutrition")),
                    gr.update(visible=(selected_topic == "Breed Info"))
                ]

            topic.change(show_topic_fields, topic, [symptom_section, nutrition_section, breed_info_section])

            submit_btn = gr.Button("Get Advice")
            output = gr.Textbox(label="πŸ’¬ AI Response", lines=20)

            gr.Markdown("## πŸ”„ Ask Follow-up")
            followup_input = gr.Textbox(label="πŸ—£οΈ Follow-up Question")
            followup_btn = gr.Button("Ask Follow-up")
            followup_output = gr.Textbox(label="πŸ’‘ Follow-up Response", lines=8)

            submit_btn.click(
                ask_ai,
                inputs=[pet, breed, other_breed, age, gender, weight, topic, symptom, other_symptom, condition, info_topic, other_info, user_detail],
                outputs=output
            )

            followup_btn.click(handle_followup, inputs=followup_input, outputs=followup_output)

        # --- Tab 2: Vaccination Records ---
        with gr.TabItem("πŸ’‰ Pet Vaccination Records"):
            gr.Markdown("### πŸ’‰ Enter Vaccination Details")

            with gr.Row():
                v_pet_type = gr.Dropdown(["Dog", "Cat"], label="Pet Type")
                v_breed = gr.Textbox(label="Breed")
                v_pet_name = gr.Textbox(label="Pet Name")
                v_age = gr.Textbox(label="Age")

            with gr.Row():
                v_last_vaccination = gr.Textbox(label="Last Vaccination Date (YYYY-MM-DD)")
                v_total_doses = gr.Number(label="Total Doses Taken")
                v_upcoming_dose = gr.Textbox(label="Upcoming Dose Date (YYYY-MM-DD)")

            v_vaccine_type = gr.Dropdown(["Rabies", "DHPP", "FVRCP", "Bordetella", "Leptospirosis", "Other"], label="Vaccine Type")
            v_notes = gr.Textbox(label="Additional Notes", lines=3)

            save_btn = gr.Button("Save Record")
            save_output = gr.Textbox(label="πŸ“‹ Status")

            view_btn = gr.Button("πŸ“‘ View All Records")
            table_output = gr.Dataframe(label="πŸ“Š Saved Records", visible=True)

            save_btn.click(
                save_vaccination_record,
                inputs=[v_pet_type, v_breed, v_pet_name, v_age, v_last_vaccination, v_total_doses, v_upcoming_dose, v_vaccine_type, v_notes],
                outputs=save_output
            )

            view_btn.click(view_all_vaccination_records, inputs=[], outputs=table_output)

# ---------------------- Run App ----------------------

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