food_classifier_api / app /food_model.py
jatin1233232's picture
Update app/food_model.py
4b576ac verified
import os
import tempfile
import requests
import json
from PIL import Image
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
# Optional: Cache download
os.environ["HF_HOME"] = "/tmp/cache"
# URLs
model_url = "https://huggingface.co/jatin1233232/Analiz_Food_Model/resolve/main/model.keras"
labels_url = "https://huggingface.co/jatin1233232/Analiz_Food_Model/resolve/main/labels.json"
# Download file from Hugging Face
def download_file(url, filename):
response = requests.get(url)
if response.status_code == 200:
file_path = os.path.join(tempfile.gettempdir(), filename)
with open(file_path, 'wb') as f:
f.write(response.content)
return file_path
else:
raise Exception(f"Failed to download: {url}")
# Download and load model
model_path = download_file(model_url, "model.keras")
model = load_model(model_path)
print("✅ Model loaded successfully.")
# Download and load labels
labels_path = download_file(labels_url, "labels.json")
with open(labels_path, 'r') as f:
labels_dict = json.load(f)
# Convert dict to list sorted by index
labels = [labels_dict[str(i)] for i in range(len(labels_dict))]
# Classification function
def classify_food(image: Image.Image, target_size=(224, 224)):
image = image.resize(target_size)
image_array = np.array(image) / 255.0
if image_array.shape[-1] == 4: # remove alpha if present
image_array = image_array[..., :3]
image_array = np.expand_dims(image_array, axis=0)
predictions = model.predict(image_array)
predicted_index = np.argmax(predictions, axis=1)[0]
predicted_label = labels[predicted_index]
confidence = float(np.max(predictions))
return predicted_label, confidence