sam133 commited on
Commit
ee969dd
·
1 Parent(s): 11fe717

� PHASE 5

Browse files
Files changed (1) hide show
  1. app.py +73 -253
app.py CHANGED
@@ -1,175 +1,38 @@
1
  #!/usr/bin/env python3
2
  """
3
- Agent2Robot - FIXED VERSION
4
- Problem: Generator functions with yield cause Gradio schema errors
5
- Solution: Convert to regular function returning final results
6
  """
7
 
8
  import gradio as gr
9
- import os
10
- import json
11
- import tempfile
12
- from datetime import datetime
13
 
14
- # Simplified backend simulation (replace with your actual imports)
15
- class MockHackathonVehicleDesigner:
16
- """Mock version of your designer for testing the fix"""
17
- def __init__(self):
18
- self.vehicle_type = "robot"
19
- self.user_task_description = ""
20
- self.process_log = []
21
- self.all_attempts = []
22
- self.best_attempt = None
23
- self.best_iteration = 1
24
- self.overall_success = True
25
-
26
- def reset_design_session(self):
27
- self.process_log = []
28
- self.all_attempts = []
29
-
30
- def log_process_step(self, message):
31
- self.process_log.append(message)
32
-
33
- def parse_user_task_for_criteria(self, description):
34
- return ["Cross obstacle", "Remain stable", "Stop safely"]
35
-
36
- def run_single_iteration(self, iteration):
37
- # Mock iteration
38
- self.all_attempts.append({
39
- 'vehicle_specs': {
40
- 'wheel_radius': 0.05,
41
- 'body_length': 0.2,
42
- 'body_width': 0.15,
43
- 'body_height': 0.1,
44
- 'wheel_distance': 0.18
45
- },
46
- 'design_reasoning': f'Iteration {iteration}: Optimized design for obstacle crossing',
47
- 'evaluation_results': {
48
- 'final_robot_x_position': 0.85,
49
- 'robot_crossed_obstacle': True,
50
- 'robot_remains_upright': True,
51
- 'no_significant_collision_with_obstacle_during_pass': True,
52
- 'overall_success': True
53
- }
54
- })
55
- self.best_attempt = self.all_attempts[-1]
56
- return True
57
-
58
- def create_final_visualization(self):
59
- return None # Mock - return None for no image
60
-
61
- def save_design_specs_json(self):
62
- return None # Mock - return None for no file
63
-
64
- # Create mock designer
65
- designer = MockHackathonVehicleDesigner()
66
-
67
- def ui_function_fixed(vehicle_type, user_description):
68
- """
69
- FIXED: Regular function (no yield) that returns final results
70
- This replaces the problematic generator function
71
- """
72
- global designer
73
-
74
- # Reset designer for new task
75
- designer.reset_design_session()
76
- designer.vehicle_type = vehicle_type.lower()
77
- designer.user_task_description = user_description
78
-
79
- # Process in one go (no real-time updates)
80
- designer.log_process_step("🚀 Initializing Agent2Robot system...")
81
-
82
- # Parse user criteria
83
- designer.log_process_step("🎯 Analyzing user task and success criteria...")
84
- criteria = designer.parse_user_task_for_criteria(user_description)
85
-
86
- designer.log_process_step(f"📋 Interpreted success criteria:")
87
- for criterion in criteria:
88
- designer.log_process_step(f" • {criterion}")
89
-
90
- # Start design process
91
- designer.log_process_step(f"🚀 Starting {vehicle_type} design process...")
92
- designer.log_process_step(f"🎯 Target: {user_description}")
93
-
94
- # Run iterations (simplified - no real-time updates)
95
- MAX_ITERATIONS = 3
96
- for iteration in range(1, MAX_ITERATIONS + 1):
97
- designer.log_process_step(f"\n=== Iteration {iteration}/{MAX_ITERATIONS} ===")
98
-
99
- try:
100
- success = designer.run_single_iteration(iteration)
101
- if success:
102
- designer.log_process_step("🎉 SUCCESS! Design meets all criteria!")
103
- break
104
- except Exception as e:
105
- designer.log_process_step(f"❌ Error in iteration {iteration}: {str(e)}")
106
-
107
- # Generate final results
108
- designer.log_process_step("📊 Generating final results...")
109
-
110
- # Prepare final outputs
111
- if designer.overall_success:
112
- final_status = "## 🎉 SUCCESS!\n\nThe LLM agent successfully designed a vehicle that meets all criteria!"
113
- else:
114
- final_status = "## ⚠️ PROCESS COMPLETED\n\nThe agent completed all iterations. Showing best attempt found."
115
-
116
- # Get best design specs
117
- best_specs = designer.best_attempt['vehicle_specs'] if designer.best_attempt else {}
118
-
119
- # Create visualization (mock)
120
- simulation_gif_path = designer.create_final_visualization()
121
-
122
- # Format performance summary
123
- if designer.best_attempt:
124
- eval_results = designer.best_attempt['evaluation_results']
125
- performance_summary = f"""## 📊 Performance Summary of Best Design
126
-
127
- **Iteration Found**: {designer.best_iteration}/{len(designer.all_attempts)}
128
- **Final Position**: {eval_results.get('final_robot_x_position', 0.0):.3f}m
129
- **Crossed Obstacle**: {'✅ Yes' if eval_results.get('robot_crossed_obstacle', False) else '❌ No'}
130
- **Remained Stable**: {'✅ Yes' if eval_results.get('robot_remains_upright', False) else '❌ No'}
131
- **Clean Pass**: {'✅ Yes' if eval_results.get('no_significant_collision_with_obstacle_during_pass', False) else '❌ No'}
132
-
133
- **Overall Success**: {'✅ ACHIEVED' if eval_results.get('overall_success', False) else '❌ NOT FULLY ACHIEVED'}
134
-
135
- **Target Distance**: 0.8m (obstacle clearance)
136
- **Achieved Distance**: {eval_results.get('final_robot_x_position', 0.0):.3f}m
137
- **Success Rate**: {100 if eval_results.get('overall_success', False) else 0}%
138
- """
139
- else:
140
- performance_summary = "## ❌ No successful attempts recorded"
141
-
142
- # Get LLM rationale
143
- llm_rationale = designer.best_attempt['design_reasoning'] if designer.best_attempt else "No design reasoning available"
144
-
145
- # Create downloadable specs (mock)
146
- download_specs_path = designer.save_design_specs_json()
147
-
148
- # Final log update
149
- designer.log_process_step(f"\n🏁 DESIGN PROCESS COMPLETED")
150
- designer.log_process_step(f"📊 Total iterations: {len(designer.all_attempts)}")
151
- designer.log_process_step(f"🏆 Best iteration: {designer.best_iteration}")
152
- designer.log_process_step(f"✅ Overall success: {designer.overall_success}")
153
-
154
- final_log = "\n".join(designer.process_log)
155
 
