File size: 1,708 Bytes
2f0e211 3e93b01 26a8953 2f0e211 26a8953 e455307 26a8953 d05ba12 26a8953 2f0e211 26a8953 d8804c0 26a8953 cfc65ef 26a8953 d8804c0 26a8953 a08bac4 4dcf9b3 26a8953 2f0e211 26a8953 cfc65ef 26a8953 |
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 |
import gradio as gr
import os
from langchain.document_loaders import OnlinePDFLoader
from langchain.text_splitter import CharacterTextSplitter
from anthropic import LanguageModel
# Set API keys from environment variables
os.environ['ANTHROPIC_API_KEY'] = os.getenv("Your_Anthropic_API_Key")
# Initialize the Anthropic model
anthropic_model = LanguageModel(api_key=os.environ['ANTHROPIC_API_KEY'], model="some_model")
pdf_content = ""
def load_pdf(pdf_doc):
global pdf_content
try:
if pdf_doc is None:
return "No PDF uploaded."
# Load and split PDF content
loader = OnlinePDFLoader(pdf_doc.name)
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
pdf_content = ' '.join(text_splitter.split_documents(documents))
return "PDF Loaded Successfully."
except Exception as e:
return f"Error processing PDF: {e}"
def chat_with_pdf(question):
context = [{"role": "system", "content": pdf_content}]
response = anthropic_model.query(question, context=context)
return response['answer']
# Define Gradio UI
def gradio_interface(pdf_doc, question):
if not pdf_content:
return load_pdf(pdf_doc)
else:
return chat_with_pdf(question)
gr.Interface(fn=gradio_interface,
inputs=[gr.File(label="Load a pdf", file_types=['.pdf'], type="file"),
gr.Textbox(label="Ask a question about the PDF")],
outputs="text",
live=True,
title="Chat with PDF content using Anthropic",
description="Upload a .PDF and interactively chat about its content."
).launch()
|