shukdevdatta123 commited on
Commit
227ffe0
·
verified ·
1 Parent(s): a445b4b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -71
app.py CHANGED
@@ -61,7 +61,8 @@ def extract_medicines(api_key, image):
61
  def recommend_medicine(api_key, medicine_name, csv_file=None):
62
  """
63
  Use Together API to recommend alternative medicines based on input medicine name
64
- using data from the provided CSV file with specific column structure
 
65
  """
66
  try:
67
  # If CSV file is provided, use it; otherwise use default
@@ -73,14 +74,36 @@ def recommend_medicine(api_key, medicine_name, csv_file=None):
73
  df = pd.read_csv(csv_file.name)
74
  else:
75
  # Use the default medicine_dataset.csv in the current directory
76
- df = pd.read_csv("medicine_dataset.csv")
 
 
 
77
 
78
- # Verify the medicine name exists in the dataset
79
- if medicine_name not in df['name'].values:
80
- return f"Error: Medicine '{medicine_name}' not found in the dataset. Please check the spelling or try another medicine."
81
 
82
- # Create system prompt with CSV data and column structure information
83
- system_prompt = f"""Develop an expert system to recommend alternative medicines for {medicine_name} based on the medicine dataset. The dataset has the following columns:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  - name: Medicine name
85
  - substitute0 through substitute4: Potential substitute medicines
86
  - sideEffect0 through sideEffect41: Possible side effects
@@ -90,47 +113,28 @@ def recommend_medicine(api_key, medicine_name, csv_file=None):
90
  - Therapeutic Class: The therapeutic classification
91
  - Action Class: How the medicine works
92
 
93
- Your task is to:
94
- 1. Find the row in the dataset where name matches exactly "{medicine_name}"
95
- 2. Find alternatives by:
96
- - Using the substitute0-substitute4 values as primary alternatives
97
- - Finding other medicines with similar Chemical Class, Therapeutic Class, or Action Class
98
 
99
- For each recommended alternative, provide:
100
- - Name of the alternative medicine
101
- - All side effects (from relevant sideEffect columns)
102
- - All uses (from relevant use columns)
103
- - Chemical Class, Habit Forming status, Therapeutic Class, and Action Class
104
- - A similarity score (0-1) indicating how similar it is to the original medicine
105
 
106
- Format the response clearly with headings for "Recommended Medicines", "Medicine Details", and "Similarity Score".
107
- """
108
 
109
- # Extract the specific row containing the medicine data to give more context
110
- medicine_data = df[df['name'] == medicine_name]
111
- if not medicine_data.empty:
112
- # Convert the specific medicine data to a string representation
113
- medicine_info = medicine_data.to_string(index=False)
114
- system_prompt += f"\n\nThe specific data for {medicine_name} is:\n{medicine_info}\n\n"
115
-
116
- # Extract substitute information for better recommendations
117
- substitutes = []
118
- for i in range(5): # substitute0 through substitute4
119
- col_name = f"substitute{i}"
120
- if col_name in medicine_data.columns:
121
- sub_value = medicine_data[col_name].iloc[0]
122
- if pd.notna(sub_value) and sub_value != "":
123
- substitutes.append(sub_value)
124
-
125
- if substitutes:
126
- system_prompt += f"The primary substitutes for {medicine_name} are: {', '.join(substitutes)}\n\n"
127
-
128
- # Include a sample of other medicines for comparison
129
- other_medicines = df[df['name'] != medicine_name].sample(min(10, len(df)-1)) if len(df) > 1 else pd.DataFrame()
130
- if not other_medicines.empty:
131
- system_prompt += "Here's a sample of other medicines in the dataset for comparison:\n"
132
- for idx, row in other_medicines.iterrows():
133
- system_prompt += f"- {row['name']}: Chemical Class: {row['Chemical Class']}, Therapeutic Class: {row['Therapeutic Class']}, Action Class: {row['Action Class']}\n"
134
 
135
  # Initialize Together client with the API key
136
  client = Together(api_key=api_key)
@@ -145,14 +149,20 @@ Format the response clearly with headings for "Recommended Medicines", "Medicine
145
  },
