-
Notifications
You must be signed in to change notification settings - Fork 0
/
Application.py
292 lines (217 loc) · 10.7 KB
/
Application.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import streamlit as st
import pandas as pd
import numpy as np
from Game import Analyzer
import torch
import torch.nn.functional as f
from transformers import BertModel, BertTokenizer
from time import sleep
import os
#forms functions
def formCreation():
st.header('Contexto')
languages= ( 'English', 'русский', 'العربية')
chooseform(languages)
return
def chooseform(languages):
languageOption = st.selectbox(
'please select your language',
languages)
if (languageOption== 'العربية'):
directory = os.getcwd()
guessesPath= directory + "\\guesses.txt"
ArabicContexto = createArabicEnviroment()
ArabicForm(guessesPath,ArabicContexto)
return
elif (languageOption== 'English'):
directory = os.getcwd()
guessesPath= directory + "\\guesses.txt"
englishContexto= createEnglishEnvironment()
EnglishForm(guessesPath, englishContexto)
return
else:
directory = os.getcwd()
guessesPath= directory + "\\guesses.txt"
RussianContexto = createRussianEnviroment()
RussianForm(guessesPath,RussianContexto)
return
#Forms
def ArabicForm(guessesPath,ArabicContexto):
Arabiccontainer = st.container()
guess= Arabiccontainer.text_input("رجاء: أدخل كلمة للتخمين", "type a word")
guess= guess.strip()
if guess == "type a word":
Arabiccontainer.info(""" **كيفية اللعب:**
لديك عدد غير محدود من التخمينات لتتمكن من العثور على الكلمة السرية:
تم ترتيب الكلمات عن طريق خوارزمية ذكاء صنعي وفقاً لمدى التقارب بين الكلمة السرية والتخمينات.
بعد اختيارك للتخمين سترى مدى قرب التخمين من الكلمة السرية، حيث تمتلك الكلمة السرية القيمة 1 وتقل هذه القيمة كلما كان التخمين بعيد عن الكلمة السرية.""")
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
else:
arabicContextoDone=False
_ ,arabicContextoSim, arabicContextoDone, new_target_arabic= checkSimilarity(guess, ArabicContexto)
guessWrite= guess+ " , " + str(arabicContextoSim*1)
if not arabicContextoDone:
if arabicContextoSim== (-1000):
st.write(" الكلمة "+ guess+" غير موجودة")
show(arabicContextoDone, guessesPath, guessWrite=None)
else:
show(arabicContextoDone, guessesPath, guessWrite)
if st.button('Give Up'):
st.write(ArabicContexto.giveup())
else:
st.write("**مبارك: لقد استطعت تخمين الكلمة الصحيحة**")
st.balloons()
setNewTarget("Arabic", new_target_arabic)
show(arabicContextoDone, guessesPath, guessWrite)
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
return
def RussianForm(guessesPath,RussianContexto):
Russiancontainer = st.container()
guess= Russiancontainer.text_input("Пожалуйста, введите свое предположение:", "type a word")
guess= guess.strip()
if guess == "type a word":
Russiancontainer.info(""" **как играть:**
Найди секретное слово. У вас есть неограниченное количество догадок.
Слова были отсортированы с помощью алгоритма искусственного интеллекта в соответствии с тем, насколько они были похожи на секретное слово.
После отправки слова вы увидите его позицию. Секретное слово - это цифра 1.
Алгоритм проанализировал тысячи текстов. Он использует контекст, в котором используются слова, для вычисления сходства между ними.""")
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
else:
russianContextoDone=False
_ ,russianContextoSim, russianContextoDone, new_target_Russian= checkSimilarity(guess, RussianContexto)
guessWrite= guess+ " , " + str(russianContextoSim*1)
if not russianContextoDone:
if russianContextoSim== (-1000):
st.write("Это слово "+ guess+" не существует")
show(russianContextoDone, guessesPath, guessWrite=None)
else:
show(russianContextoDone, guessesPath, guessWrite)
if st.button('Give Up'):
st.write(RussianContexto.giveup())
else:
st.write("**Поздравляем, вы угадали секретное слово**")
st.balloons()
setNewTarget("Russian", new_target_Russian)
show(russianContextoDone, guessesPath, guessWrite)
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
return
def EnglishForm(guessesPath, englishContexto):
Englishcontainer = st.container()
guess= Englishcontainer.text_input("Please enter your guess:", "type a word")
guess= guess.strip()
#guess= "agricultural"
if guess == "type a word":
Englishcontainer.info("""**how to play:**
Find the secret word. You have unlimited guesses.
The words were sorted by an artificial intelligence algorithm according to how similar they were to the secret word.
After submitting a word, you will see its position. The secret word is number 1.
The algorithm analyzed thousands of texts. It uses the context in which words are used to calculate the similarity between them.""")
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
else:
englishContextoDone=False
_ ,englishContextoSimilarity, englishContextoDone, new_target_English= checkSimilarity(guess, englishContexto)
if type(englishContextoSimilarity) != int:
guessWrite= guess+ " , " + str(englishContextoSimilarity*1)
if not englishContextoDone:
if englishContextoSimilarity== (-1000):
st.write("The word "+ guess+" doesent exist")
show(englishContextoDone, guessesPath, guessWrite=None)
else:
show(englishContextoDone, guessesPath, guessWrite)
if st.button('Give Up'):
st.write(englishContexto.giveup())
else:
st.write("**Congratulations you guessed the secret word**")
st.balloons()
setNewTarget("English", new_target_English)
show(englishContextoDone, guessesPath, guessWrite)
f = open(guessesPath, "w")
f.write("Words , Similarities \n")
f.close()
return
def color(x):
cold= 0
worm= 0.65
hot= 0.8
amount = x[1]
if amount >= cold and amount<= worm :
return ['background-color : #e81e80']*len(x)
elif amount> worm and amount<= hot:
return ['background-color : #Ea7051']*len(x)
elif amount > hot:
return ['background-color : #73f181']*len(x)
def show(englishContextoDone, guessesPath, guessWrite):
if guessWrite != None:
f = open(guessesPath, "a",encoding="utf-8")
f.write(guessWrite+ "\n")
f.close()
pdguessed= pd.read_csv(guessesPath, sep=",", header=0)
pdguessed = pdguessed.drop_duplicates()
sortedGuesses=pdguessed.sort_values(by=[pdguessed.keys()[1]], ascending=False)
st.dataframe(sortedGuesses.style.apply(color, axis=1), use_container_width=True)
#environment functions
def setNewTarget(language, new_taregt):
directory = os.getcwd()
targetPath = directory +"\\"+language+"Target.txt"
f = open(targetPath, "w",encoding="utf-8")
f.write(new_taregt)
f.close()
def checkSimilarity(guess , contexto):
contexto.act(guess)
if torch.is_tensor(contexto.reward):
contexto.reward = contexto.reward.item()
return contexto.observations, contexto.reward, contexto.done, contexto.new_target
#####English########
def createEnglishEnvironment():
bert_model_name= "bert-base-multilingual-cased"
directory= os.getcwd()
wordsPath= directory + "\\nouns_.txt"
available_words=[line.strip() for line in open(wordsPath, 'r')]
targetPath= directory + "\\EnglishTarget.txt"
targetFile = open(targetPath, "r")
target = targetFile.read()
targetFile.close()
print (target)
embed_calc = Analyzer(similarity_func=torch.nn.CosineSimilarity(),bert_version= bert_model_name,available_words = available_words,target= target)
return embed_calc
####### arabic ######
def createArabicEnviroment():
bert_model_name = 'asafaya/bert-base-arabic'
directory = os.getcwd()
wordsPath = directory + "\\arabic_nouns.txt"
available_words=[line.strip() for line in open(wordsPath, 'r',encoding="utf8")]
targetPath= directory + "\\ArabicTarget.txt"
targetFile = open(targetPath, "r",encoding="utf8")
target = targetFile.read()
targetFile.close()
print (target)
embed_calc = Analyzer(similarity_func=torch.nn.CosineSimilarity(),bert_version= bert_model_name,available_words = available_words,target= target)
return embed_calc
####### Russian ########
def createRussianEnviroment():
bert_model_name = 'DeepPavlov/rubert-base-cased'
directory = os.getcwd()
wordsPath = directory + "\\russian_nouns.txt"
available_words=[line.strip() for line in open(wordsPath, 'r',encoding="utf8")]
targetPath= directory + "\\RussianTarget.txt"
targetFile = open(targetPath, "r",encoding="utf8")
target = targetFile.read()
targetFile.close()
print (target)
embed_calc = Analyzer(similarity_func=torch.nn.CosineSimilarity(),bert_version= bert_model_name,available_words = available_words,target= target)
return embed_calc
#main code
formCreation()