datbkpro commited on
Commit
6c27998
·
verified ·
1 Parent(s): 3dde460

Update ui/tabs.py

Browse files
Files changed (1) hide show
  1. ui/tabs.py +47 -80
ui/tabs.py CHANGED
@@ -49,58 +49,51 @@ def create_all_tabs(audio_service: AudioService, chat_service: ChatService,
49
  with gr.Tab("Stream Object Detection"):
50
  create_streaming_object_detection()
51
  def create_voice_coding_tab(voice_coding_service):
52
- """Tạo tab Voice Coding với FastRTC"""
53
-
54
- # Tạo stream
55
- stream = voice_coding_service.create_stream()
56
 
57
  with gr.Blocks() as coding_tab:
58
- gr.Markdown("## 🦙 Voice Coding - Lập trình bằng giọng nói")
59
- gr.Markdown("Tạo và chỉnh sửa ứng dụng HTML single-file chỉ bằng giọng nói!")
60
 
61
  # State variables
62
- history = gr.State([{"role": "system", "content": "You are an AI coding assistant."}])
63
  current_code = gr.State("")
64
- status_message = gr.State("Sẵn sàng...")
65
 
66
  with gr.Row():
67
  with gr.Column(scale=1):
68
- gr.Markdown("### 🎤 Hướng dẫn sử dụng:")
69
  gr.Markdown("""
70
- 1. Nhấn **Bắt đầu Recording**
71
- 2. Nói "Hello Llama" hoặc "Code"
72
- 3. Đưa ra yêu cầu lập trình của bạn
73
- 4. Mỗi phiên giới hạn 90 giây
74
-
75
- **Ví dụ:**
76
  - "Tạo trang web hello world"
77
- - "Tạo calculator bằng HTML"
78
  - "Tạo đồng hồ digital"
 
 
 
79
  """)
80
 
81
- # FastRTC component
82
- fastrtc_audio = stream.ui()
 
 
 
 
83
 
84
- # Manual input
85
- with gr.Accordion("📝 Nhập text thủ công", open=True):
86
- text_input = gr.Textbox(
87
- label="Yêu cầu lập trình",
88
- placeholder="Ví dụ: Tạo trang web hello world với màu nền xanh...",
89
- lines=3
90
- )
91
- text_submit_btn = gr.Button("🚀 Generate Code", variant="primary")
92
 
93
- # Status display
94
  status_display = gr.Textbox(
95
  label="Trạng thái",
96
  value="Sẵn sàng...",
97
  interactive=False
98
  )
99
 
100
- # Controls
101
- with gr.Row():
102
- clear_btn = gr.Button("🗑️ Xóa hội thoại")
103
- reset_btn = gr.Button("🔄 Reset Code")
104
 
105
  with gr.Column(scale=2):
106
  with gr.Tabs():
@@ -126,15 +119,15 @@ def create_voice_coding_tab(voice_coding_service):
126
  height=400
127
  )
128
 
129
- # Event handlers cho manual input
130
- def generate_from_text(text, current_history, current_code_value):
131
  """Generate code từ text input"""
132
  if not text.strip():
133
- return current_history, current_code_value, current_history, "Vui lòng nhập yêu cầu", voice_coding_service.sandbox_html
134
 
135
  try:
136
  # Tạo prompt
137
- user_prompt = f"Please write a single-file HTML application to fulfill the following request.\nThe message:{text}\nCurrent code you have written:{current_code_value}"
138
 
139
  # Update history
