Ryu-m0m commited on
Commit
9b0079f
1 Parent(s): bcee93f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -0
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install necessary packages
2
+ #!pip install streamlit
3
+ #!pip install wikipedia
4
+ #!pip install langchain_community
5
+ #!pip install sentence-transformers
6
+ #!pip install chromadb
7
+ #!pip install huggingface_hub
8
+ #!pip install transformers
9
+
10
+ import streamlit as st
11
+ from langchain_community.document_loaders import PyPDFLoader
12
+ from langchain.text_splitter import RecursiveCharacterTextSplitter, SentenceTransformersTokenTextSplitter
13
+ import chromadb
14
+ from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
15
+ from huggingface_hub import login, InferenceClient
16
+ from sentence_transformers import CrossEncoder
17
+ import numpy as np
18
+ import random
19
+ import string
20
+ import os
21
+
22
+ # User variables
23
+ uploaded_file = st.sidebar.file_uploader("Upload your PDF", type="pdf")
24
+ model_name = 'mistralai/Mistral-7B-Instruct-v0.3'
25
+ HF_TOKEN = st.sidebar.text_input("Enter your Hugging Face token:", "", type="password")
26
+
27
+
28
+ # Initialize session state for error message
29
+ if 'error_message' not in st.session_state:
30
+ st.session_state.error_message = ""
31
+
32
+ # Function to validate token
33
+ def validate_token(token):
34
+ try:
35
+ # Attempt to log in with the provided token
36
+ login(token=token)
37
+ # Check if the token is valid by trying to access some data
38
+ HfApi().whoami()
39
+ return True
40
+ except Exception as e:
41
+ return False
42
+
43
+ # Validate the token and display appropriate message
44
+ if HF_TOKEN:
45
+ if validate_token(HF_TOKEN):
46
+ st.session_state.error_message = "" # Clear error message if the token is valid
47
+ st.sidebar.success("Token is valid!")
48
+ else:
49
+ st.session_state.error_message = "Invalid token. Please try again."
50
+ st.sidebar.error(st.session_state.error_message)
51
+ elif st.session_state.error_message:
52
+ st.sidebar.error(st.session_state.error_message)
53
+
54
+ if uploaded_file:
55
+ # Save the uploaded file temporarily
56
+ temp_file_path = os.path.join("/tmp", uploaded_file.name)
57
+ with open(temp_file_path, "wb") as f:
58
+ f.write(uploaded_file.getbuffer())
59
+
60
+ # Load the PDF using PyPDFLoader
61
+ docs = PyPDFLoader(temp_file_path).load()
62
+
63
+ # Clean up the temporary file after loading
64
+ os.remove(temp_file_path)
65
+ else:
66
+ st.warning("Please upload a PDF file.")
67
+
68
+
69
+ # Memory for chat history
70
+ if "history" not in st.session_state:
71
+ st.session_state.history = []
72
+
73
+ # Function to generate a random string for collection name
74
+ def generate_random_string(max_length=60):
75
+ if max_length > 60:
76
+ raise ValueError("The maximum length cannot exceed 60 characters.")
77
+ length = random.randint(1, max_length)
78
+ characters = string.ascii_letters + string.digits
79
+ return ''.join(random.choice(characters) for _ in range(length))
80
+
81
+ collection_name = generate_random_string()
82
+
83
+ # Function for query expansion
84
+ def augment_multiple_query(query):
85
+ client = InferenceClient(model_name, token=HF_TOKEN)
86
+ content = client.chat_completion(
87
+ messages=[
88
+ {
89
+ "role": "system",
90
+ "content": f"""You are a helpful assistant.
91
+ Suggest up to five additional related questions to help them find the information they need for the provided question.
92
+ Suggest only short questions without compound sentences. Suggest a variety of questions that cover different aspects of the topic.
93
+ Make sure they are complete questions, and that they are related to the original question."""
94
+ },
95
+ {
96
+ "role": "user",
97
+ "content": query
98
+ }
99
+ ],
100
+ max_tokens=500,
101
+ )
102
+ return content.choices[0].message.content.split("\n")
103
+
104
+ # Function to handle RAG-based question answering
105
+ def rag_advanced(user_query):
106
+
107
+
108
+ # Text Splitting
109
+ character_splitter = RecursiveCharacterTextSplitter(separators=["\n\n", "\n", ". ", " ", ""], chunk_size=1000, chunk_overlap=0)
110
+ concat_texts = "".join([doc.page_content for doc in docs])
111
+ character_split_texts = character_splitter.split_text(concat_texts)
112
+
113
+ token_splitter = SentenceTransformersTokenTextSplitter(chunk_overlap=0, tokens_per_chunk=256)
114
+ token_split_texts = [text for text in character_split_texts for text in token_splitter.split_text(text)]
115
+
116
+ # Embedding and Document Storage
117
+ embedding_function = SentenceTransformerEmbeddingFunction()
118
+ chroma_client = chromadb.Client()
119
+ chroma_collection = chroma_client.create_collection(collection_name, embedding_function=embedding_function)
120
+
121
+ ids = [str(i) for i in range(len(token_split_texts))]
122
+ chroma_collection.add(ids=ids, documents=token_split_texts)
123
+
124
+ # Document Retrieval
125
+ augmented_queries = augment_multiple_query(user_query)
126
+ joint_query = [user_query] + augmented_queries
127
+
128
+ results = chroma_collection.query(query_texts=joint_query, n_results=5, include=['documents', 'embeddings'])
129
+ retrieved_documents = results['documents']
130
+
131
+ unique_documents = list(set(doc for docs in retrieved_documents for doc in docs))
132
+
133
+ # Re-Ranking
134
+ cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
135
+ pairs = [[user_query, doc] for doc in unique_documents]
136
+ scores = cross_encoder.predict(pairs)
137
+
138
+ top_indices = np.argsort(scores)[::-1][:5]
139
+ top_documents = [unique_documents[idx] for idx in top_indices]
140
+
141
+ # LLM Reference
142
+ client = InferenceClient(model_name, token=HF_TOKEN)
143
+ response = ""
144
+ for message in client.chat_completion(
145
+ messages=[
146
+ {
147
+ "role": "system",
148
+ "content": f"""You are a helpful assitant.
149
+ You will be shown the user's questions, and the relevant information from the related documents.
150
+ Answer the user's question using only this information."""
151
+ },
152
+ {
153
+ "role": "user",
154
+ "content": f"Questions: {user_query}. \n Information: {top_documents}"
155
+ }
156
+ ],
157
+ max_tokens=500,
158
+ stream=True,
159
+ ):
160
+ response += message.choices[0].delta.content
161
+
162
+ return response
163
+
164
+ # Streamlit UI
165
+ st.title("PDF RAG Chatbot")
166
+ st.markdown("Upload your PDF and enter your 🤗 token!")
167
+ st.link_button("Get Token Here", "https://huggingface.co/settings/tokens")
168
+
169
+ # Input box for the user to type their message
170
+ if uploaded_file:
171
+ user_input = st.text_input("You: ", "", placeholder="Type your question here...")
172
+ if user_input:
173
+ response = rag_advanced(user_input)
174
+ st.session_state.history.append({"user": user_input, "bot": response})
175
+
176
+ # Display the conversation history
177
+ for chat in st.session_state.history:
178
+ st.write(f"You: {chat['user']}")
179
+ st.write(f"Bot: {chat['bot']}")
180
+
181
+
182
+ st.markdown("-----------------")
183
+ st.markdown("What is this app?")
184
+ st.markdown("""This is a simple RAG application using PDF import.
185
+ The model for chat is Mistral-7B-Instruct-v0.3.
186
+ Main libraries: Langchain (text splitting), Chromadb (vector store)
187
+ This RAG uses query expansion and re-ranking to improve the quality.
188
+ Feel free to check the files or DM me for any questions. Thank you.""")