Beable commited on
Commit
7aa591f
·
verified ·
1 Parent(s): 56aa65a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +598 -248
app.py CHANGED
@@ -1,191 +1,250 @@
1
- """
2
- RAG Diet Planning Application for Hugging Face Spaces
3
- This application provides AI-powered diet planning with nutrition analysis.
4
- """
5
-
6
  import gradio as gr
7
  import json
8
  import os
9
- import glob
10
  import re
 
11
  from typing import Dict, List, Any
12
  from main3 import run_rag_tool_router, execute_diet_tool
13
  from diet_tool import generate_diet_plan, get_diet_recommendations, calculate_nutrition_info
14
 
 
 
 
 
 
 
15
  def format_json_to_table(json_data: Any, title: str = "") -> str:
16
- """Convert JSON data to markdown table format"""
17
  if not json_data:
18
- return "No data available"
19
 
20
- if isinstance(json_data, dict):
21
- return format_dict_to_table(json_data, title)
22
- elif isinstance(json_data, list):
23
- return format_list_to_table(json_data, title)
24
- else:
25
- return f"**{title}**\n\n{str(json_data)}"
 
 
 
 
 
 
26
 
27
  def format_dict_to_table(data: dict, title: str = "") -> str:
28
- """Format dictionary as markdown table"""
29
  if not data:
30
- return f"**{title}**\n\nNo data available"
31
 
32
- formatted = f"**{title}**\n\n" if title else ""
33
 
34
  # Check if it's a simple key-value dict
35
  if all(not isinstance(v, (dict, list)) for v in data.values()):
36
- formatted += "| Key | Value |\n|-----|-------|\n"
 
37
  for key, value in data.items():
38
- formatted += f"| {key} | {value} |\n"
39
  else:
40
  # Complex nested structure
41
  for key, value in data.items():
42
- if isinstance(value, (dict, list)):
43
- formatted += f"\n### {key}\n"
44
- formatted += format_json_to_table(value)
 
 
 
45
  else:
46
- formatted += f"**{key}**: {value}\n"
47
 
48
- return formatted
49
 
50
  def format_list_to_table(data: list, title: str = "") -> str:
51
- """Format list as markdown table"""
52
  if not data:
53
- return f"**{title}**\n\nNo data available"
54
 
55
- formatted = f"**{title}**\n\n" if title else ""
56
 
57
- if isinstance(data[0], dict):
58
- # List of dictionaries - create table
59
- keys = list(data[0].keys())
60
- formatted += "| " + " | ".join(keys) + " |\n"
61
- formatted += "|" + "|".join(["-----"] * len(keys)) + "|\n"
62
-
 
63
  for item in data:
64
- row = []
65
- for key in keys:
66
- value = item.get(key, "")
67
- if isinstance(value, (dict, list)):
68
- value = str(value)[:50] + "..." if len(str(value)) > 50 else str(value)
69
- row.append(str(value))
70
- formatted += "| " + " | ".join(row) + " |\n"
 
 
 
 
 
 
 
 
 
 
 
71
  else:
72
  # Simple list
73
- formatted += "| Item |\n|------|\n"
74
- for item in data:
75
- formatted += f"| {item} |\n"
76
 
77
- return formatted
78
 
79
  def format_diet_plan_result(result: dict) -> str:
80
  """Format diet plan result specifically"""
81
- if not result:
82
- return "No diet plan data available"
83
 
84
- formatted = "# 🍽️ Diet Plan Results\n\n"
85
 
86
- # Weekly summary
87
- if "weekly_summary" in result:
88
- summary = result["weekly_summary"]
89
- formatted += "## 📊 Weekly Summary\n\n"
90
- formatted += "| Day | Calories | Protein | Carbs | Fat | Fiber |\n"
91
- formatted += "|-----|----------|---------|-------|-----|-------|\n"
92
-
93
- for day, data in summary.items():
94
- formatted += f"| {day} | {data.get('calories', 0)} | {data.get('protein', 0)}g | {data.get('carbs', 0)}g | {data.get('fat', 0)}g | {data.get('fiber', 0)}g |\n"
95
 
96
- # Detailed meals for all 7 days
97
- if "plans" in result:
98
- formatted += "\n## 🍽️ Detailed Meals (All 7 Days)\n\n"
99
 
100
- for i, plan in enumerate(result["plans"]):
101
- date = plan.get("date", f"Day {i+1}")
102
- formatted += f"### Day {i+1} - {date}\n\n"
103
-
104
- meals = plan.get("meals", [])
105
- for meal in meals:
106
- meal_name = meal.get("meal_name", "Meal")
107
- time_range = meal.get("time_range", "")
108
- nutrition = meal.get("nutrition", {})
 
 
 
 
 
 
 
 
109
 
110
- formatted += f"**{meal_name}** ({time_range})\n"
111
- formatted += f"- Calories: {nutrition.get('calories', 0)} | Protein: {nutrition.get('protein', 0)}g | Carbs: {nutrition.get('carbs', 0)}g | Fat: {nutrition.get('fat', 0)}g\n"
 
 
 
 
 
 
112
 
113
  # Foods
114
- foods = meal.get("foods", [])
115
- if foods:
116
- formatted += " - Foods: "
117
- food_names = [food.get("name", "Unknown") for food in foods[:3]]
118
- formatted += ", ".join(food_names)
119
- if len(foods) > 3:
120
- formatted += f" +{len(foods)-3} more"
121
  formatted += "\n"
122
- formatted += "\n"
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  return formatted
125
 
126
  def format_recommendations_result(result: dict) -> str:
127
- """Format diet recommendations result"""
128
- if not result:
129
- return "No recommendations data available"
130
 
131
- formatted = "# 🎯 Diet Recommendations\n\n"
132
 
133
- # BMR and TDEE
134
  if "bmr" in result:
135
- formatted += f"**BMR (Basal Metabolic Rate)**: {result['bmr']:.0f} calories/day\n"
136
  if "tdee" in result:
137
- formatted += f"**TDEE (Total Daily Energy Expenditure)**: {result['tdee']:.0f} calories/day\n"
138
  if "target_calories" in result:
