mikao007 commited on
Commit
444ae48
·
verified ·
1 Parent(s): 783c136

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +593 -0
  2. requirements.txt +59 -0
app.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+ import gradio as gr
4
+ from PyPDF2 import PdfReader
5
+ from langchain.text_splitter import CharacterTextSplitter
6
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
7
+ from langchain_community.vectorstores import FAISS
8
+ from langchain.chains.question_answering import load_qa_chain
9
+ from langchain.prompts import PromptTemplate
10
+ import shutil
11
+ import tempfile
12
+ from docx import Document
13
+ from docx.shared import Inches
14
+ from datetime import datetime
15
+
16
+ # Load environment variables
17
+ load_dotenv()
18
+
19
+ # Set Gemini API key
20
+ gemini_api_key = "AIzaSyA8zqhqNb-bNYU6KVb0Zj0XIKi3aZfvXE0"
21
+ os.environ["GOOGLE_API_KEY"] = gemini_api_key
22
+
23
+ class PDFChatBot:
24
+ def __init__(self):
25
+ self.vector_store = None
26
+ self.embeddings = GoogleGenerativeAIEmbeddings(
27
+ model="models/text-embedding-004",
28
+ google_api_key=gemini_api_key
29
+ )
30
+ self.processed_files = []
31
+ self.chat_history = [] # 儲存聊天歷史
32
+
33
+ def get_pdf_text(self, pdf_files):
34
+ """從多個PDF文件中提取文字"""
35
+ raw_text = ""
36
+ processed_count = 0
37
+
38
+ if not pdf_files:
39
+ return raw_text, processed_count
40
+
41
+ # 處理單個文件和多個文件
42
+ if not isinstance(pdf_files, list):
43
+ pdf_files = [pdf_files]
44
+
45
+ for pdf_file in pdf_files:
46
+ try:
47
+ # 如果是上傳的文件對象,使用其name屬性
48
+ pdf_path = pdf_file.name if hasattr(pdf_file, 'name') else pdf_file
49
+
50
+ pdf_reader = PdfReader(pdf_path)
51
+ file_text = ""
52
+ for page in pdf_reader.pages:
53
+ text = page.extract_text()
54
+ if text:
55
+ file_text += text + "\n"
56
+
57
+ if file_text.strip():
58
+ raw_text += file_text
59
+ processed_count += 1
60
+ self.processed_files.append(os.path.basename(pdf_path))
61
+
62
+ except Exception as e:
63
+ print(f"讀取PDF時發生錯誤:{str(e)}")
64
+ continue
65
+
66
+ return raw_text, processed_count
67
+
68
+ def get_text_chunks(self, text):
69
+ """將文字分割成區塊進行處理"""
70
+ text_splitter = CharacterTextSplitter(
71
+ separator="\n",
72
+ chunk_size=10000,
73
+ chunk_overlap=1000,
74
+ length_function=len
75
+ )
76
+ chunks = text_splitter.split_text(text)
77
+ return chunks
78
+
79
+ def create_vector_store(self, chunks):
80
+ """從文字區塊創建FAISS向量存儲"""
81
+ try:
82
+ self.vector_store = FAISS.from_texts(chunks, self.embeddings)
83
+ self.vector_store.save_local("faiss_index")
84
+ return True
85
+ except Exception as e:
86
+ print(f"創建向量存儲時發生錯誤:{str(e)}")
87
+ return False
88
+
89
+ def load_vector_store(self):
90
+ """載入已存在的向量存儲"""
91
+ try:
92
+ if os.path.exists("faiss_index"):
93
+ self.vector_store = FAISS.load_local(
94
+ "faiss_index",
95
+ embeddings=self.embeddings,
96
+ allow_dangerous_deserialization=True
97
+ )
98
+ return True
99
+ else:
100
+ return False
101
+ except Exception as e:
102
+ print(f"載入向量存儲時發生錯誤:{str(e)}")
103
+ return False
104
+
105
+ def get_conversational_chain(self, temperature=0.3, max_tokens=4096):
106
+ """創建對話鏈"""
107
+ prompt_template = """
108
+ 根據提供的內容盡可能詳細地回答問題。確保提供所有細節。
109
+ 如果你需要更多細節來完美回答問題,那麼請詢問你認為需要了解的更多細節。
110
+ 如果答案不在提供的內容中,只需說"在您提供的內容中找不到答案"。不要提供錯誤的答案。
111
+
112
+ 內容:\n {context}\n
113
+ 問題: \n{question}\n
114
+
115
+ 回答:
116
+ """
117
+
118
+ # Using Flash 2.0 model
119
+ model = ChatGoogleGenerativeAI(
120
+ model="gemini-2.0-flash-exp",
121
+ google_api_key=gemini_api_key,
122
+ temperature=temperature,
123
+ max_tokens=max_tokens,
124
+ top_p=0.8,
125
+ top_k=40
126
+ )
127
+
128
+ prompt = PromptTemplate(
129
+ template=prompt_template,
130
+ input_variables=['context', 'question']
131
+ )
132
+
133
+ chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
134
+ return chain
135
+
136
+ def answer_question(self, question, temperature=0.3, max_tokens=4096, search_k=6):
137
+ """回答用戶問題"""
138
+ if not self.vector_store:
139
+ return "請先上傳並處理PDF文件!"
140
+
141
+ if not question.strip():
142
+ return "請輸入您的問題。"
143
+
144
+ try:
145
+ # 搜索相關文檔
146
+ docs = self.vector_store.similarity_search(question, k=search_k)
147
+
148
+ if not docs:
149
+ return "在上傳的文檔中找不到相關信息。"
150
+
151
+ # 生成回答
152
+ chain = self.get_conversational_chain(temperature, max_tokens)
153
+ response = chain(
154
+ {
155
+ "input_documents": docs,
156
+ "question": question,
157
+ },
158
+ return_only_outputs=True
159
+ )
160
+
161
+ return response["output_text"]
162
+
163
+ except Exception as e:
164
+ return f"處理問題時發生錯誤:{str(e)}"
165
+
166
+ def process_pdfs(self, pdf_files, progress=gr.Progress()):
167
+ """處理PDF文件"""
168
+ if not pdf_files:
169
+ return "請上傳至少一個PDF文件。", ""
170
+
171
+ self.processed_files = []
172
+ progress(0, desc="開始處理PDF文件...")
173
+
174
+ # 提取文字
175
+ progress(0.2, desc="提取PDF文字內容...")
176
+ raw_text, processed_count = self.get_pdf_text(pdf_files)
177
+
178
+ if not raw_text.strip():
179
+ return "無法從PDF文件中提取到文字。", ""
180
+
181
+ progress(0.4, desc="分割文字內容...")
182
+ # 分割文字
183
+ text_chunks = self.get_text_chunks(raw_text)
184
+
185
+ progress(0.6, desc="創建向量存儲...")
186
+ # 創建向量存儲
187
+ success = self.create_vector_store(text_chunks)
188
+
189
+ progress(1.0, desc="處理完成!")
190
+
191
+ if success:
192
+ file_list = "已處理的文件:\n" + "\n".join([f"• {file}" for file in self.processed_files])
193
+ return f"✅ 成功處理 {processed_count} 個PDF文件!\n總共 {len(text_chunks)} 個文字區塊\n現在您可以開始提問。", file_list
194
+ else:
195
+ return "❌ PDF處理失敗,請重試。", ""
196
+
197
+ def clear_data(self):
198
+ """清除處理過的資料"""
199
+ try:
200
+ if os.path.exists("faiss_index"):
201
+ shutil.rmtree("faiss_index")
202
+ self.vector_store = None
203
+ self.processed_files = []
204
+ self.chat_history = []
205
+ return "✅ 已清除所有處理過的資料!", ""
206
+ except Exception as e:
207
+ return f"❌ 清除資料時發生錯誤:{str(e)}", ""
208
+
209
+ def create_docx_report(self, chat_history):
210
+ """創建包含聊天記錄的docx報告"""
211
+ try:
212
+ # 創建新的文檔
213
+ doc = Document()
214
+
215
+ # 添加標題
216
+ title = doc.add_heading('PDF聊天機器人 - 問答記錄', 0)
217
+ title.alignment = 1 # 置中對齊
218
+
219
+ # 添加生成時間
220
+ doc.add_paragraph(f'生成時間:{datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")}')
221
+
222
+ # 添加處理的文件列表
223
+ if self.processed_files:
224
+ doc.add_heading('已處理的PDF文件:', level=2)
225
+ for i, file in enumerate(self.processed_files, 1):
226
+ doc.add_paragraph(f'{i}. {file}', style='List Number')
227
+
228
+ doc.add_paragraph('') # 空行
229
+
230
+ # 添加問答記錄
231
+ doc.add_heading('問答記錄:', level=2)
232
+
233
+ if not chat_history:
234
+ doc.add_paragraph('目前沒有問答記錄。')
235
+ else:
236
+ for i in range(0, len(chat_history), 2):
237
+ if i + 1 < len(chat_history):
238
+ question = chat_history[i]['content']
239
+ answer = chat_history[i + 1]['content']
240
+
241
+ # 問題
242
+ q_paragraph = doc.add_paragraph()
243
+ q_run = q_paragraph.add_run(f'問題 {(i//2)+1}:')
244
+ q_run.bold = True
245
+ q_run.font.size = Inches(0.14)
246
+ q_paragraph.add_run(question)
247
+
248
+ # 回答
249
+ a_paragraph = doc.add_paragraph()
250
+ a_run = a_paragraph.add_run('回答:')
251
+ a_run.bold = True
252
+ a_run.font.size = Inches(0.14)
253
+ a_paragraph.add_run(answer)
254
+
255
+ # 分隔線
256
+ doc.add_paragraph('─' * 50)
257
+
258
+ # 保存到臨時文件
259
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.docx')
260
+ doc.save(temp_file.name)
261
+ temp_file.close()
262
+
263
+ return temp_file.name
264
+
265
+ except Exception as e:
266
+ print(f"創建docx文件時發生錯誤:{str(e)}")
267
+ return None
268
+
269
+ # 初始化聊天機器人
270
+ bot = PDFChatBot()
271
+
272
+ # Gradio 接口函數
273
+ def upload_and_process(files, progress=gr.Progress()):
274
+ return bot.process_pdfs(files, progress)
275
+
276
+ def ask_question(question, history, temperature, max_tokens, search_k):
277
+ if not question.strip():
278
+ return history, ""
279
+
280
+ response = bot.answer_question(question, temperature, max_tokens, search_k)
281
+ # 使用新的消息格式
282
+ user_msg = {"role": "user", "content": question}
283
+ assistant_msg = {"role": "assistant", "content": response}
284
+
285
+ history.append(user_msg)
286
+ history.append(assistant_msg)
287
+
288
+ # 同步更新聊天歷史到bot實例
289
+ bot.chat_history = history.copy()
290
+
291
+ return history, ""
292
+
293
+ def download_chat_history():
294
+ """下載聊天記錄為docx文件"""
295
+ if not bot.chat_history:
296
+ return None
297
+
298
+ docx_path = bot.create_docx_report(bot.chat_history)
299
+ return docx_path
300
+
301
+ def export_to_word():
302
+ """匯出問答記錄為Word文件"""
303
+ if not bot.chat_history:
304
+ return None
305
+
306
+ docx_path = bot.create_docx_report(bot.chat_history)
307
+ return docx_path
308
+
309
+ def clear_chat():
310
+ """清除聊天記錄"""
311
+ bot.chat_history = []
312
+ return [], ""
313
+
314
+ def clear_all_data():
315
+ return bot.clear_data()
316
+
317
+ def load_existing_data():
318
+ if bot.load_vector_store():
319
+ return "✅ 成功載入已處理的資料!", ""
320
+ else:
321
+ return "❌ 沒有找到已處理的資料。", ""
322
+
323
+ # 創建自定義主題
324
+ custom_theme = gr.themes.Soft(
325
+ primary_hue="blue",
326
+ secondary_hue="gray",
327
+ neutral_hue="slate",
328
+ font=gr.themes.GoogleFont("Noto Sans TC"),
329
+ font_mono=gr.themes.GoogleFont("JetBrains Mono")
330
+ )
331
+
332
+ # 創建 Gradio 介面
333
+ with gr.Blocks(
334
+ title="PDF智能問答系統",
335
+ theme=custom_theme,
336
+ css="""
337
+ .gradio-container {
338
+ max-width: 1200px !important;
339
+ margin: auto !important;
340
+ }
341
+ .main-header {
342
+ text-align: center;
343
+ padding: 20px;
344
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
345
+ color: white;
346
+ border-radius: 10px;
347
+ margin-bottom: 20px;
348
+ }
349
+ .status-box {
350
+ background-color: #f8f9fa;
351
+ border-left: 4px solid #007bff;
352
+ padding: 15px;
353
+ border-radius: 5px;
354
+ }
355
+ .file-info {
356
+ background-color: #e8f5e8;
357
+ border-left: 4px solid #28a745;
358
+ padding: 10px;
359
+ border-radius: 5px;
360
+ }
361
+ """
362
+ ) as demo:
363
+
364
+ # 主標題區域
365
+ with gr.Row():
366
+ gr.HTML("""
367
+ <div class="main-header">
368
+ <h1>🤖 PDF智能問答系統</h1>
369
+ <p>基於 Gemini 2.0 Flash 的 RAG 技術 | 支持多語言問答</p>
370
+ </div>
371
+ """)
372
+
373
+ # 主要功能區域
374
+ with gr.Tab("📁 文件管理", id="file_tab"):
375
+ with gr.Row():
376
+ with gr.Column(scale=3):
377
+ # 文件上傳區域
378
+ with gr.Group():
379
+ gr.Markdown("### 📤 上傳PDF文件")
380
+ file_upload = gr.File(
381
+ file_count="multiple",
382
+ file_types=[".pdf"],
383
+ label="選擇PDF文件",
384
+ height=150,
385
+ file_count="multiple"
386
+ )
387
+
388
+ # 處理選項
389
+ with gr.Row():
390
+ process_btn = gr.Button(
391
+ "🚀 開始處理",
392
+ variant="primary",
393
+ size="lg",
394
+ scale=2
395
+ )
396
+ load_btn = gr.Button(
397
+ "📂 載入已處理資料",
398
+ variant="secondary",
399
+ scale=1
400
+ )
401
+ clear_btn = gr.Button(
402
+ "🗑️ 清除所有資料",
403
+ variant="stop",
404
+ scale=1
405
+ )
406
+
407
+ with gr.Column(scale=2):
408
+ # 狀態顯示區域
409
+ with gr.Group():
410
+ gr.Markdown("### 📊 處理狀態")
411
+ status_text = gr.Textbox(
412
+ label="處理進度",
413
+ lines=6,
414
+ interactive=False,
415
+ elem_classes=["status-box"]
416
+ )
417
+
418
+ # 文件列表
419
+ gr.Markdown("### 📋 已處理文件")
420
+ file_list = gr.Textbox(
421
+ label="文件清單",
422
+ lines=8,
423
+ interactive=False,
424
+ elem_classes=["file-info"]
425
+ )
426
+
427
+ with gr.Tab("💬 智能問答", id="chat_tab"):
428
+ with gr.Row():
429
+ with gr.Column(scale=4):
430
+ # 聊天區域
431
+ chatbot = gr.Chatbot(
432
+ label="💬 對話記錄",
433
+ height=600,
434
+ show_copy_button=True,
435
+ type="messages",
436
+ avatar_images=["👤", "🤖"],
437
+ bubble_full_width=False
438
+ )
439
+
440
+ with gr.Column(scale=1):
441
+ # 側邊欄功能
442
+ with gr.Group():
443
+ gr.Markdown("### ⚙️ 問答設定")
444
+
445
+ # 模型參數調整
446
+ temperature = gr.Slider(
447
+ minimum=0.1,
448
+ maximum=1.0,
449
+ value=0.3,
450
+ step=0.1,
451
+ label="創意度 (Temperature)",
452
+ info="數值越高回答越有創意"
453
+ )
454
+
455
+ max_tokens = gr.Slider(
456
+ minimum=512,
457
+ maximum=8192,
458
+ value=4096,
459
+ step=512,
460
+ label="最大回答長度",
461
+ info="控制回答的詳細程度"
462
+ )
463
+
464
+ search_k = gr.Slider(
465
+ minimum=2,
466
+ maximum=10,
467
+ value=6,
468
+ step=1,
469
+ label="檢索文檔數量",
470
+ info="搜索相關文檔的數量"
471
+ )
472
+
473
+ # 輸入區域
474
+ with gr.Row():
475
+ question_input = gr.Textbox(
476
+ placeholder="請輸入您的問題... (支援中文、英文等多語言)",
477
+ label="💭 問題輸入",
478
+ lines=3,
479
+ scale=4,
480
+ max_lines=5
481
+ )
482
+ ask_btn = gr.Button(
483
+ "📤 發送問題",
484
+ variant="primary",
485
+ scale=1,
486
+ size="lg"
487
+ )
488
+
489
+ # 快捷操作
490
+ with gr.Row():
491
+ clear_chat_btn = gr.Button(
492
+ "🧹 清除對話",
493
+ variant="secondary",
494
+ scale=1
495
+ )
496
+ download_btn = gr.Button(
497
+ "📥 下載問答記錄",
498
+ variant="primary",
499
+ scale=1
500
+ )
501
+ export_btn = gr.Button(
502
+ "📄 匯出為Word",
503
+ variant="secondary",
504
+ scale=1
505
+ )
506
+
507
+ # 問題範例
508
+ with gr.Group():
509
+ gr.Markdown("### 💡 問題範例")
510
+ gr.Examples(
511
+ examples=[
512
+ "這份文檔的主要內容是什麼?",
513
+ "請總結文檔的重點和關鍵概念",
514
+ "文檔中提到了哪些重要數據或統計?",
515
+ "能否詳細解釋某個特定主題或概念?",
516
+ "文檔的結論是什麼?",
517
+ "有哪些重要的建議或建議?",
518
+ "文檔中提到了哪些風險或挑戰?",
519
+ "請比較文檔中提到的不同觀點"
520
+ ],
521
+ inputs=question_input,
522
+ label="點擊範例快速填入"
523
+ )
524
+
525
+ # 隱藏的文件下載組件
526
+ download_file = gr.File(visible=False)
527
+
528
+ # 下載功能處理函數
529
+ def handle_download():
530
+ file_path = download_chat_history()
531
+ if file_path:
532
+ return gr.update(value=file_path, visible=True)
533
+ else:
534
+ gr.Warning("沒有聊天記錄可以下載!")
535
+ return gr.update(visible=False)
536
+
537
+ # 事件處理
538
+ process_btn.click(
539
+ fn=upload_and_process,
540
+ inputs=[file_upload],
541
+ outputs=[status_text, file_list],
542
+ show_progress=True
543
+ )
544
+
545
+ load_btn.click(
546
+ fn=load_existing_data,
547
+ outputs=[status_text, file_list]
548
+ )
549
+
550
+ clear_btn.click(
551
+ fn=clear_all_data,
552
+ outputs=[status_text, file_list]
553
+ )
554
+
555
+ ask_btn.click(
556
+ fn=ask_question,
557
+ inputs=[question_input, chatbot, temperature, max_tokens, search_k],
558
+ outputs=[chatbot, question_input]
559
+ )
560
+
561
+ question_input.submit(
562
+ fn=ask_question,
563
+ inputs=[question_input, chatbot, temperature, max_tokens, search_k],
564
+ outputs=[chatbot, question_input]
565
+ )
566
+
567
+ clear_chat_btn.click(
568
+ fn=clear_chat,
569
+ outputs=[chatbot, question_input]
570
+ )
571
+
572
+ download_btn.click(
573
+ fn=handle_download,
574
+ outputs=download_file
575
+ )
576
+
577
+ export_btn.click(
578
+ fn=export_to_word,
579
+ outputs=download_file
580
+ )
581
+
582
+ if __name__ == "__main__":
583
+ # 嘗試載入現有的向量存儲
584
+ bot.load_vector_store()
585
+
586
+ # 啟動應用
587
+ demo.launch(
588
+ share=False, # 設為 True 可獲得公共連結
589
+ server_name="127.0.0.1", # 本地訪問
590
+ server_port=None, # 自動選擇可用端���
591
+ show_error=True,
592
+ inbrowser=True # 自動打開瀏覽器
593
+ )
requirements.txt ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PDF 智能問答系統 - 依賴套件清單
2
+ # 基於 Gemini 2.0 Flash 的 RAG 技術
3
+
4
+ # ===== 核心框架 =====
5
+ gradio>=4.0.0 # Web 介面框架
6
+ langchain>=0.1.0 # LangChain 核心
7
+ langchain-community>=0.0.20 # LangChain 社群擴展
8
+ langchain-google-genai>=1.0.0 # Google Gemini 整合
9
+
10
+ # ===== Google AI 服務 =====
11
+ google-generativeai>=0.3.0 # Google Gemini API
12
+
13
+ # ===== PDF 處理 =====
14
+ PyPDF2>=3.0.0 # PDF 文字提取
15
+
16
+ # ===== 向量資料庫 =====
17
+ faiss-cpu>=1.7.4 # FAISS 向量搜尋 (CPU 版本)
18
+ # faiss-gpu>=1.7.4 # 如果使用 GPU,請取消註解此行並註解上行
19
+
20
+ # ===== 文檔處理 =====
21
+ python-docx>=0.8.11 # Word 文檔生成
22
+
23
+ # ===== 環境和配置 =====
24
+ python-dotenv>=1.0.0 # 環境變數管理
25
+
26
+ # ===== 數值計算和文字處理 =====
27
+ numpy>=1.24.0 # 數值計算
28
+ tiktoken>=0.5.0 # OpenAI tokenizer
29
+
30
+ # ===== HTTP 和網路 =====
31
+ requests>=2.31.0 # HTTP 請求
32
+
33
+ # ===== 工具和輔助 =====
34
+ tqdm>=4.65.0 # 進度條
35
+ pydantic>=2.0.0 # 資料驗證
36
+
37
+ # ===== 可選增強套件 =====
38
+ # 如果需要更強的 PDF 處理能力,可以選擇以下之一:
39
+ # pymupdf>=1.23.0 # MuPDF Python 綁定,處理能力更強
40
+ # pdfplumber>=0.9.0 # 另一個 PDF 處理選項
41
+
42
+ # 如果需要更好的文字嵌入:
43
+ # sentence-transformers>=2.2.0 # 更好的嵌入模型
44
+
45
+ # 如果需要更好的文字分割:
46
+ # spacy>=3.7.0 # 自然語言處理
47
+ # nltk>=3.8.0 # 自然語言工具包
48
+
49
+ # ===== 開發工具 (可選) =====
50
+ # pytest>=7.4.0 # 測試框架
51
+ # black>=23.0.0 # 程式碼格式化
52
+ # flake8>=6.0.0 # 程式碼檢查
53
+ # jupyter>=1.0.0 # Jupyter notebook
54
+
55
+ # ===== 系統需求 =====
56
+ # Python >= 3.8
57
+ # 建議使用 Python 3.9 或更高版本
58
+ # 記憶體建議 8GB 以上
59
+ # 硬碟空間建議 2GB 以上用於模型和索引