mgbam commited on
Commit
88f811c
Β·
verified Β·
1 Parent(s): 50d96bd

Update deployer/gradio_generator.py

Browse files
Files changed (1) hide show
  1. deployer/gradio_generator.py +77 -104
deployer/gradio_generator.py CHANGED
@@ -1,117 +1,90 @@
1
- # gradio_generator.py - CPU & Spaces-compatible Gradio interface with HF Inference API for STT & Monetization
2
-
3
  import os
4
- import json
5
- import requests
6
  import gradio as gr
7
- from deployer.simulator_interface import VirtualRobot
8
- from deployer.revenue_tracker import get_revenue_stats, package_artifacts
9
  from core_creator.voice_to_app import VoiceToAppCreator
 
 
10
 
11
- # Hugging Face Inference API settings
12
- HF_STT_URL = "https://api-inference.huggingface.co/models/openai/whisper-small"
13
- HK_API_KEY = os.getenv("HK_API_KEY")
14
- if not HK_API_KEY:
15
- raise EnvironmentError(
16
- "Please set the HK_API_KEY environment variable for HuggingFace Inference API.")
17
- HEADERS = {"Authorization": f"Bearer {HK_API_KEY}"}
18
-
19
- # Core robot logic
20
- def robot_behavior(user_input: str) -> str:
21
- bot = VirtualRobot()
22
- text = user_input.strip().lower()
23
- if any(greet in text for greet in ["hello", "hi", "hey", "welcome"]):
24
- return bot.perform_action("wave") + "\n" + bot.perform_action("say Hello there!")
25
- if text.startswith("say "):
26
- return bot.perform_action(text)
27
- return bot.perform_action("say I'm sorry, I didn't understand that.")
28
-
29
- # Transcribe via Hugging Face Inference API
30
- def transcribe_audio(audio_file: str) -> str:
31
- with open(audio_file, "rb") as f:
32
- data = f.read()
33
- response = requests.post(HF_STT_URL, headers=HEADERS, data=data)
34
- if response.status_code != 200:
35
- return f"❗ Transcription error: {response.status_code}"
36
- result = response.json()
37
- return result.get("text", "")
38
-
39
- # Combined flow
40
- def transcribe_and_respond(audio_file: str) -> str:
41
- text = transcribe_audio(audio_file)
42
- return robot_behavior(text)
43
-
44
- # Package generation pipeline
45
- def on_generate(i: str):
46
- creator = VoiceToAppCreator(i)
47
  assets = creator.run_pipeline()
48
- zip_path = package_artifacts(assets)
49
- blueprint = assets.get("blueprint", {})
50
- code_files = assets.get("code", {})
51
- code_preview = "\n\n".join([f"# {fname}\n{content}" for fname, content in code_files.items()])
52
- return (
53
- "βœ… App generated successfully!",
54
- zip_path,
55
- blueprint,
56
- code_preview
57
- )
58
-
59
- # Build full-featured Gradio app
60
- def launch_gradio_app(
61
- title: str = "RoboSage App",
62
- description: str = "Your robot, your voice, monetized."
63
- ) -> gr.Blocks:
64
- with gr.Blocks() as demo:
65
- gr.Markdown(f"# πŸš€ {title}\n\n{description}")
66
-
67
- # 1. Generate & Download Artifacts
68
- with gr.Accordion("🎨 Generate App & Download Artifacts", open=True):
69
- idea = gr.Textbox(label="Robot Idea", placeholder="e.g. A friendly greeting robot.")
70
- gen_btn = gr.Button("Generate & Package", key="gen-app-btn")
71
- status = gr.Textbox(label="Generation Status", interactive=False)
72
- download_zip = gr.File(label="Download Artifacts (.zip)")
73
- blueprint_view = gr.JSON(label="App Blueprint")
74
- code_view = gr.Code(label="Generated Code Preview", language="python")
 
 
 
 
 
 
 
 
 
75
  gen_btn.click(
76
- fn=on_generate,
77
- inputs=[idea],
78
- outputs=[status, download_zip, blueprint_view, code_view]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  )
 
 
80
 
81
- # Browse artifacts directory
82
- gr.Markdown("**Browse Generated Artifacts**")
83
- files_browser = gr.File(
84
- label="Artifacts Directory",
85
- file_count="multiple",
86
- file_types=None,
87
- value="/data"
88
  )
89
 