139
- formatted += f"**Target Calories**: {result['target_calories']:.0f} calories/day\n\n"
140
-
141
- # Macro distribution
142
- if "macro_distribution" in result:
143
- macros = result["macro_distribution"]
144
- formatted += "## 📊 Macro Distribution\n\n"
145
- formatted += "| Nutrient | Grams | Calories | Percentage |\n"
146
- formatted += "|----------|-------|----------|------------|\n"
147
-
148
- for macro, data in macros.items():
149
- formatted += f"| {macro.title()} | {data.get('grams', 0):.1f}g | {data.get('calories', 0):.0f} | {data.get('percentage', 0):.1f}% |\n"
 
 
 
 
 
 
 
 
 
 
150
 
151
  # Recommendations
152
  if "recommendations" in result:
153
- formatted += "\n## 💡 Recommendations\n\n"
154
- for i, rec in enumerate(result["recommendations"], 1):
155
- formatted += f"{i}. {rec}\n"
 
156
 
157
  return formatted
158
 
159
  def format_nutrition_result(result: dict) -> str:
160
- """Format nutrition calculation result"""
161
- if not result:
162
- return "No nutrition data available"
163
-
164
- formatted = "# 🥗 Nutrition Information\n\n"
165
-
166
- # Main nutrition table
167
- if "nutrition" in result:
168
- nutrition = result["nutrition"]
169
- formatted += "## 📊 Nutrition Facts\n\n"
170
- formatted += "| Nutrient | Amount | Unit |\n"
171
- formatted += "|----------|--------|------|\n"
172
-
173
- for nutrient, data in nutrition.items():
174
- if isinstance(data, dict) and "amount" in data:
175
- formatted += f"| {nutrient.title()} | {data['amount']} | {data.get('unit', '')} |\n"
176
- else:
177
- formatted += f"| {nutrient.title()} | {data} | |\n"
 
 
 
178
 
179
  # Vitamins and minerals
180
- if "vitamins" in result:
181
- formatted += "\n## 🧪 Vitamins\n\n"
182
- for vitamin, amount in result["vitamins"].items():
183
- formatted += f"- **{vitamin}**: {amount}\n"
 
 
 
184
 
185
- if "minerals" in result:
186
- formatted += "\n## ⚡ Minerals\n\n"
187
- for mineral, amount in result["minerals"].items():
188
- formatted += f"- **{mineral}**: {amount}\n"
 
 
 
189
 
190
  return formatted
191
 
@@ -213,19 +272,122 @@ def load_latest_json_output() -> str:
213
  # Format based on file type
214
  if "diet_plan" in filename:
215
  if "weekly" in filename:
216
- return format_diet_plan_result(data)
217
  else:
218
- return format_nutrition_result(data)
219
  elif "recommendations" in filename:
220
- return format_recommendations_result(data)
 
 
221
  else:
222
- return format_json_to_table(data, f"📄 {filename}")
223
-
224
  except Exception as e:
225
- return f"❌ Error loading file: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
- def list_all_outputs() -> str:
228
- """List all JSON output files"""
229
  outputs_dir = "outputs"
230
  if not os.path.exists(outputs_dir):
231
  return "❌ No outputs directory found"
@@ -234,26 +396,31 @@ def list_all_outputs() -> str:
234
  if not json_files:
235
  return "❌ No JSON files found in outputs directory"
236
 
237
- formatted = "# 📁 All Output Files\n\n"
238
- formatted += "| File | Size | Modified | Type |\n"
239
- formatted += "|------|------|----------|------|\n"
 
 
 
240
 
241
- for file_path in sorted(json_files, key=os.path.getmtime, reverse=True):
242
  filename = os.path.basename(file_path)
243
- size = os.path.getsize(file_path)
244
- modified = os.path.getmtime(file_path)
245
 
246
- # Determine file type
247
  if "diet_plan_weekly" in filename:
248
- file_type = "📅 Weekly Diet Plan"
249
  elif "diet_plan_daily" in filename:
250
- file_type = "📅 Daily Diet Plan"
251
  elif "recommendations" in filename:
252
- file_type = "💡 Recommendations"
253
- else:
254
- file_type = "📄 Other"
 
 
 
 
255
 
256
- formatted += f"| {filename} | {size:,} bytes | {modified} | {file_type} |\n"
257
 
258
  return formatted
259
 
@@ -261,13 +428,13 @@ def extract_and_format_json_in_text(text: str) -> str:
261
  """Extract JSON objects from text and format them as tables"""
262
  if not text:
263
  return text
264
-
265
  formatted_text = text
266
-
267
  # First, try to find JSON in code blocks
268
  code_block_pattern = r'```(?:json)?\s*(\{.*?\})\s*```'
269
  matches = list(re.finditer(code_block_pattern, formatted_text, re.DOTALL | re.IGNORECASE))
270
-
271
  for match in reversed(matches):
272
  json_str = match.group(1).strip()
273
  try:
@@ -276,18 +443,19 @@ def extract_and_format_json_in_text(text: str) -> str:
276
  formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
277
  except:
278
  continue
279
-
280
  # Then, try to find standalone JSON objects
 
281
  json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
282
  matches = list(re.finditer(json_pattern, formatted_text, re.DOTALL))
283
-
284
  for match in reversed(matches):
285
  json_str = match.group(0).strip()
286
-
287
  # Skip if it's already been processed or is too short
288
  if len(json_str) < 10 or '|' in json_str:
289
  continue
290
-
291
  try:
292
  json_data = json.loads(json_str)
293
  # Only format if it looks like structured data
@@ -296,132 +464,314 @@ def extract_and_format_json_in_text(text: str) -> str:
296
  formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
297
  except:
298
  continue
299
-
300
  return formatted_text
301
 
302
  def format_json_data_to_table(json_data: Any) -> str:
303
- """Helper function to format JSON data as table"""
304
  if isinstance(json_data, dict):