140
  new_history = current_history + [
@@ -143,11 +136,11 @@ def create_voice_coding_tab(voice_coding_service):
143
 
144
  # Generate code với Groq
145
  response = voice_coding_service.groq_client.chat.completions.create(
146
- model="llama-3.3-70b-versatile",
147
  messages=new_history,
148
- temperature=1,
149
- max_tokens=2048,
150
- top_p=1,
151
  stream=False,
152
  )
153
 
@@ -155,8 +148,6 @@ def create_voice_coding_tab(voice_coding_service):
155
 
156
  # Extract HTML
157
  html_code = voice_coding_service.extract_html_content(output)
158
- if not html_code:
159
- html_code = f"<!-- Generated Code -->\n{output}"
160
 
161
  # Update history
162
  new_history.append({"role": "assistant", "content": output})
@@ -164,30 +155,32 @@ def create_voice_coding_tab(voice_coding_service):
164
  # Update sandbox
165
  sandbox_html = voice_coding_service.display_in_sandbox(html_code)
166
 
167
- return new_history, html_code, new_history, "✅ Đã generate code!", sandbox_html
168
 
169
  except Exception as e:
170
- return current_history, current_code_value, current_history, f"❌ Lỗi: {str(e)}", voice_coding_service.sandbox_html
 
171
 
172
  def update_sandbox(code):
173
  """Cập nhật sandbox khi code thay đổi"""
174
  return voice_coding_service.display_in_sandbox(code)
175
 
176
- def clear_conversation():
177
- """Xóa hội thoại"""
178
- return [{"role": "system", "content": "You are an AI coding assistant."}], "", [], "Đã xóa hội thoại", voice_coding_service.sandbox_html
 
179
 
180
- def reset_code():
181
- """Reset code"""
182
- return "", voice_coding_service.sandbox_html, "Đã reset code"
183
 
184
  # Kết nối events
185
- text_submit_btn.click(
186
- generate_from_text,
187
  inputs=[text_input, history, current_code],
188
  outputs=[history, current_code, chat_display, status_display, sandbox]
189
  ).then(
190
- lambda: "", # Clear text input
191
  outputs=[text_input]
192
  )
193
 
@@ -198,37 +191,11 @@ def create_voice_coding_tab(voice_coding_service):
198
  )
199
 
200
  clear_btn.click(
201
- clear_conversation,
202
- outputs=[history, current_code, chat_display, status_display, sandbox]
203
- )
204
-
205
- reset_btn.click(
206
- reset_code,
207
- outputs=[current_code, sandbox, status_display]
208
- )
209
-
210
- # FastRTC additional outputs handling
211
- def handle_fastrtc_outputs(output_data):
212
- """Xử lý outputs từ FastRTC"""
213
- if hasattr(output_data, 'args'):
214
- data = output_data.args[0] if output_data.args else {}
215
-
216
- if data.get('type') == 'code_generated':
217
- return data.get('history', []), data.get('code', ''), data.get('history', []), data.get('message', ''), voice_coding_service.display_in_sandbox(data.get('code', ''))
218
- elif data.get('type') == 'loading':
219
- return data.get('history', []), data.get('code', ''), data.get('history', []), data.get('message', ''), voice_coding_service.loading_html
220
- elif data.get('type') == 'error':
221
- return data.get('history', []), data.get('code', ''), data.get('history', []), data.get('message', ''), voice_coding_service.sandbox_html
222
-
223
- return history.value, current_code.value, chat_display.value, status_display.value, sandbox.value
224
-
225
- # Kết nối FastRTC outputs
226
- fastrtc_audio.on_additional_outputs(
227
- handle_fastrtc_outputs,
228
  outputs=[history, current_code, chat_display, status_display, sandbox]
229
  )
230
 
231
- return coding_tab
232
  def create_openai_realtime_tab(hybrid_service: HybridStreamingService):
233
  """Tạo tab cho OpenAI Realtime API"""
234
 
 
49
  with gr.Tab("Stream Object Detection"):
50
  create_streaming_object_detection()
51
  def create_voice_coding_tab(voice_coding_service):
52
+ """Tạo tab Voice Coding đơn giản - Text-based trước"""
 
 
 
53
 
54
  with gr.Blocks() as coding_tab:
55
+ gr.Markdown("## 🦙 Voice Coding - Lập trình bằng AI")
56
+ gr.Markdown("Tạo và chỉnh sửa ứng dụng HTML single-file với AI Assistant")
57
 
58
  # State variables
59
+ history = gr.State([{"role": "system", "content": "You are an AI coding assistant. Help create HTML applications."}])
60
  current_code = gr.State("")
 
61
 
62
  with gr.Row():
63
  with gr.Column(scale=1):
