uyen13 commited on
Commit
faec42b
·
verified ·
1 Parent(s): 25e4726

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -89
app.py CHANGED
@@ -1,91 +1,56 @@
1
- import os
2
- from langchain_community.document_loaders import PyPDFLoader
3
  from langchain.text_splitter import CharacterTextSplitter
4
- from langchain_community.embeddings import HuggingFaceEmbeddings # Sử dụng Sentence Transformers qua wrapper của Langchain
5
- from langchain_community.vectorstores import FAISS
6
  from langchain.chains import RetrievalQA
7
- # Chọn một LLM từ Langchain Community (ví dụ: chạy mô hình GGML/GGUF cục bộ)
8
- from langchain_community.llms import CTransformers # Hoặc LlamaCpp nếu bạn muốn dùng Llama.cpp
9
- from langchain_community.llms import HuggingFaceHub
10
- import os
11
-
12
- # --- Cấu hình ---
13
- pdf_path = "duong_dan_den_file_pdf_cua_ban.pdf" # <-- THAY ĐỔI ĐƯỜNG DẪN NÀY
14
- embedding_model_name = "all-MiniLM-L6-v2" # Model embedding phổ biến từ Sentence Transformers
15
- # Cấu hình cho LLM chạy cục bộ (sử dụng CTransformers với model định dạng GGUF)
16
- # Bạn cần tải về một model phù hợp, ví dụ từ TheBloke trên Hugging Face
17
- # Ví dụ: https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF
18
- # Thay đổi đường dẫn và tên file model nếu cần
19
- llm_model_path = "./models/mistral-7b-instruct-v0.1.Q4_K_M.gguf" # <-- THAY ĐỔI ĐƯỜNG DẪN ĐẾN MODEL GGUF
20
- llm_model_type = "mistral" # Loại model (ví dụ: llama, gpt2, mistral, etc.)
21
-
22
- # --- Các bước thực hiện ---
23
-
24
- # 1. Tải tài liệu PDF
25
- print(f"Đang tải tài liệu từ: {pdf_path}")
26
- loader = PyPDFLoader(pdf_path)
27
- documents = loader.load()
28
- if not documents:
29
- print("Lỗi: Không thể tải hoặc không có nội dung trong file PDF.")
30
- exit()
31
- print(f"Đã tải {len(documents)} trang.")
32
-
33
- # 2. Chia tài liệu thành các đoạn nhỏ (chunks)
34
- print("Đang chia tài liệu thành các chunks...")
35
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100) # Điều chỉnh kích thước chunk nếu cần
36
- docs = text_splitter.split_documents(documents)
37
- print(f"Đã chia thành {len(docs)} chunks.")
38
-
39
- # 3. Tạo Embeddings cho các chunks và lưu vào Vector Store (FAISS)
40
- print(f"Đang tạo embeddings bằng model: {embedding_model_name}")
41
- # Sử dụng HuggingFaceEmbeddings, nó sẽ tự động tải model sentence-transformer
42
- embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
43
-
44
- print("Đang xây dựng cơ sở dữ liệu vector FAISS...")
45
- # Tạo vector store từ các documents và embeddings
46
- vectorstore = FAISS.from_documents(docs, embeddings)
47
- print("Đã tạo xong FAISS index.")
48
-
49
- # 4. Khởi tạo LLM (Sử dụng CTransformers để chạy model GGUF cục bộ)
50
- print(f"Đang khởi tạo LLM từ model: {llm_model_path}")
51
- # Tham khảo tài liệu CTransformers để biết các tham số cấu hình khác
52
- # https://python.langchain.com/docs/integrations/llms/ctransformers
53
- llm = HuggingFaceHub(
54
- repo_id="google/flan-t5-large", # Chọn một model trên Hub
55
- model_kwargs={"temperature": 0.7, "max_length": 512}
56
- )
57
- print("Đã khởi tạo LLM.")
58
-
59
- # 5. Tạo chuỗi RetrievalQA
60
- # Chuỗi này sẽ lấy câu hỏi, tìm kiếm chunks liên quan trong vector store,
61
- # và đưa chunks đó cùng câu hỏi cho LLM để tạo câu trả lời.
62
- print("Đang tạo chuỗi RetrievalQA...")
63
- qa_chain = RetrievalQA.from_chain_type(
64
- llm=llm,
65
- chain_type="stuff", # Các loại chain khác: "map_reduce", "refine", "map_rerank"
66
- retriever=vectorstore.as_retriever(search_kwargs={'k': 3}), # Lấy 3 chunks liên quan nhất
67
- return_source_documents=True # Tùy chọn: trả về các chunks nguồn đã sử dụng
68
- )
69
- print("Chatbot đã sẵn sàng!")
70
-
71
- # 6. Vòng lặp hỏi đáp
72
- while True:
73
- query = input("\nNhập câu hỏi của bạn (hoặc gõ 'quit' để thoát): ")
74
- if query.lower() == 'quit':
75
- break
76
- if not query:
77
- continue
78
-
79
- print("Đang xử lý câu hỏi...")
80
- # Chạy chuỗi để nhận câu trả lời
81
- result = qa_chain.invoke({"query": query}) # Sử dụng invoke thay vì __call__ hoặc run
82
-
83
- print("\nCâu trả lời:")
84
- print(result['result'])
85
-
86
- # Tùy chọn: In ra các source documents được sử dụng
87
- # print("\nCác đoạn văn bản nguồn được sử dụng:")
88
- # for source_doc in result.get('source_documents', []):
89
- # print(f"- Trang {source_doc.metadata.get('page', 'N/A')}: ...{source_doc.page_content[:100]}...")
90
-
91
- print("Tạm biệt!")
 
1
+ # app.py
2
+ from langchain.document_loaders import PyPDFLoader
3
  from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain.embeddings import SentenceTransformerEmbeddings
5
+ from langchain.vectorstores import FAISS
6
  from langchain.chains import RetrievalQA
7
+ from langchain.llms import HuggingFacePipeline
8
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
9
+
10
+ import streamlit as st
11
+ import tempfile
12
+
13
+ # Load FLAN-T5 model
14
+ model_name = "google/flan-t5-base"
15
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
16
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
17
+
18
+ pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
19
+ llm = HuggingFacePipeline(pipeline=pipe)
20
+
21
+ # Streamlit UI
22
+ st.title("Chat with PDF (FLAN-T5, no OpenAI)")
23
+
24
+ uploaded_file = st.file_uploader("Upload a PDF", type="pdf")
25
+ if uploaded_file:
26
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
27
+ tmp_file.write(uploaded_file.read())
28
+ pdf_path = tmp_file.name
29
+
30
+ # Load PDF
31
+ loader = PyPDFLoader(pdf_path)
32
+ documents = loader.load()
33
+
34
+ # Split text
35
+ splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
36
+ docs = splitter.split_documents(documents)
37
+
38
+ # Embed & Store
39
+ embedding = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
40
+ db = FAISS.from_documents(docs, embedding)
41
+ retriever = db.as_retriever()
42
+
43
+ # RetrievalQA chain
44
+ qa_chain = RetrievalQA.from_chain_type(
45
+ llm=llm,
46
+ chain_type="stuff",
47
+ retriever=retriever,
48
+ return_source_documents=True
49
+ )
50
+
51
+ # Chat input
52
+ query = st.text_input("Ask a question about the PDF:")
53
+ if query:
54
+ result = qa_chain(query)
55
+ st.write("### Answer:")
56
+ st.write(result["result"])