Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1 +1,67 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, render_template
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.sparse import hstack
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
# Load saved objects
|
| 9 |
+
model = joblib.load('rf_model.joblib')
|
| 10 |
+
le_target = joblib.load('le_target.joblib')
|
| 11 |
+
encoders = joblib.load('encoders.joblib')
|
| 12 |
+
tfidf = joblib.load('tfidf_vectorizer.joblib')
|
| 13 |
+
|
| 14 |
+
@app.route('/', methods=['GET', 'POST'])
|
| 15 |
+
def index():
|
| 16 |
+
prediction = None
|
| 17 |
+
if request.method == 'POST':
|
| 18 |
+
# Get form data
|
| 19 |
+
ingredients = request.form['ingredients'].lower()
|
| 20 |
+
ingredients = ''.join(c for c in ingredients if c.isalnum() or c.isspace()) # basic cleanup
|
| 21 |
+
|
| 22 |
+
diet = request.form['diet']
|
| 23 |
+
course = request.form['course']
|
| 24 |
+
region = request.form['region']
|
| 25 |
+
prep_time = request.form['prep_time']
|
| 26 |
+
cook_time = request.form['cook_time']
|
| 27 |
+
|
| 28 |
+
# Transform ingredients using TF-IDF
|
| 29 |
+
X_ingredients = tfidf.transform([ingredients])
|
| 30 |
+
|
| 31 |
+
# Encode categorical features
|
| 32 |
+
try:
|
| 33 |
+
diet_enc = encoders['diet'].transform([diet])[0]
|
| 34 |
+
except:
|
| 35 |
+
diet_enc = 0 # fallback or handle unknown categories
|
| 36 |
+
try:
|
| 37 |
+
course_enc = encoders['course'].transform([course])[0]
|
| 38 |
+
except:
|
| 39 |
+
course_enc = 0
|
| 40 |
+
try:
|
| 41 |
+
region_enc = encoders['region'].transform([region])[0]
|
| 42 |
+
except:
|
| 43 |
+
region_enc = 0
|
| 44 |
+
|
| 45 |
+
# Prepare numeric features, convert to float/int
|
| 46 |
+
try:
|
| 47 |
+
prep_time = float(prep_time)
|
| 48 |
+
except:
|
| 49 |
+
prep_time = 0.0
|
| 50 |
+
try:
|
| 51 |
+
cook_time = float(cook_time)
|
| 52 |
+
except:
|
| 53 |
+
cook_time = 0.0
|
| 54 |
+
|
| 55 |
+
# Stack all features
|
| 56 |
+
from scipy.sparse import csr_matrix
|
| 57 |
+
X_other = csr_matrix([[diet_enc, course_enc, region_enc, prep_time, cook_time]])
|
| 58 |
+
X_input = hstack([X_ingredients, X_other])
|
| 59 |
+
|
| 60 |
+
# Predict
|
| 61 |
+
pred_encoded = model.predict(X_input)[0]
|
| 62 |
+
prediction = le_target.inverse_transform([pred_encoded])[0]
|
| 63 |
+
|
| 64 |
+
return render_template('index.html', prediction=prediction)
|
| 65 |
+
|
| 66 |
+
if __name__ == '__main__':
|
| 67 |
+
app.run(debug=True)
|