305
- if "action" in json_data:
306
- # Tool action response
307
- action = json_data["action"]
308
- args = json_data.get("args", {})
309
- return f"**🔧 Tool Action**: {action}\n\n**Arguments**:\n{format_dict_to_table(args)}"
310
- elif "final" in json_data:
311
- # Final response
312
- return f"**💬 Response**: {json_data['final']}"
313
- else:
314
- return format_dict_to_table(json_data)
315
  elif isinstance(json_data, list):
316
- return format_list_to_table(json_data)
317
  else:
318
  return str(json_data)
319
 
320
  def process_user_input(user_input: str, history: List) -> tuple:
321
- """Process user input and return response"""
 
 
322
  if not user_input.strip():
323
  return history, ""
324
 
325
- try:
326
- # Convert Gradio history format to RAG format
327
- rag_history = []
328
- for msg in history:
329
- if isinstance(msg, dict):
330
- rag_history.append({
331
- "role": msg.get("role", "user"),
332
- "content": msg.get("content", "")
333
- })
334
- else:
335
- # Handle tuple format
336
- rag_history.append({
337
- "role": "user" if len(msg) == 1 else msg[0],
338
- "content": msg[1] if len(msg) > 1 else msg[0]
339
- })
340
-
341
- # Get response from RAG system
342
- result = run_rag_tool_router(user_input, rag_history)
343
-
344
- # Format the response
345
- if result.get("action"):
346
- action_response = f"🔧 **Tool Used**: {result['action']}\n\n"
347
- if result.get("args"):
348
- action_response += f"**Arguments**:\n{format_dict_to_table(result['args'])}\n\n"
349
- if result.get("result"):
350
- action_response += f"**Result**:\n{result['result']}"
351
- final_response = action_response
352
  else:
353
- final_response = result.get("final", "No response generated")
354
-
 
 
 
 
 
 
 
 
 
 
 
 
355
  # Format any JSON in the response
356
- formatted_response = extract_and_format_json_in_text(final_response)
357
-
358
- # Update history
359
  history.append({"role": "user", "content": user_input})
360
  history.append({"role": "assistant", "content": formatted_response})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
  return history, ""
363
 
364
- except Exception as e:
365
- error_msg = f"❌ Error: {str(e)}"
 
 
366
  history.append({"role": "user", "content": user_input})
367
- history.append({"role": "assistant", "content": error_msg})
368
  return history, ""
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  # Create Gradio interface
371
- def create_interface():
372
- with gr.Blocks(title="🍽️ AI Diet Planner", theme=gr.themes.Soft()) as app:
373
- gr.Markdown("# 🍽️ AI Diet Planner & Nutrition Assistant")
374
- gr.Markdown("Ask me to create personalized diet plans, calculate nutrition information, or get dietary recommendations!")
375
-
376
- # Chat interface
377
- chatbot = gr.Chatbot(
378
- label="Conversation",
379
- height=500,
380
- type="messages",
381
- render_markdown=True
382
- )
383
-
384
- # Input area
385
- with gr.Row():
386
- msg = gr.Textbox(
387
- label="Your message",
388
- placeholder="Ask me to create a diet plan, calculate nutrition, or get recommendations...",
389
- lines=2,
390
- scale=4
391
  )
