File size: 2,416 Bytes
924a9f9
23b09ce
 
064f427
 
 
924a9f9
23b09ce
 
064f427
 
23b09ce
064f427
23b09ce
064f427
 
23b09ce
064f427
 
 
 
1e16169
064f427
 
 
 
 
23b09ce
064f427
23b09ce
 
 
 
 
 
 
 
064f427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import requests
from io import BytesIO
from PIL import Image
from transformers import pipeline

# --- 1. Load Recipes Dataset ---
@st.cache_data
def load_data():
    return pd.read_csv("recipes.csv")

df = load_data()

# --- 2. Initialize LLM Pipeline ---
llm = pipeline("text-generation", model="facebook/opt-1.3b")

# --- 3. Retrieve Recipe Function ---
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

# --- 4. Generate Response for Non-Recipe Queries ---
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

# --- 5. Display Image Function ---
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)

# --- 6. Streamlit UI ---
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))