GitHub Action commited on
Commit
c383152
·
1 Parent(s): 6e4938d

Sync ling-space changes from GitHub commit 8d05d99

Browse files
README.md CHANGED
@@ -16,3 +16,14 @@ secrets:
16
  # Ling Space
17
 
18
  这是一个用于与 Ling 系列模型进行交互的 Gradio 应用。
 
 
 
 
 
 
 
 
 
 
 
 
16
  # Ling Space
17
 
18
  这是一个用于与 Ling 系列模型进行交互的 Gradio 应用。
19
+
20
+ ## 本地开发 (Local Development)
21
+
22
+ 为了方便本地开发,本项目提供了一个基于 `watchfiles` 的热重载开发服务器。当代码文件发生变化时,应用会自动重启,无需手动干预。
23
+
24
+ 要启动开发服务器,请在 `ling-space/` 目录下运行:
25
+
26
+ ```bash
27
+ python run_dev_server.py
28
+ ```
29
+
app.py CHANGED
@@ -1,55 +1,94 @@
1
  import gradio as gr
2
- import uuid
3
  import logging
 
4
  from datetime import datetime
5
- from gradio.analytics import ANALYTICS_URL
6
  import pandas as pd
 
7
  from model_handler import ModelHandler
8
  from tab_chat import create_chat_tab
 
9
  from tab_code import create_code_tab
 
10
  from tab_smart_writer import create_smart_writer_tab
11
- from tab_test import run_model_handler_test, run_clear_chat_test
 
 
12
 
13
  # Configure logging
14
  logging.basicConfig(
15
- level=logging.INFO,
16
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
17
  )
18
  logger = logging.getLogger(__name__)
19
 
20
- def get_history_df(history):
 
21
  if not history:
22
- return pd.DataFrame({'ID': [], '对话': []})
 
 
23
  df = pd.DataFrame(history)
24
- return df[['id', 'title']].rename(columns={'id': 'ID', 'title': '对话'})
 
 
 
25
 
26
- def on_app_load(history, conv_id):
27
  """
28
  Handles the application's initial state on load.
29
- - If no history exists, creates a new conversation.
30
- - If the last conversation ID is invalid, loads the most recent one.
31
- - Otherwise, loads the last active conversation.
32
  """
 
 
 
 
 
 
 
 
 
33
  if not history:
34
- # First time ever loading, create a new chat
35
  conv_id = str(uuid.uuid4())
36
- new_convo = { "id": conv_id, "title": "(新对话)", "messages": [], "timestamp": datetime.now().isoformat() }
 
 
 
 
 
 
37
  history = [new_convo]
38
- return conv_id, history, gr.update(value=get_history_df(history)), []
 
 
 
 
 
 
39
 
40
- # Check if the last used conv_id is valid
41
  if conv_id and any(c["id"] == conv_id for c in history):
42
- # It's valid, load it
43
  for convo in history:
44
  if convo["id"] == conv_id:
45
- return conv_id, history, gr.update(value=get_history_df(history)), convo["messages"]
46
-
47
- # Last used conv_id is invalid or doesn't exist, load the most recent conversation
48
- most_recent_convo = history[0] # Assumes history is sorted by timestamp desc
49
- conv_id = most_recent_convo["id"]
50
- return conv_id, history, gr.update(value=get_history_df(history)), most_recent_convo["messages"]
51
-
52
-
 
 
 
 
 
 
 
 
 
 
 
53
  CSS = """
54
 
55
  #chatbot {
@@ -74,56 +113,188 @@ if __name__ == "__main__":
74
  logger.info("Starting Ling Space Application...")
75
  model_handler = ModelHandler()
76
 
77
- with gr.Blocks(analytics_enabled=False,
78
- fill_height=True,
79
- fill_width=True) as demo:
80
- with gr.Tabs(elem_id='indicator-space-app') as tabs:
 
 
81
 
82
- with gr.TabItem("文��聊天") as chat_tab:
83
- conversation_store, current_conversation_id, history_df, chatbot = create_chat_tab()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  chat_tab.select(
86
  fn=None,
87
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.chat')); console.log('this'); return null;}",
88
  )
89
 
90
- with gr.TabItem("代码生成") as code_tab:
91
- create_code_tab()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  code_tab.select(
94
  fn=None,
95
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.code')); return null;}",
96
  )
97
 
98
- with gr.TabItem("写作助手") as writer_tab:
99
- create_smart_writer_tab()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  writer_tab.select(
102
  fn=None,
103
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.writing')); return null;}",
104
  )
105
 
106
- with gr.TabItem("测试", visible=False):
107
- gr.Markdown("# 功能测试")
108
- with gr.Column():
109
- test_log_output = gr.Textbox(label="测试日志", interactive=False, lines=10)
110
- gr.Button("运行 ModelHandler 测试").click(run_model_handler_test, outputs=test_log_output)
111
- gr.Button("运行 清除聊天 测试").click(run_clear_chat_test, outputs=test_log_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- # Bind on_app_load to demo.load
114
  demo.load(
115
  on_app_load,
116
- inputs=[conversation_store, current_conversation_id],
117
- outputs=[current_conversation_id, conversation_store, history_df, chatbot],
118
- js="() => {window.dispatchEvent(new CustomEvent('appStart')); console.log('appStart'); return {};}"
 
 
 
 
 
 
119
  )
120
 
121
- demo.queue(default_concurrency_limit=32,
122
- max_size=128)
123
  # Launch the Gradio application
124
- demo.launch(theme=gr.themes.Default(),
 
125
  ssr_mode=False,
126
  max_threads=64,
127
  css=CSS,
128
  head="",
129
- head_paths=['./static/toastify.html', './static/app.html'])
 
 
1
  import gradio as gr
 
2
  import logging
3
+ import uuid
4
  from datetime import datetime
 
5
  import pandas as pd
6
+ from i18n import get_text
7
  from model_handler import ModelHandler
8
  from tab_chat import create_chat_tab
9
+ from tab_chat import update_language as update_chat_language
10
  from tab_code import create_code_tab
11
+ from tab_code import update_language as update_code_language
12
  from tab_smart_writer import create_smart_writer_tab
13
+ from tab_smart_writer import update_language as update_writer_language
14
+ from tab_welcome import create_welcome_tab
15
+ from tab_welcome import update_language as update_welcome_language
16
 
17
  # Configure logging
18
  logging.basicConfig(
19
+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
 
20
  )
21
  logger = logging.getLogger(__name__)
22
 
23
+
24
+ def get_history_df_from_app(history):
25
  if not history:
26
+ return pd.DataFrame(
27
+ {"ID": pd.Series(dtype="str"), "对话": pd.Series(dtype="str")}
28
+ )
29
  df = pd.DataFrame(history)
30
+ if "id" in df.columns and "title" in df.columns:
31
+ return df[["id", "title"]].rename(columns={"id": "ID", "对话": "对话"})
32
+ return pd.DataFrame({"ID": pd.Series(dtype="str"), "对话": pd.Series(dtype="str")})
33
+
34
 
35
+ def on_app_load(request: gr.Request, history, conv_id, current_lang_state):
36
  """
37
  Handles the application's initial state on load.
38
+ - Determines language from URL parameter.
39
+ - Loads conversation history or creates a new one.
 
40
  """
41
+ # --- Language Detection ---
42
+ query_params = dict(request.query_params)
43
+ url_lang = query_params.get("lang")
44
+
45
+ updated_lang = current_lang_state # Start with the default
46
+ if url_lang and url_lang in ["en", "zh"]:
47
+ updated_lang = url_lang
48
+
49
+ # --- History Loading Logic ---
50
  if not history:
51
+ # First time ever, create a new conversation
52
  conv_id = str(uuid.uuid4())
53
+ new_convo_title = get_text("chat_new_conversation_title", updated_lang)
54
+ new_convo = {
55
+ "id": conv_id,
56
+ "title": new_convo_title,
57
+ "messages": [],
58
+ "timestamp": datetime.now().isoformat(),
59
+ }
60
  history = [new_convo]
61
+ return (
62
+ conv_id,
63
+ history,
64
+ gr.update(value=get_history_df_from_app(history)),
65
+ [],
66
+ updated_lang,
67
+ )
68
 
 
69
  if conv_id and any(c["id"] == conv_id for c in history):
70
+ # Valid last session, load it
71
  for convo in history:
72
  if convo["id"] == conv_id:
73
+ return (
74
+ conv_id,
75
+ history,
76
+ gr.update(value=get_history_df_from_app(history)),
77
+ convo["messages"],
78
+ updated_lang,
79
+ )
80
+
81
+ # Fallback to most recent conversation
82
+ most_recent_convo = history[0]
83
+ return (
84
+ most_recent_convo["id"],
85
+ history,
86
+ gr.update(value=get_history_df_from_app(history)),
87
+ most_recent_convo["messages"],
88
+ updated_lang,
89
+ )
90
+
91
+
92
  CSS = """
93
 
94
  #chatbot {
 
113
  logger.info("Starting Ling Space Application...")
114
  model_handler = ModelHandler()
115
 
116
+ with gr.Blocks(analytics_enabled=False, fill_height=True, fill_width=True) as demo:
117
+ # Language State
118
+ current_lang_state = gr.State("en")
119
+
120
+ # --- Collect all components that need language updates ---
121
+ all_i18n_outputs = []
122
 
123
+ with gr.Tabs(elem_id="indicator-space-app") as tabs:
124
+ welcome_components = create_welcome_tab(current_lang_state.value)
125
+
126
+ # The order of components MUST be consistent
127
+ welcome_outputs = [
128
+ welcome_components["tab"],
129
+ welcome_components["header"],
130
+ welcome_components["description"],
131
+ welcome_components["chat_description"],
132
+ welcome_components["code_description"],
133
+ welcome_components["writer_description"],
134
+ welcome_components["lang_select_header"],
135
+ welcome_components["en_button"],
136
+ welcome_components["zh_button"],
137
+ ]
138
+ all_i18n_outputs.extend(welcome_outputs)
139
+
140
+ # --- Chat Tab ---
141
+ with gr.TabItem(
142
+ get_text("chat_tab_title", current_lang_state.value)
143
+ ) as chat_tab:
144
+ chat_components = create_chat_tab(
145
+ current_lang_state.value, current_lang_state
146
+ )
147
+
148
+ chat_outputs = [
149
+ chat_tab,
150
+ chat_components["new_chat_btn"],
151
+ chat_components["history_df"],
152
+ chat_components["chatbot"],
153
+ chat_components["textbox"],
154
+ chat_components["submit_btn"],
155
+ chat_components["recommended_title"],
156
+ chat_components["recommended_dataset"],
157
+ chat_components["system_prompt_textbox"],
158
+ chat_components["temperature_slider"],
159
+ ]
160
+ all_i18n_outputs.extend(chat_outputs)
161
 
162
  chat_tab.select(
163
  fn=None,
164
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.chat')); console.log('this'); return null;}",
165
  )
166
 
167
+ # --- Code Tab ---
168
+ with gr.TabItem(
169
+ get_text("code_tab_title", current_lang_state.value)
170
+ ) as code_tab:
171
+ code_components = create_code_tab(
172
+ current_lang_state.value, current_lang_state
173
+ )
174
+
175
+ code_outputs = [
176
+ code_tab,
177
+ code_components["prompt_input"],
178
+ code_components["overall_style_input"],
179
+ code_components["decoration_input"],
180
+ code_components["palette_display"],
181
+ code_components["generate_style_btn"],
182
+ code_components["examples_title"],
183
+ code_components["examples_dataset"],
184
+ code_components["generate_button"],
185
+ code_components["preview_tab"],
186
+ code_components["preview_header"],
187
+ code_components["source_code_tab"],
188
+ code_components["source_code_header"],
189
+ code_components["code_output"],
190
+ code_components["refresh_button"],
191
+ code_components["log_chatbot"],
192
+ code_components["js_error_channel"],
193
+ # fullscreen_button is updated in its own handler, so it's excluded here
194
+ ]
195
+ all_i18n_outputs.extend(code_outputs)
196
 
197
  code_tab.select(
198
  fn=None,
199
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.code')); return null;}",
200
  )
201
 
