ParthBhuptani commited on
Commit
27c3f18
·
verified ·
1 Parent(s): 2c46f85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -47
app.py CHANGED
@@ -1,60 +1,149 @@
1
  import gradio as gr
2
- import arxiv
3
- from transformers import pipeline
 
 
 
 
 
4
 
5
- # Load summarization model
6
- summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
 
7
 
8
- # Search and summarize papers
9
- def search_and_summarize(topic, sort_by_option):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  try:
11
- num_papers = 3 # fixed value
12
- sort_mapping = {
13
- "Relevance": arxiv.SortCriterion.Relevance,
14
- "Most Recent": arxiv.SortCriterion.SubmittedDate
15
- }
16
-
17
- search = arxiv.Search(
18
- query=topic,
19
- max_results=num_papers,
20
- sort_by=sort_mapping.get(sort_by_option, arxiv.SortCriterion.Relevance)
21
- )
22
-
23
- results = []
24
- for result in search.results():
25
- summary = summarizer(result.summary[:1000], max_length=120, min_length=30, do_sample=False)[0]['summary_text']
26
- authors = ", ".join([author.name for author in result.authors])
27
- published_date = result.published.date().strftime("%Y-%m-%d")
28
- result_block = (
29
- f"📘 *{result.title}*\n\n"
30
- f"👩‍🔬 Authors: {authors}\n"
31
- f"📅 Published: {published_date}\n\n"
32
- f"📝 Summary: {summary}\n\n"
33
- f"🔗 [Read More]({result.pdf_url})"
34
- )
35
- results.append(result_block)
36
-
37
- return "\n\n---\n\n".join(results) if results else "No results found."
38
-
39
  except Exception as e:
