Ryu-m0m commited on
Commit
21990ec
1 Parent(s): a58495e

initial commit

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 WikipediaLoader
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
+
21
+ # User variables
22
+ topic = st.sidebar.text_input("Enter the Wikipedia topic:", "Wikipedia_Keyword")
23
+ query = st.sidebar.text_input("Enter your first query:", "First query")
24
+ model_name = st.sidebar.selectbox("Select model:", ["mistralai/Mistral-7B-Instruct-v0.3", "meta-llama/Meta-Llama-3.1-8B-Instruct"])
25
+ HF_TOKEN = st.sidebar.text_input("Enter your Hugging Face token:", "YOUR_HF_TOKEN", type="password")
26
+
27
+ # Hugging Face login
28
+ login(token=HF_TOKEN)
29
+
30
+ # Memory for chat history
31
+ if "history" not in st.session_state:
32
+ st.session_state.history = []
33
+
34
+ # Function to generate a random string for collection name
35
+ def generate_random_string(max_length=60):
36
+ if max_length > 60:
37
+ raise ValueError("The maximum length cannot exceed 60 characters.")
38
+ length = random.randint(1, max_length)
39
+ characters = string.ascii_letters + string.digits
40
+ return ''.join(random.choice(characters) for _ in range(length))
41
+
42
+ collection_name = generate_random_string()
43
+
44
+ # Function for query expansion
45
+ def augment_multiple_query(query):
46
+ client = InferenceClient(model_name, token=HF_TOKEN)
47
+ content = client.chat_completion(
48
+ messages=[
49
+ {
50
+ "role": "system",
51
+ "content": f"""You are a helpful expert in {topic}. Your users are asking questions about {topic}.
52
+ Suggest up to five additional related questions to help them find the information they need for the provided question.
53
+ Suggest only short questions without compound sentences. Suggest a variety of questions that cover different aspects of the topic.
54
+ Make sure they are complete questions, and that they are related to the original question."""
55
+ },
56
+ {
57
+ "role": "user",
58
+ "content": query
59
+ }
60
+ ],
61
+ max_tokens=500,
62
+ )
63
+ return content.choices[0].message.content.split("\n")
64
+
65
+ # Custom function to handle fuzzy keyword searches
66
+ def load_wikipedia_page(topic):
67
+ try:
68
+ # Attempt to load the page directly
69
+ page = wikipedia.page(topic)
70
+ return page.content
71
+
72
+ except wikipedia.exceptions.DisambiguationError as e:
73
+ # Handle disambiguation page case
74
+ st.write(f"The keyword '{topic}' returned multiple possible pages.")
75
+ st.write("Please refine your search or select one of the following options:")
76
+
77
+ # List disambiguation options
78
+ options = e.options
79
+ selected_option = st.selectbox("Select the closest match:", options)
80
+
81
+ # Load the selected option
82
+ page = wikipedia.page(selected_option)
83
+ return page.content
84
+
85
+ except wikipedia.exceptions.PageError:
86
+ # Handle the case where no page is found
87
+ st.write(f"No page found for '{topic}'. Please try a different keyword.")
88
+ return None
89
+
90
+ # Function to handle RAG-based question answering
91
+ def rag_advanced(user_query):
92
+ # Document Loading
93
+ docs_content = load_wikipedia_page(topic)
94
+ if docs_content:
95
+ docs = [docs_content] # Wrap the content in a list for consistency
96
+
97
+ # Text Splitting
98
+ character_splitter = RecursiveCharacterTextSplitter(separators=["\n\n", "\n", ". ", " ", ""], chunk_size=1000, chunk_overlap=0)
99
+ concat_texts = "".join([doc.page_content for doc in docs])
100
+ character_split_texts = character_splitter.split_text(concat_texts)
101
+
102
+ token_splitter = SentenceTransformersTokenTextSplitter(chunk_overlap=0, tokens_per_chunk=256)
103
+ token_split_texts = [text for text in character_split_texts for text in token_splitter.split_text(text)]
104
+
105
+ # Embedding and Document Storage
106
+ embedding_function = SentenceTransformerEmbeddingFunction()
107
+ chroma_client = chromadb.Client()
108
+ chroma_collection = chroma_client.create_collection(collection_name, embedding_function=embedding_function)
109
+
110
+ ids = [str(i) for i in range(len(token_split_texts))]
111
+ chroma_collection.add(ids=ids, documents=token_split_texts)
112
+
113
+ # Document Retrieval
114
+ augmented_queries = augment_multiple_query(user_query)
115
+ joint_query = [user_query] + augmented_queries
116
+
117
+ results = chroma_collection.query(query_texts=joint_query, n_results=5, include=['documents', 'embeddings'])
118
+ retrieved_documents = results['documents']
119
+
120
+ unique_documents = list(set(doc for docs in retrieved_documents for doc in docs))
121
+
122
+ # Re-Ranking
123
+ cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
124
+ pairs = [[user_query, doc] for doc in unique_documents]
125
+ scores = cross_encoder.predict(pairs)
126
+
127
+ top_indices = np.argsort(scores)[::-1][:5]
128
+ top_documents = [unique_documents[idx] for idx in top_indices]
129
+
130
+ # LLM Reference
131
+ client = InferenceClient(model_name, token=HF_TOKEN)
132
+ response = ""
133
+ for message in client.chat_completion(
134
+ messages=[
135
+ {
136
+ "role": "system",
137
+ "content": f"""You are a helpful expert in {topic}. Your users are asking questions about {topic}.
138
+ You will be shown the user's questions, and the relevant information from the documents related to {topic}.
139
+ Answer the user's question using only this information."""
140
+ },
141
+ {
142
+ "role": "user",
143
+ "content": f"Questions: {user_query}. \n Information: {top_documents}"
144
+ }
145
+ ],
146
+ max_tokens=500,
147
+ stream=True,
148
+ ):
149
+ response += message.choices[0].delta.content
150
+
151
+ return response
152
+
153
+ # Streamlit UI
154
+ st.title("Wikipedia RAG Chatbot")
155
+
156
+ # Input box for the user to type their message
157
+ user_input = st.text_input("You: ", "")
158
+
159
+ # Generate response and update conversation history
160
+ if user_input:
161
+ response = rag_advanced(user_input)
162
+ st.session_state.history.append({"user": user_input, "bot": response})
163
+
164
+ # Display the conversation history
165
+ for chat in st.session_state.history:
166
+ st.write(f"You: {chat['user']}")
167
+ st.write(f"Bot: {chat['bot']}")