Luongsosad commited on
Commit
a03b876
·
verified ·
1 Parent(s): 17ee3ae

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -0
app.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import fitz # PyMuPDF
3
+ from langchain.llms import Ollama
4
+ from langchain.chains.question_answering import load_qa_chain
5
+ 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 mô hình Ollama (như llama3) để trả lời câu hỏi từ file PDF.",
46
+ ).launch()