40
- return f"⚠️ An error occurred: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Gradio UI
43
- with gr.Blocks(theme=gr.themes.Base()) as demo:
44
- gr.Markdown("# 🤖 AI Research Assistant\nSummarize academic research papers using Hugging Face models + Arxiv!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  with gr.Row():
47
- topic = gr.Textbox(label="🔍 Enter your research topic", placeholder="e.g. diffusion models in AI")
48
- sort_by = gr.Dropdown(choices=["Relevance", "Most Recent"], value="Relevance", label="Sort by")
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- search_btn = gr.Button("Search 🔎")
51
- output = gr.Markdown()
 
 
52
 
53
- # Show loading message
54
- def show_loading():
55
- return "⏳ Loading, please wait..."
56
 
57
- search_btn.click(fn=show_loading, inputs=[], outputs=output, queue=False)
58
- search_btn.click(fn=search_and_summarize, inputs=[topic, sort_by], outputs=output)
59
 
60
  demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
+ from fpdf import FPDF
5
+ import uuid
6
+ import re
7
+ import matplotlib.pyplot as plt
8
+ import tempfile
9
 
10
+ # Load your Nebius API key and Folder ID from environment variables
11
+ NEBIUS_API_KEY = os.getenv("NEBIUS_API_KEY") or "YOUR_NEBIUS_API_KEY"
12
+ FOLDER_ID = os.getenv("FOLDER_ID") or "YOUR_FOLDER_ID"
13
 
14
+ def generate_meal(preferences, ingredients, time):
15
+ prompt = f"""
16
+ You're a smart kitchen agent.
17
+ Given:
18
+ - Dietary preferences: {preferences}
19
+ - Ingredients available: {ingredients}
20
+ - Time available: {time} minutes
21
+ Tasks:
22
+ 1. Suggest one meal idea
23
+ 2. Provide step-by-step recipe instructions
24
+ 3. List missing ingredients (Shopping List)
25
+ 4. Estimate nutrition (calories, protein, carbs, fat)
26
+ Output in this format:
27
+ Meal Name: ...
28
+ Steps:
29
+ 1. ...
30
+ 2. ...
31
+ Shopping List:
32
+ - ...
33
+ Nutrition:
34
+ - Calories: ... kcal
35
+ - Protein: ... g
36
+ - Carbs: ... g
37
+ - Fat: ... g
38
+ """
39
+ headers = {
40
+ "Authorization": f"Api-Key {NEBIUS_API_KEY}",
41
+ "Content-Type": "application/json"
42
+ }
43
+ data = {
44
+ "modelUri": f"gpt://{FOLDER_ID}/yandexgpt-lite",
45
+ "completionOptions": {"stream": False, "temperature": 0.7, "maxTokens": 700},
46
+ "messages": [{"role": "user", "text": prompt.strip()}]
47
+ }
48
+ response = requests.post(
49
+ "https://llm.api.cloud.yandex.net/foundationModels/v1/completion",
50
+ headers=headers, json=data
51
+ )
52
  try:
53
+ text = response.json()["result"]["alternatives"][0]["message"]["text"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  except Exception as e:
55
+ return f" Error: Could not fetch recipe. {e}"
56
+ return text
57
+
58
+ def extract_nutrition(recipe_text):
59
+ # More robust pattern allowing newlines and flexible spacing
60
+ pattern = (
61
+ r"Calories:\s*([\d\.]+)\s*kcal.*?"
62
+ r"Protein:\s*([\d\.]+)\s*g.*?"
63
+ r"Carbs:\s*([\d\.]+)\s*g.*?"
64
+ r"Fat:\s*([\d\.]+)\s*g"
65
+ )
66
+ match = re.search(pattern, recipe_text.replace("\n", " "))
67
+ if match:
68
+ calories, protein, carbs, fat = map(float, match.groups())
69
+ return {"Calories": calories, "Protein": protein, "Carbs": carbs, "Fat": fat}
70
+ return None
71
+
72
+ def plot_nutrition_chart(nutrition):
73
+ fig, ax = plt.subplots()
74
+ nutrients = list(nutrition.keys())
75
+ values = list(nutrition.values())
76
+ colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
77
+ ax.pie(values, labels=nutrients, autopct='%1.1f%%', startangle=140, colors=colors)
78
+ ax.axis('equal')
79
+ plt.tight_layout()
80
+
81
+ temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
82
+ plt.savefig(temp_file.name)
83
+ plt.close(fig)
84
+ return temp_file.name
85
 
86
+ def handle_generate(preferences, ingredients, time):
87
+ recipe = generate_meal(preferences, ingredients, time)
88
+ nutrition = extract_nutrition(recipe)
89
+ chart_path = None
90
+ if nutrition:
91
+ chart_path = plot_nutrition_chart(nutrition)
92
+ return recipe, chart_path
93
+
94
+ def save_pdf(recipe_text):
95
+ pdf = FPDF()
96
+ pdf.add_page()
97
+ pdf.set_font("Arial", size=12)
98
+ for line in recipe_text.split('\n'):
99
+ pdf.multi_cell(0, 10, line)
100
+ temp_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
101
+ pdf.output(temp_file.name)
102
+ return temp_file.name
103
+
104
+ # Optional: placeholder function for speech-to-text (you can replace with real STT)
105
+ def dummy_speech_to_text(audio):
106
+ # This just returns a fixed string for demo. Replace with actual STT model call if you want.
107
+ if audio is None:
108
+ return ""
109
+ return "tomato, onion, garlic"
110
+
111
+ with gr.Blocks(css="""
112
+ body { background-color: #111; color: #eee; font-family: 'Segoe UI', sans-serif; }
113
+ .gradio-container { max-width: 900px; margin: auto; }
114
+ .input-label { font-weight: 600; margin-bottom: 5px; }
115
+ .footer { font-size: 0.8rem; color: #666; padding: 10px; text-align: center; }
116
+ @media (max-width: 600px) {
117
+ .gradio-container { padding: 10px; }
118
+ }
119
+ """) as demo:
120
+ gr.Markdown("# 👨‍🍳 AgentChef: AI Recipe Planner & Smart Kitchen Assistant")
121
 
122
  with gr.Row():
123
+ with gr.Column(scale=1, min_width=200):
124
+ preferences = gr.Textbox(label="🥗 Dietary Preferences", placeholder="e.g. vegetarian, keto")
125
+ ingredients = gr.Textbox(label="🧂 Ingredients You Have", placeholder="e.g. rice, tomato, onion", lines=3)
126
+
127
+ mic = gr.Audio(source="microphone", type="filepath", label="🎤 Speak Ingredients")
128
+ transcribed = gr.Textbox(label="📝 Transcribed Ingredients (from mic)", interactive=False)
129
+
130
+ mic.change(dummy_speech_to_text, inputs=mic, outputs=transcribed)
131
+ # Add a button to copy transcribed text to ingredients textbox if needed
132
+ copy_btn = gr.Button("Copy Transcription to Ingredients")
133
+ copy_btn.click(lambda txt: txt, inputs=transcribed, outputs=ingredients)
134
+
135
+ time = gr.Slider(5, 60, value=20, step=5, label="⏱️ Time Available (minutes)")
136
+ generate_btn = gr.Button("🍽️ Generate Recipe")
137
 
138
+ with gr.Column(scale=1, min_width=300):
139
+ recipe_output = gr.Textbox(label="📝 Recipe Output", lines=15, interactive=False)
140
+ nutrition_chart = gr.Image(label="📊 Nutrition Breakdown", interactive=False)
141
+ pdf_btn = gr.Button("📄 Export as PDF")
142
 
143
+ generate_btn.click(handle_generate,
144
+ inputs=[preferences, ingredients, time],
145
+ outputs=[recipe_output, nutrition_chart])
146
 
147
+ pdf_btn.click(save_pdf, inputs=[recipe_output], outputs=gr.File(label="📥 Download Recipe PDF"))
 
148
 
149
  demo.launch()