Spaces:
Sleeping
Sleeping
Download app.py from nutripath/nutripath-ml: direct link, hf CLI and curl.
- Browser
- Download file 3.53 kB
-
https://huggingface.co/spaces/nutripath/nutripath-ml/resolve/main/app.py
- Command line
-
hf download hf://spaces/nutripath/nutripath-ml/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nutripath/nutripath-ml/resolve/main/app.py
3.53 kB
| from flask import Flask, request, jsonify | |
| import numpy as np | |
| import torch | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.preprocessing import StandardScaler | |
| from model.preprocessing import load_dataset, get_features, encode_labels, balance_dataset, generate_description | |
| from model.nlp import compute_tfidf | |
| from model.train import train_model | |
| app = Flask(__name__) | |
| print("Training model...") | |
| df = load_dataset("model/food_dataset.csv") | |
| df = balance_dataset(df) | |
| features, target = get_features(df) | |
| target_encoded, le = encode_labels(target) | |
| tfidf_matrix, vectorizer = compute_tfidf(df['food_description']) | |
| X_numeric = features.values | |
| X_text = tfidf_matrix.toarray() | |
| X = np.hstack((X_numeric, X_text)) | |
| X_train, X_test, y_train, y_test = train_test_split(X, target_encoded, test_size=0.2, random_state=42) | |
| scaler = StandardScaler() | |
| X_train_s = scaler.fit_transform(X_train) | |
| X_test_s = scaler.transform(X_test) | |
| model, _, _, _, _ = train_model(X_train_s, y_train, X_test_s, y_test, epochs=100) | |
| model.eval() | |
| print("Model ready!") | |
| def predict(): | |
| data = request.json | |
| protein = float(data.get("proteins", 0)) | |
| carbs = float(data.get("carbohydrates", 0)) | |
| fat = float(data.get("fats_total", 0)) | |
| fiber = float(data.get("fiber", 0)) | |
| sugar = float(data.get("sugar", 0)) | |
| calories = float(data.get("calories", protein*4 + carbs*4 + fat*9)) | |
| protein_s = float(data.get("proteins_serving", protein)) | |
| carbs_s = float(data.get("carbohydrates_serving", carbs)) | |
| fat_s = float(data.get("fat_serving", fat)) | |
| fiber_s = float(data.get("fiber_serving", fiber)) | |
| sugar_s = float(data.get("sugar_serving", sugar)) | |
| class FakeRow: | |
| def __getitem__(self, key): | |
| return { | |
| 'protein_g': protein, 'carbs_g': carbs, | |
| 'fat_g': fat, 'fiber_g': fiber, | |
| 'sugar_g': sugar, 'calories': calories, | |
| }[key] | |
| description = generate_description(FakeRow()) | |
| tfidf_input = vectorizer.transform([description]).toarray() | |
| input_numeric = np.array([[protein, carbs, fat, fiber, sugar, calories]]) | |
| input_combined = np.hstack((input_numeric, tfidf_input)) | |
| input_scaled = scaler.transform(input_combined) | |
| input_tensor = torch.tensor(input_scaled, dtype=torch.float32) | |
| with torch.no_grad(): | |
| output = model(input_tensor) | |
| pred_class = torch.argmax(output, dim=1).item() | |
| probs = torch.softmax(output, dim=1).numpy()[0] | |
| class_name = le.inverse_transform([pred_class])[0] | |
| feedback = [] | |
| if protein_s >= 20: feedback.append("✅ High in protein") | |
| if fiber_s >= 5: feedback.append("✅ Good source of fiber") | |
| if sugar_s > 20: feedback.append("⚠️ High sugar content") | |
| if fat_s > 30: feedback.append("⚠️ High fat content") | |
| if carbs_s < 20: feedback.append("✅ Low-carb") | |
| if not feedback: feedback.append("ℹ️ Balanced nutritional profile") | |
| return jsonify({ | |
| "calorie_class": class_name, | |
| "probabilities": {cls: round(float(probs[i]), 4) for i, cls in enumerate(le.classes_)}, | |
| "nutritional_feedback": feedback, | |
| "nlp_profile": description, | |
| }) | |
| def health(): | |
| return jsonify({"status": "ok"}) | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) |