Turbiling commited on
Commit
33f5c90
Β·
verified Β·
1 Parent(s): 7c1961a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -72
app.py CHANGED
@@ -1,88 +1,64 @@
1
  import os
2
  import chainlit as cl
3
- 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
- # Helper function to process PDF
12
- def process_file(file_path):
13
- loader = PyPDFLoader(file_path)
14
- documents = loader.load()
15
-
16
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
17
- texts = text_splitter.split_documents(documents)
18
-
19
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
20
- vectorstore = FAISS.from_documents(texts, embeddings)
21
-
22
- custom_prompt_template = """
23
- 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.
24
- {context}
25
- Question: {question}
26
- Helpful Answer:
27
- """
28
- prompt = PromptTemplate(
29
- template=custom_prompt_template,
30
- input_variables=["context", "question"]
31
- )
32
 
33
- llm = HuggingFaceEndpoint(
34
- repo_id="meta-llama/Meta-Llama-3-8B-Instruct",
35
- temperature=0.5,
36
- max_new_tokens=500,
37
- top_k=50,
38
- huggingfacehub_api_token=os.environ.get("HUGGINGFACEHUB_API_TOKEN")
39
- )
 
 
 
 
40
 
41
- qa = RetrievalQA.from_chain_type(
42
- llm=llm,
 
43
  chain_type="stuff",
44
- retriever=vectorstore.as_retriever(search_kwargs={"k": 3}),
45
- chain_type_kwargs={"prompt": prompt},
46
- return_source_documents=True
47
  )
48
 
49
- return qa
 
50
 
51
- # Chat start β€” show file upload prompt
52
- @cl.on_chat_start
53
- async def start():
54
- await cl.Message("πŸ‘‹ Welcome! Please upload a PDF to get started.").send()
55
 
56
- # Ask user to upload a file
57
- await cl.AskFileMessage(
58
- content="πŸ“„ Upload a PDF file below:",
59
- accept=["application/pdf"],
60
- max_size_mb=20,
61
- timeout=180
62
- ).send()
63
 
64
- # Handle file and build QA chain
65
- @cl.on_message
66
- async def handle_message(message: cl.Message):
67
- if files := await cl.user_session.get("files"):
68
- file = files[0] # Get the first uploaded file
69
- file_path = file.path
70
-
71
- # Process and store the chain
72
- qa_chain = process_file(file_path)
73
- cl.user_session.set("qa_chain", qa_chain)
74
- cl.user_session.set("ready", True)
75
- await cl.Message(content=f"βœ… File `{file.name}` processed. Ask your question!").send()
76
- cl.user_session.set("files", None) # Clear after processing
77
- return
78
 
79
- # If file was already processed, answer question
80
- if not cl.user_session.get("ready"):
81
- await cl.Message("⚠️ Please upload a PDF file first.").send()
82
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- qa_chain = cl.user_session.get("qa_chain")
85
- response = qa_chain(message.content)
86
- answer = response["result"]
87
- await cl.Message(content=answer).send()
88
 
 
1
  import os
2
  import chainlit as cl
 
 
3
  from langchain_community.vectorstores import FAISS
4
+ from langchain_community.document_loaders import PyPDFLoader
5
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
6
+ from langchain.embeddings import HuggingFaceEmbeddings
7
  from langchain.chains import RetrievalQA
8
+ from langchain.chat_models import ChatOpenAI
9
 
10
+ # Initialize embedding model
11
+ embedding_model = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Use this variable to store retriever globally
14
+ retriever = None
15
+
16
+
17
+ @cl.on_message
18
+ async def handle_message(message: cl.Message):
19
+ global retriever
20
+
21
+ if not retriever:
22
+ await cl.Message(content="πŸ“‚ Please upload a PDF file first.").send()
23
+ return
24
 
25
+ # Setup QA chain
26
+ qa_chain = RetrievalQA.from_chain_type(
27
+ llm=ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.2),
28
  chain_type="stuff",
29
+ retriever=retriever,
30
+ return_source_documents=True,
 
31
  )
32
 
33
+ # Ask question
34
+ response = qa_chain(message.content)
35
 
36
+ # Respond in UI
37
+ await cl.Message(content=response["result"]).send()
 
 
38
 
 
 
 
 
 
 
 
39
 
40
+ @cl.on_file_upload
41
+ async def on_file_upload(files: list[cl.UploadedFile]):
42
+ global retriever
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Handle only the first file
45
+ uploaded_file = files[0]
46
+
47
+ # Save file locally
48
+ file_path = f"/tmp/{uploaded_file.name}"
49
+ with open(file_path, "wb") as f:
50
+ f.write(uploaded_file.content)
51
+
52
+ # Load and split PDF
53
+ loader = PyPDFLoader(file_path)
54
+ docs = loader.load()
55
+ splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
56
+ chunks = splitter.split_documents(docs)
57
+
58
+ # Create FAISS index
59
+ db = FAISS.from_documents(chunks, embedding_model)
60
+ retriever = db.as_retriever()
61
+
62
+ await cl.Message(content="βœ… PDF uploaded and processed! You can now ask questions.").send()
63
 
 
 
 
 
64