Spaces:
Sleeping
Sleeping
File size: 26,851 Bytes
5fe000d d563681 5fe000d d563681 2b58ee1 d563681 5fe000d 2b58ee1 5fe000d 8dabb5d 5fe000d 70baa7c 5fe000d 2b58ee1 5fe000d 70baa7c d563681 c9dbb79 d563681 70baa7c 5fe000d 99e4241 |
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 |
from typing import List, Tuple, Dict, Any, Generator
import sqlite3
import urllib
import requests
import os
import gradio as gr
import time
from openai import OpenAI
#make token for every part of calls to detect issues faster in testing or in beta release:
#fast-api
GEMMA_TOKEN=os.environ.get("NEBIUS_API_KEY_GEMMA")
#To be used for the main requests
DEEPSEEKv3_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK")
DEEPSEEKv3_FAST_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK_FAST")
#unused for getting all symptoms from plants db
def get_all_treatable_conditions()->List:
#Gets all the symptoms:
conn = sqlite3.connect('plants.db')
# Create a cursor object
cursor = conn.cursor()
# Execute a query to retrieve data
cursor.execute("SELECT treatable_conditions FROM 'plants'")
# Fetch all results
rows = cursor.fetchall()
# Print the results
treatable_conditions=[]
for row in rows:
treatable_conditions.append(row)
# Close the connection
conn.close()
return treatable_conditions
#Unused for writing db
def write_symptoms_into_db(data_list):
"""Initialize SQLite database"""
try:
conn = sqlite3.connect('plants.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS symptoms (name TEXT)''')
conn.commit()
for each in data_list:
insert_sql = f'''INSERT INTO 'symptoms' (name) VALUES ("{each}")'''
c.execute(insert_sql)
conn.commit()
print("Database created successfully!")
conn.close()
except sqlite3.Error as e:
print(f"An error occurred: {e}")
#@tool
def get_unique_symptoms(list_text:List[str])->List[str]:
"""Processes and deduplicates symptom descriptions into a normalized list of unique symptoms.
Performs comprehensive text processing to:
- Extract individual symptoms from complex descriptions
- Normalize formatting (removes common connecting words and punctuation)
- Deduplicate symptoms while preserving original meaning
- Handle multiple input formats (strings and tuples)
Args:
list_text: List of symptom descriptions in various formats.
Each element can be:
- String: "fever and headache"
- Tuple: ("been dizzy and nauseous",)
Example: ["fatigue, nausea", "headache and fever"]
Returns:
List of unique, alphabetically sorted symptom terms in lowercase.
Returns empty list if:
- Input is empty
- No valid strings found
Example: ['bleed', 'fever', 'headache']
Processing Details:
1. Text normalization:
- Removes connecting words ("and", "also", "like", etc.)
- Replaces punctuation with spaces
- Converts to lowercase
2. Special cases:
- Handles tuple inputs by extracting first element
- Skips non-string/non-tuple elements with warning
3. Deduplication:
- Uses set operations for uniqueness
- Returns sorted list for consistency
Examples:
>>> get_unique_symptoms(["fever and headache", "bleed"])
['bleed', 'fever', 'headache']
>>> get_unique_symptoms([("been dizzy",), "nausea"])
['dizzy', 'nausea']
>>> get_unique_symptoms([123, None])
No Correct DataType
[]
Edge Cases:
- Empty strings are filtered out
- Single-word symptoms preserved
- Mixed punctuation handled
- Warning printed for invalid types
"""
all_symptoms = []
for text in list_text:
# Handle potential errors in input text. Crucial for robustness.
if type(text)==tuple:
text=text[0]
symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
all_symptoms.extend(symptoms)
elif type(text)==str and len(text)>1:
symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
all_symptoms.extend(symptoms)
else:
print ("No Correct DataType or 1 charater text O.o")
#if not isinstance(text, str) or not text:
#continue
unique_symptoms = sorted(list(set(all_symptoms))) # Use set to get unique items, then sort for consistency
return unique_symptoms
#@tool
def lookup_symptom_and_plants(symptom_input:str)->List:
"""Search for medicinal plants that can treat a given symptom by querying a SQLite database.
This function performs a case-insensitive search in the database for:
1. First looking for an exact or partial match of the symptom
2. If not found, searches for individual words from the symptom input
3. Returns all plants that list the matched symptom in their treatable conditions
Args:
symptom_input (str): The symptom to search for (e.g., "headache", "stomach pain").
Can be a single symptom or multiple words. Leading/trailing
whitespace is automatically trimmed.
Returns:
List[dict]: A list of plant dictionaries containing all columns from the 'plants' table
where the symptom appears in treatable_conditions. Each dictionary represents
one plant with column names as keys. Returns empty list if:
- Symptom not found
- No plants treat the symptom
- Database error occurs
Raises:
sqlite3.Error: If there's a database connection or query error (handled internally,
returns empty list but prints error to console)
Notes:
- The database connection is opened and closed within this function
- Uses LIKE queries with wildcards for flexible matching
- Treatable conditions are expected to be stored as comma-separated values
- Case-insensitive matching is performed by converting to lowercase
- The function will attempt to match individual words if full phrase not found
Example:
>>> lookup_symptom_and_plants("headache")
[{'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/'}]
>>> lookup_symptom_and_plants("unknown symptom")
[]
"""
symptom_lower = symptom_input.strip().lower()
try:
conn = sqlite3.connect('plants.db')
conn.row_factory = sqlite3.Row
c = conn.cursor()
# Check if the symptom exists in symptoms table (case-insensitive)
c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{symptom_lower}%"''')
result = c.fetchone()
#if result:
# result=result[0]
if not result:
#get any 1 symptom only in case the text is not showing.
symptoms=symptom_lower.split(" ")
for each in symptoms:
c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{each}%"''')
result = c.fetchone()
if result:
print(f"Symptom '{symptom_input}' finally found in the database.")
#result=result[0]
symptom_lower=each
break
if not result:
print(f"Symptom '{symptom_input}' not found in the database.")
conn.close()
return []
# If symptom exists, search in plants table for related plants
# Assuming 'TreatableConditions' is a comma-separated string
query = f"""SELECT * FROM plants WHERE LOWER(treatable_conditions) LIKE "%{symptom_lower}%" """
c.execute(query)
plants_rows = c.fetchall()
plants_list = []
for row in plants_rows:
# Convert row to dict for easier handling
plant_dict = {key: row[key] for key in row.keys()}
plants_list.append(plant_dict)
conn.close()
return plants_list
except sqlite3.Error as e:
print(f"Database error: {e}")
return []
def analyze_symptoms_from_text_ai(text_input: str) -> str:
"""
Analyze user-provided text to extract medical symptoms in CSV format.
Args:
text_input: Raw text description of health condition
Returns:
str: Comma-separated list of symptoms in CSV format
Example:
>>> analyze_symptoms_from_text_ai("I have headache and nausea")
'headache,nausea'
"""
client = OpenAI(
base_url="https://api.studio.nebius.com/v1/",
api_key=GEMMA_TOKEN
)
try:
response = client.chat.completions.create(
model="google/gemma-2-2b-it",
max_tokens=512,
temperature=0.5,
top_p=0.9,
extra_body={"top_k": 50},
messages=[
{
"role": "system",
"content": """You are a medical symptom extractor.
Analyze the text and return ONLY a comma-separated list of symptoms in CSV format.
Example input: "I have headache and feel nauseous"
Example output: headache,nausea
Return "" , IF NO SYMTPOMS OR DIESEASE IN THE TEXT"""
},
{
"role": "user",
"content": f"Analyze this text for symptoms and list them in CSV format: {text_input}"
}
]
)
# Extract and clean the response
try:
symptoms_csv = response.choices[0].message.content.strip()
return symptoms_csv
except Exception as e:
print ("Error:",e,"\nType 'response': ",type(response),"\n",response)
except Exception as e:
print(f"Error analyzing symptoms: {str(e)}")
return ""
#@tool
def full_treatment_answer_ai(user_input: str) -> str:
"""
Searches for plant treatments based on user symptoms using Nebius API.
Args:
user_input: User's symptom description
Returns:
str: Complete treatment plan with plant recommendations and details
"""
# Initialize Nebius client
client = OpenAI(
base_url="https://api.studio.nebius.com/v1/",
api_key=DEEPSEEKv3_TOKEN
)
# Step 1: Extract symptoms from user input
text_symptoms = user_input#analyze_symptoms_from_text_ai(user_input)
symptoms_list = text_symptoms.split(",")
symptoms = get_unique_symptoms(symptoms_list)
if not symptoms:
return "Could not identify any specific symptoms. Please describe your condition in more detail."
# Step 2: Find relevant plants for each symptom
all_related_plants = []
for symptom in symptoms:
related_plants = lookup_symptom_and_plants(symptom)
all_related_plants.extend(related_plants)
# Step 3: Prepare the prompt for Nebius API
plants_info = ""
if all_related_plants:
plants_info = "Here are some plants that might be relevant:\n"
for plant in all_related_plants[:6]: # Limit to top 6 plants
plants_info += f"""\nPlant: {plant['name']}
{plant['description']}
Cures: {plant['treatable_conditions']}
Dosage: {plant['dosage']}\n"""
else:
plants_info = "I dont know specific plants for these symptoms. please get useful plants from anywhere or any other sources"
prompt = f"""I have these symptoms: {", ".join(symptoms)}.
{plants_info}
Please analyze my symptoms and recommend the most appropriate plant remedy.
Consider the symptoms, when to use each plant, dosage, and how to use it.
Provide your recommendation in this format:
**Recommended Plant**: [plant name]
**Reason**: [why this plant is good for these symptoms]
**Dosage**: [recommended dosage]
**Instructions**: [how to use it]
**Image**: [mention if image is available]
If multiple plants could work well, you may recommend up to 3 options."""
# Step 4: Call Nebius API for treatment recommendation
try:
response = client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3-0324-fast",
max_tokens=1024, # Increased for detailed responses
temperature=0.3,
top_p=0.95,
messages=[
{
"role": "system",
"content": """You are a professional botanist assistant specializing in medicinal plants.
Provide accurate, science-backed recommendations for plant-based treatments.
Include dosage, preparation methods, and safety considerations."""
},
{
"role": "user",
"content": prompt
}
]
)
final_result = response.choices[0].message.content
# Step 5: Append detailed plant information if available
if all_related_plants:
final_result += "\n---\nMore Details for Recommended Plants:\n"
for plant in all_related_plants[:3]: # Show details for top 3 plants
final_result += f"""
**Plant Name**: {plant['name']}
**Scientific Name**: {plant['scientific_name']}
**Other Names**: {plant['alternate_names']}
**Description**: {plant['description']}
**Treatable Conditions**: {plant['treatable_conditions']}
**Preparation**: {plant['preparation_methods']}
**Dosage**: {plant['dosage']}
**Side Effects**: {plant['side_effects']}
**Contraindications**: {plant['contraindications']}
**Sources**: {plant['sources']}
"""
return final_result
except Exception as e:
print(f"Error generating treatment plan: {str(e)}")
return "Sorry, I couldn't generate a treatment plan at this time. Please try again later."
#example:
# user_input="""i feel some pain in head and i feel dizzy""" #user input
# prompt='''Analyze the possible symptoms and list them in only csv format by comma in 1 line,from the following text : """{user_input}"""'''
# output='pain in head,dizzy'
# symptoms=output.split(",")
# get_unique_symptoms(symptoms)
#Filter all conditions:
#all_treatment_conditions=get_all_treatable_conditions()
#unique_symptoms=get_unique_symptoms(all_treatment_conditions)
#write_symptoms_into_db(unique_symptoms)
#related_plants = lookup_symptom_and_plants("fever")
'''
user_input = "fever"
related_plants = lookup_symptom_and_plants(user_input)
if related_plants:
print(f"Plants related to '{user_input}':")
for plant in related_plants:
print(f"- {plant['name']}")
else:
print(f"No plants found for symptom '{user_input}'.")
'''
def is_symtoms_intext_ai(text_input:str)->str: #used instead of: analyze_symptoms_from_text_ai()
"""Gives Symptoms or "" if no symptoms """
response_text=analyze_symptoms_from_text_ai(text_input)
if response_text and len(response_text)>2:
if "error" not in response_text.lower():
return response_text
return ""
class BotanistAssistant:
def __init__(self, api_endpoint: str = "https://api.studio.nebius.com/v1/"): #https://api.studio.nebius.com/v1/chat/completions
self.api_endpoint = api_endpoint
self.system_message = "You are a botanist assistant that extracts and structures information about medicinal plants."
self.client = OpenAI(
base_url="https://api.studio.nebius.com/v1/",
api_key=DEEPSEEKv3_FAST_TOKEN
)
def _build_chat_history(self, history: List[Tuple[str, str]]) -> List[Dict[str, str]]:
"""Formats chat history into API-compatible message format."""
messages = [{"role": "system", "content": self.system_message}]
for user_msg, bot_msg in history:
if user_msg:
messages.append({"role": "user", "content": user_msg})
if bot_msg:
messages.append({"role": "assistant", "content": bot_msg})
return messages
def _get_tools_schema(self) -> List[Dict[str, Any]]:
"""Returns the complete tools schema for plant medicine analysis."""
return [
{
"name": "get_unique_symptoms",
"description": "Extracts and remove duplicates of symptoms from text input. Handles natural language processing to identify individual symptoms from complex descriptions.",
"api": {
"name": "get_unique_symptoms",
"parameters": {
"type": "object",
"properties": {
"list_text": {
"type": "array",
"items": {"type": "string"},
"description": "List of symptom descriptions (strings or tuples)"
}
},
"required": ["list_text"]
}
}
},
{
"name": "lookup_symptom_and_plants",
"description": "Finds medicinal plants associated with specific symptoms from the database. Returns matching plants with their treatment properties.",
"api": {
"name": "lookup_symptom_and_plants",
"parameters": {
"type": "object",
"properties": {
"symptom_input": {
"type": "string",
"description": "Individual symptom to search for plant treatments"
}
},
"required": ["symptom_input"]
}
}
},
{
"name": "analyze_symptoms_from_text_ai",
"description": "Analyzes text to extract medical symptoms and returns them in CSV format.",
"api": {
"name": "analyze_symptoms_from_text_ai",
"parameters": {
"type": "object",
"properties": {
"text_input": {
"type": "string",
"description": "Raw text description of health condition"
}
},
"required": ["text_input"]
}
}
},
{
"name": "full_treatment_answer_ai",
"description": "Generates complete plant-based treatment plans for given symptoms, including dosage, preparation methods, and safety information.",
"api": {
"name": "full_treatment_answer_ai",
"parameters": {
"type": "object",
"properties": {
"user_input": {
"type": "string",
"description": "User's description of symptoms or health condition"
}
},
"required": ["user_input"]
}
}
}
]
def _call_tool(self, tool_name: str, parameters: Dict[str, Any]) -> Any:
"""Executes the specified tool with given parameters."""
if tool_name == "full_treatment_answer_ai":
return self.full_treatment_answer_ai(**parameters)
elif tool_name == "analyze_symptoms_from_text_ai":
return self.analyze_symptoms_from_text_ai(**parameters)
else:
raise ValueError(f"Unknown tool: {tool_name}")
def _call_assistant_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
"""Makes the API call to Nebius assistant service with no tool support.""" #TODO tool
try:
response = self.client.chat.completions.create(
model="deepseek-ai/DeepSeek-V3-0324-fast",
max_tokens=1024,
temperature=0.3,
top_p=0.9,
extra_body={"top_k": 50},
messages=messages)
return response.choices[0].message.content #TODO if not working
#return response.to_json()
except Exception as e:
print(f"Error: {str(e)}")
return {"error": str(e)}
#assistant = BotanistAssistant()
# Simple query
# Treatment query (will automatically use tools)
#for response in assistant.respond("I have migraines and trouble sleeping", []):
# print(response)
def respond(
self,
message: str,
history: List[Tuple[str, str]],
system_message: str = None
) -> Generator[str, None, None]:
"""Handles the chat response generation."""
# Update system message if provided
if system_message:
self.system_message = system_message
# Build API payload
messages = self._build_chat_history(history)
messages.append({"role": "user", "content": message})
# Get API response
api_response = self._call_assistant_api(messages)
# Process response
if "error" in api_response:
yield "Error: Could not connect to the assistant service. Please try again later."
return
treatment_response=""
symtoms_intext=is_symtoms_intext_ai(message)
if symtoms_intext:
#time.sleep(1.6)
treatment_response=full_treatment_answer_ai(symtoms_intext)
#yield treatment_response
if len(treatment_response):
treatment_response="\n**I have found that this may help you alot:**\n"+treatment_response
yield treatment_response
# Get treatment information
#treatment_response = search_for_treatment_answer_ai(message)
#yield treatment_response # First yield the treatment info
# Stream additional assistant responses if available
if api_response:
yield api_response
'''
if "choices" in api_response:
for choice in api_response["choices"][0]:
if "message" in choice and "content" in choice["message"]:
yield choice["message"]["content"]
'''
def create_app(api_endpoint: str = "https://api.studio.nebius.com/v1/") -> gr.Blocks:
"""Creates and configures the Gradio interface."""
assistant = BotanistAssistant(api_endpoint)
with gr.Blocks(title="๐ฟ Botanist Assistant", theme=gr.themes.Soft()) as demo:
gr.Markdown("# ๐ฟ Natural Medical Assistant")
gr.Markdown("Describe your symptoms to get natural plant-based treatment recommendations")
with gr.Row():
with gr.Column(scale=3):
chat = gr.ChatInterface(
assistant.respond,
additional_inputs=[
gr.Textbox(
value=assistant.system_message,
label="System Role",
interactive=True
)
]
)
with gr.Column(scale=1):
gr.Markdown("### Common Symptoms")
gr.Examples(
examples=[
["I have headache and fever"],
["got nausea, and injury caused bleeding"],
["I feel insomnia, and anxiety"],
["I am suffering from ADHD"]
],
inputs=chat.textbox,
label="Try these examples"
)
gr.Markdown("---")
gr.Markdown("""> Note: Recommendations can work as real cure treatment but you can consider it as informational purposes only.
Also You can consult a Natrual healthcare professional before use.""")
return demo
if __name__ == "__main__":
API_ENDPOINT = "https://api.studio.nebius.com/v1/" # Replace with your actual endpoint
app = create_app()
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
favicon_path="๐ฟ" # Optional: Add path to plant icon
) |