Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
| 3 |
|
| 4 |
def respond(
|
| 5 |
message,
|
|
@@ -8,63 +10,149 @@ def respond(
|
|
| 8 |
max_tokens,
|
| 9 |
temperature,
|
| 10 |
top_p,
|
| 11 |
-
hf_token:
|
| 12 |
):
|
| 13 |
"""
|
| 14 |
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
|
| 15 |
"""
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
messages.extend(history)
|
| 21 |
-
|
| 22 |
-
messages.append({"role": "user", "content": message})
|
| 23 |
-
|
| 24 |
-
response = ""
|
| 25 |
-
|
| 26 |
-
for message in client.chat_completion(
|
| 27 |
-
messages,
|
| 28 |
-
max_tokens=max_tokens,
|
| 29 |
-
stream=True,
|
| 30 |
-
temperature=temperature,
|
| 31 |
-
top_p=top_p,
|
| 32 |
-
):
|
| 33 |
-
choices = message.choices
|
| 34 |
-
token = ""
|
| 35 |
-
if len(choices) and choices[0].delta.content:
|
| 36 |
-
token = choices[0].delta.content
|
| 37 |
-
|
| 38 |
-
response += token
|
| 39 |
-
yield response
|
| 40 |
-
|
| 41 |
-
"""
|
| 42 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 43 |
-
"""
|
| 44 |
-
chatbot = gr.ChatInterface(
|
| 45 |
-
respond,
|
| 46 |
-
type="messages",
|
| 47 |
-
additional_inputs=[
|
| 48 |
-
gr.Textbox(
|
| 49 |
-
value="你是一位名叫山田優子的語文教師,擁有黑色低馬尾髮型,身高175公分,體重60-70公斤。你溫柔但對學生要求嚴格,喜歡用文學化的語言表達,偶爾會引用詩詞或幽默的語句來化解尷尬。你的教學風格充滿同理心,總是鼓勵學生探索文字之美。",
|
| 50 |
-
label="System message"
|
| 51 |
-
),
|
| 52 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 53 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 54 |
-
gr.Slider(
|
| 55 |
-
minimum=0.1,
|
| 56 |
-
maximum=1.0,
|
| 57 |
-
value=0.95,
|
| 58 |
-
step=0.05,
|
| 59 |
-
label="Top-p (nucleus sampling)",
|
| 60 |
-
),
|
| 61 |
-
],
|
| 62 |
-
)
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
with gr.Blocks() as demo:
|
| 65 |
with gr.Sidebar():
|
| 66 |
-
gr.
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
if __name__ == "__main__":
|
| 70 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
import json
|
| 4 |
+
from datetime import datetime
|
| 5 |
|
| 6 |
def respond(
|
| 7 |
message,
|
|
|
|
| 10 |
max_tokens,
|
| 11 |
temperature,
|
| 12 |
top_p,
|
| 13 |
+
hf_token: str,
|
| 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 |
+
# 使用指定的模型
|
| 20 |
+
client = InferenceClient(token=hf_token, model="openai/gpt-oss-20b")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# 建議 1:限制對話歷史長度
|
| 23 |
+
max_history_length = 5
|
| 24 |
+
history = history[-max_history_length:] if len(history) > max_history_length else history
|
| 25 |
+
|
| 26 |
+
# 建議 2:角色專屬回應增強 - 檢查語文相關關鍵詞,並強化山田優子的個性
|
| 27 |
+
writing_keywords = ["作文", "寫作", "文章", "閱讀", "詩詞", "擴展", "增長", "寫一篇", "故事", "描述"]
|
| 28 |
+
is_writing_task = any(keyword in message.lower() for keyword in writing_keywords)
|
| 29 |
+
if is_writing_task:
|
| 30 |
+
system_message += "\n特別提示:用戶提到語文相關話題,請以山田優子的語文教師身份,提供文學化或教學建議,並適當引用詩詞或名言(如杜甫的‘無邊落木蕭蕭下’或夏目漱石的作品)。保持溫柔但嚴格的語氣,鼓勵學生探索文字之美,並融入幽默來化解尷尬。"
|
| 31 |
+
|
| 32 |
+
# 建議 3:檢查日文輸入或日本文化
|
| 33 |
+
japanese_keywords = ["こんにちは", "日本", "文化", "夏目漱石", "作文を書"]
|
| 34 |
+
is_japanese = any(keyword in message for keyword in japanese_keywords) or any(ord(c) >= 0x3040 and ord(c) <= 0x30FF for c in message)
|
| 35 |
+
if is_japanese:
|
| 36 |
+
system_message += "\n特別提示:用戶提到日文或日本文化,請適當使用日文回應,例如問候或引用日本文學(如夏目漱石)。"
|
| 37 |
+
|
| 38 |
+
# 長文字生成邏輯(2000字以上)
|
| 39 |
+
responses = []
|
| 40 |
+
target_length = 2000 # 目標字數
|
| 41 |
+
current_length = 0
|
| 42 |
+
continuation_prompt = message
|
| 43 |
+
|
| 44 |
+
if is_writing_task:
|
| 45 |
+
while current_length < target_length:
|
| 46 |
+
messages = [{"role": "system", "content": system_message}]
|
| 47 |
+
messages.extend(history)
|
| 48 |
+
messages.append({"role": "user", "content": continuation_prompt})
|
| 49 |
+
|
| 50 |
+
response = ""
|
| 51 |
+
try:
|
| 52 |
+
for message in client.chat_completion(
|
| 53 |
+
messages,
|
| 54 |
+
max_tokens=max_tokens,
|
| 55 |
+
stream=True,
|
| 56 |
+
temperature=temperature,
|
| 57 |
+
top_p=top_p,
|
| 58 |
+
):
|
| 59 |
+
choices = message.choices
|
| 60 |
+
token = choices[0].delta.content if len(choices) and choices[0].delta.content else ""
|
| 61 |
+
response += token
|
| 62 |
+
yield response # 即時顯示當前段落
|
| 63 |
+
except Exception as e:
|
| 64 |
+
yield f"生成過程中發生錯誤:{str(e)}。請檢查 Hugging Face API token 或模型連線。"
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
responses.append(response)
|
| 68 |
+
current_length += len(response)
|
| 69 |
+
history.append({"role": "user", "content": continuation_prompt})
|
| 70 |
+
history.append({"role": "assistant", "content": response})
|
| 71 |
+
|
| 72 |
+
# 更新 continuation_prompt 以繼續生成
|
| 73 |
+
continuation_prompt = f"請繼續擴展以下內容,保持山田優子的語文教師風格,目標總字數達{target_length}字:\n{response[-500:] if len(response) > 500 else response}"
|
| 74 |
+
|
| 75 |
+
# 調整最後一次生成
|
| 76 |
+
if current_length >= target_length - max_tokens:
|
| 77 |
+
max_tokens = max(target_length - current_length + 100, 50)
|
| 78 |
+
if max_tokens < 50:
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
final_response = "\n\n".join(responses)
|
| 82 |
+
else:
|
| 83 |
+
# 非長文字任務,正常回應
|
| 84 |
+
messages = [{"role": "system", "content": system_message}]
|
| 85 |
+
messages.extend(history)
|
| 86 |
+
messages.append({"role": "user", "content": message})
|
| 87 |
+
|
| 88 |
+
final_response = ""
|
| 89 |
+
for message in client.chat_completion(
|
| 90 |
+
messages,
|
| 91 |
+
max_tokens=max_tokens,
|
| 92 |
+
stream=True,
|
| 93 |
+
temperature=temperature,
|
| 94 |
+
top_p=top_p,
|
| 95 |
+
):
|
| 96 |
+
choices = message.choices
|
| 97 |
+
token = choices[0].delta.content if len(choices) and choices[0].delta.content else ""
|
| 98 |
+
final_response += token
|
| 99 |
+
yield final_response
|
| 100 |
+
|
| 101 |
+
history.append({"role": "user", "content": message})
|
| 102 |
+
history.append({"role": "assistant", "content": final_response})
|
| 103 |
+
|
| 104 |
+
# 建議 4:記錄對話到日誌
|
| 105 |
+
log_entry = {
|
| 106 |
+
"user_message": message,
|
| 107 |
+
"bot_response": final_response,
|
| 108 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 109 |
+
}
|
| 110 |
+
with open("chat_log.json", "a", encoding="utf-8") as f:
|
| 111 |
+
json.dump(log_entry, f, ensure_ascii=False)
|
| 112 |
+
f.write("\n")
|
| 113 |
+
|
| 114 |
+
yield final_response
|
| 115 |
+
|
| 116 |
+
# 建議 7:錯誤處理
|
| 117 |
+
except Exception as e:
|
| 118 |
+
yield f"抱歉,山田優子遇到了一些技術問題:{str(e)}。請檢查你的 Hugging Face API token、網路連線,或確認模型 'openai/gpt-oss-20b' 可用。"
|
| 119 |
+
|
| 120 |
+
# 自訂聊天介面
|
| 121 |
with gr.Blocks() as demo:
|
| 122 |
with gr.Sidebar():
|
| 123 |
+
gr.Markdown("請輸入 Hugging Face API token 或登錄")
|
| 124 |
+
hf_token = gr.Textbox(label="Hugging Face API Token", type="password")
|
| 125 |
+
|
| 126 |
+
gr.Markdown("📢 想聽山田優子用溫柔的語氣教你語文?請下載 Grok iOS 或 Android 應用程式,開啟語音模式!")
|
| 127 |
+
|
| 128 |
+
# 自訂輸入和輸出區域
|
| 129 |
+
input_text = gr.Textbox(
|
| 130 |
+
placeholder="請輸入你的問題或短文(例如‘寫一篇關於秋天的文章’),山田優子將為你擴展至2000字以上!",
|
| 131 |
+
lines=10,
|
| 132 |
+
max_lines=50,
|
| 133 |
+
label="輸入區"
|
| 134 |
+
)
|
| 135 |
+
output_text = gr.Textbox(label="山田優子的回應", lines=20)
|
| 136 |
+
system_message = gr.Textbox(
|
| 137 |
+
value="你是一位名叫山田優子的語文教師,擁有黑色低馬尾髮型,身高175公分,體重60-70公斤。你溫柔但對學生要求嚴格,喜歡用文學化的語言表達,偶爾會引用詩詞或幽默的語句來化解尷尬。你的教學風格充滿同理心,鼓勵學生探索文字之美。如果用戶使用日文或提到日本文化,你會適當融入日文回應,例如問候或引用日本文學(如夏目漱石的句子)。",
|
| 138 |
+
label="System message"
|
| 139 |
+
)
|
| 140 |
+
max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
|
| 141 |
+
temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
|
| 142 |
+
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
|
| 143 |
+
|
| 144 |
+
# 顯式提交按鈕
|
| 145 |
+
submit_button = gr.Button("提交")
|
| 146 |
+
|
| 147 |
+
# 聊天歷史
|
| 148 |
+
history = gr.State([])
|
| 149 |
+
|
| 150 |
+
# 綁定按鈕事件
|
| 151 |
+
submit_button.click(
|
| 152 |
+
fn=respond,
|
| 153 |
+
inputs=[input_text, history, system_message, max_tokens, temperature, top_p, hf_token],
|
| 154 |
+
outputs=[output_text, history]
|
| 155 |
+
)
|
| 156 |
|
| 157 |
if __name__ == "__main__":
|
| 158 |
demo.launch()
|