NitinBot001 commited on
Commit
d81d6ab
·
verified ·
1 Parent(s): 3c51633

Update medicine.py

Browse files
Files changed (1) hide show
  1. 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
- from dotenv import load_dotenv
6
- 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 = "Text_Files"
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 form data with 'query' (required) and 'file' (optional image upload).
90
- """
91
- # 1. Get and validate the request data
92
- form_data = request.form
93
- if not form_data or 'query' not in form_data:
94
- return jsonify({"error": "Missing 'query' in request"}), 400
95
-
96
- user_query = form_data.get('query')
97
- medicine_topic = None
98
-
99
- # 2. Handle File Upload (if provided)
100
- if 'file' in request.files:
101
- file = request.files['file']
102
- if file.filename == '':
103
- return jsonify({"error": "No selected file"}), 400
104
-
105
- if file and allowed_file(file.filename):
106
- try:
107
- print("Image file received. Identifying medicine from image...")
108
- # Read the uploaded file directly
109
- img = Image.open(file.stream)
110
-
111
- # Use the vision model to identify the medicine
112
- vision_model = genai.GenerativeModel('gemini-2.5-flash')
113
- prompt = ["""Identify the specific formula or Rx or medicine name or primary subject from this image.""", img]
114
- response = vision_model.generate_content(prompt)
115
-
116
- medicine_topic = response.text.strip()
117
- print(f"Medicine identified from image: {medicine_topic}")
118
-
119
- except Exception as e:
120
- print(f"Error processing image: {e}")
121
- return jsonify({"error": "Failed to process the uploaded image."}), 500
122
- else:
123
- return jsonify({"error": f"Invalid file type. Allowed types: {', '.join(ALLOWED_EXTENSIONS)}"}), 400
124
-
125
- # 3. Handle Text-Only Input (or use the topic identified from the image)
126
- if not medicine_topic:
127
- print("No image provided. Identifying topic from text query...")
128
- try:
129
- model = genai.GenerativeModel('gemini-2.5-flash')
130
- prompt = f"""
131
- From the user query '{user_query}', identify the main medicine or medical topic.
132
- Respond with only the name of the topic or medicine (e.g., 'Ibuprofen', 'Antacids', 'Cough Suppressants').
133
-
134
- """
135
- response = model.generate_content(prompt)
136
- medicine_topic = response.text.strip()
137
- print(f"Topic identified from query: {medicine_topic}")
138
- except Exception as e:
139
- print(f"Error identifying topic from query: {e}")
140
- return jsonify({"error": "Failed to understand the query topic."}), 500
141
-
142
- # 4. Find the Relevant Knowledge Base File
143
- relevant_filename = find_relevant_file(medicine_topic)
144
- if not relevant_filename:
145
- return jsonify({"error": f"Could not find a relevant information file for '{medicine_topic}'."}), 404
146
-
147
- # 5. Get the Context from the File
148
- context = get_context_from_file(relevant_filename)
149
- if not context:
150
- return jsonify({"error": "Failed to read the content of the relevant file."}), 500
151
-
152
- # 6. Generate the Final Response Using the Context
153
- try:
154
- model = genai.GenerativeModel('gemini-2.5-flash-lite')
155
- final_prompt = f"""
156
- You are a helpful medical information assistant.
157
- Your task is to answer the user's question based ONLY on the provided context from the guide.
158
- Generate response in same language as user query.
159
- If there have no information about any medicine then prepare response using given context and your knowlage base make sure there have satisfied answer.
160
- if there have any relevent medicine of provided medicine in context then prepare answer using that context.
161
- Answer should be in simple language and short not more than 200 words.
162
- 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.
163
- ---important---
164
- 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.
165
- user is also provide the medicine name and description of the medicine.
166
- name:{medicine_topic}
167
- ---important---
168
-
169
- --- CONTEXT FROM THE GUIDE ---
170
- {context}
171
- --- END OF CONTEXT ---
172
-
173
- USER'S QUESTION: {user_query}
174
-
175
- YOUR ANSWER:
176
- """
177
-
178
- final_response = model.generate_content(final_prompt)
179
-
180
- # 7. Return the final, context-aware response
181
- return jsonify({
182
- "response": final_response.text.strip(),
183
- "identified_topic": medicine_topic,
184
- "source_file": relevant_filename
185
- })
186
-
187
- except Exception as e:
188
- print(f"Error generating final response: {e}")
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)