Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,194 +1,116 @@
|
|
1 |
-
from flask import Flask, request, jsonify
|
2 |
-
import numpy as np
|
3 |
-
import tensorflow as tf
|
4 |
-
from PIL import Image
|
5 |
-
import io
|
6 |
-
import base64
|
7 |
-
import re
|
8 |
-
import joblib
|
9 |
-
import os
|
10 |
-
|
11 |
-
app = Flask(__name__)
|
12 |
-
|
13 |
-
# Load all models - use absolute paths for Hugging Face
|
14 |
-
MODEL_DIR = os.path.join(os.getcwd(), "models")
|
15 |
-
models = {
|
16 |
-
"cnn": tf.keras.models.load_model(os.path.join(MODEL_DIR, "mnist_cnn_model.h5")),
|
17 |
-
"svm": joblib.load(os.path.join(MODEL_DIR, "mnist_svm.pkl")),
|
18 |
-
"logistic": joblib.load(os.path.join(MODEL_DIR, "mnist_logistic_regression.pkl")),
|
19 |
-
"random_forest": joblib.load(os.path.join(MODEL_DIR, "mnist_random_forest.pkl"))
|
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 |
-
# [Keep your existing /get_classification_report and /predict routes exactly as they are]
|
120 |
-
@app.route('/get_classification_report', methods=['POST'])
|
121 |
-
def get_classification_report():
|
122 |
-
model_type = request.json['model_type']
|
123 |
-
if model_type in classification_reports:
|
124 |
-
return jsonify({'report': classification_reports[model_type]})
|
125 |
-
return jsonify({'error': 'Model not found'})
|
126 |
-
|
127 |
-
@app.route('/predict', methods=['POST'])
|
128 |
-
def predict():
|
129 |
-
try:
|
130 |
-
data = request.json['image']
|
131 |
-
model_type = request.json['model_type']
|
132 |
-
|
133 |
-
# Process image directly without saving
|
134 |
-
img_data = re.sub('^data:image/png;base64,', '', data)
|
135 |
-
img = Image.open(io.BytesIO(base64.b64decode(img_data)))
|
136 |
-
processed_image = preprocess_image(img, model_type)
|
137 |
-
|
138 |
-
if model_type not in models:
|
139 |
-
return jsonify({'error': 'Model not found'})
|
140 |
-
|
141 |
-
model = models[model_type]
|
142 |
-
|
143 |
-
if model_type == "cnn":
|
144 |
-
prediction = model.predict(processed_image)
|
145 |
-
predicted_digit = np.argmax(prediction)
|
146 |
-
confidence_scores = prediction[0].tolist()
|
147 |
-
score_type = "probability"
|
148 |
-
|
149 |
-
elif model_type == "svm":
|
150 |
-
predicted_digit = model.predict(processed_image)[0]
|
151 |
-
if hasattr(model, "decision_function"):
|
152 |
-
try:
|
153 |
-
decision_scores = model.decision_function(processed_image)
|
154 |
-
if len(decision_scores.shape) == 2:
|
155 |
-
confidence_scores = decision_scores[0].tolist()
|
156 |
-
else:
|
157 |
-
confidence_scores = [0] * 10
|
158 |
-
for i in range(10):
|
159 |
-
confidence_scores[i] = sum(1 for score in decision_scores[0] if score > 0)
|
160 |
-
min_score = min(confidence_scores)
|
161 |
-
if min_score < 0:
|
162 |
-
confidence_scores = [score - min_score for score in confidence_scores]
|
163 |
-
score_type = "decision_distance"
|
164 |
-
except Exception:
|
165 |
-
confidence_scores = create_simulated_scores(int(predicted_digit))
|
166 |
-
score_type = "simulated"
|
167 |
-
else:
|
168 |
-
confidence_scores = create_simulated_scores(int(predicted_digit))
|
169 |
-
score_type = "simulated"
|
170 |
-
|
171 |
-
else:
|
172 |
-
predicted_digit = model.predict(processed_image)[0]
|
173 |
-
if hasattr(model, "predict_proba"):
|
174 |
-
try:
|
175 |
-
confidence_scores = model.predict_proba(processed_image)[0].tolist()
|
176 |
-
score_type = "probability"
|
177 |
-
except Exception:
|
178 |
-
confidence_scores = create_simulated_scores(int(predicted_digit))
|
179 |
-
score_type = "simulated"
|
180 |
-
else:
|
181 |
-
confidence_scores = create_simulated_scores(int(predicted_digit))
|
182 |
-
score_type = "simulated"
|
183 |
-
|
184 |
-
return jsonify({
|
185 |
-
'digit': int(predicted_digit),
|
186 |
-
'confidence_scores': confidence_scores,
|
187 |
-
'score_type': score_type
|
188 |
-
})
|
189 |
-
|
190 |
-
except Exception as e:
|
191 |
-
return jsonify({'error': str(e)})
|
192 |
-
|
193 |
-
if __name__ == '__main__':
|
194 |
app.run(host='0.0.0.0', port=7860)
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import numpy as np
|
3 |
+
import tensorflow as tf
|
4 |
+
from PIL import Image
|
5 |
+
import io
|
6 |
+
import base64
|
7 |
+
import re
|
8 |
+
import joblib
|
9 |
+
import os
|
10 |
+
|
11 |
+
app = Flask(__name__)
|
12 |
+
|
13 |
+
# Load all models - use absolute paths for Hugging Face
|
14 |
+
MODEL_DIR = os.path.join(os.getcwd(), "models")
|
15 |
+
models = {
|
16 |
+
"cnn": tf.keras.models.load_model(os.path.join(MODEL_DIR, "mnist_cnn_model.h5")),
|
17 |
+
"svm": joblib.load(os.path.join(MODEL_DIR, "mnist_svm.pkl")),
|
18 |
+
"logistic": joblib.load(os.path.join(MODEL_DIR, "mnist_logistic_regression.pkl")),
|
19 |
+
"random_forest": joblib.load(os.path.join(MODEL_DIR, "mnist_random_forest.pkl"))
|
20 |
+
}
|
21 |
+
|
22 |
+
# Preprocess image before prediction
|
23 |
+
def preprocess_image(image, model_type):
|
24 |
+
image = image.resize((28, 28)).convert('L')
|
25 |
+
img_array = np.array(image) / 255.0
|
26 |
+
|
27 |
+
if model_type == "cnn":
|
28 |
+
return np.expand_dims(np.expand_dims(img_array, axis=0), axis=-1)
|
29 |
+
else:
|
30 |
+
return img_array.flatten().reshape(1, -1)
|
31 |
+
|
32 |
+
def create_simulated_scores(predicted_digit):
|
33 |
+
scores = [0.01] * 10
|
34 |
+
remaining = 1.0 - sum(scores)
|
35 |
+
scores[predicted_digit] += remaining
|
36 |
+
return scores
|
37 |
+
|
38 |
+
@app.route('/')
|
39 |
+
def home():
|
40 |
+
return jsonify({
|
41 |
+
"message": "MNIST Classifier API",
|
42 |
+
"available_models": list(models.keys()),
|
43 |
+
"endpoints": {
|
44 |
+
"/predict": "POST - Send image and model_type",
|
45 |
+
"/get_classification_report": "POST - Get model metrics"
|
46 |
+
}
|
47 |
+
})
|
48 |
+
|
49 |
+
@app.route('/predict', methods=['POST'])
|
50 |
+
def predict():
|
51 |
+
try:
|
52 |
+
data = request.json['image']
|
53 |
+
model_type = request.json['model_type']
|
54 |
+
|
55 |
+
# Process image directly without saving
|
56 |
+
img_data = re.sub('^data:image/png;base64,', '', data)
|
57 |
+
img = Image.open(io.BytesIO(base64.b64decode(img_data)))
|
58 |
+
processed_image = preprocess_image(img, model_type)
|
59 |
+
|
60 |
+
if model_type not in models:
|
61 |
+
return jsonify({'error': 'Model not found'})
|
62 |
+
|
63 |
+
model = models[model_type]
|
64 |
+
|
65 |
+
if model_type == "cnn":
|
66 |
+
prediction = model.predict(processed_image)
|
67 |
+
predicted_digit = np.argmax(prediction)
|
68 |
+
confidence_scores = prediction[0].tolist()
|
69 |
+
score_type = "probability"
|
70 |
+
|
71 |
+
elif model_type == "svm":
|
72 |
+
predicted_digit = model.predict(processed_image)[0]
|
73 |
+
if hasattr(model, "decision_function"):
|
74 |
+
try:
|
75 |
+
decision_scores = model.decision_function(processed_image)
|
76 |
+
if len(decision_scores.shape) == 2:
|
77 |
+
confidence_scores = decision_scores[0].tolist()
|
78 |
+
else:
|
79 |
+
confidence_scores = [0] * 10
|
80 |
+
for i in range(10):
|
81 |
+
confidence_scores[i] = sum(1 for score in decision_scores[0] if score > 0)
|
82 |
+
min_score = min(confidence_scores)
|
83 |
+
if min_score < 0:
|
84 |
+
confidence_scores = [score - min_score for score in confidence_scores]
|
85 |
+
score_type = "decision_distance"
|
86 |
+
except Exception:
|
87 |
+
confidence_scores = create_simulated_scores(int(predicted_digit))
|
88 |
+
score_type = "simulated"
|
89 |
+
else:
|
90 |
+
confidence_scores = create_simulated_scores(int(predicted_digit))
|
91 |
+
score_type = "simulated"
|
92 |
+
|
93 |
+
else:
|
94 |
+
predicted_digit = model.predict(processed_image)[0]
|
95 |
+
if hasattr(model, "predict_proba"):
|
96 |
+
try:
|
97 |
+
confidence_scores = model.predict_proba(processed_image)[0].tolist()
|
98 |
+
score_type = "probability"
|
99 |
+
except Exception:
|
100 |
+
confidence_scores = create_simulated_scores(int(predicted_digit))
|
101 |
+
score_type = "simulated"
|
102 |
+
else:
|
103 |
+
confidence_scores = create_simulated_scores(int(predicted_digit))
|
104 |
+
score_type = "simulated"
|
105 |
+
|
106 |
+
return jsonify({
|
107 |
+
'digit': int(predicted_digit),
|
108 |
+
'confidence_scores': confidence_scores,
|
109 |
+
'score_type': score_type
|
110 |
+
})
|
111 |
+
|
112 |
+
except Exception as e:
|
113 |
+
return jsonify({'error': str(e)})
|
114 |
+
|
115 |
+
if __name__ == '__main__':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
app.run(host='0.0.0.0', port=7860)
|