-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
178 lines (138 loc) · 4.75 KB
/
app.py
File metadata and controls
178 lines (138 loc) · 4.75 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
"""CIFAR-10 Advanced CNN Image Classifier
Flask Web Application for Image Classification
"""
import os
from pathlib import Path
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, redirect, url_for, flash
# TensorFlow imports
try:
from tensorflow.keras.models import load_model
TENSORFLOW_AVAILABLE = True
except ImportError:
TENSORFLOW_AVAILABLE = False
try:
from essentials import pred_and_plot_image
ESSENTIALS_AVAILABLE = True
except ImportError:
ESSENTIALS_AVAILABLE = False
# Initialize Flask app
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
# Allowed file extensions
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}
def allowed_file(filename):
"""Check if file extension is allowed"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def get_model_path():
"""Get the path to the trained model"""
model_path = Path('model') / 'cifar10_advanced_cnn.h5'
if not model_path.exists():
return None
return model_path
# Global variables
uploaded_files = []
# Define class names (from CIFAR-10)
CLASS_NAMES = [
'0: airplane', '1: automobile', '2: bird', '3: cat', '4: deer',
'5: dog', '6: frog', '7: horse', '8: ship', '9: truck'
]
def get_model():
"""Load the model"""
if not TENSORFLOW_AVAILABLE:
return None
try:
model_path = get_model_path()
if model_path is None:
return None
return load_model(str(model_path), compile=False)
except Exception as e:
print(f"Error loading model: {str(e)}")
return None
def cleanup_files():
"""Clean up uploaded files"""
global uploaded_files
for file_path in uploaded_files:
try:
if os.path.exists(file_path):
os.remove(file_path)
except:
pass
uploaded_files = []
@app.route('/')
def home():
cleanup_files()
return render_template('main.html')
@app.route('/predict', methods=['POST'])
def predict():
global uploaded_files
if not ESSENTIALS_AVAILABLE or not TENSORFLOW_AVAILABLE:
flash('System not fully initialized', 'error')
return redirect(url_for('home'))
try:
images = request.files.getlist("image")
if not images or all(img.filename == '' for img in images):
flash('No images selected.', 'error')
return redirect(url_for('home'))
model = get_model()
if model is None:
flash('Error loading model.', 'error')
return redirect(url_for('home'))
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
image_paths = []
for image in images:
if not image or image.filename == '':
continue
if not allowed_file(image.filename):
continue
try:
filename = secure_filename(image.filename)
import time
timestamp = int(time.time() * 1000)
filename = f"{timestamp}_{filename}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
image.save(file_path)
image_paths.append(file_path)
uploaded_files.append(file_path)
except:
continue
if not image_paths:
flash('No valid images uploaded.', 'error')
return redirect(url_for('home'))
try:
probabilities, labels, throughput, total_time = pred_and_plot_image(
model=model,
class_names=CLASS_NAMES,
image_paths=image_paths
)
except:
flash('Error processing images.', 'error')
cleanup_files()
return redirect(url_for('home'))
if not probabilities:
flash('No predictions generated.', 'error')
cleanup_files()
return redirect(url_for('home'))
data = {
"image_name": image_paths,
"Probs": probabilities,
"Labels": labels
}
latency = (1000 / throughput) if throughput > 0 else 0
return render_template(
'testingoutput.html',
data=data,
length=round(total_time, 4),
tput=round(throughput, 2),
latency=round(latency, 4)
)
except:
flash('Error occurred.', 'error')
cleanup_files()
return redirect(url_for('home'))
@app.route('/goback')
def go_back():
cleanup_files()
return redirect(url_for('home'))
if __name__ == '__main__':
app.run(debug=True, port=5000)