Spaces:
Runtime error
Runtime error
import gradio as gr | |
import requests | |
from transformers import AutoModelForImageClassification, AutoTokenizer | |
from PIL import Image | |
import torch | |
# Menginisialisasi model dan tokenizer dari Hugging Face | |
model_name = "ahmadalfian/fruits_vegetables_classifier" # Model yang kamu sebutkan | |
model = AutoModelForImageClassification.from_pretrained(model_name) | |
tokenizer = AutoTokenizer.from_pretrained(model_name) | |
# Fungsi untuk memprediksi kelas | |
def predict(image): | |
image = image.convert("RGB") | |
inputs = tokenizer(image, return_tensors="pt") | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
predictions = outputs.logits.argmax(dim=1) | |
return predictions.item() | |
# Fungsi untuk mengambil informasi nutrisi | |
def get_nutritional_info(food): | |
api_key = "3pm2NGZzYongVN1gRjnroVLUpsHC8rKWJFyx5moq" | |
url = "https://api.nal.usda.gov/fdc/v1/foods/search" | |
params = { | |
"query": food, # Nama makanan yang diprediksi | |
"pageSize": 5, # Ambil lima hasil | |
"api_key": api_key | |
} | |
response = requests.get(url, params=params) | |
data = response.json() | |
if "foods" in data and len(data["foods"]) > 0: | |
# Inisialisasi total untuk nutrisi yang diinginkan | |
nutrients_totals = { | |
"Energy": 0, | |
"Carbohydrate, by difference": 0, | |
"Fiber, total dietary": 0, | |
"Vitamin C, total ascorbic acid": 0 | |
} | |
item_count = len(data["foods"]) | |
# Iterasi melalui setiap makanan | |
for food in data["foods"]: | |
for nutrient in food['foodNutrients']: | |
nutrient_name = nutrient['nutrientName'] | |
nutrient_value = nutrient['value'] | |
# Cek apakah nutrisi termasuk yang diinginkan | |
if nutrient_name in nutrients_totals: | |
nutrients_totals[nutrient_name] += nutrient_value | |
# Menghitung rata-rata nilai nutrisi | |
average_nutrients = {name: total / item_count for name, total in nutrients_totals.items()} | |
return average_nutrients | |
else: | |
return None | |
# Fungsi utama Gradio | |
def classify_and_get_nutrition(image): | |
predicted_class_idx = predict(image) | |
class_labels = [ | |
'apple', 'banana', 'beetroot', 'bell pepper', 'cabbage', 'capsicum', | |
'carrot', 'cauliflower', 'chilli pepper', 'corn', 'cucumber', | |
'eggplant', 'garlic', 'ginger', 'grapes', 'jalepeno', 'kiwi', | |
'lemon', 'lettuce', 'mango', 'onion', 'orange', 'paprika', | |
'pear', 'peas', 'pineapple', 'pomegranate', 'potato', 'raddish', | |
'soy beans', 'spinach', 'sweetcorn', 'sweetpotato', 'tomato', | |
'turnip', 'watermelon' | |
] # Semua label kelas | |
predicted_label = class_labels[predicted_class_idx] | |
nutrisi = get_nutritional_info(predicted_label) | |
if nutrisi: | |
return { | |
"Predicted Class": predicted_label, | |
"Energy (kcal)": nutrisi["Energy"], | |
"Carbohydrates (g)": nutrisi["Carbohydrate, by difference"], | |
"Fiber (g)": nutrisi["Fiber, total dietary"], | |
"Vitamin C (mg)": nutrisi["Vitamin C, total ascorbic acid"] | |
} | |
else: | |
return { | |
"Predicted Class": predicted_label, | |
"Nutritional Information": "Not Found" | |
} | |
# Antarmuka Gradio | |
iface = gr.Interface( | |
fn=classify_and_get_nutrition, | |
inputs=gr.inputs.Image(type="pil"), | |
outputs=gr.outputs.JSON(), | |
title="Fruits and Vegetables Classifier", | |
description="Upload an image of a fruit or vegetable to classify and get its nutritional information." | |
) | |
iface.launch() |