Quotes / app.py
A-Roucher
fix: change requirements
c9fa165
raw
history blame
2.02 kB
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