Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,84 +1,64 @@
|
|
1 |
import gradio as gr
|
2 |
-
from langchain.chains import RetrievalQA
|
3 |
from langchain.vectorstores import Chroma
|
4 |
-
from
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from langchain.
|
8 |
-
from
|
9 |
-
|
10 |
-
# OCR-Ersatz: LayoutLMv3 für Textextraktion aus PDFs
|
11 |
-
from transformers import LayoutLMv3Processor
|
12 |
from pdf2image import convert_from_path
|
13 |
-
|
14 |
-
import torch
|
15 |
|
16 |
class LayoutLMv3OCR:
|
17 |
def __init__(self):
|
18 |
self.processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
|
19 |
-
self.model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/layoutlmv3-base
|
20 |
|
21 |
def extract_text(self, pdf_path):
|
22 |
-
|
23 |
-
|
24 |
-
for
|
25 |
-
|
26 |
-
outputs = self.model(**
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
page_text = " ".join([token for token, pred in zip(tokens, predictions) if pred == 1])
|
31 |
-
extracted_texts.append(page_text)
|
32 |
-
return extracted_texts
|
33 |
|
34 |
-
# Initialisiere OCR
|
35 |
ocr_tool = LayoutLMv3OCR()
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
47 |
|
48 |
-
def
|
|
|
|
|
49 |
extracted_text = ocr_tool.extract_text(pdf_path)
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
documents.append(doc)
|
54 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
55 |
-
split_docs = text_splitter.split_documents(documents)
|
56 |
-
vector_store = Chroma.from_documents(split_docs, embedding=embeddings)
|
57 |
-
retriever = vector_store.as_retriever()
|
58 |
-
qa_chain = RetrievalQA(retriever=retriever, combine_documents_chain=flan_generate)
|
59 |
-
return qa_chain
|
60 |
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
relevant_pages = set()
|
65 |
-
for doc in qa_chain.retriever.get_relevant_documents(question):
|
66 |
-
relevant_pages.add(doc.metadata.get("page", "Unbekannt"))
|
67 |
-
page_info = f" (Referenz: Seite(n) {', '.join(map(str, relevant_pages))})"
|
68 |
-
return response + page_info
|
69 |
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
response_output
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
outputs=response_output,
|
78 |
-
title="RAG Chatbot (Deutsch)"
|
79 |
-
)
|
80 |
-
return interface
|
81 |
|
82 |
if __name__ == "__main__":
|
83 |
-
interface = gradio_interface()
|
84 |
interface.launch()
|
|
|
1 |
import gradio as gr
|
|
|
2 |
from langchain.vectorstores import Chroma
|
3 |
+
from langchain_community.document_loaders import PyPDFLoader
|
4 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
5 |
+
from transformers import LayoutLMv3Processor, AutoModelForSeq2SeqLM
|
6 |
+
from langchain.chains import RetrievalQA
|
7 |
+
from langchain.prompts import PromptTemplate
|
|
|
|
|
|
|
8 |
from pdf2image import convert_from_path
|
9 |
+
import os
|
|
|
10 |
|
11 |
class LayoutLMv3OCR:
|
12 |
def __init__(self):
|
13 |
self.processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
|
14 |
+
self.model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/layoutlmv3-base")
|
15 |
|
16 |
def extract_text(self, pdf_path):
|
17 |
+
images = convert_from_path(pdf_path)
|
18 |
+
text_pages = []
|
19 |
+
for image in images:
|
20 |
+
inputs = self.processor(images=image, return_tensors="pt")
|
21 |
+
outputs = self.model.generate(**inputs)
|
22 |
+
text = self.processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
23 |
+
text_pages.append(text)
|
24 |
+
return text_pages
|
|
|
|
|
|
|
25 |
|
|
|
26 |
ocr_tool = LayoutLMv3OCR()
|
27 |
|
28 |
+
def process_pdf_and_query(pdf_path, question):
|
29 |
+
loader = PyPDFLoader(pdf_path)
|
30 |
+
documents = loader.load()
|
31 |
+
|
32 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
33 |
+
vectordb = Chroma.from_documents(documents, embeddings)
|
34 |
+
|
35 |
+
retriever = vectordb.as_retriever()
|
36 |
+
prompt_template = "Beantworte die folgende Frage basierend auf dem Dokument: {context}\nFrage: {question}\nAntwort:"
|
37 |
+
prompt = PromptTemplate(input_variables=["context", "question"], template=prompt_template)
|
38 |
|
39 |
+
qa_chain = RetrievalQA.from_chain_type(llm=None, retriever=retriever, chain_type_kwargs={"prompt": prompt})
|
40 |
+
response = qa_chain.run(input_documents=documents, question=question)
|
41 |
+
return response
|
|
|
42 |
|
43 |
+
def chatbot_response(pdf, question):
|
44 |
+
pdf_path = "uploaded_pdf.pdf"
|
45 |
+
pdf.save(pdf_path)
|
46 |
extracted_text = ocr_tool.extract_text(pdf_path)
|
47 |
+
answer = process_pdf_and_query(pdf_path, question)
|
48 |
+
os.remove(pdf_path)
|
49 |
+
return answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
+
pdf_input = gr.inputs.File(label="PDF-Datei hochladen")
|
52 |
+
question_input = gr.inputs.Textbox(label="Frage eingeben")
|
53 |
+
response_output = gr.outputs.Textbox(label="Antwort")
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
interface = gr.Interface(
|
56 |
+
fn=chatbot_response,
|
57 |
+
inputs=[pdf_input, question_input],
|
58 |
+
outputs=response_output,
|
59 |
+
title="RAG Chatbot mit PDF-Unterstützung",
|
60 |
+
description="Lade eine PDF-Datei hoch und stelle Fragen zu ihrem Inhalt."
|
61 |
+
)
|
|
|
|
|
|
|
|
|
62 |
|
63 |
if __name__ == "__main__":
|
|
|
64 |
interface.launch()
|