NitinBot001 commited on
Commit
38ba0de
·
verified ·
1 Parent(s): 3f6b886

Update medicine.py

Browse files
Files changed (1) hide show
  1. medicine.py +160 -112
medicine.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import os
2
  import io
3
  from flask import Flask, request, jsonify
@@ -7,190 +9,236 @@ import google.generativeai as genai
7
  import json
8
 
9
  # --- INITIAL SETUP ---
10
-
11
- # Load environment variables from the .env file
12
  load_dotenv()
13
 
14
- # Configure the Gemini API with your key
15
  api_key = os.getenv("GOOGLE_API_KEY")
16
  if not api_key:
17
  raise ValueError("GOOGLE_API_KEY not found. Please set it in your .env file.")
18
  genai.configure(api_key=api_key)
19
 
20
- # Initialize the Flask application
21
  app = Flask(__name__)
22
 
23
  # --- CONFIGURATION ---
24
  TEXT_FILES_DIR = "MEDICINE_TXT"
25
- # Allowed file extensions for image uploads
26
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
27
 
28
- # Get a list of available knowledge base files
29
  try:
 
30
  AVAILABLE_FILES = [f for f in os.listdir(TEXT_FILES_DIR) if f.endswith('.txt')]
31
  if not AVAILABLE_FILES:
32
- raise FileNotFoundError("No .txt files found in the 'Text_Files' directory.")
33
- except FileNotFoundError:
34
- print("Warning: 'Text_Files' directory not found. The API will not have a knowledge base.")
35
  AVAILABLE_FILES = []
36
 
37
  # --- HELPER FUNCTIONS ---
38
-
39
  def allowed_file(filename):
40
- return '.' in filename and \
41
- filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
42
 
43
- def find_relevant_file(topic: str) -> str | None:
44
- """
45
- Uses Gemini to determine the most relevant file for a given topic.
46
- This is more robust than simple keyword matching.
47
- """
48
  if not AVAILABLE_FILES:
49
  return None
50
 
51
  try:
52
- model = genai.GenerativeModel('gemini-2.5-flash-lite')
53
  prompt = f"""
54
- From the following list of files, which one is the most relevant for a query about "{topic}"?
55
- Respond with only the single, most relevant filename dont include any other text.
56
 
57
- File List:
58
- {', '.join(AVAILABLE_FILES)}
59
  """
60
  response = model.generate_content(prompt)
61
- # Clean up the response to get just the filename
62
- filename = response.text.strip().replace("`", "")
63
 
64
  if filename in AVAILABLE_FILES:
65
- print(f"Gemini identified relevant file: {filename} for topic: {topic}")
66
  return filename
67
  else:
68
- print(f"Warning: Gemini suggested a file that doesn't exist: {filename}")
69
  return None
70
  except Exception as e:
71
- print(f"Error in find_relevant_file: {e}")
72
  return None
73
 
74
- def get_context_from_file(filename: str) -> str | None:
75
- """Reads and returns the content of a specified text file."""
 
 
76
  filepath = os.path.join(TEXT_FILES_DIR, filename)
77
  try:
78
  with open(filepath, 'r', encoding='utf-8') as f:
79
- return f.read()
80
- except FileNotFoundError:
 
 
 
81
  return None
82
 
83
- # --- CORE API LOGIC ---
84
-
85
  @app.route('/api/query', methods=['POST'])
86
  def handle_query():
87
  """
88
- Main API endpoint to handle user queries.
89
- Accepts JSON data with 'query' (required) and 'file' (optional image upload).
90
  """
91
- # 1. Get and validate the request data
92
- if not request.is_json:
93
- return jsonify({"error": "Request must be in JSON format with 'query' field"}), 400
94
 
95
- data = request.get_json()
96
- user_query = data.get('query')
 
 
 
 
 
 
 
 
 
97
 
98
  if not user_query:
99
- return jsonify({"error": "Missing 'query' in request"}), 400
100
 
101
- # 2. Handle File Upload (if provided)
 
 
102
  if 'file' in request.files:
103
  file = request.files['file']
104
- if file.filename == '':
105
- return jsonify({"error": "No selected file"}), 400
106
-
107
- if file and allowed_file(file.filename):
108
  try:
109
- print("Image file received. Identifying medicine from image...")
110
- # Read the uploaded file directly
 
