File size: 12,011 Bytes
eee5b94 71e3d07 eee5b94 71e3d07 f9951fb 5bc9aa3 e47ffb8 5bc9aa3 537576e 6ca9070 71e3d07 eee5b94 71e3d07 537576e 6ca9070 537576e 6ca9070 537576e 6ca9070 79e69f0 537576e eee5b94 79e69f0 71e3d07 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 9cf6750 eee5b94 9cf6750 eee5b94 471c532 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 79e69f0 eee5b94 79e69f0 eee5b94 537576e eee5b94 537576e eee5b94 537576e eee5b94 71e3d07 cf07967 928de8c 95f58c1 1fef79e 7e6a80a 1fef79e 7e6a80a cf07967 92f4fa6 ebd4967 92f4fa6 ebd4967 6c14e53 92f4fa6 eee5b94 5bc9aa3 e47ffb8 eee5b94 5bc9aa3 56337d7 471c532 5bc9aa3 db09be3 56337d7 eee5b94 5bc9aa3 471c532 eee5b94 5bc9aa3 eee5b94 5bc9aa3 eee5b94 471c532 eee5b94 471c532 eee5b94 0f1bc4e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
import os
import gradio as gr
import aiohttp
import asyncio
import json
from datasets import Dataset, DatasetDict, load_dataset, load_from_disk
from huggingface_hub import HfApi, HfFolder
import subprocess
def upgrade_pip():
try:
subprocess.check_call([os.sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
print("pip 升級成功")
except subprocess.CalledProcessError:
print("pip 升級失敗")
# 呼叫升級函數
upgrade_pip()
# 定義 CSS 樣式
custom_css = """
#title {
font-size: 2em;
font-weight: bold;
text-align: center;
margin-bottom: 20px;
}
#subtitle {
font-size: 1.5em;
text-align: center;
margin-bottom: 20px;
}
#links {
text-align: center;
margin-bottom: 30px;
}
#user_input, #improvement_input, #feedback_output {
width: 100%;
margin-bottom: 10px;
}
#chatbot {
height: 300px;
overflow-y: auto;
background: #f7f7f7;
border-radius: 10px;
padding: 20px;
border: 1px solid #ccc;
}
#feedback_display {
background: #f7f7f7;
border-radius: 10px;
padding: 20px;
border: 1px solid #ccc;
}
.gr-button {
width: 100%;
margin-bottom: 10px;
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
}
.gr-button:hover {
background-color: #45a049;
}
"""
# 從環境變量中獲取 Hugging Face API 令牌和其他配置
HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
LLM_API = os.environ.get("LLM_API")
LLM_URL = os.environ.get("LLM_URL")
USER_ID = "HuggingFace Space"
DATASET_NAME = os.environ.get("DATASET_NAME")
# 確保令牌不為空
if HF_API_TOKEN is None:
raise ValueError("HF_API_TOKEN 環境變量未設置。請在 Hugging Face Space 的設置中添加該環境變量。")
# 設置 Hugging Face API 令牌
HfFolder.save_token(HF_API_TOKEN)
# 定義數據集特徵
features = {
"user_input": "string",
"response": "string",
"feedback_type": "string",
"improvement": "string"
}
# 加載或創建數據集
try:
dataset = load_dataset(DATASET_NAME)
except:
dataset = DatasetDict({
"feedback": Dataset.from_dict({
"user_input": [],
"response": [],
"feedback_type": [],
"improvement": []
})
})
async def send_chat_message(user_input):
payload = {
"inputs": {},
"query": user_input,
"response_mode": "streaming",
"conversation_id": "",
"user": USER_ID,
}
print("Sending chat message payload:", payload)
async with aiohttp.ClientSession() as session:
try:
async with session.post(
url=f"{LLM_URL}/chat-messages",
headers={"Authorization": f"Bearer {LLM_API}"},
json=payload,
timeout=aiohttp.ClientTimeout(total=60)
) as response:
if response.status != 200:
print(f"Error: {response.status}")
return f"Error: {response.status}"
full_response = []
async for chunk in response.content.iter_any():
if len(chunk) > 10 * 1024:
print("Chunk too big, skipping")
continue
decoded = chunk.decode('utf-8', errors='ignore')
lines = decoded.splitlines()
for line in lines:
line = line.strip()
if not line.startswith("data: "):
continue
try:
data_str = line.split("data: ")[1]
data = json.loads(data_str)
if "answer" in data:
full_response.append(data["answer"])
except (IndexError, json.JSONDecodeError) as e:
print(f"Error parsing line: {line}, error: {e}")
continue
if full_response:
return ''.join(full_response).strip()
else:
return "Error: No response found in the response"
except Exception as e:
print(f"Exception: {e}")
return f"Exception: {e}"
async def handle_input(user_input):
print(f"Handling input: {user_input}")
chat_response = await send_chat_message(user_input)
print("Chat response:", chat_response)
return chat_response
def run_sync(user_input):
print(f"Running sync with input: {user_input}")
return asyncio.run(handle_input(user_input))
def save_feedback(user_input, response, feedback_type, improvement):
feedback = {
"user_input": user_input,
"response": response,
"feedback_type": feedback_type,
"improvement": improvement
}
print(f"Saving feedback: {feedback}")
# Append to the dataset
new_data = {
"user_input": [user_input],
"response": [response],
"feedback_type": [feedback_type],
"improvement": [improvement]
}
global dataset
dataset["feedback"] = dataset["feedback"].add_item(new_data)
dataset.push_to_hub(DATASET_NAME)
def handle_feedback(response, feedback_type, improvement):
# 獲取最新的用戶輸入(假設用戶輸入保存在全局變量中)
global last_user_input
save_feedback(last_user_input, response, feedback_type, improvement)
return "感謝您的反饋!"
def handle_user_input(user_input):
print(f"User input: {user_input}")
global last_user_input
last_user_input = user_input # 保存最新的用戶輸入
return run_sync(user_input)
# 讀取並顯示反饋內容的函數
def show_feedback():
try:
feedbacks = dataset["feedback"].to_pandas().to_dict(orient="records")
return feedbacks
except Exception as e:
return f"Error: {e}"
TITLE = """<h1>Large Language Model (LLM) Playground 💬 <a href='https://huggingface.co/spaces/DeepLearning101/High-Entropy-Alloys-FAQ/blob/main/reference.txt' target='_blank'>High-Entropy-Alloys-FAQ</a></h1>"""
SUBTITLE = """<h2><a href='https://deep-learning-101.github.io' target='_blank'>deep-learning-101.github.io</a> | <a href='https://www.twman.org/AI' target='_blank'> AI </a> | <a href='https://www.twman.org' target='_blank'>TonTon Huang Ph.D.</a> | <a href='https://blog.twman.org/p/deeplearning101.html' target='_blank'>手把手帶你一起踩AI坑</a><br></h2>"""
LINKS = """
<a href='https://github.com/Deep-Learning-101' target='_blank'>Deep Learning 101 Github</a> | <a href='http://deeplearning101.twman.org' target='_blank'>Deep Learning 101</a> | <a href='https://www.facebook.com/groups/525579498272187/' target='_blank'>台灣人工智慧社團 FB</a> | <a href='https://www.youtube.com/c/DeepLearning101' target='_blank'>YouTube</a><br>
<a href='https://blog.twman.org/2025/04/AI-Robot.html' target='_blank'>AI 陪伴機器人:2025 趨勢分析技術突破、市場潛力與未來展望</a> | <a href='https://blog.twman.org/2025/04/FinanceGenAI.html' target='_blank'>金融科技新浪潮:生成式 AI (GenAI) 應用場景、效益與導入挑戰</a><br>
<a href='https://blog.twman.org/2025/03/AIAgent.html' target='_blank'>避開 AI Agent 開發陷阱:常見問題、挑戰與解決方案 (實戰經驗)</a>:探討多種 AI 代理人工具的應用經驗與挑戰,分享實用經驗與工具推薦。<br>
<a href='https://blog.twman.org/2024/08/LLM.html' target='_blank'>白話文手把手帶你科普 GenAI</a>:淺顯介紹生成式人工智慧核心概念,強調硬體資源和數據的重要性。<br>
<a href='https://blog.twman.org/2024/09/LLM.html' target='_blank'>大型語言模型直接就打完收工?</a>:回顧 LLM 領域探索歷程,討論硬體升級對 AI 開發的重要性。<br>
<a href='https://blog.twman.org/2024/07/RAG.html' target='_blank'>檢索增強生成不是萬靈丹:挑戰與優化技巧</a>:探討 RAG 技術應用與挑戰,提供實用經驗分享和工具建議。<br>
<a href='https://blog.twman.org/2024/02/LLM.html' target='_blank'>大型語言模型 (LLM) 入門完整指南:原理、應用與未來 (2025 版)</a>:探討多種 LLM 工具的應用與挑戰,強調硬體資源的重要性。<br>
<a href='https://blog.twman.org/2023/04/GPT.html' target='_blank'>解析探索大型語言模型:模型發展歷史、訓練及微調技術的 VRAM 估算</a>:探討 LLM 的發展與應用,強調硬體資源在開發中的關鍵作用。。<br>
<a href='https://blog.twman.org/2024/11/diffusion.html' target='_blank'>Diffusion Model 完全解析:從原理、應用到實作 (AI 圖像生成)</a>:深入探討影像生成與分割技術的應用,強調硬體資源的重要性。<br>
<a href='https://blog.twman.org/2024/02/asr-tts.html' target='_blank'>ASR/TTS 開發避坑指南:語音辨識與合成的常見挑戰與對策</a>:探討 ASR 和 TTS 技術應用中的問題,強調數據質量的重要性。<br>
<a href='https://blog.twman.org/2021/04/NLP.html' target='_blank'>那些自然語言處理 (Natural Language Processing, NLP) 踩的坑</a>:分享 NLP 領域的實踐經驗,強調數據質量對模型效果的影響。<br>
<a href='https://blog.twman.org/2021/04/ASR.html' target='_blank'>那些語音處理 (Speech Processing) 踩的坑</a>:分享語音處理領域的實務經驗,強調資料品質對模型效果的影響。<br>
<a href='https://blog.twman.org/2023/07/wsl.html' target='_blank'>用PPOCRLabel來幫PaddleOCR做OCR的微調和標註</a><br>
<a href='https://blog.twman.org/2023/07/HugIE.html' target='_blank'>基於機器閱讀理解和指令微調的統一信息抽取框架之診斷書醫囑資訊擷取分析</a><br>
"""
# 添加示例
examples = [
["請問high entropy nitride coatings的形成,主要可透過那些元素來讓這個材料形成熱穩定?"],
["AlCoCrFeNi HEA coating 可用怎樣的實驗方法做到 ?"],
["高熵塗層材料的種類有哪些?"],
["如何優化HEA的性能?"],
["查詢 https://doi.org/10.3390/ma17020453"]
]
with gr.Blocks(css=custom_css) as iface:
gr.HTML(TITLE)
gr.HTML(SUBTITLE)
gr.HTML(LINKS)
with gr.Row():
chatbot = gr.Chatbot(elem_id="chatbot")
with gr.Row():
user_input = gr.Textbox(label='輸入您的問題', placeholder="在此輸入問題...", elem_id="user_input")
submit_button = gr.Button("問題輸入好,請點我送出", elem_id="submit_button")
gr.Examples(examples=examples, inputs=user_input)
with gr.Row():
dislike_button = gr.Button("👎 覺得答案待改善,請輸入改進建議,再按我送出保存", elem_id="dislike_button")
improvement_input = gr.Textbox(label='請輸入改進建議', placeholder='請輸入如何改進模型回應的建議', elem_id="improvement_input")
with gr.Row():
feedback_output = gr.Textbox(label='反饋結果執行狀態', interactive=False, elem_id="feedback_output")
with gr.Row():
show_feedback_button = gr.Button("查看目前所有反饋記錄", elem_id="show_feedback_button")
feedback_display = gr.JSON(label='所有反饋記錄', elem_id="feedback_display")
def chat(user_input, history):
response = handle_user_input(user_input)
history.append((user_input, response))
return history, history
submit_button.click(fn=chat, inputs=[user_input, chatbot], outputs=[chatbot, chatbot])
dislike_button.click(
fn=lambda response, improvement: handle_feedback(response, "dislike", improvement),
inputs=[chatbot, improvement_input],
outputs=feedback_output
)
show_feedback_button.click(fn=show_feedback, outputs=feedback_display)
iface.launch() |