146
  {
147
  "role": "user",
148
- "content": f"Please recommend alternatives for {medicine_name} based on the dataset. Include detailed information about each alternative."
149
  }
150
  ],
151
- max_tokens=2000
 
152
  )
153
 
154
- # Return the generated recommendations
155
- return response.choices[0].message.content
 
 
 
 
 
156
 
157
  except Exception as e:
158
  return f"Error: {str(e)}"
@@ -181,10 +191,77 @@ def send_medicine_to_recommender(api_key, medicine_names, csv_file):
181
  # Call the recommend medicine function with the first extracted medicine
182
  return recommend_medicine(api_key, first_medicine, csv_file)
183
 
184
- # Create Gradio interface with tabs for both functionalities
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  with gr.Blocks(title="Medicine Assistant") as app:
186
  gr.Markdown("# Medicine Assistant")
187
- gr.Markdown("This application helps you extract medicine names from prescriptions and find alternative medicines.")
188
 
189
  # API key input (shared between tabs)
190
  api_key_input = gr.Textbox(
@@ -194,11 +271,10 @@ with gr.Blocks(title="Medicine Assistant") as app:
194
  )
195
 
196
  # Create a file input for CSV that can be shared between tabs
197
- # Fixed the 'type' parameter to use 'filepath' instead of 'file'
198
  csv_file_input = gr.File(
199
  label="Upload Medicine CSV (Optional)",
200
  file_types=[".csv"],
201
- type="filepath" # Changed from 'file' to 'filepath'
202
  )
203
  gr.Markdown("If no CSV is uploaded, the app will use the default 'medicine_dataset.csv' file.")
204
 
@@ -211,11 +287,22 @@ with gr.Blocks(title="Medicine Assistant") as app:
211
  with gr.Column():
212
  image_input = gr.Image(type="filepath", label="Upload Prescription Image")
213
  extract_btn = gr.Button("Extract Medicines")
214
- recommend_from_extract_btn = gr.Button("Get Recommendations for First Medicine")
215
 
216
  with gr.Column():
217
  extracted_output = gr.Textbox(label="Extracted Medicines", lines=10)
218
- recommendation_from_extract_output = gr.Markdown(label="Recommendations")
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  # Connect the buttons to functions
221
  extract_btn.click(
@@ -230,13 +317,21 @@ with gr.Blocks(title="Medicine Assistant") as app:
230
  outputs=recommendation_from_extract_output
231
  )
232
 
 
 
 
 
 
 
