unieai-mcp-accton-rfp 0.0.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,337 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from typing import Any, Dict, Tuple, List, Optional
8
+ from datetime import datetime
9
+
10
+ import requests
11
+ from dotenv import load_dotenv
12
+ from fastmcp import FastMCP
13
+ from openpyxl import load_workbook
14
+ from openpyxl.worksheet.worksheet import Worksheet
15
+
16
+ # LangChain (1.x API)
17
+ from langchain_openai import ChatOpenAI
18
+ from langchain_core.messages import HumanMessage, SystemMessage
19
+
20
+ # ==============================
21
+ # 🎛 Environment & Logging
22
+ # ==============================
23
+
24
+ load_dotenv()
25
+
26
+ logging.basicConfig(level=logging.INFO)
27
+ logger = logging.getLogger("ExcelProcessor")
28
+
29
+ app = FastMCP("ExcelProcessor")
30
+ semaphore = asyncio.Semaphore(10)
31
+
32
+ # LLM 初始化 (LangChain 1.x)
33
+ llm = ChatOpenAI(
34
+ model=os.getenv("UNIEAI_MODEL"),
35
+ base_url=os.getenv("UNIEAI_API_URL"),
36
+ api_key=os.getenv("UNIEAI_API_KEY"),
37
+ temperature=0,
38
+ max_tokens=15000
39
+ )
40
+
41
+ # Appwrite ENV
42
+ APPWRITE_PROJECT_ID = os.getenv("APPWRITE_PROJECT_ID")
43
+ APPWRITE_API_KEY = os.getenv("APPWRITE_API_KEY")
44
+ APPWRITE_ENDPOINT = os.getenv("APPWRITE_ENDPOINT", "https://sgp.cloud.appwrite.io/v1")
45
+
46
+
47
+ # ==============================
48
+ # 🧩 Helper Functions
49
+ # ==============================
50
+
51
+ def _extract_json(text: str) -> Dict[str, Any]:
52
+ """擷取 JSON 區塊"""
53
+ match = re.search(r"\{[\s\S]*\}", text)
54
+ if match:
55
+ try:
56
+ return json.loads(match.group(0))
57
+ except Exception as e:
58
+ logger.warning(f"JSON 解析失敗: {e}")
59
+ return {"Result": "解析錯誤", "Reference": text.strip()}
60
+
61
+
62
+ def _parse_appwrite_url(url: str) -> Tuple[Optional[str], Optional[str]]:
63
+ pattern = r"/storage/buckets/([^/]+)/files/([^/]+)"
64
+ m = re.search(pattern, url)
65
+ if not m:
66
+ return None, None
67
+ return m.group(1), m.group(2)
68
+
69
+
70
+ def _generate_new_filename(original_name: str) -> str:
71
+ base, ext = os.path.splitext(original_name)
72
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
73
+ return f"{base}_processed_{timestamp}{ext}"
74
+
75
+
76
+ # ==============================
77
+ # 🤖 LLM Logic(新增兩階段)
78
+ # ==============================
79
+
80
+ async def _call_llm_raw(prompt: str, user_message: str):
81
+ """返回 LLM 純文字內容"""
82
+ try:
83
+ async with semaphore:
84
+ response = await llm.ainvoke([
85
+ SystemMessage(content=prompt),
86
+ HumanMessage(content=user_message),
87
+ ])
88
+ return (response.content or "").strip()
89
+ except Exception as e:
90
+ return f"LLM Error: {e}"
91
+
92
+
93
+ def _extract_result_json(text: str):
94
+ """解析第二階段 JSON"""
95
+ try:
96
+ return json.loads(re.search(r"\{[\s\S]*\}", text).group(0))
97
+ except:
98
+ return {"Result": "Error"}
99
+
100
+
101
+ # ==============================
102
+ # 📘 Prompt 建構(新:兩個 prompt)
103
+ # ==============================
104
+
105
+ #def _build_reference_prompt() -> str:
106
+ # return """
107
+ # 你是一位專業的「RFP(Request for Proposal,提案請求書)需求符合性分析專家」。
108
+ # 你的任務是根據客戶提供的 RFP 需求清單,從公司內部的產品規格文件(已上傳至知識庫)中,逐條分析並判斷產品是否符合該需求。
109
+ # 請依據輸入的內容,輸出分析說明(Reference 欄位內容)。
110
+ # 請只輸出自然語言說明,不要進行符合性判斷,也不要輸出 JSON。
111
+ #"""
112
+
113
+ def _build_reference_prompt() -> str:
114
+ return """
115
+ 你是一位嚴謹的產品經理助理,專門負責將內部產品規格(知識庫)與客戶的需求單(RFP)進行比對和符合性分析。
116
+
117
+ **任務指示:**
118
+ 1. 你將收到客戶的產品需求單 (RFP) 作為輸入。
119
+ 2. 你的知識庫已包含你公司產品的完整說明文件。
120
+ 3. 請仔細閱讀 RFP 中的每一條具體需求,並利用你的產品知識庫內容進行嚴格比對。
121
+
122
+ **比對規則:**
123
+ * **Conform (完全符合):** 公司的產品規格能**完整且無條件地**滿足 RFP 中的該項需求。
124
+ * **Half Conform (部分符合):** 公司的產品規格**只能滿足** RFP 中該項需求的**部分內容**,或者需要透過**變通、額外配置或未來規劃**才能滿足。
125
+ * **Not Conform (不符合):** 公司的產品規格**無法滿足** RFP 中的該項需求。
126
+
127
+ **輸出格式要求:**
128
+ 你必須以條列式清晰地輸出分析結果,**每一條結果必須包含**:
129
+ 1. RFP 中的**原始需求描述** (簡短摘錄或編號)。
130
+ 2. **符合程度** (只能是:Conform, Half Conform, Not Conform 三者之一)。
131
+ 3. **參考依據** (說明做出判斷的依據,需明確引用知識庫中**相關產品說明**的關鍵資訊或段落,例如:知識庫中「功能A」的描述支持此判斷)。
132
+
133
+ 請針對 RFP 中的每一條主要需求逐一進行分析。
134
+ """
135
+
136
+
137
+ def _build_result_prompt() -> str:
138
+ return """
139
+ 請依據以下 Reference 文本,判斷其符合性:
140
+ - Conform:完全符合
141
+ - Half Conform:部分符合
142
+ - Not Conform:不符合
143
+
144
+ 請僅輸出以下 JSON 格式:
145
+ {
146
+ "Result": "Conform / Half Conform / Not Conform"
147
+ }
148
+ """
149
+
150
+
151
+ def _build_user_message(a: str, b: str, c: str, d: str) -> str:
152
+ logger.info(f"🟢 _build_user_message : {a}, {b}, {c}, {d}")
153
+ return f"""
154
+ {a}, {b}, {c}, {d}
155
+
156
+ """
157
+
158
+
159
+ # ==============================
160
+ # 📊 Excel Processing Core
161
+ # ==============================
162
+
163
+ async def _process_excel_logic(url: str) -> Dict[str, Any]:
164
+ logger.info(f"🟢 開始處理 Excel:{url}")
165
+
166
+ # -------------------------
167
+ # Step 1: Download / Load
168
+ # -------------------------
169
+ source_type = ""
170
+ local_path = None
171
+ appwrite_info = (None, None)
172
+ bucket_id = None
173
+
174
+ if url.startswith("file:///"):
175
+ local_path = url.replace("file:///", "")
176
+ file_path = local_path
177
+ source_type = "local"
178
+
179
+ elif url.startswith("http"):
180
+ resp = requests.get(url)
181
+ resp.raise_for_status()
182
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp:
183
+ tmp.write(resp.content)
184
+ file_path = tmp.name
185
+
186
+ bucket_id, file_id = _parse_appwrite_url(url)
187
+ if bucket_id:
188
+ source_type = "appwrite"
189
+ appwrite_info = (bucket_id, file_id)
190
+ else:
191
+ source_type = "remote_readonly"
192
+
193
+ else:
194
+ raise ValueError("❌ 不支援檔案來源")
195
+
196
+ # -------------------------
197
+ # Step 2: Open Excel
198
+ # -------------------------
199
+ wb = load_workbook(file_path)
200
+ ws = wb.active
201
+
202
+ header = {cell.value: idx for idx, cell in enumerate(ws[1], 1)}
203
+ for col in ["itemA", "itemB", "itemC", "itemD", "Result", "Reference"]:
204
+ if col not in header:
205
+ raise ValueError(f"❌ Excel 缺少欄位:{col}")
206
+
207
+ # -------------------------
208
+ # Step 3: Two-stage LLM
209
+ # -------------------------
210
+ rows_for_llm = []
211
+
212
+ for row in ws.iter_rows(min_row=2, values_only=False):
213
+ if any([cell.value for cell in row]):
214
+ rows_for_llm.append(row)
215
+
216
+ for row in rows_for_llm:
217
+ r = row[0].row
218
+ a = row[header["itemA"] - 1].value or ""
219
+ b = row[header["itemB"] - 1].value or ""
220
+ c = row[header["itemC"] - 1].value or ""
221
+ d = row[header["itemD"] - 1].value or ""
222
+
223
+ # ----------- 第 1 次 LLM:生成 Reference -----------
224
+ user_msg_ref = _build_user_message(str(a), str(b), str(c), str(d))
225
+ ref_prompt = _build_reference_prompt()
226
+
227
+ reference_text = await _call_llm_raw(ref_prompt, user_msg_ref)
228
+ logger.info(f"🟢 reference_text : {reference_text}")
229
+ ws.cell(r, header["Reference"], reference_text)
230
+
231
+ # ----------- 第 2 次 LLM:用 Reference 判斷 Result ---
232
+ result_prompt = _build_result_prompt()
233
+ judgement_raw = await _call_llm_raw(result_prompt, reference_text)
234
+ logger.info(f"🟢 judgement_raw : {judgement_raw}")
235
+ judgement_json = _extract_result_json(judgement_raw)
236
+ ws.cell(r, header["Result"], judgement_json.get("Result", "Error"))
237
+
238
+ # -------------------------
239
+ # Step 4: Save local debug copy
240
+ # -------------------------
241
+ local_debug_dir = r"D:\TempExcelDebug"
242
+ os.makedirs(local_debug_dir, exist_ok=True)
243
+
244
+ local_debug_filename = _generate_new_filename("debug_output.xlsx")
245
+ local_debug_path = os.path.join(local_debug_dir, local_debug_filename)
246
+
247
+ wb.save(local_debug_path)
248
+ logger.info(f"📝 本機 debug 檔案已輸出:{local_debug_path}")
249
+
250
+ # -------------------------
251
+ # Step 5: Write back according to source
252
+ # -------------------------
253
+
254
+ # local
255
+ if source_type == "local":
256
+ wb.save(local_path)
257
+ return {
258
+ "status": "success",
259
+ "location_type": "local",
260
+ "output_path": local_path
261
+ }
262
+
263
+ # Appwrite
264
+ if source_type == "appwrite":
265
+ bucket_id, _ = appwrite_info
266
+
267
+ tmp_out_path = os.path.join(
268
+ tempfile.gettempdir(),
269
+ _generate_new_filename("upload.xlsx")
270
+ )
271
+ wb.save(tmp_out_path)
272
+
273
+ new_file_id = f"processed_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
274
+ new_file_name = f"{new_file_id}.xlsx"
275
+
276
+ upload_url = f"{APPWRITE_ENDPOINT}/storage/buckets/{bucket_id}/files"
277
+
278
+ headers = {
279
+ "X-Appwrite-Project": APPWRITE_PROJECT_ID,
280
+ "X-Appwrite-Key": APPWRITE_API_KEY,
281
+ }
282
+
283
+ files = {
284
+ "file": (
285
+ new_file_name,
286
+ open(tmp_out_path, "rb"),
287
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
288
+ )
289
+ }
290
+
291
+ data = { "fileId": new_file_id }
292
+
293
+ resp = requests.post(upload_url, headers=headers, files=files, data=data)
294
+ resp.raise_for_status()
295
+
296
+ return {
297
+ "status": "success",
298
+ "location_type": "appwrite_new_file",
299
+ "file_id": new_file_id,
300
+ "file_name": new_file_name,
301
+ "upload_response": resp.json(),
302
+ "download_url": f"{APPWRITE_ENDPOINT}/storage/buckets/{bucket_id}/files/{new_file_id}/view?project={APPWRITE_PROJECT_ID}"
303
+ }
304
+
305
+ # remote (can't write back)
306
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_out:
307
+ wb.save(tmp_out.name)
308
+ fallback = tmp_out.name
309
+
310
+ return {
311
+ "status": "success",
312
+ "location_type": "remote_readonly",
313
+ "output_path": fallback,
314
+ "message": "無法寫回遠端,只能輸出本機暫存檔"
315
+ }
316
+
317
+
318
+ # ==============================
319
+ # 🔧 MCP Tool
320
+ # ==============================
321
+
322
+ @app.tool()
323
+ async def process_excel(url: str):
324
+ return await _process_excel_logic(url)
325
+
326
+
327
+ # ==============================
328
+ # 🚀 CLI Test
329
+ # ==============================
330
+
331
+ if __name__ == "__main__":
332
+ test_url = (
333
+ "https://sgp.cloud.appwrite.io/v1/storage/buckets/6904374b00056677a970/files/6937a7fb00180f83ab67/view?project=6901b22e0036150b66d3&mode=admin"
334
+ )
335
+ print("🚀 測試開始...")
336
+ result = asyncio.run(_process_excel_logic(test_url))
337
+ print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -0,0 +1,327 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from typing import Any, Dict, Tuple, List, Optional
8
+ from datetime import datetime
9
+
10
+ import requests
11
+ from fastmcp import FastMCP
12
+ from openpyxl import load_workbook
13
+ from openpyxl.worksheet.worksheet import Worksheet
14
+
15
+ # LangChain (1.x API)
16
+ from langchain_openai import ChatOpenAI
17
+ from langchain_core.messages import HumanMessage, SystemMessage
18
+
19
+ # ==============================
20
+ # 🎛 Environment & Logging
21
+ # ==============================
22
+
23
+
24
+ logging.basicConfig(level=logging.INFO)
25
+ logger = logging.getLogger("unieai-mcp-accton-rfp")
26
+
27
+ app = FastMCP("unieai-mcp-accton-rfp")
28
+ semaphore = asyncio.Semaphore(10)
29
+
30
+ # LLM 初始化 (LangChain 1.x)
31
+ llm = ChatOpenAI(
32
+ model="Qwen3-30B-A3B-Thinking-2507-20251209-accton",
33
+ base_url="https://api.unieai.com/v1",
34
+ api_key="sk-XQvLNVMNTxWGxIQM3J8LYFvg3F2bYayYg0G40D4PddvhnDa6",
35
+ temperature=0,
36
+ max_tokens=32768
37
+ )
38
+
39
+ # Appwrite ENV
40
+ APPWRITE_PROJECT_ID = "6901b22e0036150b66d3"
41
+ APPWRITE_API_KEY = "standard_b1462cfd2cd0b6e5b5f305a10799444e009b880adf74e4b578e96222b148da57e17d57957fe3ffba9c7bfa2f6443b66fbcb851b8fbae0b91dc908139ca1d8e54c1bcba9034449d579449fc2abcdb1d9fdca3cc67bdb15140d8f5df1193264bd070e0f738bc3b13fd94de0d4aee3e2075f6b2124b803470d82f9501e806d16ffd"
42
+ APPWRITE_ENDPOINT = "https://sgp.cloud.appwrite.io/v1"
43
+
44
+ # ==============================
45
+ # 🔧 MCP Tool
46
+ # ==============================
47
+ """
48
+ Accton RFP 需求符合性分析
49
+
50
+ 參數說明:
51
+ - url (str): Excel 檔案 URL
52
+
53
+ 使用範例:
54
+ process_excel(
55
+ url="https://sgp.cloud.appwrite.io/v1/storage/buckets/6904374b00056677a970/files/6937a7fb00180f83ab67/view?project=6901b22e0036150b66d3&mode=admin"
56
+ )
57
+
58
+ 返回:
59
+ - status: 成功或失敗
60
+ - location_type: 檔案來源類型(local, appwrite_new_file, remote_readonly)
61
+ - output_path: 本機暫存檔案路徑(僅 local 類型)
62
+ - file_id: 上傳後的 Appwrite 檔案 ID(僅 appwrite 類型)
63
+ - file_name: 上傳後的 Appwrite 檔案名稱(僅 appwrite 類型)
64
+ - upload_response: Appwrite 上傳回應(僅 appwrite 類型)
65
+ - download_url: Appwrite 檔案預覽 URL(僅 appwrite 類型)
66
+ - message: 其他訊息(僅 remote_readonly 類型)
67
+
68
+ version = 0.0.10
69
+ """
70
+ @app.tool()
71
+ async def process_excel(url: str):
72
+ return await _process_excel_logic(url)
73
+
74
+ # ==============================
75
+ # 🧩 Helper Functions
76
+ # ==============================
77
+
78
+ def _extract_json(text: str) -> Dict[str, Any]:
79
+ """擷取 JSON 區塊"""
80
+ match = re.search(r"\{[\s\S]*\}", text)
81
+ if match:
82
+ try:
83
+ return json.loads(match.group(0))
84
+ except Exception as e:
85
+ logger.warning(f"JSON 解析失敗: {e}")
86
+ return {"Result": "解析錯誤", "Reference": text.strip()}
87
+
88
+
89
+ def _parse_appwrite_url(url: str) -> Tuple[Optional[str], Optional[str]]:
90
+ pattern = r"/storage/buckets/([^/]+)/files/([^/]+)"
91
+ m = re.search(pattern, url)
92
+ if not m:
93
+ return None, None
94
+ return m.group(1), m.group(2)
95
+
96
+
97
+ def _generate_new_filename(original_name: str) -> str:
98
+ base, ext = os.path.splitext(original_name)
99
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
100
+ return f"{base}_processed_{timestamp}{ext}"
101
+
102
+
103
+ # ==============================
104
+ # 🤖 LLM Logic(新增兩階段)
105
+ # ==============================
106
+
107
+ async def _call_llm_raw(prompt: str, user_message: str):
108
+ """返回 LLM 純文字內容"""
109
+ try:
110
+ async with semaphore:
111
+ response = await llm.ainvoke([
112
+ SystemMessage(content=prompt),
113
+ HumanMessage(content=user_message),
114
+ ])
115
+ return (response.content or "").strip()
116
+ except Exception as e:
117
+ return f"LLM Error: {e}"
118
+
119
+
120
+ def _extract_result_json(text: str):
121
+ """解析第二階段 JSON"""
122
+ try:
123
+ return json.loads(re.search(r"\{[\s\S]*\}", text).group(0))
124
+ except:
125
+ return {"Result": "Error"}
126
+
127
+
128
+ # ==============================
129
+ # 📘 Prompt 建構(新:兩個 prompt)
130
+ # ==============================
131
+
132
+ def _build_reference_prompt() -> str:
133
+ return """
134
+ 你是一位嚴謹的產品經理助理,專門負責將內部產品規格(知識庫)與客戶的需求單(RFP)進行比對和符合性分析。
135
+
136
+ **任務指示:**
137
+ 1. 你將收到客戶的產品需求單 (RFP) 作為輸入。
138
+ 2. 你的知識庫已包含你公司產品的完整說明文件。
139
+ 3. 請仔細閱讀 RFP 中的每一條具體需求,並利用你的產品知識庫內容進行嚴格比對。
140
+
141
+ **比對規則:**
142
+ * **Conform (完全符合):** 公司的產品規格能**完整且無條件地**滿足 RFP 中的該項需求。
143
+ * **Half Conform (部分符合):** 公司的產品規格**只能滿足** RFP 中該項需求的**部分內容**,或者需要透過**變通、額外配置或未來規劃**才能滿足。
144
+ * **Not Conform (不符合):** 公司的產品規格**無法滿足** RFP 中的該項需求。
145
+
146
+ **輸出格式要求:**
147
+ 你必須以條列式清晰地輸出分析結果,**每一條結果必須包含**:
148
+ 1. RFP 中的**原始需求描述** (簡短摘錄或編號)。
149
+ 2. **符合程度** (只能是:Conform, Half Conform, Not Conform 三者之一)。
150
+ 3. **參考依據** (說明做出判斷的依據,需明確引用知識庫中**相關產品說明**的關鍵資訊或段落,例如:知識庫中「功能A」的描述支持此判斷)。
151
+
152
+ 請針對 RFP 中的每一條主要需求逐一進行分析。
153
+ """
154
+
155
+
156
+ def _build_result_prompt() -> str:
157
+ return """
158
+ 請依據以下 Reference 文本,判斷其符合性:
159
+ - Conform:完全符合
160
+ - Half Conform:部分符合
161
+ - Not Conform:不符合
162
+
163
+ 請僅輸出以下 JSON 格式:
164
+ {
165
+ "Result": "Conform / Half Conform / Not Conform"
166
+ }
167
+ """
168
+
169
+
170
+ def _build_user_message(a: str, b: str, c: str, d: str) -> str:
171
+ logger.info(f"🟢 _build_user_message : {a}, {b}, {c}, {d}")
172
+ return f"""
173
+ {a}, {b}, {c}, {d}
174
+ """
175
+
176
+
177
+ # ==============================
178
+ # 📊 Excel Processing Core
179
+ # ==============================
180
+
181
+ async def _process_excel_logic(url: str) -> Dict[str, Any]:
182
+ logger.info(f"🟢 開始處理 Excel:{url}")
183
+
184
+ # -------------------------
185
+ # Step 1: Download / Load
186
+ # -------------------------
187
+ source_type = ""
188
+ local_path = None
189
+ appwrite_info = (None, None)
190
+ bucket_id = None
191
+
192
+ if url.startswith("file:///"):
193
+ local_path = url.replace("file:///", "")
194
+ file_path = local_path
195
+ source_type = "local"
196
+
197
+ elif url.startswith("http"):
198
+ resp = requests.get(url)
199
+ resp.raise_for_status()
200
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp:
201
+ tmp.write(resp.content)
202
+ file_path = tmp.name
203
+
204
+ bucket_id, file_id = _parse_appwrite_url(url)
205
+ if bucket_id:
206
+ source_type = "appwrite"
207
+ appwrite_info = (bucket_id, file_id)
208
+ else:
209
+ source_type = "remote_readonly"
210
+
211
+ else:
212
+ raise ValueError("❌ 不支援檔案來源")
213
+
214
+ # -------------------------
215
+ # Step 2: Open Excel
216
+ # -------------------------
217
+ wb = load_workbook(file_path)
218
+ ws = wb.active
219
+
220
+ header = {cell.value: idx for idx, cell in enumerate(ws[1], 1)}
221
+ for col in ["itemA", "itemB", "itemC", "itemD", "Result", "Reference"]:
222
+ if col not in header:
223
+ raise ValueError(f"❌ Excel 缺少欄位:{col}")
224
+
225
+ # -------------------------
226
+ # Step 3: Two-stage LLM
227
+ # -------------------------
228
+ rows_for_llm = []
229
+
230
+ for row in ws.iter_rows(min_row=2, values_only=False):
231
+ if any([cell.value for cell in row]):
232
+ rows_for_llm.append(row)
233
+
234
+ for row in rows_for_llm:
235
+ r = row[0].row
236
+ a = row[header["itemA"] - 1].value or ""
237
+ b = row[header["itemB"] - 1].value or ""
238
+ c = row[header["itemC"] - 1].value or ""
239
+ d = row[header["itemD"] - 1].value or ""
240
+
241
+ # ----------- 第 1 次 LLM:生成 Reference -----------
242
+ user_msg_ref = _build_user_message(str(a), str(b), str(c), str(d))
243
+ ref_prompt = _build_reference_prompt()
244
+ reference_text = await _call_llm_raw(ref_prompt, user_msg_ref)
245
+ logger.info(f"🟢 reference_text : {reference_text}")
246
+ ws.cell(r, header["Reference"], reference_text)
247
+
248
+ # ----------- 第 2 次 LLM:用 Reference 判斷 Result ---
249
+ result_prompt = _build_result_prompt()
250
+ judgement_raw = await _call_llm_raw(result_prompt, reference_text)
251
+ logger.info(f"🟢 judgement_raw : {judgement_raw}")
252
+ judgement_json = _extract_result_json(judgement_raw)
253
+ ws.cell(r, header["Result"], judgement_json.get("Result", "Error"))
254
+
255
+ # -------------------------
256
+ # Step 4: Save local debug copy
257
+ # -------------------------
258
+ local_debug_dir = r"D:\TempExcelDebug"
259
+ os.makedirs(local_debug_dir, exist_ok=True)
260
+
261
+ local_debug_filename = _generate_new_filename("debug_output.xlsx")
262
+ local_debug_path = os.path.join(local_debug_dir, local_debug_filename)
263
+
264
+ wb.save(local_debug_path)
265
+ logger.info(f"📝 本機 debug 檔案已輸出:{local_debug_path}")
266
+
267
+ # -------------------------
268
+ # Step 5: Write back according to source
269
+ # -------------------------
270
+ if source_type == "local":
271
+ wb.save(local_path)
272
+ return {
273
+ "status": "success",
274
+ "location_type": "local",
275
+ "output_path": local_path
276
+ }
277
+
278
+ # Appwrite
279
+ if source_type == "appwrite":
280
+ bucket_id, _ = appwrite_info
281
+
282
+ tmp_out_path = os.path.join(
283
+ tempfile.gettempdir(),
284
+ _generate_new_filename("upload.xlsx")
285
+ )
286
+ wb.save(tmp_out_path)
287
+
288
+ new_file_id = f"processed_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
289
+ new_file_name = f"{new_file_id}.xlsx"
290
+
291
+ upload_url = f"{APPWRITE_ENDPOINT}/storage/buckets/{bucket_id}/files"
292
+
293
+ headers = {
294
+ "X-Appwrite-Project": APPWRITE_PROJECT_ID,
295
+ "X-Appwrite-Key": APPWRITE_API_KEY,
296
+ }
297
+
298
+ files = {
299
+ "file": (
300
+ new_file_name,
301
+ open(tmp_out_path, "rb"),
302
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
303
+ )
304
+ }
305
+
306
+ data = { "fileId": new_file_id }
307
+
308
+ resp = requests.post(upload_url, headers=headers, files=files, data=data)
309
+ resp.raise_for_status()
310
+
311
+ return {
312
+ "status": "success",
313
+ "location_type": "appwrite_new_file",
314
+ "file_id": new_file_id,
315
+ "file_name": new_file_name,
316
+ "upload_response": resp.json(),
317
+ "download_url": f"{APPWRITE_ENDPOINT}/storage/buckets/{bucket_id}/files/{new_file_id}/view?project={APPWRITE_PROJECT_ID}"
318
+ }
319
+
320
+ return {"status": "error", "message": "無法處理該檔案"}
321
+
322
+ # ==============================
323
+ # 🚀 CLI Test
324
+ # ==============================
325
+
326
+ if __name__ == "__main__":
327
+ app.run()