lianghsun commited on
Commit
1703267
·
1 Parent(s): 36605e0

first commit

Browse files
Files changed (2) hide show
  1. app.py +240 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import json
3
+ from io import StringIO
4
+ import requests
5
+ from PyPDF2 import PdfReader
6
+ from datetime import datetime, timezone, timedelta
7
+
8
+ st.set_page_config(page_title="資料上傳與檢查工具", layout="wide")
9
+
10
+ BACKEND_URL = st.secrets.get("BACKEND_URL", None)
11
+
12
+ st.title("🌟 協助貢獻繁體中文資料")
13
+ st.markdown("""
14
+ 歡迎加入我們,一起建立高品質的 **繁體中文語言資料集**!你提供的每一份資料,都能幫助未來的繁中模型更準確、更理解本地語境。
15
+
16
+ 我們非常感謝你的協助,你的貢獻將直接推動繁體中文 AI 生態的發展!🌱
17
+ """)
18
+
19
+ st.info("⚠️ 請勿上傳真實個資或敏感商業資料。")
20
+
21
+ # ---- 本次上傳的共同設定(兩個 tab 共用) ----
22
+ st.markdown("### 本次上傳設定")
23
+ contributor_email = st.text_input("聯絡 email(選填)", placeholder="[email protected]")
24
+ share_permission = st.checkbox(
25
+ "我同意將本次上傳的資料,未來在去識別化後以開源形式提供研究與模型訓練使用。",
26
+ value=False,
27
+ )
28
+
29
+ # 產生 UTC+8 的上傳時間(每次互動當下)
30
+ tz_utc8 = timezone(timedelta(hours=8))
31
+ uploaded_at = datetime.now(tz_utc8).isoformat()
32
+
33
+ tab_jsonl, tab_pdf = st.tabs(["對話資料 (.jsonl)", "預訓練 PDF"])
34
+
35
+
36
+ # ---------- Tab 1: JSONL ----------
37
+ with tab_jsonl:
38
+ st.subheader("上傳對話資料")
39
+
40
+ sample_prompt = """你現在是一個資料標註助手,請幫我產生一組適合用來微調聊天模型的對話資料,輸出格式必須是 `.jsonl`。
41
+
42
+ 格式要求:
43
+
44
+ - 每一行是一個獨立的 JSON 物件。
45
+ - 每個 JSON 物件必須包含一個 `messages` 欄位。
46
+ - `messages` 是一個陣列,元素為依照 OpenAI Chat API 格式的訊息物件:
47
+ - `{"role": "system" | "user" | "assistant", "content": "文字內容"}`
48
+ - `content` 一律使用純文字字串(不要使用多段 content / 不要使用 function_call)。
49
+ - 不要輸出程式碼區塊標記 ```,只輸出純文字內容。
50
+ - 不要在檔案中加入註解或說明文字,每一行只能是 JSON。
51
+
52
+ 範例(僅供格式參考):
53
+
54
+ {"messages": [
55
+ {"role": "system", "content": "你是一個友善的客服人員。"},
56
+ {"role": "user", "content": "請問我要如何申請退貨?"},
57
+ {"role": "assistant", "content": "您好,若您要申請退貨,請先登入會員中心,在「訂單管理」中選擇欲退貨的訂單,點選「申請退貨」,依指示填寫原因並送出。"}
58
+ ]}
59
+ {"messages": [
60
+ {"role": "system", "content": "你是一個勞動法規諮詢助手。"},
61
+ {"role": "user", "content": "加班費要怎麼算?"},
62
+ {"role": "assistant", "content": "依據勞動基準法第24條,加班工資應依平日或休息日的不同,分別以正常工資的一又三分之一、二又三分之一等倍數計算。實務上請再確認公司內部規章。"}
63
+ ]}
64
+
65
+ 請依照以上規格輸出多行 `.jsonl` 對話資料。"""
66
+
67
+ st.markdown("##### 請將以下的 prompt 貼到你的對話生成模型中,產生符合格式的對話資料:")
68
+ st.code(sample_prompt, language="markdown")
69
+
70
+ jsonl_file = st.file_uploader(
71
+ "上傳對話資料 `.jsonl` 檔",
72
+ type=["jsonl"],
73
+ accept_multiple_files=False
74
+ )
75
+
76
+ jsonl_valid = False
77
+ parsed_lines = []
78
+
79
+ if jsonl_file is not None:
80
+ st.markdown("#### 檔案檢查結果")
81
+ content = jsonl_file.read().decode("utf-8")
82
+ f = StringIO(content)
83
+
84
+ errors = []
85
+ allowed_roles = {"system", "user", "assistant"}
86
+
87
+ for idx, line in enumerate(f, start=1):
88
+ line = line.strip()
89
+ if not line:
90
+ continue
91
+ try:
92
+ obj = json.loads(line)
93
+ except json.JSONDecodeError as e:
94
+ errors.append(f"第 {idx} 行不是合法 JSON:{e}")
95
+ continue
96
+
97
+ if "messages" not in obj or not isinstance(obj["messages"], list):
98
+ errors.append(f"第 {idx} 行缺少 messages 欄位或型態錯誤。")
99
+ continue
100
+
101
+ for m_idx, msg in enumerate(obj["messages"]):
102
+ if not isinstance(msg, dict):
103
+ errors.append(f"第 {idx} 行第 {m_idx+1} 則訊息不是物件。")
104
+ continue
105
+ role = msg.get("role")
106
+ msg_content = msg.get("content")
107
+ if role not in allowed_roles:
108
+ errors.append(f"第 {idx} 行第 {m_idx+1} 則 role 非預期:{role}")
109
+ if not isinstance(msg_content, str):
110
+ errors.append(f"第 {idx} 行第 {m_idx+1} 則 content 需為字串。")
111
+
112
+ parsed_lines.append(obj)
113
+
114
+ if errors:
115
+ st.error("格式檢查失敗,請修正後重新上傳:")
116
+ for e in errors[:20]:
117
+ st.write("- " + e)
118
+ if len(errors) > 20:
119
+ st.write(f"... 還有 {len(errors) - 20} 筆錯誤未顯示")
120
+ else:
121
+ jsonl_valid = True
122
+ st.success(f"檢查通過!共 {len(parsed_lines)} 筆對話。")
123
+ st.markdown("#### 範例預覽(前 2 筆)")
124
+ for i, obj in enumerate(parsed_lines[:2], start=1):
125
+ st.json(obj)
126
+
127
+ # 上傳按鈕:會在送出前幫每一筆加上 metadata
128
+ if st.button("上傳", disabled=not (jsonl_file and jsonl_valid or BACKEND_URL is None)):
129
+ if BACKEND_URL is None:
130
+ st.warning("尚未設定 BACKEND_URL,無法實際送出,請在 `st.secrets` 中配置。")
131
+ else:
132
+ # 準備 metadata(會附加在每一行 JSON 物件上)
133
+ meta = {
134
+ "uploaded_at": uploaded_at, # UTC+8 ISO 字串
135
+ "contributor_email": contributor_email if contributor_email.strip() else None,
136
+ "share_permission": bool(share_permission),
137
+ }
138
+
139
+ # 重新組一份帶 metadata 的 jsonl 內容
140
+ enriched_lines = []
141
+ for obj in parsed_lines:
142
+ obj_with_meta = {
143
+ **obj,
144
+ "metadata": meta,
145
+ }
146
+ enriched_lines.append(json.dumps(obj_with_meta, ensure_ascii=False))
147
+
148
+ payload = "\n".join(enriched_lines).encode("utf-8")
149
+
150
+ files = {"file": ("contrib.jsonl", payload, "application/jsonl")}
151
+ try:
152
+ resp = requests.post(f"{BACKEND_URL}/upload-jsonl", files=files)
153
+ if resp.ok:
154
+ st.success("已成功送交後端伺服器,等待後端進一步檢查與處理。")
155
+ else:
156
+ st.error(f"後端回傳錯誤:{resp.status_code} {resp.text}")
157
+ except Exception as e:
158
+ st.error(f"送出時發生錯誤:{e}")
159
+
160
+
161
+ # ---------- Tab 2: PDF ----------
162
+ with tab_pdf:
163
+ st.subheader("上傳預訓練 PDF(純文字型)")
164
+ st.markdown("""
165
+ **格式說明**
166
+
167
+ - 檔案副檔名:`.pdf`
168
+ - 內容須為可擷取文字的 PDF(非掃描圖片)。
169
+ - 系統會抽樣頁面檢查是否能讀取到足夠文字內容。
170
+ """)
171
+
172
+ pdf_files = st.file_uploader(
173
+ "上傳一個或多個 PDF 檔",
174
+ type=["pdf"],
175
+ accept_multiple_files=True
176
+ )
177
+
178
+ pdf_results = []
179
+
180
+ if pdf_files:
181
+ for pdf in pdf_files:
182
+ st.markdown(f"#### 檢查檔案:`{pdf.name}`")
183
+ try:
184
+ reader = PdfReader(pdf)
185
+ num_pages = len(reader.pages)
186
+ sample_pages = [0, 2, 4] # 第 1,3,5 頁(若存在)
187
+ text_snippets = []
188
+
189
+ for p in sample_pages:
190
+ if p < num_pages:
191
+ page = reader.pages[p]
192
+ text = page.extract_text() or ""
193
+ text_snippets.append(text)
194
+
195
+ total_text = "".join(text_snippets)
196
+ text_len = len(total_text)
197
+
198
+ if text_len < 100:
199
+ st.warning(f"未擷取到足夠文字內容(抽樣字數 {text_len})。此 PDF 可能是掃描型,建議先做 OCR。")
200
+ else:
201
+ st.success(f"檢查通過!頁數:{num_pages},抽樣字數:{text_len}")
202
+ st.markdown("**文字預覽(前 300 字)**")
203
+ st.text(total_text[:300])
204
+
205
+ pdf_results.append((pdf, text_len))
206
+
207
+ except Exception as e:
208
+ st.error(f"讀取 PDF 時發生錯誤:{e}")
209
+
210
+ any_valid_pdf = any(tlen >= 100 for _, tlen in pdf_results) if pdf_results else False
211
+
212
+ if st.button("上傳文本", disabled=not (pdf_files and any_valid_pdf or BACKEND_URL is None)):
213
+ if BACKEND_URL is None:
214
+ st.warning("尚未設定 BACKEND_URL,無法實際送出,請在 `st.secrets` 中配置。")
215
+ else:
216
+ files = []
217
+ for pdf, text_len in pdf_results:
218
+ if text_len < 100:
219
+ continue # 跳過疑似掃描檔
220
+ pdf.seek(0)
221
+ files.append(("files", (pdf.name, pdf.getvalue(), "application/pdf")))
222
+
223
+ if not files:
224
+ st.warning("沒有通過文字檢查的 PDF 檔案可送出。")
225
+ else:
226
+ # PDF 部分的 metadata 用 form data 一起送出,讓後端可以記錄
227
+ meta = {
228
+ "uploaded_at": uploaded_at,
229
+ "contributor_email": contributor_email if contributor_email.strip() else "",
230
+ "share_permission": json.dumps(bool(share_permission)),
231
+ }
232
+
233
+ try:
234
+ resp = requests.post(f"{BACKEND_URL}/upload-pdf", files=files, data=meta)
235
+ if resp.ok:
236
+ st.success("已成功送交後端伺服器,等待後端進一步檢查與處理。")
237
+ else:
238
+ st.error(f"後端回傳錯誤:{resp.status_code} {resp.text}")
239
+ except Exception as e:
240
+ st.error(f"送出時發生錯誤:{e}")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ requests
3
+ PyPDF2
4
+ pdfplumber