XMMR12 commited on
Commit
5fe000d
ยท
verified ยท
1 Parent(s): a2f0b14

openAI lib , no api request

Browse files
Files changed (1) hide show
  1. app.py +633 -635
app.py CHANGED
@@ -1,636 +1,634 @@
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
- import time
8
- from openai import OpenAI
9
-
10
- #make token for every part of calls to detect issues faster in testing or in beta release:
11
- #fast-api
12
-
13
- GEMMA_TOKEN=os.environ.get("NEBIUS_API_KEY_GEMMA")
14
- #To be used for the main requests
15
- DEEPSEEKv3_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK")
16
- DEEPSEEKv3_FAST_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK_FAST")
17
-
18
- #unused for getting all symptoms from plants db
19
- def get_all_treatable_conditions()->List:
20
- #Gets all the symptoms:
21
- conn = sqlite3.connect('plants.db')
22
- # Create a cursor object
23
- cursor = conn.cursor()
24
- # Execute a query to retrieve data
25
- cursor.execute("SELECT treatable_conditions FROM 'plants'")
26
- # Fetch all results
27
- rows = cursor.fetchall()
28
- # Print the results
29
- treatable_conditions=[]
30
- for row in rows:
31
- treatable_conditions.append(row)
32
- # Close the connection
33
- conn.close()
34
- return treatable_conditions
35
-
36
- #Unused for writing db
37
- def write_symptoms_into_db(data_list):
38
- """Initialize SQLite database"""
39
- try:
40
- conn = sqlite3.connect('plants.db')
41
- c = conn.cursor()
42
- c.execute('''CREATE TABLE IF NOT EXISTS symptoms (name TEXT)''')
43
- conn.commit()
44
- for each in data_list:
45
- insert_sql = f'''INSERT INTO 'symptoms' (name) VALUES ("{each}")'''
46
- c.execute(insert_sql)
47
- conn.commit()
48
- print("Database created successfully!")
49
- conn.close()
50
- except sqlite3.Error as e:
51
- print(f"An error occurred: {e}")
52
-
53
- #@tool
54
- def get_unique_symptoms(list_text:List[str])->List[str]:
55
- """Processes and deduplicates symptom descriptions into a normalized list of unique symptoms.
56
-
57
- Performs comprehensive text processing to:
58
- - Extract individual symptoms from complex descriptions
59
- - Normalize formatting (removes common connecting words and punctuation)
60
- - Deduplicate symptoms while preserving original meaning
61
- - Handle multiple input formats (strings and tuples)
62
-
63
- Args:
64
- list_text: List of symptom descriptions in various formats.
65
- Each element can be:
66
- - String: "fever and headache"
67
- - Tuple: ("been dizzy and nauseous",)
68
- Example: ["fatigue, nausea", "headache and fever"]
69
-
70
- Returns:
71
- List of unique, alphabetically sorted symptom terms in lowercase.
72
- Returns empty list if:
73
- - Input is empty
74
- - No valid strings found
75
- Example: ['bleed', 'fever', 'headache']
76
-
77
- Processing Details:
78
- 1. Text normalization:
79
- - Removes connecting words ("and", "also", "like", etc.)
80
- - Replaces punctuation with spaces
81
- - Converts to lowercase
82
- 2. Special cases:
83
- - Handles tuple inputs by extracting first element
84
- - Skips non-string/non-tuple elements with warning
85
- 3. Deduplication:
86
- - Uses set operations for uniqueness
87
- - Returns sorted list for consistency
88
-
89
- Examples:
90
- >>> get_unique_symptoms(["fever and headache", "bleed"])
91
- ['bleed', 'fever', 'headache']
92
-
93
- >>> get_unique_symptoms([("been dizzy",), "nausea"])
94
- ['dizzy', 'nausea']
95
-
96
- >>> get_unique_symptoms([123, None])
97
- No Correct DataType
98
- []
99
-
100
- Edge Cases:
101
- - Empty strings are filtered out
102
- - Single-word symptoms preserved
103
- - Mixed punctuation handled
104
- - Warning printed for invalid types
105
- """
106
-
107
- all_symptoms = []
108
-
109
- for text in list_text:
110
- # Handle potential errors in input text. Crucial for robustness.
111
- if type(text)==tuple:
112
- text=text[0]
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
- elif type(text)==str and len(text)>1:
117
- symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
118
- symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
119
- all_symptoms.extend(symptoms)
120
- else:
121
- print ("No Correct DataType or 1 charater text O.o")
122
- #if not isinstance(text, str) or not text:
123
- #continue
124
-
125
- unique_symptoms = sorted(list(set(all_symptoms))) # Use set to get unique items, then sort for consistency
126
-
127
- return unique_symptoms
128
-
129
- #@tool
130
- def lookup_symptom_and_plants(symptom_input:str)->List:
131
- """Search for medicinal plants that can treat a given symptom by querying a SQLite database.
132
-
133
- This function performs a case-insensitive search in the database for:
134
- 1. First looking for an exact or partial match of the symptom
135
- 2. If not found, searches for individual words from the symptom input
136
- 3. Returns all plants that list the matched symptom in their treatable conditions
137
-
138
- Args:
139
- symptom_input (str): The symptom to search for (e.g., "headache", "stomach pain").
140
- Can be a single symptom or multiple words. Leading/trailing
141
- whitespace is automatically trimmed.
142
-
143
- Returns:
144
- List[dict]: A list of plant dictionaries containing all columns from the 'plants' table
145
- where the symptom appears in treatable_conditions. Each dictionary represents
146
- one plant with column names as keys. Returns empty list if:
147
- - Symptom not found
148
- - No plants treat the symptom
149
- - Database error occurs
150
-
151
- Raises:
152
- sqlite3.Error: If there's a database connection or query error (handled internally,
153
- returns empty list but prints error to console)
154
-
155
- Notes:
156
- - The database connection is opened and closed within this function
157
- - Uses LIKE queries with wildcards for flexible matching
158
- - Treatable conditions are expected to be stored as comma-separated values
159
- - Case-insensitive matching is performed by converting to lowercase
160
- - The function will attempt to match individual words if full phrase not found
161
-
162
- Example:
163
- >>> lookup_symptom_and_plants("headache")
164
- [{'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/'}]
165
-
166
- >>> lookup_symptom_and_plants("unknown symptom")
167
- []
168
- """
169
- symptom_lower = symptom_input.strip().lower()
170
- try:
171
- conn = sqlite3.connect('plants.db')
172
- conn.row_factory = sqlite3.Row
173
- c = conn.cursor()
174
-
175
- # Check if the symptom exists in symptoms table (case-insensitive)
176
- c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{symptom_lower}%"''')
177
- result = c.fetchone()
178
- #if result:
179
- # result=result[0]
180
-
181
- if not result:
182
- #get any 1 symptom only in case the text is not showing.
183
- symptoms=symptom_lower.split(" ")
184
- for each in symptoms:
185
- c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{each}%"''')
186
- result = c.fetchone()
187
- if result:
188
- print(f"Symptom '{symptom_input}' finally found in the database.")
189
- #result=result[0]
190
- symptom_lower=each
191
- break
192
- if not result:
193
- print(f"Symptom '{symptom_input}' not found in the database.")
194
- conn.close()
195
- return []
196
-
197
- # If symptom exists, search in plants table for related plants
198
- # Assuming 'TreatableConditions' is a comma-separated string
199
- query = f"""SELECT * FROM plants WHERE LOWER(treatable_conditions) LIKE "%{symptom_lower}%" """
200
- c.execute(query)
201
- plants_rows = c.fetchall()
202
-
203
- plants_list = []
204
- for row in plants_rows:
205
- # Convert row to dict for easier handling
206
- plant_dict = {key: row[key] for key in row.keys()}
207
- plants_list.append(plant_dict)
208
-
209
- conn.close()
210
- return plants_list
211
-
212
- except sqlite3.Error as e:
213
- print(f"Database error: {e}")
214
- return []
215
-
216
-
217
-
218
-
219
- def analyze_symptoms_from_text_ai(text_input: str) -> str:
220
- """
221
- Analyze user-provided text to extract medical symptoms in CSV format.
222
-
223
- Args:
224
- text_input: Raw text description of health condition
225
-
226
- Returns:
227
- str: Comma-separated list of symptoms in CSV format
228
-
229
- Example:
230
- >>> analyze_symptoms_from_text_ai("I have headache and nausea")
231
- 'headache,nausea'
232
- """
233
- client = OpenAI(
234
- base_url="https://api.studio.nebius.com",
235
- api_key=GEMMA_TOKEN
236
- )
237
-
238
- try:
239
- response = client.chat.completions.create(
240
- model="google/gemma-2-2b-it",
241
- max_tokens=512,
242
- temperature=0.5,
243
- top_p=0.9,
244
- extra_body={"top_k": 50},
245
- messages=[
246
- {
247
- "role": "system",
248
- "content": """You are a medical symptom extractor.
249
- Analyze the text and return ONLY a comma-separated list of symptoms in CSV format.
250
- Example input: "I have headache and feel nauseous"
251
- Example output: headache,nausea
252
- Return "" , IF NO SYMTPOMS OR DIESEASE IN THE TEXT"""
253
- },
254
- {
255
- "role": "user",
256
- "content": f"Analyze this text for symptoms and list them in CSV format: {text_input}"
257
- }
258
- ]
259
- )
260
-
261
- # Extract and clean the response
262
- symptoms_csv = response.choices.message.content.strip()
263
- return symptoms_csv
264
-
265
- except Exception as e:
266
- print(f"Error analyzing symptoms: {str(e)}")
267
- return ""
268
-
269
- #@tool
270
- def full_treatment_answer_ai(user_input: str) -> str:
271
- """
272
- Searches for plant treatments based on user symptoms using Nebius API.
273
-
274
- Args:
275
- user_input: User's symptom description
276
-
277
- Returns:
278
- str: Complete treatment plan with plant recommendations and details
279
- """
280
- # Initialize Nebius client
281
- client = OpenAI(
282
- base_url="https://api.studio.nebius.com/",
283
- api_key=DEEPSEEKv3_TOKEN
284
- )
285
-
286
- # Step 1: Extract symptoms from user input
287
- text_symptoms = user_input#analyze_symptoms_from_text_ai(user_input)
288
- symptoms_list = text_symptoms.split(",")
289
- symptoms = get_unique_symptoms(symptoms_list)
290
-
291
- if not symptoms:
292
- return "Could not identify any specific symptoms. Please describe your condition in more detail."
293
-
294
- # Step 2: Find relevant plants for each symptom
295
- all_related_plants = []
296
- for symptom in symptoms:
297
- related_plants = lookup_symptom_and_plants(symptom)
298
- all_related_plants.extend(related_plants)
299
-
300
- # Step 3: Prepare the prompt for Nebius API
301
- plants_info = ""
302
- if all_related_plants:
303
- plants_info = "Here are some plants that might be relevant:\n"
304
- for plant in all_related_plants[:6]: # Limit to top 6 plants
305
- plants_info += f"""\nPlant: {plant['name']}
306
- {plant['description']}
307
- Cures: {plant['treatable_conditions']}
308
- Dosage: {plant['dosage']}\n"""
309
- else:
310
- plants_info = "I dont know specific plants for these symptoms. please get useful plants from anywhere or any other sources"
311
-
312
- prompt = f"""I have these symptoms: {", ".join(symptoms)}.
313
-
314
- {plants_info}
315
-
316
- Please analyze my symptoms and recommend the most appropriate plant remedy.
317
- Consider the symptoms, when to use each plant, dosage, and how to use it.
318
- Provide your recommendation in this format:
319
-
320
- **Recommended Plant**: [plant name]
321
- **Reason**: [why this plant is good for these symptoms]
322
- **Dosage**: [recommended dosage]
323
- **Instructions**: [how to use it]
324
- **Image**: [mention if image is available]
325
-
326
- If multiple plants could work well, you may recommend up to 3 options."""
327
-
328
- # Step 4: Call Nebius API for treatment recommendation
329
- try:
330
- response = client.chat.completions.create(
331
- model="deepseek-ai/DeepSeek-V3-0324-fast",
332
- max_tokens=1024, # Increased for detailed responses
333
- temperature=0.3,
334
- top_p=0.95,
335
- messages=[
336
- {
337
- "role": "system",
338
- "content": """You are a professional botanist assistant specializing in medicinal plants.
339
- Provide accurate, science-backed recommendations for plant-based treatments.
340
- Include dosage, preparation methods, and safety considerations."""
341
- },
342
- {
343
- "role": "user",
344
- "content": prompt
345
- }
346
- ]
347
- )
348
-
349
- final_result = response.choices.message.content
350
-
351
- # Step 5: Append detailed plant information if available
352
- if all_related_plants:
353
- final_result += "\n---\nMore Details for Recommended Plants:\n"
354
- for plant in all_related_plants[:3]: # Show details for top 3 plants
355
- final_result += f"""
356
- **Plant Name**: {plant['name']}
357
- **Scientific Name**: {plant['scientific_name']}
358
- **Other Names**: {plant['alternate_names']}
359
- **Description**: {plant['description']}
360
- **Treatable Conditions**: {plant['treatable_conditions']}
361
- **Preparation**: {plant['preparation_methods']}
362
- **Dosage**: {plant['dosage']}
363
- **Side Effects**: {plant['side_effects']}
364
- **Contraindications**: {plant['contraindications']}
365
- **Sources**: {plant['sources']}
366
- """
367
-
368
- return final_result
369
-
370
- except Exception as e:
371
- print(f"Error generating treatment plan: {str(e)}")
372
- return "Sorry, I couldn't generate a treatment plan at this time. Please try again later."
373
-
374
- #example:
375
- # user_input="""i feel some pain in head and i feel dizzy""" #user input
376
- # prompt='''Analyze the possible symptoms and list them in only csv format by comma in 1 line,from the following text : """{user_input}"""'''
377
- # output='pain in head,dizzy'
378
- # symptoms=output.split(",")
379
- # get_unique_symptoms(symptoms)
380
-
381
-
382
- #Filter all conditions:
383
- #all_treatment_conditions=get_all_treatable_conditions()
384
- #unique_symptoms=get_unique_symptoms(all_treatment_conditions)
385
- #write_symptoms_into_db(unique_symptoms)
386
- #related_plants = lookup_symptom_and_plants("fever")
387
-
388
- '''
389
- user_input = "fever"
390
- related_plants = lookup_symptom_and_plants(user_input)
391
- if related_plants:
392
- print(f"Plants related to '{user_input}':")
393
- for plant in related_plants:
394
- print(f"- {plant['name']}")
395
- else:
396
- print(f"No plants found for symptom '{user_input}'.")
397
- '''
398
- def is_symtoms_intext_ai(text_input:str)->str: #used instead of: analyze_symptoms_from_text_ai()
399
- """Gives Symptoms or "" if no symptoms """
400
- response_text=analyze_symptoms_from_text_ai(text_input)
401
- if len(response_text)>2:
402
- if "error" not in response_text.lower():
403
- return response_text
404
- return ""
405
-
406
- class BotanistAssistant:
407
- def __init__(self, api_endpoint: str = "https://api.studio.nebius.com/v1/chat/completions"):
408
- self.api_endpoint = api_endpoint
409
- self.system_message = "You are a botanist assistant that extracts and structures information about medicinal plants."
410
- self.client = OpenAI(
411
- base_url="https://api.studio.nebius.com",
412
- api_key=DEEPSEEKv3_FAST_TOKEN
413
- )
414
-
415
- def _build_chat_history(self, history: List[Tuple[str, str]]) -> List[Dict[str, str]]:
416
- """Formats chat history into API-compatible message format."""
417
- messages = [{"role": "system", "content": self.system_message}]
418
- for user_msg, bot_msg in history:
419
- if user_msg:
420
- messages.append({"role": "user", "content": user_msg})
421
- if bot_msg:
422
- messages.append({"role": "assistant", "content": bot_msg})
423
- return messages
424
-
425
-
426
- def _get_tools_schema(self) -> List[Dict[str, Any]]:
427
- """Returns the complete tools schema for plant medicine analysis."""
428
- return [
429
- {
430
- "name": "get_unique_symptoms",
431
- "description": "Extracts and remove duplicates of symptoms from text input. Handles natural language processing to identify individual symptoms from complex descriptions.",
432
- "api": {
433
- "name": "get_unique_symptoms",
434
- "parameters": {
435
- "type": "object",
436
- "properties": {
437
- "list_text": {
438
- "type": "array",
439
- "items": {"type": "string"},
440
- "description": "List of symptom descriptions (strings or tuples)"
441
- }
442
- },
443
- "required": ["list_text"]
444
- }
445
- }
446
- },
447
- {
448
- "name": "lookup_symptom_and_plants",
449
- "description": "Finds medicinal plants associated with specific symptoms from the database. Returns matching plants with their treatment properties.",
450
- "api": {
451
- "name": "lookup_symptom_and_plants",
452
- "parameters": {
453
- "type": "object",
454
- "properties": {
455
- "symptom_input": {
456
- "type": "string",
457
- "description": "Individual symptom to search for plant treatments"
458
- }
459
- },
460
- "required": ["symptom_input"]
461
- }
462
- }
463
- },
464
- {
465
- "name": "analyze_symptoms_from_text_ai",
466
- "description": "Analyzes text to extract medical symptoms and returns them in CSV format.",
467
- "api": {
468
- "name": "analyze_symptoms_from_text_ai",
469
- "parameters": {
470
- "type": "object",
471
- "properties": {
472
- "text_input": {
473
- "type": "string",
474
- "description": "Raw text description of health condition"
475
- }
476
- },
477
- "required": ["text_input"]
478
- }
479
- }
480
- },
481
- {
482
- "name": "full_treatment_answer_ai",
483
- "description": "Generates complete plant-based treatment plans for given symptoms, including dosage, preparation methods, and safety information.",
484
- "api": {
485
- "name": "full_treatment_answer_ai",
486
- "parameters": {
487
- "type": "object",
488
- "properties": {
489
- "user_input": {
490
- "type": "string",
491
- "description": "User's description of symptoms or health condition"
492
- }
493
- },
494
- "required": ["user_input"]
495
- }
496
- }
497
- }
498
- ]
499
-
500
- def _call_tool(self, tool_name: str, parameters: Dict[str, Any]) -> Any:
501
- """Executes the specified tool with given parameters."""
502
- if tool_name == "full_treatment_answer_ai":
503
- return self.full_treatment_answer_ai(**parameters)
504
- elif tool_name == "analyze_symptoms_from_text_ai":
505
- return self.analyze_symptoms_from_text_ai(**parameters)
506
- else:
507
- raise ValueError(f"Unknown tool: {tool_name}")
508
-
509
- def _call_assistant_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
510
- """Makes the API call to Nebius assistant service with tool support."""
511
- payload = {
512
- "model": "deepseek-ai/DeepSeek-V3-0324-fast",
513
- "messages": messages,
514
- "tools": self._get_tools_schema(),
515
- "tool_choice": "auto",
516
- "temperature": 0.3,
517
- "max_tokens": 1024
518
- }
519
-
520
- try:
521
- response = requests.post(
522
- self.api_endpoint,
523
- json=payload,
524
- headers={
525
- "Content-Type": "application/json",
526
- "Authorization": f"Bearer {DEEPSEEKv3_FAST_TOKEN}"
527
- },
528
- timeout=50 #50 secs timeout
529
- )
530
- response.raise_for_status()
531
- return response.json()
532
- except requests.exceptions.RequestException as e:
533
- print(f"API request failed: {str(e)}")
534
- return {"error": str(e)}
535
-
536
-
537
- #assistant = BotanistAssistant()
538
- # Simple query
539
- # Treatment query (will automatically use tools)
540
- #for response in assistant.respond("I have migraines and trouble sleeping", []):
541
- # print(response)
542
-
543
- def respond(
544
- self,
545
- message: str,
546
- history: List[Tuple[str, str]],
547
- system_message: str = None
548
- ) -> Generator[str, None, None]:
549
- """Handles the chat response generation."""
550
- # Update system message if provided
551
- if system_message:
552
- self.system_message = system_message
553
-
554
- # Build API payload
555
- messages = self._build_chat_history(history)
556
- messages.append({"role": "user", "content": message})
557
-
558
-
559
- # Get API response
560
- api_response = self._call_assistant_api(messages)
561
-
562
- # Process response
563
- if "error" in api_response:
564
- yield "Error: Could not connect to the assistant service. Please try again later."
565
- return
566
-
567
-
568
- treatment_response=""
569
- symtoms_intext=is_symtoms_intext_ai(message)
570
- if symtoms_intext:
571
- #time.sleep(1.6)
572
- treatment_response=full_treatment_answer_ai(symtoms_intext)
573
- #yield treatment_response
574
-
575
- if len(treatment_response):
576
- treatment_response="\n**I have found that this may help you alot:**\n"+treatment_response
577
- yield treatment_response
578
-
579
- # Get treatment information
580
- #treatment_response = search_for_treatment_answer_ai(message)
581
- #yield treatment_response # First yield the treatment info
582
-
583
- # Stream additional assistant responses if available
584
- if "choices" in api_response:
585
- for choice in api_response["choices"]:
586
- if "message" in choice and "content" in choice["message"]:
587
- yield choice["message"]["content"]
588
-
589
- def create_app(api_endpoint: str) -> gr.Blocks:
590
- """Creates and configures the Gradio interface."""
591
- assistant = BotanistAssistant(api_endpoint)
592
-
593
- with gr.Blocks(title="๐ŸŒฟ Botanist Assistant", theme=gr.themes.Soft()) as demo:
594
- gr.Markdown("# ๐ŸŒฟ Natural Medical Assistant")
595
- gr.Markdown("Describe your symptoms to get natural plant-based treatment recommendations")
596
-
597
- with gr.Row():
598
- with gr.Column(scale=3):
599
- chat = gr.ChatInterface(
600
- assistant.respond,
601
- additional_inputs=[
602
- gr.Textbox(
603
- value=assistant.system_message,
604
- label="System Role",
605
- interactive=True
606
- )
607
- ]
608
- )
609
- with gr.Column(scale=1):
610
- gr.Markdown("### Common Symptoms")
611
- gr.Examples(
612
- examples=[
613
- ["I have headache and fever"],
614
- ["got nausea, and injury caused bleeding"],
615
- ["I feel insomnia, and anxiety"],
616
- ["I am suffering from ADHD"]
617
- ],
618
- inputs=chat.textbox,
619
- label="Try these examples"
620
- )
621
-
622
- gr.Markdown("---")
623
- gr.Markdown("""> Note: Recommendations can work as real cure treatment but you can consider it as informational purposes only.
624
- Also You can consult a Natrual healthcare professional before use.""")
625
-
626
- return demo
627
-
628
- if __name__ == "__main__":
629
- API_ENDPOINT = "https://api.studio.nebius.com" # Replace with your actual endpoint
630
- app = create_app(API_ENDPOINT)
631
- app.launch(
632
- server_name="0.0.0.0",
633
- server_port=7860,
634
- share=False,
635
- favicon_path="๐ŸŒฟ" # Optional: Add path to plant icon
636
  )
 
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
+ import time
8
+ from openai import OpenAI
9
+
10
+ #make token for every part of calls to detect issues faster in testing or in beta release:
11
+ #fast-api
12
+
13
+ GEMMA_TOKEN=os.environ.get("NEBIUS_API_KEY_GEMMA")
14
+ #To be used for the main requests
15
+ DEEPSEEKv3_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK")
16
+ DEEPSEEKv3_FAST_TOKEN=os.environ.get("NEBIUS_API_KEY_DEEPSEEK_FAST")
17
+
18
+ #unused for getting all symptoms from plants db
19
+ def get_all_treatable_conditions()->List:
20
+ #Gets all the symptoms:
21
+ conn = sqlite3.connect('plants.db')
22
+ # Create a cursor object
23
+ cursor = conn.cursor()
24
+ # Execute a query to retrieve data
25
+ cursor.execute("SELECT treatable_conditions FROM 'plants'")
26
+ # Fetch all results
27
+ rows = cursor.fetchall()
28
+ # Print the results
29
+ treatable_conditions=[]
30
+ for row in rows:
31
+ treatable_conditions.append(row)
32
+ # Close the connection
33
+ conn.close()
34
+ return treatable_conditions
35
+
36
+ #Unused for writing db
37
+ def write_symptoms_into_db(data_list):
38
+ """Initialize SQLite database"""
39
+ try:
40
+ conn = sqlite3.connect('plants.db')
41
+ c = conn.cursor()
42
+ c.execute('''CREATE TABLE IF NOT EXISTS symptoms (name TEXT)''')
43
+ conn.commit()
44
+ for each in data_list:
45
+ insert_sql = f'''INSERT INTO 'symptoms' (name) VALUES ("{each}")'''
46
+ c.execute(insert_sql)
47
+ conn.commit()
48
+ print("Database created successfully!")
49
+ conn.close()
50
+ except sqlite3.Error as e:
51
+ print(f"An error occurred: {e}")
52
+
53
+ #@tool
54
+ def get_unique_symptoms(list_text:List[str])->List[str]:
55
+ """Processes and deduplicates symptom descriptions into a normalized list of unique symptoms.
56
+
57
+ Performs comprehensive text processing to:
58
+ - Extract individual symptoms from complex descriptions
59
+ - Normalize formatting (removes common connecting words and punctuation)
60
+ - Deduplicate symptoms while preserving original meaning
61
+ - Handle multiple input formats (strings and tuples)
62
+
63
+ Args:
64
+ list_text: List of symptom descriptions in various formats.
65
+ Each element can be:
66
+ - String: "fever and headache"
67
+ - Tuple: ("been dizzy and nauseous",)
68
+ Example: ["fatigue, nausea", "headache and fever"]
69
+
70
+ Returns:
71
+ List of unique, alphabetically sorted symptom terms in lowercase.
72
+ Returns empty list if:
73
+ - Input is empty
74
+ - No valid strings found
75
+ Example: ['bleed', 'fever', 'headache']
76
+
77
+ Processing Details:
78
+ 1. Text normalization:
79
+ - Removes connecting words ("and", "also", "like", etc.)
80
+ - Replaces punctuation with spaces
81
+ - Converts to lowercase
82
+ 2. Special cases:
83
+ - Handles tuple inputs by extracting first element
84
+ - Skips non-string/non-tuple elements with warning
85
+ 3. Deduplication:
86
+ - Uses set operations for uniqueness
87
+ - Returns sorted list for consistency
88
+
89
+ Examples:
90
+ >>> get_unique_symptoms(["fever and headache", "bleed"])
91
+ ['bleed', 'fever', 'headache']
92
+
93
+ >>> get_unique_symptoms([("been dizzy",), "nausea"])
94
+ ['dizzy', 'nausea']
95
+
96
+ >>> get_unique_symptoms([123, None])
97
+ No Correct DataType
98
+ []
99
+
100
+ Edge Cases:
101
+ - Empty strings are filtered out
102
+ - Single-word symptoms preserved
103
+ - Mixed punctuation handled
104
+ - Warning printed for invalid types
105
+ """
106
+
107
+ all_symptoms = []
108
+
109
+ for text in list_text:
110
+ # Handle potential errors in input text. Crucial for robustness.
111
+ if type(text)==tuple:
112
+ text=text[0]
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
+ elif type(text)==str and len(text)>1:
117
+ symptoms = text.replace(" and ", " ").replace(" been ", " ").replace(" also ", " ").replace(" like ", " ").replace(" due ", " ").replace(" a ", " ").replace(" as ", " ").replace(" an ", " ").replace(",", " ").replace(".", " ").replace(";", " ").replace("(", " ").replace(")", " ").split()
118
+ symptoms = [symptom.strip() for symptom in symptoms if symptom.strip()] # Remove extra whitespace and empty strings
119
+ all_symptoms.extend(symptoms)
120
+ else:
121
+ print ("No Correct DataType or 1 charater text O.o")
122
+ #if not isinstance(text, str) or not text:
123
+ #continue
124
+
125
+ unique_symptoms = sorted(list(set(all_symptoms))) # Use set to get unique items, then sort for consistency
126
+
127
+ return unique_symptoms
128
+
129
+ #@tool
130
+ def lookup_symptom_and_plants(symptom_input:str)->List:
131
+ """Search for medicinal plants that can treat a given symptom by querying a SQLite database.
132
+
133
+ This function performs a case-insensitive search in the database for:
134
+ 1. First looking for an exact or partial match of the symptom
135
+ 2. If not found, searches for individual words from the symptom input
136
+ 3. Returns all plants that list the matched symptom in their treatable conditions
137
+
138
+ Args:
139
+ symptom_input (str): The symptom to search for (e.g., "headache", "stomach pain").
140
+ Can be a single symptom or multiple words. Leading/trailing
141
+ whitespace is automatically trimmed.
142
+
143
+ Returns:
144
+ List[dict]: A list of plant dictionaries containing all columns from the 'plants' table
145
+ where the symptom appears in treatable_conditions. Each dictionary represents
146
+ one plant with column names as keys. Returns empty list if:
147
+ - Symptom not found
148
+ - No plants treat the symptom
149
+ - Database error occurs
150
+
151
+ Raises:
152
+ sqlite3.Error: If there's a database connection or query error (handled internally,
153
+ returns empty list but prints error to console)
154
+
155
+ Notes:
156
+ - The database connection is opened and closed within this function
157
+ - Uses LIKE queries with wildcards for flexible matching
158
+ - Treatable conditions are expected to be stored as comma-separated values
159
+ - Case-insensitive matching is performed by converting to lowercase
160
+ - The function will attempt to match individual words if full phrase not found
161
+
162
+ Example:
163
+ >>> lookup_symptom_and_plants("headache")
164
+ [{'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/'}]
165
+
166
+ >>> lookup_symptom_and_plants("unknown symptom")
167
+ []
168
+ """
169
+ symptom_lower = symptom_input.strip().lower()
170
+ try:
171
+ conn = sqlite3.connect('plants.db')
172
+ conn.row_factory = sqlite3.Row
173
+ c = conn.cursor()
174
+
175
+ # Check if the symptom exists in symptoms table (case-insensitive)
176
+ c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{symptom_lower}%"''')
177
+ result = c.fetchone()
178
+ #if result:
179
+ # result=result[0]
180
+
181
+ if not result:
182
+ #get any 1 symptom only in case the text is not showing.
183
+ symptoms=symptom_lower.split(" ")
184
+ for each in symptoms:
185
+ c.execute(f'''SELECT name FROM "symptoms" WHERE LOWER("name") LIKE "%{each}%"''')
186
+ result = c.fetchone()
187
+ if result:
188
+ print(f"Symptom '{symptom_input}' finally found in the database.")
189
+ #result=result[0]
190
+ symptom_lower=each
191
+ break
192
+ if not result:
193
+ print(f"Symptom '{symptom_input}' not found in the database.")
194
+ conn.close()
195
+ return []
196
+
197
+ # If symptom exists, search in plants table for related plants
198
+ # Assuming 'TreatableConditions' is a comma-separated string
199
+ query = f"""SELECT * FROM plants WHERE LOWER(treatable_conditions) LIKE "%{symptom_lower}%" """
200
+ c.execute(query)
201
+ plants_rows = c.fetchall()
202
+
203
+ plants_list = []
204
+ for row in plants_rows:
205
+ # Convert row to dict for easier handling
206
+ plant_dict = {key: row[key] for key in row.keys()}
207
+ plants_list.append(plant_dict)
208
+
209
+ conn.close()
210
+ return plants_list
211
+
212
+ except sqlite3.Error as e:
213
+ print(f"Database error: {e}")
214
+ return []
215
+
216
+
217
+
218
+
219
+ def analyze_symptoms_from_text_ai(text_input: str) -> str:
220
+ """
221
+ Analyze user-provided text to extract medical symptoms in CSV format.
222
+
223
+ Args:
224
+ text_input: Raw text description of health condition
225
+
226
+ Returns:
227
+ str: Comma-separated list of symptoms in CSV format
228
+
229
+ Example:
230
+ >>> analyze_symptoms_from_text_ai("I have headache and nausea")
231
+ 'headache,nausea'
232
+ """
233
+
234
+ client = OpenAI(
235
+ base_url="https://api.studio.nebius.com/v1/",
236
+ api_key=GEMMA_TOKEN
237
+ )
238
+
239
+ try:
240
+ response = client.chat.completions.create(
241
+ model="google/gemma-2-2b-it",
242
+ max_tokens=512,
243
+ temperature=0.5,
244
+ top_p=0.9,
245
+ extra_body={"top_k": 50},
246
+ messages=[
247
+ {
248
+ "role": "system",
249
+ "content": """You are a medical symptom extractor.
250
+ Analyze the text and return ONLY a comma-separated list of symptoms in CSV format.
251
+ Example input: "I have headache and feel nauseous"
252
+ Example output: headache,nausea
253
+ Return "" , IF NO SYMTPOMS OR DIESEASE IN THE TEXT"""
254
+ },
255
+ {
256
+ "role": "user",
257
+ "content": f"Analyze this text for symptoms and list them in CSV format: {text_input}"
258
+ }
259
+ ]
260
+ )
261
+
262
+ # Extract and clean the response
263
+ symptoms_csv = response.choices.message.content.strip()
264
+ return symptoms_csv
265
+
266
+ except Exception as e:
267
+ print(f"Error analyzing symptoms: {str(e)}")
268
+ return ""
269
+
270
+ #@tool
271
+ def full_treatment_answer_ai(user_input: str) -> str:
272
+ """
273
+ Searches for plant treatments based on user symptoms using Nebius API.
274
+
275
+ Args:
276
+ user_input: User's symptom description
277
+
278
+ Returns:
279
+ str: Complete treatment plan with plant recommendations and details
280
+ """
281
+ # Initialize Nebius client
282
+ client = OpenAI(
283
+ base_url="https://api.studio.nebius.com/v1/",
284
+ api_key=DEEPSEEKv3_TOKEN
285
+ )
286
+
287
+ # Step 1: Extract symptoms from user input
288
+ text_symptoms = user_input#analyze_symptoms_from_text_ai(user_input)
289
+ symptoms_list = text_symptoms.split(",")
290
+ symptoms = get_unique_symptoms(symptoms_list)
291
+
292
+ if not symptoms:
293
+ return "Could not identify any specific symptoms. Please describe your condition in more detail."
294
+
295
+ # Step 2: Find relevant plants for each symptom
296
+ all_related_plants = []
297
+ for symptom in symptoms:
298
+ related_plants = lookup_symptom_and_plants(symptom)
299
+ all_related_plants.extend(related_plants)
300
+
301
+ # Step 3: Prepare the prompt for Nebius API
302
+ plants_info = ""
303
+ if all_related_plants:
304
+ plants_info = "Here are some plants that might be relevant:\n"
305
+ for plant in all_related_plants[:6]: # Limit to top 6 plants
306
+ plants_info += f"""\nPlant: {plant['name']}
307
+ {plant['description']}
308
+ Cures: {plant['treatable_conditions']}
309
+ Dosage: {plant['dosage']}\n"""
310
+ else:
311
+ plants_info = "I dont know specific plants for these symptoms. please get useful plants from anywhere or any other sources"
312
+
313
+ prompt = f"""I have these symptoms: {", ".join(symptoms)}.
314
+
315
+ {plants_info}
316
+
317
+ Please analyze my symptoms and recommend the most appropriate plant remedy.
318
+ Consider the symptoms, when to use each plant, dosage, and how to use it.
319
+ Provide your recommendation in this format:
320
+
321
+ **Recommended Plant**: [plant name]
322
+ **Reason**: [why this plant is good for these symptoms]
323
+ **Dosage**: [recommended dosage]
324
+ **Instructions**: [how to use it]
325
+ **Image**: [mention if image is available]
326
+
327
+ If multiple plants could work well, you may recommend up to 3 options."""
328
+
329
+ # Step 4: Call Nebius API for treatment recommendation
330
+ try:
331
+ response = client.chat.completions.create(
332
+ model="deepseek-ai/DeepSeek-V3-0324-fast",
333
+ max_tokens=1024, # Increased for detailed responses
334
+ temperature=0.3,
335
+ top_p=0.95,
336
+ messages=[
337
+ {
338
+ "role": "system",
339
+ "content": """You are a professional botanist assistant specializing in medicinal plants.
340
+ Provide accurate, science-backed recommendations for plant-based treatments.
341
+ Include dosage, preparation methods, and safety considerations."""
342
+ },
343
+ {
344
+ "role": "user",
345
+ "content": prompt
346
+ }
347
+ ]
348
+ )
349
+
350
+ final_result = response.choices.message.content
351
+
352
+ # Step 5: Append detailed plant information if available
353
+ if all_related_plants:
354
+ final_result += "\n---\nMore Details for Recommended Plants:\n"
355
+ for plant in all_related_plants[:3]: # Show details for top 3 plants
356
+ final_result += f"""
357
+ **Plant Name**: {plant['name']}
358
+ **Scientific Name**: {plant['scientific_name']}
359
+ **Other Names**: {plant['alternate_names']}
360
+ **Description**: {plant['description']}
361
+ **Treatable Conditions**: {plant['treatable_conditions']}
362
+ **Preparation**: {plant['preparation_methods']}
363
+ **Dosage**: {plant['dosage']}
364
+ **Side Effects**: {plant['side_effects']}
365
+ **Contraindications**: {plant['contraindications']}
366
+ **Sources**: {plant['sources']}
367
+ """
368
+
369
+ return final_result
370
+
371
+ except Exception as e:
372
+ print(f"Error generating treatment plan: {str(e)}")
373
+ return "Sorry, I couldn't generate a treatment plan at this time. Please try again later."
374
+
375
+ #example:
376
+ # user_input="""i feel some pain in head and i feel dizzy""" #user input
377
+ # prompt='''Analyze the possible symptoms and list them in only csv format by comma in 1 line,from the following text : """{user_input}"""'''
378
+ # output='pain in head,dizzy'
379
+ # symptoms=output.split(",")
380
+ # get_unique_symptoms(symptoms)
381
+
382
+
383
+ #Filter all conditions:
384
+ #all_treatment_conditions=get_all_treatable_conditions()
385
+ #unique_symptoms=get_unique_symptoms(all_treatment_conditions)
386
+ #write_symptoms_into_db(unique_symptoms)
387
+ #related_plants = lookup_symptom_and_plants("fever")
388
+
389
+ '''
390
+ user_input = "fever"
391
+ related_plants = lookup_symptom_and_plants(user_input)
392
+ if related_plants:
393
+ print(f"Plants related to '{user_input}':")
394
+ for plant in related_plants:
395
+ print(f"- {plant['name']}")
396
+ else:
397
+ print(f"No plants found for symptom '{user_input}'.")
398
+ '''
399
+ def is_symtoms_intext_ai(text_input:str)->str: #used instead of: analyze_symptoms_from_text_ai()
400
+ """Gives Symptoms or "" if no symptoms """
401
+ response_text=analyze_symptoms_from_text_ai(text_input)
402
+ if len(response_text)>2:
403
+ if "error" not in response_text.lower():
404
+ return response_text
405
+ return ""
406
+
407
+ class BotanistAssistant:
408
+ def __init__(self, api_endpoint: str = "https://api.studio.nebius.com/v1/"): #https://api.studio.nebius.com/v1/chat/completions
409
+ self.api_endpoint = api_endpoint
410
+ self.system_message = "You are a botanist assistant that extracts and structures information about medicinal plants."
411
+ self.client = OpenAI(
412
+ base_url="https://api.studio.nebius.com/v1/",
413
+ api_key=DEEPSEEKv3_FAST_TOKEN
414
+ )
415
+
416
+ def _build_chat_history(self, history: List[Tuple[str, str]]) -> List[Dict[str, str]]:
417
+ """Formats chat history into API-compatible message format."""
418
+ messages = [{"role": "system", "content": self.system_message}]
419
+ for user_msg, bot_msg in history:
420
+ if user_msg:
421
+ messages.append({"role": "user", "content": user_msg})
422
+ if bot_msg:
423
+ messages.append({"role": "assistant", "content": bot_msg})
424
+ return messages
425
+
426
+
427
+ def _get_tools_schema(self) -> List[Dict[str, Any]]:
428
+ """Returns the complete tools schema for plant medicine analysis."""
429
+ return [
430
+ {
431
+ "name": "get_unique_symptoms",
432
+ "description": "Extracts and remove duplicates of symptoms from text input. Handles natural language processing to identify individual symptoms from complex descriptions.",
433
+ "api": {
434
+ "name": "get_unique_symptoms",
435
+ "parameters": {
436
+ "type": "object",
437
+ "properties": {
438
+ "list_text": {
439
+ "type": "array",
440
+ "items": {"type": "string"},
441
+ "description": "List of symptom descriptions (strings or tuples)"
442
+ }
443
+ },
444
+ "required": ["list_text"]
445
+ }
446
+ }
447
+ },
448
+ {
449
+ "name": "lookup_symptom_and_plants",
450
+ "description": "Finds medicinal plants associated with specific symptoms from the database. Returns matching plants with their treatment properties.",
451
+ "api": {
452
+ "name": "lookup_symptom_and_plants",
453
+ "parameters": {
454
+ "type": "object",
455
+ "properties": {
456
+ "symptom_input": {
457
+ "type": "string",
458
+ "description": "Individual symptom to search for plant treatments"
459
+ }
460
+ },
461
+ "required": ["symptom_input"]
462
+ }
463
+ }
464
+ },
465
+ {
466
+ "name": "analyze_symptoms_from_text_ai",
467
+ "description": "Analyzes text to extract medical symptoms and returns them in CSV format.",
468
+ "api": {
469
+ "name": "analyze_symptoms_from_text_ai",
470
+ "parameters": {
471
+ "type": "object",
472
+ "properties": {
473
+ "text_input": {
474
+ "type": "string",
475
+ "description": "Raw text description of health condition"
476
+ }
477
+ },
478
+ "required": ["text_input"]
479
+ }
480
+ }
481
+ },
482
+ {
483
+ "name": "full_treatment_answer_ai",
484
+ "description": "Generates complete plant-based treatment plans for given symptoms, including dosage, preparation methods, and safety information.",
485
+ "api": {
486
+ "name": "full_treatment_answer_ai",
487
+ "parameters": {
488
+ "type": "object",
489
+ "properties": {
490
+ "user_input": {
491
+ "type": "string",
492
+ "description": "User's description of symptoms or health condition"
493
+ }
494
+ },
495
+ "required": ["user_input"]
496
+ }
497
+ }
498
+ }
499
+ ]
500
+
501
+ def _call_tool(self, tool_name: str, parameters: Dict[str, Any]) -> Any:
502
+ """Executes the specified tool with given parameters."""
503
+ if tool_name == "full_treatment_answer_ai":
504
+ return self.full_treatment_answer_ai(**parameters)
505
+ elif tool_name == "analyze_symptoms_from_text_ai":
506
+ return self.analyze_symptoms_from_text_ai(**parameters)
507
+ else:
508
+ raise ValueError(f"Unknown tool: {tool_name}")
509
+
510
+ def _call_assistant_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
511
+ """Makes the API call to Nebius assistant service with no tool support.""" #TODO tool
512
+
513
+ try:
514
+ response = self.client.chat.completions.create(
515
+ model="deepseek-ai/DeepSeek-V3-0324-fast",
516
+ max_tokens=1024,
517
+ temperature=0.3,
518
+ top_p=0.9,
519
+ extra_body={"top_k": 50},
520
+ messages=messages)
521
+ return response.choices.message.content
522
+
523
+ except Exception as e:
524
+ print(f"Error: {str(e)}")
525
+ return {"error": str(e)}
526
+
527
+
528
+ #assistant = BotanistAssistant()
529
+ # Simple query
530
+ # Treatment query (will automatically use tools)
531
+ #for response in assistant.respond("I have migraines and trouble sleeping", []):
532
+ # print(response)
533
+
534
+ def respond(
535
+ self,
536
+ message: str,
537
+ history: List[Tuple[str, str]],
538
+ system_message: str = None
539
+ ) -> Generator[str, None, None]:
540
+ """Handles the chat response generation."""
541
+ # Update system message if provided
542
+ if system_message:
543
+ self.system_message = system_message
544
+
545
+ # Build API payload
546
+ messages = self._build_chat_history(history)
547
+ messages.append({"role": "user", "content": message})
548
+
549
+
550
+ # Get API response
551
+ api_response = self._call_assistant_api(messages)
552
+
553
+ # Process response
554
+ if "error" in api_response:
555
+ yield "Error: Could not connect to the assistant service. Please try again later."
556
+ return
557
+
558
+
559
+ treatment_response=""
560
+ symtoms_intext=is_symtoms_intext_ai(message)
561
+ if symtoms_intext:
562
+ #time.sleep(1.6)
563
+ treatment_response=full_treatment_answer_ai(symtoms_intext)
564
+ #yield treatment_response
565
+
566
+ if len(treatment_response):
567
+ treatment_response="\n**I have found that this may help you alot:**\n"+treatment_response
568
+ yield treatment_response
569
+
570
+ # Get treatment information
571
+ #treatment_response = search_for_treatment_answer_ai(message)
572
+ #yield treatment_response # First yield the treatment info
573
+
574
+ # Stream additional assistant responses if available
575
+ try: #json:
576
+ if "choices" in api_response:
577
+ for choice in api_response["choices"]:
578
+ if "message" in choice and "content" in choice["message"]:
579
+ yield choice["message"]["content"]
580
+ except Exception as e:
581
+ print ("Chat error:",e)
582
+ if api_response and api_response.choices:
583
+ for choice in api_response.choices:
584
+ if "message" in choice and "content" in choice["message"]:
585
+ yield choice["message"]["content"]
586
+
587
+ def create_app(api_endpoint: str = "https://api.studio.nebius.com/v1/") -> gr.Blocks:
588
+ """Creates and configures the Gradio interface."""
589
+ assistant = BotanistAssistant(api_endpoint)
590
+
591
+ with gr.Blocks(title="๐ŸŒฟ Botanist Assistant", theme=gr.themes.Soft()) as demo:
592
+ gr.Markdown("# ๐ŸŒฟ Natural Medical Assistant")
593
+ gr.Markdown("Describe your symptoms to get natural plant-based treatment recommendations")
594
+
595
+ with gr.Row():
596
+ with gr.Column(scale=3):
597
+ chat = gr.ChatInterface(
598
+ assistant.respond,
599
+ additional_inputs=[
600
+ gr.Textbox(
601
+ value=assistant.system_message,
602
+ label="System Role",
603
+ interactive=True
604
+ )
605
+ ]
606
+ )
607
+ with gr.Column(scale=1):
608
+ gr.Markdown("### Common Symptoms")
609
+ gr.Examples(
610
+ examples=[
611
+ ["I have headache and fever"],
612
+ ["got nausea, and injury caused bleeding"],
613
+ ["I feel insomnia, and anxiety"],
614
+ ["I am suffering from ADHD"]
615
+ ],
616
+ inputs=chat.textbox,
617
+ label="Try these examples"
618
+ )
619
+
620
+ gr.Markdown("---")
621
+ gr.Markdown("""> Note: Recommendations can work as real cure treatment but you can consider it as informational purposes only.
622
+ Also You can consult a Natrual healthcare professional before use.""")
623
+
624
+ return demo
625
+
626
+ if __name__ == "__main__":
627
+ API_ENDPOINT = "https://api.studio.nebius.com/v1/" # Replace with your actual endpoint
628
+ app = create_app()
629
+ app.launch(
630
+ server_name="0.0.0.0",
631
+ server_port=7860,
632
+ share=False,
633
+ favicon_path="๐ŸŒฟ" # Optional: Add path to plant icon
 
 
634
  )