Luongsosad commited on
Commit
7ec3e43
·
verified ·
1 Parent(s): df1ffa1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -33
app.py CHANGED
@@ -6,41 +6,58 @@ from langchain.prompts import PromptTemplate
6
  from langchain.docstore.document import Document
7
 
8
  def extract_text_from_pdf(file):
9
- doc = fitz.open(stream=file.read(), filetype="pdf")
10
  text = ""
11
  for page in doc:
12
  text += page.get_text()
13
  return text
14
 
15
- def answer_question(pdf_file, question):
16
- if not pdf_file or not question:
17
- return "Vui lòng tải file PDF và nhập câu hỏi."
18
-
19
- content = extract_text_from_pdf(pdf_file)
20
-
21
- # Khởi tạo model Ollama
22
- llm = Ollama(model="llama3") # Bạn có thể dùng 'mistral', 'phi', v.v.
23
-
24
- # Prompt đơn giản
25
- prompt_template = PromptTemplate.from_template(
26
- "Trả lời câu hỏi sau dựa trên tài liệu:\n\n{context}\n\nCâu hỏi: {question}"
27
- )
28
-
29
- chain = load_qa_chain(llm, chain_type="stuff", prompt=prompt_template)
30
-
31
- # LangChain yêu cầu list Document
32
- docs = [Document(page_content=content)]
33
-
34
- result = chain.run(input_documents=docs, question=question)
35
- return result
36
-
37
- gr.Interface(
38
- fn=answer_question,
39
- inputs=[
40
- gr.File(label="Tải lên PDF"),
41
- gr.Textbox(label="Câu hỏi về nội dung PDF")
42
- ],
43
- outputs="text",
44
- title="PDF Q&A với Ollama",
45
- description="Sử dụng hình Ollama (như llama3) để trả lời câu hỏi từ file PDF.",
46
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from langchain.docstore.document import Document
7
 
8
  def extract_text_from_pdf(file):
9
+ doc = fitz.open(file.name) # Fix lỗi: dùng tên file thay vì file.read()
10
  text = ""
11
  for page in doc:
12
  text += page.get_text()
13
  return text
14
 
15
+ # Trạng thái lưu lịch sử chat (nếu không dùng PDF)
16
+ chat_history = []
17
+
18
+ def answer_question(pdf_file, question, history):
19
+ if not question:
20
+ return "Vui lòng nhập câu hỏi.", history
21
+
22
+ llm = Ollama(model="llama3")
23
+
24
+ if pdf_file: # Nếu PDF được tải lên
25
+ content = extract_text_from_pdf(pdf_file)
26
+ prompt_template = PromptTemplate.from_template(
27
+ "Trả lời câu hỏi sau dựa trên tài liệu:\n\n{context}\n\nCâu hỏi: {question}"
28
+ )
29
+ chain = load_qa_chain(llm, chain_type="stuff", prompt=prompt_template)
30
+ docs = [Document(page_content=content)]
31
+ result = chain.run(input_documents=docs, question=question)
32
+ return result, history
33
+ else:
34
+ # Chat tự do (không có PDF)
35
+ context = "\n".join([f"User: {q}\nAssistant: {a}" for q, a in history[-5:]]) # nhớ 5 lượt gần nhất
36
+ prompt = f"{context}\nUser: {question}\nAssistant:"
37
+
38
+ answer = llm(prompt)
39
+ history.append((question, answer.strip()))
40
+ return answer.strip(), history
41
+
42
+ # Giao diện Gradio nâng cấp
43
+ chatbot = gr.Chatbot()
44
+ with gr.Blocks() as demo:
45
+ gr.Markdown("## 🧠 PDF Q&A Chat tự do với Ollama")
46
+ with gr.Row():
47
+ pdf_file = gr.File(label="📄 Tải PDF (tùy chọn)")
48
+ with gr.Row():
49
+ question = gr.Textbox(label="💬 Nhập câu hỏi", placeholder="Hỏi gì cũng được...")
50
+ with gr.Row():
51
+ submit_btn = gr.Button("Gửi câu hỏi")
52
+ with gr.Row():
53
+ chatbot_output = chatbot
54
+
55
+ state = gr.State([]) # Lưu lịch sử hội thoại
56
+
57
+ def respond(pdf, q, hist):
58
+ answer, updated_history = answer_question(pdf, q, hist)
59
+ return updated_history, updated_history
60
+
61
+ submit_btn.click(respond, inputs=[pdf_file, question, state], outputs=[chatbot_output, state])
62
+
63
+ demo.launch()