-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
105 lines (85 loc) · 4.45 KB
/
app.py
File metadata and controls
105 lines (85 loc) · 4.45 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
from flask import Flask, request, jsonify
import base64
import requests
import os
from werkzeug.utils import secure_filename
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# Configuration
ROBOFLOW_API_URL = "https://classify.roboflow.com/brainmri_classification/1"
ROBOFLOW_API_KEY = "rf_dqDbILKhaEMFeRG4AC8EQYkAxl33"
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = 'temp_uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def file_to_base64(file_path):
with open(file_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def predict_with_roboflow(base64_image):
response = requests.post(
ROBOFLOW_API_URL,
params={"api_key": ROBOFLOW_API_KEY},
data={"image": base64_image},
headers={"Content-Type": "application/x-www-form-urlencoded"}
)
response.raise_for_status()
return response.json()
@app.route('/predict', methods=['POST'])
def handle_prediction():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if not allowed_file(file.filename):
return jsonify({"error": "Please upload an image file (e.g., JPG, PNG)"}), 400
try:
filename = secure_filename(file.filename)
temp_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(temp_path)
base64_image = file_to_base64(temp_path)
prediction = predict_with_roboflow(base64_image)
predicted_class = ""
confidence = 0
if prediction.get('top') and prediction.get('confidence') is not None:
predicted_class = prediction['top']
confidence = round(float(prediction['confidence']) * 100, 2)
elif prediction.get('predictions'):
best_pred = max(prediction['predictions'], key=lambda x: x['confidence'])
predicted_class = best_pred['class']
confidence = round(float(best_pred['confidence']) * 100, 2)
review_text = generate_review_text(predicted_class, confidence)
return jsonify({
"image": f"data:image/*;base64,{base64_image}",
"prediction": {
"class": predicted_class,
"confidence": confidence
},
"review": review_text
})
except Exception as e:
return jsonify({"error": str(e)}), 500
finally:
if 'temp_path' in locals() and os.path.exists(temp_path):
os.remove(temp_path)
def generate_review_text(predicted_class, confidence):
base_text = 'Please consult a medical professional for a definitive diagnosis and treatment plan. This AI prediction is for informational purposes only and is not a substitute for professional medical advice.'
if not predicted_class:
return 'No clear prediction found. The AI could not confidently classify the image. Please try another image or consult a doctor.'
predicted_class = predicted_class.lower()
if predicted_class == 'glioma':
return base_text + " Gliomas are a type of tumor that starts in the brain or spinal cord. It's crucial to seek immediate medical attention for further investigation and treatment."
elif predicted_class == 'meningioma':
return base_text + ' Meningiomas are tumors that arise from the membranes that surround the brain and spinal cord. While often benign, they can still cause symptoms and may require medical evaluation and monitoring.'
elif predicted_class == 'pituitary':
return base_text + ' Pituitary tumors occur in the pituitary gland at the base of the brain. They can affect hormone levels and may require specialized medical consultation and management.'
elif predicted_class == 'notumor':
return base_text + " The scan appears to indicate no tumor. However, always remember that an AI model cannot replace a doctor's diagnosis. If you have concerns about your health, please consult a healthcare provider."
else:
return base_text + " We couldn't provide specific advice for this prediction. Please consult a doctor for any health concerns."
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)