202
+ # --- Writer Tab ---
203
+ with gr.TabItem(
204
+ get_text("writer_tab_title", current_lang_state.value)
205
+ ) as writer_tab:
206
+ writer_components = create_smart_writer_tab(current_lang_state.value)
207
+
208
+ writer_outputs = [
209
+ writer_tab,
210
+ writer_components["style_input"],
211
+ writer_components["kb_accordion"],
212
+ writer_components["kb_input"],
213
+ writer_components["btn_suggest_kb"],
214
+ writer_components["suggested_kb_dataframe"],
215
+ writer_components["short_outline_accordion"],
216
+ writer_components["short_outline_input"],
217
+ writer_components["btn_sync_outline"],
218
+ writer_components["long_outline_accordion"],
219
+ writer_components["long_outline_input"],
220
+ writer_components["flow_suggestion_display"],
221
+ writer_components["btn_accept_flow"],
222
+ writer_components["btn_change_flow"],
223
+ writer_components["inspiration_prompt_input"],
224
+ writer_components["prompt_suggestions_dataset"],
225
+ writer_components["refresh_suggestions_btn"],
226
+ writer_components["btn_generate_para"],
227
+ writer_components["btn_change_para"],
228
+ writer_components["btn_accept_para"],
229
+ writer_components["para_suggestion_display"],
230
+ writer_components["polish_title"],
231
+ writer_components["polish_soon"],
232
+ writer_components["stats_display"],
233
+ writer_components["editor"],
234
+ ]
235
+ all_i18n_outputs.extend(writer_outputs)
236
 
237
  writer_tab.select(
238
  fn=None,
239
  js="() => {window.dispatchEvent(new CustomEvent('tabSelect.writing')); return null;}",
240
  )
241
 
242
+ # --- Language Change Handler ---
243
+ def on_language_change(lang):
244
+ # Dispatch updates for each tab
245
+ welcome_updates = update_welcome_language(lang, welcome_components)
246
+ chat_updates = update_chat_language(lang, chat_components)
247
+ chat_updates[chat_tab] = gr.update(label=get_text("chat_tab_title", lang))
248
+
249
+ code_updates = update_code_language(lang, code_components)
250
+ code_updates[code_tab] = gr.update(label=get_text("code_tab_title", lang))
251
+
252
+ writer_updates = update_writer_language(lang, writer_components)
253
+ writer_updates[writer_tab] = gr.update(
254
+ label=get_text("writer_tab_title", lang)
255
+ )
256
+
257
+ all_updates = {
258
+ **welcome_updates,
259
+ **chat_updates,
260
+ **code_updates,
261
+ **writer_updates,
262
+ }
263
+ return tuple(all_updates.get(comp) for comp in all_i18n_outputs)
264
+
265
+ current_lang_state.change(
266
+ fn=on_language_change,
267
+ inputs=[current_lang_state],
268
+ outputs=all_i18n_outputs,
269
+ show_progress="hidden",
270
+ )
271
+
272
+ # --- App Load Handler ---
273
+ conversation_store = chat_components["conversation_store"]
274
+ current_conversation_id = chat_components["current_conversation_id"]
275
+ history_df = chat_components["history_df"]
276
+ chatbot = chat_components["chatbot"]
277
 
 
278
  demo.load(
279
  on_app_load,
280
+ inputs=[conversation_store, current_conversation_id, current_lang_state],
281
+ outputs=[
282
+ current_conversation_id,
283
+ conversation_store,
284
+ history_df,
285
+ chatbot,
286
+ current_lang_state,
287
+ ],
288
+ js="() => {window.dispatchEvent(new CustomEvent('appStart')); console.log('appStart'); return {};}",
289
  )
290
 
291
+ demo.queue(default_concurrency_limit=32, max_size=128)
 
292
  # Launch the Gradio application
293
+ demo.launch(
294
+ theme=gr.themes.Default(),
295
  ssr_mode=False,
296
  max_threads=64,
297
  css=CSS,
298
  head="",
299
+ head_paths=["./static/toastify.html", "./static/app.html"],
300
+ )
i18n/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/__init__.py
2
+ from .core import I18nManager
3
+ import gradio as gr
4
+
5
+ # Global instance
6
+ i18n_manager = I18nManager()
7
+
8
+ # Helper function to access translations easily if needed in Python
9
+ def get_text(key: str, lang_state: str | gr.State) -> str:
10
+ lang = lang_state.value if isinstance(lang_state, gr.State) else lang_state
11
+ return i18n_manager.get(key, lang, default=key)
12
+
13
+ # Expose the dictionaries for frontend injection
14
+ def get_ui_translations():
15
+ return i18n_manager.get_all_ui_translations()
i18n/common.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/common.py
2
+
3
+ ui_translations = {
4
+ # Common UI elements (Fallback/Generic)
5
+ "tab_chat": {
6
+ "en": "Chat",
7
+ "zh": "文本聊天"
8
+ },
9
+ "tab_code": {
10
+ "en": "Code",
11
+ "zh": "代码生成"
12
+ },
13
+ "tab_writer": {
14
+ "en": "Writer",
15
+ "zh": "写作助手"
16
+ },
17
+ "tab_test": {
18
+ "en": "Test",
19
+ "zh": "测试"
20
+ },
21
+ "new_conversation_title": {
22
+ "en": "(New Conversation)",
23
+ "zh": "(新对话)"
24
+ }
25
+ }
26
+
27
+ prompt_fragments = {}
i18n/core.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/core.py
2
+ from typing import Dict
3
+ from . import common, tab_chat, tab_code, tab_smart_writer, tab_welcome
4
+
5
+ MODULES = [common, tab_chat, tab_code, tab_smart_writer, tab_welcome]
6
+
7
+ class I18nManager:
8
+ def __init__(self):
9
+ self.ui_translations: Dict[str, Dict[str, str]] = {}
10
+ self.prompt_fragments: Dict[str, Dict[str, str]] = {}
11
+ self._load_translations()
12
+
13
+ def _load_translations(self):
14
+ """
15
+ Load and merge translations from all registered modules.
16
+ Structure:
17
+ {
18
+ "key_name": {
19
+ "en": "English Text",
20
+ "zh": "中文文本"
21
+ },
22
+ ...
23
+ }
24
+ """
25
+ for module in MODULES:
26
+ # Merge UI Translations
27
+ if hasattr(module, "ui_translations"):
28
+ for key, trans_map in module.ui_translations.items():
29
+ if key in self.ui_translations:
30
+ print(f"[I18n] Warning: Duplicate UI key '{key}' in {module}. Overwriting.")
31
+ self.ui_translations[key] = trans_map
32
+
33
+ # Merge Prompt Fragments
34
+ if hasattr(module, "prompt_fragments"):
35
+ for key, trans_map in module.prompt_fragments.items():
36
+ if key in self.prompt_fragments:
37
+ print(f"[I18n] Warning: Duplicate prompt key '{key}' in {module}. Overwriting.")
38
+ self.prompt_fragments[key] = trans_map
39
+
40
+ def get_all_ui_translations(self) -> Dict[str, Dict[str, str]]:
41
+ """Returns the complete dictionary for UI translations."""
42
+ return self.ui_translations
43
+
44
+ def get_all_prompt_translations(self) -> Dict[str, Dict[str, str]]:
45
+ """Returns the complete dictionary for prompt fragments."""
46
+ return self.prompt_fragments
47
+
48
+ def get(self, key: str, lang: str, default: str) -> str:
49
+ """
50
+ Get a specific translation.
51
+ Checks UI translations first, then prompt fragments.
52
+ """
53
+ # Check UI dict
54
+ if key in self.ui_translations:
55
+ return self.ui_translations[key].get(lang, default or self.ui_translations[key].get("en", key))
56
+
57
+ # Check Prompt dict
58
+ if key in self.prompt_fragments:
59
+ return self.prompt_fragments[key].get(lang, default or self.prompt_fragments[key].get("en", key))
60
+
61
+ return default or key
i18n/tab_chat.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i1n/tab_chat.py
2
+
3
+ ui_translations = {
4
+ # Tab Name (used in app.py)
5
+ "chat_tab_title": {
6
+ "en": "Chat",
7
+ "zh": "文本聊天"
8
+ },
9
+ # Components
10
+ "chat_new_chat_button": {
11
+ "en": "➕ New Chat",
12
+ "zh": "➕ 新对话"
13
+ },
14
+ "chat_history_dataframe_header": {
15
+ "en": "History",
16
+ "zh": "对话记录"
17
+ },
18
+ "chat_chatbot_placeholder": {
19
+ "en": "Enter message...",
20
+ "zh": "输入消息..."
21
+ },
22
+ "chat_textbox_placeholder": {
23
+ "en": "Enter message...",
24
+ "zh": "输入消息..."
25
+ },
26
+ "chat_submit_button": {
27
+ "en": "Send",
28
+ "zh": "发送"
29
+ },
30
+ "chat_recommended_dialogues_title": {
31
+ "en": "### Recommended Dialogues",
32
+ "zh": "### 推荐对话"
33
+ },
34
+ "chat_recommended_dataset_label": {
35
+ "en": "Recommended Scenarios",
36
+ "zh": "推荐场景"
37
+ },
38
+ "chat_recommended_dataset_header": {
39
+ "en": "Try a scenario",
40
+ "zh": "选择一个场景试试"
41
+ },
42
+ "chat_system_prompt_label": {
43
+ "en": "System Prompt",
44
+ "zh": "系统提示词"
45
+ },
46
+ "chat_system_prompt_placeholder": {
47
+ "en": "Enter system prompt...",
48
+ "zh": "输入系统提示词..."
49
+ },
50
+ "chat_temperature_slider_label": {
51
+ "en": "Temperature",
52
+ "zh": "温度参数"
53
+ },
54
+
55
+ # Logic-related text
56
+ "chat_new_conversation_title": {
57
+ "en": "(New Conversation)",
58
+ "zh": "(新对话)"
59
+ }
60
+ }
61
+
62
+ # Prompt fragments can be added here later if needed
63
+ prompt_fragments = {}
i18n/tab_code.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/tab_code.py
2
+
3
+ ui_translations = {
4
+ # Tab Name (used in app.py)
5
+ "code_tab_title": {
6
+ "en": "Code Generation",
7
+ "zh": "代码生成"
8
+ },
9
+ # Components
10
+ "code_prompt_label": {
11
+ "en": "Prompt",
12
+ "zh": "提示词"
13
+ },
14
+ "code_prompt_placeholder": {
15
+ "en": "e.g., create a simple page with a title and a button",
16
+ "zh": "例如:创建一个带标题和按钮的简单页面"
17
+ },
18
+ "code_overall_style_label": {
19
+ "en": "Overall Style",
20
+ "zh": "整体风格"
21
+ },
22
+ "code_overall_style_placeholder": {
23
+ "en": "e.g., like a parchment book",
24
+ "zh": "例如:类似一本羊皮纸的书"
25
+ },
26
+ "code_decoration_style_label": {
27
+ "en": "Decoration Style",
28
+ "zh": "装饰风格"
29
+ },
30
+ "code_decoration_style_placeholder": {
31
+ "en": "e.g., thick borders, no rounded corners",
32
+ "zh": "例如:粗边框,无圆角"
33
+ },
34
+ "code_palette_label": {
35
+ "en": "Style Palette",
36
+ "zh": "风格色板"
37
+ },
38
+ "code_palette_placeholder": {
39
+ "en": "(Displays after generating style)",
40
+ "zh": "(生成风格后展示)"
41
+ },
42
+ "code_generate_style_button": {
43
+ "en": "🎲 Generate Random Style",
44
+ "zh": "🎲 随机生成风格"
45
+ },
46
+ "code_examples_title": {
47
+ "en": "### Examples",
48
+ "zh": "### 示例"
49
+ },
50
+ "code_examples_dataset_label": {
51
+ "en": "Examples",
52
+ "zh": "示例"
53
+ },
54
+ "code_examples_dataset_header": {
55
+ "en": "Select an example",
56
+ "zh": "选择一个示例"
57
+ },
58
+ "code_generate_code_button": {
59
+ "en": "Generate Code",
60
+ "zh": "生成代码"
61
+ },
62
+ "code_preview_tab_title": {
63
+ "en": "Live Preview",
64
+ "zh": "实时预览"
65
+ },
66
+ "code_preview_header": {
67
+ "en": "### Live Preview",
68
+ "zh": "### 实时预览"
69
+ },
70
+ "code_fullscreen_button": {
71
+ "en": "Fullscreen",
72
+ "zh": "全屏预览"
73
+ },
74
+ "code_exit_fullscreen_button": {
75
+ "en": "Exit Fullscreen",
76
+ "zh": "退出全屏"
77
+ },
78
+ "code_preview_placeholder": {
79
+ "en": "<p>Preview will be displayed here.</p>",
80
+ "zh": "<p>预览将在此处显示。</p>"
81
+ },
82
+ "code_source_code_tab_title": {
83
+ "en": "Generated Source Code",
84
+ "zh": "生成的源代码"
85
+ },
86
+ "code_source_code_header": {
87
+ "en": "### Generated Source Code",
88
+ "zh": "### 生成的源代码"
89
+ },
90
+ "code_source_code_label": {
91
+ "en": "Generated Code",
92
+ "zh": "生成的代码"
93
+ },
94
+ "code_refresh_preview_button": {
95
+ "en": "Refresh Preview",
96
+ "zh": "刷新预览"
97
+ },
98
+ "code_log_chatbot_label": {
99
+ "en": "Generation Log",
100
+ "zh": "生成日志"
101
+ },
102
+ "code_debug_channel_label": {
103
+ "en": "Debug Error Channel",
104
+ "zh": "Debug Error Channel"
105
+ },
106
+
107
+ # Logic-related text
108
+ "code_log_no_code_warning": {
109
+ "en": "⚠️ **Warning**: No code available to refresh.",
110
+ "zh": "⚠️ **警告**: 没有代码可供刷新。"
111
+ },
112
+ "code_log_refreshed_state": {
113
+ "en": "🔄 **Status**: Preview has been manually refreshed.",
114
+ "zh": "🔄 **状态**: 预览已手动刷新。"
115
+ },
116
+ "code_log_runtime_error": {
117
+ "en": "🚨 **A runtime exception was detected in the preview!**\n```\n{error_text}\n```",
118
+ "zh": "🚨 **在预览中发现运行时异常!**\n```\n{error_text}\n```"
119
+ }
120
+ }
121
+
122
+ prompt_fragments = {}
i18n/tab_smart_writer.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/tab_smart_writer.py
2
+
3
+ ui_translations = {
4
+ # Tab Name (used in app.py)
5
+ "writer_tab_title": {"en": "Writing Assistant", "zh": "写作助手"},
6
+ # Left Column: Entity Console
7
+ "writer_style_input_label": {
8
+ "en": "Overall Story and Style",
9
+ "zh": "整体故事和风格",
10
+ },
11
+ "writer_kb_accordion_label": {"en": "Writing Knowledge Base", "zh": "写作知识库"},
12
+ "writer_kb_dataframe_headers": {
13
+ "en": ["Name", "Description"],
14
+ "zh": ["名称", "说明"],
15
+ },
16
+ "writer_suggest_kb_button": {"en": "🔍 Extract New Terms", "zh": "🔍 提取新词条"},
17
+ "writer_suggested_kb_label": {"en": "Recommended Terms", "zh": "推荐词条"},
18
+ "writer_short_outline_accordion_label": {
19
+ "en": "Current Chapter Outline",
20
+ "zh": "当前章节大纲",
21
+ },
22
+ "writer_short_outline_dataframe_headers": {
23
+ "en": ["Done", "Task"],
24
+ "zh": ["完成", "任务"],
25
+ },
26
+ "writer_sync_outline_button": {"en": "🔄 Sync Status", "zh": "🔄 同步状态"},
27
+ "writer_long_outline_accordion_label": {
28
+ "en": "Overall Story Outline",
29
+ "zh": "故事整体大纲",
30
+ },
31
+ # Right Column: Writing Canvas
32
+ # Area 1: Real-time Continuation (Flow)
33
+ "writer_flow_suggestion_label": {
34
+ "en": "Real-time Continuation",
35
+ "zh": "实时续写建议",
36
+ },
37
+ "writer_flow_suggestion_placeholder": {
38
+ "en": "(Waiting for input or click 'Try another'...)",
39
+ "zh": "(等待输入或点击“换一个”...)",
40
+ },
41
+ "writer_accept_flow_button": {"en": "Accept (Tab)", "zh": "采纳续写 (Tab)"},
42
+ "writer_change_flow_button": {
43
+ "en": "Try another (Shift+Tab)",
44
+ "zh": "换一个 (Shift+Tab)",
45
+ },
46
+ "writer_debounce_loading_text": {
47
+ "en": "Generating suggestion...",
48
+ "zh": "稍后开始续写",
49
+ },
50
+ # Area 2: Paragraph Continuation (Inspiration)
51
+ "writer_inspiration_prompt_label": {"en": "Continuation Prompt", "zh": "续写提示"},
52
+ "writer_inspiration_prompt_placeholder": {
53
+ "en": "e.g., write a paragraph about...",
54
+ "zh": "例如:写一段关于...的描写",
55
+ },
56
+ "writer_prompt_suggestions_label": {
57
+ "en": "Recommended Prompts (Click to fill)",
58
+ "zh": "推荐提示 (点击填入)",
59
+ },
60
+ "writer_refresh_suggestions_button": {
61
+ "en": "🎲 New Suggestions",
62
+ "zh": "🎲 换一批建议",
63
+ },
64
+ "writer_generate_para_button": {
65
+ "en": "Continue Paragraph (Cmd+Enter)",
66
+ "zh": "整段续写 (Cmd+Enter)",
67
+ },
68
+ "writer_change_para_button": {"en": "Try another", "zh": "换一个"},
69
+ "writer_accept_para_button": {"en": "Accept", "zh": "采纳"},
70
+ "writer_para_suggestion_placeholder": {
71
+ "en": "(Click 'Continue Paragraph' to generate content...)",
72
+ "zh": "(点击“整段续写”生成内容...)",
73
+ },
74
+ # Area 3: Adjust/Polish
75
+ "writer_polish_title": {"en": "#### 🛠️ Adjust & Polish", "zh": "#### 🛠️ 调整润色"},
76
+ "writer_coming_soon": {"en": "(Coming Soon)", "zh": "(敬请期待)"},
77
+ # Editor & Stats
78
+ "writer_editor_label": {"en": "Immersive Writing Canvas", "zh": "沉浸写作画布"},
79
+ "writer_editor_placeholder": {
80
+ "en": "Start your creation...",
81
+ "zh": "开始你的创作...",
82
+ },
83
+ "writer_stats_words": {"en": "Words", "zh": "字"},
84
+ "writer_stats_mins": {"en": "mins", "zh": "分钟"},
85
+ "writer_stats_format": {
86
+ "en": "{words} Words | ~{read_time} mins",
87
+ "zh": "{words} 字 | 约 {read_time} 分钟",
88
+ },
89
+ "writer_stats_default": {"en": "0 Words | 0 mins", "zh": "0 字 | 0 分钟"},
90
+ }
91
+
92
+ prompt_fragments = {}
i18n/tab_welcome.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/tab_welcome.py
2
+
3
+ ui_translations = {
4
+ "welcome_tab_title": {
5
+ "en": "Welcome",
6
+ "zh": "欢迎"
7
+ },
8
+ "welcome_header": {
9
+ "en": "Welcome to Ling Space",
10
+ "zh": "欢迎来到 Ling Space"
11
+ },
12
+ "welcome_description": {
13
+ "en": "Experience the power of Ling Series Models through these demos.",
14
+ "zh": "通过这些演示体验 Ling 系列模型的能力。"
15
+ },
16
+ "welcome_chat_desc": {
17
+ "en": "Text Generation Chat: Converse with the model naturally.",
18
+ "zh": "文本聊天:与模型进行自然对话。"
19
+ },
20
+ "welcome_code_desc": {
21
+ "en": "Code Generation: Generate and preview code snippets.",
22
+ "zh": "代码生成:生成并预览代码片段。"
23
+ },
24
+ "welcome_writer_desc": {
25
+ "en": "Smart Writing Assistant: Get help with your writing tasks.",
26
+ "zh": "写作助手:获取写作任务的帮助。"
27
+ },
28
+ "welcome_select_language": {
29
+ "en": "Select Language",
30
+ "zh": "选择语言"
31
+ },
32
+ "lang_en": {
33
+ "en": "English",
34
+ "zh": "English"
35
+ },
36
+ "lang_zh": {
37
+ "en": "中文",
38
+ "zh": "中文"
39
+ },
40
+ }
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
  gradio==6.0.1
