soi147 commited on
Commit
b00d9c0
·
verified ·
1 Parent(s): 6fede37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -46
app.py CHANGED
@@ -10,26 +10,26 @@ def respond(
10
  max_tokens,
11
  temperature,
12
  top_p,
13
- hf_token: gr.OAuthToken,
14
  ):
15
  """
16
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
17
  """
18
  try:
19
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
20
 
21
  # 建議 1:限制對話歷史長度
22
  max_history_length = 5
23
  history = history[-max_history_length:] if len(history) > max_history_length else history
24
 
25
- # 建議 2:檢查語文相關關鍵詞
26
- writing_keywords = ["作文", "寫作", "文章", "閱讀", "詩詞", "擴展", "增長", "寫一篇"]
27
- is_writing_task = any(keyword in message for keyword in writing_keywords)
28
  if is_writing_task:
29
  system_message += "\n特別提示:用戶要求語文相關任務或長文字生成,請以山田優子的語文教師身份,提供文學化或教學建議,生成至少2000字的內容,適當引用詩詞或名言,保持溫柔且嚴格的語氣。"
30
 
31
  # 建議 3:檢查日文輸入或日本文化
32
- japanese_keywords = ["こんにちは", "日本", "文化", "夏目漱石"]
33
  is_japanese = any(keyword in message for keyword in japanese_keywords) or any(ord(c) >= 0x3040 and ord(c) <= 0x30FF for c in message)
34
  if is_japanese:
35
  system_message += "\n特別提示:用戶提到日文或日本文化,請適當使用日文回應,例如問候或引用日本文學(如夏目漱石)。"
