-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
447 lines (349 loc) · 15.2 KB
/
Copy pathapp.py
File metadata and controls
447 lines (349 loc) · 15.2 KB
1
2
3
4
5
6
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
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
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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
from flask import Flask, render_template, request,redirect , jsonify
import joblib
from sklearn.preprocessing import StandardScaler,LabelEncoder
from ultralytics import YOLO
import yaml
import os
import uuid
import numpy as np
import pydicom
from werkzeug.utils import secure_filename
import cv2
from PIL import Image
import io
import base64
from PIL import Image
from flask_cors import CORS
from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from sklearn.exceptions import InconsistentVersionWarning
import warnings
warnings.filterwarnings("ignore", category=InconsistentVersionWarning)
app = Flask(__name__)
model = joblib.load('saved_models/lgbm_model.joblib')
llm = OllamaLLM(model="gemma3")
prompt = ChatPromptTemplate.from_template("Answer the question: {question}")
output_parser = StrOutputParser()
chat_chain = prompt | llm | output_parser
'''
llava_model= OllamaLLM(model="llava")
prompt_template = """Answer the question about the image if provided.
Otherwise, answer the text question normally.
Question: {question}
{% if image %}Image: {image}{% endif %}
Answer:"""
prompt = ChatPromptTemplate.from_template(prompt_template)
chat_chain = prompt | llava_model | StrOutputParser()
CORS(app)
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
'''
@app.route('/')
def login():
return render_template('login.html')
#--------------------------------------------------------------------------
@app.route('/detail.html',methods=['GET','POST'])
def fun():
return render_template('detail.html')
#--------------------------------------------------------------------------
@app.route('/heartdisease',methods=['GET','POST'])
def home():
if request.method=='POST':
return render_template('heartdisease.html')
model = joblib.load('saved_models/lgbm_model.joblib') # Replace with your actual model file
le_Sex = joblib.load('saved_models/le_Sex.joblib')
le_ChestPainType = joblib.load('saved_models/le_ChestPainType.joblib')
le_RestingECG = joblib.load('saved_models/le_RestingECG.joblib')
le_ExerciseAngina = joblib.load('saved_models/le_ExerciseAngina.joblib')
le_ST_Slope = joblib.load('saved_models/le_ST_Slope.joblib')
scaler = joblib.load('saved_models/scaler.joblib')
#--------------------------------------------------------------------------
@app.route('/assess_risk', methods=['POST'])
def assess_risk():
try:
# Get form data
form_data = {
'sex': request.form.get('sex'),
'age': float(request.form.get('age')),
'chest_pain_type': request.form.get('chest_pain_type'),
'resting_bp': float(request.form.get('resting_bp')),
'cholesterol': float(request.form.get('cholesterol')),
'fasting_bs': float(request.form.get('fasting_bs')),
'resting_ecg': request.form.get('resting_ecg'),
'max_hr': float(request.form.get('max_hr')),
'exercise_angina': request.form.get('exercise_angina'),
'oldpeak': float(request.form.get('oldpeak')),
'st_slope': request.form.get('st_slope')
}
# Encode categorical variables
processed_data = [
le_Sex.transform([form_data['sex']])[0] if form_data['sex'] in le_Sex.classes_ else -1,
form_data['age'],
le_ChestPainType.transform([form_data['chest_pain_type']])[0] if form_data['chest_pain_type'] in le_ChestPainType.classes_ else -1,
form_data['resting_bp'],
form_data['cholesterol'],
form_data['fasting_bs'],
le_RestingECG.transform([form_data['resting_ecg']])[0] if form_data['resting_ecg'] in le_RestingECG.classes_ else -1,
form_data['max_hr'],
le_ExerciseAngina.transform([form_data['exercise_angina']])[0] if form_data['exercise_angina'] in le_ExerciseAngina.classes_ else -1,
form_data['oldpeak'],
le_ST_Slope.transform([form_data['st_slope']])[0] if form_data['st_slope'] in le_ST_Slope.classes_ else -1
]
# Standardize the input data
input_data_scaled = scaler.transform([processed_data])
# Make prediction (assuming your model outputs 1 for high risk, 0 for low risk)
prediction = model.predict(input_data_scaled)
y_pred_class = [1 if x > 0.5 else 0 for x in prediction]
risk_score = float(prediction[0])
risk_level = 'high_risk' if y_pred_class[0] == 1 else 'low_risk'
if risk_level == 'high_risk':
recommendations = [
"Schedule an appointment with your doctor immediately",
"Monitor your blood pressure daily",
"Adopt a low-sodium, heart-healthy diet",
"Begin a supervised exercise program",
"If you smoke, seek help to quit immediately",
"Limit alcohol consumption"
]
else:
recommendations = [
"Continue regular health check-ups",
"Maintain a balanced diet with plenty of fruits and vegetables",
"Engage in 150 minutes of moderate exercise weekly",
"Monitor your cholesterol levels annually",
"Practice stress-reduction techniques",
"Avoid tobacco products"
]
return jsonify({
'success': True,
'risk_level': risk_level,
'risk_score': risk_score,
'form_data': form_data,
'recommendations': recommendations
})
except ValueError as e:
return jsonify({
'success': False,
'error': str(e),
'message': 'Invalid input value. Please check your form data.'
}), 400
except Exception as e:
return jsonify({
'success': False,
'error': str(e),
'message': 'Error processing your request. Please try again.'
}), 500
#--------------------------------------------------------------------------
@app.route('/classificationpred', methods=['GET', 'POST'])
def classpred():
if request.method == 'POST':
# Handle any POST data if needed
pass
return render_template('classificationpred.html')
model2 = YOLO('saved_models/my_model.pt')
# Configuration
UPLOAD_FOLDER = 'temp_uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def encode_image_to_base64(image):
_, buffer = cv2.imencode('.jpg', image)
return base64.b64encode(buffer).decode('utf-8')
#--------------------------------------------------------------------------
@app.route('/api/analyze', methods=['POST'])
def analyze():
try:
print("\n=== NEW REQUEST ===")
print("Request files:", request.files)
if 'image' not in request.files:
print("No 'image' key in request")
return jsonify({"error": "No image uploaded"}), 400
image_file = request.files['image']
print("Received file:", image_file.filename)
# Validate filename
if image_file.filename == '':
print("Empty filename")
return jsonify({"error": "No selected file"}), 400
# Validate file extension
if not allowed_file(image_file.filename):
print("Invalid file extension")
return jsonify({"error": "Invalid file type"}), 400
# Create upload directory if missing
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
print(f"Upload folder: {os.path.abspath(UPLOAD_FOLDER)}")
# Save file
temp_path = os.path.join(UPLOAD_FOLDER, secure_filename(image_file.filename))
print("Saving to:", temp_path)
image_file.save(temp_path)
print("File saved successfully")
# Verify file exists
if not os.path.exists(temp_path):
print("ERROR: File not saved correctly")
return jsonify({"error": "File processing failed"}), 500
# Model prediction
print("Running prediction...")
results = model2.predict(temp_path, conf=0.25, device='cpu')
print("Prediction completed:", results)
# Read the original image
original_image = cv2.imread(temp_path)
# Plot the results on the image
annotated_image = results[0].plot() # This adds bounding boxes and labels
# Convert annotated image to base64
detected_image_base64 = encode_image_to_base64(annotated_image)
if not results or len(results[0].boxes) == 0:
print("No detections found")
return jsonify({
"condition": "healthy",
"confidence": 0,
"detected_image": detected_image_base64 # Still return the original image
})
# Process results
best_result = results[0].boxes[0]
class_name = model2.names[int(best_result.cls)]
confidence = float(best_result.conf) * 100
print(f"Detection: {class_name} ({confidence:.2f}%)")
return jsonify({
"condition": class_name,
"confidence": round(confidence, 2),
"detected_image": detected_image_base64
})
except Exception as e:
print("\n!!! ERROR !!!")
print(str(e))
import traceback
traceback.print_exc()
return jsonify({"error": "Analysis failed", "details": str(e)}), 500
finally:
# Clean up
if 'temp_path' in locals() and os.path.exists(temp_path):
os.remove(temp_path)
print("Temp file cleaned up")
#--------------------------------------------------------------------------
@app.route('/cancerprediction', methods=['GET', 'POST'])
def cancer_prediction_page():
if request.method == 'POST':
# Handle form submission if needed
pass
return render_template('oncology_analysis.html')
model3 = YOLO('saved_models/updated_my_model.pt')
# Configuration
UPLOAD_FOLDER = 'temp_uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'dcm'}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
# Ensure upload directory exists
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def allowed_file2(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def encode_image2_to_base64(image):
_, buffer = cv2.imencode('.jpg', image)
return base64.b64encode(buffer).decode('utf-8')
#--------------------------------------------------------------------------
@app.route('/api/analyze-oncology', methods=['POST'])
def analyze_oncology():
try:
print("\n=== NEW ONCOLOGY ANALYSIS REQUEST ===")
print("Request files:", request.files)
if 'image' not in request.files:
print("No 'image' key in request")
return jsonify({"error": "No image uploaded"}), 400
image_file = request.files['image']
print("Received file:", image_file.filename)
# Validate filename
if image_file.filename == '':
print("Empty filename")
return jsonify({"error": "No selected file"}), 400
# Validate file extension
if not allowed_file(image_file.filename):
print("Invalid file extension")
return jsonify({"error": "Invalid file type. Supported types: PNG, JPG, JPEG, DICOM"}), 400
# Create upload directory if missing
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
print(f"Upload folder: {os.path.abspath(UPLOAD_FOLDER)}")
# Save file
temp_path = os.path.join(UPLOAD_FOLDER, secure_filename(image_file.filename))
print("Saving to:", temp_path)
image_file.save(temp_path)
print("File saved successfully")
# Verify file exists
if not os.path.exists(temp_path):
print("ERROR: File not saved correctly")
return jsonify({"error": "File processing failed"}), 500
# Model prediction
print("Running oncology prediction...")
results = model3.predict(temp_path, conf=0.25, device='cpu')
print("Prediction completed:", results)
# Read the original image
original_image = cv2.imread(temp_path)
# Plot the results on the image
annotated_image = results[0].plot() # This adds bounding boxes and labels
# Convert annotated image to base64
detected_image_base64 = encode_image_to_base64(annotated_image)
if not results or len(results[0].boxes) == 0:
print("No cancer detections found")
return jsonify({
"condition": "No malignant findings detected",
"confidence": 0,
"detected_image": detected_image_base64
})
# Process results
best_result = results[0].boxes[0]
class_name = model3.names[int(best_result.cls)]
confidence = float(best_result.conf) * 100
print(f"Detection: {class_name} ({confidence:.2f}%)")
return jsonify({
"condition": class_name,
"confidence": round(confidence, 2),
"detected_image": detected_image_base64
})
except Exception as e:
print("\n!!! ONCOLOGY ANALYSIS ERROR !!!")
print(str(e))
import traceback
traceback.print_exc()
return jsonify({"error": "Oncology analysis failed", "details": str(e)}), 500
finally:
# Clean up
if 'temp_path' in locals() and os.path.exists(temp_path):
os.remove(temp_path)
print("Temp file cleaned up")
#--------------------------------------------------------------------------
@app.route('/api/chatbot', methods=['POST'])
def chatbot():
try:
# Check if the request contains JSON or form data
if request.content_type == 'application/json':
data = request.get_json()
user_message = data.get("message", "").strip()
user_image = None
else:
user_message = request.form.get("message", "").strip()
user_image = request.files.get("image")
if not user_message and not user_image:
return jsonify({"response": "No message or image received."}), 400
# Process the text message
if user_message:
result = chat_chain.invoke({"question": user_message})
response_message = result
else:
response_message = "Image received, processing..."
# Here you can add image processing logic if needed
if user_image:
# Process the image (e.g., save it, analyze it, etc.)
pass # Add your image processing logic here
return jsonify({"response": response_message})
except Exception as e:
print("Error in chatbot:", e)
return jsonify({"response": "Internal error occurred."}), 500
if __name__ == '__main__':
print("plk--->STARTING THE SERVER<---plk")
app.run(host='0.0.0.0', port=5000,debug=True)