File size: 7,391 Bytes
363451a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdf8b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc68d24
 
c06fde8
 
 
dc68d24
 
 
 
 
c06fde8
 
dc68d24
c06fde8
dc68d24
 
c06fde8
dc68d24
 
 
 
 
 
 
c06fde8
 
 
 
 
 
 
dc68d24
c06fde8
dc68d24
bdf8b5c
 
c06fde8
 
 
 
 
 
bdf8b5c
c06fde8
 
bdf8b5c
c06fde8
bdf8b5c
dc68d24
bdf8b5c
 
dc68d24
c06fde8
 
bdf8b5c
 
 
 
363451a
fb9e172
c06fde8
363451a
 
 
 
 
bdf8b5c
 
c06fde8
fb9e172
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# import os
# import gradio as gr
# from langchain_community.vectorstores import FAISS
# from langchain_community.embeddings import HuggingFaceEmbeddings
# from langchain_community.document_loaders import PyPDFLoader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.chains import ConversationalRetrievalChain
# from langchain.memory import ConversationBufferMemory
# from langchain_huggingface import HuggingFaceEndpoint

# # Set token for Hugging Face Inference API
# os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv("HUGGINGFACEHUB_API_TOKEN")

# # Load embedding model
# embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# # Initialize LLM
# llm = HuggingFaceEndpoint(
#     repo_id="mistralai/Mistral-7B-Instruct-v0.3",
#     task="text-generation",
#     max_new_tokens=128,
#     temperature=0.5,
# )

# # Memory for conversation context
# memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# # Shared state
# qa_chain = None

# # Step 1: Upload + Process PDF
# def process_pdf(pdf_file):
#     global qa_chain
#     loader = PyPDFLoader(pdf_file.name)
#     pages = loader.load()

#     splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
#     chunks = splitter.split_documents(pages)

#     vectordb = FAISS.from_documents(chunks, embeddings)

#     qa_chain = ConversationalRetrievalChain.from_llm(
#         llm=llm,
#         retriever=vectordb.as_retriever(),
#         memory=memory
#     )

#     return "PDF processed! You can now ask questions."

# # Step 2: Chatbot logic
# def chat_fn(message, history=[]):
#     if qa_chain is None:
#         return history + [[message, "⚠️ Please upload a PDF first."]], history
#     answer = qa_chain.run(message)
#     history.append((message, answer))
#     return history, history

# # Gradio UI
# with gr.Blocks() as demo:
#     gr.Markdown("## πŸ“„ Chat with PDF using Mistral 7B + LangChain")
#     upload = gr.File(label="Upload a PDF", type="filepath")
#     status = gr.Textbox(label="Status", interactive=False)
#     upload.change(fn=process_pdf, inputs=upload, outputs=status)
#     gr.ChatInterface(chat_fn)

# demo.launch()


# import os
# import gradio as gr
# from langchain_community.vectorstores import FAISS
# from langchain_community.embeddings import HuggingFaceEmbeddings
# from langchain_community.document_loaders import PyPDFLoader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.chains import ConversationalRetrievalChain
# from langchain.memory import ConversationBufferMemory
# from langchain_huggingface import HuggingFaceEndpoint

# # Set token for Hugging Face Inference API
# os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv("HUGGINGFACEHUB_API_TOKEN")

# # Load embedding model
# embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# # Initialize LLM
# llm = HuggingFaceEndpoint(
#     repo_id="mistralai/Mistral-7B-Instruct-v0.3",
#     task="text-generation",
#     max_new_tokens=128,
#     temperature=0.5,
# )

# # Memory for conversation context
# memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

# # Shared state
# qa_chain = None

# # Step 1: Upload + Process PDF
# def process_pdf(pdf_file):
#     global qa_chain
#     loader = PyPDFLoader(pdf_file.name)
#     pages = loader.load()

#     splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
#     chunks = splitter.split_documents(pages)

#     vectordb = FAISS.from_documents(chunks, embeddings)

#     qa_chain = ConversationalRetrievalChain.from_llm(
#         llm=llm,
#         retriever=vectordb.as_retriever(),
#         memory=memory
#     )

#     return "βœ… PDF processed! You can now chat.", gr.update(interactive=True), gr.update(interactive=True)

# # Step 2: Chatbot logic
# def chat_fn(message, history=[]):
#     if qa_chain is None:
#         return history + [[message, "⚠️ Please upload a PDF first."]], history
#     answer = qa_chain.run(message)
#     history.append((message, answer))
#     return history, history

# # Gradio UI
# with gr.Blocks() as demo:
#     gr.Markdown("## πŸ“„ Chat with PDF using Mistral 7B + LangChain")

#     upload = gr.File(label="Upload a PDF", file_types=[".pdf"])
#     status = gr.Textbox(label="Status", interactive=False)

#     chatbot = gr.Chatbot(label="Chat")
#     message = gr.Textbox(label="Ask a question", placeholder="Type your question...", interactive=False)
#     send_btn = gr.Button("Send", interactive=False)

#     upload.change(fn=process_pdf, inputs=upload, outputs=[status, message, send_btn])
#     send_btn.click(fn=chat_fn, inputs=message, outputs=[chatbot, chatbot])

# demo.launch(share=True)


import os
import gradio as gr
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain_huggingface import HuggingFaceEndpoint

# Set token for Hugging Face Inference API
os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.getenv("HUGGINGFACEHUB_API_TOKEN")

# Load embedding model
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# Initialize LLM
llm = HuggingFaceEndpoint(
    repo_id="mistralai/Mistral-7B-Instruct-v0.3",
    task="text-generation",
    max_new_tokens=128,
    temperature=0.5,
)

# Step 1: Upload + Process PDF
def process_pdf(pdf_file):
    loader = PyPDFLoader(pdf_file.name)
    pages = loader.load()

    splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
    chunks = splitter.split_documents(pages)

    vectordb = FAISS.from_documents(chunks, embeddings)

    memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

    qa_chain = ConversationalRetrievalChain.from_llm(
        llm=llm,
        retriever=vectordb.as_retriever(),
        memory=memory
    )

    return qa_chain, "βœ… PDF processed! You can now chat.", gr.update(interactive=True), gr.update(interactive=True)

# Step 2: Chatbot logic
def chat_fn(message, chat_history, qa_chain):
    if qa_chain is None:
        return chat_history + [[message, "⚠️ Please upload a PDF first."]], chat_history, qa_chain
    answer = qa_chain.run(message)
    chat_history.append((message, answer))
    return chat_history, chat_history, qa_chain

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("## πŸ“„ Chat with any PDF using Mistral 7B + LangChain")

    qa_chain_state = gr.State(None)
    chat_state = gr.State([])

    upload = gr.File(label="Upload a PDF", file_types=[".pdf"])
    status = gr.Textbox(label="Status", interactive=False)

    chatbot = gr.Chatbot(label="Chat")
    message = gr.Textbox(label="Ask a question", placeholder="Type your question...", interactive=False)
    send_btn = gr.Button("Send", interactive=False)

    upload.change(fn=process_pdf, inputs=upload, outputs=[qa_chain_state, status, message, send_btn])
    send_btn.click(fn=chat_fn, inputs=[message, chat_state, qa_chain_state], outputs=[chatbot, chat_state, qa_chain_state])

demo.launch(share=True)