233
  gr.Markdown("""
234
  ### How to use:
235
  1. Enter your Together API key
236
  2. Upload a clear image of a prescription
237
  3. Click 'Extract Medicines' to see the identified medicines
238
  4. Optionally upload a custom medicine dataset CSV
239
- 5. Click 'Get Recommendations for First Medicine' to find alternatives
 
 
240
 
241
  ### Note:
242
  - Your API key is used only for the current session
@@ -251,12 +346,12 @@ with gr.Blocks(title="Medicine Assistant") as app:
251
  with gr.Column():
252
  medicine_name = gr.Textbox(
253
  label="Medicine Name",
254
- placeholder="Enter a medicine name exactly as it appears in the dataset"
255
  )
256
  submit_btn = gr.Button("Get Recommendations", variant="primary")
257
 
258
  with gr.Column():
259
- recommendation_output = gr.Markdown(label="Recommendations")
260
 
261
  submit_btn.click(
262
  recommend_medicine,
@@ -267,30 +362,25 @@ with gr.Blocks(title="Medicine Assistant") as app:
267
  gr.Markdown("""
268
  ## How to use this tool:
269
  1. Enter your Together API key (same key used across the application)
270
- 2. Enter a medicine name **exactly as it appears** in the CSV file
271
  3. Click "Get Recommendations" to see alternatives
272
 
273
- ### CSV Format Requirements:
274
- The app expects a CSV with these columns:
275
- - `name`: Medicine name
276
- - `substitute0` through `substitute4`: Potential substitute medicines
277
- - `sideEffect0` through `sideEffect41`: Possible side effects
278
- - `use0` through `use4`: Medical uses
279
- - `Chemical Class`: The chemical classification
280
- - `Habit Forming`: Whether the medicine is habit-forming
281
- - `Therapeutic Class`: The therapeutic classification
282
- - `Action Class`: How the medicine works
283
  """)
284
 
285
  gr.Markdown("""
286
  ## About This Application
287
 
288
- This Medicine Assistant application combines two powerful tools:
289
 
290
  1. **Prescription Medicine Extractor**: Uses computer vision AI to identify medicine names from prescription images
291
  2. **Medicine Alternative Recommender**: Provides detailed information about alternative medications
 
292
 
293
- Both tools utilize the Together AI platform for advanced AI capabilities. Your API key is not stored and is only used to make API calls during your active session.
294
 
295
  ### Important Note
296
 
 
61
  def recommend_medicine(api_key, medicine_name, csv_file=None):
62
  """
63
  Use Together API to recommend alternative medicines based on input medicine name
64
+ using data from the provided CSV file with specific column structure.
65
+ It will use AI to find similar medicines even if the exact name isn't in the dataset.
66
  """
67
  try:
68
  # If CSV file is provided, use it; otherwise use default
 
74
  df = pd.read_csv(csv_file.name)
75
  else:
76
  # Use the default medicine_dataset.csv in the current directory
77
+ try:
78
+ df = pd.read_csv("medicine_dataset.csv")
79
+ except FileNotFoundError:
80
+ return "Error: Default medicine_dataset.csv not found. Please upload a CSV file."
81
 
82
+ # Check if medicine is in the dataset
83
+ medicine_exists = medicine_name in df['name'].values
 
84
 
85
+ # Create a helpful context about the dataset to send to the LLM
86
+ dataset_overview = f"The dataset contains {len(df)} medicines with columns for name, substitutes, side effects, uses, chemical class, etc."
87
+
88
+ # Sample of medicine names to give the model context
89
+ sample_names = df['name'].sample(min(20, len(df))).tolist()
90
+ medicine_sample = f"Sample medicines in the dataset: {', '.join(sample_names)}"
91
+
92
+ # Extract specific medicine data if available
93
+ medicine_data = None
94
+ medicine_info_str = ""
95
+ if medicine_exists:
96
+ medicine_data = df[df['name'] == medicine_name]
97
+ medicine_info_str = medicine_data.to_string(index=False)
98
+
99
+ # Create system prompt with dataset context
100
+ system_prompt = f"""You are a pharmaceutical expert system that recommends alternative medicines based on a comprehensive medicine dataset. The user has provided the medicine name "{medicine_name}".
101
+
102
+ DATASET INFORMATION:
103
+ {dataset_overview}
104
+ {medicine_sample}
105
+
106
+ The dataset has the following columns:
107
  - name: Medicine name
108
  - substitute0 through substitute4: Potential substitute medicines
109
  - sideEffect0 through sideEffect41: Possible side effects
 
113
  - Therapeutic Class: The therapeutic classification
114
  - Action Class: How the medicine works
115
 
116
+ YOUR TASK:
 
 
 
 
117
 
118
+ {"The medicine was found in the dataset with the following information:" if medicine_exists else "The medicine was NOT found in the dataset with an exact match. Your task is to:"}
 
 
 
 
 
119
 
120
+ {medicine_info_str if medicine_exists else "1. Identify what kind of medicine this likely is based on its name (e.g., antibiotics, pain relievers, etc.)"}
121
+ {'' if medicine_exists else "2. Look for medicines in the sample list that might be similar or serve similar purposes"}
122
 
123
+ Please recommend alternative medicines for "{medicine_name}" with the following details for each:
124
+ 1. Name of the alternative medicine
125
+ 2. Why it's a good alternative (similar chemical composition, therapeutic use, etc.)
126
+ 3. Potential side effects to be aware of
127
+ 4. Usage recommendations
128
+ 5. Similarity to the original medicine (high, medium, low)
129
+
130
+ Include at least 3-5 alternatives if possible.
131
+
132
+ IMPORTANT:
133
+ - If the medicine name contains strength or formulation (like "500mg" or "Duo"), focus on finding the base medicine first
134
+ - Explain why these alternatives might be suitable replacements
135
+ - Include appropriate medical disclaimers
136
+ - Format your response clearly with headings for each alternative medicine
137
+ """
 
 
 
 
 
 
 
 
 
 
138
 
139
  # Initialize Together client with the API key
140
  client = Together(api_key=api_key)
 
149
  },
