phucbienvan commited on
Commit
6cb69fd
·
1 Parent(s): e55933e

change text

Browse files
Files changed (2) hide show
  1. app.py +26 -26
  2. utils/llm_handler.py +8 -8
app.py CHANGED
@@ -11,7 +11,7 @@ from io import BytesIO
11
  load_dotenv()
12
 
13
  if not os.getenv("HUGGINGFACEHUB_API_TOKEN"):
14
- st.error("HUGGINGFACEHUB_API_TOKEN không tồn tại trong biến môi trường!")
15
  st.stop()
16
 
17
  st.set_page_config(
@@ -20,7 +20,7 @@ st.set_page_config(
20
  layout="wide"
21
  )
22
 
23
- # Hiển thị logo và tiêu đề cạnh nhau
24
  col1, col2 = st.columns([1, 5])
25
  with col1:
26
  try:
@@ -29,12 +29,12 @@ with col1:
29
  logo = Image.open(BytesIO(response.content))
30
  st.image(logo, width=150)
31
  except Exception as e:
32
- st.error(f"Không thể tải logo: {e}")
33
 
34
  with col2:
35
  st.title("📚 PDF Chatbot")
36
- st.markdown("### Tải lên file PDF và đặt câu hỏi về nội dung")
37
- st.markdown("##### Tác giả: phucbienvan")
38
 
39
  if "vector_store" not in st.session_state:
40
  st.session_state["vector_store"] = None
@@ -46,11 +46,11 @@ if "pdf_name" not in st.session_state:
46
  st.session_state["pdf_name"] = None
47
 
48
  with st.sidebar:
49
- st.header("Tải lên tài liệu")
50
- uploaded_file = st.file_uploader("Chọn file PDF", type="pdf")
51
 
52
  if uploaded_file is not None and (st.session_state["pdf_name"] != uploaded_file.name):
53
- with st.spinner("Đang xử lý file PDF..."):
54
  pdf_processor = PDFProcessor()
55
  st.session_state["vector_store"] = pdf_processor.process_pdf(uploaded_file)
56
 
@@ -60,18 +60,18 @@ with st.sidebar:
60
  st.session_state["pdf_name"] = uploaded_file.name
61
  st.session_state["chat_history"] = []
62
 
63
- st.success(f"Đã xử lý file: {uploaded_file.name}")
64
 
65
  st.markdown("---")
66
- st.markdown("### Hướng dẫn sử dụng")
67
  st.markdown("""
68
- 1. Tải lên file PDF từ máy tính
69
- 2. Đợi hệ thống xử lý file
70
- 3. Đặt câu hỏi về nội dung file
71
- 4. Nhận câu trả lời từ chatbot
72
  """)
73
 
74
- # Hiển thị logo ở sidebar
75
  st.markdown("---")
76
  try:
77
  logo_url = "https://cdn-avatars.huggingface.co/v1/production/uploads/65129261353a60593b1dc353/PY40eVSt4jkYQinleKGua.jpeg"
@@ -81,7 +81,7 @@ with st.sidebar:
81
  except:
82
  pass
83
 
84
- st.subheader("Cuộc trò chuyện")
85
 
86
  for i, (question, answer) in enumerate(st.session_state["chat_history"]):
87
  message_container = st.container()
@@ -90,7 +90,7 @@ for i, (question, answer) in enumerate(st.session_state["chat_history"]):
90
  with col1:
91
  st.markdown("🧑")
92
  with col2:
93
- st.markdown(f"**Bạn:** {question}")
94
 
95
  message_container = st.container()
96
  with message_container:
@@ -102,15 +102,15 @@ for i, (question, answer) in enumerate(st.session_state["chat_history"]):
102
 
103
  st.markdown("---")
104
 
105
- question = st.text_input("Nhập câu hỏi của bạn:", key="question_input")
106
 
107
- if st.button("Gửi câu hỏi"):
108
  if st.session_state["qa_chain"] is None:
109
- st.error("Vui lòng tải lên file PDF trước khi đặt câu hỏi!")
110
  elif not question:
111
- st.warning("Vui lòng nhập câu hỏi!")
112
  else:
113
- with st.spinner("Đang tìm câu trả lời..."):
114
  llm_handler = LLMHandler()
115
  answer, sources = llm_handler.get_answer(st.session_state["qa_chain"], question)
116
 
@@ -122,7 +122,7 @@ if st.button("Gửi câu hỏi"):
122
  with col1:
123
  st.markdown("🧑")
124
  with col2:
125
- st.markdown(f"**Bạn:** {question}")
126
 
127
  message_container = st.container()
128
  with message_container:
@@ -133,13 +133,13 @@ if st.button("Gửi câu hỏi"):
133
  st.markdown(f"**Bot:** {answer}")
134
 
135
  if sources:
136
- with st.expander("Xem nguồn tham khảo"):
137
  for i, doc in enumerate(sources):
138
- st.markdown(f"**Nguồn {i+1}:**")
139
  st.markdown(doc.page_content)
140
  st.markdown("---")
141
 
142
  st.rerun()
143
 
144
  st.markdown("---")
145
- st.markdown("### 📚 PDF Chatbot | Tác giả: phucbienvan")
 
11
  load_dotenv()
12
 
13
  if not os.getenv("HUGGINGFACEHUB_API_TOKEN"):
14
+ st.error("HUGGINGFACEHUB_API_TOKEN does not exist in environment variables!")
15
  st.stop()
16
 
17
  st.set_page_config(
 
20
  layout="wide"
21
  )
22
 
23
+ # Display logo and title side by side
24
  col1, col2 = st.columns([1, 5])
25
  with col1:
26
  try:
 
29
  logo = Image.open(BytesIO(response.content))
30
  st.image(logo, width=150)
31
  except Exception as e:
32
+ st.error(f"Could not load logo: {e}")
33
 
34
  with col2:
35
  st.title("📚 PDF Chatbot")
36
+ st.markdown("### Upload PDF files and ask questions about the content")
37
+ st.markdown("##### Author: phucbienvan")
38
 
39
  if "vector_store" not in st.session_state:
40
  st.session_state["vector_store"] = None
 
46
  st.session_state["pdf_name"] = None
47
 
48
  with st.sidebar:
49
+ st.header("Upload Document")
50
+ uploaded_file = st.file_uploader("Choose PDF file", type="pdf")
51
 
52
  if uploaded_file is not None and (st.session_state["pdf_name"] != uploaded_file.name):
53
+ with st.spinner("Processing PDF file..."):
54
  pdf_processor = PDFProcessor()
55
  st.session_state["vector_store"] = pdf_processor.process_pdf(uploaded_file)
56
 
 
60
  st.session_state["pdf_name"] = uploaded_file.name
61
  st.session_state["chat_history"] = []
62
 
63
+ st.success(f"Processed file: {uploaded_file.name}")
64
 
65
  st.markdown("---")
66
+ st.markdown("### User Guide")
67
  st.markdown("""
68
+ 1. Upload a PDF file from your computer
69
+ 2. Wait for the system to process the file
70
+ 3. Ask questions about the file content
71
+ 4. Get answers from the chatbot
72
  """)
73
 
74
+ # Display logo in sidebar
75
  st.markdown("---")
76
  try:
77
  logo_url = "https://cdn-avatars.huggingface.co/v1/production/uploads/65129261353a60593b1dc353/PY40eVSt4jkYQinleKGua.jpeg"
 
81
  except:
82
  pass
83
 
84
+ st.subheader("Conversation")
85
 
86
  for i, (question, answer) in enumerate(st.session_state["chat_history"]):
87
  message_container = st.container()
 
90
  with col1:
91
  st.markdown("🧑")
92
  with col2:
93
+ st.markdown(f"**You:** {question}")
94
 
95
  message_container = st.container()
96
  with message_container:
 
102
 
103
  st.markdown("---")
104
 
105
+ question = st.text_input("Enter your question:", key="question_input")
106
 
107
+ if st.button("Send Question"):
108
  if st.session_state["qa_chain"] is None:
109
+ st.error("Please upload a PDF file before asking questions!")
110
  elif not question:
111
+ st.warning("Please enter a question!")
112
  else:
113
+ with st.spinner("Finding answer..."):
114
  llm_handler = LLMHandler()
115
  answer, sources = llm_handler.get_answer(st.session_state["qa_chain"], question)
116
 
 
122
  with col1:
123
  st.markdown("🧑")
124
  with col2:
125
+ st.markdown(f"**You:** {question}")
126
 
127
  message_container = st.container()
128
  with message_container:
 
133
  st.markdown(f"**Bot:** {answer}")
134
 
135
  if sources:
136
+ with st.expander("View References"):
137
  for i, doc in enumerate(sources):
138
+ st.markdown(f"**Source {i+1}:**")
139
  st.markdown(doc.page_content)
140
  st.markdown("---")
141
 
142
  st.rerun()
143
 
144
  st.markdown("---")
145
+ st.markdown("### 📚 PDF Chatbot | Author: phucbienvan")
utils/llm_handler.py CHANGED
@@ -31,17 +31,17 @@ class LLMHandler:
31
  return "\n".join([doc.page_content for doc in docs])
32
 
33
  def generate_answer(question, context):
34
- # Giới hạn độ dài context để tránh vượt quá token limit
35
  if len(context) > 3000:
36
  context = context[:3000]
37
 
38
- prompt = f"""<s>[INST] Bạn là trợ lý AI hữu ích. Sử dụng đoạn văn bản sau để trả lời câu hỏi. Nếu không tìm thấy câu trả lời, hãy nói "Tôi không tìm thấy thông tin về điều này trong tài liệu." Hãy trả lời đầy đủ và chi tiết.
39
 
40
- Đoạn văn bản: {context}
41
 
42
- Câu hỏi: {question}
43
 
44
- Trả lời bằng tiếng Việt: [/INST]"""
45
 
46
  try:
47
  response = self.client.text_generation(
@@ -54,14 +54,14 @@ Trả lời bằng tiếng Việt: [/INST]"""
54
  return_full_text=False
55
  )
56
 
57
- # Đảm bảo câu trả lời hoàn chỉnh
58
  if response and not response.endswith(('.', '!', '?', '"', ')', ']', '}')):
59
  response += "..."
60
 
61
  return response
62
  except Exception as e:
63
  print(f"Error generating response: {e}")
64
- return "Xin lỗi, tôi gặp lỗi khi xử lý câu hỏi của bạn. Vui lòng thử lại."
65
 
66
  return {
67
  "get_context": get_relevant_context,
@@ -82,4 +82,4 @@ Trả lời bằng tiếng Việt: [/INST]"""
82
  return answer, []
83
  except Exception as e:
84
  print(f"Error in get_answer: {e}")
85
- return "Xin lỗi, có lỗi xảy ra.", []
 
31
  return "\n".join([doc.page_content for doc in docs])
32
 
33
  def generate_answer(question, context):
34
+ # Limit context length to avoid exceeding token limit
35
  if len(context) > 3000:
36
  context = context[:3000]
37
 
38
+ prompt = f"""<s>[INST] You are a helpful AI assistant. Use the following text to answer the question. If you cannot find the answer, say "I couldn't find information about this in the document." Provide a complete and detailed answer.
39
 
40
+ Text: {context}
41
 
42
+ Question: {question}
43
 
44
+ Answer in Vietnamese: [/INST]"""
45
 
46
  try:
47
  response = self.client.text_generation(
 
54
  return_full_text=False
55
  )
56
 
57
+ # Ensure complete answer
58
  if response and not response.endswith(('.', '!', '?', '"', ')', ']', '}')):
59
  response += "..."
60
 
61
  return response
62
  except Exception as e:
63
  print(f"Error generating response: {e}")
64
+ return "Sorry, I encountered an error processing your question. Please try again."
65
 
66
  return {
67
  "get_context": get_relevant_context,
 
82
  return answer, []
83
  except Exception as e:
84
  print(f"Error in get_answer: {e}")
85
+ return "Sorry, an error occurred.", []