thejagstudio commited on
Commit
2710430
·
verified ·
1 Parent(s): e205a76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -97
app.py CHANGED
@@ -1,97 +1,100 @@
1
- from flask import Flask, request, render_template, jsonify
2
- import cv2
3
- import numpy as np
4
- import tensorflow as tf
5
- import pandas as pd
6
- import base64
7
- import json
8
-
9
- # Initialize Flask app
10
- app = Flask(__name__)
11
-
12
- # Load model and data at startup
13
- model = tf.keras.models.load_model("sneaker_category_predictor_v2.h5")
14
-
15
- # Define expected columns for one-hot encoding
16
- with open("metadata.json", "r") as f:
17
- METADATA_COLUMNS = json.load(f)
18
-
19
-
20
- def encode_metadata(data):
21
- # Create DataFrame with single row
22
- df = pd.DataFrame({k: [v.lower()] for k, v in data.items()})
23
-
24
- # Initialize empty DataFrame with all possible columns
25
- encoded = pd.DataFrame()
26
-
27
- # Encode each feature maintaining consistent columns
28
- for feature, possible_values in METADATA_COLUMNS.items():
29
- feature_encoded = pd.get_dummies(df[feature], prefix=feature)
30
- # Add missing columns with 0s
31
- for value in possible_values:
32
- col_name = f"{feature}_{value}"
33
- if col_name not in feature_encoded.columns:
34
- feature_encoded[col_name] = 0
35
- encoded = pd.concat([encoded, feature_encoded], axis=1)
36
-
37
- # Ensure consistent column order
38
- all_columns = [
39
- f"{feat}_{val}" for feat, vals in METADATA_COLUMNS.items() for val in vals
40
- ]
41
- encoded = encoded.reindex(columns=all_columns, fill_value=0)
42
-
43
- return encoded.values.astype(np.float32)
44
-
45
-
46
- @app.route("/")
47
- def index():
48
- global METADATA_COLUMNS
49
- return render_template("index.html", metadata=METADATA_COLUMNS)
50
-
51
-
52
- @app.route("/predict", methods=["POST"])
53
- def predict():
54
- try:
55
- data = request.json
56
-
57
- # Process image
58
- img_data = base64.b64decode(data["image"])
59
- img_array = np.frombuffer(img_data, np.uint8)
60
- img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
61
- img = cv2.resize(img, (224, 224))
62
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
63
- img = img / 255.0
64
- img = np.expand_dims(img, axis=0)
65
-
66
- # Encode metadata with consistent columns
67
- metadata = encode_metadata(
68
- {
69
- "brand": data["brand"],
70
- "color": data["color"],
71
- "gender": data["gender"],
72
- "midsole": data["midsole"],
73
- "upperMaterial": data["upperMaterial"],
74
- }
75
- )
76
- # Make prediction
77
- predictions = model.predict([img, metadata])
78
- categories = [
79
- "Lifestyle",
80
- "Running",
81
- "Other",
82
- "Cleat",
83
- "Sandal",
84
- "Basketball",
85
- "Boot",
86
- "Skateboarding",
87
- ]
88
- confidenceList = predictions[0].tolist()
89
-
90
- return jsonify({"categories": categories, "confidence": confidenceList})
91
-
92
- except Exception as e:
93
- return jsonify({"error": str(e)}), 400
94
-
95
-
96
- if __name__ == "__main__":
97
- app.run(host="0.0.0.0", port=7860)
 
 
 
 
1
+ from flask import Flask, request, render_template, jsonify
2
+ from huggingface_hub import hf_hub_download
3
+ import cv2
4
+ import numpy as np
5
+ import tensorflow as tf
6
+ import pandas as pd
7
+ import base64
8
+ import json
9
+
10
+ # Initialize Flask app
11
+ app = Flask(__name__)
12
+
13
+ # Load model and data at startup
14
+ # model = tf.keras.models.load_model("sneaker_category_predictor_v2.h5")
15
+ model_path = hf_hub_download(repo_id="thejagstudio/SneakerAI", filename="sneaker_category_predictor_v2.h5")
16
+ model = tf.keras.models.load_model(model_path)
17
+
18
+ # Define expected columns for one-hot encoding
19
+ with open("metadata.json", "r") as f:
20
+ METADATA_COLUMNS = json.load(f)
21
+
22
+
23
+ def encode_metadata(data):
24
+ # Create DataFrame with single row
25
+ df = pd.DataFrame({k: [v.lower()] for k, v in data.items()})
26
+
27
+ # Initialize empty DataFrame with all possible columns
28
+ encoded = pd.DataFrame()
29
+
30
+ # Encode each feature maintaining consistent columns
31
+ for feature, possible_values in METADATA_COLUMNS.items():
32
+ feature_encoded = pd.get_dummies(df[feature], prefix=feature)
33
+ # Add missing columns with 0s
34
+ for value in possible_values:
35
+ col_name = f"{feature}_{value}"
36
+ if col_name not in feature_encoded.columns:
37
+ feature_encoded[col_name] = 0
38
+ encoded = pd.concat([encoded, feature_encoded], axis=1)
39
+
40
+ # Ensure consistent column order
41
+ all_columns = [
42
+ f"{feat}_{val}" for feat, vals in METADATA_COLUMNS.items() for val in vals
43
+ ]
44
+ encoded = encoded.reindex(columns=all_columns, fill_value=0)
45
+
46
+ return encoded.values.astype(np.float32)
47
+
48
+
49
+ @app.route("/")
50
+ def index():
51
+ global METADATA_COLUMNS
52
+ return render_template("index.html", metadata=METADATA_COLUMNS)
53
+
54
+
55
+ @app.route("/predict", methods=["POST"])
56
+ def predict():
57
+ try:
58
+ data = request.json
59
+
60
+ # Process image
61
+ img_data = base64.b64decode(data["image"])
62
+ img_array = np.frombuffer(img_data, np.uint8)
63
+ img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
64
+ img = cv2.resize(img, (224, 224))
65
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
66
+ img = img / 255.0
67
+ img = np.expand_dims(img, axis=0)
68
+
69
+ # Encode metadata with consistent columns
70
+ metadata = encode_metadata(
71
+ {
72
+ "brand": data["brand"],
73
+ "color": data["color"],
74
+ "gender": data["gender"],
75
+ "midsole": data["midsole"],
76
+ "upperMaterial": data["upperMaterial"],
77
+ }
78
+ )
79
+ # Make prediction
80
+ predictions = model.predict([img, metadata])
81
+ categories = [
82
+ "Lifestyle",
83
+ "Running",
84
+ "Other",
85
+ "Cleat",
86
+ "Sandal",
87
+ "Basketball",
88
+ "Boot",
89
+ "Skateboarding",
90
+ ]
91
+ confidenceList = predictions[0].tolist()
92
+
93
+ return jsonify({"categories": categories, "confidence": confidenceList})
94
+
95
+ except Exception as e:
96
+ return jsonify({"error": str(e)}), 400
97
+
98
+
99
+ if __name__ == "__main__":
100
+ app.run(host="0.0.0.0", port=7860)