File size: 11,108 Bytes
a8687fe 008130d | 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | import tensorflow
from flask import Flask, request, jsonify
import csv
import math
import os
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
from werkzeug.utils import secure_filename
import PIL
import google.generativeai as genai
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
os.environ['GOOGLE_API_KEY'] = "AIzaSyDrzwEvzqTTx33g3ikKoWyRU_mtxCuDa7s"
genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
# Define food labels (food101 classes)
label = ['apple pie',
'baby back ribs',
'baklava',
'beef carpaccio',
'beef tartare',
'beet salad',
'beignets',
'bibimbap',
'bread pudding',
'breakfast burrito',
'bruschetta',
'caesar salad',
'cannoli',
'caprese salad',
'carrot cake',
'ceviche',
'cheese plate',
'cheesecake',
'chicken curry',
'chicken quesadilla',
'chicken wings',
'chocolate cake',
'chocolate mousse',
'churros',
'clam chowder',
'club sandwich',
'crab cakes',
'creme brulee',
'croque madame',
'cup cakes',
'deviled eggs',
'donuts',
'dumplings',
'edamame',
'eggs benedict',
'escargots',
'falafel',
'filet mignon',
'fish and_chips',
'foie gras',
'french fries',
'french onion soup',
'french toast',
'fried calamari',
'fried rice',
'frozen yogurt',
'garlic bread',
'gnocchi',
'greek salad',
'grilled cheese sandwich',
'grilled salmon',
'guacamole',
'gyoza',
'hamburger',
'hot and sour soup',
'hot dog',
'huevos rancheros',
'hummus',
'ice cream',
'lasagna',
'lobster bisque',
'lobster roll sandwich',
'macaroni and cheese',
'macarons',
'miso soup',
'mussels',
'nachos',
'omelette',
'onion rings',
'oysters',
'pad thai',
'paella',
'pancakes',
'panna cotta',
'peking duck',
'pho',
'pizza',
'pork chop',
'poutine',
'prime rib',
'pulled pork sandwich',
'ramen',
'ravioli',
'red velvet cake',
'risotto',
'samosa',
'sashimi',
'scallops',
'seaweed salad',
'shrimp and grits',
'spaghetti bolognese',
'spaghetti carbonara',
'spring rolls',
'steak',
'strawberry shortcake',
'sushi',
'tacos',
'octopus balls',
'tiramisu',
'tuna tartare',
'waffles']
# Nutrition link base URL
nu_link = 'https://www.nutritionix.com/food/'
# Load the pre-trained model
tensorflow.keras.backend.clear_session()
import os
import requests
from keras.models import load_model
from tensorflow.keras.models import load_model
# GDRIVE_URL = "https://drive.google.com/uc?export=download&id=1cJt6ifr4aTdPj_R7sFJ86Kfz0b43HWFV"
# MODEL_PATH = "model_trained_101class.keras"
#
# def download_model():
# """Download the model from Google Drive if not already present."""
# if not os.path.exists(MODEL_PATH):
# print("Downloading model...")
# response = requests.get(GDRIVE_URL, stream=True)
# with open(MODEL_PATH, "wb") as file:
# for chunk in response.iter_content(chunk_size=1024):
# if chunk:
# file.write(chunk)
# print("Download complete.")
# GDRIVE_URL = "https://drive.google.com/uc?export=download&id=1cJt6ifr4aTdPj_R7sFJ86Kfz0b43HWFV"
# MODEL_PATH = "/tmp/model_trained_101class.keras" # Store in the temporary directory
#
# def download_model():
# """Download the model from Google Drive if not already present."""
# if not os.path.exists(MODEL_PATH):
# print("Downloading model...")
# response = requests.get(GDRIVE_URL, stream=True)
# with open(MODEL_PATH, "wb") as file:
# for chunk in response.iter_content(chunk_size=1024):
# if chunk:
# file.write(chunk)
# print("Download complete.")
#
# # Ensure model is available before loading
# download_model()
#
# # Load the model
# model_best = load_model(MODEL_PATH, compile=False)
# print("Model Loaded Successfully!")
# # Define the Google Drive direct download link and model path
# GDRIVE_URL = "https://drive.google.com/uc?export=download&id=1cJt6ifr4aTdPj_R7sFJ86Kfz0b43HWFV"
# MODEL_PATH = "./model_trained_101class.keras" # Store in the temporary directory
#
#
# def download_model():
# """Download the model from Google Drive if not already present."""
# print(f"Current working directory: {os.getcwd()}")
# print(f"Model will be saved at: {MODEL_PATH}")
#
# if not os.path.exists(MODEL_PATH):
# print("Downloading model...")
#
# # Start a session to handle cookies
# session = requests.Session()
# response = session.get(GDRIVE_URL, stream=True)
#
# # Check for a Google Drive confirmation token (for large files)
# for key, value in response.cookies.items():
# if key.startswith("download_warning"):
# GDRIVE_URL_with_token = GDRIVE_URL + "&confirm=" + value
# response = session.get(GDRIVE_URL_with_token, stream=True)
#
# # Download the file in chunks
# with open(MODEL_PATH, "wb") as file:
# for chunk in response.iter_content(chunk_size=1024):
# if chunk:
# file.write(chunk)
#
# print("Download complete.")
# if os.path.exists(MODEL_PATH):
# print(f"Current working directory: {os.getcwd()}")
# # print("Downloading model...")
# else:
# print("Model already exists.")
#
#
# # Ensure model is available before loading
# download_model()
#
# # Load the model
# model_best = load_model(MODEL_PATH, compile=False)
# print("Model Loaded Successfully!")
# Path to the model stored in Git LFS
# MODEL_PATH = "model_trained_101class.keras" # Store in the local repository
# # Ensure the model exists (Git LFS should have downloaded it)
# if not os.path.exists(MODEL_PATH):
# print(f"Error: Model file not found at {MODEL_PATH}.")
# print("If you just cloned the repo, run the following command to download large files:")
# print("\n git lfs pull\n")
# exit(1)
#
# # Load the model
# model_best = load_model(MODEL_PATH, compile=False)
# print("Model Loaded Successfully!")
model = tensorflow.keras.models.load_model("model_trained_101class.keras")
# Load nutrition data from CSV file
nutrition_table = dict()
with open('nutrition101.csv', 'r') as file:
reader = csv.reader(file)
for i, row in enumerate(reader):
if i == 0:
continue # Skip header row
name = row[1].strip()
nutrition_table[name] = [
{'name': 'protein', 'value': float(row[2])},
{'name': 'calcium', 'value': float(row[3])},
{'name': 'fat', 'value': float(row[4])},
{'name': 'carbohydrates', 'value': float(row[5])},
{'name': 'vitamins', 'value': float(row[6])}
]
@app.route('/api/predict', methods=['POST'])
def api_predict():
# Retrieve the single uploaded image
file = request.files.get("img")
if not file:
return jsonify({"error": "No image provided"}), 400
# Save the uploaded image
filename = secure_filename("uploaded.jpg")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Preprocess the image for prediction
pred_img = tensorflow.keras.preprocessing.image.load_img(filepath, target_size=(224, 224))
pred_img = tensorflow.keras.preprocessing.image.img_to_array(pred_img)
pred_img = np.expand_dims(pred_img, axis=0) # Add batch dimension
pred_img = pred_img / 255.0 # Normalize pixel values
# Perform prediction with the pre-trained model
pred = model_best.predict(pred_img)
# Fallback for NaN predictions (if applicable)
if (math.isnan(pred[0][0]) and math.isnan(pred[0][1]) and
math.isnan(pred[0][2]) and math.isnan(pred[0][3])):
pred = np.array([[0.05, 0.05, 0.05, 0.07, 0.09, 0.19, 0.55, 0.0, 0.0, 0.0, 0.0]])
# Get indices of top three predictions
top = pred.argsort()[0][-3:]
label.sort() # Ensure the labels are sorted
top_food = label[top[2]] # Highest predicted label
# Create a result dictionary for the predictions with probability percentages
result = {
top_food: float("{:.2f}".format(pred[0][top[2]] * 100)),
label[top[1]]: float("{:.2f}".format(pred[0][top[1]] * 100)),
label[top[0]]: float("{:.2f}".format(pred[0][top[0]] * 100))
}
# Retrieve nutrition data for the predicted food
nutrition_data = nutrition_table.get(top_food, [])
# Construct nutrition URL
food_link = f'{nu_link}{top_food}'
# Use generative AI to get a descriptive response (assuming synchronous response)
img = PIL.Image.open(filepath)
vision_model = genai.GenerativeModel('gemini-1.5-flash')
ai_response = vision_model.generate_content([
"Give me response in this form 'The image displays /items/ with an /estimated calories for all items and give accurate calories /' ",
img
])
# Prepare the API response data as a JSON object
response_data = {
"image": filepath,
"result": result,
"nutrition": nutrition_data,
"food": food_link,
"ai": ai_response.text # Assumes the generative AI response has a 'text' attribute
}
return jsonify(response_data)
# @app.route('/')
# def home():
# return "Flask App is Running on Render!"
#
# if __name__ == "__main__":
# import click
#
#
# @click.command()
# @click.option('--debug', is_flag=True)
# @click.option('--threaded', is_flag=True)
# @click.argument('HOST', default='0.0.0.0')
# @click.argument('PORT', default=5000, type=int)
# def run(debug, threaded, host, port):
# """
# Run the server using:
# python server.py
# Use:
# python server.py --help
# to see help text.
# """
# HOST, PORT = host, port
# app.run(host=HOST, port=PORT, debug=debug, threaded=threaded)
#
#
# run()
@app.route("/")
def home():
return "Flask App is Running !"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000)) # Use Render-assigned PORT
app.run(host="0.0.0.0", port=port, debug=True)
from transformers import pipeline
model = pipeline("image-classification", model="Kali-123/calorie-tracker")
|