Update app.py
Browse files
app.py
CHANGED
|
@@ -1,86 +1,83 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
import torch
|
| 4 |
from transformers import BertTokenizer, pipeline
|
| 5 |
|
| 6 |
-
# 1.
|
| 7 |
hf_token = os.getenv("HF_TOKEN")
|
| 8 |
model_name = "google-bert/bert-base-chinese"
|
| 9 |
|
| 10 |
try:
|
| 11 |
-
#
|
| 12 |
tokenizer = BertTokenizer.from_pretrained(model_name, token=hf_token)
|
| 13 |
-
tokenizer.add_tokens(['明月', '裝飾', '窗子', '
|
| 14 |
|
| 15 |
-
#
|
| 16 |
classifier = pipeline("sentiment-analysis", model="LiYuan/amazon-review-sentiment-analysis", token=hf_token)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
except Exception as e:
|
| 18 |
-
|
| 19 |
-
classifier = None
|
| 20 |
-
print(f"Error: {e}")
|
| 21 |
|
| 22 |
-
def
|
| 23 |
-
if not tokenizer
|
| 24 |
|
| 25 |
lines = [line.strip() for line in input_text.split('\n') if line.strip()]
|
| 26 |
-
if not lines: return "💡
|
| 27 |
|
| 28 |
-
# 2.
|
| 29 |
batch_out = tokenizer.batch_encode_plus(
|
| 30 |
lines,
|
| 31 |
-
add_special_tokens=True,
|
| 32 |
-
padding='max_length',
|
| 33 |
-
max_length=
|
| 34 |
-
truncation=True,
|
| 35 |
return_tensors="pt"
|
| 36 |
)
|
| 37 |
|
| 38 |
-
results = classifier(lines)
|
| 39 |
lab_reports = []
|
| 40 |
-
|
| 41 |
for i, line in enumerate(lines):
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
| 47 |
tokens = [tokenizer.decode([idx]) for idx in ids if idx != 0]
|
| 48 |
|
| 49 |
lab_reports.append({
|
| 50 |
"📝 原始句子": line,
|
| 51 |
-
"
|
| 52 |
-
"
|
| 53 |
-
"
|
| 54 |
-
|
| 55 |
-
"Attention Mask": mask[:10],
|
| 56 |
-
"Token Type IDs": type_ids[:10]
|
| 57 |
-
},
|
| 58 |
-
"🛠️ 底層解碼還原": tokenizer.decode(ids)
|
| 59 |
})
|
| 60 |
|
| 61 |
return lab_reports
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
with gr.Blocks(theme=gr.themes.
|
| 65 |
-
gr.Markdown("##
|
| 66 |
-
gr.Markdown("
|
| 67 |
|
| 68 |
with gr.Row():
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
with gr.Column(scale=2):
|
| 78 |
-
output_json = gr.JSON(label="📊 實驗報告 (包含 Input IDs, Mask, Type IDs)")
|
| 79 |
|
| 80 |
-
run_btn.click(fn=
|
| 81 |
|
| 82 |
gr.Examples(
|
| 83 |
-
examples=[["
|
| 84 |
inputs=input_area
|
| 85 |
)
|
| 86 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
|
|
|
| 3 |
from transformers import BertTokenizer, pipeline
|
| 4 |
|
| 5 |
+
# 1. 安全金鑰與工具初始化 (對應書中圖 1-3)
|
| 6 |
hf_token = os.getenv("HF_TOKEN")
|
| 7 |
model_name = "google-bert/bert-base-chinese"
|
| 8 |
|
| 9 |
try:
|
| 10 |
+
# 載入編碼器並擴充字典 (實作書中 2.3.6 節)
|
| 11 |
tokenizer = BertTokenizer.from_pretrained(model_name, token=hf_token)
|
| 12 |
+
tokenizer.add_tokens(['明月', '裝飾', '窗子', '李福林'])
|
| 13 |
|
| 14 |
+
# 載入情感分析管線 (第 5-6 章)
|
| 15 |
classifier = pipeline("sentiment-analysis", model="LiYuan/amazon-review-sentiment-analysis", token=hf_token)
|
| 16 |
+
|
| 17 |
+
# 載入命名實體識別管線 (第 10-11 章實戰任務)
|
| 18 |
+
# 使用專門處理中文實體的模型
|
| 19 |
+
ner_tagger = pipeline("ner", model="ckiplab/bert-base-chinese-ner", token=hf_token)
|
| 20 |
except Exception as e:
|
| 21 |
+
print(f"初始化錯誤: {e}")
|
| 22 |
+
tokenizer = classifier = ner_tagger = None
|
|
|
|
| 23 |
|
| 24 |
+
def advanced_nlp_lab(input_text):
|
| 25 |
+
if not tokenizer: return "⚠️ 系統初始化失敗"
|
| 26 |
|
| 27 |
lines = [line.strip() for line in input_text.split('\n') if line.strip()]
|
| 28 |
+
if not lines: return "💡 請輸入文字開始偵測!"
|
| 29 |
|
| 30 |
+
# 2. 實作進階批次編碼 (對應書中 2.3.5 節)
|
| 31 |
batch_out = tokenizer.batch_encode_plus(
|
| 32 |
lines,
|
| 33 |
+
add_special_tokens=True,
|
| 34 |
+
padding='max_length',
|
| 35 |
+
max_length=25,
|
| 36 |
+
truncation=True,
|
| 37 |
return_tensors="pt"
|
| 38 |
)
|
| 39 |
|
|
|
|
| 40 |
lab_reports = []
|
|
|
|
| 41 |
for i, line in enumerate(lines):
|
| 42 |
+
# 3. 實作 NER 實體偵測 (對應書中第 10 章任務)
|
| 43 |
+
ner_results = ner_tagger(line)
|
| 44 |
+
entities = [f"{entity['word']}({entity['entity']})" for entity in ner_results]
|
| 45 |
+
|
| 46 |
+
# 4. 情感分析 (對應書中第 7 章任務)
|
| 47 |
+
sentiment = classifier(line)[0]
|
| 48 |
|
| 49 |
+
ids = batch_out['input_ids'][i].tolist()
|
| 50 |
tokens = [tokenizer.decode([idx]) for idx in ids if idx != 0]
|
| 51 |
|
| 52 |
lab_reports.append({
|
| 53 |
"📝 原始句子": line,
|
| 54 |
+
"🔍 實體偵測 (NER)": entities if entities else "未偵測到實體",
|
| 55 |
+
"🎭 情感分析": f"{sentiment['label']} (信心: {sentiment['score']:.2f})",
|
| 56 |
+
"🧩 分詞結構": " | ".join(tokens),
|
| 57 |
+
"🔢 機器編碼 IDs": [idx for idx in ids if idx != 0]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
})
|
| 59 |
|
| 60 |
return lab_reports
|
| 61 |
|
| 62 |
+
# 5. 建立專業風格 Blocks 介面
|
| 63 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 64 |
+
gr.Markdown("## 🕵️♂️ Hugging Face 中文語義全解析實驗室")
|
| 65 |
+
gr.Markdown("本程式整合了李福林著《Hugging Face 自然語言處理實戰》中的多項任務:從編碼矩陣到情感分類,再到命名實體識別。")
|
| 66 |
|
| 67 |
with gr.Row():
|
| 68 |
+
input_area = gr.Textbox(
|
| 69 |
+
label="🔮 請輸入包含人名、地名或情感的中文 (支援多行)",
|
| 70 |
+
lines=4,
|
| 71 |
+
placeholder="例如:李福林在北京寫下了這本 Hugging Face 實戰書。"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
run_btn = gr.Button("🚀 啟動多維度語義解析", variant="primary")
|
| 75 |
+
output_json = gr.JSON(label="📊 深度解析報告 (實作書中第 2, 7, 10 章核心)")
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
run_btn.click(fn=advanced_nlp_lab, inputs=input_area, outputs=output_json)
|
| 78 |
|
| 79 |
gr.Examples(
|
| 80 |
+
examples=[["李福林在台北展示了 Transformer 的威力"], ["明月裝飾了你的窗子"]],
|
| 81 |
inputs=input_area
|
| 82 |
)
|
| 83 |
|