Spaces:
Sleeping
Sleeping
File size: 16,017 Bytes
640b9e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | import os
import gradio
import shutil
import json
import dotenv
import pickle
import itertools
from collections import Counter
from datetime import datetime
from huggingface_hub import HfApi, HfFolder
from openai import OpenAI as OpenAIClient
from pinecone import ServerlessSpec
from pinecone.grpc import PineconeGRPC as Pinecone
from transformers import BertTokenizerFast
from langchain.text_splitter import CharacterTextSplitter
from langchain_community.document_loaders import DirectoryLoader
'''
This file contains the code for user prompting of the language model.
The language model used is gpt 3.5 turbo and uses documents stored in Pinecone.
'''
# Load environment variables
dotenv.load_dotenv()
assert os.getenv("OPENAI_API_KEY") is not None, "Please set the OPENAI_API_KEY environment variable."
assert os.getenv("PINECONE_API_KEY") is not None, "Please set the PINECONE_API_KEY environment variable."
assert os.getenv("HUGGINGFACE_API_KEY") is not None, "Please set the HUGGINGFACE_API_KEY environment variable."
HfFolder.save_token(os.getenv("HUGGINGFACE_API_KEY"))
CHAT_HISTORY_FILE = "chat_history.pkl"
NEW_UPLOAD_DIRECTORY = "new_uploads/"
PREV_UPLOAD_DIRECTORY = "prev_uploads/"
DOC_CHUNK_SIZE = 1000
DOC_CHUNK_OVERLAP = 40
EMBEDDING_FILE = 'embeddings.json'
INDEX_NAME = "hybrid"
BATCH_SIZE = 100
INTERACTIONS_DATASET = "ryanRocks/FalconOpenAIInteractions"
FILES_DATASET = "ryanRocks/FalconOpenAIFiles"
# Ensure uploads directory exists
os.makedirs(NEW_UPLOAD_DIRECTORY, exist_ok=True)
os.makedirs(PREV_UPLOAD_DIRECTORY, exist_ok=True)
chat_history = []
chatbot_history = []
# Initialize Pinecone database
try:
pc = Pinecone(
api_key=os.getenv("PINECONE_API_KEY"),
pool_threads=30,
spec=ServerlessSpec(
cloud="aws",
region="us-east-1",
),
)
print("Connected to Pinecone")
except Exception as e:
print(f"Error initializing Pinecone: {e}")
exit()
# Initialize index if it does not exist
existing_indexes = [index.name for index in pc.list_indexes().indexes]
if INDEX_NAME not in existing_indexes:
pc.create_index(
name=INDEX_NAME,
dimension=1536,
metric="dotproduct",
spec=ServerlessSpec(
cloud="aws",
region="us-east-1",
),
)
print(f"Created index {INDEX_NAME}")
else:
print(f"Index {INDEX_NAME} already exists")
def initialize_chat_history():
'''
Initialize the chat history using the chat history pickle file.
'''
global chatbot_history
loaded_chat_history = []
if (os.path.exists(CHAT_HISTORY_FILE)):
with open(CHAT_HISTORY_FILE, "rb") as f:
loaded_chat_history = pickle.load(f)
else:
loaded_chat_history = []
for i in range(0, len(loaded_chat_history), 2):
chatbot_history.append((
loaded_chat_history[i]['content'],
loaded_chat_history[i+1]['content']
))
async def upload_file(files):
'''
Upload files to Pinecone
Args:
files: List of file paths to process
'''
# Copy files to uploads directory for easier processing
for file in files:
file_path = os.path.join(NEW_UPLOAD_DIRECTORY, file.name.split('/')[-1])
shutil.move(file.name, file_path)
# Load documents
documents = read_documents()
dense_embeddings = dense_embed(documents)
sparse_embeddings = sparse_embed(documents)
#save_embeddings(dense_embeddings, EMBEDDING_FILE)
# Upsert embeddings into Pinecone
await upsert(dense_embeddings, sparse_embeddings)
# Move newly uploaded files to previous uploads directory
move_files()
return get_uploaded_files()
def read_documents():
'''
Load documents from a specified directory into a list
Args:
file_paths: List of file paths to load documents from
Returns:
documents: List of documents loaded from the directory, split by chunks
'''
# Load documents
print("Loading documents...")
documents = []
# Declare loaders for different file types
pdf_loader = DirectoryLoader(NEW_UPLOAD_DIRECTORY, glob="*.pdf")
docx_loader = DirectoryLoader(NEW_UPLOAD_DIRECTORY, glob="*.docx")
txt_loader = DirectoryLoader(NEW_UPLOAD_DIRECTORY, glob="*.txt")
for loader in [pdf_loader, docx_loader, txt_loader]:
# Load document
try:
# Error loading documents: Expected directory, got file: '/private/var/folders/sc/_5mj781j5315nzv10s8kvs1w0000gn/T/gradio/33a9766ee3f05c368d3c7fe56f6f2356e88a4348/YuYouChen Resume.pdf'
documents.extend(loader.load())
except Exception as e:
print(f"Error loading documents: {e}")
if (len(documents) == 0):
print("No documents loaded.")
return []
# Split documents into chunks
text_splitter = CharacterTextSplitter(chunk_size=DOC_CHUNK_SIZE, chunk_overlap=DOC_CHUNK_OVERLAP)
documents = text_splitter.split_documents(documents)
# Iterate to edit metadata to include chunk number
# format = {filename}_{chunk number}
chunk_num = 1
prev_doc_id = documents[0].metadata['source']
for chunk in documents:
if chunk.metadata['source'] != prev_doc_id:
chunk_num = 1
prev_doc_id = chunk.metadata['source']
chunk.metadata['source'] = f"{prev_doc_id}_{chunk_num}"
chunk_num += 1
print("Documents loaded")
return documents
def dense_embed(documents):
'''
Embed documents using OpenAIEmbeddings
Args:
documents: List of documents to embed
Returns:
List of JSON objects {doc_id, embeddings, metadata}
'''
print("Generating dense embeddings...")
# Use OpenAI to embed documents
client = OpenAIClient(
api_key=os.getenv("OPENAI_API_KEY")
)
embeddings = []
# Embed each chunk
for chunk in documents:
chunk_embeddings = client.embeddings.create(
model="text-embedding-3-small",
input=chunk.page_content
)
# Extract embeddings from response
chunk_embedding = [record.embedding for record in chunk_embeddings.data]
embeddings.append({
'doc_id': chunk.metadata['source'].split('/')[-1],
'embeddings': chunk_embedding[0],
'metadata': {'source': chunk.metadata['source'], 'text': chunk.page_content}
})
print("Complete")
return embeddings
def sparse_embed(documents):
'''
Generate sparse embeddings for a list of documents
Args:
documents: List of documents to generate sparse embeddings for
Returns:
List of sparse embeddings in dictionary format
'''
print("Generating sparse embeddings...")
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
sparse_embeds = []
for chunk in documents:
# Create batch of input_ids
inputs = tokenizer(
chunk.page_content,
padding=True,
truncation=True,
max_length=512,
add_special_tokens=False,
)['input_ids']
# Create sparse dictionaries
sparse_embed = build_dict(inputs)
sparse_embeds.append(sparse_embed)
print("Complete")
return sparse_embeds
def build_dict(input_batch):
'''
Build a dictionary for sparse embeddings
Args:
input_batch: List of embeddings to convert to a dictionary
Returns:
List of sparse embeddings in dictionary format
'''
sparse_emb = []
# Iterate through input batch
indices = []
values = []
# Convert the input_batch list to a dictionary of key to frequency values
freqs = dict(Counter(input_batch))
for idx in freqs:
indices.append(idx)
values.append(float(freqs[idx]))
sparse_emb.append({'indices': indices, 'values': values})
return sparse_emb
def save_embeddings(embeddings, filename):
'''
Save generated embedding to a json file
Args:
embeddings: List of embeddings to save
filename: Name of the file to save the embeddings
'''
print("Saving embedding...")
with open(filename, 'w') as file:
json.dump(embeddings, file)
print("Complete")
def chunks(iterable):
'''
Breaks vector list into chunks of BATCH_SIZE for parallel upserts
Args:
iterable: List of vectors to chunk
'''
print("Chunking")
it = iter(iterable)
chunk = tuple(itertools.islice(it, BATCH_SIZE))
while chunk:
yield chunk
chunk = tuple(itertools.islice(it, BATCH_SIZE))
print("Complete")
def vectorize(dense_embeddings, sparse_embeddings):
'''
Vectorize embeddings with document ids to prepare for insertion into Pinecone
Args:
embeddings: List of embeddings to vectorize
Returns:
List of vectors with tuples (chunk ids, embeddings)
'''
print("Vectorizing...")
vectors = []
for dense, sparse in zip(dense_embeddings, sparse_embeddings):
vectors.append({
'id': dense['doc_id'],
'values': dense['embeddings'],
'sparse_values': sparse[0],
'metadata': dense['metadata'],
})
print("Vectorized")
return vectors
async def upsert(dense_embeddings, sparse_embeddings):
'''
Upsert embeddings into pinecone
'''
index = pc.Index(INDEX_NAME)
vectors = vectorize(dense_embeddings, sparse_embeddings)
# Insert vectors into database in chunks
print("Upserting embeddings...")
vector_chunks = chunks(vectors)
for chunk in vector_chunks:
index.upsert(chunk)
print("Complete")
def move_files():
'''
Move uploaded files to the previous uploads directory
'''
print("Moving files...")
api = HfApi()
for file in os.listdir(NEW_UPLOAD_DIRECTORY):
file_path = os.path.join(NEW_UPLOAD_DIRECTORY, file)
if (os.path.isfile(file_path)):
# Upload file to HuggingFace Datasets
api.upload_file(
path_or_fileobj = file_path,
path_in_repo = file,
repo_id = "ryanRocks/FalconOpenAIFiles",
repo_type = "dataset",
)
# Move file to previous uploads directory
new_file_path = os.path.join(PREV_UPLOAD_DIRECTORY, file)
shutil.move(file_path, new_file_path)
def hybrid_scale(dense, sparse, alpha):
print("Hybrid scaling...")
# Check alpha value in range 0 to 1
if alpha < 0 or alpha > 1:
raise ValueError("Alpha must be between 0 and 1")
# Scale dense and sparse vectors to create hybrid search vectors
hdense = [v * alpha for v in dense]
hsparse = {
'indices': sparse['indices'],
'values': [v * (1 - alpha) for v in sparse['values']],
}
print("Complete")
return hdense, hsparse
def hybrid_query(question, top_k, alpha):
try:
print("Hybrid querying...")
# Convert the question into a dense vector
print("Converting question to dense vector...")
client = OpenAIClient(
api_key=os.getenv("OPENAI_API_KEY")
)
query_embedding = client.embeddings.create(
model="text-embedding-3-small",
input=question,
)
dense_vec = [record.embedding for record in query_embedding.data][0]
print("Complete")
# Convert the question into a sparse vector
print("Converting question to sparse vector...")
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
inputs = tokenizer(
question,
padding=True,
truncation=True,
max_length=512,
add_special_tokens=False,
)['input_ids']
sparse_vec = build_dict(inputs)[0]
print("Complete")
# Scale alpha with hybrid_scale
dense_vec, sparse_vec = hybrid_scale(
dense_vec, sparse_vec, alpha
)
# Query pinecone with the query parameters
print("Querying Pinecone...")
index = pc.Index(INDEX_NAME)
result = index.query(
vector=dense_vec,
sparse_vector=sparse_vec,
top_k=top_k,
include_values=True,
include_metadata=True,
)
print("Complete")
# Return search results as json
return result
except Exception as e:
print(f"Error querying Pinecone: {e}")
def prompt(question, history):
'''
Prompt the language model with user input
Args:
question: User string input to prompt the language model
Returns:
Language model response to the user
'''
global chatbot_history
global chat_history
# Handle clearing history
if len(history) == 0:
chatbot_history = []
chat_history = []
with open(CHAT_HISTORY_FILE, "wb") as f:
pickle.dump(chat_history, f)
# Check for API key
if (os.getenv("OPENAI_API_KEY") is None):
return "Please set the OPENAI_API_KEY environment variable."
# Query database and prompt the language model with results
try:
# Query database for context
results = hybrid_query(question, top_k=5, alpha=0.4)
context = ""
for match in results['matches']:
context += match['metadata']['text'] + "\n"
client = OpenAIClient()
# Prepare prompt with chat history
prompt = f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
messages = [{"role": "system", "content": "You are a helpful assistant."}]
messages.extend(chat_history)
messages.append({"role": "user", "content": prompt})
time = datetime.now().isoformat()
print("Prompting language model...")
response = client.chat.completions.create(
messages=messages,
model="gpt-3.5-turbo",
)
# Extract answer from response
answer = response.choices[0].message.content.strip()
interaction = [
{"timestamp": time},
{"role": "user", "content": question},
{"role": "assistant", "content": answer},
{"full_prompt": messages},
]
with open(f"{time}.json", "w") as f:
json.dump(interaction, f)
# Upload interaction to HuggingFace Datasets
api = HfApi()
api.upload_file(
path_or_fileobj = f"{time}.json",
path_in_repo = f"{time}.json",
repo_id = INTERACTIONS_DATASET,
repo_type = "dataset",
)
# Save chat history
chat_history.extend([
{"role": "user", "content": question},
{"role": "assistant", "content": answer},
])
with open(CHAT_HISTORY_FILE, "wb") as f:
pickle.dump(chat_history, f)
return answer
# Handle exceptions
except Exception as e:
return "Error: " + str(e)
def get_uploaded_files():
'''
Get uploaded files in prev_uploads directory
'''
uploaded_files = []
for file in os.listdir(PREV_UPLOAD_DIRECTORY):
file_path = os.path.join(PREV_UPLOAD_DIRECTORY, file)
if (os.path.isfile(file_path)):
uploaded_files.append(file_path)
return uploaded_files
# Create a Gradio interface
with gradio.Blocks() as demo:
# Load chat history
initialize_chat_history()
# Create chatbot interface
chatbot = gradio.Chatbot(value=chat_history, placeholder="What would you like to know?")
gradio.ChatInterface(fn=prompt, chatbot=chatbot)
# Create file upload interface
file_output = gradio.File(value=get_uploaded_files())
upload_button = gradio.UploadButton("Click to upload a file", file_types=["pdf, docx, txt"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output)
demo.launch() |