64
+ gr.Markdown("### 🎯 Hướng dẫn sử dụng:")
65
  gr.Markdown("""
66
+ **Nhập yêu cầu lập trình:**
 
 
 
 
 
67
  - "Tạo trang web hello world"
68
+ - "Tạo calculator bằng HTML/CSS/JS"
69
  - "Tạo đồng hồ digital"
70
+ - "Tạo form đăng ký với validation"
71
+
72
+ **Chức năng voice đang được phát triển**
73
  """)
74
 
75
+ # Text input chính
76
+ text_input = gr.Textbox(
77
+ label="Yêu cầu lập trình",
78
+ placeholder="Ví dụ: Tạo trang web hello world với màu nền xanh và chữ màu trắng...",
79
+ lines=3
80
+ )
81
 
82
+ with gr.Row():
83
+ generate_btn = gr.Button("🚀 Generate Code", variant="primary", scale=2)
84
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary", scale=1)
 
 
 
 
 
85
 
86
+ # Status
87
  status_display = gr.Textbox(
88
  label="Trạng thái",
89
  value="Sẵn sàng...",
90
  interactive=False
91
  )
92
 
93
+ # FastRTC component (tạm ẩn)
94
+ with gr.Accordion("🎤 Voice Input (Experimental)", open=False):
95
+ gr.Markdown("Chức năng voice đang được phát triển...")
96
+ # fastrtc_audio = voice_coding_service.create_stream().ui()
97
 
98
  with gr.Column(scale=2):
99
  with gr.Tabs():
 
119
  height=400
120
  )
121
 
122
+ # Event handlers
123
+ def generate_code(text, current_history, current_code_value):
124
  """Generate code từ text input"""
125
  if not text.strip():
126
+ return current_history, current_code_value, current_history, "Vui lòng nhập yêu cầu", voice_coding_service.sandbox_html
127
 
128
  try:
129
  # Tạo prompt
130
+ user_prompt = f"Create a single-file HTML application for: {text}. Current code: {current_code_value}. Respond with complete HTML code only."
131
 
132
  # Update history
133
  new_history = current_history + [
 
136
 
137
  # Generate code với Groq
138
  response = voice_coding_service.groq_client.chat.completions.create(
139
+ model="llama-3.1-8b-instant",
140
  messages=new_history,
141
+ temperature=0.7,
142
+ max_tokens=1024,
143
+ top_p=0.9,
144
  stream=False,
145
  )
146
 
 
148
 
149
  # Extract HTML
150
  html_code = voice_coding_service.extract_html_content(output)
 
 
151
 
152
  # Update history
153
  new_history.append({"role": "assistant", "content": output})
 
155
  # Update sandbox
156
  sandbox_html = voice_coding_service.display_in_sandbox(html_code)
157
 
158
+ return new_history, html_code, new_history, "✅ Đã generate code thành công!", sandbox_html
159
 
160
  except Exception as e:
161
+ error_msg = f"❌ Lỗi: {str(e)}"
162
+ return current_history, current_code_value, current_history, error_msg, voice_coding_service.sandbox_html
163
 
164
  def update_sandbox(code):
165
  """Cập nhật sandbox khi code thay đổi"""
166
  return voice_coding_service.display_in_sandbox(code)
167
 
168
+ def clear_all():
169
+ """Xóa tất cả"""
170
+ empty_history = [{"role": "system", "content": "You are an AI coding assistant."}]
171
+ return empty_history, "", empty_history, "Đã xóa tất cả", voice_coding_service.sandbox_html
172
 
173
+ def clear_text():
174
+ """Xóa text input"""
175
+ return ""
176
 
177
  # Kết nối events
178
+ generate_btn.click(
179
+ generate_code,
180
  inputs=[text_input, history, current_code],
181
  outputs=[history, current_code, chat_display, status_display, sandbox]
182
  ).then(
183
+ clear_text,
184
  outputs=[text_input]
185
  )
186
 
 
191
  )
192
 
193
  clear_btn.click(
194
+ clear_all,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  outputs=[history, current_code, chat_display, status_display, sandbox]
196
  )
197
 
198
+ return coding_tab
199
  def create_openai_realtime_tab(hybrid_service: HybridStreamingService):
200
  """Tạo tab cho OpenAI Realtime API"""
201