sms_agent / embeddings.py
abrah926's picture
batch embedding
a124d51 verified
raw
history blame
3.18 kB
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModel
import faiss
import torch
import numpy as np
import os
def log(message):
print(f"βœ… {message}")
# βœ… Load datasets
datasets = {
"sales": load_dataset("goendalf666/sales-conversations"),
"blended": load_dataset("blended_skill_talk"),
"dialog": load_dataset("daily_dialog"),
"multiwoz": load_dataset("multi_woz_v22"),
}
# βœ… Load MiniLM model for embeddings
model_name = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
def embed_text(texts):
"""Generate embeddings for a batch of texts."""
inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt", max_length=512)
with torch.no_grad():
embeddings = model(**inputs).last_hidden_state.mean(dim=1).cpu().numpy()
return embeddings
# βœ… Batch processing function
def create_embeddings(dataset_name, dataset, batch_size=100):
print(f"πŸ“₯ Creating embeddings for {dataset_name}...")
if dataset_name == "goendalf666/sales-conversations":
texts = [" ".join(row.values()) for row in dataset["train"]]
elif dataset_name == "blended_skill_talk":
texts = [" ".join(row["free_messages"] + row["guided_messages"]) for row in dataset["train"]]
elif dataset_name == "daily_dialog":
texts = [" ".join(row["dialog"]) for row in dataset["train"]]
elif dataset_name == "multi_woz_v22":
texts = [" ".join(row["turns"]["utterance"]) for row in dataset["train"]]
else:
print(f"⚠️ Warning: Dataset {dataset_name} not handled properly!")
texts = []
log(f"βœ… Extracted {len(texts)} texts from {dataset_name}.")
# Process in batches
all_embeddings = []
for i in range(0, len(texts), batch_size):
batch = texts[i : i + batch_size]
batch_embeddings = embed_text(batch)
all_embeddings.append(batch_embeddings)
# βœ… Log progress
log(f"πŸš€ Processed {i + len(batch)}/{len(texts)} embeddings for {dataset_name}...")
# Convert list of numpy arrays to a single numpy array
all_embeddings = np.vstack(all_embeddings)
return all_embeddings
# βœ… Save embeddings to FAISS with unique filename
def save_embeddings_to_faiss(embeddings, index_name="my_embeddings"):
index_file = f"{index_name}.faiss"
# βœ… Check if previous FAISS index exists, append if needed
if os.path.exists(index_file):
log("πŸ”„ Loading existing FAISS index to append...")
index = faiss.read_index(index_file)
index.add(np.array(embeddings).astype(np.float32))
else:
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(np.array(embeddings).astype(np.float32))
faiss.write_index(index, index_file) # βœ… Save FAISS index
log(f"βœ… Saved FAISS index: {index_file}")
# βœ… Run embeddings process
for name, dataset in datasets.items():
embeddings = create_embeddings(name, dataset, batch_size=100)
save_embeddings_to_faiss(embeddings, index_name=name)
log(f"βœ… Embeddings for {name} saved to FAISS.")