Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +118 -0
- requirements.txt +6 -0
app.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from transformers import ViTFeatureExtractor, ViTForImageClassification
|
4 |
+
from PIL import Image
|
5 |
+
import requests
|
6 |
+
import io
|
7 |
+
import warnings
|
8 |
+
import gradio as gr
|
9 |
+
import threading
|
10 |
+
import uvicorn
|
11 |
+
|
12 |
+
warnings.filterwarnings('ignore')
|
13 |
+
|
14 |
+
# Load the pre-trained Vision Transformer model and feature extractor
|
15 |
+
model_name = "google/vit-base-patch16-224"
|
16 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
|
17 |
+
model = ViTForImageClassification.from_pretrained(model_name)
|
18 |
+
|
19 |
+
# API key for the nutrition information
|
20 |
+
api_key = 'TTnVMFxStvcP3sUXow/sGw==CnAQfUtuozhAAO5M'
|
21 |
+
|
22 |
+
app = FastAPI()
|
23 |
+
|
24 |
+
def identify_image(image: Image.Image):
|
25 |
+
"""Identify the food item in the image."""
|
26 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
27 |
+
outputs = model(**inputs)
|
28 |
+
logits = outputs.logits
|
29 |
+
predicted_class_idx = logits.argmax(-1).item()
|
30 |
+
predicted_label = model.config.id2label[predicted_class_idx]
|
31 |
+
food_name = predicted_label.split(',')[0]
|
32 |
+
return food_name
|
33 |
+
|
34 |
+
def get_calories(food_name: str):
|
35 |
+
"""Get the calorie information of the identified food item."""
|
36 |
+
api_url = f'https://api.api-ninjas.com/v1/nutrition?query={food_name}'
|
37 |
+
response = requests.get(api_url, headers={'X-Api-Key': api_key})
|
38 |
+
if response.status_code == requests.codes.ok:
|
39 |
+
return response.json()
|
40 |
+
else:
|
41 |
+
raise HTTPException(status_code=response.status_code, detail=response.text)
|
42 |
+
|
43 |
+
@app.post("/identify_and_get_nutrition")
|
44 |
+
async def identify_and_get_nutrition(file: UploadFile = File(...)):
|
45 |
+
image_data = await file.read()
|
46 |
+
image = Image.open(io.BytesIO(image_data))
|
47 |
+
food_name = identify_image(image)
|
48 |
+
nutrition_info = get_calories(food_name)
|
49 |
+
if len(nutrition_info) == 0:
|
50 |
+
return JSONResponse(content={"message": "No nutritional information found."}, status_code=404)
|
51 |
+
return nutrition_info
|
52 |
+
|
53 |
+
# Gradio Interface
|
54 |
+
def gradio_interface(image_file):
|
55 |
+
image = Image.open(image_file)
|
56 |
+
food_name = identify_image(image)
|
57 |
+
nutrition_info = get_calories(food_name)
|
58 |
+
if len(nutrition_info) == 0:
|
59 |
+
return "No nutritional information found."
|
60 |
+
|
61 |
+
nutrition_data = nutrition_info[0]
|
62 |
+
table = f"""
|
63 |
+
<table border="1" style="width: 100%; border-collapse: collapse;">
|
64 |
+
<tr><th colspan="4" style="text-align: center;"><b>Nutrition Facts</b></th></tr>
|
65 |
+
<tr><td colspan="4" style="text-align: center;"><b>Food Name: {nutrition_data['name']}</b></td></tr>
|
66 |
+
<tr>
|
67 |
+
<td style="text-align: left;"><b>Calories</b></td><td style="text-align: right;">{nutrition_data['calories']}</td>
|
68 |
+
<td style="text-align: left;"><b>Serving Size (g)</b></td><td style="text-align: right;">{nutrition_data['serving_size_g']}</td>
|
69 |
+
</tr>
|
70 |
+
<tr>
|
71 |
+
<td style="text-align: left;"><b>Total Fat (g)</b></td><td style="text-align: right;">{nutrition_data['fat_total_g']}</td>
|
72 |
+
<td style="text-align: left;"><b>Saturated Fat (g)</b></td><td style="text-align: right;">{nutrition_data['fat_saturated_g']}</td>
|
73 |
+
</tr>
|
74 |
+
<tr>
|
75 |
+
<td style="text-align: left;"><b>Protein (g)</b></td><td style="text-align: right;">{nutrition_data['protein_g']}</td>
|
76 |
+
<td style="text-align: left;"><b>Sodium (mg)</b></td><td style="text-align: right;">{nutrition_data['sodium_mg']}</td>
|
77 |
+
</tr>
|
78 |
+
<tr>
|
79 |
+
<td style="text-align: left;"><b>Potassium (mg)</b></td><td style="text-align: right;">{nutrition_data['potassium_mg']}</td>
|
80 |
+
<td style="text-align: left;"><b>Cholesterol (mg)</b></td><td style="text-align: right;">{nutrition_data['cholesterol_mg']}</td>
|
81 |
+
</tr>
|
82 |
+
<tr>
|
83 |
+
<td style="text-align: left;"><b>Total Carbohydrates (g)</b></td><td style="text-align: right;">{nutrition_data['carbohydrates_total_g']}</td>
|
84 |
+
<td style="text-align: left;"><b>Fiber (g)</b></td><td style="text-align: right;">{nutrition_data['fiber_g']}</td>
|
85 |
+
</tr>
|
86 |
+
<tr>
|
87 |
+
<td style="text-align: left;"><b>Sugar (g)</b></td><td style="text-align: right;">{nutrition_data['sugar_g']}</td>
|
88 |
+
<td></td><td></td>
|
89 |
+
</tr>
|
90 |
+
</table>
|
91 |
+
"""
|
92 |
+
return table
|
93 |
+
|
94 |
+
iface = gr.Interface(
|
95 |
+
fn=gradio_interface,
|
96 |
+
inputs=gr.Image(type="filepath"),
|
97 |
+
outputs="html",
|
98 |
+
title="Food Identification and Nutrition Info",
|
99 |
+
description="Upload an image of food to get nutritional information.",
|
100 |
+
allow_flagging="never" # Disable flagging
|
101 |
+
)
|
102 |
+
|
103 |
+
def run_gradio():
|
104 |
+
iface.launch(share=True)
|
105 |
+
|
106 |
+
def run_fastapi():
|
107 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
108 |
+
|
109 |
+
if __name__ == "__main__":
|
110 |
+
# Run Gradio and FastAPI in separate threads
|
111 |
+
gradio_thread = threading.Thread(target=run_gradio)
|
112 |
+
fastapi_thread = threading.Thread(target=run_fastapi)
|
113 |
+
|
114 |
+
gradio_thread.start()
|
115 |
+
fastapi_thread.start()
|
116 |
+
|
117 |
+
gradio_thread.join()
|
118 |
+
fastapi_thread.join()
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
transformers
|
3 |
+
torch
|
4 |
+
torchvision
|
5 |
+
requests
|
6 |
+
python-dotenv
|