File size: 2,024 Bytes
63db6ac c9fa165 63db6ac 0bff0fd d3b59ef c9fa165 63db6ac c9fa165 63db6ac 0bff0fd 63db6ac c9fa165 63db6ac c9fa165 63db6ac c9fa165 63db6ac c9fa165 63db6ac |
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 |
import streamlit as st
from sentence_transformers import SentenceTransformer
import datasets
import faiss
import torch
st.sidebar.text_input("Type your quote here")
dataset = datasets.load_dataset('A-Roucher/english_historical_quotes', download_mode="force_redownload")
dataset = datasets.Dataset.from_dict(dataset['train'][:100])
model_name = "sentence-transformers/all-MiniLM-L6-v2" # BAAI/bge-small-en-v1.5" # "Cohere/Cohere-embed-english-light-v3.0" # "sentence-transformers/all-MiniLM-L6-v2"
encoder = SentenceTransformer(model_name)
embeddings = encoder.encode(
dataset["quote"],
batch_size=4,
show_progress_bar=True,
convert_to_numpy=True,
normalize_embeddings=True,
)
# dataset_embeddings = datasets.Dataset.from_dict({"embeddings": embeddings})
# dataset_embeddings.add_faiss_index(column="embeddings")
# dataset_embeddings.save_faiss_index('embeddings', 'output/index_alone.faiss')
# import faiss
# index = faiss.read_index('index_alone.faiss')
sentence = "Knowledge of history is power."
sentence_embedding = encoder.encode([sentence])
# scores, samples = dataset_embeddings.search(
# sentence_embedding, k=10
# )
sentence_embedding_tensor = torch.Tensor(sentence_embedding)
dataset_embeddings_tensor = torch.Tensor(embeddings)
from sentence_transformers.util import semantic_search
author_indexes = list(range(10))
hits = semantic_search(sentence_embedding_tensor, dataset_embeddings_tensor[author_indexes, :], top_k=5)
list_hits = [author_indexes[i['corpus_id']] for i in hits[0]]
print(list_hits)
print(dataset)
st.write(dataset.select(list_hits))
# sentence_embedding = model.encode([sentence])
# scores, sample_indexes = QUOTES_INDEX.search(
# sentence_embedding, k=k
# )
# quotes = QUOTES_DATASET.iloc[sample_indexes[0]]
# author_descriptions_df = get_authors_descriptions(quotes['author'].unique())
# quotes = quotes.merge(author_descriptions_df, on='author')
# quotes["scores"] = scores[0]
# quotes = quotes.sort_values("scores", ascending=True) # lower is better
|