2
  python-dotenv
3
  httpx
 
4
  # transformers
5
  # torch
 
1
  gradio==6.0.1
2
  python-dotenv
3
  httpx
4
+ watchfiles
5
  # transformers
6
  # torch
run_dev_server.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import watchfiles
2
+ import logging
3
+ import sys
4
+
5
+ # Configure logging to provide feedback on the watcher's status
6
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
7
+
8
+ if __name__ == '__main__':
9
+ """
10
+ This script uses 'watchfiles' to monitor for file changes in the current
11
+ directory (and subdirectories) and automatically restarts the Gradio
12
+ application.
13
+
14
+ It's a convenient way to develop without manually stopping and restarting
15
+ the server after each code change.
16
+
17
+ To run:
18
+ python run_dev_server.py
19
+ """
20
+ logging.info("Starting file watcher and development server for app.py...")
21
+
22
+ # run_process will watch for changes in the current path ('.')
23
+ # and restart the target command.
24
+ watchfiles.run_process(
25
+ '.', # Watch the current directory
26
+ target=f'{sys.executable} app.py --color', # Command to run
27
+ target_type='command'
28
+ )
static/app.html CHANGED
@@ -5,9 +5,73 @@
5
 
6
  // --- Logger utility (structured, levelled, timestamped) ---
7
  const SpaceApp = {
 
 
 
8
 
9
  hasBooted: false,
10
  fnUnloadLastTab: null,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  toastInfo: function(...args) {
13
  // use toastify
@@ -16,7 +80,9 @@
16
  duration: 3000,
17
  gravity: "top",
18
  position: "right",
19
- backgroundColor: "green",
 
 
20
  }).showToast();
21
  console.info("TOAST_INFO", ...args);
22
  },
@@ -27,7 +93,9 @@
27
  duration: 5000,
28
  gravity: "top",
29
  position: "right",
30
- backgroundColor: "red",
 
 
31
  }).showToast();
32
  console.error("TOAST_ERROR", ...args);
33
  },
@@ -105,6 +173,14 @@
105
  'tabSelect.writing': () => SpaceApp.WritingAssistantTab.toggle(),
106
  // New listener for fullscreen toggle
107
  'tab.code.toggleFullscreen': (e) => SpaceApp.WebGeneratorTab.toggleFullscreen(e),
 
 
 
 
 
 
 
 
108
  };
109
  for (const [event, handler] of Object.entries(listeners)) {
110
  window.addEventListener(event, handler);
@@ -151,6 +227,8 @@
151
  return;
152
  }
153
  SpaceApp.hasBooted = true;
 
 
154
  SpaceApp.toastInfo("Booting Space App...");
155
  SpaceApp.registerEventListeners();
156
  SpaceApp.TextGeneratorTab.init();
 
5
 
6
  // --- Logger utility (structured, levelled, timestamped) ---