111
  img = Image.open(file.stream)
 
112
 
113
- # Use the vision model to identify the medicine
114
- vision_model = genai.GenerativeModel('gemini-2.5-flash')
115
- prompt = ["""Identify the specific formula or Rx or medicine name or primary subject from this image.""", img]
116
- response = vision_model.generate_content(prompt)
 
 
 
 
 
117
 
 
118
  medicine_topic = response.text.strip()
119
- print(f"Medicine identified from image: {medicine_topic}")
120
-
121
  except Exception as e:
122
  print(f"Error processing image: {e}")
123
- return jsonify({"error": "Failed to process the uploaded image."}), 500
124
- else:
125
- return jsonify({"error": f"Invalid file type. Allowed types: {', '.join(ALLOWED_EXTENSIONS)}"}), 400
126
 
127
- # 3. Handle Text-Only Input (or use the topic identified from the image)
128
- medicine_topic = None
129
  if not medicine_topic:
130
- print("No image provided. Identifying topic from text query...")
131
  try:
132
- model = genai.GenerativeModel('gemini-2.5-flash')
133
- prompt = f"""
134
- From the user query '{user_query}', identify the main medicine or medical topic.
135
- Respond with only the name of the topic or medicine (e.g., 'Ibuprofen', 'Antacids', 'Cough Suppressants').
136
-
137
  """
138
- response = model.generate_content(prompt)
139
  medicine_topic = response.text.strip()
140
- print(f"Topic identified from query: {medicine_topic}")
141
  except Exception as e:
142
- print(f"Error identifying topic from query: {e}")
143
- return jsonify({"error": "Failed to understand the query topic."}), 500
144
-
145
- # 4. Find the Relevant Knowledge Base File
146
- relevant_filename = find_relevant_file(medicine_topic)
147
- if not relevant_filename:
148
- return jsonify({"error": f"Could not find a relevant information file for '{medicine_topic}'."}), 404
149
-
150
- # 5. Get the Context from the File
151
- context = get_context_from_file(relevant_filename)
152
- if not context:
153
- return jsonify({"error": "Failed to read the content of the relevant file."}), 500
154
-
155
- # 6. Generate the Final Response Using the Context
156
  try:
157
- model = genai.GenerativeModel('gemini-2.5-flash-lite')
158
- final_prompt = f"""
159
- You are a helpful medical information assistant.
160
- Your task is to answer the user's question based ONLY on the provided context from the guide.
161
- Generate response in same language as user query.
162
- If there have no information about any medicine then prepare response using given context and your knowlage base make sure there have satisfied answer.
163
- if there have any relevent medicine of provided medicine in context then prepare answer using that context.
164
- Answer should be in simple language and short not more than 200 words.
165
- 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.
166
- ---important---
167
- 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.
168
- user is also provide the medicine name and description of the medicine.
169
- name:{medicine_topic}
170
- ---important---
171
 
172
- --- CONTEXT FROM THE GUIDE ---
173
- {context}
174
- --- END OF CONTEXT ---
175
-
176
- USER'S QUESTION: {user_query}
177
-
178
- YOUR ANSWER:
179
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- final_response = model.generate_content(final_prompt)
182
 
183
- # 7. Return the final, context-aware response
184
  return jsonify({
185
- "response": final_response.text.strip(),
 
186
  "identified_topic": medicine_topic,
187
- "source_file": relevant_filename
 
188
  })
189
-
190
  except Exception as e:
191
- print(f"Error generating final response: {e}")
192
- return jsonify({"error": "An error occurred while generating the response."}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  if __name__ == '__main__':
195
- # Runs the Flask server
 
 
 
 
 
196
  app.run(host='0.0.0.0', port=5002, debug=True)
 
1
+ # medicine.py - FIXED VERSION
2
+
3
  import os
4
  import io
5
  from flask import Flask, request, jsonify
 
9
  import json
10
 
11
  # --- INITIAL SETUP ---
 
 
12
  load_dotenv()
13
 
 
14
  api_key = os.getenv("GOOGLE_API_KEY")
15
  if not api_key:
16
  raise ValueError("GOOGLE_API_KEY not found. Please set it in your .env file.")
17
  genai.configure(api_key=api_key)
18
 
 
19
  app = Flask(__name__)
20
 
21
  # --- CONFIGURATION ---
22
  TEXT_FILES_DIR = "MEDICINE_TXT"
23
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}
 
24
 
25
+ # Check for available knowledge base files
26
  try:
27
+ os.makedirs(TEXT_FILES_DIR, exist_ok=True)
28
  AVAILABLE_FILES = [f for f in os.listdir(TEXT_FILES_DIR) if f.endswith('.txt')]
29
  if not AVAILABLE_FILES:
30
+ print(f"Warning: No .txt files found in '{TEXT_FILES_DIR}'. Running without knowledge base.")
31
+ except Exception as e:
32
+ print(f"Warning: Error accessing '{TEXT_FILES_DIR}': {e}")
33
  AVAILABLE_FILES = []
34
 
35
  # --- HELPER FUNCTIONS ---
 
36
  def allowed_file(filename):
37
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
38
 
39
+ def find_relevant_file(topic: str) -> str:
40
+ """Find the most relevant file for a given topic using Gemini"""
 
 
 
41
  if not AVAILABLE_FILES:
42
  return None
43
 
44
  try:
45
+ model = genai.GenerativeModel('gemini-2.0-flash-exp')
46
  prompt = f"""
