Update app.py

#1
by krisha06 - opened
Files changed (1) hide show
  1. app.py +56 -43
app.py CHANGED
@@ -73,7 +73,6 @@ def load_llm_model():
73
 
74
  llm_model = load_llm_model()
75
 
76
- # --- 7. Answer Greeting and Handle Q&A Queries ---
77
  def answer_question(query, context=""):
78
  greetings = ["hi", "hello", "hii", "hey", "greetings", "how are you", "what's up", "how's it going"]
79
 
@@ -106,22 +105,40 @@ def answer_question(query, context=""):
106
 
107
  return answer
108
 
109
- # --- 8. Classify Query Type (Q&A or Recipe Search) ---
110
- @st.cache_resource
111
- def load_classifier():
112
- return pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
113
-
114
- classifier = load_classifier()
115
-
116
- def classify_query(query):
117
- recipe_keywords = ["make", "cook", "bake", "recipe", "prepare"]
118
- if any(keyword in query.lower() for keyword in recipe_keywords):
119
- return "Recipe Search"
120
 
121
- labels = ["Q&A", "Recipe Search"]
122
- result = classifier(query, candidate_labels=labels, multi_label=False)
123
- return result.get("labels", ["Q&A"])[0]
124
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  # --- 9. Display Image Function ---
126
  def display_image(image_url, recipe_name):
127
  try:
@@ -136,7 +153,7 @@ def display_image(image_url, recipe_name):
136
  placeholder_url = "https://via.placeholder.com/300?text=No+Image"
137
  st.image(placeholder_url, caption=recipe_name, use_container_width=True)
138
 
139
- # --- 10. Streamlit UI ---
140
  st.title("🍽️ AI Recipe & Q&A Assistant")
141
 
142
  user_query = st.text_input("Enter your question or recipe search query:", "", key="main_query_input")
@@ -146,31 +163,27 @@ if "retrieved_recipes" not in st.session_state:
146
 
147
  if st.button("Ask AI"):
148
  if user_query:
149
- # Handle greetings separately
150
- greeting_response = answer_question(user_query)
151
- if greeting_response == "Hello! How can I assist you today?":
 
152
  st.subheader("πŸ€– AI Answer:")
153
- st.write(greeting_response)
154
- else:
155
- # Classify query
156
- intent = classify_query(user_query)
157
-
158
- if intent == "Q&A":
159
- st.subheader("πŸ€– AI Answer:")
160
- response = answer_question(user_query)
161
- st.write(response)
162
-
163
- elif intent == "Recipe Search":
164
- retrieved_recipes = retrieve_recipes(user_query)
165
- if retrieved_recipes is not None and not retrieved_recipes.empty:
166
- st.session_state["retrieved_recipes"] = retrieved_recipes
167
- st.subheader("🍴 Found Recipes:")
168
- for index, recipe in retrieved_recipes.iterrows():
169
- st.markdown(f"### {recipe['title']}")
170
- st.write(f"**Ingredients:** {recipe['ingredients']}")
171
- st.write(f"**Instructions:** {recipe['instructions']}")
172
- display_image(recipe.get('img_src', ''), recipe['title'])
173
- else:
174
- st.warning("⚠️ No relevant recipes found.")
175
  else:
176
- st.warning("❌ Unable to classify the query.")
 
 
 
 
 
 
73
 
74
  llm_model = load_llm_model()
75
 
 
76
  def answer_question(query, context=""):
77
  greetings = ["hi", "hello", "hii", "hey", "greetings", "how are you", "what's up", "how's it going"]
78
 
 
105
 
106
  return answer
107
 
108
+ # --- 8. Few-Shot Classification Function ---
109
+ def classify_with_few_shot(query):
110
+ prompt = """
111
+ Classify the following query as one of three types:
112
+ 1. Greeting
113
+ 2. Recipe Search
114
+ 3. Non-Recipe Query
 
 
 
 
115
 
116
+ Example Queries:
117
+ - "Hi" -> Greeting
118
+ - "How do I make lasagna?" -> Recipe Search
119
+ - "What is the capital of France?" -> Non-Recipe Query
120
+
121
+ Query: "{query}"
122
+ Classification:
123
+ """
124
+
125
+ full_prompt = prompt.format(query=query)
126
+
127
+ # Use your existing LLM model (or another one) for the few-shot classification
128
+ response = llm_model(question=full_prompt, context="") # Adjust to how your model processes prompts
129
+
130
+ classification = response.get("answer", "").strip() # Assuming the model returns the classification directly
131
+
132
+ # Check the output and map it to a valid intent
133
+ if "Greeting" in classification:
134
+ return "Greeting"
135
+ elif "Recipe Search" in classification:
136
+ return "Recipe Search"
137
+ elif "Non-Recipe Query" in classification:
138
+ return "Non-Recipe Query"
139
+ else:
140
+ return "Unclassified"
141
+
142
  # --- 9. Display Image Function ---
143
  def display_image(image_url, recipe_name):
144
  try:
 
153
  placeholder_url = "https://via.placeholder.com/300?text=No+Image"
154
  st.image(placeholder_url, caption=recipe_name, use_container_width=True)
155
 
156
+ # --- 10. Streamlit UI ---
157
  st.title("🍽️ AI Recipe & Q&A Assistant")
158
 
159
  user_query = st.text_input("Enter your question or recipe search query:", "", key="main_query_input")
 
163
 
164
  if st.button("Ask AI"):
165
  if user_query:
166
+ # Classify query using few-shot prompting
167
+ intent = classify_with_few_shot(user_query) # Updated to use classify_with_few_shot()
168
+
169
+ if intent == "Greeting":
170
  st.subheader("πŸ€– AI Answer:")
171
+ st.write(answer_question(user_query))
172
+
173
+ elif intent == "Recipe Search":
174
+ retrieved_recipes = retrieve_recipes(user_query)
175
+ if retrieved_recipes is not None and not retrieved_recipes.empty:
176
+ st.session_state["retrieved_recipes"] = retrieved_recipes
177
+ st.subheader("🍴 Found Recipes:")
178
+ for index, recipe in retrieved_recipes.iterrows():
179
+ st.markdown(f"### {recipe['title']}")
180
+ st.write(f"**Ingredients:** {recipe['ingredients']}")
181
+ st.write(f"**Instructions:** {recipe['instructions']}")
182
+ display_image(recipe.get('img_src', ''), recipe['title'])
 
 
 
 
 
 
 
 
 
 
183
  else:
184
+ st.warning("⚠️ No relevant recipes found.")
185
+ elif intent == "Non-Recipe Query":
186
+ st.subheader("πŸ€– AI Answer:")
187
+ st.write("I'm specialized in recipes! Feel free to ask me anything food-related. 😊")
188
+ else:
189
+ st.warning("❌ Unable to classify the query.")