150
  {
151
  "role": "user",
152
+ "content": f"Please recommend alternatives for {medicine_name} based on the available information."
153
  }
154
  ],
155
+ max_tokens=2000,
156
+ temperature=0.7 # Slightly higher temperature for creative recommendations
157
  )
158
 
159
+ # Get the raw response
160
+ recommendation_text = response.choices[0].message.content
161
+
162
+ # Add disclaimer
163
+ final_response = recommendation_text + "\n\n---\n\n**DISCLAIMER:** This information is for educational purposes only. Always consult with a healthcare professional before making any changes to your medication."
164
+
165
+ return final_response
166
 
167
  except Exception as e:
168
  return f"Error: {str(e)}"
 
191
  # Call the recommend medicine function with the first extracted medicine
192
  return recommend_medicine(api_key, first_medicine, csv_file)
193
 
194
+ def analyze_full_prescription(api_key, medicine_names, csv_file):
195
+ """
196
+ Takes all extracted medicine names and analyzes their interactions and provides comprehensive information
197
+ """
198
+ if not medicine_names or medicine_names.startswith("Error") or medicine_names.startswith("Please"):
199
+ return "Please extract valid medicine names first"
200
+
201
+ try:
202
+ # Parse the medicine names from the extracted text
203
+ medicine_lines = medicine_names.strip().split('\n')
204
+ cleaned_medicines = []
205
+
206
+ # Clean up medicine names (remove bullets, numbers, etc.)
207
+ for medicine in medicine_lines:
208
+ cleaned_medicine = medicine.lstrip('•-*0123456789. ').strip()
209
+ if cleaned_medicine:
210
+ cleaned_medicines.append(cleaned_medicine)
211
+
212
+ if not cleaned_medicines:
213
+ return "No valid medicine names found in extraction"
214
+
215
+ # Create a prompt for the LLM to analyze the full prescription
216
+ medicines_list = ", ".join(cleaned_medicines)
217
+
218
+ system_prompt = f"""You are a pharmaceutical expert analyzing a full prescription containing the following medicines: {medicines_list}.
219
+
220
+ Please provide a comprehensive analysis including:
221
+
222
+ 1. Purpose: The likely medical condition(s) being treated with this combination of medicines
223
+ 2. Potential interactions: Any known drug interactions between these medicines
224
+ 3. Side effects: Common side effects to watch for when taking this combination
225
+ 4. Recommendations: General advice for the patient taking these medicines
226
+ 5. Questions for the doctor: Important questions the patient should ask their healthcare provider
227
+
228
+ Base your analysis on pharmacological knowledge about these medicines and their typical uses.
229
+ """
230
+
231
+ # Initialize Together client with the API key
232
+ client = Together(api_key=api_key)
233
+
234
+ # Make API call
235
+ response = client.chat.completions.create(
236
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
237
+ messages=[
238
+ {
239
+ "role": "system",
240
+ "content": system_prompt
241
+ },
242
+ {
243
+ "role": "user",
244
+ "content": f"Please analyze this prescription with the following medicines: {medicines_list}"
245
+ }
246
+ ],
247
+ max_tokens=2000,
248
+ temperature=0.3 # Lower temperature for more factual responses
249
+ )
250
+
251
+ analysis_text = response.choices[0].message.content
252
+
253
+ # Add disclaimer
254
+ final_response = analysis_text + "\n\n---\n\n**DISCLAIMER:** This analysis is for informational purposes only and should not replace professional medical advice. Always consult with your healthcare provider about your prescription."
255
+
256
+ return final_response
257
+
258
+ except Exception as e:
259
+ return f"Error: {str(e)}"
260
+
261
+ # Create Gradio interface with tabs for all functionalities
262
  with gr.Blocks(title="Medicine Assistant") as app:
