Coots commited on
Commit
a43c45a
Β·
verified Β·
1 Parent(s): 1cbee68

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -41
app.py CHANGED
@@ -1,53 +1,75 @@
1
- from flask import Flask, request, jsonify, send_from_directory
2
- from flask_cors import CORS
3
- import joblib, numpy as np, json, math, xgboost as xgb, logging
 
 
4
 
5
- app = Flask(__name__, static_folder=".", static_url_path="")
6
- CORS(app)
7
- logging.basicConfig(level=logging.INFO)
8
 
9
- # Load models
10
  try:
11
- rf = joblib.load("rf_model.pkl")
12
  xgb_model = xgb.Booster()
13
  xgb_model.load_model("xgb_model.json")
14
- app.logger.info("βœ… Models loaded.")
15
  except Exception as e:
16
- app.logger.error(f"❌ Model load error: {e}")
17
- raise
 
18
 
19
- # Load tile data
20
  with open("tile_catalog.json") as f:
21
  tile_catalog = json.load(f)
22
- with open("tile_sizes.json") as f:
23
- tile_sizes = json.load(f)
24
 
25
- @app.route('/')
26
- def homepage():
27
- return send_from_directory(".", "index.html")
 
 
 
 
 
28
 
29
- @app.route('/recommend', methods=['POST'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def recommend():
31
- data = request.get_json()
32
- # Basic validation
33
- for key in ('tile_type','length','width','area','price_range'):
34
- if key not in data:
35
- return jsonify({"error":f"Missing {key}"}),400
36
-
37
- length = float(data['length']); width = float(data['width'])
38
- coverage = length * width
39
- # build features for ML
40
- features = np.array([[0 if data['tile_type']=='floor' else 1, data['area'], coverage, *data['price_range'], data['price_range'][1]/coverage, coverage/data['price_range'][1]]])
41
- xgb_pred = xgb_model.predict(xgb.DMatrix(features))[0]
42
- rf_pred = rf.predict_proba(features)[0,1]
43
- score = (xgb_pred+rf_pred)/2
44
-
45
- # Filter products
46
- recs = []
47
- for p in tile_catalog:
48
- if p['type']==data['tile_type'] and p['size']==f"{length}x{width}" and data['price_range'][0] <= p['price'] <= data['price_range'][1]:
49
- recs.append({**p})
50
- return jsonify({"recommendation_score": round(score,3), "recommended_products": recs})
51
-
52
- if __name__=="__main__":
53
- app.run(host="0.0.0.0", port=7860, debug=False)
 
 
1
+ from flask import Flask, request, jsonify
2
+ import json
3
+ import math
4
+ import joblib
5
+ import xgboost as xgb
6
 
7
+ app = Flask(__name__)
 
 
8
 
9
+ # Load ML models
10
  try:
11
+ rf_model = joblib.load("rf_model.pkl")
12
  xgb_model = xgb.Booster()
13
  xgb_model.load_model("xgb_model.json")
14
+ print("βœ… Models loaded")
15
  except Exception as e:
16
+ print(f"❌ Model loading failed: {e}")
17
+ rf_model = None
18
+ xgb_model = None
19
 
20
+ # Load product catalog
21
  with open("tile_catalog.json") as f:
22
  tile_catalog = json.load(f)
 
 
23
 
24
+ @app.route("/api/calculate", methods=["POST"])
25
+ def calculate_tiles():
26
+ data = request.json
27
+ try:
28
+ length = float(data.get("length", 0))
29
+ width = float(data.get("width", 0))
30
+ tile_length = float(data.get("tile_length", 0))
31
+ tile_width = float(data.get("tile_width", 0))
32
 
33
+ if not all([length, width, tile_length, tile_width]):
34
+ return jsonify({"error": "All dimensions must be provided"}), 400
35
+
36
+ area = length * width
37
+ tile_area = tile_length * tile_width
38
+ tiles_needed = math.ceil((area / tile_area) * 1.1) # 10% buffer
39
+ boxes_needed = math.ceil(tiles_needed / 10) # Assume 10 tiles/box
40
+
41
+ return jsonify({
42
+ "area": area,
43
+ "tile_area": tile_area,
44
+ "tiles_needed": tiles_needed,
45
+ "boxes_needed": boxes_needed
46
+ })
47
+ except Exception as e:
48
+ return jsonify({"error": str(e)}), 500
49
+
50
+ @app.route("/recommend", methods=["POST"])
51
  def recommend():
52
+ data = request.json
53
+ tile_type = data.get("tile_type", "").lower()
54
+ area = float(data.get("area_range", 0))
55
+
56
+ if not tile_catalog:
57
+ return jsonify({"result": "❌ No catalog available"})
58
+
59
+ suggestions = []
60
+ for product in tile_catalog:
61
+ if product["type"].lower() == tile_type:
62
+ if product.get("area_range_min", 0) <= area <= product.get("area_range_max", float("inf")):
63
+ suggestions.append({
64
+ "name": product.get("name", "Tile Product"),
65
+ "price": product.get("price", "β‚Ή0"),
66
+ "link": product.get("link", "#")
67
+ })
68
+
69
+ if suggestions:
70
+ return jsonify({"result": "βœ… Recommended", "suggestions": suggestions[:4]})
71
+ else:
72
+ return jsonify({"result": "❌ No matching products", "suggestions": []})
73
+
74
+ if __name__ == "__main__":
75
+ app.run(debug=True)