Spaces:
No application file
No application file
# -*- coding: utf-8 -*- | |
"""recipeteller.ipynb | |
Automatically generated by Colab. | |
Original file is located at | |
https://colab.research.google.com/drive/1cs8uKGpq9jzvso3vhAKjy9iSwbV_gnGM | |
""" | |
# Use a pipeline as a high-level helper | |
from transformers import pipeline | |
pipe = pipeline("text2text-generation", model="google/flan-t5-base") | |
# Use a pipeline as a high-level helper | |
from transformers import pipeline | |
pipe = pipeline("text2text-generation", model="google/flan-t5-base") | |
pip install datasets | |
pip install datasets | |
from datasets import load_dataset | |
# Load the dataset | |
dataset = load_dataset("Zappandy/recipe_nlg") | |
# Sample 5% of the dataset | |
train_sample = dataset["train"].shuffle(seed=42).select(range(int(0.05 * len(dataset["train"])))) | |
val_sample = dataset["validation"].shuffle(seed=42).select(range(int(0.05 * len(dataset["validation"])))) | |
print(f"Training samples: {len(train_sample)}, Validation samples: {len(val_sample)}") | |
print(dataset.column_names) | |
from transformers import AutoTokenizer | |
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") | |
def preprocess_function(examples): | |
return tokenizer(examples['text'], padding="max_length", truncation=True) | |
def preprocess_function(examples): | |
return tokenizer(examples['text'], padding="max_length", truncation=True, return_tensors="pt") | |
def preprocess_function(examples): | |
try: | |
return tokenizer(examples['text'], padding="max_length", truncation=True) | |
except KeyError as e: | |
print(f"KeyError: {e} - Available columns: {examples.keys()}") | |
raise | |
from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSequenceClassification | |
from datasets import load_dataset | |
# Load dataset (replace with your own dataset or path) | |
dataset = load_dataset('imdb') | |
# Initialize the tokenizer | |
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") | |
# Define the preprocessing function | |
def preprocess_function(examples): | |
return tokenizer(examples['text'], padding="max_length", truncation=True) | |
# Reduce the dataset size for faster training | |
small_train_dataset = dataset['train'].select(range(2000)) # Use only 2000 samples for training | |
small_test_dataset = dataset['test'].select(range(1000)) # Use only 1000 samples for testing | |
# Tokenize the datasets | |
tokenized_train = small_train_dataset.map(preprocess_function, batched=True) | |
tokenized_val = small_test_dataset.map(preprocess_function, batched=True) | |
# Define the model (replace with your own model or pre-trained model) | |
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2) | |
# Define the training arguments | |
training_args = TrainingArguments( | |
output_dir='./results', # output directory | |
evaluation_strategy="epoch", # evaluate after each epoch | |
per_device_train_batch_size=16, # batch size for training | |
per_device_eval_batch_size=64, # batch size for evaluation | |
num_train_epochs=1, # number of training epochs (reduced for speed) | |
weight_decay=0.01, # strength of weight decay | |
save_total_limit=1, # keep only the most recent checkpoint | |
logging_dir='./logs', # directory for storing logs | |
logging_steps=10, # log every 10 steps | |
) | |
# Create Trainer instance | |
trainer = Trainer( | |
model=model, | |
args=training_args, | |
train_dataset=tokenized_train, | |
eval_dataset=tokenized_val, | |
tokenizer=tokenizer | |
) | |
# Start training | |
trainer.train() | |
eval_results = trainer.evaluate() | |
print(eval_results) | |
# Save the model and tokenizer | |
model.save_pretrained('./trained_model') | |
tokenizer.save_pretrained('./trained_model') | |
from transformers import pipeline | |
# Load the model and tokenizer | |
model = AutoModelForSequenceClassification.from_pretrained('./trained_model') | |
tokenizer = AutoTokenizer.from_pretrained('./trained_model') | |
# Create a pipeline for text classification | |
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer) | |
# Make predictions | |
predictions = classifier("This is a great movie!") | |
print(predictions) | |
training_args = TrainingArguments( | |
output_dir='./results', | |
evaluation_strategy="epoch", # Evaluate every epoch | |
save_strategy="epoch", # Save the model at the end of each epoch | |
save_total_limit=3, # Keep only the last 3 checkpoints | |
) | |
pip install gradio | |
import gradio as gr | |
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline | |
# Load the trained model and tokenizer | |
model = AutoModelForSequenceClassification.from_pretrained('./trained_model') | |
tokenizer = AutoTokenizer.from_pretrained('./trained_model') | |
# Create a pipeline for text classification | |
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer) | |
# Define a function that takes input text and returnimport gradio as gr | |
# Define the recipe suggestion function | |
def suggest_recipe(ingredients): | |
# Example recipe database | |
recipes = { | |
# Pakistani Cuisine | |
"biryani": "Ingredients: basmati rice, chicken, yogurt, spices, onions, tomatoes. Instructions: Marinate chicken, cook with spices and yogurt, and layer with rice. Steam together.", | |
"karahi": "Ingredients: chicken, tomatoes, ginger, garlic, green chilies, spices. Instructions: Cook chicken with spices and tomatoes in a wok until tender.", | |
"nihari": "Ingredients: beef shank, flour, ghee, ginger, garlic, spices. Instructions: Slow cook beef with spices and serve with naan.", | |
"haleem": "Ingredients: wheat, lentils, beef, ginger, garlic, spices. Instructions: Cook all ingredients together until a thick consistency is achieved.", | |
"seekh kebab": "Ingredients: ground beef, onions, spices, ginger, garlic. Instructions: Mix ingredients, shape onto skewers, and grill until cooked.", | |
"chapli kebab": "Ingredients: minced meat, pomegranate seeds, spices, onions, tomatoes. Instructions: Shape into patties and shallow fry until golden.", | |
# Indian Cuisine | |
"butter chicken": "Ingredients: chicken, butter, cream, tomatoes, spices. Instructions: Cook chicken, make a rich tomato-based sauce with cream, and simmer together.", | |
"palak paneer": "Ingredients: spinach, paneer, cream, garlic, spices. Instructions: Cook spinach with spices, blend, and add paneer cubes.", | |
"masala dosa": "Ingredients: rice, lentils, potato, curry leaves, spices. Instructions: Make rice and lentil batter, cook thin pancakes, and fill with spiced potato mixture.", | |
"chole bhature": "Ingredients: chickpeas, tomatoes, onions, flour, spices. Instructions: Cook chickpeas with spices, and serve with deep-fried bread.", | |
"samosa": "Ingredients: flour, potatoes, peas, spices. Instructions: Make a dough, fill with spiced potato mixture, and deep fry.", | |
"tandoori chicken": "Ingredients: chicken, yogurt, tandoori spices, lemon juice. Instructions: Marinate chicken, and cook in a tandoor or oven until charred.", | |
# Chinese Cuisine | |
"dumplings": "Ingredients: flour, ground meat, cabbage, soy sauce, ginger. Instructions: Make dough, prepare filling, and steam or fry dumplings.", | |
"sweet and sour chicken": "Ingredients: chicken, bell peppers, pineapple, soy sauce, vinegar. Instructions: Stir-fry chicken with vegetables and a tangy sweet sauce.", | |
"fried rice": "Ingredients: rice, soy sauce, eggs, vegetables, garlic. Instructions: Stir-fry rice with soy sauce, eggs, and vegetables.", | |
"hot and sour soup": "Ingredients: tofu, mushrooms, soy sauce, vinegar, spices. Instructions: Cook all ingredients together in a spicy, tangy broth.", | |
"kung pao chicken": "Ingredients: chicken, peanuts, dried chilies, soy sauce, garlic. Instructions: Stir-fry chicken with peanuts and a savory sauce.", | |
"spring rolls": "Ingredients: spring roll wrappers, vegetables, soy sauce. Instructions: Fill wrappers with vegetables, roll, and deep fry.", | |
# Western Cuisine | |
"fish and chips": "Ingredients: fish fillets, potatoes, flour, eggs, breadcrumbs. Instructions: Coat fish in batter, fry with chips, and serve with tartar sauce.", | |
"caesar salad": "Ingredients: lettuce, croutons, Parmesan cheese, Caesar dressing. Instructions: Toss lettuce with croutons and dressing, garnish with Parmesan.", | |
"spaghetti carbonara": "Ingredients: spaghetti, eggs, Parmesan cheese, pancetta, black pepper. Instructions: Cook spaghetti, mix with sauce made of eggs, cheese, and pancetta.", | |
"pancakes": "Ingredients: flour, eggs, milk, sugar, butter. Instructions: Mix ingredients and cook on a hot griddle until golden brown.", | |
"hamburger": "Ingredients: ground beef, burger buns, lettuce, tomato, cheese. Instructions: Shape beef into patties, grill, and assemble burger with toppings.", | |
"apple pie": "Ingredients: apples, sugar, flour, butter, cinnamon. Instructions: Make pie crust, fill with spiced apples, and bake until golden." | |
} | |
# Convert the ingredients to lowercase for case-insensitive matching | |
ingredients = ingredients.lower() | |
# Check if any of the recipes match the ingredients | |
for dish, recipe in recipes.items(): | |
if dish in ingredients: | |
return recipe | |
return "Sorry, we couldn't find a recipe for these ingredients." | |
# Create the Gradio interface | |
interface = gr.Interface( | |
fn=suggest_recipe, # Function to call for generating recipe | |
inputs=gr.Textbox(label="Enter Ingredients (comma-separated)"), # Input for ingredients | |
outputs=gr.Textbox(label="Recipe Suggestion"), # Output for recipe | |
title="Recipe Suggestion App", # Title of the app | |
description="Enter the ingredients you have, and I'll suggest a recipe for you." # Description | |
) | |
# Launch the Gradio interface with a public link | |
interface.launch(share=True) # share=True to generate a public link | |