X
File size: 1,827 Bytes
0b67164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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__)

@app.route("/", methods=["GET"])
def root():
    return {"msg": "Nutrition Model is Live!"}

@app.route("/predict", methods=["POST"])
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)