File size: 2,008 Bytes
b6d7881
2f0e211
 
3e93b01
39fc553
 
b13b769
2f0e211
b13b769
 
e455307
26a8953
2f0e211
26a8953
 
f421284
 
d8804c0
26a8953
 
a41389e
f421284
4dcf9b3
f421284
2f0e211
26a8953
39fc553
 
 
 
b13b769
39fc553
 
 
8d1c8be
 
f421284
cfc65ef
26a8953
 
 
 
f421284
b13b769
 
 
 
f421284
 
b13b769
 
f421284
 
b13b769
 
32c2f3c
f421284
 
b13b769
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
import os
import gradio as gr
from langchain.document_loaders import OnlinePDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.chat_models import ChatAnthropic
from langchain.prompts import ChatPromptTemplate
from transformers import pipeline

# Fetch API key from environment variables
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")

pdf_content = ""

def load_pdf(pdf_doc):
    global pdf_content
    if pdf_doc is None:
        return "No PDF uploaded.", ""
    try:
        loader = OnlinePDFLoader(pdf_doc.name)
        documents = loader.load()
        pdf_content = ' '.join(documents)
        return "PDF Loaded Successfully.", pdf_content
    except Exception as e:
        return f"Error processing PDF: {e}", ""

def chat_with_pdf(question):
    model = ChatAnthropic()
    prompt = ChatPromptTemplate.from_messages([
        ("human", pdf_content),
        ("human", question),
        ("human", "Give a clear summary of this pdf information at an 8th grade reading level.")
    ])
    chain = prompt | model
    response = chain.invoke({})
    summarizer = pipeline("summarization")
    summary = summarizer(pdf_content, max_length=1000, min_length=30, do_sample=False)[0]['summary_text']
    return summary, response.content

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.components.File(label="Load a pdf", file_types=['.pdf'], type="file"),
        gr.components.Textbox(label="Ask a question about the PDF")
    ],
    outputs=[
        gr.components.Textbox(label="Summary"),
        gr.components.Textbox(label="Chat Response")
    ],
    live=True,
    title=os.getenv("ANTHROPIC_API_KEY")+"Chat with PDF content using Anthropic",
    description="Upload a .PDF and interactively chat about its content.",
    api_name='chat_with_pdf_3'  # Changing api_name to avoid conflicts
).launch()