90
- # 2. Robot Simulation (Text & Voice)
91
- with gr.Accordion("πŸ€– Test Your Robot", open=False):
92
- text_input = gr.Textbox(label="Text Command", placeholder="Type 'hello' or 'say Good job!'" )
93
- text_btn = gr.Button("Send Text", key="send-text-btn")
94
- text_output = gr.Textbox(label="Robot Response", lines=3, interactive=False)
95
- text_btn.click(fn=robot_behavior, inputs=[text_input], outputs=[text_output])
96
-
97
- gr.Markdown("---")
98
-
99
- audio_input = gr.Audio(source="microphone", type="filepath", label="Record Command")
100
- audio_btn = gr.Button("Send Audio", key="send-audio-btn")
101
- audio_output = gr.Textbox(label="Robot Response (via voice)", lines=3, interactive=False)
102
- audio_btn.click(fn=transcribe_and_respond, inputs=[audio_input], outputs=[audio_output])
103
-
104
- # 3. Monetization & Revenue Dashboard
105
- with gr.Accordion("πŸ’° Monetization Dashboard", open=False):
106
- subscribe_btn = gr.Button("Subscribe to Pro Plan", key="subscribe-btn")
107
- subscribe_msg = gr.Textbox(label="Subscription Status", interactive=False)
108
- rev_btn = gr.Button("View Revenue Stats", key="rev-stats-btn")
109
- rev_table = gr.Dataframe(label="Revenue & Usage Metrics")
110
- subscribe_btn.click(fn=lambda: "βœ… Subscribed!", inputs=None, outputs=[subscribe_msg])
111
- rev_btn.click(fn=get_revenue_stats, inputs=None, outputs=[rev_table])
112
 
113
  return demo
114
 
115
- if __name__ == "__main__":
116
- app = launch_gradio_app()
117
- app.launch()
 
 
1
+ import asyncio
 
2
  import os
3
+ import shutil
 
4
  import gradio as gr
5
+
 
6
  from core_creator.voice_to_app import VoiceToAppCreator
7
+ from deployer.simulator_interface import VirtualRobot
8
+ from deployer.revenue_tracker import package_artifacts
9
 
10
+ # Async pipeline runner for generating the robot app
11
+ async def run_pipeline_async(idea: str) -> str:
12
+ creator = VoiceToAppCreator(idea)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  assets = creator.run_pipeline()
14
+ title = assets.get("blueprint", {}).get("title", "<unknown>")
15
+ return title
16
+
17
+ # Synchronous wrapper for Gradio
18
+ def generate_app(idea: str) -> str:
19
+ title = asyncio.run(run_pipeline_async(idea))
20
+ return f"βœ… Generated app: {title}"
21
+
22
+ # Package artifacts into a ZIP and return the path
23
+ def get_app_zip() -> str:
24
+ # package_artifacts should return the absolute path to the ZIP
25
+ zip_path = package_artifacts()
26
+ if not os.path.isfile(zip_path):
27
+ raise FileNotFoundError(f"Expected ZIP at {zip_path}, but not found.")
28
+ return zip_path
29
+
30
+ # Simulated robot behavior
31
+ def robot_behavior(command: str) -> str:
32
+ return VirtualRobot().perform_action(command)
33
+
34
+ # Launch the Gradio interface
35
+ def launch_gradio_app():
36
+ with gr.Blocks(css=".gradio-container { width: 800px; margin: auto; }
37
+ .section { margin-bottom: 20px; }") as demo:
38
+ gr.Markdown("# πŸš€ RoboSage\nGenerate your custom robot app and test it live.")
39
+
40
+ with gr.Group(elem_id="generate-app"), gr.Box():
41
+ gr.Markdown("## 1️⃣ Generate App")
42
+ idea_input = gr.Textbox(
43
+ label="Your Robot Idea",
44
+ placeholder="e.g. A friendly greeting robot",
45
+ lines=1
46
+ )
47
+ gen_btn = gr.Button("Generate App")
48
+ status_output = gr.Textbox(label="Status", interactive=False)
49
+
50
  gen_btn.click(
51
+ fn=generate_app,
52
+ inputs=[idea_input],
53
+ outputs=[status_output]
54
+ )
55
+
56
+ with gr.Group(elem_id="download-app"), gr.Box():
57
+ gr.Markdown("## πŸ“¦ Download Packaged App")
58
+ dl_btn = gr.Button("Download App ZIP")
59
+ dl_file = gr.File(label="App ZIP File")
60
+
61
+ dl_btn.click(
62
+ fn=get_app_zip,
63
+ inputs=None,
64
+ outputs=[dl_file]
65
+ )
66
+
67
+ with gr.Group(elem_id="robot-sim"), gr.Box():
68
+ gr.Markdown("## 2️⃣ Robot Simulator")
69
+ cmd_input = gr.Textbox(
70
+ label="Command",
71
+ placeholder="hello or say You rock!",
72
+ lines=1
73
  )
74
+ sim_btn = gr.Button("Send")
75
+ sim_output = gr.Textbox(label="Robot Response", lines=4, interactive=False)
76
 
77
+ sim_btn.click(
78
+ fn=robot_behavior,
79
+ inputs=[cmd_input],
80
+ outputs=[sim_output]
 
 
 
81
  )
82
 
83
+ demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  return demo
86
 
87
+
88
+ # Expose interface for external imports
89
+ robot_behavior = robot_behavior
90
+ launch_gradio_app = launch_gradio_app