7
  const SpaceApp = {
8
+
9
+ STORAGE_KEY_LANG: 'ling_space_locale',
10
+ URL_PARAM_LANG: 'lang',
11
 
12
  hasBooted: false,
13
  fnUnloadLastTab: null,
14
+
15
+ supportedLangs: function() {
16
+ return ['en', 'zh'];
17
+ },
18
+
19
+ setLanguage: function(lang, reload = true) {
20
+ if (!SpaceApp.supportedLangs().includes(lang)) {
21
+ console.error(`[I18n] Unsupported language: ${lang}`);
22
+ return;
23
+ }
24
+
25
+ localStorage.setItem(SpaceApp.STORAGE_KEY_LANG, lang);
26
+ console.log(`[I18n] Language set to: ${lang}`);
27
+
28
+ if (reload) {
29
+ // Update URL to reflect language or just reload
30
+ const url = new URL(window.location);
31
+ url.searchParams.set(SpaceApp.URL_PARAM_LANG, lang);
32
+ window.location.href = url.toString();
33
+ }
34
+ },
35
+
36
+ detectLanguage: function() {
37
+
38
+ // 1. Check URL Parameter, if any.
39
+ const urlParams = new URLSearchParams(window.location.search);
40
+ const urlLang = urlParams.get(SpaceApp.URL_PARAM_LANG);
41
+ if (urlLang && SpaceApp.supportedLangs().includes(urlLang)) {
42
+ console.log(`[I18n] Detected language from URL: ${urlLang}`);
43
+ return urlLang;
44
+ } else {
45
+ console.log(`[I18n] No valid language found in URL parameters, found: ${urlLang}`);
46
+ }
47
+
48
+ // 2. Check LocalStorage, if any.
49
+ const storedLang = localStorage.getItem(SpaceApp.STORAGE_KEY_LANG);
50
+ if (storedLang && SpaceApp.supportedLangs().includes(storedLang)) {
51
+ console.log(`[I18n] Detected language from LocalStorage: ${storedLang}`);
52
+ return storedLang;
53
+ } else {
54
+ console.log(`[I18n] No valid language found in LocalStorage, found: ${storedLang}`);
55
+ }
56
+
57
+ // 3. Check Browser User Agent
58
+ const browserLang = navigator.language || navigator.userLanguage;
59
+ if (browserLang) {
60
+ // Extract primary language code (e.g., 'zh-CN' -> 'zh')
61
+ const primaryLang = browserLang.split('-')[0].toLowerCase();
62
+ if (SpaceApp.supportedLangs().includes(primaryLang)) {
63
+ console.log(`[I18n] Detected language from UserAgent: ${primaryLang} (of ${browserLang})`);
64
+ return primaryLang;
65
+ } else {
66
+ console.log(`[I18n] No valid language found in UserAgent, found: ${browserLang}`);
67
+ }
68
+ } else {
69
+ console.log(`[I18n] No language found in UserAgent, navigator is ${JSON.stringify(navigator)}`);
70
+ }
71
+
72
+ console.log(`[I18n] cannot determine lang, using default language: ${DEFAULT_LOCALE}`);
73
+ return DEFAULT_LOCALE;
74
+ },
75
 
76
  toastInfo: function(...args) {
77
  // use toastify
 
80
  duration: 3000,
81
  gravity: "top",
82
  position: "right",
83
+ style: {
84
+ background: "green"
85
+ }
86
  }).showToast();
87
  console.info("TOAST_INFO", ...args);
88
  },
 
93
  duration: 5000,
94
  gravity: "top",
95
  position: "right",
96
+ style: {
97
+ background: "green"
98
+ }
99
  }).showToast();
100
  console.error("TOAST_ERROR", ...args);
101
  },
 
173
  'tabSelect.writing': () => SpaceApp.WritingAssistantTab.toggle(),
174
  // New listener for fullscreen toggle
175
  'tab.code.toggleFullscreen': (e) => SpaceApp.WebGeneratorTab.toggleFullscreen(e),
176
+ 'langChange.SpaceApp': (e) => {
177
+ const lang = e.detail.lang;
178
+ if (lang) {
179
+ SpaceApp.setLanguage(lang, true);
180
+ } else {
181
+ console.error("langChange.SpaceApp event received without 'lang' detail.");
182
+ }
183
+ },
184
  };
185
  for (const [event, handler] of Object.entries(listeners)) {
186
  window.addEventListener(event, handler);
 
227
  return;
228
  }
229
  SpaceApp.hasBooted = true;
230
+ const currentLang = SpaceApp.detectLanguage();
231
+ SpaceApp.setLanguage(currentLang, false);
232
  SpaceApp.toastInfo("Booting Space App...");
233
  SpaceApp.registerEventListeners();
234
  SpaceApp.TextGeneratorTab.init();
tab_chat.py CHANGED
@@ -6,62 +6,58 @@ from model_handler import ModelHandler
6
  from config import CHAT_MODEL_SPECS, LING_1T
7
  from recommand_config import RECOMMENDED_INPUTS
8
  from ui_components.model_selector import create_model_selector
 
9
 
10
- def create_chat_tab():
 
 
 
 
 
 
 
 
 
 
 
 
11
  model_handler = ModelHandler()
12
 
 
13
  conversation_store = gr.BrowserState(default_value=[], storage_key="ling_conversation_history")
14
  current_conversation_id = gr.BrowserState(default_value=None, storage_key="ling_current_conversation_id")
15
 
16
- def get_history_df(history):
17
- if not history:
18
- return pd.DataFrame({'ID': [], '对话': []})
19
- df = pd.DataFrame(history)
20
- return df[['id', 'title']].rename(columns={'id': 'ID', 'title': '对话'})
21
-
22
- def handle_new_chat(history, current_conv_id=None):
23
- # Try to find the current conversation
24
  current_convo = next((c for c in history if c["id"] == current_conv_id), None) if history else None
25
 
26
- # If current conversation exists and is empty, reuse it
27
  if current_convo and not current_convo.get("messages", []):
28
- return (
29
- current_conv_id,
30
- history,
31
- [],
32
- gr.update(value=get_history_df(history))
33
- )
34
 
35
  conv_id = str(uuid.uuid4())
 
36
  new_convo = {
37
- "id": conv_id, "title": "(新对话)",
38
  "messages": [], "timestamp": datetime.now().isoformat()
39
  }
40
  updated_history = [new_convo] + (history or [])
41
- return (
42
- conv_id,
43
- updated_history,
44
- [],
45
- gr.update(value=get_history_df(updated_history))
46
- )
47
 
48
- def load_conversation_from_df(df: pd.DataFrame, evt: gr.SelectData, history):
49
- if evt.index is None:
50
  return None, []
51
  selected_id = df.iloc[evt.index[0]]['ID']
52
  for convo in history:
53
  if convo["id"] == selected_id:
54
  return selected_id, convo["messages"]
55
- # Fallback to new chat if something goes wrong
56
- new_id, _, new_msgs, _ = handle_new_chat(history)
57
  return new_id, new_msgs
58
 
59
  with gr.Row(equal_height=False, elem_id="indicator-chat-tab"):
60
  with gr.Column(scale=1):
61
- new_chat_btn = gr.Button("➕ 新对话")
62
  history_df = gr.DataFrame(
63
  value=get_history_df(conversation_store.value),
64
- headers=["ID", "对话记录"],
65
  datatype=["str", "str"],
66
  interactive=False,
67
  visible=True,
@@ -69,16 +65,17 @@ def create_chat_tab():
69
  )
70
 
71
  with gr.Column(scale=4):
72
- chatbot = gr.Chatbot(height=500)
73
  with gr.Row():
74
- textbox = gr.Textbox(placeholder="输入消息...", container=False, scale=7)
75
- submit_btn = gr.Button("发送", scale=1)
76
 
77
- gr.Markdown("### 推荐对话")
78
  recommended_dataset = gr.Dataset(
79
  components=[gr.Textbox(visible=False)],
80
  samples=[[item["task"]] for item in RECOMMENDED_INPUTS],
81
- label="推荐场景", headers=["选择一个场景试试"],
 
82
  )
83
 
84
  with gr.Column(scale=1):
@@ -87,17 +84,16 @@ def create_chat_tab():
87
  default_model_constant=LING_1T
88
  )
89
 
90
- system_prompt_textbox = gr.Textbox(label="系统提示词", lines=5, placeholder="输入系统提示词...")
91
- temperature_slider = gr.Slider(minimum=0, maximum=1.0, value=0.7, step=0.1, label="温度参数")
92
 
93
  # --- Event Handlers --- #
94
- # The change handler is now encapsulated within create_model_selector
95
- def on_select_recommendation(evt: gr.SelectData, history, current_conv_id):
96
  selected_task = evt.value[0]
97
  item = next((i for i in RECOMMENDED_INPUTS if i["task"] == selected_task), None)
98
  if not item: return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
99
 
100
- new_id, new_history, new_messages, history_df_update = handle_new_chat(history, current_conv_id)
101
 
102
  return (
103
  new_id, new_history,
@@ -109,8 +105,6 @@ def create_chat_tab():
109
  new_messages
110
  )
111
 
112
- recommended_dataset.select(on_select_recommendation, inputs=[conversation_store, current_conversation_id], outputs=[current_conversation_id, conversation_store, model_dropdown, system_prompt_textbox, temperature_slider, textbox, history_df, chatbot], show_progress="none")
113
-
114
  def chat_stream(conv_id, history, model_display_name, message, chat_history, system_prompt, temperature):
115
  if not message:
116
  yield chat_history
@@ -120,12 +114,13 @@ def create_chat_tab():
120
  for history_update in response_generator:
121
  yield history_update
122
 
123
- def on_chat_stream_complete(conv_id, history, final_chat_history):
124
  current_convo = next((c for c in history if c["id"] == conv_id), None)
125
  if not current_convo:
126
  return history, gr.update()
127
-
128
- if len(final_chat_history) > len(current_convo["messages"]) and current_convo["title"] == "(新对话)":
 
129
  user_message = final_chat_history[-2]["content"] if len(final_chat_history) > 1 else final_chat_history[0]["content"]
130
  current_convo["title"] = user_message[:50]
131
 
@@ -134,6 +129,27 @@ def create_chat_tab():
134
 
135
  history = sorted([c for c in history if c["id"] != conv_id] + [current_convo], key=lambda x: x["timestamp"], reverse=True)
136
  return history, gr.update(value=get_history_df(history))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
  submit_btn.click(
139
  chat_stream,
@@ -141,7 +157,7 @@ def create_chat_tab():
141
  [chatbot]
142
  ).then(
143
  on_chat_stream_complete,
144
- [current_conversation_id, conversation_store, chatbot],
145
  [conversation_store, history_df]
146
  )
147
  textbox.submit(
@@ -150,11 +166,28 @@ def create_chat_tab():
150
  [chatbot]
151
  ).then(
152
  on_chat_stream_complete,
153
- [current_conversation_id, conversation_store, chatbot],
154
  [conversation_store, history_df]
155
  )
156
 
157
- new_chat_btn.click(handle_new_chat, inputs=[conversation_store, current_conversation_id], outputs=[current_conversation_id, conversation_store, chatbot, history_df])
158
- history_df.select(load_conversation_from_df, inputs=[history_df, conversation_store], outputs=[current_conversation_id, chatbot])
159
-
160
- return conversation_store, current_conversation_id, history_df, chatbot
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from config import CHAT_MODEL_SPECS, LING_1T
7
  from recommand_config import RECOMMENDED_INPUTS
8
  from ui_components.model_selector import create_model_selector
9
+ from i18n import get_text
10
 
11
+ def get_history_df(history):
12
+ if not history:
13
+ # Provide explicit column names for an empty DataFrame
14
+ return pd.DataFrame({'ID': pd.Series(dtype='str'), '对话': pd.Series(dtype='str')})
15
+ df = pd.DataFrame(history)
16
+ # Ensure columns exist before renaming
17
+ if 'id' in df.columns and 'title' in df.columns:
18
+ return df[['id', 'title']].rename(columns={'id': 'ID', '对话': '对话'})
19
+ else:
20
+ return pd.DataFrame({'ID': pd.Series(dtype='str'), '对话': pd.Series(dtype='str')})
21
+
22
+
23
+ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
24
  model_handler = ModelHandler()
25
 
26
+ # Browser-side storage for conversation history and current ID
27
  conversation_store = gr.BrowserState(default_value=[], storage_key="ling_conversation_history")
28
  current_conversation_id = gr.BrowserState(default_value=None, storage_key="ling_current_conversation_id")
29
 
30
+ def handle_new_chat(history, current_conv_id, lang):
 
 
 
 
 
 
 
31
  current_convo = next((c for c in history if c["id"] == current_conv_id), None) if history else None
32
 
 
33
  if current_convo and not current_convo.get("messages", []):
34
+ return current_conv_id, history, [], gr.update(value=get_history_df(history))
 
 
 
 
 
35
 
36
  conv_id = str(uuid.uuid4())
37
+ new_convo_title = get_text('chat_new_conversation_title', lang)
38
  new_convo = {
39
+ "id": conv_id, "title": new_convo_title,
40
  "messages": [], "timestamp": datetime.now().isoformat()
41
  }
