Spaces:
Running
Running
Daniel Foley
commited on
Commit
Β·
364893a
1
Parent(s):
a9e136f
Forgot to include everyone on last commit + old scripts
Browse filesCo-authored By: Daniel dfoley3838@gmail.com
Co-authored By: Brandon bmv2021@bu.edu
Co-authored By: Enrico enricoll@bu.edu
Co-authored By: Jinanshi jinanshi@bu.edu
- old_scripts/app.py +213 -0
- old_scripts/app1.1.py +85 -0
- old_scripts/bpl_scraper.py +177 -0
- old_scripts/faiss_migrate.ipynb +179 -0
- old_scripts/new_streamlit.app +152 -0
- old_scripts/new_streamlit.py +188 -0
- old_scripts/streamlit-rag-app.py +185 -0
- old_scripts/test_streamlit.py +15 -0
old_scripts/app.py
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
from typing import List
|
4 |
+
|
5 |
+
|
6 |
+
|
7 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
8 |
+
|
9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
10 |
+
|
11 |
+
from langchain.vectorstores import Chroma
|
12 |
+
|
13 |
+
from langchain.chains import (
|
14 |
+
|
15 |
+
ConversationalRetrievalChain,
|
16 |
+
|
17 |
+
)
|
18 |
+
|
19 |
+
from langchain.chat_models import ChatOpenAI
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
from langchain.docstore.document import Document
|
24 |
+
|
25 |
+
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
import chainlit as cl
|
30 |
+
|
31 |
+
|
32 |
+
|
33 |
+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
@cl.on_chat_start
|
44 |
+
|
45 |
+
async def on_chat_start():
|
46 |
+
|
47 |
+
files = None
|
48 |
+
|
49 |
+
|
50 |
+
|
51 |
+
# Wait for the user to upload a file
|
52 |
+
|
53 |
+
while files == None:
|
54 |
+
|
55 |
+
files = await cl.AskFileMessage(
|
56 |
+
|
57 |
+
content="Please upload a text file to begin!",
|
58 |
+
|
59 |
+
accept=["text/plain"],
|
60 |
+
|
61 |
+
max_size_mb=20,
|
62 |
+
|
63 |
+
timeout=180,
|
64 |
+
|
65 |
+
).send()
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
file = files[0]
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
msg = cl.Message(content=f"Processing `{file.name}`...")
|
74 |
+
|
75 |
+
await msg.send()
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
with open(file.path, "r", encoding="utf-8") as f:
|
80 |
+
|
81 |
+
text = f.read()
|
82 |
+
|
83 |
+
|
84 |
+
|
85 |
+
# Split the text into chunks
|
86 |
+
|
87 |
+
texts = text_splitter.split_text(text)
|
88 |
+
|
89 |
+
|
90 |
+
|
91 |
+
# Create a metadata for each chunk
|
92 |
+
|
93 |
+
metadatas = [{"source": f"{i}-pl"} for i in range(len(texts))]
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
# Create a Chroma vector store
|
98 |
+
|
99 |
+
embeddings = OpenAIEmbeddings()
|
100 |
+
|
101 |
+
docsearch = await cl.make_async(Chroma.from_texts)(
|
102 |
+
|
103 |
+
texts, embeddings, metadatas=metadatas
|
104 |
+
|
105 |
+
)
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
message_history = ChatMessageHistory()
|
110 |
+
|
111 |
+
|
112 |
+
|
113 |
+
memory = ConversationBufferMemory(
|
114 |
+
|
115 |
+
memory_key="chat_history",
|
116 |
+
|
117 |
+
output_key="answer",
|
118 |
+
|
119 |
+
chat_memory=message_history,
|
120 |
+
|
121 |
+
return_messages=True,
|
122 |
+
|
123 |
+
)
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
# Create a chain that uses the Chroma vector store
|
128 |
+
|
129 |
+
chain = ConversationalRetrievalChain.from_llm(
|
130 |
+
|
131 |
+
ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, streaming=True),
|
132 |
+
|
133 |
+
chain_type="stuff",
|
134 |
+
|
135 |
+
retriever=docsearch.as_retriever(),
|
136 |
+
|
137 |
+
memory=memory,
|
138 |
+
|
139 |
+
return_source_documents=True,
|
140 |
+
|
141 |
+
)
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
# Let the user know that the system is ready
|
146 |
+
|
147 |
+
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
|
148 |
+
|
149 |
+
await msg.update()
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
cl.user_session.set("chain", chain)
|
154 |
+
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
@cl.on_message
|
160 |
+
|
161 |
+
async def main(message: cl.Message):
|
162 |
+
|
163 |
+
chain = cl.user_session.get("chain") # type: ConversationalRetrievalChain
|
164 |
+
|
165 |
+
cb = cl.AsyncLangchainCallbackHandler()
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
res = await chain.acall(message.content, callbacks=[cb])
|
170 |
+
|
171 |
+
answer = res["answer"]
|
172 |
+
|
173 |
+
source_documents = res["source_documents"] # type: List[Document]
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
text_elements = [] # type: List[cl.Text]
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
if source_documents:
|
182 |
+
|
183 |
+
for source_idx, source_doc in enumerate(source_documents):
|
184 |
+
|
185 |
+
source_name = f"source_{source_idx}"
|
186 |
+
|
187 |
+
# Create the text element referenced in the message
|
188 |
+
|
189 |
+
text_elements.append(
|
190 |
+
|
191 |
+
cl.Text(content=source_doc.page_content, name=source_name, display="side")
|
192 |
+
|
193 |
+
)
|
194 |
+
|
195 |
+
source_names = [text_el.name for text_el in text_elements]
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
if source_names:
|
200 |
+
|
201 |
+
answer += f"\nSources: {', '.join(source_names)}"
|
202 |
+
|
203 |
+
else:
|
204 |
+
|
205 |
+
answer += "\nNo sources found"
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
await cl.Message(content=answer, elements=text_elements).send()
|
210 |
+
|
211 |
+
|
212 |
+
|
213 |
+
|
old_scripts/app1.1.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv # Import dotenv to load environment variables
|
2 |
+
import os
|
3 |
+
import chainlit as cl
|
4 |
+
from langchain.chains import RetrievalQA
|
5 |
+
from langchain_community.vectorstores import FAISS
|
6 |
+
from langchain_community.embeddings import OpenAIEmbeddings
|
7 |
+
from langchain.text_splitter import CharacterTextSplitter
|
8 |
+
from langchain.chat_models import ChatOpenAI
|
9 |
+
from langchain.schema import Document
|
10 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
11 |
+
import json
|
12 |
+
|
13 |
+
# Load environment variables from .env file
|
14 |
+
load_dotenv()
|
15 |
+
|
16 |
+
# Get the OpenAI API key from the environment
|
17 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
18 |
+
|
19 |
+
if not OPENAI_API_KEY:
|
20 |
+
raise ValueError("OPENAI_API_KEY is not set. Please add it to your .env file.")
|
21 |
+
|
22 |
+
# Global variables for vector store and QA chain
|
23 |
+
vector_store = None
|
24 |
+
qa_chain = None
|
25 |
+
|
26 |
+
# Step 1: Load and Process JSON Data
|
27 |
+
def load_json_file(file_path):
|
28 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
29 |
+
data = json.load(file)
|
30 |
+
return data
|
31 |
+
|
32 |
+
def setup_vector_store_from_json(json_data):
|
33 |
+
# Create Document objects with URLs and content
|
34 |
+
documents = [Document(page_content=item["content"], metadata={"url": item["url"]}) for item in json_data]
|
35 |
+
|
36 |
+
# Create embeddings and store them in FAISS
|
37 |
+
#embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)
|
38 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
39 |
+
vector_store = FAISS.from_documents(documents, embeddings)
|
40 |
+
return vector_store
|
41 |
+
|
42 |
+
def setup_qa_chain(vector_store):
|
43 |
+
retriever = vector_store.as_retriever(search_kwargs={"k": 3})
|
44 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo", openai_api_key=OPENAI_API_KEY)
|
45 |
+
qa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever, return_source_documents=True)
|
46 |
+
return qa_chain
|
47 |
+
|
48 |
+
# Initialize Chainlit: Preload data when the chat starts
|
49 |
+
@cl.on_chat_start
|
50 |
+
async def chat_start():
|
51 |
+
global vector_store, qa_chain
|
52 |
+
|
53 |
+
# Load and preprocess the JSON file
|
54 |
+
json_data = load_json_file("football_players.json")
|
55 |
+
vector_store = setup_vector_store_from_json(json_data)
|
56 |
+
qa_chain = setup_qa_chain(vector_store)
|
57 |
+
|
58 |
+
# Send a welcome message
|
59 |
+
await cl.Message(content="Welcome to the RAG app! Ask me any question based on the knowledge base.").send()
|
60 |
+
|
61 |
+
# Process user queries
|
62 |
+
@cl.on_message
|
63 |
+
async def main(message: cl.Message):
|
64 |
+
global qa_chain
|
65 |
+
|
66 |
+
# Ensure the QA chain is ready
|
67 |
+
if qa_chain is None:
|
68 |
+
await cl.Message(content="The app is still initializing. Please wait a moment and try again.").send()
|
69 |
+
return
|
70 |
+
|
71 |
+
# Get query from the user and run the QA chain
|
72 |
+
query = message.content
|
73 |
+
response = qa_chain({"query": query})
|
74 |
+
|
75 |
+
# Extract the answer and source documents
|
76 |
+
answer = response["result"]
|
77 |
+
sources = response["source_documents"]
|
78 |
+
|
79 |
+
# Format and send the response
|
80 |
+
await cl.Message(content=f"**Answer:** {answer}").send()
|
81 |
+
if sources:
|
82 |
+
await cl.Message(content="**Sources:**").send()
|
83 |
+
for i, doc in enumerate(sources, 1):
|
84 |
+
url = doc.metadata.get("url", "No URL available")
|
85 |
+
await cl.Message(content=f"**Source {i}:** {doc.page_content}\n**URL:** {url}").send()
|
old_scripts/bpl_scraper.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
from bs4 import BeautifulSoup
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
import re
|
6 |
+
from typing import List, Dict
|
7 |
+
import logging
|
8 |
+
from urllib.parse import urljoin, urlparse
|
9 |
+
|
10 |
+
class DigitalCommonwealthScraper:
|
11 |
+
def __init__(self, base_url: str = "https://www.digitalcommonwealth.org"):
|
12 |
+
"""
|
13 |
+
Initialize the scraper with base URL and logging
|
14 |
+
|
15 |
+
:param base_url: Base URL for Digital Commonwealth
|
16 |
+
"""
|
17 |
+
self.base_url = base_url
|
18 |
+
logging.basicConfig(level=logging.INFO)
|
19 |
+
self.logger = logging.getLogger(__name__)
|
20 |
+
|
21 |
+
# Headers to mimic browser request
|
22 |
+
self.headers = {
|
23 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
24 |
+
}
|
25 |
+
|
26 |
+
def fetch_page(self, url: str) -> requests.Response:
|
27 |
+
"""
|
28 |
+
Fetch webpage content with error handling
|
29 |
+
|
30 |
+
:param url: URL to fetch
|
31 |
+
:return: Response object
|
32 |
+
"""
|
33 |
+
try:
|
34 |
+
response = requests.get(url, headers=self.headers)
|
35 |
+
response.raise_for_status()
|
36 |
+
return response
|
37 |
+
except requests.RequestException as e:
|
38 |
+
self.logger.error(f"Error fetching {url}: {e}")
|
39 |
+
return None
|
40 |
+
|
41 |
+
def extract_json_metadata(self, url: str) -> Dict:
|
42 |
+
"""
|
43 |
+
Extract JSON metadata from the page
|
44 |
+
|
45 |
+
:param url: URL of the page
|
46 |
+
:return: Dictionary of metadata
|
47 |
+
"""
|
48 |
+
json_url = f"{url}.json"
|
49 |
+
response = self.fetch_page(json_url)
|
50 |
+
|
51 |
+
if response:
|
52 |
+
try:
|
53 |
+
return response.json()
|
54 |
+
except json.JSONDecodeError:
|
55 |
+
self.logger.error(f"Could not parse JSON from {json_url}")
|
56 |
+
return {}
|
57 |
+
return {}
|
58 |
+
|
59 |
+
def extract_images(self, url: str) -> List[Dict]:
|
60 |
+
"""
|
61 |
+
Extract images from the page
|
62 |
+
|
63 |
+
:param url: URL of the page to scrape
|
64 |
+
:return: List of image dictionaries
|
65 |
+
"""
|
66 |
+
# Fetch page content
|
67 |
+
response = self.fetch_page(url)
|
68 |
+
if not response:
|
69 |
+
return []
|
70 |
+
|
71 |
+
# Parse HTML
|
72 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
73 |
+
|
74 |
+
# Extract JSON metadata
|
75 |
+
metadata = self.extract_json_metadata(url)
|
76 |
+
|
77 |
+
# List to store images
|
78 |
+
images = []
|
79 |
+
|
80 |
+
# Strategy 1: Look for image viewers or specific image containers
|
81 |
+
image_containers = [
|
82 |
+
soup.find('div', class_='viewer-container'),
|
83 |
+
soup.find('div', class_='image-viewer'),
|
84 |
+
soup.find('div', id='image-container')
|
85 |
+
]
|
86 |
+
|
87 |
+
# Strategy 2: Find all image tags
|
88 |
+
img_tags = soup.find_all('img')
|
89 |
+
|
90 |
+
# Combine image sources
|
91 |
+
for img in img_tags:
|
92 |
+
# Get image source
|
93 |
+
src = img.get('src')
|
94 |
+
if not src:
|
95 |
+
continue
|
96 |
+
|
97 |
+
# Resolve relative URLs
|
98 |
+
full_src = urljoin(url, src)
|
99 |
+
|
100 |
+
# Extract alt text or use filename
|
101 |
+
alt = img.get('alt', os.path.basename(urlparse(full_src).path))
|
102 |
+
|
103 |
+
# Create image dictionary
|
104 |
+
image_info = {
|
105 |
+
'url': full_src,
|
106 |
+
'alt': alt,
|
107 |
+
'source_page': url
|
108 |
+
}
|
109 |
+
|
110 |
+
# Try to add metadata if available
|
111 |
+
if metadata:
|
112 |
+
try:
|
113 |
+
# Extract relevant metadata from JSON if possible
|
114 |
+
image_info['metadata'] = {
|
115 |
+
'title': metadata.get('data', {}).get('attributes', {}).get('title_info_primary_tsi'),
|
116 |
+
'description': metadata.get('data', {}).get('attributes', {}).get('abstract_tsi'),
|
117 |
+
'subject': metadata.get('data', {}).get('attributes', {}).get('subject_geographic_sim')
|
118 |
+
}
|
119 |
+
except Exception as e:
|
120 |
+
self.logger.warning(f"Error extracting metadata: {e}")
|
121 |
+
|
122 |
+
images.append(image_info)
|
123 |
+
|
124 |
+
return images
|
125 |
+
|
126 |
+
def download_images(self, images: List[Dict], output_dir: str = 'downloaded_images') -> List[str]:
|
127 |
+
"""
|
128 |
+
Download images to local directory
|
129 |
+
|
130 |
+
:param images: List of image dictionaries
|
131 |
+
:param output_dir: Directory to save images
|
132 |
+
:return: List of downloaded file paths
|
133 |
+
"""
|
134 |
+
# Create output directory
|
135 |
+
os.makedirs(output_dir, exist_ok=True)
|
136 |
+
|
137 |
+
downloaded_files = []
|
138 |
+
|
139 |
+
for i, image in enumerate(images):
|
140 |
+
try:
|
141 |
+
response = requests.get(image['url'], headers=self.headers)
|
142 |
+
response.raise_for_status()
|
143 |
+
|
144 |
+
# Generate filename
|
145 |
+
ext = os.path.splitext(urlparse(image['url']).path)[1] or '.jpg'
|
146 |
+
filename = os.path.join(output_dir, f'image_{i}{ext}')
|
147 |
+
|
148 |
+
with open(filename, 'wb') as f:
|
149 |
+
f.write(response.content)
|
150 |
+
|
151 |
+
downloaded_files.append(filename)
|
152 |
+
self.logger.info(f"Downloaded: {filename}")
|
153 |
+
|
154 |
+
except Exception as e:
|
155 |
+
self.logger.error(f"Error downloading {image['url']}: {e}")
|
156 |
+
|
157 |
+
return downloaded_files
|
158 |
+
|
159 |
+
#def main():
|
160 |
+
# Example usage
|
161 |
+
# scraper = DigitalCommonwealthScraper()
|
162 |
+
#
|
163 |
+
# Example URL from input
|
164 |
+
# url = "https://www.digitalcommonwealth.org/search/commonwealth-oai:5712qh738"
|
165 |
+
|
166 |
+
# Extract images
|
167 |
+
#images = scraper.extract_images(url)
|
168 |
+
|
169 |
+
# Print image information
|
170 |
+
#for img in images:
|
171 |
+
# print(json.dumps(img, indent=2))
|
172 |
+
|
173 |
+
# Optional: Download images
|
174 |
+
#scraper.download_images(images)
|
175 |
+
|
176 |
+
#if __name__ == "__main__":
|
177 |
+
# main()
|
old_scripts/faiss_migrate.ipynb
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"Used this to migrate vectors to pinecone from our faiss indices. I recommend you use our scripts to ingest your data directly into Pinecone. For this, direct it to a folder containing the index.faiss and index.pkl files that you want to ingest into pinecone."
|
8 |
+
]
|
9 |
+
},
|
10 |
+
{
|
11 |
+
"cell_type": "code",
|
12 |
+
"execution_count": null,
|
13 |
+
"metadata": {},
|
14 |
+
"outputs": [
|
15 |
+
{
|
16 |
+
"name": "stderr",
|
17 |
+
"output_type": "stream",
|
18 |
+
"text": [
|
19 |
+
"c:\\Users\\dfole\\Desktop\\CS549\\pinecone_venv\\Lib\\site-packages\\pinecone\\data\\index.py:1: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
20 |
+
" from tqdm.autonotebook import tqdm\n"
|
21 |
+
]
|
22 |
+
}
|
23 |
+
],
|
24 |
+
"source": [
|
25 |
+
"import getpass\n",
|
26 |
+
"import os\n",
|
27 |
+
"import time\n",
|
28 |
+
"from pinecone import Pinecone, ServerlessSpec\n",
|
29 |
+
"\n",
|
30 |
+
"pinecone_api_key = os.environ.get(\"PINECONE_API_KEY\")\n",
|
31 |
+
"\n",
|
32 |
+
"pc = Pinecone(api_key=pinecone_api_key)"
|
33 |
+
]
|
34 |
+
},
|
35 |
+
{
|
36 |
+
"cell_type": "code",
|
37 |
+
"execution_count": 2,
|
38 |
+
"metadata": {},
|
39 |
+
"outputs": [],
|
40 |
+
"source": [
|
41 |
+
"from langchain_huggingface import HuggingFaceEmbeddings\n",
|
42 |
+
"\n",
|
43 |
+
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")"
|
44 |
+
]
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"cell_type": "code",
|
48 |
+
"execution_count": null,
|
49 |
+
"metadata": {},
|
50 |
+
"outputs": [
|
51 |
+
{
|
52 |
+
"name": "stderr",
|
53 |
+
"output_type": "stream",
|
54 |
+
"text": [
|
55 |
+
"100%|ββββββββββ| 4685/4685 [1:57:28<00:00, 1.50s/it] \n"
|
56 |
+
]
|
57 |
+
},
|
58 |
+
{
|
59 |
+
"name": "stdout",
|
60 |
+
"output_type": "stream",
|
61 |
+
"text": [
|
62 |
+
"Successfully migrated 468455 documents to Pinecone index 'bpl-rag'\n"
|
63 |
+
]
|
64 |
+
}
|
65 |
+
],
|
66 |
+
"source": [
|
67 |
+
"import os\n",
|
68 |
+
"from langchain_community.vectorstores import FAISS\n",
|
69 |
+
"from pinecone import Pinecone, ServerlessSpec\n",
|
70 |
+
"from langchain_community.embeddings import OpenAIEmbeddings\n",
|
71 |
+
"from tqdm import tqdm\n",
|
72 |
+
"from langchain_pinecone import PineconeVectorStore\n",
|
73 |
+
"\n",
|
74 |
+
"def migrate_faiss_to_pinecone(\n",
|
75 |
+
" faiss_index_path: str,\n",
|
76 |
+
" pinecone_api_key: str,\n",
|
77 |
+
" index_name: str,\n",
|
78 |
+
" batch_size: int = 100\n",
|
79 |
+
"):\n",
|
80 |
+
" \"\"\"\n",
|
81 |
+
" Migrate a local FAISS index to Pinecone.\n",
|
82 |
+
" \n",
|
83 |
+
" Args:\n",
|
84 |
+
" faiss_index_path: Path to the local FAISS index\n",
|
85 |
+
" pinecone_api_key: Your Pinecone API key\n",
|
86 |
+
" pinecone_environment: Pinecone environment (e.g., \"us-east1-gcp\")\n",
|
87 |
+
" index_name: Name of the Pinecone index to create/use\n",
|
88 |
+
" batch_size: Number of vectors to upload in each batch\n",
|
89 |
+
" \"\"\"\n",
|
90 |
+
" # Load the local FAISS index\n",
|
91 |
+
" embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-MiniLM-L6-v2\")\n",
|
92 |
+
" faiss_vectorstore = FAISS.load_local(faiss_index_path, embeddings,allow_dangerous_deserialization=True)\n",
|
93 |
+
" pc = Pinecone(api_key=pinecone_api_key)\n",
|
94 |
+
"\n",
|
95 |
+
" index = pc.Index(index_name)\n",
|
96 |
+
" \n",
|
97 |
+
" # Get all the vectors and documents from FAISS\n",
|
98 |
+
" all_docs = faiss_vectorstore.docstore._dict\n",
|
99 |
+
" docs = dict()\n",
|
100 |
+
"\n",
|
101 |
+
" for uuid in faiss_vectorstore.docstore._dict:\n",
|
102 |
+
" doc = faiss_vectorstore.docstore._dict[uuid]\n",
|
103 |
+
" # print(doc)\n",
|
104 |
+
" if doc.metadata['field'] in ['abstract_tsi','title_info_primary_tsi','title_info_primary_subtitle_tsi', 'title_info_alternative_tsim']:\n",
|
105 |
+
" if len(doc.page_content) > 3:\n",
|
106 |
+
" docs[uuid] = doc\n",
|
107 |
+
"\n",
|
108 |
+
" total_docs = len(docs)\n",
|
109 |
+
" \n",
|
110 |
+
" pinecone_vectorstore = PineconeVectorStore(index=index, embedding=embeddings)\n",
|
111 |
+
"\n",
|
112 |
+
" # Batch processing\n",
|
113 |
+
" for i in tqdm(range(0, total_docs, batch_size)):\n",
|
114 |
+
" batch_ids = list(docs.keys())[i:i + batch_size]\n",
|
115 |
+
" batch_docs = [docs[doc_id] for doc_id in batch_ids]\n",
|
116 |
+
" batch_embeddings = [faiss_vectorstore.index.reconstruct(j).tolist() \n",
|
117 |
+
" for j in range(i, min(i + batch_size, total_docs))]\n",
|
118 |
+
" \n",
|
119 |
+
" # Create metadata for each document\n",
|
120 |
+
" metadatas = [doc.metadata for doc in batch_docs]\n",
|
121 |
+
" texts = [doc.page_content for doc in batch_docs]\n",
|
122 |
+
" # print(batch_docs)\n",
|
123 |
+
" # Add vectors to Pinecone\n",
|
124 |
+
" pinecone_vectorstore.add_texts(\n",
|
125 |
+
" texts=texts,\n",
|
126 |
+
" metadatas=metadatas,\n",
|
127 |
+
" embeddings=batch_embeddings,\n",
|
128 |
+
" ids=batch_ids\n",
|
129 |
+
" )\n",
|
130 |
+
" \n",
|
131 |
+
" print(f\"Successfully migrated {total_docs} documents to Pinecone index '{index_name}'\")\n",
|
132 |
+
" return pinecone_vectorstore\n",
|
133 |
+
"\n",
|
134 |
+
"# Example usage:\n",
|
135 |
+
"if __name__ == \"__main__\":\n",
|
136 |
+
" # Set your credentials and paths\n",
|
137 |
+
" FAISS_INDEX_PATH = \"faiss_900_1200\"\n",
|
138 |
+
" PINECONE_API_KEY = \"pcsk_47kPH2_665LiydNVZXrhKkZgx7eNJ5bjEChMWhp6Vx2fUrShiNXRZ2rSCdonUiAkUTDJ7n\"\n",
|
139 |
+
" INDEX_NAME = \"bpl-rag\"\n",
|
140 |
+
" \n",
|
141 |
+
" # Perform migration\n",
|
142 |
+
" pinecone_vs = migrate_faiss_to_pinecone(\n",
|
143 |
+
" faiss_index_path=FAISS_INDEX_PATH,\n",
|
144 |
+
" pinecone_api_key=PINECONE_API_KEY,\n",
|
145 |
+
" index_name=INDEX_NAME,\n",
|
146 |
+
" batch_size=100\n",
|
147 |
+
" )"
|
148 |
+
]
|
149 |
+
},
|
150 |
+
{
|
151 |
+
"cell_type": "code",
|
152 |
+
"execution_count": null,
|
153 |
+
"metadata": {},
|
154 |
+
"outputs": [],
|
155 |
+
"source": []
|
156 |
+
}
|
157 |
+
],
|
158 |
+
"metadata": {
|
159 |
+
"kernelspec": {
|
160 |
+
"display_name": "pinecone_venv",
|
161 |
+
"language": "python",
|
162 |
+
"name": "python3"
|
163 |
+
},
|
164 |
+
"language_info": {
|
165 |
+
"codemirror_mode": {
|
166 |
+
"name": "ipython",
|
167 |
+
"version": 3
|
168 |
+
},
|
169 |
+
"file_extension": ".py",
|
170 |
+
"mimetype": "text/x-python",
|
171 |
+
"name": "python",
|
172 |
+
"nbconvert_exporter": "python",
|
173 |
+
"pygments_lexer": "ipython3",
|
174 |
+
"version": "3.12.4"
|
175 |
+
}
|
176 |
+
},
|
177 |
+
"nbformat": 4,
|
178 |
+
"nbformat_minor": 2
|
179 |
+
}
|
old_scripts/new_streamlit.app
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from typing import List, Tuple, Optional
|
4 |
+
from pinecone import Pinecone
|
5 |
+
from langchain_pinecone import PineconeVectorStore
|
6 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
7 |
+
from langchain_openai import ChatOpenAI
|
8 |
+
from langchain_core.prompts import PromptTemplate
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
from RAG import RAG
|
11 |
+
import logging
|
12 |
+
|
13 |
+
# Configure logging
|
14 |
+
logging.basicConfig(level=logging.INFO)
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
|
17 |
+
# Page configuration
|
18 |
+
st.set_page_config(
|
19 |
+
page_title="RAG Chatbot",
|
20 |
+
page_icon="π€",
|
21 |
+
layout="wide"
|
22 |
+
)
|
23 |
+
|
24 |
+
def initialize_models() -> Tuple[Optional[ChatOpenAI], HuggingFaceEmbeddings]:
|
25 |
+
"""Initialize the language model and embeddings."""
|
26 |
+
try:
|
27 |
+
load_dotenv()
|
28 |
+
|
29 |
+
# Initialize OpenAI model
|
30 |
+
llm = ChatOpenAI(
|
31 |
+
model="gpt-4", # Changed from gpt-4o-mini which appears to be a typo
|
32 |
+
temperature=0,
|
33 |
+
timeout=60, # Added reasonable timeout
|
34 |
+
max_retries=2
|
35 |
+
)
|
36 |
+
|
37 |
+
# Initialize embeddings
|
38 |
+
embeddings = HuggingFaceEmbeddings(
|
39 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
40 |
+
)
|
41 |
+
|
42 |
+
return llm, embeddings
|
43 |
+
|
44 |
+
except Exception as e:
|
45 |
+
logger.error(f"Error initializing models: {str(e)}")
|
46 |
+
st.error(f"Failed to initialize models: {str(e)}")
|
47 |
+
return None, None
|
48 |
+
|
49 |
+
def process_message(
|
50 |
+
query: str,
|
51 |
+
llm: ChatOpenAI,
|
52 |
+
index_name: str,
|
53 |
+
embeddings: HuggingFaceEmbeddings
|
54 |
+
) -> Tuple[str, List]:
|
55 |
+
"""Process the user message using the RAG system."""
|
56 |
+
try:
|
57 |
+
response, sources = RAG(
|
58 |
+
query=query,
|
59 |
+
llm=llm,
|
60 |
+
index_name=index_name,
|
61 |
+
embeddings=embeddings
|
62 |
+
)
|
63 |
+
return response, sources
|
64 |
+
except Exception as e:
|
65 |
+
logger.error(f"Error in process_message: {str(e)}")
|
66 |
+
return f"Error processing message: {str(e)}", []
|
67 |
+
|
68 |
+
def display_sources(sources: List) -> None:
|
69 |
+
"""Display sources in expandable sections with proper formatting and custom URLs."""
|
70 |
+
if not sources:
|
71 |
+
st.info("No sources available for this response.")
|
72 |
+
return
|
73 |
+
|
74 |
+
st.subheader("Sources")
|
75 |
+
for i, doc in enumerate(sources, 1):
|
76 |
+
try:
|
77 |
+
with st.expander(f"Source {i}"):
|
78 |
+
if hasattr(doc, 'page_content'):
|
79 |
+
st.markdown(f"**Content:** {doc.page_content}")
|
80 |
+
if hasattr(doc, 'metadata'):
|
81 |
+
# Construct URL from source metadata
|
82 |
+
|
83 |
+
# Display other metadata
|
84 |
+
for key, value in doc.metadata.items():
|
85 |
+
if key != 'source': # Skip source since we already used it for URL
|
86 |
+
st.markdown(f"**{key.title()}:** {value}")
|
87 |
+
else:
|
88 |
+
st.markdown(f"**Content:** {str(doc)}")
|
89 |
+
except Exception as e:
|
90 |
+
logger.error(f"Error displaying source {i}: {str(e)}")
|
91 |
+
st.error(f"Error displaying source {i}")
|
92 |
+
|
93 |
+
def main():
|
94 |
+
st.title("RAG Chatbot")
|
95 |
+
|
96 |
+
# Initialize session state
|
97 |
+
if "messages" not in st.session_state:
|
98 |
+
st.session_state.messages = []
|
99 |
+
|
100 |
+
# Initialize models
|
101 |
+
llm, embeddings = initialize_models()
|
102 |
+
if not llm or not embeddings:
|
103 |
+
st.error("Failed to initialize the application. Please check the logs.")
|
104 |
+
return
|
105 |
+
|
106 |
+
# Constants
|
107 |
+
INDEX_NAME = 'bpl-rag'
|
108 |
+
|
109 |
+
# Display chat history
|
110 |
+
for message in st.session_state.messages:
|
111 |
+
with st.chat_message(message["role"]):
|
112 |
+
st.markdown(message["content"])
|
113 |
+
|
114 |
+
# Chat input
|
115 |
+
user_input = st.chat_input("Type your message here...")
|
116 |
+
if user_input:
|
117 |
+
# Display user message
|
118 |
+
with st.chat_message("user"):
|
119 |
+
st.markdown(user_input)
|
120 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
121 |
+
|
122 |
+
# Process and display assistant response
|
123 |
+
with st.chat_message("assistant"):
|
124 |
+
with st.spinner("Thinking..."):
|
125 |
+
response, sources = process_message(
|
126 |
+
query=user_input,
|
127 |
+
llm=llm,
|
128 |
+
index_name=INDEX_NAME,
|
129 |
+
embeddings=embeddings
|
130 |
+
)
|
131 |
+
|
132 |
+
if isinstance(response, str):
|
133 |
+
st.markdown(response)
|
134 |
+
st.session_state.messages.append({
|
135 |
+
"role": "assistant",
|
136 |
+
"content": response
|
137 |
+
})
|
138 |
+
|
139 |
+
# Display sources
|
140 |
+
display_sources(sources)
|
141 |
+
else:
|
142 |
+
st.error("Received an invalid response format")
|
143 |
+
|
144 |
+
# Footer
|
145 |
+
st.markdown("---")
|
146 |
+
st.markdown(
|
147 |
+
"Built with β€οΈ using Streamlit + LangChain + OpenAI",
|
148 |
+
help="An AI-powered chatbot with RAG capabilities"
|
149 |
+
)
|
150 |
+
|
151 |
+
if __name__ == "__main__":
|
152 |
+
main()
|
old_scripts/new_streamlit.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from typing import List, Tuple, Optional
|
4 |
+
from pinecone import Pinecone
|
5 |
+
from langchain_pinecone import PineconeVectorStore
|
6 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
7 |
+
from langchain_openai import ChatOpenAI
|
8 |
+
from langchain_core.prompts import PromptTemplate
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
from RAG import RAG
|
11 |
+
from bpl_scraper import DigitalCommonwealthScraper
|
12 |
+
import logging
|
13 |
+
import json
|
14 |
+
import shutil
|
15 |
+
from PIL import Image
|
16 |
+
import io
|
17 |
+
|
18 |
+
# Configure logging
|
19 |
+
logging.basicConfig(level=logging.INFO)
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
# Page configuration
|
23 |
+
st.set_page_config(
|
24 |
+
page_title="Boston Public Library Chatbot",
|
25 |
+
page_icon="π€",
|
26 |
+
layout="wide"
|
27 |
+
)
|
28 |
+
|
29 |
+
def initialize_models() -> Tuple[Optional[ChatOpenAI], HuggingFaceEmbeddings]:
|
30 |
+
"""Initialize the language model and embeddings."""
|
31 |
+
try:
|
32 |
+
load_dotenv()
|
33 |
+
|
34 |
+
# Initialize OpenAI model
|
35 |
+
llm = ChatOpenAI(
|
36 |
+
model="gpt-4", # Changed from gpt-4o-mini which appears to be a typo
|
37 |
+
temperature=0,
|
38 |
+
timeout=60, # Added reasonable timeout
|
39 |
+
max_retries=2
|
40 |
+
)
|
41 |
+
|
42 |
+
# Initialize embeddings
|
43 |
+
embeddings = HuggingFaceEmbeddings(
|
44 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
45 |
+
)
|
46 |
+
|
47 |
+
return llm, embeddings
|
48 |
+
|
49 |
+
except Exception as e:
|
50 |
+
logger.error(f"Error initializing models: {str(e)}")
|
51 |
+
st.error(f"Failed to initialize models: {str(e)}")
|
52 |
+
return None, None
|
53 |
+
|
54 |
+
def process_message(
|
55 |
+
query: str,
|
56 |
+
llm: ChatOpenAI,
|
57 |
+
index_name: str,
|
58 |
+
embeddings: HuggingFaceEmbeddings
|
59 |
+
) -> Tuple[str, List]:
|
60 |
+
"""Process the user message using the RAG system."""
|
61 |
+
try:
|
62 |
+
response, sources = RAG(
|
63 |
+
query=query,
|
64 |
+
llm=llm,
|
65 |
+
index_name=index_name,
|
66 |
+
embeddings=embeddings
|
67 |
+
)
|
68 |
+
return response, sources
|
69 |
+
except Exception as e:
|
70 |
+
logger.error(f"Error in process_message: {str(e)}")
|
71 |
+
return f"Error processing message: {str(e)}", []
|
72 |
+
|
73 |
+
def display_sources(sources: List) -> None:
|
74 |
+
"""Display sources in expandable sections with proper formatting."""
|
75 |
+
if not sources:
|
76 |
+
st.info("No sources available for this response.")
|
77 |
+
return
|
78 |
+
|
79 |
+
st.subheader("Sources")
|
80 |
+
for i, doc in enumerate(sources, 1):
|
81 |
+
try:
|
82 |
+
with st.expander(f"Source {i}"):
|
83 |
+
if hasattr(doc, 'page_content'):
|
84 |
+
st.markdown(f"**Content:** {doc.page_content[0:100] + ' ...'}")
|
85 |
+
if hasattr(doc, 'metadata'):
|
86 |
+
for key, value in doc.metadata.items():
|
87 |
+
st.markdown(f"**{key.title()}:** {value}")
|
88 |
+
|
89 |
+
# Web Scraper to display images of sources
|
90 |
+
# Especially helpful if the sources are images themselves
|
91 |
+
# or are OCR'd text files
|
92 |
+
scraper = DigitalCommonwealthScraper()
|
93 |
+
images = scraper.extract_images(doc.metadata["URL"])
|
94 |
+
images = images[:1]
|
95 |
+
|
96 |
+
# If there are no images then don't display them
|
97 |
+
if not images:
|
98 |
+
st.warning("No images found on the page.")
|
99 |
+
return
|
100 |
+
|
101 |
+
# Download the images
|
102 |
+
# Delete the directory if it already exists
|
103 |
+
# to clear the existing cache of images for each listed source
|
104 |
+
output_dir = 'downloaded_images'
|
105 |
+
if os.path.exists(output_dir):
|
106 |
+
shutil.rmtree(output_dir)
|
107 |
+
|
108 |
+
# Download the main image to a local directory
|
109 |
+
downloaded_files = scraper.download_images(images)
|
110 |
+
|
111 |
+
# Display the image using st.image
|
112 |
+
# Display the title of the image using img.get
|
113 |
+
st.image(downloaded_files, width=400, caption=[
|
114 |
+
img.get('alt', f'Image {i+1}') for i, img in enumerate(images)
|
115 |
+
])
|
116 |
+
|
117 |
+
else:
|
118 |
+
st.markdown(f"**Content:** {str(doc)}")
|
119 |
+
|
120 |
+
except Exception as e:
|
121 |
+
logger.error(f"Error displaying source {i}: {str(e)}")
|
122 |
+
st.error(f"Error displaying source {i}")
|
123 |
+
|
124 |
+
|
125 |
+
def main():
|
126 |
+
st.title("Boston Public Library RAG Chatbot")
|
127 |
+
|
128 |
+
# Initialize session state
|
129 |
+
if "messages" not in st.session_state:
|
130 |
+
st.session_state.messages = []
|
131 |
+
|
132 |
+
# Initialize models
|
133 |
+
llm, embeddings = initialize_models()
|
134 |
+
if not llm or not embeddings:
|
135 |
+
st.error("Failed to initialize the application. Please check the logs.")
|
136 |
+
return
|
137 |
+
|
138 |
+
# Constants
|
139 |
+
INDEX_NAME = 'bpl-rag'
|
140 |
+
|
141 |
+
# Display chat history
|
142 |
+
for message in st.session_state.messages:
|
143 |
+
with st.chat_message(message["role"]):
|
144 |
+
st.markdown(message["content"])
|
145 |
+
|
146 |
+
# Chat input
|
147 |
+
user_input = st.chat_input("Type your message here...")
|
148 |
+
|
149 |
+
|
150 |
+
|
151 |
+
if user_input:
|
152 |
+
# Display user message
|
153 |
+
with st.chat_message("user"):
|
154 |
+
st.markdown(user_input)
|
155 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
156 |
+
|
157 |
+
# Process and display assistant response
|
158 |
+
with st.chat_message("assistant"):
|
159 |
+
with st.spinner("Thinking..."):
|
160 |
+
response, sources = process_message(
|
161 |
+
query=user_input,
|
162 |
+
llm=llm,
|
163 |
+
index_name=INDEX_NAME,
|
164 |
+
embeddings=embeddings
|
165 |
+
)
|
166 |
+
|
167 |
+
if isinstance(response, str):
|
168 |
+
st.markdown(response)
|
169 |
+
st.session_state.messages.append({
|
170 |
+
"role": "assistant",
|
171 |
+
"content": response
|
172 |
+
})
|
173 |
+
|
174 |
+
# Display sources
|
175 |
+
display_sources(sources)
|
176 |
+
|
177 |
+
else:
|
178 |
+
st.error("Received an invalid response format")
|
179 |
+
|
180 |
+
# Footer
|
181 |
+
st.markdown("---")
|
182 |
+
st.markdown(
|
183 |
+
"Built with β€οΈ using Streamlit + LangChain + OpenAI",
|
184 |
+
help="An AI-powered chatbot with RAG capabilities"
|
185 |
+
)
|
186 |
+
|
187 |
+
if __name__ == "__main__":
|
188 |
+
main()
|
old_scripts/streamlit-rag-app.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
import os
|
4 |
+
|
5 |
+
import json
|
6 |
+
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
|
9 |
+
|
10 |
+
|
11 |
+
# from langchain.chains import RetrievalQA
|
12 |
+
|
13 |
+
from langchain_community.vectorstores import FAISS
|
14 |
+
|
15 |
+
from langchain.text_splitter import CharacterTextSplitter
|
16 |
+
|
17 |
+
from langchain_openai import ChatOpenAI, OpenAIEmbeddings, OpenAI
|
18 |
+
|
19 |
+
from langchain.schema import Document
|
20 |
+
|
21 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
22 |
+
|
23 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
24 |
+
|
25 |
+
from langchain.chains.retrieval import create_retrieval_chain
|
26 |
+
|
27 |
+
from langchain_core.prompts import PromptTemplate
|
28 |
+
|
29 |
+
|
30 |
+
|
31 |
+
# Load environment variables
|
32 |
+
|
33 |
+
load_dotenv()
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
# Get the OpenAI API key from the environment
|
38 |
+
|
39 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
40 |
+
|
41 |
+
if not OPENAI_API_KEY:
|
42 |
+
|
43 |
+
st.error("OPENAI_API_KEY is not set. Please add it to your .env file.")
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
# Initialize session state variables
|
48 |
+
|
49 |
+
if 'vector_store' not in st.session_state:
|
50 |
+
|
51 |
+
st.session_state.vector_store = None
|
52 |
+
|
53 |
+
# if 'qa_chain' not in st.session_state:
|
54 |
+
|
55 |
+
# st.session_state.qa_chain = None
|
56 |
+
|
57 |
+
|
58 |
+
|
59 |
+
|
60 |
+
|
61 |
+
# def setup_qa_chain(vector_store):
|
62 |
+
|
63 |
+
# """Set up the QA chain with a retriever."""
|
64 |
+
|
65 |
+
# retriever = vector_store.as_retriever(search_kwargs={"k": 3})
|
66 |
+
|
67 |
+
# llm = ChatOpenAI(model="gpt-3.5-turbo", openai_api_key=OPENAI_API_KEY)
|
68 |
+
|
69 |
+
# qa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever, return_source_documents=True)
|
70 |
+
|
71 |
+
# return qa_chain
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
prompt_template = PromptTemplate.from_template("Answer the following query based on a number of context documents Query:{query},Context:{context},Answer:")
|
76 |
+
|
77 |
+
|
78 |
+
|
79 |
+
def main():
|
80 |
+
|
81 |
+
# Set page title and header
|
82 |
+
|
83 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo", openai_api_key=OPENAI_API_KEY)
|
84 |
+
|
85 |
+
st.set_page_config(page_title="LibRAG", page_icon="π")
|
86 |
+
|
87 |
+
st.title("Boston Public Library Database π")
|
88 |
+
|
89 |
+
|
90 |
+
|
91 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
92 |
+
|
93 |
+
|
94 |
+
|
95 |
+
# Sidebar for initialization
|
96 |
+
|
97 |
+
# st.sidebar.header("Initialize Knowledge Base")
|
98 |
+
|
99 |
+
# if st.sidebar.button("Load Data"):
|
100 |
+
|
101 |
+
# try:
|
102 |
+
|
103 |
+
# st.session_state.vector_store = FAISS.load_local(
|
104 |
+
|
105 |
+
# "vector-store", embeddings, allow_dangerous_deserialization=True
|
106 |
+
|
107 |
+
# )
|
108 |
+
|
109 |
+
# st.session_state.qa_chain = setup_qa_chain(st.session_state.vector_store)
|
110 |
+
|
111 |
+
# st.sidebar.success("Knowledge base loaded successfully!")
|
112 |
+
|
113 |
+
# except Exception as e:
|
114 |
+
|
115 |
+
# st.sidebar.error(f"Error loading data: {e}")
|
116 |
+
|
117 |
+
|
118 |
+
|
119 |
+
st.session_state.vector_store = FAISS.load_local("vector-store", embeddings, allow_dangerous_deserialization=True)
|
120 |
+
|
121 |
+
st.session_state.combine_docs_chain = create_stuff_documents_chain(llm, prompt_template)
|
122 |
+
|
123 |
+
st.session_stateretrieval_chain = create_retrieval_chain(st.session_state.vector_store.as_retriever(search_kwargs={"k": 3}), combine_docs_chain)
|
124 |
+
|
125 |
+
# st.session_state.qa_chain = setup_qa_chain(st.session_state.vector_store)
|
126 |
+
|
127 |
+
# Query input and processing
|
128 |
+
|
129 |
+
st.header("Ask a Question")
|
130 |
+
|
131 |
+
query = st.text_input("Enter your question about BPL's database")
|
132 |
+
|
133 |
+
response = llm.invoke()
|
134 |
+
|
135 |
+
if query:
|
136 |
+
|
137 |
+
# Check if vector store and QA chain are initialized
|
138 |
+
|
139 |
+
if st.session_state.response is None:
|
140 |
+
|
141 |
+
st.warning("Please load the knowledge base first using the sidebar.")
|
142 |
+
|
143 |
+
else:
|
144 |
+
|
145 |
+
# Run the query
|
146 |
+
|
147 |
+
try:
|
148 |
+
|
149 |
+
st.session_state.response = retrieval_chain.invoke({"input": f"{query}"})
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
# Display answer
|
154 |
+
|
155 |
+
st.subheader("Answer")
|
156 |
+
|
157 |
+
st.write(response["result"])
|
158 |
+
|
159 |
+
|
160 |
+
|
161 |
+
# Display sources
|
162 |
+
|
163 |
+
st.subheader("Sources")
|
164 |
+
|
165 |
+
sources = response["source_documents"]
|
166 |
+
|
167 |
+
for i, doc in enumerate(sources, 1):
|
168 |
+
|
169 |
+
with st.expander(f"Source {i}"):
|
170 |
+
|
171 |
+
st.write(f"**Content:** {doc.page_content}")
|
172 |
+
|
173 |
+
st.write(f"**URL:** {doc.metadata.get('url', 'No URL available')}")
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
except Exception as e:
|
178 |
+
|
179 |
+
st.error(f"An error occurred: {e}")
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
if __name__ == "__main__":
|
184 |
+
|
185 |
+
main()
|
old_scripts/test_streamlit.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import sys
|
3 |
+
|
4 |
+
st.set_option('client.showErrorDetails', True)
|
5 |
+
|
6 |
+
def main():
|
7 |
+
try:
|
8 |
+
st.title("Test App")
|
9 |
+
st.write("Hello World!")
|
10 |
+
except Exception as e:
|
11 |
+
st.error(f"An error occurred: {str(e)}")
|
12 |
+
print(f"Error: {str(e)}", file=sys.stderr)
|
13 |
+
|
14 |
+
if __name__ == "__main__":
|
15 |
+
main()
|