-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
58 lines (42 loc) · 2.12 KB
/
app.py
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
import numpy as np
import pandas as pd
from scipy.spatial import distance
import streamlit as st
words = []
with open('words.txt', "r", encoding='utf8') as fp:
for index, word in enumerate(fp):
words.append(word.strip('\n'))
with open('embeddings_matrix.npy', 'rb') as f:
embeddings_matrix = np.load(f, allow_pickle=True)
st.title('Guess the secret word !')
st.write('The goal of the game is to guess the secret word. To do so, '
'propose any word and see how close you are from the secret word. '
'**The lower the score you get, the closer '
'you are to the secret word**. When you score low, you did a good job ! It means your proposed word is either easily '
'interchangeable with the secret word, or that it is often associated with the secret word.')
seed = 1
import random
random.seed(seed)
target_index = random.randint(0, embeddings_matrix.shape[0])
target_word = words[target_index]
target_embedding = embeddings_matrix[target_index]
distances = [distance.cosine(target_embedding, vec) for vec in embeddings_matrix]
distances = np.array([[int(i), dist] for i, dist in zip(range(len(distances)), distances)])
distances = distances[distances[:, 1].argsort()]
distances = np.c_[distances, [words[int(distances[i, 0])] for i in range(len(distances))]]
@st.cache(allow_output_mutation=True)
def store_inputs():
return []
proposed_word = st.text_input('Enter your proposed word')
if proposed_word:
if proposed_word in words:
rank = np.where(distances[:,2]==proposed_word)[0][0]
distance = float(distances[rank,1])
st.write(proposed_word ,'is', round(distance,3),'unit away from the target word ! It is the',rank ,'closest word !')
store_inputs().append({'Proposed Word': proposed_word,'Score': distance,'Rank' : rank})
if rank == 0:
st.write('**Congratulations !! You found the secret word !**')
else:
st.write('I dont know this word :( Please select another one')
st.write('History of proposed words: Top words are currently the closest to the secret word.')
st.table(pd.DataFrame(store_inputs()).sort_values(by='Rank'))