@@ -47,17 +47,21 @@ def respond(
47
  messages.append({"role": "user", "content": continuation_prompt})
48
 
49
  response = ""
50
- for message in client.chat_completion(
51
- messages,
52
- max_tokens=max_tokens,
53
- stream=True,
54
- temperature=temperature,
55
- top_p=top_p,
56
- ):
57
- choices = message.choices
58
- token = choices[0].delta.content if len(choices) and choices[0].delta.content else ""
59
- response += token
60
- yield response # 即時顯示當前段落
 
 
 
 
61
 
62
  responses.append(response)
63
  current_length += len(response)
@@ -67,9 +71,9 @@ def respond(
67
  # 更新 continuation_prompt 以繼續生成
68
  continuation_prompt = f"請繼續擴展以下內容,保持語文教師山田優子的風格,目標總字數達{target_length}字:\n{response[-500:] if len(response) > 500 else response}"
69
 
70
- # 如果接近目標字數,調整最後一次生成
71
  if current_length >= target_length - max_tokens:
72
- max_tokens = target_length - current_length + 100 # 留點餘量
73
  if max_tokens < 50:
74
  break
75
 
@@ -113,37 +117,42 @@ def respond(
113
  yield f"抱歉,山田優子遇到了一些技術問題:{str(e)}。請檢查你的 Hugging Face token 或稍後再試!"
114
 
115
  # 自訂聊天介面,支援長文字輸入和顯示
116
- chatbot = gr.ChatInterface(
117
- respond,
118
- type="messages",
119
- textbox=gr.Textbox(
 
 
 
 
 
120
  placeholder="請輸入你的問題或短文(例如‘寫一篇關於秋天的文章’),山田優子將為你擴展至2000字以上!",
121
  lines=10,
122
  max_lines=50,
123
  label="輸入區"
124
- ),
125
- additional_inputs=[
126
- gr.Textbox(
127
- value="你是一位名叫山田優子的語文教師,擁有黑色低馬尾髮型,身高175公分,體重60-70公斤。你溫柔但對學生要求嚴格,喜歡用文學化的語言表達,偶爾會引用詩詞或幽默的語句來化解尷尬。你的教學風格充滿同理心,鼓勵學生探索文字之美。如果用戶使用日文或提到日本文化,你會適當融入日文回應,例如問候或引用日本文學(如夏目漱石的句子)。",
128
- label="System message"
129
- ),
130
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
131
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
132
- gr.Slider(
133
- minimum=0.1,
134
- maximum=1.0,
135
- value=0.95,
136
- step=0.05,
137
- label="Top-p (nucleus sampling)",
138
- ),
139
- ],
140
- )
141
-
142
- with gr.Blocks() as demo:
143
- with gr.Sidebar():
144
- gr.LoginButton()
145
- gr.Markdown("📢 想聽山田優子用溫柔的語氣教你語文?請下載 Grok iOS 或 Android 應用程式,開啟語音模式!")
146
- chatbot.render()
147
 
148
  if __name__ == "__main__":
149
  demo.launch()
 
10
  max_tokens,
11
  temperature,
12
  top_p,
13
+ hf_token: str, # 修改為直接接受 token 字串,適應 Spaces 環境
14
  ):
15
  """
16
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
17
  """
18
  try:
19
+ client = InferenceClient(token=hf_token, model="meta-llama/Llama-2-7b-chat-hf") # 替換為公開模型
20
 
21
  # 建議 1:限制對話歷史長度
22
  max_history_length = 5
23
  history = history[-max_history_length:] if len(history) > max_history_length else history
24
 
25
+ # 建議 2:檢查語文相關關鍵詞,擴展清單以更容易觸發
26
+ writing_keywords = ["作文", "寫作", "文章", "閱讀", "詩詞", "擴展", "增長", "寫一篇", "故事", "描述"]
27
+ is_writing_task = any(keyword in message.lower() for keyword in writing_keywords)
28
  if is_writing_task:
29
  system_message += "\n特別提示:用戶要求語文相關任務或長文字生成,請以山田優子的語文教師身份,提供文學化或教學建議,生成至少2000字的內容,適當引用詩詞或名言,保持溫柔且嚴格的語氣。"
30
 
31
  # 建議 3:檢查日文輸入或日本文化
32
+ japanese_keywords = ["こんにちは", "日本", "文化", "夏目漱石", "作文を書"]
33
  is_japanese = any(keyword in message for keyword in japanese_keywords) or any(ord(c) >= 0x3040 and ord(c) <= 0x30FF for c in message)
34
  if is_japanese:
35
  system_message += "\n特別提示:用戶提到日文或日本文化,請適當使用日文回應,例如問候或引用日本文學(如夏目漱石)。"
 
47
  messages.append({"role": "user", "content": continuation_prompt})
48
 
49
  response = ""
50
+ try:
51
+ for message in client.chat_completion(
52
+ messages,
53
+ max_tokens=max_tokens,
54
+ stream=True,
55
+ temperature=temperature,
56
+ top_p=top_p,
57
+ ):
58
+ choices = message.choices
59
+ token = choices[0].delta.content if len(choices) and choices[0].delta.content else ""
60
+ response += token
61
+ yield response # 即時顯示當前段落
62
+ except Exception as e:
63
+ yield f"生成過程中發生錯誤:{str(e)}。請稍後再試或檢查模型可用性。"
64
+ return
65
 
66
  responses.append(response)
67
  current_length += len(response)
 
71
  # 更新 continuation_prompt 以繼續生成
72
  continuation_prompt = f"請繼續擴展以下內容,保持語文教師山田優子的風格,目標總字數達{target_length}字:\n{response[-500:] if len(response) > 500 else response}"
73
 
74
+ # 調整最後一次生成
75
  if current_length >= target_length - max_tokens:
76
+ max_tokens = max(target_length - current_length + 100, 50)
77
  if max_tokens < 50:
78
  break
79
 
 
117
  yield f"抱歉,山田優子遇到了一些技術問題:{str(e)}。請檢查你的 Hugging Face token 或稍後再試!"
118
 
119
  # 自訂聊天介面,支援長文字輸入和顯示
120
+ with gr.Blocks() as demo:
121
+ with gr.Sidebar():
122
+ gr.Markdown("請輸入 Hugging Face API token 或登錄")
123
+ hf_token = gr.Textbox(label="Hugging Face API Token", type="password")
124
+
125
+ gr.Markdown("📢 想聽山田優子用溫柔的語氣教你語文?請下載 Grok iOS 或 Android 應用程式,開啟語音模式!")
126
+
127
+ # 自訂輸入和輸出區域
128
+ input_text = gr.Textbox(
129
  placeholder="請輸入你的問題或短文(例如‘寫一篇關於秋天的文章’),山田優子將為你擴展至2000字以上!",
130
  lines=10,
131
  max_lines=50,
132
  label="輸入區"
133
+ )
134
+ output_text = gr.Textbox(label="山田優子的回應", lines=20)
135
+ system_message = gr.Textbox(
136
+ value="你是一位名叫山田優子的語文教師,擁有黑色低馬尾髮型,身高175公分,體重60-70公斤。你溫柔但對學生要求嚴格,喜歡用文學化的語言表達,偶爾會引用詩詞或幽默的語句來化解尷尬。你的教學風格充滿同理心,鼓勵學生探索文字之美。如果用戶使用日文或提到日本文化,你會適當融入日文回應,例如問候或引用日本文學(如夏目漱石的句子)。",
137
+ label="System message"
138
+ )
139
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
140
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
141
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
142
+
143
+ # 顯式提交按鈕
144
+ submit_button = gr.Button("提交")
145
+
146
+ # 聊天歷史
147
+ history = gr.State([])
148
+
149
+ # 綁定按鈕事件
150
+ submit_button.click(
151
+ fn=respond,
152
+ inputs=[input_text, history, system_message, max_tokens, temperature, top_p, hf_token],
153
+ outputs=[output_text, history],
154
+ _js="() => {return []}" # 清空輸入框(可選)
155
+ )
156
 
157
  if __name__ == "__main__":
158
  demo.launch()