cwadayi commited on
Commit
2af716e
·
verified ·
1 Parent(s): 881be67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -46
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
- # 載入並擴充字典(實作書中 2.3.6 節與 2.4 節)
12
  tokenizer = BertTokenizer.from_pretrained(model_name, token=hf_token)
13
- tokenizer.add_tokens(['明月', '裝飾', '窗子', '夢境'])
14
 
15
- # 載入情感分析管線(對應書中第 5 章與第 6 章概念)
16
  classifier = pipeline("sentiment-analysis", model="LiYuan/amazon-review-sentiment-analysis", token=hf_token)
 
 
 
 
17
  except Exception as e:
18
- tokenizer = None
19
- classifier = None
20
- print(f"Error: {e}")
21
 
22
- def nlp_creative_lab(input_text):
23
- if not tokenizer or not classifier: return "⚠️ 系統初始化失敗,請檢查 Secret 設定。"
24
 
25
  lines = [line.strip() for line in input_text.split('\n') if line.strip()]
26
- if not lines: return "💡 請在左側輸入文字開始實驗!"
27
 
28
- # 2. 實作進階批次編碼(對應書中 2.3.4 2.3.5 節)
29
  batch_out = tokenizer.batch_encode_plus(
30
  lines,
31
- add_special_tokens=True, # 增加 [CLS] 與 [SEP]
32
- padding='max_length', # 對齊長度
33
- max_length=20, # 方便介面觀察的固定長度
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
- ids = batch_out['input_ids'][i].tolist()
43
- mask = batch_out['attention_mask'][i].tolist()
44
- type_ids = batch_out['token_type_ids'][i].tolist()
 
 
 
45
 
46
- # 實作書中 decode 驗證與分詞視覺化
47
  tokens = [tokenizer.decode([idx]) for idx in ids if idx != 0]
48
 
49
  lab_reports.append({
50
  "📝 原始句子": line,
51
- "🎭 情感分析": f"{results[i]['label']} (信心: {results[i]['score']:.2f})",
52
- "🧩 詞元分開 (Tokens)": " | ".join(tokens),
53
- "🔢 進階編碼數據 (表 2-2)": {
54
- "Input IDs (前10位)": ids[:10],
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
- # 3. 建立 Blocks 創意介面
64
- with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
65
- gr.Markdown("## 🏛️ Hugging Face 中文 NLP 標準流程實驗室")
66
- gr.Markdown("本程式實作李福林著《Hugging Face 自然語言處理實戰》中的核心技術:編碼器矩陣解析與批次處理流程。")
67
 
68
  with gr.Row():
69
- with gr.Column(scale=1):
70
- input_area = gr.Textbox(
71
- label="🔮 靈感輸入區 (支援多行)",
72
- lines=5,
73
- placeholder="輸入詩句或評論...\n例如:明月裝飾了你的窗子"
74
- )
75
- run_btn = gr.Button("🔥 執行標準流程測試", variant="primary")
76
-
77
- with gr.Column(scale=2):
78
- output_json = gr.JSON(label="📊 實驗報告 (包含 Input IDs, Mask, Type IDs)")
79
 
80
- run_btn.click(fn=nlp_creative_lab, inputs=input_area, outputs=output_json)
81
 
82
  gr.Examples(
83
- examples=[["明月裝飾了你的窗子\n你裝飾了別人的夢"], ["Hugging Face 工具集大幅降低了研發成本"]],
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