42
  updated_history = [new_convo] + (history or [])
43
+ return conv_id, updated_history, [], gr.update(value=get_history_df(updated_history))
 
 
 
 
 
44
 
45
+ def load_conversation_from_df(df: pd.DataFrame, evt: gr.SelectData, history, lang):
46
+ if evt.index is None or len(df) == 0:
47
  return None, []
48
  selected_id = df.iloc[evt.index[0]]['ID']
49
  for convo in history:
50
  if convo["id"] == selected_id:
51
  return selected_id, convo["messages"]
52
+ new_id, _, new_msgs, _ = handle_new_chat(history, None, lang)
 
53
  return new_id, new_msgs
54
 
55
  with gr.Row(equal_height=False, elem_id="indicator-chat-tab"):
56
  with gr.Column(scale=1):
57
+ new_chat_btn = gr.Button(get_text('chat_new_chat_button', initial_lang))
58
  history_df = gr.DataFrame(
59
  value=get_history_df(conversation_store.value),
60
+ headers=["ID", get_text('chat_history_dataframe_header', initial_lang)],
61
  datatype=["str", "str"],
62
  interactive=False,
63
  visible=True,
 
65
  )
66
 
67
  with gr.Column(scale=4):
68
+ chatbot = gr.Chatbot(height=500, placeholder=get_text('chat_chatbot_placeholder', initial_lang))
69
  with gr.Row():
70
+ textbox = gr.Textbox(placeholder=get_text('chat_textbox_placeholder', initial_lang), container=False, scale=7)
71
+ submit_btn = gr.Button(get_text('chat_submit_button', initial_lang), scale=1)
72
 
73
+ recommended_title = gr.Markdown(get_text('chat_recommended_dialogues_title', initial_lang))
74
  recommended_dataset = gr.Dataset(
75
  components=[gr.Textbox(visible=False)],
76
  samples=[[item["task"]] for item in RECOMMENDED_INPUTS],
77
+ label=get_text('chat_recommended_dataset_label', initial_lang),
78
+ headers=[get_text('chat_recommended_dataset_header', initial_lang)],
79
  )
80
 
81
  with gr.Column(scale=1):
 
84
  default_model_constant=LING_1T
85
  )
86
 
87
+ system_prompt_textbox = gr.Textbox(label=get_text('chat_system_prompt_label', initial_lang), lines=5, placeholder=get_text('chat_system_prompt_placeholder', initial_lang))
88
+ temperature_slider = gr.Slider(minimum=0, maximum=1.0, value=0.7, step=0.1, label=get_text('chat_temperature_slider_label', initial_lang))
89
 
90
  # --- Event Handlers --- #
91
+ def on_select_recommendation(evt: gr.SelectData, history, current_conv_id, lang):
 
92
  selected_task = evt.value[0]
93
  item = next((i for i in RECOMMENDED_INPUTS if i["task"] == selected_task), None)
94
  if not item: return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
95
 
96
+ new_id, new_history, new_messages, history_df_update = handle_new_chat(history, current_conv_id, lang)
97
 
98
  return (
99
  new_id, new_history,
 
105
  new_messages
106
  )
107
 
 
 
108
  def chat_stream(conv_id, history, model_display_name, message, chat_history, system_prompt, temperature):
109
  if not message:
110
  yield chat_history
 
114
  for history_update in response_generator:
115
  yield history_update
116
 
117
+ def on_chat_stream_complete(conv_id, history, final_chat_history, lang):
118
  current_convo = next((c for c in history if c["id"] == conv_id), None)
119
  if not current_convo:
120
  return history, gr.update()
121
+
122
+ new_convo_title = get_text('chat_new_conversation_title', lang)
123
+ if len(final_chat_history) > len(current_convo["messages"]) and current_convo["title"] == new_convo_title:
124
  user_message = final_chat_history[-2]["content"] if len(final_chat_history) > 1 else final_chat_history[0]["content"]
125
  current_convo["title"] = user_message[:50]
126
 
 
129
 
130
  history = sorted([c for c in history if c["id"] != conv_id] + [current_convo], key=lambda x: x["timestamp"], reverse=True)
131
  return history, gr.update(value=get_history_df(history))
132
+
133
+ # Store all components that need i18n updates
134
+ components = {
135
+ "new_chat_btn": new_chat_btn,
136
+ "history_df": history_df,
137
+ "chatbot": chatbot,
138
+ "textbox": textbox,
139
+ "submit_btn": submit_btn,
140
+ "recommended_title": recommended_title,
141
+ "recommended_dataset": recommended_dataset,
142
+ "system_prompt_textbox": system_prompt_textbox,
143
+ "temperature_slider": temperature_slider,
144
+ "model_dropdown": model_dropdown,
145
+ "model_description_markdown": model_description_markdown,
146
+ # Non-updatable components needed for event handlers and app.py
147
+ "conversation_store": conversation_store,
148
+ "current_conversation_id": current_conversation_id,
149
+ }
150
+
151
+ # Wire event handlers
152
+ recommended_dataset.select(on_select_recommendation, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, model_dropdown, system_prompt_textbox, temperature_slider, textbox, history_df, chatbot], show_progress="none")
153
 
154
  submit_btn.click(
155
  chat_stream,
 
157
  [chatbot]
158
  ).then(
159
  on_chat_stream_complete,
160
+ [current_conversation_id, conversation_store, chatbot, current_lang_state],
161
  [conversation_store, history_df]
162
  )
163
  textbox.submit(
 
166
  [chatbot]
167
  ).then(
168
  on_chat_stream_complete,
169
+ [current_conversation_id, conversation_store, chatbot, current_lang_state],
170
  [conversation_store, history_df]
171
  )
172
 
173
+ new_chat_btn.click(handle_new_chat, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, chatbot, history_df])
174
+ history_df.select(load_conversation_from_df, inputs=[history_df, conversation_store, current_lang_state], outputs=[current_conversation_id, chatbot])
175
+
176
+ return components
177
+
178
+ def update_language(lang: str, components: dict):
179
+ """
180
+ Returns a dictionary mapping components to their gr.update calls for language change.
181
+ """
182
+ updates = {
183
+ components["new_chat_btn"]: gr.update(value=get_text('chat_new_chat_button', lang)),
184
+ components["history_df"]: gr.update(headers=["ID", get_text('chat_history_dataframe_header', lang)]),
185
+ components["chatbot"]: gr.update(placeholder=get_text('chat_chatbot_placeholder', lang)),
186
+ components["textbox"]: gr.update(placeholder=get_text('chat_textbox_placeholder', lang)),
187
+ components["submit_btn"]: gr.update(value=get_text('chat_submit_button', lang)),
188
+ components["recommended_title"]: gr.update(value=get_text('chat_recommended_dialogues_title', lang)),
189
+ components["recommended_dataset"]: gr.update(label=get_text('chat_recommended_dataset_label', lang), headers=[get_text('chat_recommended_dataset_header', lang)]),
190
+ components["system_prompt_textbox"]: gr.update(label=get_text('chat_system_prompt_label', lang), placeholder=get_text('chat_system_prompt_placeholder', lang)),
191
+ components["temperature_slider"]: gr.update(label=get_text('chat_temperature_slider_label', lang)),
192
+ }
193
+ return updates
tab_code.py CHANGED
@@ -1,16 +1,17 @@
1
  import gradio as gr
2
  import logging
3
- from config import CHAT_MODEL_SPECS, LING_1T, CODE_FRAMEWORK_SPECS, STATIC_PAGE
4
  from ui_components.model_selector import create_model_selector
5
  from ui_components.code_framework_selector import create_code_framework_selector
6
  from code_kit.agent_code_generator import code_generation_agent
7
  from code_kit.agent_style_generator import generate_random_style
8
  from code_kit.code_examples import CODE_EXAMPLES
 
9
 
10
  # Configure logging
11
  logger = logging.getLogger(__name__)
12
 
13
- def refresh_preview(code_type_display_name, current_code, chatbot_history):
14
  """
15
  Refresh the preview and add a log entry.
16
  Refactored to rely solely on the HTML content for preview, assuming all frameworks
@@ -21,7 +22,7 @@ def refresh_preview(code_type_display_name, current_code, chatbot_history):
21
 
22
  # Simple validation: Check if code seems to be HTML
23
  if not current_code or not isinstance(current_code, str):
24
- chatbot_history.append({"role": "assistant", "content": "⚠️ **警告**: 没有代码可供刷新。"})
25
  return gr.update(), chatbot_history
26
 
27
  # For all currently supported frameworks (Static, React+Tailwind, R3F, Old School),
@@ -35,16 +36,16 @@ def refresh_preview(code_type_display_name, current_code, chatbot_history):
35
  </iframe>
36
  </div>
37
  """
38
- chatbot_history.append({"role": "assistant", "content": "🔄 **状态**: 预览已手动刷新。"})
39
  logger.info("Refreshed preview.")
40
  return gr.HTML(final_preview_html), chatbot_history
41
 
42
- def toggle_fullscreen(is_fullscreen):
43
  logger.info(f"--- [Toggle Fullscreen] Called ---")
44
  logger.info(f"Current state before toggle: {is_fullscreen}")
45
 
46
  is_fullscreen = not is_fullscreen
47
- new_button_text = "退出全屏" if is_fullscreen else "全屏预览"
48
 
49
  logger.info(f"New state: {is_fullscreen}")
50
 
@@ -53,12 +54,12 @@ def toggle_fullscreen(is_fullscreen):
53
  gr.update(value=new_button_text)
54
  )
55
 
56
- def log_js_error(error_text, chatbot_history):
57
  """Appends a JavaScript error received from the frontend to the log chatbot."""
58
  if not error_text:
59
  return chatbot_history
60
 
61
- formatted_error = f"🚨 **在预览中发现运行时异常!**\n```\n{error_text}\n```"
62
 
63
  # Check if the last message is the same error to prevent flooding
64
  if chatbot_history and chatbot_history[-1]["content"] == formatted_error:
@@ -67,15 +68,8 @@ def log_js_error(error_text, chatbot_history):
67
  chatbot_history.append({"role": "assistant", "content": formatted_error})
68
  return chatbot_history
69
 
70
- def create_code_tab():
71
- # Inject custom CSS to hide components
72
- gr.HTML("""
73
- <style>
74
- .hidden-component {
75
- display: none;
76
- }
77
- </style>
78
- """)
79
  fullscreen_state = gr.State(False)
80
 
81
  # JavaScript to dispatch a custom event for fullscreen toggle
@@ -110,55 +104,43 @@ def create_code_tab():
110
  with gr.Column(scale=1): # Settings Panel
111
  code_framework_dropdown = create_code_framework_selector(
112
  framework_specs=CODE_FRAMEWORK_SPECS,
113
- default_framework_constant=STATIC_PAGE
114
  )
115
  model_choice_dropdown, model_description_markdown = create_model_selector(
116
  model_specs=CHAT_MODEL_SPECS,
117
  default_model_constant=LING_1T
118
  )
119
-
120
- prompt_input = gr.Textbox(lines=5, placeholder="例如:创建一个带标题和按钮的简单页面", label="提示词")
121
-
122
- overall_style_input = gr.Textbox(label="整体风格", placeholder="例如:类似一本羊皮纸的书", lines=2)
123
-
124
- decoration_input = gr.Textbox(label="装饰风格", placeholder="例如:粗边框,无圆角", lines=2)
125
-
126
- # Hidden textbox to store the raw palette string for the prompt
127
  palette_input = gr.Textbox(label="Palette (Raw)", elem_classes="hidden-component")
128
-
129
- palette_display = gr.HTML(value='<div style="color: #999; font-size: 12px;">(生成风格后展示)</div>',
130
- container=True,
131
- label="风格色板",
132
- show_label=True)
133
-
134
- generate_style_btn = gr.Button("🎲 随机生成风格", size="sm")
135
-
136
  with gr.Column():
137
- gr.Markdown("### 示例")
138
  examples_dataset = gr.Dataset(
139
  components=[gr.Textbox(visible=False)],
140
  samples=[[item["task"]] for item in CODE_EXAMPLES],
141
- label="示例",
142
- headers=["选择一个示例"],
143
  )
