Download app.py from carsten12/X: direct link, hf CLI and curl.
- Browser
- Download file 1.83 kB
-
https://huggingface.co/spaces/carsten12/X/resolve/main/app.py
- Command line
-
hf download hf://spaces/carsten12/X/app.py
-
curl -L -o app.py https://huggingface.co/spaces/carsten12/X/resolve/main/app.py
1.83 kB
| # huggingface_nutrition_api/app.py | |
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| from io import BytesIO | |
| from flask import Flask, request, jsonify | |
| import requests | |
| import os | |
| # 🔹 Load Model | |
| model = tf.keras.models.load_model("inceptionv3_model.keras", compile=False) | |
| # 🔹 Constants for Denormalization | |
| IMG_DIMN = 224 | |
| CALORIES_MAX = 9485.81543 | |
| MASS_MAX = 7975 | |
| FAT_MAX = 875.5410156 | |
| CARB_MAX = 844.5686035 | |
| PROTEIN_MAX = 147.491821 | |
| app = Flask(__name__) | |
| def root(): | |
| return {"msg": "Nutrition Model is Live!"} | |
| def predict(): | |
| try: | |
| data = request.get_json() | |
| if not data or "image_url" not in data: | |
| return jsonify({"error": "Missing image_url"}), 400 | |
| image_url = data["image_url"] | |
| response = requests.get(image_url) | |
| if response.status_code != 200: | |
| return jsonify({"error": "Failed to download image"}), 400 | |
| image = Image.open(BytesIO(response.content)).resize((IMG_DIMN, IMG_DIMN)).convert("RGB") | |
| image_array = np.array(image) / 255.0 | |
| image_array = np.expand_dims(image_array, axis=0).astype(np.float32) | |
| prediction = model(image_array, training=False).numpy().flatten() | |
| result = { | |
| "calories": round(float(prediction[0] * CALORIES_MAX), 2), | |
| "mass": round(float(prediction[1] * MASS_MAX), 2), | |
| "fat": round(float(prediction[2] * FAT_MAX), 2), | |
| "carbohydrates": round(float(prediction[3] * CARB_MAX), 2), | |
| "protein": round(float(prediction[4] * PROTEIN_MAX), 2), | |
| } | |
| return jsonify({"prediction": result}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |