ParthBhuptani commited on
Commit
1280140
·
verified ·
1 Parent(s): 3bb9502

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -42
app.py CHANGED
@@ -1,60 +1,94 @@
1
- import os
2
  import gradio as gr
3
  import requests
 
 
4
 
5
- # Nebius environment variables from Hugging Face secrets
6
- FOLDER_ID = os.environ.get("FOLDER_ID")
7
- NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
 
8
 
9
- # Function to call Nebius API
10
- def call_nebius(prompt):
11
- url = "https://llm.api.cloud.yandex.net/foundationModels/v1/completion"
12
-
13
  headers = {
14
  "Authorization": f"Bearer {NEBIUS_API_KEY}",
15
  "Content-Type": "application/json"
16
  }
17
-
18
- data = {
19
  "modelUri": f"gpt://{FOLDER_ID}/yandexgpt/latest",
20
- "completionOptions": {
21
- "stream": False,
22
- "temperature": 0.7,
23
- "maxTokens": 500
24
- },
25
- "messages": [
26
- {"role": "system", "text": "You are a smart kitchen agent. Suggest healthy and delicious recipes."},
27
- {"role": "user", "text": prompt}
28
- ]
29
  }
30
 
31
- response = requests.post(url, headers=headers, json=data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- try:
34
- result = response.json()
35
- return result["result"]["alternatives"][0]["message"]["text"]
36
- except Exception as e:
37
- return f"❌ Error: {e}\n\nResponse: {response.text}"
38
-
39
- # Gradio UI logic
40
- def generate_recipe(ingredients, preference):
41
- if not ingredients:
42
- return "⚠️ Please enter some ingredients."
43
- prompt = f"Give me a recipe using the following ingredients: {ingredients}. Make it {preference.lower()} and healthy."
44
- return call_nebius(prompt)
45
-
46
- # UI layout
47
- with gr.Blocks(theme=gr.themes.Base()) as demo:
48
- gr.Markdown("👨‍🍳 **AgentChef: AI Recipe Planner & Smart Kitchen Assistant**")
49
 
50
  with gr.Row():
51
- ingredients_input = gr.Textbox(label="🛒 Ingredients (comma-separated)", placeholder="e.g. tomato, onion, rice")
52
- preference_input = gr.Dropdown(label="🥗 Dietary Preferences", choices=["Vegetarian", "Vegan", "Keto", "No Preference"], value="Vegetarian")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- submit_btn = gr.Button("🍽️ Generate Recipe")
55
- output = gr.Textbox(label="📋 Recipe Result", lines=10)
 
56
 
57
- submit_btn.click(generate_recipe, inputs=[ingredients_input, preference_input], outputs=output)
 
 
58
 
59
- # Launch
60
  demo.launch()
 
 
1
  import gradio as gr
2
  import requests
3
+ import json
4
+ import datetime
5
 
6
+ # Load credentials from secrets
7
+ import os
8
+ NEBIUS_API_KEY = os.getenv("NEBIUS_API_KEY")
9
+ FOLDER_ID = os.getenv("FOLDER_ID")
10
 
11
+ # === Nebius API Function ===
12
+ def ask_nebius(prompt):
 
 
13
  headers = {
14
  "Authorization": f"Bearer {NEBIUS_API_KEY}",
15
  "Content-Type": "application/json"
16
  }
17
+ body = {
 
18
  "modelUri": f"gpt://{FOLDER_ID}/yandexgpt/latest",
19
+ "completionOptions": {"stream": False, "temperature": 0.5, "maxTokens": 1000},
20
+ "messages": [{"role": "user", "text": prompt}]
 
 
 
 
 
 
 
21
  }
22
 
23
+ res = requests.post("https://llm.api.cloud.yandex.net/foundationModels/v1/completion", headers=headers, json=body)
24
+ if res.status_code == 200:
25
+ return res.json()['result']['alternatives'][0]['message']['text']
26
+ else:
27
+ return f"Error: {res.status_code} - {res.text}"
28
+
29
+ # === Recipe Planner Function ===
30
+ def generate_recipe(diet, pantry):
31
+ prompt = f"You are a smart kitchen assistant. Suggest a detailed recipe for a {diet} user with ingredients from the pantry: {pantry}. Include cooking steps and nutritional info."
32
+ return ask_nebius(prompt)
33
+
34
+ # === Weekly Meal Planner Function ===
35
+ def weekly_meal_plan(diet):
36
+ prompt = f"Generate a full 7-day meal plan (Breakfast, Lunch, Dinner) for a {diet} diet. Include variety and healthy options."
37
+ return ask_nebius(prompt)
38
+
39
+ # === PDF Download ===
40
+ def download_text_as_pdf(text):
41
+ from fpdf import FPDF
42
+ pdf = FPDF()
43
+ pdf.add_page()
44
+ pdf.set_font("Arial", size=12)
45
+ for line in text.split('\n'):
46
+ pdf.cell(200, 10, txt=line, ln=True)
47
+ filename = f"meal_plan_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.pdf"
48
+ pdf.output(filename)
49
+ return filename
50
+
51
+ # === Gradio Interface ===
52
+ with gr.Blocks(theme=gr.themes.Base(), title="AgentChef") as demo:
53
+ gr.Markdown("""
54
+ ## 🍳 AgentChef: AI Recipe Planner & Smart Kitchen Assistant
55
 
56
+ Plan meals, check pantry items, generate weekly diet charts, and download PDFs — all with AI!
57
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  with gr.Row():
60
+ diet_input = gr.Dropdown(label="🍽️ Dietary Preferences", choices=["Vegetarian", "Vegan", "Keto", "Paleo", "Regular"], value="Vegetarian")
61
+ pantry_input = gr.Textbox(label="🌾 Pantry Items (comma-separated)", placeholder="e.g. tomato, rice, beans")
62
+
63
+ with gr.Row():
64
+ mic = gr.Audio(type="filepath", label="🎤 Speak Ingredients (Optional)")
65
+ transcript_output = gr.Textbox(label="Speech-to-text Result")
66
+
67
+ with gr.Row():
68
+ generate_button = gr.Button("🍽 Generate Recipe")
69
+ meal_button = gr.Button("🍒 Weekly Meal Plan")
70
+
71
+ result = gr.Textbox(label="🌱 Output")
72
+ pdf_button = gr.Button("📄 Download as PDF")
73
+ file_output = gr.File(label="Download Link")
74
+
75
+ # === Callbacks ===
76
+ def transcribe_audio(audio_file):
77
+ import speech_recognition as sr
78
+ recognizer = sr.Recognizer()
79
+ with sr.AudioFile(audio_file) as source:
80
+ audio_data = recognizer.record(source)
81
+ return recognizer.recognize_google(audio_data)
82
+
83
+ mic.change(transcribe_audio, inputs=mic, outputs=transcript_output)
84
 
85
+ def handle_generate(diet, pantry, spoken):
86
+ pantry_all = (spoken or '') + ", " + (pantry or '')
87
+ return generate_recipe(diet, pantry_all)
88
 
89
+ generate_button.click(handle_generate, inputs=[diet_input, pantry_input, transcript_output], outputs=result)
90
+ meal_button.click(weekly_meal_plan, inputs=diet_input, outputs=result)
91
+ pdf_button.click(download_text_as_pdf, inputs=result, outputs=file_output)
92
 
93
+ # === Launch ===
94
  demo.launch()