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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""recipeteller.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1cs8uKGpq9jzvso3vhAKjy9iSwbV_gnGM
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
# Use a pipeline as a high-level helper
|
| 11 |
+
from transformers import pipeline
|
| 12 |
+
|
| 13 |
+
pipe = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 14 |
+
|
| 15 |
+
# Use a pipeline as a high-level helper
|
| 16 |
+
from transformers import pipeline
|
| 17 |
+
|
| 18 |
+
pipe = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 19 |
+
|
| 20 |
+
pip install datasets
|
| 21 |
+
|
| 22 |
+
pip install datasets
|
| 23 |
+
|
| 24 |
+
from datasets import load_dataset
|
| 25 |
+
|
| 26 |
+
# Load the dataset
|
| 27 |
+
dataset = load_dataset("Zappandy/recipe_nlg")
|
| 28 |
+
|
| 29 |
+
# Sample 5% of the dataset
|
| 30 |
+
train_sample = dataset["train"].shuffle(seed=42).select(range(int(0.05 * len(dataset["train"]))))
|
| 31 |
+
val_sample = dataset["validation"].shuffle(seed=42).select(range(int(0.05 * len(dataset["validation"]))))
|
| 32 |
+
print(f"Training samples: {len(train_sample)}, Validation samples: {len(val_sample)}")
|
| 33 |
+
|
| 34 |
+
print(dataset.column_names)
|
| 35 |
+
|
| 36 |
+
from transformers import AutoTokenizer
|
| 37 |
+
|
| 38 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 39 |
+
|
| 40 |
+
def preprocess_function(examples):
|
| 41 |
+
return tokenizer(examples['text'], padding="max_length", truncation=True)
|
| 42 |
+
|
| 43 |
+
def preprocess_function(examples):
|
| 44 |
+
return tokenizer(examples['text'], padding="max_length", truncation=True, return_tensors="pt")
|
| 45 |
+
|
| 46 |
+
def preprocess_function(examples):
|
| 47 |
+
try:
|
| 48 |
+
return tokenizer(examples['text'], padding="max_length", truncation=True)
|
| 49 |
+
except KeyError as e:
|
| 50 |
+
print(f"KeyError: {e} - Available columns: {examples.keys()}")
|
| 51 |
+
raise
|
| 52 |
+
|
| 53 |
+
from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSequenceClassification
|
| 54 |
+
from datasets import load_dataset
|
| 55 |
+
|
| 56 |
+
# Load dataset (replace with your own dataset or path)
|
| 57 |
+
dataset = load_dataset('imdb')
|
| 58 |
+
|
| 59 |
+
# Initialize the tokenizer
|
| 60 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 61 |
+
|
| 62 |
+
# Define the preprocessing function
|
| 63 |
+
def preprocess_function(examples):
|
| 64 |
+
return tokenizer(examples['text'], padding="max_length", truncation=True)
|
| 65 |
+
|
| 66 |
+
# Reduce the dataset size for faster training
|
| 67 |
+
small_train_dataset = dataset['train'].select(range(2000)) # Use only 2000 samples for training
|
| 68 |
+
small_test_dataset = dataset['test'].select(range(1000)) # Use only 1000 samples for testing
|
| 69 |
+
|
| 70 |
+
# Tokenize the datasets
|
| 71 |
+
tokenized_train = small_train_dataset.map(preprocess_function, batched=True)
|
| 72 |
+
tokenized_val = small_test_dataset.map(preprocess_function, batched=True)
|
| 73 |
+
|
| 74 |
+
# Define the model (replace with your own model or pre-trained model)
|
| 75 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
|
| 76 |
+
|
| 77 |
+
# Define the training arguments
|
| 78 |
+
training_args = TrainingArguments(
|
| 79 |
+
output_dir='./results', # output directory
|
| 80 |
+
evaluation_strategy="epoch", # evaluate after each epoch
|
| 81 |
+
per_device_train_batch_size=16, # batch size for training
|
| 82 |
+
per_device_eval_batch_size=64, # batch size for evaluation
|
| 83 |
+
num_train_epochs=1, # number of training epochs (reduced for speed)
|
| 84 |
+
weight_decay=0.01, # strength of weight decay
|
| 85 |
+
save_total_limit=1, # keep only the most recent checkpoint
|
| 86 |
+
logging_dir='./logs', # directory for storing logs
|
| 87 |
+
logging_steps=10, # log every 10 steps
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Create Trainer instance
|
| 91 |
+
trainer = Trainer(
|
| 92 |
+
model=model,
|
| 93 |
+
args=training_args,
|
| 94 |
+
train_dataset=tokenized_train,
|
| 95 |
+
eval_dataset=tokenized_val,
|
| 96 |
+
tokenizer=tokenizer
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# Start training
|
| 100 |
+
trainer.train()
|
| 101 |
+
|
| 102 |
+
eval_results = trainer.evaluate()
|
| 103 |
+
print(eval_results)
|
| 104 |
+
|
| 105 |
+
# Save the model and tokenizer
|
| 106 |
+
model.save_pretrained('./trained_model')
|
| 107 |
+
tokenizer.save_pretrained('./trained_model')
|
| 108 |
+
|
| 109 |
+
from transformers import pipeline
|
| 110 |
+
|
| 111 |
+
# Load the model and tokenizer
|
| 112 |
+
model = AutoModelForSequenceClassification.from_pretrained('./trained_model')
|
| 113 |
+
tokenizer = AutoTokenizer.from_pretrained('./trained_model')
|
| 114 |
+
|
| 115 |
+
# Create a pipeline for text classification
|
| 116 |
+
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
| 117 |
+
|
| 118 |
+
# Make predictions
|
| 119 |
+
predictions = classifier("This is a great movie!")
|
| 120 |
+
print(predictions)
|
| 121 |
+
|
| 122 |
+
training_args = TrainingArguments(
|
| 123 |
+
output_dir='./results',
|
| 124 |
+
evaluation_strategy="epoch", # Evaluate every epoch
|
| 125 |
+
save_strategy="epoch", # Save the model at the end of each epoch
|
| 126 |
+
save_total_limit=3, # Keep only the last 3 checkpoints
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
pip install gradio
|
| 130 |
+
|
| 131 |
+
import gradio as gr
|
| 132 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
|
| 133 |
+
|
| 134 |
+
# Load the trained model and tokenizer
|
| 135 |
+
model = AutoModelForSequenceClassification.from_pretrained('./trained_model')
|
| 136 |
+
tokenizer = AutoTokenizer.from_pretrained('./trained_model')
|
| 137 |
+
|
| 138 |
+
# Create a pipeline for text classification
|
| 139 |
+
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
| 140 |
+
|
| 141 |
+
# Define a function that takes input text and returnimport gradio as gr
|
| 142 |
+
|
| 143 |
+
# Define the recipe suggestion function
|
| 144 |
+
def suggest_recipe(ingredients):
|
| 145 |
+
# Example recipe database
|
| 146 |
+
recipes = {
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# Pakistani Cuisine
|
| 150 |
+
"biryani": "Ingredients: basmati rice, chicken, yogurt, spices, onions, tomatoes. Instructions: Marinate chicken, cook with spices and yogurt, and layer with rice. Steam together.",
|
| 151 |
+
"karahi": "Ingredients: chicken, tomatoes, ginger, garlic, green chilies, spices. Instructions: Cook chicken with spices and tomatoes in a wok until tender.",
|
| 152 |
+
"nihari": "Ingredients: beef shank, flour, ghee, ginger, garlic, spices. Instructions: Slow cook beef with spices and serve with naan.",
|
| 153 |
+
"haleem": "Ingredients: wheat, lentils, beef, ginger, garlic, spices. Instructions: Cook all ingredients together until a thick consistency is achieved.",
|
| 154 |
+
"seekh kebab": "Ingredients: ground beef, onions, spices, ginger, garlic. Instructions: Mix ingredients, shape onto skewers, and grill until cooked.",
|
| 155 |
+
"chapli kebab": "Ingredients: minced meat, pomegranate seeds, spices, onions, tomatoes. Instructions: Shape into patties and shallow fry until golden.",
|
| 156 |
+
|
| 157 |
+
# Indian Cuisine
|
| 158 |
+
"butter chicken": "Ingredients: chicken, butter, cream, tomatoes, spices. Instructions: Cook chicken, make a rich tomato-based sauce with cream, and simmer together.",
|
| 159 |
+
"palak paneer": "Ingredients: spinach, paneer, cream, garlic, spices. Instructions: Cook spinach with spices, blend, and add paneer cubes.",
|
| 160 |
+
"masala dosa": "Ingredients: rice, lentils, potato, curry leaves, spices. Instructions: Make rice and lentil batter, cook thin pancakes, and fill with spiced potato mixture.",
|
| 161 |
+
"chole bhature": "Ingredients: chickpeas, tomatoes, onions, flour, spices. Instructions: Cook chickpeas with spices, and serve with deep-fried bread.",
|
| 162 |
+
"samosa": "Ingredients: flour, potatoes, peas, spices. Instructions: Make a dough, fill with spiced potato mixture, and deep fry.",
|
| 163 |
+
"tandoori chicken": "Ingredients: chicken, yogurt, tandoori spices, lemon juice. Instructions: Marinate chicken, and cook in a tandoor or oven until charred.",
|
| 164 |
+
|
| 165 |
+
# Chinese Cuisine
|
| 166 |
+
"dumplings": "Ingredients: flour, ground meat, cabbage, soy sauce, ginger. Instructions: Make dough, prepare filling, and steam or fry dumplings.",
|
| 167 |
+
"sweet and sour chicken": "Ingredients: chicken, bell peppers, pineapple, soy sauce, vinegar. Instructions: Stir-fry chicken with vegetables and a tangy sweet sauce.",
|
| 168 |
+
"fried rice": "Ingredients: rice, soy sauce, eggs, vegetables, garlic. Instructions: Stir-fry rice with soy sauce, eggs, and vegetables.",
|
| 169 |
+
"hot and sour soup": "Ingredients: tofu, mushrooms, soy sauce, vinegar, spices. Instructions: Cook all ingredients together in a spicy, tangy broth.",
|
| 170 |
+
"kung pao chicken": "Ingredients: chicken, peanuts, dried chilies, soy sauce, garlic. Instructions: Stir-fry chicken with peanuts and a savory sauce.",
|
| 171 |
+
"spring rolls": "Ingredients: spring roll wrappers, vegetables, soy sauce. Instructions: Fill wrappers with vegetables, roll, and deep fry.",
|
| 172 |
+
|
| 173 |
+
# Western Cuisine
|
| 174 |
+
"fish and chips": "Ingredients: fish fillets, potatoes, flour, eggs, breadcrumbs. Instructions: Coat fish in batter, fry with chips, and serve with tartar sauce.",
|
| 175 |
+
"caesar salad": "Ingredients: lettuce, croutons, Parmesan cheese, Caesar dressing. Instructions: Toss lettuce with croutons and dressing, garnish with Parmesan.",
|
| 176 |
+
"spaghetti carbonara": "Ingredients: spaghetti, eggs, Parmesan cheese, pancetta, black pepper. Instructions: Cook spaghetti, mix with sauce made of eggs, cheese, and pancetta.",
|
| 177 |
+
"pancakes": "Ingredients: flour, eggs, milk, sugar, butter. Instructions: Mix ingredients and cook on a hot griddle until golden brown.",
|
| 178 |
+
"hamburger": "Ingredients: ground beef, burger buns, lettuce, tomato, cheese. Instructions: Shape beef into patties, grill, and assemble burger with toppings.",
|
| 179 |
+
"apple pie": "Ingredients: apples, sugar, flour, butter, cinnamon. Instructions: Make pie crust, fill with spiced apples, and bake until golden."
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Convert the ingredients to lowercase for case-insensitive matching
|
| 184 |
+
ingredients = ingredients.lower()
|
| 185 |
+
|
| 186 |
+
# Check if any of the recipes match the ingredients
|
| 187 |
+
for dish, recipe in recipes.items():
|
| 188 |
+
if dish in ingredients:
|
| 189 |
+
return recipe
|
| 190 |
+
|
| 191 |
+
return "Sorry, we couldn't find a recipe for these ingredients."
|
| 192 |
+
|
| 193 |
+
# Create the Gradio interface
|
| 194 |
+
interface = gr.Interface(
|
| 195 |
+
fn=suggest_recipe, # Function to call for generating recipe
|
| 196 |
+
inputs=gr.Textbox(label="Enter Ingredients (comma-separated)"), # Input for ingredients
|
| 197 |
+
outputs=gr.Textbox(label="Recipe Suggestion"), # Output for recipe
|
| 198 |
+
title="Recipe Suggestion App", # Title of the app
|
| 199 |
+
description="Enter the ingredients you have, and I'll suggest a recipe for you." # Description
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Launch the Gradio interface with a public link
|
| 203 |
+
interface.launch(share=True) # share=True to generate a public link
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
transformers
|
| 3 |
+
datasets
|
| 4 |
+
torch # or tensorflow
|
| 5 |
+
numpy
|
| 6 |
+
pandas
|