Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,9 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
3 |
import os
|
4 |
import base64
|
|
|
5 |
|
6 |
def extract_medicines(api_key, image):
|
7 |
"""
|
@@ -56,39 +58,241 @@ def extract_medicines(api_key, image):
|
|
56 |
except Exception as e:
|
57 |
return f"Error: {str(e)}"
|
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 |
gr.Markdown("""
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
92 |
""")
|
93 |
|
94 |
# Launch the app
|
|
|
1 |
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
import os
|
5 |
import base64
|
6 |
+
from together import Together
|
7 |
|
8 |
def extract_medicines(api_key, image):
|
9 |
"""
|
|
|
58 |
except Exception as e:
|
59 |
return f"Error: {str(e)}"
|
60 |
|
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
|
68 |
+
if csv_file is not None:
|
69 |
+
# Read the uploaded CSV
|
70 |
+
if isinstance(csv_file, str): # Path to default CSV
|
71 |
+
df = pd.read_csv(csv_file)
|
72 |
+
else: # Uploaded file
|
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
|
87 |
+
- use0 through use4: Medical uses
|
88 |
+
- Chemical Class: The chemical classification
|
89 |
+
- Habit Forming: Whether the medicine is habit-forming
|
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)
|
137 |
+
|
138 |
+
# Make API call
|
139 |
+
response = client.chat.completions.create(
|
140 |
+
model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
|
141 |
+
messages=[
|
142 |
+
{
|
143 |
+
"role": "system",
|
144 |
+
"content": system_prompt
|
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)}"
|
159 |
+
|
160 |
+
def send_medicine_to_recommender(api_key, medicine_names, csv_file=None):
|
161 |
+
"""
|
162 |
+
Takes medicine names extracted from prescription and gets recommendations
|
163 |
+
"""
|
164 |
+
if not medicine_names or medicine_names.startswith("Error") or medicine_names.startswith("Please"):
|
165 |
+
return "Please extract valid medicine names first"
|
166 |
+
|
167 |
+
# Extract the first medicine name from the list (assuming it's the first line or first item)
|
168 |
+
medicine_lines = medicine_names.strip().split('\n')
|
169 |
+
if not medicine_lines:
|
170 |
+
return "No valid medicine name found in extraction results"
|
171 |
+
|
172 |
+
# Get the first medicine name (remove any bullet points or numbers)
|
173 |
+
first_medicine = medicine_lines[0]
|
174 |
+
# Clean up the medicine name (remove bullets, numbers, etc.)
|
175 |
+
first_medicine = first_medicine.lstrip('•-*0123456789. ').strip()
|
176 |
+
|
177 |
+
# Check if we have a valid medicine name
|
178 |
+
if not first_medicine:
|
179 |
+
return "Could not identify a valid medicine name from extraction"
|
180 |
+
|
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(
|
191 |
+
label="Together API Key",
|
192 |
+
placeholder="Enter your Together API key here...",
|
193 |
+
type="password"
|
194 |
)
|
195 |
|
196 |
+
with gr.Tabs():
|
197 |
+
with gr.Tab("Prescription Medicine Extractor"):
|
198 |
+
gr.Markdown("## Prescription Medicine Extractor")
|
199 |
+
gr.Markdown("Upload a prescription image to extract medicine names using Together AI's Llama-Vision-Free model.")
|
200 |
+
|
201 |
+
with gr.Row():
|
202 |
+
with gr.Column():
|
203 |
+
image_input = gr.Image(type="filepath", label="Upload Prescription Image")
|
204 |
+
extract_btn = gr.Button("Extract Medicines")
|
205 |
+
recommend_from_extract_btn = gr.Button("Get Recommendations for First Medicine")
|
206 |
+
|
207 |
+
with gr.Column():
|
208 |
+
extracted_output = gr.Textbox(label="Extracted Medicines", lines=10)
|
209 |
+
recommendation_from_extract_output = gr.Markdown(label="Recommendations")
|
210 |
+
|
211 |
+
# Connect the buttons to functions
|
212 |
+
extract_btn.click(
|
213 |
+
fn=extract_medicines,
|
214 |
+
inputs=[api_key_input, image_input],
|
215 |
+
outputs=extracted_output
|
216 |
+
)
|
217 |
+
|
218 |
+
recommend_from_extract_btn.click(
|
219 |
+
fn=send_medicine_to_recommender,
|
220 |
+
inputs=[api_key_input, extracted_output, None], # Pass None as csv_file to use default
|
221 |
+
outputs=recommendation_from_extract_output
|
222 |
+
)
|
223 |
+
|
224 |
+
gr.Markdown("""
|
225 |
+
### How to use:
|
226 |
+
1. Enter your Together API key
|
227 |
+
2. Upload a clear image of a prescription
|
228 |
+
3. Click 'Extract Medicines' to see the identified medicines
|
229 |
+
4. Optionally click 'Get Recommendations for First Medicine' to find alternatives
|
230 |
+
|
231 |
+
### Note:
|
232 |
+
- Your API key is used only for the current session
|
233 |
+
- For best results, ensure the prescription image is clear and readable
|
234 |
+
""")
|
235 |
+
|
236 |
+
with gr.Tab("Medicine Alternative Recommender"):
|
237 |
+
gr.Markdown("## Medicine Alternative Recommender")
|
238 |
+
gr.Markdown("This tool recommends alternative medicines based on an input medicine name using the Together API.")
|
239 |
+
|
240 |
+
with gr.Row():
|
241 |
+
with gr.Column():
|
242 |
+
medicine_name = gr.Textbox(
|
243 |
+
label="Medicine Name",
|
244 |
+
placeholder="Enter a medicine name exactly as it appears in the dataset"
|
245 |
+
)
|
246 |
+
csv_file = gr.File(
|
247 |
+
label="Upload Medicine CSV (Optional)",
|
248 |
+
file_types=[".csv"],
|
249 |
+
type="file"
|
250 |
+
)
|
251 |
+
gr.Markdown("If no CSV is uploaded, the app will use the default 'medicine_dataset.csv' file.")
|
252 |
+
|
253 |
+
submit_btn = gr.Button("Get Recommendations", variant="primary")
|
254 |
+
|
255 |
+
with gr.Column():
|
256 |
+
recommendation_output = gr.Markdown(label="Recommendations")
|
257 |
+
|
258 |
+
submit_btn.click(
|
259 |
+
recommend_medicine,
|
260 |
+
inputs=[api_key_input, medicine_name, csv_file],
|
261 |
+
outputs=recommendation_output
|
262 |
+
)
|
263 |
+
|
264 |
+
gr.Markdown("""
|
265 |
+
## How to use this tool:
|
266 |
+
1. Enter your Together API key (same key used across the application)
|
267 |
+
2. Enter a medicine name **exactly as it appears** in the CSV file
|
268 |
+
3. Optionally upload a custom medicine dataset CSV file (otherwise the default medicine_dataset.csv will be used)
|
269 |
+
4. Click "Get Recommendations" to see alternatives
|
270 |
+
|
271 |
+
### CSV Format Requirements:
|
272 |
+
The app expects a CSV with these columns:
|
273 |
+
- `name`: Medicine name
|
274 |
+
- `substitute0` through `substitute4`: Potential substitute medicines
|
275 |
+
- `sideEffect0` through `sideEffect41`: Possible side effects
|
276 |
+
- `use0` through `use4`: Medical uses
|
277 |
+
- `Chemical Class`: The chemical classification
|
278 |
+
- `Habit Forming`: Whether the medicine is habit-forming
|
279 |
+
- `Therapeutic Class`: The therapeutic classification
|
280 |
+
- `Action Class`: How the medicine works
|
281 |
+
""")
|
282 |
+
|
283 |
gr.Markdown("""
|
284 |
+
## About This Application
|
285 |
+
|
286 |
+
This Medicine Assistant application combines two powerful tools:
|
287 |
+
|
288 |
+
1. **Prescription Medicine Extractor**: Uses computer vision AI to identify medicine names from prescription images
|
289 |
+
2. **Medicine Alternative Recommender**: Provides detailed information about alternative medications
|
290 |
+
|
291 |
+
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.
|
292 |
+
|
293 |
+
### Important Note
|
294 |
+
|
295 |
+
This application is for informational purposes only. Always consult with a healthcare professional before making any changes to your medication regimen.
|
296 |
""")
|
297 |
|
298 |
# Launch the app
|