Spaces:
Sleeping
Sleeping
Update medicine.py
Browse files- medicine.py +188 -192
medicine.py
CHANGED
|
@@ -1,193 +1,189 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
from flask import Flask, request, jsonify
|
| 4 |
-
from PIL import Image
|
| 5 |
-
|
| 6 |
-
import
|
| 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 |
-
def
|
| 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 |
-
file
|
| 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 |
-
---important---
|
| 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 |
-
return jsonify({"error": "An error occurred while generating the response."}), 500
|
| 190 |
-
|
| 191 |
-
if __name__ == '__main__':
|
| 192 |
-
# Runs the Flask server
|
| 193 |
app.run(host='0.0.0.0', port=5002, debug=True)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
from flask import Flask, request, jsonify
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import google.generativeai as genai
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# --- INITIAL SETUP ---
|
| 9 |
+
|
| 10 |
+
# Configure the Gemini API with your key
|
| 11 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 12 |
+
if not api_key:
|
| 13 |
+
raise ValueError("GOOGLE_API_KEY not found. Please set it in your .env file.")
|
| 14 |
+
genai.configure(api_key=api_key)
|
| 15 |
+
|
| 16 |
+
# Initialize the Flask application
|
| 17 |
+
app = Flask(__name__)
|
| 18 |
+
|
| 19 |
+
# --- CONFIGURATION ---
|
| 20 |
+
TEXT_FILES_DIR = "Text_Files"
|
| 21 |
+
# Allowed file extensions for image uploads
|
| 22 |
+
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
|
| 23 |
+
|
| 24 |
+
# Get a list of available knowledge base files
|
| 25 |
+
try:
|
| 26 |
+
AVAILABLE_FILES = [f for f in os.listdir(TEXT_FILES_DIR) if f.endswith('.txt')]
|
| 27 |
+
if not AVAILABLE_FILES:
|
| 28 |
+
raise FileNotFoundError("No .txt files found in the 'Text_Files' directory.")
|
| 29 |
+
except FileNotFoundError:
|
| 30 |
+
print("Warning: 'Text_Files' directory not found. The API will not have a knowledge base.")
|
| 31 |
+
AVAILABLE_FILES = []
|
| 32 |
+
|
| 33 |
+
# --- HELPER FUNCTIONS ---
|
| 34 |
+
|
| 35 |
+
def allowed_file(filename):
|
| 36 |
+
return '.' in filename and \
|
| 37 |
+
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 38 |
+
|
| 39 |
+
def find_relevant_file(topic: str) -> str | None:
|
| 40 |
+
"""
|
| 41 |
+
Uses Gemini to determine the most relevant file for a given topic.
|
| 42 |
+
This is more robust than simple keyword matching.
|
| 43 |
+
"""
|
| 44 |
+
if not AVAILABLE_FILES:
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
model = genai.GenerativeModel('gemini-2.5-flash-lite')
|
| 49 |
+
prompt = f"""
|
| 50 |
+
From the following list of files, which one is the most relevant for a query about "{topic}"?
|
| 51 |
+
Respond with only the single, most relevant filename dont include any other text.
|
| 52 |
+
|
| 53 |
+
File List:
|
| 54 |
+
{', '.join(AVAILABLE_FILES)}
|
| 55 |
+
"""
|
| 56 |
+
response = model.generate_content(prompt)
|
| 57 |
+
# Clean up the response to get just the filename
|
| 58 |
+
filename = response.text.strip().replace("`", "")
|
| 59 |
+
|
| 60 |
+
if filename in AVAILABLE_FILES:
|
| 61 |
+
print(f"Gemini identified relevant file: {filename} for topic: {topic}")
|
| 62 |
+
return filename
|
| 63 |
+
else:
|
| 64 |
+
print(f"Warning: Gemini suggested a file that doesn't exist: {filename}")
|
| 65 |
+
return None
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Error in find_relevant_file: {e}")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
def get_context_from_file(filename: str) -> str | None:
|
| 71 |
+
"""Reads and returns the content of a specified text file."""
|
| 72 |
+
filepath = os.path.join(TEXT_FILES_DIR, filename)
|
| 73 |
+
try:
|
| 74 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 75 |
+
return f.read()
|
| 76 |
+
except FileNotFoundError:
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
# --- CORE API LOGIC ---
|
| 80 |
+
|
| 81 |
+
@app.route('/api/query', methods=['POST'])
|
| 82 |
+
def handle_query():
|
| 83 |
+
"""
|
| 84 |
+
Main API endpoint to handle user queries.
|
| 85 |
+
Accepts form data with 'query' (required) and 'file' (optional image upload).
|
| 86 |
+
"""
|
| 87 |
+
# 1. Get and validate the request data
|
| 88 |
+
form_data = request.form
|
| 89 |
+
if not form_data or 'query' not in form_data:
|
| 90 |
+
return jsonify({"error": "Missing 'query' in request"}), 400
|
| 91 |
+
|
| 92 |
+
user_query = form_data.get('query')
|
| 93 |
+
medicine_topic = None
|
| 94 |
+
|
| 95 |
+
# 2. Handle File Upload (if provided)
|
| 96 |
+
if 'file' in request.files:
|
| 97 |
+
file = request.files['file']
|
| 98 |
+
if file.filename == '':
|
| 99 |
+
return jsonify({"error": "No selected file"}), 400
|
| 100 |
+
|
| 101 |
+
if file and allowed_file(file.filename):
|
| 102 |
+
try:
|
| 103 |
+
print("Image file received. Identifying medicine from image...")
|
| 104 |
+
# Read the uploaded file directly
|
| 105 |
+
img = Image.open(file.stream)
|
| 106 |
+
|
| 107 |
+
# Use the vision model to identify the medicine
|
| 108 |
+
vision_model = genai.GenerativeModel('gemini-2.5-flash')
|
| 109 |
+
prompt = ["""Identify the specific formula or Rx or medicine name or primary subject from this image.""", img]
|
| 110 |
+
response = vision_model.generate_content(prompt)
|
| 111 |
+
|
| 112 |
+
medicine_topic = response.text.strip()
|
| 113 |
+
print(f"Medicine identified from image: {medicine_topic}")
|
| 114 |
+
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"Error processing image: {e}")
|
| 117 |
+
return jsonify({"error": "Failed to process the uploaded image."}), 500
|
| 118 |
+
else:
|
| 119 |
+
return jsonify({"error": f"Invalid file type. Allowed types: {', '.join(ALLOWED_EXTENSIONS)}"}), 400
|
| 120 |
+
|
| 121 |
+
# 3. Handle Text-Only Input (or use the topic identified from the image)
|
| 122 |
+
if not medicine_topic:
|
| 123 |
+
print("No image provided. Identifying topic from text query...")
|
| 124 |
+
try:
|
| 125 |
+
model = genai.GenerativeModel('gemini-2.5-flash')
|
| 126 |
+
prompt = f"""
|
| 127 |
+
From the user query '{user_query}', identify the main medicine or medical topic.
|
| 128 |
+
Respond with only the name of the topic or medicine (e.g., 'Ibuprofen', 'Antacids', 'Cough Suppressants').
|
| 129 |
+
|
| 130 |
+
"""
|
| 131 |
+
response = model.generate_content(prompt)
|
| 132 |
+
medicine_topic = response.text.strip()
|
| 133 |
+
print(f"Topic identified from query: {medicine_topic}")
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error identifying topic from query: {e}")
|
| 136 |
+
return jsonify({"error": "Failed to understand the query topic."}), 500
|
| 137 |
+
|
| 138 |
+
# 4. Find the Relevant Knowledge Base File
|
| 139 |
+
relevant_filename = find_relevant_file(medicine_topic)
|
| 140 |
+
if not relevant_filename:
|
| 141 |
+
return jsonify({"error": f"Could not find a relevant information file for '{medicine_topic}'."}), 404
|
| 142 |
+
|
| 143 |
+
# 5. Get the Context from the File
|
| 144 |
+
context = get_context_from_file(relevant_filename)
|
| 145 |
+
if not context:
|
| 146 |
+
return jsonify({"error": "Failed to read the content of the relevant file."}), 500
|
| 147 |
+
|
| 148 |
+
# 6. Generate the Final Response Using the Context
|
| 149 |
+
try:
|
| 150 |
+
model = genai.GenerativeModel('gemini-2.5-flash-lite')
|
| 151 |
+
final_prompt = f"""
|
| 152 |
+
You are a helpful medical information assistant.
|
| 153 |
+
Your task is to answer the user's question based ONLY on the provided context from the guide.
|
| 154 |
+
Generate response in same language as user query.
|
| 155 |
+
If there have no information about any medicine then prepare response using given context and your knowlage base make sure there have satisfied answer.
|
| 156 |
+
if there have any relevent medicine of provided medicine in context then prepare answer using that context.
|
| 157 |
+
Answer should be in simple language and short not more than 200 words.
|
| 158 |
+
If the answer cannot be found in the provided context, then you have to prepare response using your knowlage base make sure there have satisfied answer.
|
| 159 |
+
---important---
|
| 160 |
+
Dont tell user to i have no information about that medicine. inplace of that prepare answer using given context and your knowlage base make sure there have satisfied answer.
|
| 161 |
+
user is also provide the medicine name and description of the medicine.
|
| 162 |
+
name:{medicine_topic}
|
| 163 |
+
---important---
|
| 164 |
+
|
| 165 |
+
--- CONTEXT FROM THE GUIDE ---
|
| 166 |
+
{context}
|
| 167 |
+
--- END OF CONTEXT ---
|
| 168 |
+
|
| 169 |
+
USER'S QUESTION: {user_query}
|
| 170 |
+
|
| 171 |
+
YOUR ANSWER:
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
final_response = model.generate_content(final_prompt)
|
| 175 |
+
|
| 176 |
+
# 7. Return the final, context-aware response
|
| 177 |
+
return jsonify({
|
| 178 |
+
"response": final_response.text.strip(),
|
| 179 |
+
"identified_topic": medicine_topic,
|
| 180 |
+
"source_file": relevant_filename
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print(f"Error generating final response: {e}")
|
| 185 |
+
return jsonify({"error": "An error occurred while generating the response."}), 500
|
| 186 |
+
|
| 187 |
+
if __name__ == '__main__':
|
| 188 |
+
# Runs the Flask server
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
app.run(host='0.0.0.0', port=5002, debug=True)
|