XMMR12 commited on
Commit
9ceda7c
·
verified ·
1 Parent(s): d20ee49
Files changed (2) hide show
  1. README.md +3 -0
  2. app.py +582 -580
README.md CHANGED
@@ -12,7 +12,10 @@ short_description: Agent that helps you with natural treatment
12
  tags:
13
  - agents
14
  - web-search
 
15
  - medical
 
 
16
  ---
17
  # 🌿 HyBio Agent - Natural Treatment Assistant
18
 
 
12
  tags:
13
  - agents
14
  - web-search
15
+ - plants
16
  - medical
17
+ thumbnail: >-
18
+ https://huggingface.co/spaces/XMMR12/HyBio-Agent/resolve/main/thumbnail.png
19
  ---
20
  # 🌿 HyBio Agent - Natural Treatment Assistant
21
 
app.py CHANGED
@@ -1,581 +1,583 @@
1
- from typing import List, Tuple, Dict, Any, Generator
2
- import sqlite3
3
- import urllib
4
- import requests
5
- import os
6
- import gradio as gr
7
- from smolagents import tool
8
- import time
9
-
10
- #specialtoken=os.getenv("SPECIALTOKEN")+"deepseek-r1-0528"
11
- specialtoken=os.getenv("SPECIALTOKEN")+"openai"#"openai-large"#"openai-roblox"
12
- fasttoken=os.getenv("SPECIALTOKEN")+"models/"+"openai-fast"
13
-
14
- #unused for getting all symptoms from plants db
15
- def get_all_treatable_conditions()->List:
16
- #Gets all the symptoms:
17
- conn = sqlite3.connect('plants.db')
18
- # Create a cursor object
19
- cursor = conn.cursor()
20
- # Execute a query to retrieve data
21
- cursor.execute("SELECT treatable_conditions FROM 'plants'")
22
- # Fetch all results
23
- rows = cursor.fetchall()
24
- # Print the results
25
- treatable_conditions=[]
26
- for row in rows:
27
- treatable_conditions.append(row)
28
- # Close the connection
29
- conn.close()
30
- return treatable_conditions
31
-
32
- #Unused for writing db
33
- def write_symptoms_into_db(data_list):
34
- """Initialize SQLite database"""
35
- try:
36
- conn = sqlite3.connect('plants.db')
37
- c = conn.cursor()
38
- c.execute('''CREATE TABLE IF NOT EXISTS symptoms (name TEXT)''')
39
- conn.commit()
40
- for each in data_list:
41
- insert_sql = f'''INSERT INTO 'symptoms' (name) VALUES ("{each}")'''
42
- c.execute(insert_sql)
43
- conn.commit()
44
- print("Database created successfully!")
45
- conn.close()
46
- except sqlite3.Error as e:
47
- print(f"An error occurred: {e}")
48
-
49
- #@tool
50
- def get_unique_symptoms(list_text:List[str])->List[str]:
51
- """Processes and deduplicates symptom descriptions into a normalized list of unique symptoms.
52
-
53
- Performs comprehensive text processing to:
54
- - Extract individual symptoms from complex descriptions
55
- - Normalize formatting (removes common connecting words and punctuation)
56
- - Deduplicate symptoms while preserving original meaning
57
- - Handle multiple input formats (strings and tuples)
58
-
59
- Args:
60
- list_text: List of symptom descriptions in various formats.
61
- Each element can be:
62
- - String: "fever and headache"
63
- - Tuple: ("been dizzy and nauseous",)
64
- Example: ["fatigue, nausea", "headache and fever"]
65
-
66
- Returns:
67
- List of unique, alphabetically sorted symptom terms in lowercase.
68
- Returns empty list if:
69
- - Input is empty
70
- - No valid strings found
71
- Example: ['bleed', 'fever', 'headache']
72
-
73
- Processing Details:
74
- 1. Text normalization:
75
- - Removes connecting words ("and", "also", "like", etc.)
76
- - Replaces punctuation with spaces
77
- - Converts to lowercase
78
- 2. Special cases:
79
- - Handles tuple inputs by extracting first element
80
- - Skips non-string/non-tuple elements with warning
81
- 3. Deduplication:
82
- - Uses set operations for uniqueness
83
- - Returns sorted list for consistency
84
-
85
- Examples:
86
- >>> get_unique_symptoms(["fever and headache", "bleed"])
87
- ['bleed', 'fever', 'headache']
88
-
89
- >>> get_unique_symptoms([("been dizzy",), "nausea"])
90
- ['dizzy', 'nausea']
91
-
92
- >>> get_unique_symptoms([123, None])
93
- No Correct DataType
94
- []
95
-
96
- Edge Cases:
97
- - Empty strings are filtered out
98
- - Single-word symptoms preserved
99
- - Mixed punctuation handled
100
- - Warning printed for invalid types
101
- """
102
-
103
- all_symptoms = []
104
-
105
- for text in list_text:
106
- # Handle potential errors in input text. Crucial for robustness.
107
- if type(text)==tuple:
108
- text=text[0]
109
- symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
110
- symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
111
- all_symptoms.extend(symptoms)
112
- elif type(text)==str and len(text)>1:
113
- symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
114
- symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
115
- all_symptoms.extend(symptoms)
116
- else:
117
- print ("No Correct DataType or 1 charater text O.o")
118
- #if not isinstance(text, str) or not text:
119
- #continue
120
-
121
- unique_symptoms = sorted(list(set(all_symptoms))) # Use set to get unique items, then sort for consistency
122
-
123
- return unique_symptoms
124
-
125
- #@tool
126
- def lookup_symptom_and_plants(symptom_input:str)->List:
127
- """Search for medicinal plants that can treat a given symptom by querying a SQLite database.
128
-
129
- This function performs a case-insensitive search in the database for:
130
- 1. First looking for an exact or partial match of the symptom
131
- 2. If not found, searches for individual words from the symptom input
132
- 3. Returns all plants that list the matched symptom in their treatable conditions
133
-
134
- Args:
135
- symptom_input (str): The symptom to search for (e.g., "headache", "stomach pain").
136
- Can be a single symptom or multiple words. Leading/trailing
137
- whitespace is automatically trimmed.
138
-
139
- Returns:
140
- List[dict]: A list of plant dictionaries containing all columns from the 'plants' table
141
- where the symptom appears in treatable_conditions. Each dictionary represents
142
- one plant with column names as keys. Returns empty list if:
143
- - Symptom not found
144
- - No plants treat the symptom
145
- - Database error occurs
146
-
147
- Raises:
148
- sqlite3.Error: If there's a database connection or query error (handled internally,
149
- returns empty list but prints error to console)
150
-
151
- Notes:
152
- - The database connection is opened and closed within this function
153
- - Uses LIKE queries with wildcards for flexible matching
154
- - Treatable conditions are expected to be stored as comma-separated values
155
- - Case-insensitive matching is performed by converting to lowercase
156
- - The function will attempt to match individual words if full phrase not found
157
-
158
- Example:
159
- >>> lookup_symptom_and_plants("headache")
160
- [{'name': 'Neem', 'scientific_name': 'Azadirachta indica', 'alternate_names': 'Indian Lilac, Margosa Tree', 'description': 'Neem is a tropical evergreen tree known for its extensive medicinal properties. Native to the Indian subcontinent, it has been used for thousands of years in traditional medicine systems like Ayurveda and Unani. Various parts of the tree including fruits, seeds, oil, leaves, roots, and bark have therapeutic benefits.', 'plant_family': 'Meliaceae', 'origin': 'Indian subcontinent', 'growth_habitat': 'Tropical and subtropical regions, often found in dry and arid soils', 'active_components': 'Azadirachtin, Nimbin, Nimbidin, Sodium nimbidate, Quercetin', 'treatable_conditions': 'Skin diseases, infections, fever, diabetes, dental issues, inflammation, malaria, digestive disorders', 'preparation_methods': 'Leaves and bark can be dried and powdered; oil extracted from seeds; decoctions and infusions made from leaves or bark', 'dosage': 'Varies depending on preparation and condition; oils generally used topically, leaf powder doses range from 500 mg to 2 grams daily when taken orally', 'duration': 'Treatment duration depends on condition, often several weeks to months for chronic ailments', 'contraindications': 'Pregnant and breastfeeding women advised to avoid internal consumption; caution in people with liver or kidney disease', 'side_effects': 'Possible allergic reactions, nausea, diarrhea if consumed in excess', 'interactions': 'May interact with blood sugar lowering medications and immunosuppressants', 'part_used': 'Leaves, seeds, bark, roots, oil, fruits', 'harvesting_time': 'Leaves and fruits commonly harvested in summer; seeds collected when fruits mature', 'storage_tips': 'Store dried parts in airtight containers away from direct sunlight; oils kept in cool, dark places', 'images': '', 'related_videos': '', 'sources': 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3769010/, https://www.who.int/medicines/areas/traditional/overview/en/'}]
161
-
162
- >>> lookup_symptom_and_plants("unknown symptom")
163
- []
164
- """
165
- symptom_lower = symptom_input.strip().lower()
166
- try:
167
- conn = sqlite3.connect('plants.db')
168
- conn.row_factory = sqlite3.Row
169
- c = conn.cursor()
170
-
171
- # Check if the symptom exists in symptoms table (case-insensitive)
172
- c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{symptom_lower}%"''')
173
- result = c.fetchone()
174
- #if result:
175
- # result=result[0]
176
-
177
- if not result:
178
- #get any 1 symptom only in case the text is not showing.
179
- symptoms=symptom_lower.split(" ")
180
- for each in symptoms:
181
- c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{each}%"''')
182
- result = c.fetchone()
183
- if result:
184
- print(f"Symptom '{symptom_input}' finally found in the database.")
185
- #result=result[0]
186
- symptom_lower=each
187
- break
188
- if not result:
189
- print(f"Symptom '{symptom_input}' not found in the database.")
190
- conn.close()
191
- return []
192
-
193
- # If symptom exists, search in plants table for related plants
194
- # Assuming 'TreatableConditions' is a comma-separated string
195
- query = f"""SELECT * FROM plants WHERE LOWER(treatable_conditions) LIKE "%{symptom_lower}%" """
196
- c.execute(query)
197
- plants_rows = c.fetchall()
198
-
199
- plants_list = []
200
- for row in plants_rows:
201
- # Convert row to dict for easier handling
202
- plant_dict = {key: row[key] for key in row.keys()}
203
- plants_list.append(plant_dict)
204
-
205
- conn.close()
206
- return plants_list
207
-
208
- except sqlite3.Error as e:
209
- print(f"Database error: {e}")
210
- return []
211
-
212
-
213
- #@tool
214
- def analyze_symptoms_from_text_ai(user_input:str)->str:
215
- """Analyze user-provided text to extract medical symptoms in CSV format.
216
-
217
- This function sends the user's text description to an AI service which identifies
218
- and returns potential medical symptoms in a comma-separated string format.
219
-
220
- Args:
221
- user_input (str): The text containing symptom descriptions to be analyzed.
222
- Example: "I feel some pain in head and I feel dizzy"
223
-
224
- Returns:
225
- str: A comma-separated string of identified symptoms.
226
- Example: "pain in head,dizzy"
227
-
228
- Note:
229
- This function requires an internet connection as it makes an API call to
230
- an external AI service. The service URL is expected to be available in
231
- the 'fasttoken' variable.
232
-
233
- Example:
234
- >>> analyze_symptoms_from_text_ai("I have a headache and nausea")
235
- 'headache,nausea'
236
- """
237
- #user_input="""i feel some pain in head and i feel dizzy""" #user input
238
- #text_symptoms='pain in head,dizzy' #returned output
239
- prompt='''Analyze this text for possible symptoms and list them in only csv format by comma in 1 line from the following text : """{user_input}"""'''
240
- prompt=urllib.parse.quote(prompt)
241
- response = requests.get(f"{fasttoken}/{prompt}")
242
- text_symptoms=response.text
243
-
244
- return text_symptoms
245
-
246
- #@tool
247
- def full_treatment_answer_ai(user_input:str)->str:
248
- """
249
- Searches a database for treatable conditions based on user-input and getting from it symptoms and plants needed for the treatment.
250
-
251
- Args:
252
- user_input (str): A string representing the user's full symptoms.
253
-
254
- Returns:
255
- str: Ready Full treatment plan with plants answer about the symptoms (and with side effects of the plants if available).
256
- """
257
- all_related_plants=[]
258
- """
259
- old Return:
260
- A list of dictionaries, where each dictionary represents a treatable condition
261
- and its associated symptoms. Returns an empty list if no matching conditions are found.
262
- Returns None if there's an error connecting to or querying the database.
263
- """
264
- #EXAMPLE:
265
- '''[{'name': 'Neem',
266
- 'scientific_name': 'Azadirachta indica',
267
- 'alternate_names': 'Indian Lilac, Margosa Tree',
268
- 'description': 'Neem is a tropical evergreen tree known for its extensive medicinal properties. Native to the Indian subcontinent, it has been used for thousands of years in traditional medicine systems like Ayurveda and Unani. Various parts of the tree including fruits, seeds, oil, leaves, roots, and bark have therapeutic benefits.',
269
- 'plant_family': 'Meliaceae',
270
- 'origin': 'Indian subcontinent',
271
- 'growth_habitat': 'Tropical and subtropical regions, often found in dry and arid soils',
272
- 'active_components': 'Azadirachtin, Nimbin, Nimbidin, Sodium nimbidate, Quercetin',
273
- 'treatable_conditions': 'Skin diseases, infections, fever, diabetes, dental issues, inflammation, malaria, digestive disorders',
274
- 'preparation_methods': 'Leaves and bark can be dried and powdered; oil extracted from seeds; decoctions and infusions made from leaves or bark',
275
- 'dosage': 'Varies depending on preparation and condition; oils generally used topically, leaf powder doses range from 500 mg to 2 grams daily when taken orally',
276
- 'duration': 'Treatment duration depends on condition, often several weeks to months for chronic ailments',
277
- 'contraindications': 'Pregnant and breastfeeding women advised to avoid internal consumption; caution in people with liver or kidney disease',
278
- 'side_effects': 'Possible allergic reactions, nausea, diarrhea if consumed in excess',
279
- 'interactions': 'May interact with blood sugar lowering medications and immunosuppressants',
280
- 'part_used': 'Leaves, seeds, bark, roots, oil, fruits',
281
- 'harvesting_time': 'Leaves and fruits commonly harvested in summer; seeds collected when fruits mature',
282
- 'storage_tips': 'Store dried parts in airtight containers away from direct sunlight; oils kept in cool, dark places',
283
- 'images': '',
284
- 'related_videos': '',
285
- 'sources': 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3769010/, https://www.who.int/medicines/areas/traditional/overview/en/'}]'''
286
- text_symptoms=user_input#analyze_symptoms_from_text_ai(user_input)
287
- symptoms_list=text_symptoms.split(",")
288
- symptoms=get_unique_symptoms(symptoms_list)
289
-
290
- for symptom in symptoms:
291
- related_plants = lookup_symptom_and_plants(symptom)
292
- for each in related_plants:
293
- all_related_plants.append(each)
294
- plants_info=""
295
- if len(all_related_plants)>0:
296
- for each in all_related_plants[:6]: #GET top 7 if available
297
- plants_info+="""Here are some plants that might be relevant:\nPlant:{each['name']}\n{each['description']}\nCures:{each['treatable_conditions']}.\n """
298
- else:
299
- plants_info="No Plants found , please get useful plants from anywhere or any other sources."
300
- prompt=f"""I have these symptoms: {",".join(symptoms)}.
301
-
302
- {plants_info}
303
-
304
- Please analyze my symptoms and recommend the most appropriate plant remedy.
305
- Consider the symptoms, when to use each plant, dosage, and how to use it.
306
- Provide your recommendation in this format:
307
-
308
- **Recommended Plant**: [plant name]
309
- **Reason**: [why this plant is good for these symptoms]
310
- **Dosage**: [recommended dosage]
311
- **Instructions**: [how to use it]
312
- **Image**: [mention the image is available if applicable]
313
-
314
- If multiple plants could work well, you may recommend up to 3 options."""
315
-
316
- #filter the names and description, treatments only and send it in post to AI
317
- prompt=urllib.parse.quote(prompt)
318
- response = requests.get(f"{fasttoken}/{prompt}")
319
- final_result=response.text
320
-
321
- #Get the answer and send it to user then post all data for each plant in a good form for user to view
322
-
323
- if len(all_related_plants)>0:
324
- final_result+="\n---\nMore Details for Plants:\n"
325
- for each in all_related_plants[:4]:
326
- final_result+=f"""\n**Plant Name**: {each['name']}
327
- **Other Names**: {each['scientific_name']} , {each['alternate_names']}
328
- **Description**: {each['description']}
329
- **Plant Family**: {each['plant_family']}, **Origin**: {each['origin']}
330
- **Treatment Conditions**: {each['treatable_conditions']}
331
- **Preparation Methods**: {each['preparation_methods']}
332
- **Side Effects**: {each['side_effects']}
333
- **Storage Tips**: {each['storage_tips']}
334
- **Info. Sources**: {each['sources']}
335
- """
336
- return final_result
337
-
338
- #example:
339
- # user_input="""i feel some pain in head and i feel dizzy""" #user input
340
- # prompt='''Analyze the possible symptoms and list them in only csv format by comma in 1 line,from the following text : """{user_input}"""'''
341
- # output='pain in head,dizzy'
342
- # symptoms=output.split(",")
343
- # get_unique_symptoms(symptoms)
344
-
345
-
346
- #Filter all conditions:
347
- #all_treatment_conditions=get_all_treatable_conditions()
348
- #unique_symptoms=get_unique_symptoms(all_treatment_conditions)
349
- #write_symptoms_into_db(unique_symptoms)
350
- #related_plants = lookup_symptom_and_plants("fever")
351
-
352
- '''
353
- user_input = "fever"
354
- related_plants = lookup_symptom_and_plants(user_input)
355
- if related_plants:
356
- print(f"Plants related to '{user_input}':")
357
- for plant in related_plants:
358
- print(f"- {plant['name']}")
359
- else:
360
- print(f"No plants found for symptom '{user_input}'.")
361
- '''
362
- def is_symtoms_intext_ai(text_input:str)->str: #used instead of: analyze_symptoms_from_text_ai()
363
- """Gives Symptoms or "" if no symptoms """
364
- prompt='''Analyze this text for possible symptoms and list them in only csv format by comma in 1 line from the following text : """{user_input}"""
365
- ---
366
- Return "" , IF NO SYMTPOMS OR DIESEASE IN THE TEXT
367
- '''
368
- prompt=urllib.parse.quote(prompt)
369
- response = requests.get(f"{fasttoken}/{prompt}")
370
- response_text=response.text
371
- if len(response_text)>2:
372
- if "error" not in response_text.lower():
373
- return response_text
374
- return ""
375
-
376
- class BotanistAssistant:
377
- def __init__(self, api_endpoint: str):
378
- self.api_endpoint = api_endpoint
379
- self.system_message = "You are a botanist assistant that extracts and structures information about medicinal plants."
380
-
381
- def _build_chat_history(self, history: List[Tuple[str, str]]) -> List[Dict[str, str]]:
382
- """Formats chat history into API-compatible message format."""
383
- messages = [{"role": "system", "content": self.system_message}]
384
- for user_msg, bot_msg in history:
385
- if user_msg:
386
- messages.append({"role": "user", "content": user_msg})
387
- if bot_msg:
388
- messages.append({"role": "assistant", "content": bot_msg})
389
- return messages
390
-
391
- def _get_tools_schema(self) -> List[Dict[str, Any]]:
392
- """Returns the complete tools schema for plant medicine analysis."""
393
- return [
394
- {
395
- "name": "get_unique_symptoms",
396
- "description": "Extracts and deduplicates symptoms from text input. Handles natural language processing to identify individual symptoms from complex descriptions.",
397
- "api": {
398
- "name": "get_unique_symptoms",
399
- "parameters": {
400
- "type": "object",
401
- "properties": {
402
- "list_text": {
403
- "type": "array",
404
- "items": {"type": "string"},
405
- "description": "List of symptom descriptions (strings or tuples)"
406
- }
407
- },
408
- "required": ["list_text"]
409
- }
410
- }
411
- },
412
- {
413
- "name": "lookup_symptom_and_plants",
414
- "description": "Finds medicinal plants associated with specific symptoms from the database. Returns matching plants with their treatment properties.",
415
- "api": {
416
- "name": "lookup_symptom_and_plants",
417
- "parameters": {
418
- "type": "object",
419
- "properties": {
420
- "symptom_input": {
421
- "type": "string",
422
- "description": "Individual symptom to search for plant treatments"
423
- }
424
- },
425
- "required": ["symptom_input"]
426
- }
427
- }
428
- },
429
- {
430
- "name": "analyze_symptoms_from_text_ai",
431
- "description": "AI-powered symptom analysis that interprets natural language descriptions of health conditions and extracts medically relevant symptoms.",
432
- "api": {
433
- "name": "analyze_symptoms_from_text_ai",
434
- "parameters": {
435
- "type": "object",
436
- "properties": {
437
- "text_input": {
438
- "type": "string",
439
- "description": "Raw text description of health condition"
440
- }
441
- },
442
- "required": ["text_input"]
443
- }
444
- }
445
- },
446
- {
447
- "name": "search_for_treatment_answer_ai",
448
- "description": "Comprehensive treatment finder that takes symptoms, analyzes them, and returns complete plant-based treatment plans with dosage instructions.",
449
- "api": {
450
- "name": "search_for_treatment_answer_ai",
451
- "parameters": {
452
- "type": "object",
453
- "properties": {
454
- "list_symptoms": {
455
- "type": "array",
456
- "items": {"type": "string"},
457
- "description": "List of identified symptoms"
458
- }
459
- },
460
- "required": ["list_symptoms"]
461
- }
462
- }
463
- }
464
- ]
465
-
466
- def _call_assistant_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
467
- """Makes the API call to the assistant service."""
468
- payload = {
469
- "model": "openai",
470
- "messages": messages,
471
- #"tools": self._get_tools_schema(), TOOLS REMOVED
472
- #"tool_choice": "auto" #TODO fix tools
473
- }
474
-
475
- try:
476
- response = requests.post(
477
- self.api_endpoint,
478
- json=payload,
479
- headers={"Content-Type": "application/json"},
480
- timeout=30 # 30-second timeout
481
- )
482
- response.raise_for_status()
483
- return response.json() #-_-
484
- except requests.exceptions.RequestException as e:
485
- print(f"API request failed: {str(e)}")
486
- return {"error": str(e)}
487
-
488
- def respond(
489
- self,
490
- message: str,
491
- history: List[Tuple[str, str]],
492
- system_message: str = None
493
- ) -> Generator[str, None, None]:
494
- """Handles the chat response generation."""
495
- # Update system message if provided
496
- if system_message:
497
- self.system_message = system_message
498
-
499
- # Build API payload
500
- messages = self._build_chat_history(history)
501
- messages.append({"role": "user", "content": message})
502
-
503
-
504
- # Get API response
505
- api_response = self._call_assistant_api(messages)
506
-
507
- # Process response
508
- if "error" in api_response:
509
- yield "Error: Could not connect to the assistant service. Please try again later."
510
- return
511
-
512
-
513
- treatment_response=""
514
- symtoms_intext=is_symtoms_intext_ai(message)
515
- if symtoms_intext:
516
- time.sleep(1.6)
517
- treatment_response=full_treatment_answer_ai(symtoms_intext)
518
- #yield treatment_response
519
-
520
- if len(treatment_response):
521
- treatment_response="\n**I have found that this may help you alot:**\n"+treatment_response
522
- yield treatment_response
523
-
524
- # Get treatment information
525
- #treatment_response = search_for_treatment_answer_ai(message)
526
- #yield treatment_response # First yield the treatment info
527
-
528
- # Stream additional assistant responses if available
529
- if "choices" in api_response:
530
- for choice in api_response["choices"]:
531
- if "message" in choice and "content" in choice["message"]:
532
- yield choice["message"]["content"].split("**Sponsor**")[0].split("Sponsor")[0]
533
-
534
- def create_app(api_endpoint: str) -> gr.Blocks:
535
- """Creates and configures the Gradio interface."""
536
- assistant = BotanistAssistant(api_endpoint)
537
-
538
- with gr.Blocks(title="Botanist Assistant", theme=gr.themes.Soft()) as demo:
539
- gr.Markdown("# 🌿 Natural Medical Assistant")
540
- gr.Markdown("Describe your symptoms to get natural plant-based treatment recommendations")
541
-
542
- with gr.Row():
543
- with gr.Column(scale=3):
544
- chat = gr.ChatInterface(
545
- assistant.respond,
546
- additional_inputs=[
547
- gr.Textbox(
548
- value=assistant.system_message,
549
- label="System Role",
550
- interactive=True
551
- )
552
- ]
553
- )
554
- with gr.Column(scale=1):
555
- gr.Markdown("### Common Symptoms")
556
- gr.Examples(
557
- examples=[
558
- ["I have headache and fever"],
559
- ["got nausea, and injury caused bleeding"],
560
- ["I feel insomnia, and anxiety"]
561
- ],
562
- inputs=chat.textbox,
563
- label="Try these examples"
564
- )
565
-
566
- gr.Markdown("---")
567
- gr.Markdown("""> Note: Recommendations can work as real cure treatment but you can consider it as informational purposes only.
568
- Also You can consult a Natrual healthcare professional before use.""")
569
-
570
-
571
- return demo
572
-
573
- if __name__ == "__main__":
574
- API_ENDPOINT = specialtoken # Replace with your actual endpoint
575
- app = create_app(API_ENDPOINT)
576
- app.launch(
577
- server_name="0.0.0.0",
578
- server_port=7860,
579
- share=False,
580
- favicon_path="🌿" # Optional: Add path to plant icon
 
 
581
  )
 
