NitinBot001 commited on
Commit
86f1bd2
Β·
verified Β·
1 Parent(s): 8849838

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +749 -185
main.py CHANGED
@@ -1,252 +1,816 @@
1
- # main.py - FIXED VERSION
 
 
 
 
2
 
3
  import os
 
4
  import uuid
5
  import json
6
- import requests
 
7
  from flask import Flask, request, jsonify, send_from_directory
8
  from werkzeug.utils import secure_filename
 
9
  import google.generativeai as genai
10
  from dotenv import load_dotenv
11
  from flask_cors import CORS
 
 
 
12
 
13
- # Step 1: API Key and Environment Setup
 
 
 
 
 
 
 
14
  load_dotenv()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  try:
16
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
17
- except TypeError:
18
- print("ERROR: Google API Key not found.")
19
- print("Create a .env file and add 'GOOGLE_API_KEY=your_key_here'")
20
- exit()
21
 
 
22
  app = Flask(__name__, static_folder='.', static_url_path='')
23
  CORS(app)
 
24
 
25
- # Serve static files
26
- @app.route('/<path:path>')
27
- def serve_static(path):
28
- return send_from_directory('.', path)
29
 
30
- @app.route('/')
31
- def serve_index():
32
- return send_from_directory('.', 'index.html')
33
-
34
- # Step 2: FIXED API Endpoints
35
- API_ENDPOINTS = {
36
- "skin_disease": "http://localhost:5003/api/skin", # Update when ready
37
- "medicine_info": "http://localhost:5002/api/query",
38
- "report_reading": "http://localhost:5004/api/report", # Update when ready
39
- "disease_query": "http://localhost:5001/ask"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
 
42
- # Session storage
43
- SESSIONS = {}
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Step 3: Query Classification Function
46
- def classify_query_with_gemini(query: str):
47
- """Classify user query using Gemini API"""
48
- model = genai.GenerativeModel(os.getenv("MODEL","gemini-2.5-flash-lite"))
49
 
50
- prompt = f"""
51
- Analyze the user's medical query and classify it into one of the following categories:
52
- - skin_disease: For queries about skin conditions, rashes, moles, spots, or any visible symptoms on the skin.
53
- - medicine_info: For queries about medicines (usage, side effects, identification from image).
54
- - report_reading: For queries asking to interpret medical reports, lab tests, or blood work from images.
55
- - disease_query: For general questions about diseases, symptoms, causes, or treatments.
56
-
57
- Determine if an image is essential to answer the query accurately.
58
 
59
- User query: "{query}"
 
 
 
 
 
60
 
61
- Output ONLY valid JSON with "category" (string) and "image_required" (boolean).
 
 
 
 
62
 
63
- Example 1:
64
- Query: "what are the symptoms of typhoid"
65
- Output: {{"category": "disease_query", "image_required": false}}
 
 
66
 
67
- Example 2:
68
- Query: "I have a red circular rash on my arm, what is it?"
69
- Output: {{"category": "skin_disease", "image_required": true}}
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- Example 3:
72
- Query: "Can you tell me what this lab report says?"
73
- Output: {{"category": "report_reading", "image_required": true}}
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- Example 4:
76
- Query: "What is this white pill with 'IP 204' written on it?"
77
- Output: {{"category": "medicine_info", "image_required": true}}
78
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  try:
81
- response = model.generate_content(prompt)
82
- cleaned_text = response.text.strip().replace('```json', '').replace('```', '')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  result = json.loads(cleaned_text)
84
- print(f"Classification result: {result}")
 
 
 
 
 
 
85
  return result
 
86
  except Exception as e:
87
- print(f"Classification error: {e}")
88
- # Default fallback
89
  return {"category": "disease_query", "image_required": False}
90
 
91
- # Step 4: API Routes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  @app.route('/start_session', methods=['POST'])
93
  def start_session():
 
 
 
 
 
 
94
  session_id = str(uuid.uuid4())
95
- SESSIONS[session_id] = {"status": "started"}
96
- print(f"Session started: {session_id}")
 
 
 
 
 
97
  return jsonify({"session_id": session_id}), 200
98
 
99
  @app.route('/process_query', methods=['POST'])
100
  def process_query():
101
- data = request.get_json()
102
- session_id = data.get('session_id')
103
- query = data.get('query')
104
-
105
- if not session_id or session_id not in SESSIONS:
106
- return jsonify({"error": "Invalid or missing session_id"}), 400
107
- if not query:
108
- return jsonify({"error": "Query is required"}), 400
109
-
110
- print(f"Session {session_id}: Query received: '{query}'")
111
- classification = classify_query_with_gemini(query)
112
-
113
- SESSIONS[session_id]['classification'] = classification
114
- SESSIONS[session_id]['query'] = query
115
-
116
- if classification.get('image_required'):
117
- print(f"Session {session_id}: Image required for '{classification.get('category')}'")
118
- return jsonify({
119
- "status": "image_required",
120
- "message": "Please upload an image via /process_with_image endpoint",
121
- "category": classification.get('category')
122
- }), 200
123
- else:
124
- # Process without image
125
  category = classification['category']
126
- endpoint_url = API_ENDPOINTS.get(category)
127
 
128
- if not endpoint_url:
129
- return jsonify({"error": f"No endpoint configured for category: {category}"}), 500
 
 
 
 
130
 
131
- try:
132
- print(f"Forwarding to {category} API at {endpoint_url}")
133
-
134
- # FIXED: Proper request format for each service
135
- if category == "disease_query":
136
- # disease.py expects 'query' field
137
- response = requests.post(endpoint_url, json={"query": query})
138
- elif category == "medicine_info":
139
- # medicine.py expects 'main_query' field
140
- response = requests.post(endpoint_url, json={"main_query": query})
141
- else:
142
- # Default format for future services
143
- response = requests.post(endpoint_url, json={"query": query})
144
-
145
- response.raise_for_status()
146
- result = response.json()
147
-
148
- # Clean up session
149
- del SESSIONS[session_id]
150
- print(f"Session {session_id} closed successfully")
151
-
152
  return jsonify({
153
- "status": "success",
 
154
  "category": category,
155
- "response": result
156
- })
157
-
158
- except requests.exceptions.RequestException as e:
159
- print(f"Error calling {category} API: {e}")
160
- del SESSIONS[session_id]
161
- return jsonify({
162
- "error": f"Failed to reach {category} service",
163
- "details": str(e)
164
- }), 503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  @app.route('/process_with_image', methods=['POST'])
167
  def process_with_image():
168
- session_id = request.form.get('session_id')
169
-
170
- if not session_id or session_id not in SESSIONS:
171
- return jsonify({"error": "Invalid or missing session_id"}), 400
172
-
173
- if 'photo' not in request.files:
174
- return jsonify({"error": "No photo file found in request"}), 400
175
 
176
- file = request.files['photo']
177
- if file.filename == '':
178
- return jsonify({"error": "No file selected"}), 400
179
-
180
- # Get session data
181
- query = SESSIONS[session_id].get('query')
182
- classification = SESSIONS[session_id].get('classification')
183
- category = classification.get('category')
184
- endpoint_url = API_ENDPOINTS.get(category)
185
-
186
- if not endpoint_url:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  del SESSIONS[session_id]
188
- return jsonify({"error": f"No endpoint configured for category: {category}"}), 500
189
-
190
- print(f"Session {session_id}: Processing image for '{category}'")
 
 
 
 
 
191
 
 
 
 
192
  try:
193
- # FIXED: Proper request format based on category
194
- if category == "medicine_info":
195
- # medicine.py expects 'file' and 'main_query'
196
- files = {'file': (file.filename, file.stream, file.mimetype)}
197
- data = {'main_query': query}
198
- response = requests.post(endpoint_url, files=files, data=data)
199
-
200
- elif category == "disease_query":
201
- # disease.py doesn't typically need images, but if it did:
202
- files = {'file': (file.filename, file.stream, file.mimetype)}
203
- data = {'query': query}
204
- response = requests.post(endpoint_url, files=files, data=data)
205
-
206
- else:
207
- # Default format for skin_disease, report_reading
208
- files = {'file': (file.filename, file.stream, file.mimetype)}
209
- data = {'query': query}
210
- response = requests.post(endpoint_url, files=files, data=data)
211
 
212
- response.raise_for_status()
213
- result = response.json()
 
214
 
215
- # Clean up session
216
- del SESSIONS[session_id]
217
- print(f"Session {session_id} closed successfully")
 
 
 
218
 
219
  return jsonify({
220
  "status": "success",
221
- "category": category,
222
- "response": result
223
  })
 
 
 
 
224
 
225
- except requests.exceptions.RequestException as e:
226
- print(f"Error calling {category} API with image: {e}")
227
- del SESSIONS[session_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  return jsonify({
229
- "error": f"Failed to reach {category} service",
230
- "details": str(e)
231
- }), 503
 
 
 
 
 
232
 
233
  @app.route('/health', methods=['GET'])
234
  def health_check():
235
- """Health check endpoint to verify services"""
236
- service_status = {}
237
-
238
- for service, url in API_ENDPOINTS.items():
239
- try:
240
- # Try to connect to each service
241
- if "localhost" in url:
242
- test_url = url.replace('/ask', '').replace('/api/query', '')
243
- requests.get(test_url, timeout=1)
244
- service_status[service] = "βœ… Running"
245
- except:
246
- service_status[service] = "❌ Not reachable"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  return jsonify({
249
- "main_service": "βœ… Running",
250
- "connected_services": service_status,
251
- "sessions_active": len(SESSIONS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # integrated_medical_system.py - Production Ready Single File
2
+ """
3
+ Integrated Medical Information System
4
+ Combines disease queries, medicine information, and image analysis
5
+ """
6
 
7
  import os
8
+ import io
9
  import uuid
10
  import json
11
+ import time
12
+ from datetime import datetime, timedelta
13
  from flask import Flask, request, jsonify, send_from_directory
14
  from werkzeug.utils import secure_filename
15
+ from PIL import Image
16
  import google.generativeai as genai
17
  from dotenv import load_dotenv
18
  from flask_cors import CORS
19
+ import logging
20
+ from functools import wraps
21
+ import threading
22
 
23
+ # Configure logging
24
+ logging.basicConfig(
25
+ level=logging.INFO,
26
+ format='%(asctime)s - %(levelname)s - %(message)s'
27
+ )
28
+ logger = logging.getLogger(__name__)
29
+
30
+ # Load environment variables
31
  load_dotenv()
32
+
33
+ # Configuration
34
+ CONFIG = {
35
+ 'GOOGLE_API_KEY': os.getenv("GOOGLE_API_KEY"),
36
+ 'MODEL': os.getenv("MODEL", "gemini-2.0-flash-exp"),
37
+ 'DISEASE_FACT_SHEETS_DIR': "Text_Files",
38
+ 'MEDICINE_KNOWLEDGE_DIR': "MEDICINE_TXT",
39
+ 'ALLOWED_EXTENSIONS': {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'txt'},
40
+ 'MAX_FILE_SIZE': 16 * 1024 * 1024, # 16MB
41
+ 'SESSION_TIMEOUT': 300, # 5 minutes
42
+ 'RATE_LIMIT_PER_MINUTE': 60
43
+ }
44
+
45
+ # Validate API key
46
+ if not CONFIG['GOOGLE_API_KEY']:
47
+ logger.error("GOOGLE_API_KEY not found in environment variables")
48
+ raise ValueError("GOOGLE_API_KEY is required. Please set it in your .env file")
49
+
50
+ # Configure Gemini AI
51
  try:
52
+ genai.configure(api_key=CONFIG['GOOGLE_API_KEY'])
53
+ logger.info("βœ… Gemini AI configured successfully")
54
+ except Exception as e:
55
+ logger.error(f"❌ Error configuring Gemini AI: {e}")
56
+ raise
57
 
58
+ # Initialize Flask app
59
  app = Flask(__name__, static_folder='.', static_url_path='')
60
  CORS(app)
61
+ app.config['MAX_CONTENT_LENGTH'] = CONFIG['MAX_FILE_SIZE']
62
 
63
+ # Global storage
64
+ SESSIONS = {}
65
+ RATE_LIMITS = {}
 
66
 
67
+ # Create necessary directories
68
+ for directory in [CONFIG['DISEASE_FACT_SHEETS_DIR'], CONFIG['MEDICINE_KNOWLEDGE_DIR']]:
69
+ os.makedirs(directory, exist_ok=True)
70
+
71
+ # System Instructions
72
+ SYSTEM_INSTRUCTIONS = {
73
+ 'disease': """
74
+ You are a helpful Health Fact Sheet Assistant. Answer questions about diseases
75
+ based on provided fact sheets or general medical knowledge.
76
+ - Use fact sheet content when available
77
+ - Provide clear, accurate medical information
78
+ - Include disclaimers when using general knowledge
79
+ - Keep responses concise and helpful
80
+ - Respond in the same language as the user query
81
+ """,
82
+
83
+ 'medicine': """
84
+ You are a Medicine Information Assistant. Provide accurate information about
85
+ medications, their uses, dosages, and side effects.
86
+ - Use knowledge base when available
87
+ - Provide dosage and usage instructions
88
+ - Include important warnings and side effects
89
+ - Add medical disclaimers
90
+ - Keep responses under 300 words
91
+ - Respond in the same language as the user query
92
+ """,
93
+
94
+ 'classifier': """
95
+ You are a medical query classifier. Classify queries into these categories:
96
+ - disease_query: General questions about diseases, symptoms, causes, treatments
97
+ - medicine_info: Questions about medicines, drugs, medications, pills
98
+ - skin_disease: Questions about skin conditions, rashes, moles, visible skin issues
99
+ - report_reading: Questions about interpreting medical reports, lab results, test results
100
+
101
+ Also determine if an image is essential for accurate diagnosis/analysis.
102
+ """
103
  }
104
 
105
+ # Utility Functions
106
+ def cleanup_expired_sessions():
107
+ """Remove expired sessions"""
108
+ current_time = time.time()
109
+ expired_sessions = [
110
+ session_id for session_id, data in SESSIONS.items()
111
+ if current_time - data.get('created', 0) > CONFIG['SESSION_TIMEOUT']
112
+ ]
113
+ for session_id in expired_sessions:
114
+ del SESSIONS[session_id]
115
+ if expired_sessions:
116
+ logger.info(f"Cleaned up {len(expired_sessions)} expired sessions")
117
 
118
+ def rate_limit_check(client_ip):
119
+ """Simple rate limiting"""
120
+ current_time = time.time()
121
+ minute_ago = current_time - 60
122
 
123
+ if client_ip not in RATE_LIMITS:
124
+ RATE_LIMITS[client_ip] = []
125
+
126
+ # Clean old requests
127
+ RATE_LIMITS[client_ip] = [
128
+ req_time for req_time in RATE_LIMITS[client_ip]
129
+ if req_time > minute_ago
130
+ ]
131
 
132
+ # Check limit
133
+ if len(RATE_LIMITS[client_ip]) >= CONFIG['RATE_LIMIT_PER_MINUTE']:
134
+ return False
135
+
136
+ RATE_LIMITS[client_ip].append(current_time)
137
+ return True
138
 
139
+ def allowed_file(filename, file_type='image'):
140
+ """Check if file extension is allowed"""
141
+ if not filename or '.' not in filename:
142
+ return False
143
+ extension = filename.rsplit('.', 1)[1].lower()
144
 
145
+ if file_type == 'image':
146
+ return extension in {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}
147
+ elif file_type == 'text':
148
+ return extension == 'txt'
149
+ return extension in CONFIG['ALLOWED_EXTENSIONS']
150
 
151
+ def safe_gemini_call(model_name, prompt, image=None, max_retries=3):
152
+ """Make safe Gemini API calls with retries"""
153
+ for attempt in range(max_retries):
154
+ try:
155
+ model = genai.GenerativeModel(model_name)
156
+ if image:
157
+ response = model.generate_content([prompt, image])
158
+ else:
159
+ response = model.generate_content(prompt)
160
+ return response.text.strip()
161
+ except Exception as e:
162
+ logger.warning(f"Gemini API attempt {attempt + 1} failed: {e}")
163
+ if attempt == max_retries - 1:
164
+ raise
165
+ time.sleep(1 * (attempt + 1)) # Exponential backoff
166
 
167
+ # Core Functions
168
+ def get_available_diseases():
169
+ """Get list of available disease fact sheets"""
170
+ try:
171
+ if not os.path.isdir(CONFIG['DISEASE_FACT_SHEETS_DIR']):
172
+ return []
173
+ return [
174
+ os.path.splitext(f)[0].replace('_', ' ')
175
+ for f in os.listdir(CONFIG['DISEASE_FACT_SHEETS_DIR'])
176
+ if f.endswith('.txt')
177
+ ]
178
+ except Exception as e:
179
+ logger.error(f"Error getting available diseases: {e}")
180
+ return []
181
 
182
+ def get_disease_fact_sheet(disease_name):
183
+ """Read disease fact sheet content"""
184
+ try:
185
+ filename = disease_name.replace(' ', '_') + '.txt'
186
+ filepath = os.path.join(CONFIG['DISEASE_FACT_SHEETS_DIR'], filename)
187
+
188
+ if os.path.exists(filepath):
189
+ with open(filepath, 'r', encoding='utf-8') as f:
190
+ content = f.read()
191
+ logger.info(f"Found fact sheet for: {disease_name}")
192
+ return {"disease": disease_name, "content": content}
193
+ else:
194
+ logger.warning(f"No fact sheet found for: {disease_name}")
195
+ return {"error": f"Fact sheet not found for: {disease_name}"}
196
+ except Exception as e:
197
+ logger.error(f"Error reading fact sheet for {disease_name}: {e}")
198
+ return {"error": f"Error reading fact sheet: {str(e)}"}
199
+
200
+ def get_available_medicine_files():
201
+ """Get available medicine knowledge base files"""
202
+ try:
203
+ if not os.path.isdir(CONFIG['MEDICINE_KNOWLEDGE_DIR']):
204
+ return []
205
+ return [
206
+ f for f in os.listdir(CONFIG['MEDICINE_KNOWLEDGE_DIR'])
207
+ if f.endswith('.txt')
208
+ ]
209
+ except Exception as e:
210
+ logger.error(f"Error getting medicine files: {e}")
211
+ return []
212
+
213
+ def find_relevant_medicine_file(topic):
214
+ """Find most relevant medicine file for topic"""
215
+ available_files = get_available_medicine_files()
216
+ if not available_files:
217
+ return None
218
+
219
+ try:
220
+ prompt = f"""
221
+ From these files, which is most relevant for: "{topic}"?
222
+ Respond with ONLY the filename, nothing else.
223
+ Files: {', '.join(available_files)}
224
+ """
225
+ response = safe_gemini_call(CONFIG['MODEL'], prompt)
226
+ filename = response.replace('`', '').replace('"', '').strip()
227
+
228
+ return filename if filename in available_files else None
229
+ except Exception as e:
230
+ logger.error(f"Error finding relevant medicine file: {e}")
231
+ return None
232
+
233
+ def get_medicine_context(filename):
234
+ """Read medicine knowledge base file"""
235
+ if not filename:
236
+ return None
237
 
238
  try:
239
+ filepath = os.path.join(CONFIG['MEDICINE_KNOWLEDGE_DIR'], filename)
240
+ with open(filepath, 'r', encoding='utf-8') as f:
241
+ return f.read()
242
+ except Exception as e:
243
+ logger.error(f"Error reading medicine file {filename}: {e}")
244
+ return None
245
+
246
+ def classify_query(query):
247
+ """Classify user query using Gemini"""
248
+ try:
249
+ prompt = f"""
250
+ {SYSTEM_INSTRUCTIONS['classifier']}
251
+
252
+ User query: "{query}"
253
+
254
+ Output ONLY valid JSON with "category" (string) and "image_required" (boolean).
255
+
256
+ Examples:
257
+ {{"category": "disease_query", "image_required": false}}
258
+ {{"category": "medicine_info", "image_required": true}}
259
+ {{"category": "skin_disease", "image_required": true}}
260
+ {{"category": "report_reading", "image_required": true}}
261
+ """
262
+
263
+ response = safe_gemini_call(CONFIG['MODEL'], prompt)
264
+ cleaned_text = response.replace('```json', '').replace('```', '').strip()
265
  result = json.loads(cleaned_text)
266
+
267
+ # Validate result
268
+ valid_categories = ['disease_query', 'medicine_info', 'skin_disease', 'report_reading']
269
+ if result.get('category') not in valid_categories:
270
+ result['category'] = 'disease_query'
271
+
272
+ logger.info(f"Query classified as: {result}")
273
  return result
274
+
275
  except Exception as e:
276
+ logger.error(f"Classification error: {e}")
 
277
  return {"category": "disease_query", "image_required": False}
278
 
279
+ def process_disease_query(query):
280
+ """Process disease-related queries"""
281
+ try:
282
+ available_diseases = get_available_diseases()
283
+
284
+ # Try to find relevant disease in query
285
+ relevant_disease = None
286
+ for disease in available_diseases:
287
+ if disease.lower() in query.lower():
288
+ relevant_disease = disease
289
+ break
290
+
291
+ context = ""
292
+ source = "general_knowledge"
293
+
294
+ if relevant_disease:
295
+ fact_sheet = get_disease_fact_sheet(relevant_disease)
296
+ if 'content' in fact_sheet:
297
+ context = f"FACT SHEET FOR {relevant_disease}:\n{fact_sheet['content']}"
298
+ source = f"fact_sheet_{relevant_disease}"
299
+
300
+ prompt = f"""
301
+ {SYSTEM_INSTRUCTIONS['disease']}
302
+
303
+ {context}
304
+
305
+ User question: "{query}"
306
+
307
+ Available diseases with fact sheets: {', '.join(available_diseases) if available_diseases else 'None'}
308
+
309
+ Provide a helpful, accurate response. If using general knowledge, include appropriate disclaimers.
310
+ """
311
+
312
+ response = safe_gemini_call(CONFIG['MODEL'], prompt)
313
+
314
+ return {
315
+ "status": "success",
316
+ "response": response,
317
+ "source": source,
318
+ "available_diseases": len(available_diseases)
319
+ }
320
+
321
+ except Exception as e:
322
+ logger.error(f"Error processing disease query: {e}")
323
+ return {"error": f"Failed to process disease query: {str(e)}"}
324
+
325
+ def process_medicine_query(query, image=None):
326
+ """Process medicine-related queries"""
327
+ try:
328
+ medicine_topic = None
329
+
330
+ # If image provided, analyze it first
331
+ if image:
332
+ vision_prompt = """
333
+ Identify the medicine from this image. Look for:
334
+ - Medicine name or brand
335
+ - Active ingredients
336
+ - Any text on packaging or pills
337
+ Respond with just the medicine name or main component.
338
+ """
339
+ medicine_topic = safe_gemini_call(CONFIG['MODEL'], vision_prompt, image)
340
+ logger.info(f"Medicine identified from image: {medicine_topic}")
341
+
342
+ # If no medicine from image, extract from query
343
+ if not medicine_topic:
344
+ extract_prompt = f"""
345
+ From this query: "{query}"
346
+ Extract the main medicine or medical topic being asked about.
347
+ Respond with ONLY the medicine/topic name.
348
+ """
349
+ medicine_topic = safe_gemini_call(CONFIG['MODEL'], extract_prompt)
350
+
351
+ # Find relevant knowledge base file
352
+ context = None
353
+ source_file = find_relevant_medicine_file(medicine_topic)
354
+ if source_file:
355
+ context = get_medicine_context(source_file)
356
+
357
+ # Build prompt
358
+ if context:
359
+ prompt = f"""
360
+ {SYSTEM_INSTRUCTIONS['medicine']}
361
+
362
+ KNOWLEDGE BASE CONTEXT:
363
+ {context}
364
+
365
+ IDENTIFIED MEDICINE/TOPIC: {medicine_topic}
366
+ USER QUESTION: {query}
367
+
368
+ Answer based on the knowledge base context when available.
369
+ """
370
+ else:
371
+ prompt = f"""
372
+ {SYSTEM_INSTRUCTIONS['medicine']}
373
+
374
+ MEDICINE/TOPIC: {medicine_topic}
375
+ USER QUESTION: {query}
376
+
377
+ Provide accurate medical information about this medicine/topic.
378
+ """
379
+
380
+ response = safe_gemini_call(CONFIG['MODEL'], prompt)
381
+
382
+ return {
383
+ "status": "success",
384
+ "response": response,
385
+ "identified_topic": medicine_topic,
386
+ "source_file": source_file or "general_knowledge",
387
+ "knowledge_base_files": len(get_available_medicine_files())
388
+ }
389
+
390
+ except Exception as e:
391
+ logger.error(f"Error processing medicine query: {e}")
392
+ return {"error": f"Failed to process medicine query: {str(e)}"}
393
+
394
+ def process_skin_disease_query(query, image=None):
395
+ """Process skin disease queries (placeholder for future implementation)"""
396
+ try:
397
+ if image:
398
+ prompt = f"""
399
+ You are a dermatology assistant. Analyze this skin image and the user's query: "{query}"
400
+
401
+ Provide information about possible skin conditions, but always include:
402
+ - This is not a medical diagnosis
403
+ - Recommend seeing a dermatologist
404
+ - General skin care advice
405
+
406
+ Keep response under 250 words.
407
+ """
408
+ response = safe_gemini_call(CONFIG['MODEL'], prompt, image)
409
+ else:
410
+ response = f"""
411
+ Regarding your skin concern: "{query}"
412
+
413
+ For accurate diagnosis of skin conditions, a visual examination is usually necessary.
414
+ I recommend:
415
+ - Consulting with a dermatologist
416
+ - Taking clear photos in good lighting if seeking online consultation
417
+ - Noting any changes, symptoms, or triggers
418
+
419
+ If this is urgent (rapid changes, pain, bleeding), please seek immediate medical attention.
420
+ """
421
+
422
+ return {
423
+ "status": "success",
424
+ "response": response,
425
+ "category": "skin_disease",
426
+ "disclaimer": "This is not medical diagnosis. Consult a dermatologist."
427
+ }
428
+
429
+ except Exception as e:
430
+ logger.error(f"Error processing skin disease query: {e}")
431
+ return {"error": f"Failed to process skin disease query: {str(e)}"}
432
+
433
+ def process_report_reading_query(query, image=None):
434
+ """Process medical report reading queries (placeholder for future implementation)"""
435
+ try:
436
+ if image:
437
+ prompt = f"""
438
+ You are a medical report analysis assistant. The user asks: "{query}"
439
+
440
+ Analyze this medical report/lab result image and provide:
441
+ - Key findings in simple language
442
+ - What the values typically indicate
443
+ - Important notes or abnormalities
444
+
445
+ Always include:
446
+ - This is not a medical interpretation
447
+ - Results should be discussed with healthcare provider
448
+ - Context and medical history are important for interpretation
449
+
450
+ Keep response under 300 words.
451
+ """
452
+ response = safe_gemini_call(CONFIG['MODEL'], prompt, image)
453
+ else:
454
+ response = f"""
455
+ To help interpret medical reports or lab results, I would need to see the actual report image.
456
+
457
+ However, please remember:
458
+ - Medical reports should always be discussed with your healthcare provider
459
+ - Lab values can vary by laboratory and individual circumstances
460
+ - Context, symptoms, and medical history are crucial for proper interpretation
461
+
462
+ If you have urgent concerns about your results, contact your healthcare provider immediately.
463
+ """
464
+
465
+ return {
466
+ "status": "success",
467
+ "response": response,
468
+ "category": "report_reading",
469
+ "disclaimer": "This is not medical interpretation. Consult your healthcare provider."
470
+ }
471
+
472
+ except Exception as e:
473
+ logger.error(f"Error processing report reading query: {e}")
474
+ return {"error": f"Failed to process report reading query: {str(e)}"}
475
+
476
+ # Background cleanup task
477
+ def background_cleanup():
478
+ """Background task to clean up expired sessions"""
479
+ while True:
480
+ try:
481
+ cleanup_expired_sessions()
482
+ time.sleep(60) # Run every minute
483
+ except Exception as e:
484
+ logger.error(f"Cleanup task error: {e}")
485
+
486
+ # Start background thread
487
+ cleanup_thread = threading.Thread(target=background_cleanup, daemon=True)
488
+ cleanup_thread.start()
489
+
490
+ # API Routes
491
+ @app.route('/')
492
+ def serve_index():
493
+ """Serve main page"""
494
+ try:
495
+ return send_from_directory('.', 'index.html')
496
+ except:
497
+ return jsonify({
498
+ "service": "Integrated Medical Information System",
499
+ "status": "running",
500
+ "endpoints": {
501
+ "/start_session": "POST - Start new session",
502
+ "/process_query": "POST - Process text query",
503
+ "/process_with_image": "POST - Process query with image",
504
+ "/upload_fact_sheet": "POST - Upload disease fact sheet",
505
+ "/upload_medicine_info": "POST - Upload medicine info",
506
+ "/health": "GET - Health check",
507
+ "/stats": "GET - System statistics"
508
+ }
509
+ })
510
+
511
+ @app.route('/<path:path>')
512
+ def serve_static(path):
513
+ """Serve static files"""
514
+ return send_from_directory('.', path)
515
+
516
  @app.route('/start_session', methods=['POST'])
517
  def start_session():
518
+ """Start a new session"""
519
+ # Rate limiting
520
+ client_ip = request.remote_addr
521
+ if not rate_limit_check(client_ip):
522
+ return jsonify({"error": "Rate limit exceeded"}), 429
523
+
524
  session_id = str(uuid.uuid4())
525
+ SESSIONS[session_id] = {
526
+ "status": "started",
527
+ "created": time.time(),
528
+ "ip": client_ip
529
+ }
530
+
531
+ logger.info(f"Session started: {session_id} from {client_ip}")
532
  return jsonify({"session_id": session_id}), 200
533
 
534
  @app.route('/process_query', methods=['POST'])
535
  def process_query():
536
+ """Process text-only queries"""
537
+ try:
538
+ data = request.get_json()
539
+ session_id = data.get('session_id')
540
+ query = data.get('query')
541
+
542
+ if not session_id or session_id not in SESSIONS:
543
+ return jsonify({"error": "Invalid or missing session_id"}), 400
544
+
545
+ if not query:
546
+ return jsonify({"error": "Query is required"}), 400
547
+
548
+ logger.info(f"Session {session_id}: Processing query: '{query}'")
549
+
550
+ # Classify query
551
+ classification = classify_query(query)
 
 
 
 
 
 
 
 
552
  category = classification['category']
553
+ image_required = classification.get('image_required', False)
554
 
555
+ # Store classification in session
556
+ SESSIONS[session_id].update({
557
+ 'classification': classification,
558
+ 'query': query,
559
+ 'last_activity': time.time()
560
+ })
561
 
562
+ if image_required:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563
  return jsonify({
564
+ "status": "image_required",
565
+ "message": "Please upload an image for better analysis",
566
  "category": category,
567
+ "session_id": session_id
568
+ }), 200
569
+
570
+ # Process query based on category
571
+ if category == 'disease_query':
572
+ result = process_disease_query(query)
573
+ elif category == 'medicine_info':
574
+ result = process_medicine_query(query)
575
+ elif category == 'skin_disease':
576
+ result = process_skin_disease_query(query)
577
+ elif category == 'report_reading':
578
+ result = process_report_reading_query(query)
579
+ else:
580
+ result = {"error": f"Unknown category: {category}"}
581
+
582
+ # Clean up session
583
+ del SESSIONS[session_id]
584
+ logger.info(f"Session {session_id} completed successfully")
585
+
586
+ result['category'] = category
587
+ return jsonify(result)
588
+
589
+ except Exception as e:
590
+ logger.error(f"Error processing query: {e}")
591
+ return jsonify({"error": f"Failed to process query: {str(e)}"}), 500
592
 
593
  @app.route('/process_with_image', methods=['POST'])
594
  def process_with_image():
595
+ """Process queries with image upload"""
596
+ try:
597
+ session_id = request.form.get('session_id')
 
 
 
 
598
 
599
+ if not session_id or session_id not in SESSIONS:
600
+ return jsonify({"error": "Invalid or missing session_id"}), 400
601
+
602
+ if 'photo' not in request.files:
603
+ return jsonify({"error": "No photo file found"}), 400
604
+
605
+ file = request.files['photo']
606
+ if file.filename == '' or not allowed_file(file.filename, 'image'):
607
+ return jsonify({"error": "Invalid image file"}), 400
608
+
609
+ # Get session data
610
+ session = SESSIONS[session_id]
611
+ query = session.get('query')
612
+ classification = session.get('classification', {})
613
+ category = classification.get('category', 'disease_query')
614
+
615
+ logger.info(f"Session {session_id}: Processing image for category '{category}'")
616
+
617
+ # Process image
618
+ try:
619
+ image = Image.open(file.stream)
620
+ # Convert to RGB if needed
621
+ if image.mode != 'RGB':
622
+ image = image.convert('RGB')
623
+ except Exception as e:
624
+ logger.error(f"Error processing image: {e}")
625
+ return jsonify({"error": "Invalid image format"}), 400
626
+
627
+ # Process based on category
628
+ if category == 'medicine_info':
629
+ result = process_medicine_query(query, image)
630
+ elif category == 'skin_disease':
631
+ result = process_skin_disease_query(query, image)
632
+ elif category == 'report_reading':
633
+ result = process_report_reading_query(query, image)
634
+ else:
635
+ # Fallback to disease query
636
+ result = process_disease_query(query)
637
+
638
+ # Clean up session
639
  del SESSIONS[session_id]
640
+ logger.info(f"Session {session_id} with image completed successfully")
641
+
642
+ result['category'] = category
643
+ return jsonify(result)
644
+
645
+ except Exception as e:
646
+ logger.error(f"Error processing query with image: {e}")
647
+ return jsonify({"error": f"Failed to process query with image: {str(e)}"}), 500
648
 
649
+ @app.route('/upload_fact_sheet', methods=['POST'])
650
+ def upload_fact_sheet():
651
+ """Upload disease fact sheet"""
652
  try:
653
+ if 'file' not in request.files:
654
+ return jsonify({"error": "No file provided"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
 
656
+ file = request.files['file']
657
+ if not file.filename or not allowed_file(file.filename, 'text'):
658
+ return jsonify({"error": "Invalid file. Must be a .txt file"}), 400
659
 
660
+ # Secure filename
661
+ filename = secure_filename(file.filename)
662
+ filepath = os.path.join(CONFIG['DISEASE_FACT_SHEETS_DIR'], filename)
663
+
664
+ file.save(filepath)
665
+ logger.info(f"Disease fact sheet uploaded: {filename}")
666
 
667
  return jsonify({
668
  "status": "success",
669
+ "message": f"Fact sheet '{filename}' uploaded successfully",
670
+ "total_fact_sheets": len(get_available_diseases())
671
  })
672
+
673
+ except Exception as e:
674
+ logger.error(f"Error uploading fact sheet: {e}")
675
+ return jsonify({"error": f"Failed to upload: {str(e)}"}), 500
676
 
677
+ @app.route('/upload_medicine_info', methods=['POST'])
678
+ def upload_medicine_info():
679
+ """Upload medicine knowledge base file"""
680
+ try:
681
+ if 'file' not in request.files:
682
+ return jsonify({"error": "No file provided"}), 400
683
+
684
+ file = request.files['file']
685
+ if not file.filename or not allowed_file(file.filename, 'text'):
686
+ return jsonify({"error": "Invalid file. Must be a .txt file"}), 400
687
+
688
+ # Secure filename
689
+ filename = secure_filename(file.filename)
690
+ filepath = os.path.join(CONFIG['MEDICINE_KNOWLEDGE_DIR'], filename)
691
+
692
+ file.save(filepath)
693
+ logger.info(f"Medicine info file uploaded: {filename}")
694
+
695
  return jsonify({
696
+ "status": "success",
697
+ "message": f"Medicine info '{filename}' uploaded successfully",
698
+ "total_medicine_files": len(get_available_medicine_files())
699
+ })
700
+
701
+ except Exception as e:
702
+ logger.error(f"Error uploading medicine info: {e}")
703
+ return jsonify({"error": f"Failed to upload: {str(e)}"}), 500
704
 
705
  @app.route('/health', methods=['GET'])
706
  def health_check():
707
+ """System health check"""
708
+ try:
709
+ diseases = get_available_diseases()
710
+ medicine_files = get_available_medicine_files()
711
+
712
+ return jsonify({
713
+ "status": "βœ… Running",
714
+ "service": "Integrated Medical Information System",
715
+ "timestamp": datetime.now().isoformat(),
716
+ "gemini_configured": True,
717
+ "active_sessions": len(SESSIONS),
718
+ "disease_fact_sheets": len(diseases),
719
+ "medicine_knowledge_files": len(medicine_files),
720
+ "rate_limits_active": len(RATE_LIMITS),
721
+ "system_info": {
722
+ "max_file_size_mb": CONFIG['MAX_FILE_SIZE'] // (1024 * 1024),
723
+ "session_timeout_minutes": CONFIG['SESSION_TIMEOUT'] // 60,
724
+ "rate_limit_per_minute": CONFIG['RATE_LIMIT_PER_MINUTE']
725
+ }
726
+ })
727
+ except Exception as e:
728
+ logger.error(f"Health check error: {e}")
729
+ return jsonify({"status": "❌ Error", "error": str(e)}), 500
730
+
731
+ @app.route('/stats', methods=['GET'])
732
+ def get_stats():
733
+ """Get system statistics"""
734
+ diseases = get_available_diseases()
735
+ medicine_files = get_available_medicine_files()
736
 
737
  return jsonify({
738
+ "available_diseases": diseases,
739
+ "available_medicine_files": medicine_files,
740
+ "counts": {
741
+ "diseases": len(diseases),
742
+ "medicine_files": len(medicine_files),
743
+ "active_sessions": len(SESSIONS),
744
+ "rate_limited_ips": len(RATE_LIMITS)
745
+ },
746
+ "recent_sessions": len([
747
+ s for s in SESSIONS.values()
748
+ if time.time() - s.get('created', 0) < 300 # Last 5 minutes
749
+ ])
750
+ })
751
+
752
+ @app.route('/diseases', methods=['GET'])
753
+ def list_diseases():
754
+ """List available diseases"""
755
+ diseases = get_available_diseases()
756
+ return jsonify({
757
+ "available_diseases": diseases,
758
+ "count": len(diseases)
759
+ })
760
+
761
+ @app.route('/medicines', methods=['GET'])
762
+ def list_medicines():
763
+ """List available medicine files"""
764
+ files = get_available_medicine_files()
765
+ return jsonify({
766
+ "available_medicine_files": files,
767
+ "count": len(files)
768
  })
769
+
770
+ # Error handlers
771
+ @app.errorhandler(413)
772
+ def too_large(e):
773
+ return jsonify({"error": "File too large. Maximum size is 16MB"}), 413
774
+
775
+ @app.errorhandler(404)
776
+ def not_found(e):
777
+ return jsonify({"error": "Endpoint not found"}), 404
778
+
779
+ @app.errorhandler(500)
780
+ def internal_error(e):
781
+ return jsonify({"error": "Internal server error"}), 500
782
+
783
+ if __name__ == '__main__':
784
+ logger.info("=" * 60)
785
+ logger.info("πŸ₯ Starting Integrated Medical Information System")
786
+ logger.info(f"πŸ“ Disease fact sheets: {CONFIG['DISEASE_FACT_SHEETS_DIR']}/")
787
+ logger.info(f"πŸ’Š Medicine knowledge: {CONFIG['MEDICINE_KNOWLEDGE_DIR']}/")
788
+
789
+ # Check available knowledge base
790
+ diseases = get_available_diseases()
791
+ medicine_files = get_available_medicine_files()
792
+
793
+ if diseases:
794
+ logger.info(f"βœ… {len(diseases)} disease fact sheets loaded")
795
+ for disease in diseases[:3]:
796
+ logger.info(f" - {disease}")
797
+ if len(diseases) > 3:
798
+ logger.info(f" ... and {len(diseases) - 3} more")
799
+ else:
800
+ logger.warning(f"⚠️ No disease fact sheets found in '{CONFIG['DISEASE_FACT_SHEETS_DIR']}'")
801
+
802
+ if medicine_files:
803
+ logger.info(f"βœ… {len(medicine_files)} medicine files loaded")
804
+ for file in medicine_files[:3]:
805
+ logger.info(f" - {file}")
806
+ if len(medicine_files) > 3:
807
+ logger.info(f" ... and {len(medicine_files) - 3} more")
808
+ else:
809
+ logger.warning(f"⚠️ No medicine files found in '{CONFIG['MEDICINE_KNOWLEDGE_DIR']}'")
810
+
811
+ logger.info("=" * 60)
812
+ logger.info("πŸš€ Server starting on http://localhost:5000")
813
+ logger.info("πŸ“š Upload .txt files to knowledge directories for enhanced responses")
814
+ logger.info("=" * 60)
815
+
816
+ app.run(host='0.0.0.0', port=7860, debug=False)