Spaces:
Sleeping
Sleeping
File size: 2,394 Bytes
fbe3ac4 c106446 42c84c3 fbe3ac4 42c84c3 6378bf1 bd2041d 42c84c3 fbe3ac4 42c84c3 fbe3ac4 42c84c3 fbe3ac4 42c84c3 6378bf1 bd2041d 03a5db9 692eafb c106446 42c84c3 03a5db9 24d5864 42c84c3 03a5db9 42c84c3 24d5864 692eafb ee9ba92 42c84c3 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 |
import gradio as gr
import os
from langchain.vectorstores import Chroma # Verwenden des normalen Chroma Moduls
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate
from pdfplumber import open as open_pdf # Verwenden von pdfplumber zum Extrahieren von Text aus PDFs
def process_pdf_and_query(pdf_path, question):
# Lade die PDF und extrahiere den Text
with open_pdf(pdf_path) as pdf:
text = ""
for page in pdf.pages:
text += page.extract_text()
# Text als Dokumente in den Chroma Vektor-Datenbank laden
documents = [{"content": text, "metadata": {"source": pdf_path}}]
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 dem Text der PDF
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()
|