Spaces:
Sleeping
Sleeping
File size: 2,463 Bytes
fbe3ac4 03a5db9 c106446 692eafb fbe3ac4 6378bf1 b2bbc8f 03a5db9 6378bf1 bd2041d 03a5db9 fbe3ac4 03a5db9 fbe3ac4 6378bf1 bd2041d 03a5db9 692eafb c106446 03a5db9 24d5864 b62f55c 03a5db9 ee9ba92 24d5864 692eafb ee9ba92 692eafb ee9ba92 03a5db9 fbe3ac4 ee9ba92 fbe3ac4 ee9ba92 fbe3ac4 692eafb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
import gradio as gr
import pdfplumber
import os
from langchain.vectorstores import Chroma
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
def extract_text_from_pdf(pdf_path):
# Verwende pdfplumber, um den Text aus der PDF zu extrahieren
with pdfplumber.open(pdf_path) as pdf:
full_text = ""
for page in pdf.pages:
full_text += page.extract_text()
return full_text
def process_pdf_and_query(pdf_path, question):
text = extract_text_from_pdf(pdf_path)
# Extrahiere die Dokumente und erstelle einen Vektorstore
documents = [{"text": text}]
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
vectordb = Chroma.from_documents(documents, embeddings)
retriever = vectordb.as_retriever()
prompt_template = "Beantworte die folgende Frage basierend auf dem Dokument: {context}\nFrage: {question}\nAntwort:"
prompt = PromptTemplate(input_variables=["context", "question"], template=prompt_template)
qa_chain = RetrievalQA.from_chain_type(llm=None, retriever=retriever, chain_type_kwargs={"prompt": prompt})
response = qa_chain.run(input_documents=documents, question=question)
return response
def chatbot_response(pdf, question):
# Gradio gibt uns die PDF als NamedString, wir extrahieren den Inhalt als Byte-Stream
pdf_path = "/tmp/uploaded_pdf.pdf"
# Extrahiere den Inhalt der Datei als Bytes
pdf_content = pdf.read() # Hier holen wir den Inhalt der PDF als Byte-Stream
# Speichern des Byte-Streams von der Datei
with open(pdf_path, "wb") as f:
f.write(pdf_content)
# Frage beantworten basierend auf der PDF und extrahiertem Text
answer = process_pdf_and_query(pdf_path, question)
# Temporäre Datei löschen
os.remove(pdf_path)
return answer
# Gradio Interface
pdf_input = gr.File(label="PDF-Datei hochladen")
question_input = gr.Textbox(label="Frage eingeben")
response_output = gr.Textbox(label="Antwort")
interface = gr.Interface(
fn=chatbot_response,
inputs=[pdf_input, question_input],
outputs=response_output,
title="RAG Chatbot mit PDF-Unterstützung",
description="Lade eine PDF-Datei hoch und stelle Fragen zu ihrem Inhalt."
)
if __name__ == "__main__":
interface.launch()
|