156
- # RETURN (not yield) all 9 outputs at once
157
- return (
158
- final_log, # process_log_output
159
- best_specs, # current_design_specs_output
160
- 100, # progress_bar_output
161
- final_status, # final_status_output
162
- simulation_gif_path, # simulation_video_output
163
- best_specs, # best_design_specs_output
164
- download_specs_path, # download_json_output
165
- performance_summary, # performance_summary_output
166
- llm_rationale # llm_rationale_output
167
- )
168
 
169
- def create_fixed_agent2robot_interface():
170
- """Create the FIXED Agent2Robot Gradio interface"""
171
 
172
- # Custom CSS for better appearance
173
  custom_css = """
174
  .main-header {
175
  text-align: center;
@@ -180,34 +43,31 @@ def create_fixed_agent2robot_interface():
180
  margin-bottom: 20px;
181
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
182
  }
183
- .process-log {
184
- font-family: 'Courier New', monospace;
185
- font-size: 12px;
186
- line-height: 1.4;
187
- }
188
  """
189
 
190
  with gr.Blocks(
191
- title="🤖🚁 Agent2Robot - FIXED VERSION",
192
  theme=gr.themes.Soft(),
193
  css=custom_css
194
  ) as demo:
195
 
196
- # Header Section
197
  gr.HTML("""
198
  <div class="main-header">
199
- <h1>🤖🚁 Agent2Robot - FIXED!</h1>
200
- <h2>LLM-Agent-Designed Obstacle-Passing Vehicle System</h2>
201
- <p><strong>✅ PROBLEM SOLVED: Generator function converted to regular function</strong></p>
202
- <p>Describe your desired vehicle and task in natural language!</p>
203
  </div>
204
  """)
205
 
206
- # Main Input Section
 
 
207
  with gr.Row():
208
  with gr.Column(scale=1):
209
  gr.Markdown("## 🎯 1. Define Your Vehicle Challenge")
