| import streamlit as st |
| import pandas as pd |
| import requests |
| from io import BytesIO |
| from PIL import Image |
| from transformers import pipeline |
|
|
| |
| @st.cache_data |
| def load_data(): |
| return pd.read_csv("recipes.csv") |
|
|
| df = load_data() |
|
|
| |
| llm = pipeline("text-generation", model="facebook/opt-1.3b") |
|
|
| |
| def retrieve_recipe(query): |
| matching_recipes = df[df['recipe_name'].str.contains(query, case=False, na=False)] |
| return matching_recipes if not matching_recipes.empty else None |
|
|
| |
| def generate_response(query): |
| prompt = f"You are an AI assistant that only provides recipe-related responses. If the user asks something unrelated to recipes, politely decline. Query: {query}" |
| response = llm(prompt, max_length=100, do_sample=True)[0]['generated_text'] |
| return response |
|
|
| |
| def display_image(image_url, recipe_name): |
| try: |
| if not isinstance(image_url, str) or not image_url.startswith("http"): |
| raise ValueError("Invalid or missing image URL") |
| response = requests.get(image_url, timeout=5) |
| response.raise_for_status() |
| image = Image.open(BytesIO(response.content)) |
| st.image(image, caption=recipe_name, use_container_width=True) |
| except requests.exceptions.RequestException: |
| st.image("https://via.placeholder.com/300?text=No+Image", caption=recipe_name, use_container_width=True) |
|
|
| |
| st.title("🍽 Recipe Finder RAG App") |
| query = st.text_input("Ask me for a recipe:") |
|
|
| if query: |
| recipe_result = retrieve_recipe(query) |
| if recipe_result is not None: |
| for _, row in recipe_result.iterrows(): |
| st.subheader(row['recipe_name']) |
| st.write(f"**Prep Time:** {row['prep_time']} | **Cook Time:** {row['cook_time']} | **Total Time:** {row['total_time']}") |
| st.write(f"**Servings:** {row['servings']} | **Yield:** {row['yield']}") |
| st.write(f"**Ingredients:** {row['ingredients']}") |
| st.write(f"**Directions:** {row['directions']}") |
| st.write(f"[View Full Recipe]({row['url']})") |
| display_image(row['img_src'], row['recipe_name']) |
| else: |
| st.warning("⚠ No recipe found! Generating a response...") |
| st.write(generate_response(query)) |
|
|