1
+ from typing import List, Tuple, Dict, Any, Generator
2
+ import sqlite3
3
+ import urllib
4
+ import requests
5
+ import os
6
+ import gradio as gr
7
+ from smolagents import tool
8
+ import time
9
+
10
+ #specialtoken=os.getenv("SPECIALTOKEN")+"deepseek-r1-0528"
11
+ specialtoken=os.getenv("SPECIALTOKEN")+"openai"#"openai-large"#"openai-roblox"
12
+ fasttoken=os.getenv("SPECIALTOKEN")+"models/"+"openai-fast"
13
+
14
+ #unused for getting all symptoms from plants db
15
+ def get_all_treatable_conditions()->List:
16
+ #Gets all the symptoms:
17
+ conn = sqlite3.connect('plants.db')
18
+ # Create a cursor object
19
+ cursor = conn.cursor()
20
+ # Execute a query to retrieve data
21
+ cursor.execute("SELECT treatable_conditions FROM 'plants'")
22
+ # Fetch all results
23
+ rows = cursor.fetchall()
24
+ # Print the results
25
+ treatable_conditions=[]
26
+ for row in rows:
27
+ treatable_conditions.append(row)
28
+ # Close the connection
29
+ conn.close()
30
+ return treatable_conditions
31
+
32
+ #Unused for writing db
33
+ def write_symptoms_into_db(data_list):
34
+ """Initialize SQLite database"""
35
+ try:
36
+ conn = sqlite3.connect('plants.db')
37
+ c = conn.cursor()
38
+ c.execute('''CREATE TABLE IF NOT EXISTS symptoms (name TEXT)''')
39
+ conn.commit()
40
+ for each in data_list:
41
+ insert_sql = f'''INSERT INTO 'symptoms' (name) VALUES ("{each}")'''
42
+ c.execute(insert_sql)
43
+ conn.commit()
44
+ print("Database created successfully!")
45
+ conn.close()
46
+ except sqlite3.Error as e:
47
+ print(f"An error occurred: {e}")
48
+
49
+ #@tool
50
+ def get_unique_symptoms(list_text:List[str])->List[str]:
51
+ """Processes and deduplicates symptom descriptions into a normalized list of unique symptoms.
52
+
53
+ Performs comprehensive text processing to:
54
+ - Extract individual symptoms from complex descriptions
55
+ - Normalize formatting (removes common connecting words and punctuation)
56
+ - Deduplicate symptoms while preserving original meaning
57
+ - Handle multiple input formats (strings and tuples)
58
+
59
+ Args:
60
+ list_text: List of symptom descriptions in various formats.
61
+ Each element can be:
62
+ - String: "fever and headache"
63
+ - Tuple: ("been dizzy and nauseous",)
64
+ Example: ["fatigue, nausea", "headache and fever"]
65
+
66
+ Returns:
67
+ List of unique, alphabetically sorted symptom terms in lowercase.
68
+ Returns empty list if:
69
+ - Input is empty
70
+ - No valid strings found
71
+ Example: ['bleed', 'fever', 'headache']
72
+
73
+ Processing Details:
74
+ 1. Text normalization:
75
+ - Removes connecting words ("and", "also", "like", etc.)
76
+ - Replaces punctuation with spaces
77
+ - Converts to lowercase
78
+ 2. Special cases:
79
+ - Handles tuple inputs by extracting first element
80
+ - Skips non-string/non-tuple elements with warning
81
+ 3. Deduplication:
82
+ - Uses set operations for uniqueness
83
+ - Returns sorted list for consistency
84
+
85
+ Examples:
86
+ >>> get_unique_symptoms(["fever and headache", "bleed"])
87
+ ['bleed', 'fever', 'headache']
88
+
89
+ >>> get_unique_symptoms([("been dizzy",), "nausea"])
90
+ ['dizzy', 'nausea']
91
+
92
+ >>> get_unique_symptoms([123, None])
93
+ No Correct DataType
94
+ []
95
+
96
+ Edge Cases:
97
+ - Empty strings are filtered out
98
+ - Single-word symptoms preserved
99
+ - Mixed punctuation handled
100
+ - Warning printed for invalid types
101
+ """
102
+
103
+ all_symptoms = []
104
+
105
+ for text in list_text:
106
+ # Handle potential errors in input text. Crucial for robustness.
107
+ if type(text)==tuple:
108
+ text=text[0]
109
+ symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
110
+ symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
111
+ all_symptoms.extend(symptoms)
112
+ elif type(text)==str and len(text)>1:
113
+ symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
114
+ symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
115
+ all_symptoms.extend(symptoms)
116
+ else:
117
+ print ("No Correct DataType or 1 charater text O.o")
118
+ #if not isinstance(text, str) or not text:
119
+ #continue
120
+
121
+ unique_symptoms = sorted(list(set(all_symptoms))) # Use set to get unique items, then sort for consistency
122
+
123
+ return unique_symptoms
124
+
125
+ #@tool
126
+ def lookup_symptom_and_plants(symptom_input:str)->List:
127
+ """Search for medicinal plants that can treat a given symptom by querying a SQLite database.
128
+
129
+ This function performs a case-insensitive search in the database for:
130
+ 1. First looking for an exact or partial match of the symptom
131
+ 2. If not found, searches for individual words from the symptom input
132
+ 3. Returns all plants that list the matched symptom in their treatable conditions
133
+
134
+ Args:
135
+ symptom_input (str): The symptom to search for (e.g., "headache", "stomach pain").
136
+ Can be a single symptom or multiple words. Leading/trailing
137
+ whitespace is automatically trimmed.
138
+
139
+ Returns:
140
+ List[dict]: A list of plant dictionaries containing all columns from the 'plants' table
141
+ where the symptom appears in treatable_conditions. Each dictionary represents
142
+ one plant with column names as keys. Returns empty list if:
143
+ - Symptom not found
144
+ - No plants treat the symptom
145
+ - Database error occurs
146
+
147
+ Raises:
148
+ sqlite3.Error: If there's a database connection or query error (handled internally,
149
+ returns empty list but prints error to console)
150
+
151
+ Notes:
152
+ - The database connection is opened and closed within this function
153
+ - Uses LIKE queries with wildcards for flexible matching
154
+ - Treatable conditions are expected to be stored as comma-separated values
155
+ - Case-insensitive matching is performed by converting to lowercase
156
+ - The function will attempt to match individual words if full phrase not found
157
+
158
+ Example:
159
+ >>> lookup_symptom_and_plants("headache")
160
+ [{'name': 'Neem', 'scientific_name': 'Azadirachta indica', 'alternate_names': 'Indian Lilac, Margosa Tree', 'description': 'Neem is a tropical evergreen tree known for its extensive medicinal properties. Native to the Indian subcontinent, it has been used for thousands of years in traditional medicine systems like Ayurveda and Unani. Various parts of the tree including fruits, seeds, oil, leaves, roots, and bark have therapeutic benefits.', 'plant_family': 'Meliaceae', 'origin': 'Indian subcontinent', 'growth_habitat': 'Tropical and subtropical regions, often found in dry and arid soils', 'active_components': 'Azadirachtin, Nimbin, Nimbidin, Sodium nimbidate, Quercetin', 'treatable_conditions': 'Skin diseases, infections, fever, diabetes, dental issues, inflammation, malaria, digestive disorders', 'preparation_methods': 'Leaves and bark can be dried and powdered; oil extracted from seeds; decoctions and infusions made from leaves or bark', 'dosage': 'Varies depending on preparation and condition; oils generally used topically, leaf powder doses range from 500 mg to 2 grams daily when taken orally', 'duration': 'Treatment duration depends on condition, often several weeks to months for chronic ailments', 'contraindications': 'Pregnant and breastfeeding women advised to avoid internal consumption; caution in people with liver or kidney disease', 'side_effects': 'Possible allergic reactions, nausea, diarrhea if consumed in excess', 'interactions': 'May interact with blood sugar lowering medications and immunosuppressants', 'part_used': 'Leaves, seeds, bark, roots, oil, fruits', 'harvesting_time': 'Leaves and fruits commonly harvested in summer; seeds collected when fruits mature', 'storage_tips': 'Store dried parts in airtight containers away from direct sunlight; oils kept in cool, dark places', 'images': '', 'related_videos': '', 'sources': 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3769010/, https://www.who.int/medicines/areas/traditional/overview/en/'}]
161
+
162
+ >>> lookup_symptom_and_plants("unknown symptom")
163
+ []
164
+ """
165
+ symptom_lower = symptom_input.strip().lower()
166
+ try:
167
+ conn = sqlite3.connect('plants.db')
168
+ conn.row_factory = sqlite3.Row
169
+ c = conn.cursor()
170
+
171
+ # Check if the symptom exists in symptoms table (case-insensitive)
172
+ c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{symptom_lower}%"''')
173
+ result = c.fetchone()
174
+ #if result:
175
+ # result=result[0]
176
+
177
+ if not result:
178
+ #get any 1 symptom only in case the text is not showing.
179
+ symptoms=symptom_lower.split(" ")
180
+ for each in symptoms:
181
+ c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{each}%"''')
182
+ result = c.fetchone()
183
+ if result:
184
+ print(f"Symptom '{symptom_input}' finally found in the database.")
185
+ #result=result[0]
186
+ symptom_lower=each
187
+ break
188
+ if not result:
189
+ print(f"Symptom '{symptom_input}' not found in the database.")
190
+ conn.close()
191
+ return []
192
+
193
+ # If symptom exists, search in plants table for related plants
194
+ # Assuming 'TreatableConditions' is a comma-separated string
195
+ query = f"""SELECT * FROM plants WHERE LOWER(treatable_conditions) LIKE "%{symptom_lower}%" """
196
+ c.execute(query)
197
+ plants_rows = c.fetchall()
198
+
199
+ plants_list = []
200
+ for row in plants_rows:
201
+ # Convert row to dict for easier handling
202
+ plant_dict = {key: row[key] for key in row.keys()}
203
+ plants_list.append(plant_dict)
204
+
205
+ conn.close()
206
+ return plants_list
207
+
208
+ except sqlite3.Error as e:
209
+ print(f"Database error: {e}")
210
+ return []
211
+
212
+
213
+ #@tool
214
+ def analyze_symptoms_from_text_ai(user_input:str)->str:
215
+ """Analyze user-provided text to extract medical symptoms in CSV format.
216
+
217
+ This function sends the user's text description to an AI service which identifies
218
+ and returns potential medical symptoms in a comma-separated string format.
219
+
220
+ Args:
221
+ user_input (str): The text containing symptom descriptions to be analyzed.
222
+ Example: "I feel some pain in head and I feel dizzy"
223
+
224
+ Returns:
225
+ str: A comma-separated string of identified symptoms.
226
+ Example: "pain in head,dizzy"
227
+
228
+ Note:
229
+ This function requires an internet connection as it makes an API call to
230
+ an external AI service. The service URL is expected to be available in
231
+ the 'fasttoken' variable.
232
+
233
+ Example:
234
+ >>> analyze_symptoms_from_text_ai("I have a headache and nausea")
235
+ 'headache,nausea'
236
+ """
237
+ #user_input="""i feel some pain in head and i feel dizzy""" #user input
238
+ #text_symptoms='pain in head,dizzy' #returned output
239
+ prompt='''Analyze this text for possible symptoms and list them in only csv format by comma in 1 line from the following text : """{user_input}""" Return "" if no symptoms found.'''
240
+ prompt=urllib.parse.quote(prompt)
241
+ response = requests.get(f"{fasttoken}/{prompt}")
242
+ text_symptoms=response.text
243
+
244
+ return text_symptoms
245
+
246
+ #@tool
247
+ def full_treatment_answer_ai(user_input:str)->str:
248
+ """
249
+ Searches a database for treatable conditions based on user-input and getting from it symptoms and plants needed for the treatment.
250
+
251
+ Args:
252
+ user_input (str): A string representing the user's full symptoms.
253
+
254
+ Returns:
255
+ str: Ready Full treatment plan with plants answer about the symptoms (and with side effects of the plants if available).
256
+ """
257
+ all_related_plants=[]
258
+ """
259
+ old Return:
260
+ A list of dictionaries, where each dictionary represents a treatable condition
261
+ and its associated symptoms. Returns an empty list if no matching conditions are found.
262
+ Returns None if there's an error connecting to or querying the database.
263
+ """
264
+ #EXAMPLE:
265
+ '''[{'name': 'Neem',
266
+ 'scientific_name': 'Azadirachta indica',
267
+ 'alternate_names': 'Indian Lilac, Margosa Tree',
268
+ 'description': 'Neem is a tropical evergreen tree known for its extensive medicinal properties. Native to the Indian subcontinent, it has been used for thousands of years in traditional medicine systems like Ayurveda and Unani. Various parts of the tree including fruits, seeds, oil, leaves, roots, and bark have therapeutic benefits.',
269
+ 'plant_family': 'Meliaceae',
270
+ 'origin': 'Indian subcontinent',
271
+ 'growth_habitat': 'Tropical and subtropical regions, often found in dry and arid soils',
272
+ 'active_components': 'Azadirachtin, Nimbin, Nimbidin, Sodium nimbidate, Quercetin',
273
+ 'treatable_conditions': 'Skin diseases, infections, fever, diabetes, dental issues, inflammation, malaria, digestive disorders',
274
+ 'preparation_methods': 'Leaves and bark can be dried and powdered; oil extracted from seeds; decoctions and infusions made from leaves or bark',
275
+ 'dosage': 'Varies depending on preparation and condition; oils generally used topically, leaf powder doses range from 500 mg to 2 grams daily when taken orally',
276
+ 'duration': 'Treatment duration depends on condition, often several weeks to months for chronic ailments',
277
+ 'contraindications': 'Pregnant and breastfeeding women advised to avoid internal consumption; caution in people with liver or kidney disease',
278
+ 'side_effects': 'Possible allergic reactions, nausea, diarrhea if consumed in excess',
279
+ 'interactions': 'May interact with blood sugar lowering medications and immunosuppressants',
280
+ 'part_used': 'Leaves, seeds, bark, roots, oil, fruits',
281
+ 'harvesting_time': 'Leaves and fruits commonly harvested in summer; seeds collected when fruits mature',
282
+ 'storage_tips': 'Store dried parts in airtight containers away from direct sunlight; oils kept in cool, dark places',
283
+ 'images': '',
284
+ 'related_videos': '',
285
+ 'sources': 'https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3769010/, https://www.who.int/medicines/areas/traditional/overview/en/'}]'''
286
+ text_symptoms=user_input#analyze_symptoms_from_text_ai(user_input)
287
+ symptoms_list=text_symptoms.split(",")
288
+ symptoms=get_unique_symptoms(symptoms_list)
289
+
290
+ for symptom in symptoms:
291
+ related_plants = lookup_symptom_and_plants(symptom)
292
+ for each in related_plants:
293
+ all_related_plants.append(each)
294
+ plants_info=""
295
+ if len(all_related_plants)>0:
296
+ plants_info="Here are some plants that might be relevant:\n"
297
+ for each in all_related_plants[:6]: #GET top 7 if available
298
+ plants_info+="""Plant:{each['name']}\n{each['description']}\nCures:{each['treatable_conditions']}\nDosage:{each['dosage']}.\n """
299
+ else:
300
+ plants_info="No Plants found , please get useful plants from anywhere or any other sources."
301
+ prompt=f"""I have these symptoms: {",".join(symptoms)}.
302
+
303
+ {plants_info}
304
+
305
+ Please analyze my symptoms and recommend the most appropriate plant remedy.
306
+ Consider the symptoms, when to use each plant, dosage, and how to use it.
307
+ Provide your recommendation in this format:
308
+
309
+ **Recommended Plant**: [plant name]
310
+ **Reason**: [why this plant is good for these symptoms]
311
+ **Dosage**: [recommended dosage]
312
+ **Instructions**: [how to use it]
313
+ **Image**: [mention the image is available if applicable]
314
+
315
+ If multiple plants could work well, you may recommend up to 3 options."""
316
+
317
+ #filter the names and description, treatments only and send it in post to AI
318
+ prompt=urllib.parse.quote(prompt)
319
+ response = requests.get(f"{fasttoken}/{prompt}")
320
+ final_result=response.text
321
+
322
+ #Get the answer and send it to user then post all data for each plant in a good form for user to view
323
+
324
+ if len(all_related_plants)>0:
325
+ final_result+="\n---\nMore Details for Plants:\n"
326
+ for each in all_related_plants[:4]:
327
+ final_result+=f"""\n**Plant Name**: {each['name']}
328
+ **Other Names**: {each['scientific_name']} , {each['alternate_names']}
329
+ **Description**: {each['description']}
330
+ **Plant Family**: {each['plant_family']}, **Origin**: {each['origin']}
331
+ **Treatment Conditions**: {each['treatable_conditions']}
332
+ **Preparation Methods**: {each['preparation_methods']}
333
+ **Side Effects**: {each['side_effects']}
334
+ **Storage Tips**: {each['storage_tips']}
335
+ **Info. Sources**: {each['sources']}
336
+ """
337
+ return final_result
338
+
339
+ #example:
340
+ # user_input="""i feel some pain in head and i feel dizzy""" #user input
341
+ # prompt='''Analyze the possible symptoms and list them in only csv format by comma in 1 line,from the following text : """{user_input}"""'''
342
+ # output='pain in head,dizzy'
343
+ # symptoms=output.split(",")
344
+ # get_unique_symptoms(symptoms)
345
+
346
+
347
+ #Filter all conditions:
348
+ #all_treatment_conditions=get_all_treatable_conditions()
349
+ #unique_symptoms=get_unique_symptoms(all_treatment_conditions)
350
+ #write_symptoms_into_db(unique_symptoms)
351
+ #related_plants = lookup_symptom_and_plants("fever")
352
+
353
+ '''
354
+ user_input = "fever"
355
+ related_plants = lookup_symptom_and_plants(user_input)
356
+ if related_plants:
357
+ print(f"Plants related to '{user_input}':")
358
+ for plant in related_plants:
359
+ print(f"- {plant['name']}")
360
+ else:
361
+ print(f"No plants found for symptom '{user_input}'.")
362
+ '''
363
+ def is_symtoms_intext_ai(text_input:str)->str: #used instead of: analyze_symptoms_from_text_ai()
364
+ """Gives Symptoms or "" if no symptoms """
365
+ prompt='''Analyze this text for possible symptoms and list them in only csv format by comma in 1 line from the following text : """{user_input}"""
366
+ ---
367
+ Return "" , IF NO SYMTPOMS OR DIESEASE IN THE TEXT
368
+ '''
369
+ prompt=urllib.parse.quote(prompt)
370
+ response = requests.get(f"{fasttoken}/{prompt}")
371
+ response_text=response.text
372
+ if len(response_text)>2:
373
+ if "error" not in response_text.lower():
374
+ return response_text
375
+ return ""
376
+
377
+ class BotanistAssistant:
378
+ def __init__(self, api_endpoint: str):
379
+ self.api_endpoint = api_endpoint
380
+ self.system_message = "You are a botanist assistant that extracts and structures information about medicinal plants."
381
+
382
+ def _build_chat_history(self, history: List[Tuple[str, str]]) -> List[Dict[str, str]]:
383
+ """Formats chat history into API-compatible message format."""
384
+ messages = [{"role": "system", "content": self.system_message}]
385
+ for user_msg, bot_msg in history:
386
+ if user_msg:
387
+ messages.append({"role": "user", "content": user_msg})
388
+ if bot_msg:
389
+ messages.append({"role": "assistant", "content": bot_msg})
390
+ return messages
391
+
392
+ def _get_tools_schema(self) -> List[Dict[str, Any]]:
393
+ """Returns the complete tools schema for plant medicine analysis."""
394
+ return [
395
+ {
396
+ "name": "get_unique_symptoms",
397
+ "description": "Extracts and deduplicates symptoms from text input. Handles natural language processing to identify individual symptoms from complex descriptions.",
398
+ "api": {
399
+ "name": "get_unique_symptoms",
400
+ "parameters": {
401
+ "type": "object",
402
+ "properties": {
403
+ "list_text": {
404
+ "type": "array",
405
+ "items": {"type": "string"},
406
+ "description": "List of symptom descriptions (strings or tuples)"
407
+ }
408
+ },
409
+ "required": ["list_text"]
410
+ }
411
+ }
412
+ },
413
+ {
414
+ "name": "lookup_symptom_and_plants",
415
+ "description": "Finds medicinal plants associated with specific symptoms from the database. Returns matching plants with their treatment properties.",
416
+ "api": {
417
+ "name": "lookup_symptom_and_plants",
418
+ "parameters": {
419
+ "type": "object",
420
+ "properties": {
421
+ "symptom_input": {
422
+ "type": "string",
423
+ "description": "Individual symptom to search for plant treatments"
424
+ }
425
+ },
426
+ "required": ["symptom_input"]
427
+ }
428
+ }
429
+ },
430
+ {
431
+ "name": "analyze_symptoms_from_text_ai",
432
+ "description": "AI-powered symptom analysis that interprets natural language descriptions of health conditions and extracts medically relevant symptoms.",
433
+ "api": {
434
+ "name": "analyze_symptoms_from_text_ai",
435
+ "parameters": {
436
+ "type": "object",
437
+ "properties": {
438
+ "text_input": {
439
+ "type": "string",
440
+ "description": "Raw text description of health condition"
441
+ }
442
+ },
443
+ "required": ["text_input"]
444
+ }
445
+ }
446
+ },
447
+ {
448
+ "name": "search_for_treatment_answer_ai",
449
+ "description": "Comprehensive treatment finder that takes symptoms, analyzes them, and returns complete plant-based treatment plans with dosage instructions.",
450
+ "api": {
451
+ "name": "search_for_treatment_answer_ai",
452
+ "parameters": {
453
+ "type": "object",
454
+ "properties": {
455
+ "list_symptoms": {
456
+ "type": "array",
457
+ "items": {"type": "string"},
458
+ "description": "List of identified symptoms"
459
+ }
460
+ },
461
+ "required": ["list_symptoms"]
462
+ }
463
+ }
464
+ }
465
+ ]
466
+
467
+ def _call_assistant_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
468
+ """Makes the API call to the assistant service."""
469
+ payload = {
470
+ "model": "openai",
471
+ "messages": messages,
472
+ #"tools": self._get_tools_schema(), TOOLS REMOVED
473
+ #"tool_choice": "auto" #TODO fix tools
474
+ }
475
+
476
+ try:
477
+ response = requests.post(
478
+ self.api_endpoint,
479
+ json=payload,
480
+ headers={"Content-Type": "application/json"},
481
+ timeout=30 # 30-second timeout
482
+ )
483
+ response.raise_for_status()
484
+ return response.json() #-_-
485
+ except requests.exceptions.RequestException as e:
486
+ print(f"API request failed: {str(e)}")
487
+ return {"error": str(e)}
488
+
489
+ def respond(
490
+ self,
491
+ message: str,
492
+ history: List[Tuple[str, str]],
493
+ system_message: str = None
494
+ ) -> Generator[str, None, None]:
495
+ """Handles the chat response generation."""
496
+ # Update system message if provided
497
+ if system_message:
498
+ self.system_message = system_message
499
+
500
+ # Build API payload
501
+ messages = self._build_chat_history(history)
502
+ messages.append({"role": "user", "content": message})
503
+
504
+
505
+ # Get API response
506
+ api_response = self._call_assistant_api(messages)
507
+
508
+ # Process response
509
+ if "error" in api_response:
510
+ yield "Error: Could not connect to the assistant service. Please try again later."
511
+ return
512
+
513
+
514
+ treatment_response=""
515
+ symtoms_intext=is_symtoms_intext_ai(message)
516
+ if symtoms_intext:
517
+ time.sleep(1.6)
518
+ treatment_response=full_treatment_answer_ai(symtoms_intext)
519
+ #yield treatment_response
520
+
521
+ if len(treatment_response):
522
+ treatment_response="\n**I have found that this may help you alot:**\n"+treatment_response
523
+ yield treatment_response
524
+
525
+ # Get treatment information
526
+ #treatment_response = search_for_treatment_answer_ai(message)
527
+ #yield treatment_response # First yield the treatment info
528
+
529
+ # Stream additional assistant responses if available
530
+ if "choices" in api_response:
531
+ for choice in api_response["choices"]:
532
+ if "message" in choice and "content" in choice["message"]:
533
+ yield choice["message"]["content"].split("**Sponsor**")[0].split("Sponsor")[0]
534
+
535
+ def create_app(api_endpoint: str) -> gr.Blocks:
536
+ """Creates and configures the Gradio interface."""
537
+ assistant = BotanistAssistant(api_endpoint)
538
+
539
+ with gr.Blocks(title="Botanist Assistant", theme=gr.themes.Soft()) as demo:
540
+ gr.Markdown("# 🌿 Natural Medical Assistant")
541
+ gr.Markdown("Describe your symptoms to get natural plant-based treatment recommendations")
542
+
543
+ with gr.Row():
544
+ with gr.Column(scale=3):
545
+ chat = gr.ChatInterface(
546
+ assistant.respond,
547
+ additional_inputs=[
548
+ gr.Textbox(
549
+ value=assistant.system_message,
550
+ label="System Role",
551
+ interactive=True
552
+ )
553
+ ]
554
+ )
555
+ with gr.Column(scale=1):
556
+ gr.Markdown("### Common Symptoms")
557
+ gr.Examples(
558
+ examples=[
559
+ ["I have headache and fever"],
560
+ ["got nausea, and injury caused bleeding"],
561
+ ["I feel insomnia and anxiety"],
562
+ ["I am suffering from ADHD"]
563
+ ],
564
+ inputs=chat.textbox,
565
+ label="Try these examples"
566
+ )
567
+
568
+ gr.Markdown("---")
569
+ gr.Markdown("""> Note: Recommendations can work as real cure treatment but you can consider it as informational purposes only.
570
+ Also You can consult a Natrual healthcare professional before use.""")
571
+
572
+
573
+ return demo
574
+
575
+ if __name__ == "__main__":
576
+ API_ENDPOINT = specialtoken # Replace with your actual endpoint
577
+ app = create_app(API_ENDPOINT)
578
+ app.launch(
579
+ server_name="0.0.0.0",
580
+ server_port=7860,
581
+ share=False,
582
+ favicon_path="🌿" # Optional: Add path to plant icon
583
  )