210
 
 
211
  vehicle_type_input = gr.Radio(
212
  choices=["Robot", "Drone"],
213
  label="1. Choose Vehicle Type",
@@ -229,26 +89,26 @@ def create_fixed_agent2robot_interface():
229
  )
230
 
231
  gr.Markdown("""
232
- ### FIXED!
233
- - **Problem**: Generator function with yield statements
234
- - **Solution**: Regular function returning final results
235
- - **Status**: Schema error resolved!
236
  """)
237
 
238
  with gr.Column(scale=2):
239
- gr.Markdown("## 🤖 2. AI Agent Results")
240
 
241
- process_log_output = gr.Textbox(
242
- label="🤖 AI Agent - Process Log",
243
- lines=15,
244
- interactive=False,
245
- elem_classes=["process-log"],
246
- value=""
247
  )
248
 
249
  with gr.Row():
250
  current_design_specs_output = gr.JSON(
251
- label="⚙️ Design Specs",
252
  value={}
253
  )
254
 
@@ -261,87 +121,47 @@ def create_fixed_agent2robot_interface():
261
  show_label=True,
262
  value=0
263
  )
264
-
265
- # Results Section
266
- with gr.Accordion("🏆 Final Results & Design Specifications", open=True):
267
- final_status_output = gr.Markdown(
268
- value="Click 'Start AI Design Process' to begin..."
269
- )
270
-
271
- with gr.Row():
272
- with gr.Column(scale=2):
273
- simulation_video_output = gr.Image(
274
- label="🎬 Simulation of Best Design's Trial",
275
- interactive=False,
276
- height=300,
277
- value=None
278
- )
279
-
280
- performance_summary_output = gr.Markdown(
281
- label="📊 Performance Summary",
282
- value=""
283
- )
284
 
285
- with gr.Column(scale=1):
286
- best_design_specs_output = gr.JSON(
287
- label="🔩 Best Vehicle Design Specifications",
288
- value={}
289
- )
290
-
291
- download_json_output = gr.File(
292
- label="📄 Download Design Specs (JSON)",
293
- file_count="single",
294
- type="filepath",
295
- interactive=True,
296
- value=None
297
- )
298
-
299
- llm_rationale_output = gr.Textbox(
300
- label="💡 LLM's Design Rationale",
301
- lines=6,
302
- interactive=False,
303
- value=""
304
- )
305
 
306
- # Connect button to FIXED function (no more yield!)
307
  start_button.click(
308
- fn=ui_function_fixed,
309
- inputs=[vehicle_type_input, user_description_input],
310
  outputs=[
311
- process_log_output,
312
- current_design_specs_output,
313
  progress_bar_output,
314
- final_status_output,
315
  simulation_video_output,
316
- best_design_specs_output,
317
- download_json_output,
318
- performance_summary_output,
319
- llm_rationale_output
320
  ]
321
  )
322
 
323
- # Information Footer
324
  gr.Markdown("---")
325
- gr.Markdown("""
326
- ## ✅ PROBLEM SOLVED!
327
-
328
- **Root Cause**: Generator functions with `yield` statements cause `TypeError: argument of type 'bool' is not iterable` during Gradio's API schema generation.
329
-
330
- **Solution**: Convert generator function to regular function that returns final results instead of yielding intermediate updates.
331
-
332
- **Trade-off**: No real-time progress updates, but fully functional interface.
333
- """)
334
 
335
  return demo
336
 
337
  if __name__ == "__main__":
338
- print("🤖🚁 Agent2Robot - FIXED VERSION")
339
- print("=" * 60)
340
- print(" Generator function converted to regular function")
341
- print("🚀 Launching fixed interface...")
342
 
343
  try:
344
- app = create_fixed_agent2robot_interface()
345
  app.launch(
346
  server_name="0.0.0.0",
347
  server_port=7860,
@@ -352,4 +172,4 @@ if __name__ == "__main__":
352
  )
353
  except Exception as e:
354
  print(f"❌ Error launching app: {e}")
355
- print("Please check the implementation.")
 
1
  #!/usr/bin/env python3
2
  """
3
+ Agent2Robot - MINIMAL WORKING VERSION
4
+ Based on successful Step 4 but with simple return function
 
5
  """
6
 
7
  import gradio as gr
 
 
 
 
8
 
