XMMR12 commited on
Commit
fa3daba
ยท
verified ยท
1 Parent(s): 0ae6334

Gradio Hackathon project

Browse files

Gradio Hackathon project for :
Agents-MCP-Hackathon
tags: agent-demo-track

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