144
- generate_button = gr.Button("生成代码", variant="primary")
145
 
146
  with gr.Column(scale=4):
147
  with gr.Tabs(elem_id="result_tabs") as result_tabs:
148
- with gr.TabItem("实时预览", id=0):
149
  with gr.Row():
150
- gr.Markdown("### 实时预览")
151
- fullscreen_button = gr.Button("全屏预览", scale=0)
152
- preview_output = gr.HTML(value="<p>预览将在此处显示。</p>")
153
- with gr.TabItem("生成的源代码", id=1):
154
- gr.Markdown("### 生成的源代码")
155
- code_output = gr.Code(language="html", label="生成的代码", interactive=True)
156
- refresh_button = gr.Button("刷新预览")
157
 
158
  with gr.Column(scale=1, elem_id="right-panel") as right_panel:
159
- log_chatbot = gr.Chatbot(label="生成日志", height=300)
160
-
161
- js_error_channel = gr.Textbox(visible=True, elem_classes=["js_error_channel"], label="Debug Error Channel", interactive=False)
162
 
163
  # Event Handler for Example Selection
164
  def on_select_example(evt: gr.SelectData):
@@ -173,7 +155,7 @@ def create_code_tab():
173
  fn=on_select_example,
174
  inputs=None,
175
  outputs=[prompt_input, model_choice_dropdown],
176
- show_progress="none"
177
  )
178
 
179
  # Event Handler for Style Generation
@@ -185,7 +167,7 @@ def create_code_tab():
185
 
186
  refresh_button.click(
187
  fn=refresh_preview,
188
- inputs=[code_framework_dropdown, code_output, log_chatbot],
189
  outputs=[preview_output, log_chatbot]
190
  )
191
 
@@ -205,13 +187,46 @@ def create_code_tab():
205
 
206
  fullscreen_button.click(
207
  fn=toggle_fullscreen,
208
- inputs=[fullscreen_state],
209
  outputs=[fullscreen_state, fullscreen_button],
210
  js=dispatch_fullscreen_event_js
211
  )
212
 
213
  js_error_channel.change(
214
- fn=log_js_error,
215
- inputs=[js_error_channel, log_chatbot],
216
  outputs=log_chatbot
217
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import logging
3
+ from config import CHAT_MODEL_SPECS, LING_1T, CODE_FRAMEWORK_SPECS, REACT_TAILWIND
4
  from ui_components.model_selector import create_model_selector
5
  from ui_components.code_framework_selector import create_code_framework_selector
6
  from code_kit.agent_code_generator import code_generation_agent
7
  from code_kit.agent_style_generator import generate_random_style
8
  from code_kit.code_examples import CODE_EXAMPLES
9
+ from i18n import get_text
10
 
11
  # Configure logging
12
  logger = logging.getLogger(__name__)
13
 
14
+ def refresh_preview(code_type_display_name, current_code, chatbot_history, lang):
15
  """
16
  Refresh the preview and add a log entry.
17
  Refactored to rely solely on the HTML content for preview, assuming all frameworks
 
22
 
23
  # Simple validation: Check if code seems to be HTML
24
  if not current_code or not isinstance(current_code, str):
25
+ chatbot_history.append({"role": "assistant", "content": get_text('code_log_no_code_warning', lang)})
26
  return gr.update(), chatbot_history
27
 
28
  # For all currently supported frameworks (Static, React+Tailwind, R3F, Old School),
 
36
  </iframe>
37
  </div>
38
  """
39
+ chatbot_history.append({"role": "assistant", "content": get_text('code_log_refreshed_state', lang)})
40
  logger.info("Refreshed preview.")
41
  return gr.HTML(final_preview_html), chatbot_history
42
 
43
+ def toggle_fullscreen(is_fullscreen, lang):
44
  logger.info(f"--- [Toggle Fullscreen] Called ---")
45
  logger.info(f"Current state before toggle: {is_fullscreen}")
46
 
47
  is_fullscreen = not is_fullscreen
48
+ new_button_text = get_text('code_exit_fullscreen_button', lang) if is_fullscreen else get_text('code_fullscreen_button', lang)
49
 
50
  logger.info(f"New state: {is_fullscreen}")
51
 
 
54
  gr.update(value=new_button_text)
55
  )
56
 
57
+ def log_js_error(error_text, chatbot_history, lang):
58
  """Appends a JavaScript error received from the frontend to the log chatbot."""
59
  if not error_text:
60
  return chatbot_history
61
 
62
+ formatted_error = get_text('code_log_runtime_error', lang).format(error_text=error_text)
63
 
64
  # Check if the last message is the same error to prevent flooding
65
  if chatbot_history and chatbot_history[-1]["content"] == formatted_error:
 
68
  chatbot_history.append({"role": "assistant", "content": formatted_error})
69
  return chatbot_history
70
 
71
+ def create_code_tab(initial_lang: str, current_lang_state: gr.State):
72
+ gr.HTML("""<style>.hidden-component { display: none; }</style>""")
 
 
 
 
 
 
 
73
  fullscreen_state = gr.State(False)
74
 
75
  # JavaScript to dispatch a custom event for fullscreen toggle
 
104
  with gr.Column(scale=1): # Settings Panel
105
  code_framework_dropdown = create_code_framework_selector(
106
  framework_specs=CODE_FRAMEWORK_SPECS,
107
+ default_framework_constant=REACT_TAILWIND
108
  )
109
  model_choice_dropdown, model_description_markdown = create_model_selector(
110
  model_specs=CHAT_MODEL_SPECS,
111
  default_model_constant=LING_1T
112
  )
113
+ prompt_input = gr.Textbox(lines=5, placeholder=get_text('code_prompt_placeholder', initial_lang), label=get_text('code_prompt_label', initial_lang))
114
+ overall_style_input = gr.Textbox(label=get_text('code_overall_style_label', initial_lang), placeholder=get_text('code_overall_style_placeholder', initial_lang), lines=2)
115
+ decoration_input = gr.Textbox(label=get_text('code_decoration_style_label', initial_lang), placeholder=get_text('code_decoration_style_placeholder', initial_lang), lines=2)
 
 
 
 
 
116
  palette_input = gr.Textbox(label="Palette (Raw)", elem_classes="hidden-component")
117
+ palette_display = gr.HTML(value=f"<div style='color: #999; font-size: 12px;'>{get_text('code_palette_placeholder', initial_lang)}</div>", container=True, label=get_text('code_palette_label', initial_lang), show_label=True)
118
+ generate_style_btn = gr.Button(get_text('code_generate_style_button', initial_lang), size="sm")
 
 
 
 
 
 
119
  with gr.Column():
120
+ examples_title = gr.Markdown(get_text('code_examples_title', initial_lang))
121
  examples_dataset = gr.Dataset(
122
  components=[gr.Textbox(visible=False)],
123
  samples=[[item["task"]] for item in CODE_EXAMPLES],
124
+ label=get_text('code_examples_dataset_label', initial_lang),
125
+ headers=[get_text('code_examples_dataset_header', initial_lang)],
126
  )
127
+ generate_button = gr.Button(get_text('code_generate_code_button', initial_lang), variant="primary")
128
 
129
  with gr.Column(scale=4):
130
  with gr.Tabs(elem_id="result_tabs") as result_tabs:
131
+ with gr.TabItem(get_text('code_preview_tab_title', initial_lang), id=0) as preview_tab:
132
  with gr.Row():
133
+ preview_header = gr.Markdown(get_text('code_preview_header', initial_lang))
134
+ fullscreen_button = gr.Button(get_text('code_fullscreen_button', initial_lang), scale=0)
135
+ preview_output = gr.HTML(value=get_text('code_preview_placeholder', initial_lang))
136
+ with gr.TabItem(get_text('code_source_code_tab_title', initial_lang), id=1) as source_code_tab:
137
+ source_code_header = gr.Markdown(get_text('code_source_code_header', initial_lang))
138
+ code_output = gr.Code(language="html", label=get_text('code_source_code_label', initial_lang), interactive=True)
139
+ refresh_button = gr.Button(get_text('code_refresh_preview_button', initial_lang))
140
 
141
  with gr.Column(scale=1, elem_id="right-panel") as right_panel:
142
+ log_chatbot = gr.Chatbot(label=get_text('code_log_chatbot_label', initial_lang), height=300)
143
+ js_error_channel = gr.Textbox(visible=True, elem_classes=["js_error_channel"], label=get_text('code_debug_channel_label', initial_lang), interactive=False)
 
144
 
145
  # Event Handler for Example Selection
146
  def on_select_example(evt: gr.SelectData):
 
155
  fn=on_select_example,
156
  inputs=None,
157
  outputs=[prompt_input, model_choice_dropdown],
158
+ show_progress="hidden"
159
  )
160
 
161
  # Event Handler for Style Generation
 
167
 
168
  refresh_button.click(
169
  fn=refresh_preview,
170
+ inputs=[code_framework_dropdown, code_output, log_chatbot, current_lang_state],
171
  outputs=[preview_output, log_chatbot]
172
  )
173
 
 
187
 
188
  fullscreen_button.click(
189
  fn=toggle_fullscreen,
190
+ inputs=[fullscreen_state, current_lang_state],
191
  outputs=[fullscreen_state, fullscreen_button],
192
  js=dispatch_fullscreen_event_js
193
  )
194
 
195
  js_error_channel.change(
196
+ fn=log_js_error,
197
+ inputs=[js_error_channel, log_chatbot, current_lang_state],
198
  outputs=log_chatbot
199
  )
200
+
201
+ return {
202
+ "prompt_input": prompt_input, "overall_style_input": overall_style_input,
203
+ "decoration_input": decoration_input, "palette_display": palette_display,
204
+ "generate_style_btn": generate_style_btn, "examples_title": examples_title,
205
+ "examples_dataset": examples_dataset, "generate_button": generate_button,
206
+ "preview_tab": preview_tab, "preview_header": preview_header,
207
+ "fullscreen_button": fullscreen_button, "preview_output": preview_output,
208
+ "source_code_tab": source_code_tab, "source_code_header": source_code_header,
209
+ "code_output": code_output, "refresh_button": refresh_button,
210
+ "log_chatbot": log_chatbot, "js_error_channel": js_error_channel
211
+ }
212
+
213
+ def update_language(lang: str, components: dict):
214
+ return {
215
+ components["prompt_input"]: gr.update(label=get_text('code_prompt_label', lang), placeholder=get_text('code_prompt_placeholder', lang)),
216
+ components["overall_style_input"]: gr.update(label=get_text('code_overall_style_label', lang), placeholder=get_text('code_overall_style_placeholder', lang)),
217
+ components["decoration_input"]: gr.update(label=get_text('code_decoration_style_label', lang), placeholder=get_text('code_decoration_style_placeholder', lang)),
218
+ components["palette_display"]: gr.update(label=get_text('code_palette_label', lang)),
219
+ components["generate_style_btn"]: gr.update(value=get_text('code_generate_style_button', lang)),
220
+ components["examples_title"]: gr.update(value=get_text('code_examples_title', lang)),
221
+ components["examples_dataset"]: gr.update(label=get_text('code_examples_dataset_label', lang), headers=[get_text('code_examples_dataset_header', lang)]),
222
+ components["generate_button"]: gr.update(value=get_text('code_generate_code_button', lang)),
223
+ components["preview_tab"]: gr.update(label=get_text('code_preview_tab_title', lang)),
224
+ components["preview_header"]: gr.update(value=get_text('code_preview_header', lang)),
225
+ # Fullscreen button is updated in its own event handler
226
+ components["source_code_tab"]: gr.update(label=get_text('code_source_code_tab_title', lang)),
227
+ components["source_code_header"]: gr.update(value=get_text('code_source_code_header', lang)),
228
+ components["code_output"]: gr.update(label=get_text('code_source_code_label', lang)),
229
+ components["refresh_button"]: gr.update(value=get_text('code_refresh_preview_button', lang)),
230
+ components["log_chatbot"]: gr.update(label=get_text('code_log_chatbot_label', lang)),
231
+ components["js_error_channel"]: gr.update(label=get_text('code_debug_channel_label', lang)),
232
+ }
tab_smart_writer.py CHANGED
@@ -1,5 +1,4 @@
1
  import gradio as gr
