File size: 8,813 Bytes
c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 c6624ca 73961e4 |
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 |
import numpy as np
import pandas as pd
import gradio as gr
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input, decode_predictions
from fuzzywuzzy import fuzz
from transformers import pipeline
import requests
from PIL import Image
from io import BytesIO
# Load models using pipeline for recipe generation
models = {
"Flan-T5 Small": pipeline("text2text-generation", model="BhavaishKumar112/flan-t5-small"),
"GPT-Neo 125M": pipeline("text-generation", model="BhavaishKumar112/gpt-neo-125M"),
"Final GPT-2 Trained": pipeline("text-generation", model="BhavaishKumar112/finalgpt2trained")
}
# Supported cuisines for recipe generation
cuisines = ["Thai", "Indian", "Chinese", "Italian"]
# Load the dataset for image classification and recipe search
dataset_path = "Food_Recipe.csv" # Update with your dataset path
data_df = pd.read_csv(dataset_path)
# Load MobileNetV2 pre-trained model for image classification
mobilenet_model = MobileNetV2(weights="imagenet")
# Function to preprocess images
def preprocess_image(image_path, target_size=(224, 224)):
image = load_img(image_path, target_size=target_size)
image_array = img_to_array(image)
image_array = np.expand_dims(image_array, axis=0)
return preprocess_input(image_array)
# Function to classify an image
def classify_image(image):
try:
image_array = preprocess_image(image)
predictions = mobilenet_model.predict(image_array)
decoded_predictions = decode_predictions(predictions, top=3)[0]
return decoded_predictions
except Exception as e:
print(f"Error during classification: {e}")
return []
# Map classification to recipe using fuzzy matching
def map_to_recipe(classification_results):
for result in classification_results:
best_match = None
best_score = 0
for index, row in data_df.iterrows():
score = fuzz.partial_ratio(result[1].lower(), row["name"].lower())
if score > best_score:
best_score = score
best_match = row
if best_score >= 70:
return best_match
return None
# Generate recipe summary
def generate_summary(recipe):
ingredients = recipe.get("ingredients_name", "No ingredients provided")
time_to_cook = recipe.get("time_to_cook", "Time to cook not provided")
instructions = recipe.get("instructions", "No instructions provided")
return f"Ingredients: {ingredients}\n\nTime to Cook: {time_to_cook}\n\nInstructions: {instructions}"
# Function to handle image input and return recipe details
def get_recipe_details(image):
classification_results = classify_image(image)
if not classification_results:
return "Error: No classification results found for the image."
recipe = map_to_recipe(classification_results)
if recipe is not None:
return generate_summary(recipe)
else:
return "No matching recipe found for this image."
# Function for recipe generation (as before)
def generate_recipe(input_text, selected_model, selected_cuisine):
prompt = (
f"Generate a detailed and structured {selected_cuisine} recipe for {input_text}. "
f"Include all the necessary details such as ingredients under an 'Ingredients' heading "
f"and steps under a 'Recipe' heading. Ensure the response is concise and well-organized."
)
model = models[selected_model]
output = model(prompt, max_length=500, num_return_sequences=1)[0]['generated_text']
return output
# Function to fetch and display the image for a recipe name
def fetch_recipe_image(recipe_name):
matching_row = data_df[data_df['name'].str.contains(recipe_name, case=False, na=False)]
if not matching_row.empty:
image_url = matching_row.iloc[0]['image_url']
try:
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
return img
except Exception as e:
return f"Error fetching image: {e}"
else:
return "No matching recipe found. Please check the recipe name."
# Gradio interface with updated professional design
def main():
with gr.Blocks(css="""
/* General Body Styling */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f5f5f5; /* Light background */
margin: 0;
padding: 0;
color: #333; /* Dark text */
}
/* Header Styling */
.header {
background-color: #006064; /* Professional Blue */
color: white;
padding: 20px;
font-size: 24px;
font-weight: bold;
text-align: center;
border-radius: 10px;
}
/* Card Style for Tabs */
.tab-container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
margin-top: 20px;
}
/* Card for each input section */
.card {
background-color: #ffffff;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
margin-bottom: 20px;
}
.card-title {
font-size: 18px;
font-weight: bold;
color: #006064;
margin-bottom: 10px;
}
/* Inputs and Buttons */
.input-text, .radio, .button {
width: 100%;
padding: 12px;
border-radius: 8px;
border: 1px solid #ddd;
background-color: #f5f5f5;
color: #333;
font-size: 16px;
}
.input-text:focus, .radio:focus, .button:focus {
border-color: #006064;
}
.button {
background-color: #006064;
color: white;
font-weight: bold;
cursor: pointer;
}
.button:hover {
background-color: #004d40; /* Darker shade of blue on hover */
}
/* Output Box */
.output-box {
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
font-size: 16px;
color: #333;
max-height: 350px;
overflow-y: auto;
white-space: pre-wrap;
}
.output-box img {
max-width: 100%;
border-radius: 8px;
}
/* Tab Title */
.tab-title {
font-size: 22px;
font-weight: bold;
color: #006064;
margin-bottom: 10px;
}
""") as app:
with gr.Tab("Recipe Generator"):
gr.HTML("<div class='header'>Recipe Generator</div>")
with gr.Column(visible=True):
with gr.Box(elem_classes=["tab-container"]):
recipe_input = gr.Textbox(label="Enter Recipe Name or Ingredients", placeholder="e.g., Chicken curry or chicken, garlic, onions", elem_classes=["input-text"])
selected_cuisine = gr.Radio(choices=cuisines, label="Cuisine", value="Indian", elem_classes=["radio"])
selected_model = gr.Radio(choices=list(models.keys()), label="Model", value="Flan-T5 Small", elem_classes=["radio"])
generate_button = gr.Button("Generate Recipe", elem_classes=["button"])
recipe_output = gr.Textbox(label="Recipe", lines=15, elem_classes=["output-box"])
generate_button.click(generate_recipe, inputs=[recipe_input, selected_model, selected_cuisine], outputs=recipe_output)
with gr.Tab("Recipe Finder from Image"):
gr.HTML("<div class='header'>Recipe Finder from Image</div>")
with gr.Column(visible=True):
with gr.Box(elem_classes=["tab-container"]):
image_input = gr.Image(type="filepath", label="Upload an Image")
image_output = gr.Textbox(label="Recipe Details", lines=10, elem_classes=["output-box"])
image_input.change(get_recipe_details, inputs=image_input, outputs=image_output)
with gr.Tab("Recipe Image Search"):
gr.HTML("<div class='header'>Recipe Image Search</div>")
with gr.Column(visible=True):
with gr.Box(elem_classes=["tab-container"]):
recipe_name_input = gr.Textbox(label="Recipe Name", placeholder="e.g., Mixed Sprouts in Chettinad Masala Recipe", elem_classes=["input-text"])
fetch_image_button
|