263
  gr.Markdown("# Medicine Assistant")
264
+ gr.Markdown("This application helps you extract medicine names from prescriptions, find alternative medicines, and analyze full prescriptions.")
265
 
266
  # API key input (shared between tabs)
267
  api_key_input = gr.Textbox(
 
271
  )
272
 
273
  # Create a file input for CSV that can be shared between tabs
 
274
  csv_file_input = gr.File(
275
  label="Upload Medicine CSV (Optional)",
276
  file_types=[".csv"],
277
+ type="filepath"
278
  )
279
  gr.Markdown("If no CSV is uploaded, the app will use the default 'medicine_dataset.csv' file.")
280
 
 
287
  with gr.Column():
288
  image_input = gr.Image(type="filepath", label="Upload Prescription Image")
289
  extract_btn = gr.Button("Extract Medicines")
 
290
 
291
  with gr.Column():
292
  extracted_output = gr.Textbox(label="Extracted Medicines", lines=10)
293
+
294
+ with gr.Row():
295
+ with gr.Column(scale=1):
296
+ recommend_from_extract_btn = gr.Button("Get Recommendations for First Medicine", variant="primary")
297
+ analyze_full_btn = gr.Button("Analyze Full Prescription", variant="secondary")
298
+
299
+ with gr.Column(scale=2):
300
+ output_tabs = gr.Tabs()
301
+ with output_tabs:
302
+ with gr.Tab("Recommendations"):
303
+ recommendation_from_extract_output = gr.Markdown()
304
+ with gr.Tab("Full Analysis"):
305
+ full_analysis_output = gr.Markdown()
306
 
307
  # Connect the buttons to functions
308
  extract_btn.click(
 
317
  outputs=recommendation_from_extract_output
318
  )
319
 
320
+ analyze_full_btn.click(
321
+ fn=analyze_full_prescription,
322
+ inputs=[api_key_input, extracted_output, csv_file_input],
323
+ outputs=full_analysis_output
324
+ )
325
+
326
  gr.Markdown("""
327
  ### How to use:
328
  1. Enter your Together API key
329
  2. Upload a clear image of a prescription
330
  3. Click 'Extract Medicines' to see the identified medicines
331
  4. Optionally upload a custom medicine dataset CSV
332
+ 5. Choose to:
333
+ - Get alternatives for the first medicine
334
+ - Analyze the entire prescription for interactions and information
335
 
336
  ### Note:
337
  - Your API key is used only for the current session
 
346
  with gr.Column():
347
  medicine_name = gr.Textbox(
348
  label="Medicine Name",
349
+ placeholder="Enter a medicine name (e.g., Augmentin 625 Duo)"
350
  )
351
  submit_btn = gr.Button("Get Recommendations", variant="primary")
352
 
353
  with gr.Column():
354
+ recommendation_output = gr.Markdown()
355
 
356
  submit_btn.click(
357
  recommend_medicine,
 
362
  gr.Markdown("""
363
  ## How to use this tool:
364
  1. Enter your Together API key (same key used across the application)
365
+ 2. Enter a medicine name - the AI will find it or match similar alternatives
366
  3. Click "Get Recommendations" to see alternatives
367
 
368
+ ### Features:
369
+ - Even if the exact medicine isn't in the database, the AI will try to find similar alternatives
370
+ - The system analyzes the medicine name to determine its likely purpose and composition
371
+ - Recommendations include substitutes, side effects, and usage information
 
 
 
 
 
 
372
  """)
373
 
374
  gr.Markdown("""
375
  ## About This Application
376
 
377
+ This Medicine Assistant application combines powerful tools powered by Large Language Models:
378
 
379
  1. **Prescription Medicine Extractor**: Uses computer vision AI to identify medicine names from prescription images
380
  2. **Medicine Alternative Recommender**: Provides detailed information about alternative medications
381
+ 3. **Prescription Analyzer**: Analyzes entire prescriptions for potential interactions and insights
382
 
383
+ All tools utilize the Together AI platform for advanced AI capabilities. Your API key is not stored and is only used to make API calls during your active session.
384
 
385
  ### Important Note
386