47
+ From the following list of files, which one is most relevant for: "{topic}"?
48
+ Respond with ONLY the filename, nothing else.
49
 
50
+ Files: {', '.join(AVAILABLE_FILES)}
 
51
  """
52
  response = model.generate_content(prompt)
53
+ filename = response.text.strip().replace("`", "").replace('"', '')
 
54
 
55
  if filename in AVAILABLE_FILES:
56
+ print(f"Found relevant file: {filename} for topic: {topic}")
57
  return filename
58
  else:
59
+ print(f"No matching file found for: {topic}")
60
  return None
61
  except Exception as e:
62
+ print(f"Error finding relevant file: {e}")
63
  return None
64
 
65
+ def get_context_from_file(filename: str) -> str:
66
+ """Read content from a text file"""
67
+ if not filename:
68
+ return None
69
  filepath = os.path.join(TEXT_FILES_DIR, filename)
70
  try:
71
  with open(filepath, 'r', encoding='utf-8') as f:
72
+ content = f.read()
73
+ print(f"Successfully loaded context from {filename}")
74
+ return content
75
+ except Exception as e:
76
+ print(f"Error reading file {filename}: {e}")
77
  return None
78
 
79
+ # --- MAIN API ENDPOINT ---
 
80
  @app.route('/api/query', methods=['POST'])
81
  def handle_query():
82
  """