2
- import time
3
  from smart_writer_kit.agent_for_streaming_completion import fetch_flow_suggestion_agent, accept_flow_suggestion_agent
4
  from smart_writer_kit.agent_for_inspiration_expansion import fetch_inspiration_agent, apply_inspiration_agent
5
  from smart_writer_kit.agent_for_paragraph_continuation import fetch_paragraph_continuation_agent
@@ -7,6 +6,7 @@ from smart_writer_kit.agent_for_prompt_suggestion import fetch_prompt_suggestion
7
  from smart_writer_kit.agent_for_outline_update import update_outline_status_agent
8
  from smart_writer_kit.agent_for_kb_update import suggest_new_kb_terms_agent
9
  from ui_components.debounce_manager import DebounceManager
 
10
 
11
  # --- Mock Data (for UI population only) ---
12
 
@@ -16,7 +16,7 @@ MOCK_STYLE = """故事:人类逐渐走向消亡时,人形机器人的休闲
16
  """
17
 
18
  MOCK_KNOWLEDGE_BASE = [
19
- ["Alpha", "故事的主角,女性人形机器人,外表与人类无异。性格有线"],
20
  ["横滨", "故事发生的主要城市。由于海平面上升,城市部分地区被淹没,形成独特的水上景观。"]
21
  ]
22
 
@@ -35,71 +35,73 @@ MOCK_LONG_TERM_OUTLINE = [
35
  ]
36
 
37
  # --- UI Helper Functions ---
38
- def get_stats(text):
39
  """Calculate word count and read time."""
40
  if not text:
41
- return "0 Words | 0 mins"
42
  words = len(text.split())