9
+ def simple_test_function(vehicle_type, user_description):
10
+ """Simple test function that returns results like Step 4 worked"""
11
+ if not user_description:
12
+ user_description = "No description provided"
13
+
14
+ # Simple return (like Step 4 but with return instead of yield)
15
+ text_output = f"✅ COMPLETED!\nVehicle: {vehicle_type}\nDescription: {user_description}\nTest successful!"
16
+ json_output = {
17
+ "vehicle_type": vehicle_type,
18
+ "description": user_description,
19
+ "test_status": "success",
20
+ "parameters": {
21
+ "speed": 5.2,
22
+ "weight": 1.8,
23
+ "dimensions": [10, 8, 6]
24
+ }
25
+ }
26
+ progress_value = 100
27
+ image_output = None
28
+ file_output = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ return text_output, json_output, progress_value, image_output, file_output
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ def create_minimal_working_app():
33
+ """MINIMAL working app based on successful Step 4"""
34
 
35
+ # Exact same CSS as Step 4 (worked)
36
  custom_css = """
37
  .main-header {
38
  text-align: center;
 
43
  margin-bottom: 20px;
44
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
45
  }
 
 
 
 
 
46
  """
47
 
48
  with gr.Blocks(
49
+ title="🤖🚁 Agent2Robot - MINIMAL WORKING",
50
  theme=gr.themes.Soft(),
51
  css=custom_css
52
  ) as demo:
53
 
54
+ # Exact same header as Step 4 (worked)
55
  gr.HTML("""
56
  <div class="main-header">
57
+ <h1>🤖🚁 Agent2Robot</h1>
58
+ <h2>MINIMAL WORKING VERSION</h2>
59
+ <p><strong>Based on successful Step 4 components</strong></p>
 
60
  </div>
61
  """)
62
 
63
+ # Exact same layout as Step 4 (worked)
64
+ gr.Markdown("## 🔧 MINIMAL WORKING TEST")
65
+
66
  with gr.Row():
67
  with gr.Column(scale=1):
68
  gr.Markdown("## 🎯 1. Define Your Vehicle Challenge")
69
 
70
+ # Exact same components as Step 4 (worked)
71
  vehicle_type_input = gr.Radio(
72
  choices=["Robot", "Drone"],
73
  label="1. Choose Vehicle Type",
 
89
  )
90
 
91
  gr.Markdown("""
92
+ ### 📋 Status
93
+ - **Version**: Minimal working (Step 4 base)
94
+ - **Function**: Simple return (no yield)
95
+ - **Goal**: Isolate the problematic component
96
  """)
97
 
98
  with gr.Column(scale=2):
99
+ gr.Markdown("## 🤖 2. Test Outputs")
100
 
101
+ # Exact same output components as Step 4 (worked)
102
+ output_textbox = gr.Textbox(
103
+ label="📝 Text Output",
104
+ lines=5,
105
+ value="",
106
+ interactive=False
107
  )
108
 
109
  with gr.Row():
110
  current_design_specs_output = gr.JSON(
111
+ label="⚙️ JSON Output Test",
112
  value={}
113
  )
114
 
 
121
  show_label=True,
122
  value=0
123
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
+ simulation_video_output = gr.Image(
126
+ label="🎬 Image Output Test",
127
+ interactive=False,
128
+ height=200,
129
+ value=None
130
+ )
131
+
132
+ download_json_output = gr.File(
133
+ label="📄 File Output Test",
134
+ file_count="single",
135
+ type="filepath",
136
+ interactive=True,
137
+ value=None
138
+ )
 
 
 
 
 
 
139
 
140
+ # Simple button connection (5 outputs like Step 4)
141
  start_button.click(
142
+ fn=simple_test_function,
143
+ inputs=[vehicle_type_input, user_description_input],
144
  outputs=[
145
+ output_textbox,
146
+ current_design_specs_output,
147
  progress_bar_output,
 
148
  simulation_video_output,
149
+ download_json_output
 
 
 
150
  ]
151
  )
152
 
 
153
  gr.Markdown("---")
154
+ gr.Markdown("**Status**: If this works, we can add components one by one to find the problematic one.")
 
 
 
 
 
 
 
 
155
 
156
  return demo
157
 
158
  if __name__ == "__main__":
159
+ print("🔧 Agent2Robot - MINIMAL WORKING VERSION")
160
+ print("=" * 50)
161
+ print("🚀 Testing minimal working components...")
 
162
 
163
  try:
164
+ app = create_minimal_working_app()
165
  app.launch(
166
  server_name="0.0.0.0",
167
  server_port=7860,
 
172
  )
173
  except Exception as e:
174
  print(f"❌ Error launching app: {e}")
175
+ print("Even minimal version has issues!")