83
+ Handle medicine queries with optional image upload
84
+ Accepts both JSON and FormData
85
  """
 
 
 
86
 
87
+ # FIXED: Handle both JSON and FormData
88
+ user_query = None
89
+ medicine_topic = None
90
+
91
+ # Check if request is JSON
92
+ if request.is_json:
93
+ data = request.get_json()
94
+ user_query = data.get('main_query')
95
+ else:
96
+ # Handle FormData (when image is uploaded)
97
+ user_query = request.form.get('main_query')
98
 
99
  if not user_query:
100
+ return jsonify({"error": "Missing 'main_query' in request"}), 400
101
 
102
+ print(f"Received query: {user_query}")
103
+
104
+ # Handle image upload if present
105
  if 'file' in request.files:
106
  file = request.files['file']
107
+
108
+ if file and file.filename != '' and allowed_file(file.filename):
 
 
109
  try:
110
+ print(f"Processing uploaded image: {file.filename}")
111
+
112
+ # Process image with Gemini Vision
113
  img = Image.open(file.stream)
114
+ vision_model = genai.GenerativeModel('gemini-2.0-flash-exp')
115
 
116
+ vision_prompt = [
117
+ """Identify the medicine from this image. Look for:
118
+ - Medicine name or brand
119
+ - Active ingredients
120
+ - Rx number or formula
121
+ - Any text on packaging or pills
122
+ Respond with just the medicine name or main component.""",
123
+ img
124
+ ]
125
 
126
+ response = vision_model.generate_content(vision_prompt)
127
  medicine_topic = response.text.strip()
128
+ print(f"Identified from image: {medicine_topic}")
129
+
130
  except Exception as e:
131
  print(f"Error processing image: {e}")
132
+ # Continue without image data
 
 
133
 
134
+ # If no medicine identified from image, extract from query text
 
135
  if not medicine_topic:
 
136
  try:
137
+ model = genai.GenerativeModel('gemini-2.0-flash-exp')
138
+ extract_prompt = f"""
139
+ From this query: "{user_query}"
140
+ Extract the main medicine or medical topic being asked about.
141
+ Respond with ONLY the medicine/topic name (e.g., 'Paracetamol', 'Antibiotics')
142
  """
143
+ response = model.generate_content(extract_prompt)
144
  medicine_topic = response.text.strip()
145
+ print(f"Extracted topic from query: {medicine_topic}")
146
  except Exception as e:
147
+ print(f"Error extracting topic: {e}")
148
+ medicine_topic = "general medicine"
149
+
150
+ # Find relevant knowledge base file
151
+ context = None
152
+ source_file = None
153
+
154
+ if AVAILABLE_FILES:
155
+ relevant_file = find_relevant_file(medicine_topic)
156
+ if relevant_file:
157
+ context = get_context_from_file(relevant_file)
158
+ source_file = relevant_file
159
+
160
+ # Generate response
161
  try:
162
+ model = genai.GenerativeModel('gemini-2.0-flash-exp')
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ # Build prompt based on available context
165
+ if context:
166
+ final_prompt = f"""
167
+ You are a medical information assistant.
168
+
169
+ CONTEXT FROM KNOWLEDGE BASE:
170
+ {context}
171
+
172
+ IDENTIFIED MEDICINE/TOPIC: {medicine_topic}
173
+
174
+ USER QUESTION: {user_query}
175
+
176
+ Instructions:
177
+ - Answer based on the context if available
178
+ - Use simple language
179
+ - Keep response under 200 words
180
+ - Include dosage, usage, and warnings if relevant
181
+ - If context doesn't have the info, use general knowledge
182
+ - Respond in the same language as the user query
183
+ """
184
+ else:
185
+ final_prompt = f"""
186
+ You are a medical information assistant.
187
+
188
+ MEDICINE/TOPIC: {medicine_topic}
189
+ USER QUESTION: {user_query}
190
+
191
+ Provide accurate medical information about this topic.
192
+ - Use simple language
193
+ - Keep response under 200 words
194
+ - Include dosage, usage, side effects if relevant
195
+ - Add standard medical disclaimers
196
+ - Respond in the same language as the user query
197
+ """
198
 
199
+ response = model.generate_content(final_prompt)
200
 
 
201
  return jsonify({
202
+ "status": "success",
203
+ "response": response.text.strip(),
204
  "identified_topic": medicine_topic,
205
+ "source_file": source_file if source_file else "general_knowledge",
206
+ "knowledge_base_available": len(AVAILABLE_FILES) > 0
207
  })
208
+
209
  except Exception as e:
210
+ print(f"Error generating response: {e}")
211
+ return jsonify({
212
+ "error": "Failed to generate response",
213
+ "details": str(e)
214
+ }), 500
215
+
216
+ @app.route('/health', methods=['GET'])
217
+ def health_check():
218
+ """Health check endpoint"""
219
+ return jsonify({
220
+ "status": "running",
221
+ "service": "medicine_info",
222
+ "knowledge_base_files": len(AVAILABLE_FILES),
223
+ "port": 5002
224
+ })
225
+
226
+ @app.route('/', methods=['GET'])
227
+ def index():
228
+ """Basic info endpoint"""
229
+ return jsonify({
230
+ "service": "Medicine Information API",
231
+ "endpoint": "/api/query",
232
+ "methods": ["POST"],
233
+ "accepts": "JSON or FormData with 'main_query' and optional 'file'",
234
+ "knowledge_base": f"{len(AVAILABLE_FILES)} files available"
235
+ })
236
 
237
  if __name__ == '__main__':
238
+ print("="*50)
239
+ print("Starting Medicine Information Service")
240
+ print(f"Knowledge base: {len(AVAILABLE_FILES)} files in '{TEXT_FILES_DIR}'")
241
+ if AVAILABLE_FILES:
242
+ print(f"Available files: {', '.join(AVAILABLE_FILES[:5])}")
243
+ print("="*50)
244
  app.run(host='0.0.0.0', port=5002, debug=True)