acecalisto3 commited on
Commit
f6f4b8a
1 Parent(s): 7af66c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py CHANGED
@@ -322,6 +322,180 @@ with gr.Blocks() as iface:
322
  terminal_input = gr.Textbox(label="Enter Command")
323
  terminal_button = gr.Button("Run")
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  # App Creation Process Class
326
  class AppCreationProcess:
327
  def __init__(self):
 
322
  terminal_input = gr.Textbox(label="Enter Command")
323
  terminal_button = gr.Button("Run")
324
 
325
+ # App Creation Process Class
326
+ class AppCreationProcess:
327
+ def __init__(self):
328
+ self.current_step = 1
329
+ self.app_name = ""
330
+ self.components = []
331
+
332
+ def get_current_step_info(self):
333
+ steps = {
334
+ 1: "App Initialization",
335
+ 2: "Component Addition",
336
+ 3: "Property Configuration",
337
+ 4: "Code Generation",
338
+ 5: "Deployment"
339
+ }
340
+ return f"Step {self.current_step}: {steps[self.current_step]}"
341
+
342
+ def add_component(self, component_type):
343
+ new_component = Component(component_type)
344
+ self.components.append(new_component.to_dict())
345
+ return self.update_app_canvas()
346
+
347
+ def set_component_property(self, component_id, property_name, property_value):
348
+ for component in self.components:
349
+ if component['id'] == component_id:
350
+ if property_name in component['properties']:
351
+ component['properties'][property_name.strip()] = property_value.strip()
352
+ return self.update_app_canvas(), f"Property '{property_name}' set to '{property_value}' for component {component_id}"
353
+ else:
354
+ return None, f"Error: Property '{property_name}' not found in component {component_id}"
355
+ return None, f"Error: Component with ID {component_id} not found."
356
+
357
+ def update_app_canvas(self):
358
+ components_html = "".join([
359
+ f"<div>Component ID: {component['id']}, Type: {component['type']}, Properties: {component['properties']}</div>"
360
+ for component in self.components
361
+ ])
362
+ return components_html
363
+
364
+ def generate_python_code(self):
365
+ code = f"""import gradio as gr\n\nwith gr.Blocks() as {self.app_name}:\n"""
366
+ for component in self.components:
367
+ code += " " + Component(**component).render() + "\n"
368
+ code += f"\n{self.app_name}.launch()\n"
369
+ return code
370
+
371
+ def deploy_to_huggingface(self):
372
+ # Generate Python code
373
+ code = self.generate_python_code()
374
+ # Create requirements.txt
375
+ with open("requirements.txt", "w") as f:
376
+ f.write("gradio==3.32.0\n")
377
+ # Create the app.py file
378
+ with open("app.py", "w") as f:
379
+ f.write(code)
380
+ # Execute the deployment command
381
+ try:
382
+ subprocess.run(["huggingface-cli", "repo", "create", "--type", "space", "--space_sdk", "gradio", self.app_name], check=True)
383
+ subprocess.run(["git", "init"], cwd=f"./{self.app_name}", check=True)
384
+ subprocess.run(["git", "add", "."], cwd=f"./{self.app_name}", check=True)
385
+ subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=f"./{self.app_name}", check=True)
386
+ subprocess.run(["git", "push", "https://huggingface.co/spaces/" + self.app_name, "main"], cwd=f"./{self.app_name}", check=True)
387
+ return f"Successfully deployed to Hugging Face Spaces: https://huggingface.co/spaces/{self.app_name}"
388
+ except Exception as e:
389
+ return f"Error deploying to Hugging Face Spaces: {e}"
390
+
391
+ app_process = AppCreationProcess()
392
+
393
+ # Function to handle terminal input
394
+ def run_terminal_command(command, history):
395
+ global terminal_history
396
+ output = ""
397
+ try:
398
+ # Basic command parsing (expand with NLP)
399
+ if command.startswith("add "):
400
+ component_type = command.split("add ", 1)[1].strip()
401
+ output = app_process.add_component(component_type)
402
+ elif command.startswith("set "):
403
+ _, output = set_component_property(command)
404
+ elif command.startswith("search "):
405
+ search_query = command.split("search ", 1)[1].strip()
406
+ output = i_s(search_query)
407
+ elif command.startswith("deploy "):
408
+ output = app_process.deploy_to_huggingface()
409
+ else:
410
+ # Attempt to execute command as Python code
411
+ try:
412
+ result = subprocess.check_output(
413
+ command, shell=True, stderr=subprocess.STDOUT, text=True
414
+ )
415
+ output = result
416
+ except Exception as e:
417
+ output = f"Error executing Python code: {str(e)}"
418
+ except Exception as e:
419
+ output = f"Error: {str(e)}"
420
+ finally:
421
+ terminal_history += f"User: {command}\n{output}\n"
422
+ return terminal_history
423
+
424
+ def set_component_property(command):
425
+ try:
426
+ # Improved 'set' command parsing
427
+ set_parts = command.split(" ", 2)[1:]
428
+ if len(set_parts) != 2:
429
+ raise ValueError("Invalid 'set' command format.")
430
+ component_id = int(set_parts[0]) # Use component ID
431
+ property_name, property_value = set_parts[1].split("=", 1)
432
+ return app_process.set_component_property(component_id, property_name, property_value)
433
+ except Exception as e:
434
+ return None, f"Error: {str(e)}\n"
435
+
436
+ # Function to handle chat interaction
437
+ def run_chat(message, history):
438
+ global terminal_history
439
+ if message.startswith("!"):
440
+ command = message[1:]
441
+ terminal_history = run_terminal_command(command, history)
442
+ else:
443
+ model_index = 0 # Select the model to use for chat response
444
+ response = get_nlp_response(message, model_index)
445
+ if response:
446
+ return history, terminal_history + f"User: {message}\nAssistant: {response}"
447
+ else:
448
+ return history, terminal_history + f"User: {message}\nAssistant: I'm sorry, I couldn't generate a response. Please try again.\n"
449
+
450
+ # Gradio Interface
451
+ with gr.Blocks() as iface:
452
+ gr.Markdown("# Sequential App Builder")
453
+
454
+ with gr.Row():
455
+ current_step = gr.Markdown(app_process.get_current_step_info())
456
+
457
+ with gr.Row():
458
+ prev_button = gr.Button("Previous Step")
459
+ next_button = gr.Button("Next Step")
460
+
461
+ # Step 1: App Initialization
462
+ with gr.Group() as step1:
463
+ app_name_input = gr.Textbox(label="Enter App Name")
464
+ init_app_button = gr.Button("Initialize App")
465
+
466
+ # Step 2: Component Addition
467
+ with gr.Group() as step2:
468
+ component_type = gr.Dropdown(choices=list(components_registry.keys()), label="Select Component Type")
469
+ add_component_button = gr.Button("Add Component")
470
+ components_display = gr.HTML()
471
+
472
+ # Step 3: Property Configuration
473
+ with gr.Group() as step3:
474
+ component_id = gr.Number(label="Component ID")
475
+ property_name = gr.Textbox(label="Property Name")
476
+ property_value = gr.Textbox(label="Property Value")
477
+ set_property_button = gr.Button("Set Property")
478
+
479
+ # Step 4: Code Generation
480
+ with gr.Group() as step4:
481
+ generated_code = gr.Code(language="python")
482
+ generate_code_button = gr.Button("Generate Code")
483
+
484
+ # Step 5: Deployment
485
+ with gr.Group() as step5:
486
+ deploy_button = gr.Button("Deploy to Hugging Face Spaces")
487
+ deployment_status = gr.Markdown()
488
+
489
+ # Chat and Terminal (optional, can be hidden or shown based on preference)
490
+ with gr.Accordion("Advanced", open=False):
491
+ chat_history = gr.Chatbot(label="Chat with Agent")
492
+ chat_input = gr.Textbox(label="Your Message")
493
+ chat_button = gr.Button("Send")
494
+
495
+ terminal_output = gr.Textbox(lines=8, label="Terminal", value=terminal_history)
496
+ terminal_input = gr.Textbox(label="Enter Command")
497
+ terminal_button = gr.Button("Run")
498
+
499
  # App Creation Process Class
500
  class AppCreationProcess:
501
  def __init__(self):