File size: 1,997 Bytes
63db6ac
 
 
 
 
 
 
 
 
0bff0fd
 
63db6ac
 
 
 
 
 
0bff0fd
63db6ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bff0fd
63db6ac
0bff0fd
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

x = st.slider('Select a value')
st.write(x, 'squared is', x * x)

st.sidebar.text_input("Type your quote here")

dataset = datasets.load_dataset('A-Roucher/english_historical_quotes', download_mode="force_redownload")
dataset = dataset['train']

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
# )

from sentence_transformers.util import semantic_search

# hits = semantic_search(sentence_embedding, dataset_embeddings[:, :], top_k=5)
author_indexes = list(range(1000))
hits = semantic_search(sentence_embedding, dataset_embeddings[author_indexes, :], top_k=5)
st.write(hits)
list_hits = [author_indexes[i['corpus_id']] for i in hits[0]]
st.write(dataset_embeddings.select([12676, 4967, 2612, 8884, 4797]))



# 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