43
  read_time = max(1, words // 200) # Average reading speed
44
- return f"{words} Words | ~{read_time} mins"
 
 
45
 
46
  # --- UI Construction ---
47
 
48
- def create_smart_writer_tab():
49
- # Initialize DebounceManager
50
- debounce_manager = DebounceManager(debounce_time=2.0, tick_time=0.3, loading_text="稍后开始续写")
51
 
52
  with gr.Row(equal_height=False, elem_id="indicator-writing-tab"):
53
  # --- Left Column: Entity Console ---
54
  with gr.Column(scale=1) as left_panel:
55
 
56
  style_input = gr.Textbox(
57
- label="整体故事和风格",
58
  lines=8,
59
  value=MOCK_STYLE,
60
  interactive=True
61
  )
62
 
63
- with gr.Accordion("写作知识库", open=True):
64
-
 
65
  kb_input = gr.Dataframe(
66
- headers=["名称", "说明"],
67
  datatype=["str", "str"],
68
  value=MOCK_KNOWLEDGE_BASE,
69
  interactive=True,
70
  wrap=True
71
  )
72
  with gr.Row():
73
- btn_suggest_kb = gr.Button("🔍 提取新词条", size="sm")
74
 
75
  suggested_kb_dataframe = gr.Dataframe(
76
  headers=["Term", "Description"],
77
  datatype=["str", "str"],
78
  visible=False,
79
  interactive=False,
80
- label="推荐词条"
81
  )
82
 
83
- with gr.Accordion("当前章节大纲", open=True):
84
 
85
  short_outline_input = gr.Dataframe(
86
- headers=["Done", "Task"],
87
  datatype=["bool", "str"],
88
  value=MOCK_SHORT_TERM_OUTLINE,
89
  interactive=True,
90
- label="当前章节大纲",
91
  col_count=(2, "fixed"),
92
  )
93
  with gr.Row():
94
- btn_sync_outline = gr.Button("🔄 同步状态", size="sm")
95
 
96
- with gr.Accordion("故事整体大纲", open=False):
97
  long_outline_input = gr.Dataframe(
98
- headers=["Done", "Task"],
99
  datatype=["bool", "str"],
100
  value=MOCK_LONG_TERM_OUTLINE,
101
  interactive=True,
102
- label="故事总纲",
103
  col_count=(2, "fixed"),
104
  )
105
 
@@ -114,62 +116,63 @@ def create_smart_writer_tab():
114
 
115
  flow_suggestion_display = gr.Textbox(
116
  show_label=True,
117
- label="实时续写建议",
118
- placeholder="(等待输入或点击“换一个”...)",
119
  lines=3,
120
  interactive=False,
121
  elem_classes=["flow-suggestion-box"],
122
  )
123
 
124
- btn_accept_flow = gr.Button("采纳续写 (Tab)", size="sm", variant="primary", elem_id='btn-action-accept-flow')
125
- btn_change_flow = gr.Button("换一个 (Shift+Tab)", size="sm", elem_id='btn-action-change-flow')
126
 
127
  # Debounce Progress Indicator (Using Manager)
128
  debounce_state, debounce_timer, debounce_progress = debounce_manager.create_ui()
129
- debounce_progress.visible = True
130
 
131
  # Area 2: Paragraph Continuation (Inspiration)
132
  with gr.Column(scale=1, min_width=200):
133
  inspiration_prompt_input = gr.Textbox(
134
- label="续写提示",
135
- placeholder="例如:写一段关于...的描写",
136
  lines=2
137
  )
138
-
139
  prompt_suggestions_dataset = gr.Dataset(
140
- label="推荐提示 (点击填入)",
141
  components=[gr.Textbox(visible=False)],
142
  samples=[["生成建议..."], ["生成建议..."], ["生成建议..."]],
143
  type="values"
144
  )
145
-
146
- refresh_suggestions_btn = gr.Button("🎲 换一批建议", size="sm", variant="secondary") # Combined trigger
147
-
 
 
148
  with gr.Row():
149
- btn_generate_para = gr.Button("整段续写 (Cmd+Enter)", size="sm", variant="primary", elem_id="btn-action-create-paragraph")
150
- btn_change_para = gr.Button("换一个", size="sm")
151
- btn_accept_para = gr.Button("采纳", size="sm")
152
 
153
  para_suggestion_display = gr.Textbox(
154
  show_label=False,
155
- placeholder="(点击“整段续写”生成内容...)",
156
  lines=3,
157
  interactive=False
158
  )
159
 
160
  # Area 3: Adjust/Polish (Placeholder)
161
  with gr.Column(scale=1, min_width=200):
162
- gr.Markdown("#### 🛠️ 调整润色")
163
- gr.Markdown("(Coming Soon)")
164
 
165
  # --- TOOLBAR ---
166
  with gr.Row(elem_classes=["toolbar"]):
167
- stats_display = gr.Markdown("0 Words | 0 mins")
168
-
169
- # --- EDITOR ---
170
  editor = gr.Textbox(
171
- label="沉浸写作画布",
172
- placeholder="开始你的创作...",
173
  lines=25, # Reduced lines slightly to accommodate ribbon
174
  elem_classes=["writing-editor"],
175
  elem_id="writing-editor",
@@ -269,4 +272,111 @@ def create_smart_writer_tab():
269
  fn=suggest_new_kb_terms_agent,
270
  inputs=[kb_input, editor],
271
  outputs=[suggested_kb_dataframe]
272
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
2
  from smart_writer_kit.agent_for_streaming_completion import fetch_flow_suggestion_agent, accept_flow_suggestion_agent
3
  from smart_writer_kit.agent_for_inspiration_expansion import fetch_inspiration_agent, apply_inspiration_agent
4
  from smart_writer_kit.agent_for_paragraph_continuation import fetch_paragraph_continuation_agent
 
6
  from smart_writer_kit.agent_for_outline_update import update_outline_status_agent
7
  from smart_writer_kit.agent_for_kb_update import suggest_new_kb_terms_agent
8
  from ui_components.debounce_manager import DebounceManager
9
+ from i18n import get_text
10
 
11
  # --- Mock Data (for UI population only) ---
12
 
 
16
  """
17
 
18
  MOCK_KNOWLEDGE_BASE = [
19
+ ["Alpha", "故事的主角,女性人形机器人,外表与人类无异。性格悠闲"],
20
  ["横滨", "故事发生的主要城市。由于海平面上升,城市部分地区被淹没,形成独特的水上景观。"]
21
  ]
22
 
 
35
  ]
36
 
37
  # --- UI Helper Functions ---
38
+ def get_stats(text, lang):
39
  """Calculate word count and read time."""
40
  if not text:
41
+ return get_text("writer_stats_default", lang)
42
  words = len(text.split())
43
  read_time = max(1, words // 200) # Average reading speed
44
+ return get_text("writer_stats_format", lang).format(
45
+ words=words, read_time=read_time
46
+ )
47
 
48
  # --- UI Construction ---
49
 
50
+ def create_smart_writer_tab(initial_lang: str):
51
+ debounce_manager = DebounceManager(debounce_time=2.0, tick_time=0.3, loading_text=get_text("writer_debounce_loading_text", initial_lang))
 
52
 
53
  with gr.Row(equal_height=False, elem_id="indicator-writing-tab"):
54
  # --- Left Column: Entity Console ---
55
  with gr.Column(scale=1) as left_panel:
56
 
57
  style_input = gr.Textbox(
58
+ label=get_text("writer_style_input_label", initial_lang),
59
  lines=8,
60
  value=MOCK_STYLE,
61
  interactive=True
62
  )
63
 
64
+ with gr.Accordion(
65
+ get_text("writer_kb_accordion_label", initial_lang), open=True
66
+ ) as kb_accordion:
67
  kb_input = gr.Dataframe(
68
+ headers=[get_text("writer_kb_dataframe_headers", initial_lang), '?'],
69
  datatype=["str", "str"],
70
  value=MOCK_KNOWLEDGE_BASE,
71
  interactive=True,
72
  wrap=True
73
  )
74
  with gr.Row():
75
+ btn_suggest_kb = gr.Button(get_text("writer_suggest_kb_button", initial_lang), size="sm")
76
 
77
  suggested_kb_dataframe = gr.Dataframe(
78
  headers=["Term", "Description"],
79
  datatype=["str", "str"],
80
  visible=False,
81
  interactive=False,
82
+ label=get_text("writer_suggested_kb_label", initial_lang),
83
  )
84
 
85
+ with gr.Accordion(get_text("writer_short_outline_accordion_label", initial_lang), open=True) as short_outline_accordion:
86
 
87
  short_outline_input = gr.Dataframe(
88
+ headers=[get_text("writer_short_outline_dataframe_headers", initial_lang), '?'],
89
  datatype=["bool", "str"],
90
  value=MOCK_SHORT_TERM_OUTLINE,
91
  interactive=True,
92
+ label="???",
93
  col_count=(2, "fixed"),
94
  )
95
  with gr.Row():
96
+ btn_sync_outline = gr.Button(get_text("writer_sync_outline_button", initial_lang), size="sm")
97
 
98
+ with gr.Accordion(get_text("writer_long_outline_accordion_label", initial_lang), open=False) as long_outline_accordion:
99
  long_outline_input = gr.Dataframe(
100
+ headers=[get_text("writer_short_outline_dataframe_headers", initial_lang), '?'],
101
  datatype=["bool", "str"],
102
  value=MOCK_LONG_TERM_OUTLINE,
103
  interactive=True,
104
+ label="???",
105
  col_count=(2, "fixed"),
106
  )
107
 
 
116
 
117
  flow_suggestion_display = gr.Textbox(
118
  show_label=True,
119
+ label=get_text("writer_flow_suggestion_label", initial_lang),
120
+ placeholder=get_text("writer_flow_suggestion_placeholder", initial_lang),
121
  lines=3,
122
  interactive=False,
123
  elem_classes=["flow-suggestion-box"],
124
  )
125
 
126
+ btn_accept_flow = gr.Button(get_text("writer_accept_flow_button", initial_lang),size="sm",variant="primary",elem_id="btn-action-accept-flow")
127
+ btn_change_flow = gr.Button(get_text("writer_change_flow_button", initial_lang),size="sm",elem_id="btn-action-change-flow")
128
 
129
  # Debounce Progress Indicator (Using Manager)
130
  debounce_state, debounce_timer, debounce_progress = debounce_manager.create_ui()
131
+ debounce_progress.visible = True
132
 
133
  # Area 2: Paragraph Continuation (Inspiration)
134
  with gr.Column(scale=1, min_width=200):
135
  inspiration_prompt_input = gr.Textbox(
136
+ label=get_text("writer_inspiration_prompt_label", initial_lang),
137
+ placeholder=get_text("writer_inspiration_prompt_placeholder", initial_lang),
138
  lines=2
139
  )
 
140
  prompt_suggestions_dataset = gr.Dataset(
141
+ label=get_text("writer_prompt_suggestions_label", initial_lang),
142
  components=[gr.Textbox(visible=False)],
143
  samples=[["生成建议..."], ["生成建议..."], ["生成建议..."]],
144
  type="values"
145
  )
146
+ refresh_suggestions_btn = gr.Button(
147
+ get_text("writer_refresh_suggestions_button", initial_lang),
148
+ size="sm",
149
+ variant="secondary",
150
+ )
151
  with gr.Row():
152
+ btn_generate_para = gr.Button(get_text("writer_generate_para_button", initial_lang),size="sm",variant="primary",elem_id="btn-action-create-paragraph")
153
+ btn_change_para = gr.Button(get_text("writer_change_para_button", initial_lang),size="sm")
154
+ btn_accept_para = gr.Button(get_text("writer_accept_para_button", initial_lang),size="sm")
155
 
156
  para_suggestion_display = gr.Textbox(
157
  show_label=False,
158
+ placeholder=get_text("writer_para_suggestion_placeholder", initial_lang),
159
  lines=3,
160
  interactive=False
161
  )
162
 
163
  # Area 3: Adjust/Polish (Placeholder)
164
  with gr.Column(scale=1, min_width=200):
165
+ polish_title = gr.Markdown(get_text("writer_polish_title", initial_lang))
166
+ polish_soon = gr.Markdown(get_text("writer_coming_soon", initial_lang))
167
 
168
  # --- TOOLBAR ---
169
  with gr.Row(elem_classes=["toolbar"]):
170
+ # --- EDITOR ---
171
+ stats_display = gr.Markdown(get_text("writer_stats_default", initial_lang))
172
+
173
  editor = gr.Textbox(
174
+ label=get_text("writer_editor_label", initial_lang),
175
+ placeholder=get_text("writer_editor_placeholder", initial_lang),
176
  lines=25, # Reduced lines slightly to accommodate ribbon
177
  elem_classes=["writing-editor"],
178
  elem_id="writing-editor",
 
272
  fn=suggest_new_kb_terms_agent,
273
  inputs=[kb_input, editor],
274
  outputs=[suggested_kb_dataframe]
275
+ )
276
+
277
+ return {
278
+ "style_input": style_input,
279
+ "kb_accordion": kb_accordion,
280
+ "kb_input": kb_input,
281
+ "btn_suggest_kb": btn_suggest_kb,
282
+ "suggested_kb_dataframe": suggested_kb_dataframe,
283
+ "short_outline_accordion": short_outline_accordion,
284
+ "short_outline_input": short_outline_input,
285
+ "btn_sync_outline": btn_sync_outline,
286
+ "long_outline_accordion": long_outline_accordion,
287
+ "long_outline_input": long_outline_input,
288
+ "flow_suggestion_display": flow_suggestion_display,
289
+ "btn_accept_flow": btn_accept_flow,
290
+ "btn_change_flow": btn_change_flow,
291
+ "inspiration_prompt_input": inspiration_prompt_input,
292
+ "prompt_suggestions_dataset": prompt_suggestions_dataset,
293
+ "refresh_suggestions_btn": refresh_suggestions_btn,
294
+ "btn_generate_para": btn_generate_para,
295
+ "btn_change_para": btn_change_para,
296
+ "btn_accept_para": btn_accept_para,
297
+ "para_suggestion_display": para_suggestion_display,
298
+ "polish_title": polish_title,
299
+ "polish_soon": polish_soon,
300
+ "stats_display": stats_display,
301
+ "editor": editor,
302
+ }
303
+
304
+
305
+ def update_language(lang: str, components: dict):
306
+ return {
307
+ components["style_input"]: gr.update(
308
+ label=get_text("writer_style_input_label", lang)
309
+ ),
310
+ components["kb_accordion"]: gr.update(
311
+ label=get_text("writer_kb_accordion_label", lang)
312
+ ),
313
+ components["kb_input"]: gr.update(
314
+ headers=get_text("writer_kb_dataframe_headers", lang)
315
+ ),
316
+ components["btn_suggest_kb"]: gr.update(
317
+ value=get_text("writer_suggest_kb_button", lang)
318
+ ),
319
+ components["suggested_kb_dataframe"]: gr.update(
320
+ label=get_text("writer_suggested_kb_label", lang)
321
+ ),
322
+ components["short_outline_accordion"]: gr.update(
323
+ label=get_text("writer_short_outline_accordion_label", lang)
324
+ ),
325
+ components["short_outline_input"]: gr.update(
326
+ headers=get_text("writer_short_outline_dataframe_headers", lang)
327
+ ),
328
+ components["btn_sync_outline"]: gr.update(
329
+ value=get_text("writer_sync_outline_button", lang)
330
+ ),
331
+ components["long_outline_accordion"]: gr.update(
332
+ label=get_text("writer_long_outline_accordion_label", lang)
333
+ ),
334
+ components["long_outline_input"]: gr.update(
335
+ headers=get_text("writer_short_outline_dataframe_headers", lang)
336
+ ), # Assuming same headers
337
+ components["flow_suggestion_display"]: gr.update(
338
+ label=get_text("writer_flow_suggestion_label", lang),
339
+ placeholder=get_text("writer_flow_suggestion_placeholder", lang),
340
+ ),
341
+ components["btn_accept_flow"]: gr.update(
342
+ value=get_text("writer_accept_flow_button", lang)
343
+ ),
344
+ components["btn_change_flow"]: gr.update(
345
+ value=get_text("writer_change_flow_button", lang)
346
+ ),
347
+ components["inspiration_prompt_input"]: gr.update(
348
+ label=get_text("writer_inspiration_prompt_label", lang),
349
+ placeholder=get_text("writer_inspiration_prompt_placeholder", lang),
350
+ ),
351
+ components["prompt_suggestions_dataset"]: gr.update(
352
+ label=get_text("writer_prompt_suggestions_label", lang)
353
+ ),
354
+ components["refresh_suggestions_btn"]: gr.update(
355
+ value=get_text("writer_refresh_suggestions_button", lang)
356
+ ),
357
+ components["btn_generate_para"]: gr.update(
358
+ value=get_text("writer_generate_para_button", lang)
359
+ ),
360
+ components["btn_change_para"]: gr.update(
361
+ value=get_text("writer_change_para_button", lang)
362
+ ),
363
+ components["btn_accept_para"]: gr.update(
364
+ value=get_text("writer_accept_para_button", lang)
365
+ ),
366
+ components["para_suggestion_display"]: gr.update(
367
+ placeholder=get_text("writer_para_suggestion_placeholder", lang)
368
+ ),
369
+ components["polish_title"]: gr.update(
370
+ value=get_text("writer_polish_title", lang)
371
+ ),
372
+ components["polish_soon"]: gr.update(
373
+ value=get_text("writer_coming_soon", lang)
374
+ ),
375
+ components["editor"]: gr.update(
376
+ label=get_text("writer_editor_label", lang),
377
+ placeholder=get_text("writer_editor_placeholder", lang),
378
+ ),
379
+ components["stats_display"]: gr.update(
380
+ value=get_text("writer_stats_default", lang)
381
+ ), # Reset stats on lang change
382
+ }
tab_test.py DELETED
@@ -1,27 +0,0 @@
1
- import time
2
-
3
- def run_model_handler_test():
4
- """
5
- Simulates a test for the ModelHandler's get_response method.
6
- """
7
- log = []
8
- log.append("Running ModelHandler test...")
9
- # Simulate some test logic
10
- time.sleep(1)
11
- log.append("ModelHandler test passed: Placeholder response received.")
12
- print("\n".join(log)) # Also print to stdio
13
- return "\n".join(log)
14
-
15
- def run_clear_chat_test():
16
- """
17
- Simulates a test for the clear_chat functionality.
18
- """
19
- log = []
20
- log.append("Running clear_chat test...")
21
- # Simulate some test logic
22
- time.sleep(1)
23
- log.append("clear_chat test passed: Chatbot and textbox cleared.")
24
- print("\n".join(log)) # Also print to stdio
25
- return "\n".join(log)
26
-
27
- # You can add more test functions here
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tab_welcome.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from i18n import get_text
3
+
4
+ def create_welcome_tab(initial_lang: str):
5
+ """
6
+ Creates the UI components for the Welcome Tab.
7
+ Returns a dictionary of all component handles that need dynamic updates.
8
+ """
9
+ with gr.TabItem(get_text("welcome_tab_title", initial_lang)) as welcome_tab:
10
+ with gr.Column(elem_classes=["welcome-container"]):
11
+ welcome_header_md = gr.Markdown(f"# {get_text('welcome_header', initial_lang)}")
12
+ welcome_desc_md = gr.Markdown(get_text('welcome_description', initial_lang))
13
+
14
+ with gr.Row():
15
+ with gr.Column(scale=1):
16
+ welcome_chat_desc_md = gr.Markdown(f"### {get_text('tab_chat', initial_lang)}\n{get_text('welcome_chat_desc', initial_lang)}")
17
+ with gr.Column(scale=1):
18
+ welcome_code_desc_md = gr.Markdown(f"### {get_text('tab_code', initial_lang)}\n{get_text('welcome_code_desc', initial_lang)}")
19
+ with gr.Column(scale=1):
20
+ welcome_writer_desc_md = gr.Markdown(f"### {get_text('tab_writer', initial_lang)}\n{get_text('welcome_writer_desc', initial_lang)}")
21
+
22
+ gr.Markdown("---")
23
+
24
+ with gr.Row():
25
+ welcome_lang_select_md = gr.Markdown(f"### {get_text('welcome_select_language', initial_lang)}")
26
+
27
+ with gr.Row():
28
+ en_button = gr.Button(get_text('lang_en', initial_lang))
29
+ zh_button = gr.Button(get_text('lang_zh', initial_lang))
30
+
31
+ en_button.click(
32
+ fn=None,
33
+ inputs=[],
34
+ js="() => { window.dispatchEvent(new CustomEvent('langChange.SpaceApp', { detail: { lang: 'en' } })); }"
35
+ )
36
+ zh_button.click(
37
+ fn=None,
38
+ inputs=[],
39
+ js="() => { window.dispatchEvent(new CustomEvent('langChange.SpaceApp', { detail: { lang: 'zh' } })); }"
40
+ )
41
+
42
+ # Return a dictionary for easier access in app.py
43
+ components = {
44
+ "tab": welcome_tab,
45
+ "header": welcome_header_md,
46
+ "description": welcome_desc_md,
47
+ "chat_description": welcome_chat_desc_md,
48
+ "code_description": welcome_code_desc_md,
49
+ "writer_description": welcome_writer_desc_md,
50
+ "lang_select_header": welcome_lang_select_md,
51
+ "en_button": en_button,
52
+ "zh_button": zh_button
53
+ }
54
+
55
+ return components
56
+
57
+ def update_language(lang: str, components: dict):
58
+ """
59
+ Returns a dictionary mapping components to their gr.update calls.
60
+ """
61
+ updates = {
62
+ components["tab"]: gr.update(label=get_text("welcome_tab_title", lang)),
63
+ components["header"]: gr.update(value=f"# {get_text('welcome_header', lang)}"),
64
+ components["description"]: gr.update(value=get_text('welcome_description', lang)),
65
+ components["chat_description"]: gr.update(value=f"### {get_text('tab_chat', lang)}\n{get_text('welcome_chat_desc', lang)}"),
66
+ components["code_description"]: gr.update(value=f"### {get_text('tab_code', lang)}\n{get_text('welcome_code_desc', lang)}"),
67
+ components["writer_description"]: gr.update(value=f"### {get_text('tab_writer', lang)}\n{get_text('welcome_writer_desc', lang)}"),
68
+ components["lang_select_header"]: gr.update(value=f"### {get_text('welcome_select_language', lang)}"),
69
+ components["en_button"]: gr.update(value=get_text('lang_en', lang)),
70
+ components["zh_button"]: gr.update(value=get_text('lang_zh', lang)),
71
+ }
72
+ return updates