File size: 2,579 Bytes
d68acf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import os
import gradio as gr
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import Chroma
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings, OllamaLLM

# -------------------------
# 1. LOAD MULTIPLE PDFs
# -------------------------

def load_documents(folder_path="documents"):
    documents = []
    for file in os.listdir(folder_path):
        if file.endswith(".pdf"):
            loader = PyPDFLoader(os.path.join(folder_path, file))
            docs = loader.load()
            for doc in docs:
                doc.metadata["source"] = file
            documents.extend(docs)
    return documents

# -------------------------
# 2. BUILD VECTOR DATABASE
# -------------------------

documents = load_documents("documents")

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200
)

docs = text_splitter.split_documents(documents)

embeddings = OllamaEmbeddings(model="mistral")
db = Chroma.from_documents(docs, embeddings)

llm = OllamaLLM(model="mistral")

# -------------------------
# 3. CHAT MEMORY
# -------------------------

chat_history = []

# -------------------------
# 4. QUESTION FUNCTION
# -------------------------

def ask_pdf(question):

    global chat_history

    retrieved_docs = db.similarity_search(question, k=3)

    context = "\n\n".join(
        [doc.page_content for doc in retrieved_docs]
    )

    sources = list(set([doc.metadata["source"] for doc in retrieved_docs]))

    # Guardrail: if no context found
    if not context.strip():
        return "I don't have enough information from the documents to answer this."

    prompt = f"""

You are a helpful assistant.

Answer ONLY from the provided context.

If the answer is not in the context, say:

"I don't have enough information from the documents."



Chat history:

{chat_history}



Context:

{context}



Question:

{question}



Answer:

"""

    answer = llm.invoke(prompt)

    chat_history.append({"question": question, "answer": answer})

    citation_text = "\n\nSources: " + ", ".join(sources)

    return answer + citation_text


# -------------------------
# 5. GRADIO UI
# -------------------------

interface = gr.Interface(
    fn=ask_pdf,
    inputs="text",
    outputs="text",
    title="Advanced Ask My PDF Bot",
    description="Chat with multiple PDFs. Shows sources. Has memory. Guardrails enabled."
)

interface.launch()