Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,76 +4,81 @@ from langchain_community.document_loaders import PyPDFLoader
|
|
| 4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
|
|
|
| 7 |
from langchain.prompts import PromptTemplate
|
| 8 |
-
from langchain_community.llms import HuggingFaceEndpoint
|
| 9 |
from langchain.chains import RetrievalQA
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@cl.on_chat_start
|
| 12 |
async def start():
|
| 13 |
-
await cl.Message("π Welcome!
|
| 14 |
|
| 15 |
await cl.AskFileMessage(
|
| 16 |
-
content="π Upload a PDF file below:",
|
| 17 |
accept=["application/pdf"],
|
| 18 |
max_size_mb=20,
|
| 19 |
timeout=180
|
| 20 |
).send()
|
| 21 |
|
|
|
|
| 22 |
@cl.on_message
|
| 23 |
async def handle_message(message: cl.Message):
|
| 24 |
if files := await cl.user_session.get("files"):
|
| 25 |
file = files[0]
|
| 26 |
file_path = file.path
|
| 27 |
-
await cl.Message(f"π Received file: {file.name}").send()
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
await cl.Message("π PDF loaded successfully. Splitting text...").send()
|
| 31 |
-
loader = PyPDFLoader(file_path)
|
| 32 |
-
documents = loader.load()
|
| 33 |
-
|
| 34 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 35 |
-
texts = text_splitter.split_documents(documents)
|
| 36 |
-
|
| 37 |
-
await cl.Message("π Creating embeddings and FAISS vector store...").send()
|
| 38 |
-
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 39 |
-
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 40 |
-
|
| 41 |
-
await cl.Message("βοΈ Building RetrievalQA chain...").send()
|
| 42 |
-
custom_prompt_template = """
|
| 43 |
-
Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know.
|
| 44 |
-
{context}
|
| 45 |
-
Question: {question}
|
| 46 |
-
Helpful Answer:
|
| 47 |
-
"""
|
| 48 |
-
prompt = PromptTemplate(
|
| 49 |
-
template=custom_prompt_template,
|
| 50 |
-
input_variables=["context", "question"]
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
llm = HuggingFaceEndpoint(
|
| 54 |
-
repo_id="meta-llama/Meta-Llama-3-8B-Instruct",
|
| 55 |
-
temperature=0.5,
|
| 56 |
-
max_new_tokens=500,
|
| 57 |
-
top_k=50,
|
| 58 |
-
huggingfacehub_api_token=os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
qa = RetrievalQA.from_chain_type(
|
| 62 |
-
llm=llm,
|
| 63 |
-
chain_type="stuff",
|
| 64 |
-
retriever=vectorstore.as_retriever(search_kwargs={"k": 3}),
|
| 65 |
-
chain_type_kwargs={"prompt": prompt},
|
| 66 |
-
return_source_documents=True
|
| 67 |
-
)
|
| 68 |
-
|
| 69 |
-
cl.user_session.set("qa_chain", qa)
|
| 70 |
-
cl.user_session.set("ready", True)
|
| 71 |
-
await cl.Message("β
QA chain is ready. You can ask your question now.").send()
|
| 72 |
-
cl.user_session.set("files", None)
|
| 73 |
-
|
| 74 |
-
except Exception as e:
|
| 75 |
-
await cl.Message(f"β Error during processing: {str(e)}").send()
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
return
|
| 78 |
|
| 79 |
if not cl.user_session.get("ready"):
|
|
@@ -82,9 +87,7 @@ async def handle_message(message: cl.Message):
|
|
| 82 |
|
| 83 |
qa_chain = cl.user_session.get("qa_chain")
|
| 84 |
await cl.Message("π¬ Thinking...").send()
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
except Exception as e:
|
| 90 |
-
await cl.Message(f"β Error during QA: {str(e)}").send()
|
|
|
|
| 4 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
from langchain_community.vectorstores import FAISS
|
| 6 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 7 |
+
from langchain_community.chat_models import ChatGroq
|
| 8 |
from langchain.prompts import PromptTemplate
|
|
|
|
| 9 |
from langchain.chains import RetrievalQA
|
| 10 |
|
| 11 |
+
# PDF to QA chain processor
|
| 12 |
+
def process_file(file_path):
|
| 13 |
+
loader = PyPDFLoader(file_path)
|
| 14 |
+
documents = loader.load()
|
| 15 |
+
cl.run_sync(cl.Message("π PDF loaded successfully. Splitting text...").send())
|
| 16 |
+
|
| 17 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 18 |
+
texts = text_splitter.split_documents(documents)
|
| 19 |
+
|
| 20 |
+
cl.run_sync(cl.Message("π Creating embeddings and FAISS vector store...").send())
|
| 21 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 22 |
+
vectorstore = FAISS.from_documents(texts, embeddings)
|
| 23 |
+
|
| 24 |
+
cl.run_sync(cl.Message("βοΈ Building RetrievalQA chain...").send())
|
| 25 |
+
|
| 26 |
+
prompt_template = """
|
| 27 |
+
Use the following pieces of context to answer the question at the end.
|
| 28 |
+
If you don't know the answer, just say you don't know β don't try to make up an answer.
|
| 29 |
+
|
| 30 |
+
{context}
|
| 31 |
+
|
| 32 |
+
Question: {question}
|
| 33 |
+
Helpful Answer:
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
prompt = PromptTemplate(
|
| 37 |
+
template=prompt_template,
|
| 38 |
+
input_variables=["context", "question"]
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
llm = ChatGroq(
|
| 42 |
+
api_key=os.environ.get("GROQ_API_KEY"),
|
| 43 |
+
model_name="llama3-8b-8192"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 47 |
+
llm=llm,
|
| 48 |
+
chain_type="stuff",
|
| 49 |
+
retriever=vectorstore.as_retriever(search_kwargs={"k": 3}),
|
| 50 |
+
chain_type_kwargs={"prompt": prompt},
|
| 51 |
+
return_source_documents=True
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
return qa_chain
|
| 55 |
+
|
| 56 |
+
# On Chat Start
|
| 57 |
@cl.on_chat_start
|
| 58 |
async def start():
|
| 59 |
+
await cl.Message("π Welcome! Upload a PDF to begin.").send()
|
| 60 |
|
| 61 |
await cl.AskFileMessage(
|
| 62 |
+
content="π Upload a PDF file below (Max 20 MB):",
|
| 63 |
accept=["application/pdf"],
|
| 64 |
max_size_mb=20,
|
| 65 |
timeout=180
|
| 66 |
).send()
|
| 67 |
|
| 68 |
+
# On User Message
|
| 69 |
@cl.on_message
|
| 70 |
async def handle_message(message: cl.Message):
|
| 71 |
if files := await cl.user_session.get("files"):
|
| 72 |
file = files[0]
|
| 73 |
file_path = file.path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
# Build RAG pipeline
|
| 76 |
+
qa_chain = await cl.make_async(process_file)(file_path)
|
| 77 |
+
cl.user_session.set("qa_chain", qa_chain)
|
| 78 |
+
cl.user_session.set("ready", True)
|
| 79 |
+
|
| 80 |
+
await cl.Message(f"β
File `{file.name}` processed. QA chain is ready. You can now ask your question!").send()
|
| 81 |
+
cl.user_session.set("files", None)
|
| 82 |
return
|
| 83 |
|
| 84 |
if not cl.user_session.get("ready"):
|
|
|
|
| 87 |
|
| 88 |
qa_chain = cl.user_session.get("qa_chain")
|
| 89 |
await cl.Message("π¬ Thinking...").send()
|
| 90 |
+
|
| 91 |
+
response = qa_chain(message.content)
|
| 92 |
+
answer = response["result"]
|
| 93 |
+
await cl.Message(content=f"π§ Answer: {answer}").send()
|
|
|
|
|
|