392
- send_btn = gr.Button("Send", variant="primary", scale=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
 
394
- # Action buttons
395
- with gr.Row():
396
- clear_btn = gr.Button("Clear Chat", variant="secondary")
397
- load_latest_btn = gr.Button("📄 Load Latest JSON", variant="secondary")
398
- list_outputs_btn = gr.Button("📁 List All Outputs", variant="secondary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
- # Event handlers
401
- msg.submit(process_user_input, [msg, chatbot], [chatbot, msg])
402
- send_btn.click(process_user_input, [msg, chatbot], [chatbot, msg])
403
- clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
404
- load_latest_btn.click(load_latest_json_output, outputs=chatbot)
405
- list_outputs_btn.click(list_all_outputs, outputs=chatbot)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
- # Examples
408
- gr.Examples(
409
- examples=[
410
- "Create a weekly diet plan for a 25-year-old male, 70kg, 175cm, moderate activity",
411
- "Calculate nutrition for 200g chicken breast and 150g rice",
412
- "Get diet recommendations for weight loss",
413
- "Create a vegetarian meal plan for 7 days"
414
- ],
415
- inputs=msg
416
- )
417
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  return app
419
 
420
- # Create and launch the app
421
  if __name__ == "__main__":
422
- app = create_interface()
423
  app.launch(
424
- server_name="0.0.0.0",
425
  server_port=7860,
426
  share=False
427
  )
 
 
 
 
 
 
1
  import gradio as gr
2
  import json
3
  import os
4
+ import pandas as pd
5
  import re
6
+ import glob
7
  from typing import Dict, List, Any
8
  from main3 import run_rag_tool_router, execute_diet_tool
9
  from diet_tool import generate_diet_plan, get_diet_recommendations, calculate_nutrition_info
10
 
11
+ # Ensure outputs directory exists
12
+ os.makedirs("outputs", exist_ok=True)
13
+
14
+ # Global chat history
15
+ chat_history = []
16
+
17
  def format_json_to_table(json_data: Any, title: str = "") -> str:
18
+ """Convert JSON data to a formatted table string"""
19
  if not json_data:
20
+ return ""
21
 
22
+ try:
23
+ if isinstance(json_data, str):
24
+ json_data = json.loads(json_data)
25
+
26
+ if isinstance(json_data, dict):
27
+ return format_dict_to_table(json_data, title)
28
+ elif isinstance(json_data, list):
29
+ return format_list_to_table(json_data, title)
30
+ else:
31
+ return str(json_data)
32
+ except:
33
+ return str(json_data)
34
 
35
  def format_dict_to_table(data: dict, title: str = "") -> str:
36
+ """Format dictionary as a table"""
37
  if not data:
38
+ return ""
39
 
40
+ result = f"## {title}\n\n" if title else ""
41
 
42
  # Check if it's a simple key-value dict
43
  if all(not isinstance(v, (dict, list)) for v in data.values()):
44
+ result += "| Key | Value |\n"
45
+ result += "|-----|-------|\n"
46
  for key, value in data.items():
47
+ result += f"| **{key}** | {value} |\n"
48
  else:
49
  # Complex nested structure
50
  for key, value in data.items():
51
+ if isinstance(value, dict):
52
+ result += f"### {key}\n"
53
+ result += format_dict_to_table(value)
54
+ elif isinstance(value, list):
55
+ result += f"### {key}\n"
56
+ result += format_list_to_table(value)
57
  else:
58
+ result += f"**{key}**: {value}\n"
59
 
60
+ return result
61
 
62
  def format_list_to_table(data: list, title: str = "") -> str:
63
+ """Format list as a table"""
64
  if not data:
65
+ return ""
66
 
67
+ result = f"## {title}\n\n" if title else ""
68
 
69
+ if not data:
70
+ return result
71
+
72
+ # Check if all items are dictionaries with similar keys
73
+ if all(isinstance(item, dict) for item in data):
74
+ # Get all unique keys
75
+ all_keys = set()
76
  for item in data:
77
+ all_keys.update(item.keys())
78
+
79
+ if all_keys:
80
+ # Create table header
81
+ result += "| " + " | ".join(all_keys) + " |\n"
82
+ result += "|" + "|".join(["---"] * len(all_keys)) + "|\n"
83
+
84
+ # Add rows
85
+ for item in data:
86
+ row = []
87
+ for key in all_keys:
88
+ value = item.get(key, "")
89
+ if isinstance(value, (dict, list)):
90
+ value = json.dumps(value, ensure_ascii=False)[:50] + "..."
91
+ row.append(str(value))
92
+ result += "| " + " | ".join(row) + " |\n"
93
+ else:
94
+ result += "Empty list\n"
95
  else:
96
  # Simple list
97
+ for i, item in enumerate(data):
98
+ result += f"{i+1}. {item}\n"
 
99
 
100
+ return result
101
 
102
  def format_diet_plan_result(result: dict) -> str:
103
  """Format diet plan result specifically"""
104
+ if not result or "error" in result:
105
+ return f" Error: {result.get('error', 'Unknown error')}"
106
 
107
+ formatted = "## 🍽️ Diet Plan\n\n"
108
 
109
+ if "plan_type" in result:
110
+ formatted += f"**Plan Type**: {result['plan_type']}\n\n"
 
 
 
 
 
 
 
111
 
112
+ if "plan" in result:
113
+ plan = result["plan"]
 
114
 
115
+ # Daily totals
116
+ if "daily_totals" in plan:
117
+ totals = plan["daily_totals"]
118
+ formatted += "### 📊 Daily Nutrition Summary\n\n"
119
+ formatted += "| Nutrient | Amount |\n"
120
+ formatted += "|----------|--------|\n"
121
+ formatted += f"| **Calories** | {totals.get('calories', 0)} kcal |\n"
122
+ formatted += f"| **Protein** | {totals.get('protein', 0)} g |\n"
123
+ formatted += f"| **Carbs** | {totals.get('carbs', 0)} g |\n"
124
+ formatted += f"| **Fat** | {totals.get('fat', 0)} g |\n"
125
+ formatted += f"| **Fiber** | {totals.get('fiber', 0)} g |\n\n"
126
+
127
+ # Meals
128
+ if "meals" in plan:
129
+ formatted += "### 🍽️ Meals\n\n"
130
+ for meal in plan["meals"]:
131
+ formatted += f"#### {meal.get('meal_name', 'Meal')} ({meal.get('time_range', '')})\n\n"
132
 
133
+ # Meal nutrition
134
+ if "nutrition" in meal:
135
+ nutrition = meal["nutrition"]
136
+ formatted += "**Nutrition**: "
137
+ formatted += f"{nutrition.get('calories', 0)} kcal, "
138
+ formatted += f"{nutrition.get('protein', 0)}g protein, "
139
+ formatted += f"{nutrition.get('carbs', 0)}g carbs, "
140
+ formatted += f"{nutrition.get('fat', 0)}g fat\n\n"
141
 
142
  # Foods
143
+ if "foods" in meal:
144
+ formatted += "**Foods**:\n"
145
+ for food in meal["foods"]:
146
+ formatted += f"- **{food.get('name', 'Unknown')}** "
147
+ formatted += f"({food.get('portion_grams', 0)}g) - "
148
+ formatted += f"{food.get('calories', 0)} kcal\n"
 
149
  formatted += "\n"
150
+
151
+ elif "plans" in result:
152
+ # Weekly plan
153
+ plans = result["plans"]
154
+ formatted += f"### 📅 Weekly Plan ({len(plans)} days)\n\n"
155
+
156
+ for i, plan in enumerate(plans): # Show all days
157
+ formatted += f"#### Day {i+1} - {plan.get('date', '')}\n"
158
+ if "daily_totals" in plan:
159
+ totals = plan["daily_totals"]
160
+ formatted += f"**Total**: {totals.get('calories', 0)} kcal, "
161
+ formatted += f"{totals.get('protein', 0)}g protein\n\n"
162
 
163
  return formatted
164
 
165
  def format_recommendations_result(result: dict) -> str:
166
+ """Format recommendations result specifically"""
167
+ if not result or "error" in result:
168
+ return f" Error: {result.get('error', 'Unknown error')}"
169
 
170
+ formatted = "## �� Diet Recommendations\n\n"
171
 
172
+ # Basic metrics
173
  if "bmr" in result:
174
+ formatted += f"**BMR (Basal Metabolic Rate)**: {result['bmr']} kcal/day\n"
175
  if "tdee" in result:
176
+ formatted += f"**TDEE (Total Daily Energy Expenditure)**: {result['tdee']} kcal/day\n"
177
  if "target_calories" in result:
178
+ formatted += f"**Target Calories**: {result['target_calories']} kcal/day\n\n"
179
+
180
+ # Macro ratios
181
+ if "macro_ratios" in result:
182
+ ratios = result["macro_ratios"]
183
+ formatted += "### 🎯 Macro Ratios\n\n"
184
+ formatted += "| Macronutrient | Percentage |\n"
185
+ formatted += "|---------------|------------|\n"
186
+ for macro, ratio in ratios.items():
187
+ formatted += f"| **{macro.title()}** | {ratio} |\n"
188
+ formatted += "\n"
189
+
190
+ # Macro grams
191
+ if "macro_grams" in result:
192
+ grams = result["macro_grams"]
193
+ formatted += "### ⚖️ Daily Macro Targets (grams)\n\n"
194
+ formatted += "| Macronutrient | Grams |\n"
195
+ formatted += "|---------------|-------|\n"
196
+ for macro, grams_val in grams.items():
197
+ formatted += f"| **{macro.title()}** | {grams_val} g |\n"
198
+ formatted += "\n"
199
 
200
  # Recommendations
201
  if "recommendations" in result:
202
+ recs = result["recommendations"]
203
+ formatted += "### 💡 Recommendations\n\n"
204
+ for key, value in recs.items():
205
+ formatted += f"**{key.replace('_', ' ').title()}**: {value}\n"
206
 
207
  return formatted
208
 
209
  def format_nutrition_result(result: dict) -> str:
210
+ """Format nutrition calculation result specifically"""
211
+ if not result or "error" in result:
212
+ return f" Error: {result.get('error', 'Unknown error')}"
213
+
214
+ formatted = "## 🧮 Nutrition Information\n\n"
215
+
216
+ if "food_name" in result:
217
+ formatted += f"**Food**: {result['food_name']}\n"
218
+ if "portion_grams" in result:
219
+ formatted += f"**Portion**: {result['portion_grams']} grams\n\n"
220
+
221
+ # Basic nutrition
222
+ formatted += "### 📊 Nutritional Values\n\n"
223
+ formatted += "| Nutrient | Amount |\n"
224
+ formatted += "|----------|--------|\n"
225
+
226
+ nutrients = ["calories", "protein", "carbs", "fat", "fiber"]
227
+ for nutrient in nutrients:
228
+ if nutrient in result:
229
+ unit = "kcal" if nutrient == "calories" else "g"
230
+ formatted += f"| **{nutrient.title()}** | {result[nutrient]} {unit} |\n"
231
 
232
  # Vitamins and minerals
233
+ if "vitamins" in result and result["vitamins"]:
234
+ formatted += "\n### 🥕 Vitamins\n\n"
235
+ if isinstance(result["vitamins"], list):
236
+ for vitamin in result["vitamins"]:
237
+ formatted += f"- {vitamin}\n"
238
+ else:
239
+ formatted += str(result["vitamins"])
240
 
241
+ if "minerals" in result and result["minerals"]:
242
+ formatted += "\n### ⚡ Minerals\n\n"
243
+ if isinstance(result["minerals"], list):
244
+ for mineral in result["minerals"]:
245
+ formatted += f"- {mineral}\n"
246
+ else:
247
+ formatted += str(result["minerals"])
248
 
249
  return formatted
250
 
 
272
  # Format based on file type
273
  if "diet_plan" in filename:
274
  if "weekly" in filename:
275
+ return format_weekly_diet_plan(data, filename)
276
  else:
277
+ return format_daily_diet_plan(data, filename)
278
  elif "recommendations" in filename:
279
+ return format_recommendations_result(data, filename)
280
+ elif "nutrition" in filename:
281
+ return format_nutrition_result(data, filename)
282
  else:
283
+ return format_json_data_to_table(data, f"Latest Output: {filename}")
284
+
285
  except Exception as e:
286
+ return f"❌ Error reading {latest_file}: {str(e)}"
287
+
288
+ def format_weekly_diet_plan(data: dict, filename: str) -> str:
289
+ """Format weekly diet plan from JSON file"""
290
+ if not data or "result" not in data:
291
+ return f"❌ Invalid data in {filename}"
292
+
293
+ result = data["result"]
294
+ if "plans" not in result:
295
+ return f"❌ No plans found in {filename}"
296
+
297
+ plans = result["plans"]
298
+ formatted = f"## 📅 Weekly Diet Plan ({len(plans)} days)\n\n"
299
+ formatted += f"**File**: {filename}\n\n"
300
+
301
+ # Summary table for all days
302
+ formatted += "### 📊 Weekly Summary\n\n"
303
+ formatted += "| Day | Date | Calories | Protein | Carbs | Fat | Fiber |\n"
304
+ formatted += "|-----|------|----------|---------|-------|-----|-------|\n"
305
+
306
+ for i, plan in enumerate(plans):
307
+ totals = plan.get("daily_totals", {})
308
+ date = plan.get("date", f"Day {i+1}")
309
+ formatted += f"| {i+1} | {date} | {totals.get('calories', 0)} | {totals.get('protein', 0)}g | {totals.get('carbs', 0)}g | {totals.get('fat', 0)}g | {totals.get('fiber', 0)}g |\n"
310
+
311
+ # Detailed view for all days
312
+ formatted += "\n### 🍽️ Detailed Meals (All Days)\n\n"
313
+
314
+ for i, plan in enumerate(plans):
315
+ date = plan.get("date", f"Day {i+1}")
316
+ formatted += f"#### Day {i+1} - {date}\n\n"
317
+
318
+ meals = plan.get("meals", [])
319
+ for meal in meals:
320
+ meal_name = meal.get("meal_name", "Meal")
321
+ time_range = meal.get("time_range", "")
322
+ nutrition = meal.get("nutrition", {})
323
+
324
+ formatted += f"**{meal_name}** ({time_range})\n"
325
+ formatted += f"- Calories: {nutrition.get('calories', 0)} | Protein: {nutrition.get('protein', 0)}g | Carbs: {nutrition.get('carbs', 0)}g | Fat: {nutrition.get('fat', 0)}g\n"
326
+
327
+ # Foods
328
+ foods = meal.get("foods", [])
329
+ if foods:
330
+ formatted += " - Foods: "
331
+ food_names = [f.get("name", "Unknown") for f in foods[:3]] # Show first 3 foods
332
+ formatted += ", ".join(food_names)
333
+ if len(foods) > 3:
334
+ formatted += f" (+{len(foods)-3} more)"
335
+ formatted += "\n"
336
+ formatted += "\n"
337
+
338
+ return formatted
339
+
340
+ def format_daily_diet_plan(data: dict, filename: str) -> str:
341
+ """Format daily diet plan from JSON file"""
342
+ if not data or "result" not in data:
343
+ return f"❌ Invalid data in {filename}"
344
+
345
+ result = data["result"]
346
+ if "plan" not in result:
347
+ return f"❌ No plan found in {filename}"
348
+
349
+ plan = result["plan"]
350
+ formatted = f"## 🍽️ Daily Diet Plan\n\n"
351
+ formatted += f"**File**: {filename}\n\n"
352
+
353
+ # Daily totals
354
+ if "daily_totals" in plan:
355
+ totals = plan["daily_totals"]
356
+ formatted += "### 📊 Daily Nutrition Summary\n\n"
357
+ formatted += "| Nutrient | Amount |\n"
358
+ formatted += "|----------|--------|\n"
359
+ formatted += f"| **Calories** | {totals.get('calories', 0)} kcal |\n"
360
+ formatted += f"| **Protein** | {totals.get('protein', 0)} g |\n"
361
+ formatted += f"| **Carbs** | {totals.get('carbs', 0)} g |\n"
362
+ formatted += f"| **Fat** | {totals.get('fat', 0)} g |\n"
363
+ formatted += f"| **Fiber** | {totals.get('fiber', 0)} g |\n\n"
364
+
365
+ # Meals
366
+ if "meals" in plan:
367
+ formatted += "### 🍽️ Meals\n\n"
368
+ for meal in plan["meals"]:
369
+ meal_name = meal.get("meal_name", "Meal")
370
+ time_range = meal.get("time_range", "")
371
+ nutrition = meal.get("nutrition", {})
372
+
373
+ formatted += f"#### {meal_name} ({time_range})\n\n"
374
+ formatted += f"**Nutrition**: {nutrition.get('calories', 0)} kcal, {nutrition.get('protein', 0)}g protein, {nutrition.get('carbs', 0)}g carbs, {nutrition.get('fat', 0)}g fat\n\n"
375
+
376
+ # Foods
377
+ foods = meal.get("foods", [])
378
+ if foods:
379
+ formatted += "**Foods**:\n"
380
+ for food in foods:
381
+ name = food.get("name", "Unknown")
382
+ portion = food.get("portion_grams", 0)
383
+ calories = food.get("calories", 0)
384
+ formatted += f"- **{name}** ({portion}g) - {calories} kcal\n"
385
+ formatted += "\n"
386
+
387
+ return formatted
388
 
389
+ def list_all_json_outputs() -> str:
390
+ """List all JSON output files with their details"""
391
  outputs_dir = "outputs"
392
  if not os.path.exists(outputs_dir):
393
  return "❌ No outputs directory found"
 
396
  if not json_files:
397
  return "❌ No JSON files found in outputs directory"
398
 
399
+ # Sort by modification time (newest first)
400
+ json_files.sort(key=os.path.getmtime, reverse=True)
401
+
402
+ formatted = "## 📁 Available JSON Outputs\n\n"
403
+ formatted += "| File | Type | Size | Modified |\n"
404
+ formatted += "|------|------|------|----------|\n"
405
 
406
+ for file_path in json_files:
407
  filename = os.path.basename(file_path)
408
+ file_type = "Unknown"
 
409
 
 
410
  if "diet_plan_weekly" in filename:
411
+ file_type = "Weekly Diet Plan"
412
  elif "diet_plan_daily" in filename:
413
+ file_type = "Daily Diet Plan"
414
  elif "recommendations" in filename:
415
+ file_type = "Recommendations"
416
+ elif "nutrition" in filename:
417
+ file_type = "Nutrition Info"
418
+
419
+ file_size = os.path.getsize(file_path)
420
+ mod_time = os.path.getmtime(file_path)
421
+ mod_date = pd.Timestamp.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M")
422
 
423
+ formatted += f"| {filename} | {file_type} | {file_size:,} bytes | {mod_date} |\n"
424
 
425
  return formatted
426
 
 
428
  """Extract JSON objects from text and format them as tables"""
429
  if not text:
430
  return text
431
+
432
  formatted_text = text
433
+
434
  # First, try to find JSON in code blocks
435
  code_block_pattern = r'```(?:json)?\s*(\{.*?\})\s*```'
436
  matches = list(re.finditer(code_block_pattern, formatted_text, re.DOTALL | re.IGNORECASE))
437
+
438
  for match in reversed(matches):
439
  json_str = match.group(1).strip()
440
  try:
 
443
  formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
444
  except:
445
  continue
446
+
447
  # Then, try to find standalone JSON objects
448
+ # Look for patterns that start with { and end with }
449
  json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
450
  matches = list(re.finditer(json_pattern, formatted_text, re.DOTALL))
451
+
452
  for match in reversed(matches):
453
  json_str = match.group(0).strip()
454
+
455
  # Skip if it's already been processed or is too short
456
  if len(json_str) < 10 or '|' in json_str:
457
  continue
458
+
459
  try:
460
  json_data = json.loads(json_str)
461
  # Only format if it looks like structured data
 
464
  formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
465
  except:
466
  continue
467
+
468
  return formatted_text
469
 
470
  def format_json_data_to_table(json_data: Any) -> str:
471
+ """Format JSON data to a table string"""
472
  if isinstance(json_data, dict):
473
+ return format_dict_to_table(json_data, "Data")
 
 
 
 
 
 
 
 
 
474
  elif isinstance(json_data, list):
475
+ return format_list_to_table(json_data, "Data")
476
  else:
477
  return str(json_data)
478
 
479
  def process_user_input(user_input: str, history: List) -> tuple:
480
+ """Process user input through RAG system"""
481
+ global chat_history
482
+
483
  if not user_input.strip():
484
  return history, ""
485
 
486
+ # Convert Gradio history format to our format
487
+ rag_history = []
488
+ for msg in history:
489
+ if isinstance(msg, dict):
490
+ rag_history.append(msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
491
  else:
492
+ # Handle old format
493
+ user_msg, bot_msg = msg
494
+ rag_history.append({"role": "user", "content": user_msg})
495
+ rag_history.append({"role": "assistant", "content": bot_msg})
496
+
497
+ # Process through RAG system
498
+ result = run_rag_tool_router(user_input, rag_history)
499
+
500
+ # Update our chat history
501
+ chat_history.append({"role": "user", "content": user_input})
502
+
503
+ # Handle different response types
504
+ if isinstance(result, dict) and "final" in result:
505
+ response = result["final"]
506
  # Format any JSON in the response
507
+ formatted_response = extract_and_format_json_in_text(response)
508
+ chat_history.append({"role": "assistant", "content": formatted_response})
 
509
  history.append({"role": "user", "content": user_input})
510
  history.append({"role": "assistant", "content": formatted_response})
511
+ return history, ""
512
+
513
+ elif isinstance(result, dict) and "action" in result:
514
+ action = result["action"]
515
+ args = result.get("args", {})
516
+
517
+ # Show the action being taken
518
+ action_response = f"**Executing**: {action}\n\n**Arguments**:\n```json\n{json.dumps(args, indent=2)}\n```"
519
+
520
+ # Execute diet tools
521
+ if action in ["generate_diet_plan", "get_diet_recommendations", "calculate_nutrition_info", "expand_diet_database"]:
522
+ diet_result = execute_diet_tool(action, args)
523
+
524
+ if diet_result.get("success"):
525
+ final_response = f"✅ **{diet_result.get('message', 'Operation completed successfully')}**\n\n"
526
+ if "result" in diet_result:
527
+ # Format the result based on action type
528
+ if action == "generate_diet_plan":
529
+ formatted_result = format_diet_plan_result(diet_result['result'])
530
+ elif action == "get_diet_recommendations":
531
+ formatted_result = format_recommendations_result(diet_result['result'])
532
+ elif action == "calculate_nutrition_info":
533
+ formatted_result = format_nutrition_result(diet_result['result'])
534
+ else:
535
+ formatted_result = format_json_to_table(diet_result['result'], "Result")
536
+
537
+ final_response += formatted_result
538
+ else:
539
+ final_response = f"❌ **Error**: {diet_result.get('error', 'Unknown error occurred')}"
540
+
541
+ # Add to history
542
+ history.append({"role": "user", "content": user_input})
543
+ history.append({"role": "assistant", "content": action_response + "\n\n" + final_response})
544
+ chat_history.append({"role": "assistant", "content": final_response})
545
+ else:
546
+ # For other tools, show placeholder
547
+ final_response = "🔄 This tool is not yet implemented in the web interface."
548
+ history.append({"role": "user", "content": user_input})
549
+ history.append({"role": "assistant", "content": action_response + "\n\n" + final_response})
550
+ chat_history.append({"role": "assistant", "content": final_response})
551
 
552
  return history, ""
553
 
554
+ else:
555
+ # Handle errors or other responses
556
+ error_response = f"❌ **Error**: {json.dumps(result, indent=2, ensure_ascii=False)}"
557
+ chat_history.append({"role": "assistant", "content": error_response})
558
  history.append({"role": "user", "content": user_input})
559
+ history.append({"role": "assistant", "content": error_response})
560
  return history, ""
561
 
562
+ def create_diet_plan_interface(age: int, sex: str, height_cm: float, weight_kg: float,
563
+ activity_level: str, goal: str, plan_type: str) -> str:
564
+ """Create diet plan using the interface"""
565
+ user_profile = {
566
+ "age": age,
567
+ "sex": sex,
568
+ "height_cm": height_cm,
569
+ "weight_kg": weight_kg,
570
+ "activity_level": activity_level,
571
+ "goal": goal,
572
+ "dietary_restrictions": [],
573
+ "allergies": [],
574
+ "preferences": []
575
+ }
576
+
577
+ try:
578
+ result = generate_diet_plan(user_profile, plan_type)
579
+ return format_diet_plan_result(result)
580
+ except Exception as e:
581
+ return f"❌ Error: {str(e)}"
582
+
583
+ def get_recommendations_interface(age: int, sex: str, height_cm: float, weight_kg: float,
584
+ activity_level: str, goal: str) -> str:
585
+ """Get diet recommendations using the interface"""
586
+ user_profile = {
587
+ "age": age,
588
+ "sex": sex,
589
+ "height_cm": height_cm,
590
+ "weight_kg": weight_kg,
591
+ "activity_level": activity_level,
592
+ "goal": goal,
593
+ "dietary_restrictions": [],
594
+ "allergies": [],
595
+ "preferences": []
596
+ }
597
+
598
+ try:
599
+ result = get_diet_recommendations(user_profile)
600
+ return format_recommendations_result(result)
601
+ except Exception as e:
602
+ return f"❌ Error: {str(e)}"
603
+
604
+ def calculate_nutrition_interface(food_name: str, portion_grams: float) -> str:
605
+ """Calculate nutrition info using the interface"""
606
+ try:
607
+ result = calculate_nutrition_info(food_name, portion_grams)
608
+ return format_nutrition_result(result)
609
+ except Exception as e:
610
+ return f"❌ Error: {str(e)}"
611
+
612
  # Create Gradio interface
613
+ with gr.Blocks(title="RAG Diet Assistant") as app:
614
+ gr.Markdown("# 🍽️ RAG Diet Assistant")
615
+ gr.Markdown("Your intelligent nutrition planning assistant powered by RAG (Retrieval-Augmented Generation)")
616
+
617
+ with gr.Tabs():
618
+ # Chat Interface Tab
619
+ with gr.Tab("💬 Chat Assistant"):
620
+ gr.Markdown("Ask me anything about diet planning, nutrition, or health!")
621
+
622
+ chatbot = gr.Chatbot(
623
+ label="Conversation",
624
+ height=500,
625
+ type="messages",
626
+ render_markdown=True
 
 
 
 
 
 
627
  )
628
+
629
+ with gr.Row():
630
+ msg = gr.Textbox(
631
+ label="Your message",
632
+ placeholder="Ask me to create a diet plan, calculate nutrition, or get recommendations...",
633
+ lines=2,
634
+ scale=4
635
+ )
636
+ send_btn = gr.Button("Send", variant="primary", scale=1)
637
+
638
+ # Action buttons
639
+ with gr.Row():
640
+ clear_btn = gr.Button("Clear Chat", variant="secondary")
641
+ load_latest_btn = gr.Button("📄 Load Latest JSON", variant="secondary")
642
+ list_outputs_btn = gr.Button("📁 List All Outputs", variant="secondary")
643
+
644
+ # Event handlers
645
+ msg.submit(process_user_input, [msg, chatbot], [chatbot, msg])
646
+ send_btn.click(process_user_input, [msg, chatbot], [chatbot, msg])
647
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
648
+ load_latest_btn.click(lambda: ([{"role": "assistant", "content": load_latest_json_output()}], ""), outputs=[chatbot, msg])
649
+ list_outputs_btn.click(lambda: ([{"role": "assistant", "content": list_all_json_outputs()}], ""), outputs=[chatbot, msg])
650
 
651
+ # Diet Plan Creator Tab
652
+ with gr.Tab("📋 Diet Plan Creator"):
653
+ gr.Markdown("Create personalized diet plans based on your profile")
654
+
655
+ with gr.Row():
656
+ with gr.Column():
657
+ gr.Markdown("### Personal Information")
658
+ age = gr.Number(label="Age", value=30, minimum=15, maximum=100)
659
+ sex = gr.Dropdown(label="Gender", choices=["male", "female"], value="male")
660
+ height_cm = gr.Number(label="Height (cm)", value=175, minimum=100, maximum=250)
661
+ weight_kg = gr.Number(label="Weight (kg)", value=75, minimum=30, maximum=300)
662
+
663
+ gr.Markdown("### Activity & Goals")
664
+ activity_level = gr.Dropdown(
665
+ label="Activity Level",
666
+ choices=["sedentary", "light", "moderate", "active", "very_active"],
667
+ value="moderate"
668
+ )
669
+ goal = gr.Dropdown(
670
+ label="Goal",
671
+ choices=["weight_loss", "muscle_gain", "maintenance", "keto", "mediterranean"],
672
+ value="weight_loss"
673
+ )
674
+ plan_type = gr.Dropdown(
675
+ label="Plan Type",
676
+ choices=["daily", "weekly"],
677
+ value="daily"
678
+ )
679
+
680
+ create_plan_btn = gr.Button("Create Diet Plan", variant="primary")
681
+
682
+ with gr.Column():
683
+ plan_output = gr.Textbox(
684
+ label="Diet Plan",
685
+ lines=20,
686
+ max_lines=30
687
+ )
688
+
689
+ create_plan_btn.click(
690
+ create_diet_plan_interface,
691
+ inputs=[age, sex, height_cm, weight_kg, activity_level, goal, plan_type],
692
+ outputs=plan_output
693
+ )
694
 
695
+ # Recommendations Tab
696
+ with gr.Tab("📊 Diet Recommendations"):
697
+ gr.Markdown("Get personalized nutrition recommendations")
698
+
699
+ with gr.Row():
700
+ with gr.Column():
701
+ gr.Markdown("### Personal Information")
702
+ rec_age = gr.Number(label="Age", value=30, minimum=15, maximum=100)
703
+ rec_sex = gr.Dropdown(label="Gender", choices=["male", "female"], value="male")
704
+ rec_height_cm = gr.Number(label="Height (cm)", value=175, minimum=100, maximum=250)
705
+ rec_weight_kg = gr.Number(label="Weight (kg)", value=75, minimum=30, maximum=300)
706
+
707
+ gr.Markdown("### Activity & Goals")
708
+ rec_activity_level = gr.Dropdown(
709
+ label="Activity Level",
710
+ choices=["sedentary", "light", "moderate", "active", "very_active"],
711
+ value="moderate"
712
+ )
713
+ rec_goal = gr.Dropdown(
714
+ label="Goal",
715
+ choices=["weight_loss", "muscle_gain", "maintenance", "keto", "mediterranean"],
716
+ value="weight_loss"
717
+ )
718
+
719
+ get_rec_btn = gr.Button("Get Recommendations", variant="primary")
720
+
721
+ with gr.Column():
722
+ rec_output = gr.Textbox(
723
+ label="Recommendations",
724
+ lines=15,
725
+ max_lines=20
726
+ )
727
+
728
+ get_rec_btn.click(
729
+ get_recommendations_interface,
730
+ inputs=[rec_age, rec_sex, rec_height_cm, rec_weight_kg, rec_activity_level, rec_goal],
731
+ outputs=rec_output
732
+ )
733
 
734
+ # Nutrition Calculator Tab
735
+ with gr.Tab("🧮 Nutrition Calculator"):
736
+ gr.Markdown("Calculate nutritional values for specific foods")
737
+
738
+ with gr.Row():
739
+ with gr.Column():
740
+ food_name = gr.Textbox(
741
+ label="Food Name",
742
+ placeholder="e.g., Chicken Breast, Apple, Brown Rice...",
743
+ value="Chicken Breast"
744
+ )
745
+ portion_grams = gr.Number(
746
+ label="Portion (grams)",
747
+ value=150,
748
+ minimum=1,
749
+ maximum=1000
750
+ )
751
+
752
+ calc_nutrition_btn = gr.Button("Calculate Nutrition", variant="primary")
753
+
754
+ with gr.Column():
755
+ nutrition_output = gr.Textbox(
756
+ label="Nutritional Information",
757
+ lines=15,
758
+ max_lines=20
759
+ )
760
+
761
+ calc_nutrition_btn.click(
762
+ calculate_nutrition_interface,
763
+ inputs=[food_name, portion_grams],
764
+ outputs=nutrition_output
765
+ )
766
+
767
+ def create_gradio_interface():
768
+ """Create and return the Gradio interface for Hugging Face Spaces"""
769
  return app
770
 
 
771
  if __name__ == "__main__":
772
+ # For local development
773
  app.launch(
774
+ server_name="127.0.0.1",
775
  server_port=7860,
776
  share=False
777
  )