Javierss commited on
Commit
5320625
·
1 Parent(s): 62a6862

Add hybrid model method and languages

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.gif filter=lfs diff=lfs merge=lfs -text
37
+ config/w2v_models/esp_w2v_model filter=lfs diff=lfs merge=lfs -text
38
+ config/w2v_models/eng_w2v_model filter=lfs diff=lfs merge=lfs -text
3d_rotation.gif DELETED
Binary file (165 kB)
 
__pycache__/app.cpython-311.pyc CHANGED
Binary files a/__pycache__/app.cpython-311.pyc and b/__pycache__/app.cpython-311.pyc differ
 
__pycache__/app_word2vec.cpython-311.pyc ADDED
Binary file (18.4 kB). View file
 
__pycache__/game.cpython-311.pyc CHANGED
Binary files a/__pycache__/game.cpython-311.pyc and b/__pycache__/game.cpython-311.pyc differ
 
__pycache__/game_word2vec.cpython-311.pyc ADDED
Binary file (12.9 kB). View file
 
__pycache__/hints.cpython-311.pyc ADDED
Binary file (8.16 kB). View file
 
__pycache__/pistas.cpython-311.pyc CHANGED
Binary files a/__pycache__/pistas.cpython-311.pyc and b/__pycache__/pistas.cpython-311.pyc differ
 
__pycache__/tracking.cpython-311.pyc ADDED
Binary file (1.09 kB). View file
 
app.py CHANGED
@@ -1,28 +1,31 @@
1
  import gradio as gr
2
  import json
3
- from game import Semantrix
 
4
 
5
 
6
- config_file_path = "config/lang.json"
7
-
8
 
9
 
10
  with open(config_file_path, "r") as file:
11
  Config_full = json.load(file)
12
 
13
- lang = 0
14
 
15
- if lang == 0:
16
- Config = Config_full["SPA"]["Game"]
17
- elif lang == 1:
18
  Config = Config_full["ENG"]["Game"]
 
19
  else:
20
  Config = Config_full["SPA"]["Game"]
 
 
21
 
22
  def convert_to_markdown_centered(text):
23
  # Separar el texto de último intento y el historial
24
- lines = text.strip().split('\n')
25
-
26
  if not lines:
27
  return ""
28
 
@@ -31,14 +34,13 @@ def convert_to_markdown_centered(text):
31
  # Crear el formato Markdown
32
  markdown = '<div align="center">\n\n'
33
 
34
-
35
  # Crear la tabla de historial
36
- markdown += "## Mejores intentos\n"
37
  markdown += "<table>\n"
38
  markdown += " <tr>\n"
39
- markdown += " <th>Ranking</th>\n"
40
- markdown += " <th>Palabra</th>\n"
41
- markdown += " <th>Puntuación</th>\n"
42
  markdown += " </tr>\n"
43
 
44
  for line in history_attempts:
@@ -53,177 +55,215 @@ def convert_to_markdown_centered(text):
53
 
54
  # Formatear el último intento
55
  last_items = eval(last_attempt)
56
- markdown += f"## Último Intento\n"
57
- markdown += f"**{last_items[0]}:** {last_items[1]} - Score: {last_items[2]}\n\n"
 
 
 
 
58
  markdown += "---\n\n"
59
 
60
-
61
  markdown += "</div>"
62
 
63
  return markdown
64
 
 
65
  with gr.Blocks() as demo:
66
  state = gr.State(-1)
67
  difficulty = gr.State(-1)
68
  hint = gr.State(False)
69
- hint_path = "config/hint.png"
70
- game = Semantrix()
71
-
72
 
73
-
74
 
75
- gr.Markdown(
76
  """
77
- <p style="text-align:center"> SEMANTRIX: EL JUEGO DE LAS PALABRAS </p>
 
 
78
  """
79
  )
80
 
81
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- def reset(difficulty):
84
  game.prepare_game(difficulty)
85
  output = [
86
- -1,
87
- gr.Textbox(visible=False),
88
- gr.Textbox(visible=False),
89
- gr.Image(hint_path,visible=True,interactive=False),
90
- gr.Button("Empezar",visible=True,variant="secondary"),
91
- gr.Radio(visible=False),
92
- gr.Textbox(visible=False),
93
- gr.Button(visible=False)
94
-
95
- ]
 
 
 
 
 
 
96
 
97
  return output
98
 
99
- def change(state,inp):
100
 
101
  state = state + 1
102
- return [state,inp]
103
 
104
- def update(state, radio,inp,hint):
105
  global difficulty
106
  dif_state = 4
107
  output = [state]
108
-
109
  state_int = state
110
 
111
  if state_int == -1:
112
  output.extend(
113
- [
114
- gr.Button("Empezar", visible=True),
115
- gr.Radio(label="", visible=False),
116
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=False, label=""),
117
- gr.Button("Rendirse", visible=False),
118
- gr.Textbox(visible=False),
119
- gr.Image(interactive=False, visible=True),
120
- gr.Textbox(visible=False),
121
- gr.Button(visible=False),
122
- gr.Markdown(visible=False),
123
- ]
124
- )
125
-
126
- if state_int == 1:
 
 
127
  output.extend(
128
- [
129
- gr.Button("Si", visible=False),
130
- gr.Radio(["", "NO"], label="", visible=True),
131
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
132
- gr.Button("Rendirse", visible=False),
133
- gr.Textbox(visible=False),
134
- gr.Image(interactive=False, visible=False),
135
- gr.Textbox(visible=False),
136
- gr.Button(visible=False),
137
- gr.Markdown(visible=False),
138
- ]
 
 
139
  )
140
  elif state_int == 2:
141
- if radio == "NO":
142
  output = [
143
  dif_state,
144
  gr.Button("Introducir", visible=True),
145
  gr.Radio(visible=False),
146
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
147
- gr.Button("Rendirse", visible=False),
 
 
148
  gr.Textbox(visible=False),
149
  gr.Image(interactive=False, visible=False),
150
  gr.Textbox(visible=False),
151
  gr.Button(visible=False),
152
  gr.Markdown(visible=False),
153
- ]
154
-
155
  else:
156
  output.extend(
157
  [
158
- gr.Button("Siguiente", visible=True),
159
- gr.Radio(visible=False),
160
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
161
- gr.Button("Rendirse", visible=False),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  gr.Textbox(visible=False),
163
  gr.Image(interactive=False, visible=False),
164
  gr.Textbox(visible=False),
165
  gr.Button(visible=False),
166
  gr.Markdown(visible=False),
167
- ]
168
- )
169
- elif state_int == dif_state:
170
- output.extend(
171
- [
172
- gr.Button("Siguiente", visible=False),
173
- gr.Radio(["Fácil", "Normal", "Difícil", "Experto"], visible=True),
174
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
175
- gr.Button("Rendirse", visible=False),
176
- gr.Textbox(visible=False),
177
- gr.Image(interactive=False, visible=False),
178
- gr.Textbox(visible=False),
179
- gr.Button(visible=False),
180
- gr.Markdown(visible=False),
181
- ]
182
  )
183
  elif state_int == dif_state + 1:
184
- if radio == "Fácil":
185
  difficulty = 1
186
- elif radio == "Normal":
187
  difficulty = 2
188
- elif radio == "Dificil":
189
  difficulty = 3
190
  else:
191
  difficulty = 4
192
 
193
-
194
-
195
  output.extend(
196
- [
197
- gr.Button("Empezar", visible=True, variant="primary"),
198
- gr.Radio(visible=False),
199
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
200
- gr.Button("Rendirse", visible=False),
201
- gr.Textbox(visible=False),
202
- gr.Image(interactive=False, visible=False),
203
- gr.Textbox(visible=False),
204
- gr.Button(visible=False),
205
- gr.Markdown(visible=False),
206
-
207
- ]
 
208
  )
209
-
210
  elif state_int == dif_state + 2:
211
 
212
  game.prepare_game(difficulty)
213
 
214
  # feed = game.play_game(inp)
215
  output.extend(
216
- [
217
- gr.Button("Enviar", visible=True, variant="primary"),
218
- gr.Radio(label="", visible=False),
219
- gr.Textbox( visible=False, label=""),
220
- gr.Button(visible=True,variant='stop'),
221
- gr.Textbox(value="",visible=True,placeholder="Nueva palabra"),
222
- gr.Image(interactive=False, visible=False),
223
- gr.Textbox(visible=False),
224
- gr.Button(visible=False),
225
- gr.Markdown(visible=False),
226
- ]
227
  )
228
  elif state_int > dif_state + 2:
229
  feed = game.play_game(inp)
@@ -232,86 +272,136 @@ with gr.Blocks() as demo:
232
  ranking_md = convert_to_markdown_centered(feedback_trim[1])
233
  feedback = feedback_trim[0].split("[hint]")
234
  win = feedback_trim[0].split("[win]")
 
235
  if len(feedback) > 1:
236
  hint = True
237
  else:
238
  hint = False
239
-
240
- if len(win) > 1:
241
- won = True
242
  curiosity = game.curiosity()
243
  output.extend(
244
- [
245
- gr.Button("Enviar", visible=False, variant="primary"),
246
- gr.Radio(label="", visible=False),
247
- gr.Textbox(win[1], visible=True, label=""),
248
- gr.Button(visible=False,variant='stop'),
249
- gr.Textbox(value="",visible=False,placeholder="Nueva palabra"),
250
- gr.Image(hint_path,interactive=False, visible=True),
251
- gr.Textbox(curiosity, visible=True, label="Curiosidad"),
252
- gr.Button(visible=True),
253
- gr.Markdown(visible=False),
254
- ]
255
- )
 
 
 
 
 
 
256
  return output
257
 
258
  output.extend(
259
- [
260
- gr.Button("Enviar", visible=True, variant="primary"),
261
- gr.Radio(label="", visible=False),
262
- gr.Textbox(feedback[0], visible=True, label=""),
263
- gr.Button(visible=True,variant='stop'),
264
- gr.Textbox(value="",visible=True,placeholder="Nueva palabra"),
265
- gr.Image(hint_path,interactive=False, visible=False),
266
- gr.Textbox(feedback[1] if hint else "", visible=hint, label="Pista"),
267
- gr.Button(visible=False),
268
- gr.Markdown(ranking_md, visible=True),
269
- ]
270
- )
271
-
 
272
 
273
  else:
274
  output.extend(
275
- [
276
- gr.Button("Siguiente", visible=True),
277
- gr.Radio(label="", visible=False),
278
- gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
279
- gr.Button("Pista", visible=False),
280
- gr.Textbox(visible=False),
281
- gr.Image(interactive=False, visible=False),
282
- gr.Textbox(visible=False),
283
- gr.Button(visible=False),
284
- gr.Markdown(visible=False),
285
- ]
 
 
286
  )
287
  return output
288
-
289
- img = gr.Image(hint_path,height=430,interactive=False, visible=True)
290
  ranking = gr.Markdown(visible=False)
291
 
292
  with gr.Row():
293
- out = gr.Textbox(
294
- visible=False, placeholder=Config[list(Config.keys())[0]]
295
- )
296
- hint_out = gr.Textbox(
297
- visible=False
298
- )
299
  radio = gr.Radio(visible=False)
300
  with gr.Row():
301
- inp = gr.Textbox(visible=False,interactive=True,label="")
302
- but = gr.Button("Empezar")
303
  give_up = gr.Button("Pista", visible=False)
304
- reload = gr.Button("Volver a jugar", visible=False)
305
-
306
- inp.submit(change, inputs=[state,inp], outputs=[state,inp])
307
- but.click(change, inputs=[state,inp], outputs=[state,inp])
308
- give_up.click(change, inputs=[state,gr.Textbox("give_up",visible=False,interactive=True,label="")], outputs=[state,inp])
309
- reload.click(reset,inputs=difficulty,outputs=[state,out,inp,img, but, radio,hint_out,reload])
310
- radio.input(change, inputs=[state,inp], outputs=[state,inp])
311
- demo.load(reset,inputs=difficulty,outputs=[state,out,inp,img, but, radio,hint_out,reload])
312
-
313
- # out.change(button_name, inputs=radio, outputs=[but, radio, out])
314
-
315
- state.change(update, inputs=[state, radio,inp,hint], outputs=[state, but, radio, out, give_up, inp, img, hint_out, reload,ranking])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  if __name__ == "__main__":
317
  demo.launch()
 
1
  import gradio as gr
2
  import json
3
+ from game_word2vec import Semantrix as semantrix_word2vec
4
+ from game import Semantrix as semantrix_sentence_transformers
5
 
6
 
7
+ # config_file_path = "config/lang.json"
8
+ config_file_path = "/home/user/Research/semantrix/config/lang.json"
9
 
10
 
11
  with open(config_file_path, "r") as file:
12
  Config_full = json.load(file)
13
 
14
+ lang_conf = 0
15
 
16
+
17
+ if lang_conf == 1:
 
18
  Config = Config_full["ENG"]["Game"]
19
+ Menu = Config_full["ENG"]["Menu"]
20
  else:
21
  Config = Config_full["SPA"]["Game"]
22
+ Menu = Config_full["SPA"]["Menu"]
23
+
24
 
25
  def convert_to_markdown_centered(text):
26
  # Separar el texto de último intento y el historial
27
+ lines = text.strip().split("\n")
28
+
29
  if not lines:
30
  return ""
31
 
 
34
  # Crear el formato Markdown
35
  markdown = '<div align="center">\n\n'
36
 
 
37
  # Crear la tabla de historial
38
+ markdown += "## " + Menu["Best_tries"] + "\n"
39
  markdown += "<table>\n"
40
  markdown += " <tr>\n"
41
+ markdown += " <th>" + Menu["N_try"] + "</th>\n"
42
+ markdown += " <th>" + Menu["Word"] + "</th>\n"
43
+ markdown += " <th>" + Menu["Score"] + "</th>\n"
44
  markdown += " </tr>\n"
45
 
46
  for line in history_attempts:
 
55
 
56
  # Formatear el último intento
57
  last_items = eval(last_attempt)
58
+ markdown += f"## " + Menu["Last_try"] + "\n"
59
+ markdown += (
60
+ f"**{last_items[0]}:** {last_items[1]} - "
61
+ + Menu["Score"]
62
+ + f": {last_items[2]}\n\n"
63
+ )
64
  markdown += "---\n\n"
65
 
 
66
  markdown += "</div>"
67
 
68
  return markdown
69
 
70
+
71
  with gr.Blocks() as demo:
72
  state = gr.State(-1)
73
  difficulty = gr.State(-1)
74
  hint = gr.State(False)
75
+ logo_path = "config/logo.png"
76
+ logo_win_path = "config/logo_win.gif"
 
77
 
78
+ game = semantrix_sentence_transformers()
79
 
80
+ header = gr.Markdown(
81
  """
82
+ <p style="text-align:center"> """
83
+ + Menu["Header"]
84
+ + """ </p>
85
  """
86
  )
87
 
88
+ def reset(difficulty, lang, model):
89
+ global Config, game, Menu
90
+ language = 1 if lang == "English" else 0
91
+
92
+ if model == "Word2Vec":
93
+ game = semantrix_word2vec(language)
94
+ else:
95
+ game = semantrix_sentence_transformers(language)
96
+
97
+ if language == 1:
98
+ Config = Config_full["ENG"]["Game"]
99
+ Menu = Config_full["ENG"]["Menu"]
100
+ else:
101
+ Config = Config_full["SPA"]["Game"]
102
+ Menu = Config_full["SPA"]["Menu"]
103
 
 
104
  game.prepare_game(difficulty)
105
  output = [
106
+ -1,
107
+ gr.Textbox(visible=False),
108
+ gr.Textbox(visible=False),
109
+ gr.Image(logo_path, visible=True, interactive=False),
110
+ gr.Button(Menu["Start"], visible=True, variant="secondary"),
111
+ gr.Radio(visible=False),
112
+ gr.Textbox(visible=False),
113
+ gr.Button(visible=False),
114
+ gr.Markdown(
115
+ """
116
+ <p style="text-align:center"> """
117
+ + Menu["Header"]
118
+ + """ </p>
119
+ """
120
+ ),
121
+ ]
122
 
123
  return output
124
 
125
+ def change(state, inp):
126
 
127
  state = state + 1
128
+ return [state, inp]
129
 
130
+ def update(state, radio, inp, hint):
131
  global difficulty
132
  dif_state = 4
133
  output = [state]
134
+
135
  state_int = state
136
 
137
  if state_int == -1:
138
  output.extend(
139
+ [
140
+ gr.Button(Menu["Start"], visible=True),
141
+ gr.Radio(label="", visible=False),
142
+ gr.Textbox(
143
+ Config[list(Config.keys())[state_int]], visible=False, label=""
144
+ ),
145
+ gr.Button(Menu["Give_up"], visible=False),
146
+ gr.Textbox(visible=False),
147
+ gr.Image(interactive=False, visible=True),
148
+ gr.Textbox(visible=False),
149
+ gr.Button(visible=False),
150
+ gr.Markdown(visible=False),
151
+ ]
152
+ )
153
+
154
+ elif state_int == 1:
155
  output.extend(
156
+ [
157
+ gr.Button(visible=False),
158
+ gr.Radio([Menu["Yes"], Menu["No"]], label="", visible=True),
159
+ gr.Textbox(
160
+ Config[list(Config.keys())[state_int]], visible=True, label=""
161
+ ),
162
+ gr.Button(Menu["Give_up"], visible=False),
163
+ gr.Textbox(visible=False),
164
+ gr.Image(interactive=False, visible=False),
165
+ gr.Textbox(visible=False),
166
+ gr.Button(visible=False),
167
+ gr.Markdown(visible=False),
168
+ ]
169
  )
170
  elif state_int == 2:
171
+ if radio == Menu["No"]:
172
  output = [
173
  dif_state,
174
  gr.Button("Introducir", visible=True),
175
  gr.Radio(visible=False),
176
+ gr.Textbox(
177
+ Config[list(Config.keys())[state_int]], visible=True, label=""
178
+ ),
179
+ gr.Button(Menu["Give_up"], visible=False),
180
  gr.Textbox(visible=False),
181
  gr.Image(interactive=False, visible=False),
182
  gr.Textbox(visible=False),
183
  gr.Button(visible=False),
184
  gr.Markdown(visible=False),
185
+ ]
186
+
187
  else:
188
  output.extend(
189
  [
190
+ gr.Button(Menu["Next"], visible=True),
191
+ gr.Radio(visible=False),
192
+ gr.Textbox(
193
+ Config[list(Config.keys())[state_int]],
194
+ visible=True,
195
+ label="",
196
+ ),
197
+ gr.Button(Menu["Give_up"], visible=False),
198
+ gr.Textbox(visible=False),
199
+ gr.Image(interactive=False, visible=False),
200
+ gr.Textbox(visible=False),
201
+ gr.Button(visible=False),
202
+ gr.Markdown(visible=False),
203
+ ]
204
+ )
205
+ elif state_int == dif_state:
206
+ output.extend(
207
+ [
208
+ gr.Button(Menu["Next"], visible=False),
209
+ gr.Radio(
210
+ [Menu["Easy"], Menu["Normal"], Menu["Hard"], Menu["Expert"]],
211
+ visible=True,
212
+ ),
213
+ gr.Textbox(
214
+ Config[list(Config.keys())[state_int]], visible=True, label=""
215
+ ),
216
+ gr.Button(Menu["Give_up"], visible=False),
217
  gr.Textbox(visible=False),
218
  gr.Image(interactive=False, visible=False),
219
  gr.Textbox(visible=False),
220
  gr.Button(visible=False),
221
  gr.Markdown(visible=False),
222
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  )
224
  elif state_int == dif_state + 1:
225
+ if radio == Menu["Easy"]:
226
  difficulty = 1
227
+ elif radio == Menu["Normal"]:
228
  difficulty = 2
229
+ elif radio == Menu["Hard"]:
230
  difficulty = 3
231
  else:
232
  difficulty = 4
233
 
 
 
234
  output.extend(
235
+ [
236
+ gr.Button(Menu["Start"], visible=True, variant="primary"),
237
+ gr.Radio(visible=False),
238
+ gr.Textbox(
239
+ Config[list(Config.keys())[state_int]], visible=True, label=""
240
+ ),
241
+ gr.Button(Menu["Give_up"], visible=False),
242
+ gr.Textbox(visible=False),
243
+ gr.Image(interactive=False, visible=False),
244
+ gr.Textbox(visible=False),
245
+ gr.Button(visible=False),
246
+ gr.Markdown(visible=False),
247
+ ]
248
  )
249
+
250
  elif state_int == dif_state + 2:
251
 
252
  game.prepare_game(difficulty)
253
 
254
  # feed = game.play_game(inp)
255
  output.extend(
256
+ [
257
+ gr.Button(Menu["Send"], visible=True, variant="primary"),
258
+ gr.Radio(label="", visible=False),
259
+ gr.Textbox(visible=False, label=""),
260
+ gr.Button(visible=True, variant="stop"),
261
+ gr.Textbox(value="", visible=True, placeholder=Menu["New_word"]),
262
+ gr.Image(interactive=False, visible=False),
263
+ gr.Textbox(visible=False),
264
+ gr.Button(visible=False),
265
+ gr.Markdown(visible=False),
266
+ ]
267
  )
268
  elif state_int > dif_state + 2:
269
  feed = game.play_game(inp)
 
272
  ranking_md = convert_to_markdown_centered(feedback_trim[1])
273
  feedback = feedback_trim[0].split("[hint]")
274
  win = feedback_trim[0].split("[win]")
275
+ lose = feedback_trim[0].split("[lose]")
276
  if len(feedback) > 1:
277
  hint = True
278
  else:
279
  hint = False
280
+
281
+ if len(win) > 1 or len(lose) > 1:
282
+ won = True if len(win) > 1 else False
283
  curiosity = game.curiosity()
284
  output.extend(
285
+ [
286
+ gr.Button(Menu["Send"], visible=False, variant="primary"),
287
+ gr.Radio(label="", visible=False),
288
+ gr.Textbox(win[1] if won else lose[1], visible=True, label=""),
289
+ gr.Button(visible=False, variant="stop"),
290
+ gr.Textbox(
291
+ value="", visible=False, placeholder=Menu["New_word"]
292
+ ),
293
+ gr.Image(
294
+ logo_win_path if won else logo_path,
295
+ interactive=False,
296
+ visible=True,
297
+ ),
298
+ gr.Textbox(curiosity, visible=True, label=Menu["Curiosity"]),
299
+ gr.Button(visible=True),
300
+ gr.Markdown(visible=False),
301
+ ]
302
+ )
303
  return output
304
 
305
  output.extend(
306
+ [
307
+ gr.Button(Menu["Send"], visible=True, variant="primary"),
308
+ gr.Radio(label="", visible=False),
309
+ gr.Textbox(feedback[0], visible=True, label=""),
310
+ gr.Button(visible=True, variant="stop"),
311
+ gr.Textbox(value="", visible=True, placeholder=Menu["New_word"]),
312
+ gr.Image(logo_path, interactive=False, visible=False),
313
+ gr.Textbox(
314
+ feedback[1] if hint else "", visible=hint, label="Pista"
315
+ ),
316
+ gr.Button(visible=False),
317
+ gr.Markdown(ranking_md, visible=True),
318
+ ]
319
+ )
320
 
321
  else:
322
  output.extend(
323
+ [
324
+ gr.Button(Menu["Next"], visible=True),
325
+ gr.Radio(label="", visible=False),
326
+ gr.Textbox(
327
+ Config[list(Config.keys())[state_int]], visible=True, label=""
328
+ ),
329
+ gr.Button("Pista", visible=False),
330
+ gr.Textbox(visible=False),
331
+ gr.Image(interactive=False, visible=False),
332
+ gr.Textbox(visible=False),
333
+ gr.Button(visible=False),
334
+ gr.Markdown(visible=False),
335
+ ]
336
  )
337
  return output
338
+
339
+ img = gr.Image(logo_path, height=430, interactive=False, visible=True)
340
  ranking = gr.Markdown(visible=False)
341
 
342
  with gr.Row():
343
+ out = gr.Textbox(visible=False, placeholder=Config[list(Config.keys())[0]])
344
+ hint_out = gr.Textbox(visible=False)
 
 
 
 
345
  radio = gr.Radio(visible=False)
346
  with gr.Row():
347
+ inp = gr.Textbox(visible=False, interactive=True, label="")
348
+ but = gr.Button(Menu["Start"])
349
  give_up = gr.Button("Pista", visible=False)
350
+ reload = gr.Button(Menu["Play_again"], visible=False)
351
+
352
+ with gr.Accordion("Configuración/Settings", open=False):
353
+ with gr.Row():
354
+ model = (
355
+ gr.Dropdown(
356
+ ["Sentence Transformers", "Word2Vec"],
357
+ value="Sentence Transformers",
358
+ label="Embedding Model",
359
+ ),
360
+ )
361
+ lang = (
362
+ gr.Dropdown(
363
+ ["Español", "English"], value="Español", label="Idioma/Language"
364
+ ),
365
+ )
366
+
367
+ inp.submit(change, inputs=[state, inp], outputs=[state, inp])
368
+ but.click(change, inputs=[state, inp], outputs=[state, inp])
369
+ give_up.click(
370
+ change,
371
+ inputs=[
372
+ state,
373
+ gr.Textbox("give_up", visible=False, interactive=True, label=""),
374
+ ],
375
+ outputs=[state, inp],
376
+ )
377
+ radio.input(change, inputs=[state, inp], outputs=[state, inp])
378
+
379
+ reload.click(
380
+ reset,
381
+ inputs=[difficulty, lang[0], model[0]],
382
+ outputs=[state, out, inp, img, but, radio, hint_out, reload, header],
383
+ )
384
+ demo.load(
385
+ reset,
386
+ inputs=[difficulty, lang[0], model[0]],
387
+ outputs=[state, out, inp, img, but, radio, hint_out, reload, header],
388
+ )
389
+ lang[0].select(
390
+ reset,
391
+ inputs=[difficulty, lang[0], model[0]],
392
+ outputs=[state, out, inp, img, but, radio, hint_out, reload, header],
393
+ )
394
+ model[0].select(
395
+ reset,
396
+ inputs=[difficulty, lang[0], model[0]],
397
+ outputs=[state, out, inp, img, but, radio, hint_out, reload, header],
398
+ )
399
+
400
+ state.change(
401
+ update,
402
+ inputs=[state, radio, inp, hint],
403
+ outputs=[state, but, radio, out, give_up, inp, img, hint_out, reload, ranking],
404
+ )
405
+
406
  if __name__ == "__main__":
407
  demo.launch()
app_trans.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ from game import Semantrix
4
+
5
+
6
+ config_file_path = "config/lang.json"
7
+
8
+
9
+
10
+ with open(config_file_path, "r") as file:
11
+ Config_full = json.load(file)
12
+
13
+ lang = 0
14
+
15
+ if lang == 0:
16
+ Config = Config_full["SPA"]["Game"]
17
+ elif lang == 1:
18
+ Config = Config_full["ENG"]["Game"]
19
+ else:
20
+ Config = Config_full["SPA"]["Game"]
21
+
22
+ def convert_to_markdown_centered(text):
23
+ # Separar el texto de último intento y el historial
24
+ lines = text.strip().split('\n')
25
+
26
+ if not lines:
27
+ return ""
28
+
29
+ last_attempt = lines[0]
30
+ history_attempts = lines[2:12]
31
+ # Crear el formato Markdown
32
+ markdown = '<div align="center">\n\n'
33
+
34
+
35
+ # Crear la tabla de historial
36
+ markdown += "## Mejores intentos\n"
37
+ markdown += "<table>\n"
38
+ markdown += " <tr>\n"
39
+ markdown += " <th>Ranking</th>\n"
40
+ markdown += " <th>Palabra</th>\n"
41
+ markdown += " <th>Puntuación</th>\n"
42
+ markdown += " </tr>\n"
43
+
44
+ for line in history_attempts:
45
+ items = eval(line.strip())
46
+ markdown += " <tr>\n"
47
+ markdown += f" <td><strong>{items[0]}</strong></td>\n"
48
+ markdown += f" <td>{items[1]}</td>\n"
49
+ markdown += f" <td>{items[2]}</td>\n"
50
+ markdown += " </tr>\n"
51
+
52
+ markdown += "</table>\n\n"
53
+
54
+ # Formatear el último intento
55
+ last_items = eval(last_attempt)
56
+ markdown += f"## Último Intento\n"
57
+ markdown += f"**{last_items[0]}:** {last_items[1]} - Score: {last_items[2]}\n\n"
58
+ markdown += "---\n\n"
59
+
60
+
61
+ markdown += "</div>"
62
+
63
+ return markdown
64
+
65
+ with gr.Blocks() as demo:
66
+ state = gr.State(-1)
67
+ difficulty = gr.State(-1)
68
+ hint = gr.State(False)
69
+ hint_path = "config/hint.png"
70
+ game = Semantrix()
71
+
72
+
73
+
74
+
75
+ gr.Markdown(
76
+ """
77
+ <p style="text-align:center"> SEMANTRIX: EL JUEGO DE LAS PALABRAS </p>
78
+ """
79
+ )
80
+
81
+
82
+
83
+ def reset(difficulty):
84
+ game.prepare_game(difficulty)
85
+ output = [
86
+ -1,
87
+ gr.Textbox(visible=False),
88
+ gr.Textbox(visible=False),
89
+ gr.Image(hint_path,visible=True,interactive=False),
90
+ gr.Button("Empezar",visible=True,variant="secondary"),
91
+ gr.Radio(visible=False),
92
+ gr.Textbox(visible=False),
93
+ gr.Button(visible=False)
94
+
95
+ ]
96
+
97
+ return output
98
+
99
+ def change(state,inp):
100
+
101
+ state = state + 1
102
+ return [state,inp]
103
+
104
+ def update(state, radio,inp,hint):
105
+ global difficulty
106
+ dif_state = 4
107
+ output = [state]
108
+
109
+ state_int = state
110
+
111
+ if state_int == -1:
112
+ output.extend(
113
+ [
114
+ gr.Button("Empezar", visible=True),
115
+ gr.Radio(label="", visible=False),
116
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=False, label=""),
117
+ gr.Button("Rendirse", visible=False),
118
+ gr.Textbox(visible=False),
119
+ gr.Image(interactive=False, visible=True),
120
+ gr.Textbox(visible=False),
121
+ gr.Button(visible=False),
122
+ gr.Markdown(visible=False),
123
+ ]
124
+ )
125
+
126
+ if state_int == 1:
127
+ output.extend(
128
+ [
129
+ gr.Button("Si", visible=False),
130
+ gr.Radio(["SÍ", "NO"], label="", visible=True),
131
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
132
+ gr.Button("Rendirse", visible=False),
133
+ gr.Textbox(visible=False),
134
+ gr.Image(interactive=False, visible=False),
135
+ gr.Textbox(visible=False),
136
+ gr.Button(visible=False),
137
+ gr.Markdown(visible=False),
138
+ ]
139
+ )
140
+ elif state_int == 2:
141
+ if radio == "NO":
142
+ output = [
143
+ dif_state,
144
+ gr.Button("Introducir", visible=True),
145
+ gr.Radio(visible=False),
146
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
147
+ gr.Button("Rendirse", visible=False),
148
+ gr.Textbox(visible=False),
149
+ gr.Image(interactive=False, visible=False),
150
+ gr.Textbox(visible=False),
151
+ gr.Button(visible=False),
152
+ gr.Markdown(visible=False),
153
+ ]
154
+
155
+ else:
156
+ output.extend(
157
+ [
158
+ gr.Button("Siguiente", visible=True),
159
+ gr.Radio(visible=False),
160
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
161
+ gr.Button("Rendirse", visible=False),
162
+ gr.Textbox(visible=False),
163
+ gr.Image(interactive=False, visible=False),
164
+ gr.Textbox(visible=False),
165
+ gr.Button(visible=False),
166
+ gr.Markdown(visible=False),
167
+ ]
168
+ )
169
+ elif state_int == dif_state:
170
+ output.extend(
171
+ [
172
+ gr.Button("Siguiente", visible=False),
173
+ gr.Radio(["Fácil", "Normal", "Difícil", "Experto"], visible=True),
174
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
175
+ gr.Button("Rendirse", visible=False),
176
+ gr.Textbox(visible=False),
177
+ gr.Image(interactive=False, visible=False),
178
+ gr.Textbox(visible=False),
179
+ gr.Button(visible=False),
180
+ gr.Markdown(visible=False),
181
+ ]
182
+ )
183
+ elif state_int == dif_state + 1:
184
+ if radio == "Fácil":
185
+ difficulty = 1
186
+ elif radio == "Normal":
187
+ difficulty = 2
188
+ elif radio == "Dificil":
189
+ difficulty = 3
190
+ else:
191
+ difficulty = 4
192
+
193
+
194
+
195
+ output.extend(
196
+ [
197
+ gr.Button("Empezar", visible=True, variant="primary"),
198
+ gr.Radio(visible=False),
199
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
200
+ gr.Button("Rendirse", visible=False),
201
+ gr.Textbox(visible=False),
202
+ gr.Image(interactive=False, visible=False),
203
+ gr.Textbox(visible=False),
204
+ gr.Button(visible=False),
205
+ gr.Markdown(visible=False),
206
+
207
+ ]
208
+ )
209
+
210
+ elif state_int == dif_state + 2:
211
+
212
+ game.prepare_game(difficulty)
213
+
214
+ # feed = game.play_game(inp)
215
+ output.extend(
216
+ [
217
+ gr.Button("Enviar", visible=True, variant="primary"),
218
+ gr.Radio(label="", visible=False),
219
+ gr.Textbox( visible=False, label=""),
220
+ gr.Button(visible=True,variant='stop'),
221
+ gr.Textbox(value="",visible=True,placeholder="Nueva palabra"),
222
+ gr.Image(interactive=False, visible=False),
223
+ gr.Textbox(visible=False),
224
+ gr.Button(visible=False),
225
+ gr.Markdown(visible=False),
226
+ ]
227
+ )
228
+ elif state_int > dif_state + 2:
229
+ feed = game.play_game(inp)
230
+ feedback_trim = feed.split("[rank]")
231
+ if len(feedback_trim) > 1:
232
+ ranking_md = convert_to_markdown_centered(feedback_trim[1])
233
+ feedback = feedback_trim[0].split("[hint]")
234
+ win = feedback_trim[0].split("[win]")
235
+ if len(feedback) > 1:
236
+ hint = True
237
+ else:
238
+ hint = False
239
+
240
+ if len(win) > 1:
241
+ won = True
242
+ curiosity = game.curiosity()
243
+ output.extend(
244
+ [
245
+ gr.Button("Enviar", visible=False, variant="primary"),
246
+ gr.Radio(label="", visible=False),
247
+ gr.Textbox(win[1], visible=True, label=""),
248
+ gr.Button(visible=False,variant='stop'),
249
+ gr.Textbox(value="",visible=False,placeholder="Nueva palabra"),
250
+ gr.Image(hint_path,interactive=False, visible=True),
251
+ gr.Textbox(curiosity, visible=True, label="Curiosidad"),
252
+ gr.Button(visible=True),
253
+ gr.Markdown(visible=False),
254
+ ]
255
+ )
256
+ return output
257
+
258
+ output.extend(
259
+ [
260
+ gr.Button("Enviar", visible=True, variant="primary"),
261
+ gr.Radio(label="", visible=False),
262
+ gr.Textbox(feedback[0], visible=True, label=""),
263
+ gr.Button(visible=True,variant='stop'),
264
+ gr.Textbox(value="",visible=True,placeholder="Nueva palabra"),
265
+ gr.Image(hint_path,interactive=False, visible=False),
266
+ gr.Textbox(feedback[1] if hint else "", visible=hint, label="Pista"),
267
+ gr.Button(visible=False),
268
+ gr.Markdown(ranking_md, visible=True),
269
+ ]
270
+ )
271
+
272
+
273
+ else:
274
+ output.extend(
275
+ [
276
+ gr.Button("Siguiente", visible=True),
277
+ gr.Radio(label="", visible=False),
278
+ gr.Textbox(Config[list(Config.keys())[state_int]], visible=True, label=""),
279
+ gr.Button("Pista", visible=False),
280
+ gr.Textbox(visible=False),
281
+ gr.Image(interactive=False, visible=False),
282
+ gr.Textbox(visible=False),
283
+ gr.Button(visible=False),
284
+ gr.Markdown(visible=False),
285
+ ]
286
+ )
287
+ return output
288
+
289
+ img = gr.Image(hint_path,height=430,interactive=False, visible=True)
290
+ ranking = gr.Markdown(visible=False)
291
+
292
+ with gr.Row():
293
+ out = gr.Textbox(
294
+ visible=False, placeholder=Config[list(Config.keys())[0]]
295
+ )
296
+ hint_out = gr.Textbox(
297
+ visible=False
298
+ )
299
+ radio = gr.Radio(visible=False)
300
+ with gr.Row():
301
+ inp = gr.Textbox(visible=False,interactive=True,label="")
302
+ but = gr.Button("Empezar")
303
+ give_up = gr.Button("Pista", visible=False)
304
+ reload = gr.Button("Volver a jugar", visible=False)
305
+
306
+ inp.submit(change, inputs=[state,inp], outputs=[state,inp])
307
+ but.click(change, inputs=[state,inp], outputs=[state,inp])
308
+ give_up.click(change, inputs=[state,gr.Textbox("give_up",visible=False,interactive=True,label="")], outputs=[state,inp])
309
+ reload.click(reset,inputs=difficulty,outputs=[state,out,inp,img, but, radio,hint_out,reload])
310
+ radio.input(change, inputs=[state,inp], outputs=[state,inp])
311
+ demo.load(reset,inputs=difficulty,outputs=[state,out,inp,img, but, radio,hint_out,reload])
312
+
313
+ # out.change(button_name, inputs=radio, outputs=[but, radio, out])
314
+
315
+ state.change(update, inputs=[state, radio,inp,hint], outputs=[state, but, radio, out, give_up, inp, img, hint_out, reload,ranking])
316
+ if __name__ == "__main__":
317
+ demo.launch()
config/lang.json CHANGED
@@ -52,6 +52,28 @@
52
  "hint_4_3": " únicamente con unos pocos emojis:",
53
  "hint_4_4": "He pensado en una película relacionada con la palabra secreta y te la voy a representar con emojis, la película es:\n",
54
  "curiosity": "Cuéntame una curiosidad sobre \""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
56
  },
57
  "ENG": {
@@ -62,7 +84,7 @@
62
  "Rules": "Each word you propose will receive a semantic score between 0 and 10. A high score means you're very close to guessing the secret word.\n\nIf I see you're a bit lost, I'll be here to give you hints to help you get closer to the secret word.\n\nAs extra help, I'll show a ranking of all the words you've suggested, ordered by their score. This way, you can have a better idea of how close they are and which words work best.\n\nYou'll be the winner when you correctly guess the secret word. Don't give up, it's within your reach!",
63
  "Difficulty_presentation_Full": "In this exciting semantic guessing challenge, you can choose how big you want the challenge to be. Here are the difficulty levels:\n\n- Easy: Obvious clues for quick guessing. Ideal for beginners.\n\n- Normal: Clues only when you're very lost. An intermediate challenge.\n\n- Hard: Minimal help and complex words. For sharp thinkers.\n\n- Expert: No clues and difficult words. For semantic champions.\n\nRemember, whether you win or lose, each level is designed to make you enjoy and improve your guessing and word comprehension skills. Choose your level and start playing!",
64
  "Difficulty": "Choose your difficulty level",
65
- "Begin": "\n\nTurn on your mind, trust your ideas, and above all, have a good time! This is a game where each word, each score, and each clue brings you closer to your victory. Good luck!",
66
  "New_word": "New word: ",
67
  "Feedback_0": "Ice-cold, score: ",
68
  "Feedback_1": "Cold, score: ",
@@ -108,6 +130,28 @@
108
  "hint_4_3": " only with a few emojis:",
109
  "hint_4_4": "I've thought of a movie related to the secret word, and I'll represent it with emojis. The movie is:\n",
110
  "curiosity": "Tell me an interesting fact about \""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  }
112
  }
113
  }
 
52
  "hint_4_3": " únicamente con unos pocos emojis:",
53
  "hint_4_4": "He pensado en una película relacionada con la palabra secreta y te la voy a representar con emojis, la película es:\n",
54
  "curiosity": "Cuéntame una curiosidad sobre \""
55
+ },
56
+ "Menu": {
57
+ "Header": "SEMANTRIX: EL JUEGO DE LAS PALABRAS",
58
+ "Start": "Empezar",
59
+ "Next": "Siguiente",
60
+ "Yes": "Sí",
61
+ "No": "No",
62
+ "Easy": "Fácil",
63
+ "Normal": "Normal",
64
+ "Hard": "Difícil",
65
+ "Expert": "Experto",
66
+ "New_word": "Nueva palabra",
67
+ "Send": "Enviar",
68
+ "Give_up": "Rendirse",
69
+ "Language": "Idioma",
70
+ "Best_tries": "Mejores intentos",
71
+ "N_try": "Intento nº",
72
+ "Word": "Palabra",
73
+ "Score": "Puntuación",
74
+ "Last_try": "Último intento",
75
+ "Curiosity": "Curiosidad",
76
+ "Play_again": "Jugar de nuevo"
77
  }
78
  },
79
  "ENG": {
 
84
  "Rules": "Each word you propose will receive a semantic score between 0 and 10. A high score means you're very close to guessing the secret word.\n\nIf I see you're a bit lost, I'll be here to give you hints to help you get closer to the secret word.\n\nAs extra help, I'll show a ranking of all the words you've suggested, ordered by their score. This way, you can have a better idea of how close they are and which words work best.\n\nYou'll be the winner when you correctly guess the secret word. Don't give up, it's within your reach!",
85
  "Difficulty_presentation_Full": "In this exciting semantic guessing challenge, you can choose how big you want the challenge to be. Here are the difficulty levels:\n\n- Easy: Obvious clues for quick guessing. Ideal for beginners.\n\n- Normal: Clues only when you're very lost. An intermediate challenge.\n\n- Hard: Minimal help and complex words. For sharp thinkers.\n\n- Expert: No clues and difficult words. For semantic champions.\n\nRemember, whether you win or lose, each level is designed to make you enjoy and improve your guessing and word comprehension skills. Choose your level and start playing!",
86
  "Difficulty": "Choose your difficulty level",
87
+ "Begin": "Turn on your mind, trust your ideas, and above all, have a good time! This is a game where each word, each score, and each clue brings you closer to your victory. Good luck!",
88
  "New_word": "New word: ",
89
  "Feedback_0": "Ice-cold, score: ",
90
  "Feedback_1": "Cold, score: ",
 
130
  "hint_4_3": " only with a few emojis:",
131
  "hint_4_4": "I've thought of a movie related to the secret word, and I'll represent it with emojis. The movie is:\n",
132
  "curiosity": "Tell me an interesting fact about \""
133
+ },
134
+ "Menu": {
135
+ "Header": "SEMANTRIX: THE WORD GUESSING GAME",
136
+ "Start": "Start",
137
+ "Next": "Next",
138
+ "Yes": "Yes",
139
+ "No": "No",
140
+ "Easy": "Easy",
141
+ "Normal": "Normal",
142
+ "Hard": "Hard",
143
+ "Expert": "Expert",
144
+ "New_word": "New word",
145
+ "Send": "Send",
146
+ "Give_up": "Give up",
147
+ "Language": "Language",
148
+ "Best_tries": "Best tries",
149
+ "N_try": "Try nº",
150
+ "Word": "Word",
151
+ "Score": "Score",
152
+ "Last_try": "Last try",
153
+ "Curiosity": "Curiosity",
154
+ "Play_again": "Play again"
155
  }
156
  }
157
  }
config/{hint.png → logo.png} RENAMED
File without changes
config/secret.json CHANGED
@@ -105,7 +105,7 @@
105
  "nose",
106
  "wood",
107
  "leg",
108
- "cars",
109
  "hair",
110
  "key",
111
  "stewardess",
@@ -626,7 +626,7 @@
626
  "nariz",
627
  "madera",
628
  "pierna",
629
- "autos",
630
  "cabello",
631
  "llave",
632
  "azafata",
 
105
  "nose",
106
  "wood",
107
  "leg",
108
+ "car",
109
  "hair",
110
  "key",
111
  "stewardess",
 
626
  "nariz",
627
  "madera",
628
  "pierna",
629
+ "coche",
630
  "cabello",
631
  "llave",
632
  "azafata",
data/ranking.txt CHANGED
@@ -1 +1,24 @@
1
- ---------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ['#22', 'ring', 2.82]
2
+ ---------------------------
3
+ ['#10', 'prado', 5.47]
4
+ ['#6', 'lugar', 5.35]
5
+ ['#15', 'robar', 5.31]
6
+ ['#7', 'campo', 5.18]
7
+ ['#14', 'robo', 5.02]
8
+ ['#2', 'loco', 4.74]
9
+ ['#21', 'lucha', 4.65]
10
+ ['#18', 'palabra', 4.39]
11
+ ['#3', 'persona', 4.33]
12
+ ['#1', 'amigo', 4.27]
13
+ ['#19', 'dispositivo', 4.25]
14
+ ['#8', 'habitación', 4.19]
15
+ ['#13', 'policía', 4.1]
16
+ ['#12', 'policia', 3.57]
17
+ ['#17', 'invento', 3.54]
18
+ ['#16', 'niño', 3.44]
19
+ ['#9', 'personal', 3.18]
20
+ ['#20', 'pelea', 3.12]
21
+ ['#22', 'ring', 2.82]
22
+ ['#4', 'imbecil', 2.81]
23
+ ['#11', 'vaca', 2.13]
24
+ ['#5', 'psicólogo', 2.05]
display.py DELETED
@@ -1,192 +0,0 @@
1
- # %%
2
- import asyncio
3
- import pickle as pk
4
- import time
5
- import warnings
6
-
7
- import matplotlib as mpl
8
- import matplotlib.pyplot as plt
9
- import mpl_toolkits.mplot3d.art3d as art3d
10
- import numpy as np
11
- import torch
12
- from matplotlib import cm
13
- from matplotlib.animation import FuncAnimation
14
- from matplotlib.gridspec import GridSpec
15
- from matplotlib.patches import Circle, PathPatch
16
- from mpl_toolkits.mplot3d import Axes3D, axes3d
17
- from sklearn.decomposition import PCA
18
-
19
- warnings.filterwarnings("ignore", category=UserWarning)
20
-
21
- # file_path = "word_embeddings_mpnet.pth"
22
- # embeddings_dict = torch.load(file_path)
23
-
24
- # # %%
25
- # words = list(embeddings_dict.keys())
26
-
27
- # sentences = [[word] for word in words]
28
-
29
- # vectors = list(embeddings_dict.values())
30
- # vectors_list = []
31
- # for item in vectors:
32
- # vectors_list.append(item.tolist())
33
-
34
- # vector_list = vectors_list[:10]
35
- # # %%
36
- # # pca = PCA(n_components=3)
37
- # # pca = pca.fit(vectors_list)
38
- # # pk.dump(pca, open("pca_mpnet.pkl", "wb"))
39
- # score = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
40
-
41
-
42
- # %%
43
- def display_words(words, vector_list, score, bold):
44
- # %%
45
- plt.ioff()
46
- fig = plt.figure()
47
-
48
- ax = fig.add_subplot(111, projection="3d")
49
- plt.rcParams["image.cmap"] = "magma"
50
- colormap = cm.get_cmap("magma") # You can choose any colormap you like
51
-
52
- # Normalize the float values to the range [0, 1]
53
- score = np.array(score)
54
- norm = plt.Normalize(0, 10) # type: ignore
55
- colors = colormap(norm(score))
56
- ax.xaxis.pane.fill = False
57
- ax.yaxis.pane.fill = False
58
- ax.w_zaxis.set_pane_color(
59
- (0.87, 0.91, 0.94, 0.8)
60
- ) # Set the z-axis face color (gray)
61
- ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Transparent x-axis line
62
- ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Transparent y-axis line
63
- ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
64
-
65
- # Turn off axis labels
66
- ax.set_xticks([])
67
- ax.set_yticks([])
68
- ax.set_zticks([])
69
- ax.grid(False)
70
- # %%
71
- data_pca = vector_list
72
-
73
- if len(data_pca) > 1:
74
- # for i in range(len(data_pca) - 1):
75
- # data = np.append(
76
- # data_pca,
77
- # [norm_distance(data_pca[0], data_pca[i + 1], score[i + 1])],
78
- # axis=0,
79
- # )
80
-
81
- # Create copies of the zero-th element of data_pca
82
- data_pca0 = np.repeat(data_pca[0][None, :], len(data_pca) - 1, axis=0)
83
-
84
- # Use these arrays to construct the calls to norm_distance_v
85
- data = norm_distance_v(data_pca0, data_pca[1:], score[1:])
86
-
87
- else:
88
- data = data_pca.transpose()
89
-
90
- (
91
- x,
92
- y,
93
- z,
94
- ) = data
95
-
96
- center_x = x[0]
97
- center_y = y[0]
98
- center_z = z[0]
99
- # %%
100
- ax.autoscale(enable=True, axis="both", tight=True)
101
- # if bold == -1:
102
- # k = len(words) - 1
103
- # else:
104
- # k = repeated
105
- for i, word in enumerate(words):
106
- if i == bold:
107
- fontsize = "large"
108
- fontweight = "demibold"
109
- else:
110
- fontsize = "medium"
111
- fontweight = "normal"
112
-
113
- ax.text(
114
- x[i],
115
- y[i],
116
- z[i] + 0.05,
117
- word,
118
- fontsize=fontsize,
119
- fontweight=fontweight,
120
- alpha=1,
121
- )
122
- # ax.text(
123
- # x[0],
124
- # y[0],
125
- # z[0] + 0.05,
126
- # words[0],
127
- # fontsize="medium",
128
- # fontweight="normal",
129
- # alpha=1,
130
- # )
131
- ax.scatter(x, y, z, c="black", marker="o", s=75, cmap="magma", vmin=0, vmax=10)
132
- scatter = ax.scatter(
133
- x,
134
- y,
135
- z,
136
- marker="o",
137
- s=70,
138
- c=colors,
139
- cmap="magma",
140
- vmin=0,
141
- vmax=10,
142
- )
143
-
144
- # cax = fig.add_subplot(gs[1, :]) # cb = plt.colorbar(sc, cax=cax)
145
- # a = fig.colorbar(
146
- # mappable=scatter,
147
- # ax=ax,
148
- # cmap="magma",
149
- # norm=mpl.colors.Normalize(vmin=0, vmax=10),
150
- # orientation="horizontal",
151
- # )
152
- fig.colorbar(
153
- cm.ScalarMappable(norm=mpl.colors.Normalize(0, 10), cmap="magma"),
154
- ax=ax,
155
- orientation="horizontal",
156
- )
157
- # cbar.set_label("Score Values")
158
-
159
- def update(frame):
160
- distance = 0.5 * (score.max() - score.min())
161
- ax.set_xlim(center_x - distance, center_x + distance)
162
- ax.set_ylim(center_y - distance, center_y + distance)
163
- ax.set_zlim(center_z - distance, center_z + distance)
164
- ax.view_init(elev=20, azim=frame)
165
-
166
- # %%
167
-
168
- # Create the animation
169
- frames = np.arange(0, 360, 5)
170
- ani = FuncAnimation(fig, update, frames=frames, interval=120)
171
-
172
- ani.save("3d_rotation.gif", writer="pillow", dpi=140)
173
- plt.close(fig)
174
-
175
-
176
- # %%
177
- def norm_distance_v(orig, points, distances):
178
- # Calculate the vector AB
179
-
180
- AB = points - orig
181
-
182
- # Calculate the normalized vector AB
183
- Normalized_AB = AB / np.linalg.norm(AB, axis=1, keepdims=True)
184
-
185
- # Specify the desired distance from point A
186
- d = 10 - (distances.reshape(-1, 1) * 1)
187
-
188
- # Calculate the new points C
189
- C = orig + (Normalized_AB * d)
190
- C = np.append([orig[0]], C, axis=0)
191
-
192
- return np.array([C[:, 0], C[:, 1], C[:, 2]])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
game.py CHANGED
@@ -1,16 +1,14 @@
1
  # %%
2
  import json
3
- # import pickle as pk
4
  import random
5
- # import threading
6
  from datetime import datetime
7
- # import time
8
- # import gradio as gr
9
  import numpy as np
10
- # from display import display_words
11
  from gensim.models import KeyedVectors
12
- from pistas import curiosity, hint
13
- from seguimiento import calculate_moving_average, calculate_tendency_slope
 
 
 
14
  from sentence_transformers import SentenceTransformer
15
  import warnings
16
 
@@ -23,70 +21,60 @@ class Semantrix:
23
  "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
24
  )
25
 
26
-
27
-
28
  config_file_path = "config/lang.json"
29
  secret_file_path = "config/secret.json"
30
  data_path = "data/"
 
31
  class DictWrapper:
32
  def __init__(self, data_dict):
33
  self.__dict__.update(data_dict)
34
 
35
- def __init__(self):
36
 
37
  self.embeddings_dict = {}
38
-
39
-
40
  with open(self.config_file_path, "r") as file:
41
  self.Config_full = json.load(file)
42
 
43
  with open(self.secret_file_path, "r") as file:
44
  self.secret = json.load(file)
45
 
46
- self.lang = 0
47
 
48
- if self.lang == 0:
49
- self.Config = self.DictWrapper(self.Config_full["SPA"]["Game"])
50
- self.secret_dict = self.secret["SPA"]
51
- elif self.lang == 1:
52
  self.Config = self.DictWrapper(self.Config_full["ENG"]["Game"])
53
- secret_dict = self.secret["ENG"]
54
  else:
55
  self.Config = self.DictWrapper(self.Config_full["SPA"]["Game"])
56
  self.secret_dict = self.secret["SPA"]
57
 
58
-
59
  with open(self.data_path + "ranking.txt", "w+") as file:
60
  file.write("---------------------------")
61
 
62
- # pca = pk.load(open("pca_mpnet.pkl", "rb"))
63
-
64
- # print(Config.Difficulty_presentation_Full)
65
- # difficulty = int(input(Config.Difficulty + ": "))
66
-
67
- def prepare_game(self,difficulty):
68
- # global secret, secret_list, words, scores, word_vect, thread, win, n, recent_hint, f_dev_avg, last_hint
69
 
70
- self.secret_list = self.secret_dict["basic"] if difficulty <= 2 else self.secret_dict["advanced"]
 
 
 
 
71
 
72
  self.secret = self.secret_list.pop(random.randint(0, len(self.secret_list) - 1))
73
  self.secret = self.secret.lower()
74
 
75
-
76
  self.words = [self.Config.secret_word]
77
  self.scores = [10]
78
 
79
  if self.secret not in self.embeddings_dict.keys():
80
- self.embeddings_dict[self.secret] = self.model_st.encode(self.secret, convert_to_tensor=True)
81
- self.model.add_vector(self.secret, self.embeddings_dict[self.secret].tolist())
 
 
 
 
82
 
83
  self.word_vect = [self.embeddings_dict[self.secret].tolist()]
84
 
85
- # thread = threading.Thread(
86
- # target=display_words, args=(words, pca.transform(word_vect), scores, -1)
87
- # )
88
- # thread.start()
89
-
90
  self.win = False
91
  self.n = 0
92
  self.recent_hint = 0
@@ -97,8 +85,7 @@ class Semantrix:
97
  if self.difficulty == 1:
98
  self.n = 3
99
 
100
-
101
- def preproc_vectors(self,repeated):
102
  ascending_indices = np.argsort(self.scores)
103
  descending_indices = list(ascending_indices[::-1])
104
  ranking_data = []
@@ -118,47 +105,41 @@ class Semantrix:
118
  for item in ranking_data:
119
  file.write("%s\n" % item)
120
 
121
- if len(self.words) > 11:
122
- if k in descending_indices[:11]:
123
- descending_indices = descending_indices[:11]
124
- else:
125
- descending_indices = descending_indices[:11]
126
- descending_indices.append(k)
127
- words_display = [self.words[i] for i in descending_indices]
128
- # displayvect_display = pca.transform([word_vect[i] for i in descending_indices])
129
- scores_display = [self.scores[i] for i in descending_indices]
130
- bold = descending_indices.index(k)
131
-
132
- else:
133
- words_display = self.words
134
- # displayvect_display = pca.transform(word_vect)
135
- scores_display = self.scores
136
- bold = k
137
-
138
- return (
139
- words_display,
140
- # displayvect_display,
141
- scores_display,
142
- bold,
143
- )
144
-
145
-
146
-
147
-
148
 
149
- def play_game(self,word):
150
- # global win, n, recent_hint, f_dev_avg, last_hint, words, word_vect, scores, thread
151
 
152
  word = word.lower()
153
  if word == "give_up":
154
  text = (
155
- "[win]"
156
- +
157
- self.Config.Feedback_9
158
- + self.secret
159
- + "\n\n"
160
- + self.Config.Feedback_10
161
- )
162
  return text
163
 
164
  if word in self.words:
@@ -167,19 +148,15 @@ class Semantrix:
167
  repeated = -1
168
  self.words.append(word)
169
 
170
- # thread.join()
171
-
172
  if word not in self.embeddings_dict.keys():
173
  embedding = self.model_st.encode(word, convert_to_tensor=True)
174
  self.embeddings_dict[word] = embedding
175
  self.model.add_vector(word, embedding.tolist())
176
 
177
- if repeated == -1:
178
- self.word_vect.append(self.embeddings_dict[word].tolist())
179
-
180
  score = round(self.model.similarity(self.secret, word) * 10, 2)
181
 
182
  if repeated == -1:
 
183
  self.scores.append(score)
184
 
185
  if score <= 2.5:
@@ -223,9 +200,9 @@ class Semantrix:
223
  self.last_hint,
224
  self.lang,
225
  (
226
- self.DictWrapper(self.Config_full["SPA"]["Hint"])
227
- if self.lang == 0
228
- else self.DictWrapper(self.Config_full["ENG"]["Hint"])
229
  ),
230
  )
231
  feedback += "\n" + hint_text
@@ -234,25 +211,14 @@ class Semantrix:
234
  if self.recent_hint != 0:
235
  self.recent_hint -= 1
236
 
237
- (
238
- words_display,
239
- scores_display,
240
- bold_display,
241
- ) = self.preproc_vectors(repeated)
242
 
243
- feedback += "[rank]" + open(self.data_path + "ranking.txt", "r").read()
244
 
245
  if self.win:
246
  bold_display = 0
247
 
248
- # thread = threading.Thread(
249
- # target=display_words,
250
- # args=(words_display, displayvect_display, scores_display, bold_display),
251
- # )
252
- # thread.start()
253
-
254
  if self.win:
255
- # feedback += "\nCongratulations! You guessed the secret word."
256
 
257
  with open(self.data_path + "ranking.txt", "r") as original_file:
258
  file_content = original_file.readlines()
@@ -262,11 +228,17 @@ class Semantrix:
262
  with open(self.data_path + "plays/" + new_file_name, "w+") as new_file:
263
  new_file.writelines(file_content[2:])
264
 
265
-
266
  return feedback
267
-
268
  def curiosity(self):
269
 
270
- feedback = curiosity(self.secret, self.DictWrapper(self.Config_full["SPA"]["Hint"]))
271
-
 
 
 
 
 
 
 
272
  return feedback
 
1
  # %%
2
  import json
 
3
  import random
 
4
  from datetime import datetime
 
 
5
  import numpy as np
 
6
  from gensim.models import KeyedVectors
7
+ from hints import curiosity, hint
8
+ from tracking import (
9
+ calculate_moving_average,
10
+ calculate_tendency_slope,
11
+ )
12
  from sentence_transformers import SentenceTransformer
13
  import warnings
14
 
 
21
  "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
22
  )
23
 
 
 
24
  config_file_path = "config/lang.json"
25
  secret_file_path = "config/secret.json"
26
  data_path = "data/"
27
+
28
  class DictWrapper:
29
  def __init__(self, data_dict):
30
  self.__dict__.update(data_dict)
31
 
32
+ def __init__(self, lang=0):
33
 
34
  self.embeddings_dict = {}
35
+
 
36
  with open(self.config_file_path, "r") as file:
37
  self.Config_full = json.load(file)
38
 
39
  with open(self.secret_file_path, "r") as file:
40
  self.secret = json.load(file)
41
 
42
+ self.lang = lang
43
 
44
+ if self.lang == 1:
 
 
 
45
  self.Config = self.DictWrapper(self.Config_full["ENG"]["Game"])
46
+ self.secret_dict = self.secret["ENG"]
47
  else:
48
  self.Config = self.DictWrapper(self.Config_full["SPA"]["Game"])
49
  self.secret_dict = self.secret["SPA"]
50
 
 
51
  with open(self.data_path + "ranking.txt", "w+") as file:
52
  file.write("---------------------------")
53
 
54
+ def prepare_game(self, difficulty):
 
 
 
 
 
 
55
 
56
+ self.secret_list = (
57
+ self.secret_dict["basic"]
58
+ if difficulty <= 2
59
+ else self.secret_dict["advanced"]
60
+ )
61
 
62
  self.secret = self.secret_list.pop(random.randint(0, len(self.secret_list) - 1))
63
  self.secret = self.secret.lower()
64
 
 
65
  self.words = [self.Config.secret_word]
66
  self.scores = [10]
67
 
68
  if self.secret not in self.embeddings_dict.keys():
69
+ self.embeddings_dict[self.secret] = self.model_st.encode(
70
+ self.secret, convert_to_tensor=True
71
+ )
72
+ self.model.add_vector(
73
+ self.secret, self.embeddings_dict[self.secret].tolist()
74
+ )
75
 
76
  self.word_vect = [self.embeddings_dict[self.secret].tolist()]
77
 
 
 
 
 
 
78
  self.win = False
79
  self.n = 0
80
  self.recent_hint = 0
 
85
  if self.difficulty == 1:
86
  self.n = 3
87
 
88
+ def preproc_vectors(self, repeated):
 
89
  ascending_indices = np.argsort(self.scores)
90
  descending_indices = list(ascending_indices[::-1])
91
  ranking_data = []
 
105
  for item in ranking_data:
106
  file.write("%s\n" % item)
107
 
108
+ # if len(self.words) > 11:
109
+ # if k in descending_indices[:11]:
110
+ # descending_indices = descending_indices[:11]
111
+ # else:
112
+ # descending_indices = descending_indices[:11]
113
+ # descending_indices.append(k)
114
+ # words_display = [self.words[i] for i in descending_indices]
115
+ # # displayvect_display = pca.transform([word_vect[i] for i in descending_indices])
116
+ # scores_display = [self.scores[i] for i in descending_indices]
117
+ # bold = descending_indices.index(k)
118
+
119
+ # else:
120
+ # words_display = self.words
121
+ # # displayvect_display = pca.transform(word_vect)
122
+ # scores_display = self.scores
123
+ # bold = k
124
+
125
+ # return (
126
+ # words_display,
127
+ # # displayvect_display,
128
+ # scores_display,
129
+ # bold,
130
+ # )
 
 
 
 
131
 
132
+ def play_game(self, word):
 
133
 
134
  word = word.lower()
135
  if word == "give_up":
136
  text = (
137
+ "[lose]"
138
+ + self.Config.Feedback_9
139
+ + self.secret
140
+ + "\n\n"
141
+ + self.Config.Feedback_10
142
+ )
 
143
  return text
144
 
145
  if word in self.words:
 
148
  repeated = -1
149
  self.words.append(word)
150
 
 
 
151
  if word not in self.embeddings_dict.keys():
152
  embedding = self.model_st.encode(word, convert_to_tensor=True)
153
  self.embeddings_dict[word] = embedding
154
  self.model.add_vector(word, embedding.tolist())
155
 
 
 
 
156
  score = round(self.model.similarity(self.secret, word) * 10, 2)
157
 
158
  if repeated == -1:
159
+ self.word_vect.append(self.embeddings_dict[word].tolist())
160
  self.scores.append(score)
161
 
162
  if score <= 2.5:
 
200
  self.last_hint,
201
  self.lang,
202
  (
203
+ self.DictWrapper(self.Config_full["ENG"]["Hint"])
204
+ if self.lang == 1
205
+ else self.DictWrapper(self.Config_full["SPA"]["Hint"])
206
  ),
207
  )
208
  feedback += "\n" + hint_text
 
211
  if self.recent_hint != 0:
212
  self.recent_hint -= 1
213
 
214
+ self.preproc_vectors(repeated)
 
 
 
 
215
 
216
+ feedback += "[rank]" + open(self.data_path + "ranking.txt", "r").read()
217
 
218
  if self.win:
219
  bold_display = 0
220
 
 
 
 
 
 
 
221
  if self.win:
 
222
 
223
  with open(self.data_path + "ranking.txt", "r") as original_file:
224
  file_content = original_file.readlines()
 
228
  with open(self.data_path + "plays/" + new_file_name, "w+") as new_file:
229
  new_file.writelines(file_content[2:])
230
 
 
231
  return feedback
232
+
233
  def curiosity(self):
234
 
235
+ feedback = curiosity(
236
+ self.secret,
237
+ (
238
+ self.DictWrapper(self.Config_full["ENG"]["Hint"])
239
+ if self.lang == 1
240
+ else self.DictWrapper(self.Config_full["SPA"]["Hint"])
241
+ ),
242
+ )
243
+
244
  return feedback
game_word2vec.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import json
3
+ import random
4
+ from datetime import datetime
5
+ import numpy as np
6
+ from gensim.models import KeyedVectors
7
+ from hints import curiosity, hint
8
+ from tracking import (
9
+ calculate_moving_average,
10
+ calculate_tendency_slope,
11
+ )
12
+ from sentence_transformers import SentenceTransformer
13
+ import warnings
14
+
15
+ warnings.filterwarnings(action="ignore", category=UserWarning, module="gensim")
16
+
17
+
18
+ class Semantrix:
19
+
20
+ model_st = SentenceTransformer(
21
+ "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
22
+ )
23
+
24
+ config_file_path = "config/lang.json"
25
+
26
+ secret_file_path = "config/secret.json"
27
+
28
+ data_path = "data/"
29
+
30
+ class DictWrapper:
31
+ def __init__(self, data_dict):
32
+ self.__dict__.update(data_dict)
33
+
34
+ def __init__(self, lang=0):
35
+
36
+ self.lang = lang
37
+
38
+ self.embeddings_dict = {}
39
+
40
+ with open(self.config_file_path, "r") as file:
41
+ self.Config_full = json.load(file)
42
+
43
+ with open(self.secret_file_path, "r") as file:
44
+ self.secret = json.load(file)
45
+
46
+ if self.lang == 1:
47
+ self.model = KeyedVectors.load("config/w2v_models/eng_w2v_model", mmap="r")
48
+ self.Config = self.DictWrapper(self.Config_full["ENG"]["Game"])
49
+ self.secret_dict = self.secret["ENG"]
50
+ else:
51
+ self.model = KeyedVectors.load("config/w2v_models/esp_w2v_model", mmap="r")
52
+ self.Config = self.DictWrapper(self.Config_full["SPA"]["Game"])
53
+ self.secret_dict = self.secret["SPA"]
54
+
55
+ with open(self.data_path + "ranking.txt", "w+") as file:
56
+ file.write("---------------------------")
57
+
58
+ def prepare_game(self, difficulty):
59
+
60
+ self.secret_list = (
61
+ self.secret_dict["basic"]
62
+ if difficulty <= 2
63
+ else self.secret_dict["advanced"]
64
+ )
65
+
66
+ self.secret = self.secret_list.pop(random.randint(0, len(self.secret_list) - 1))
67
+ self.secret = self.secret.lower()
68
+
69
+ self.words = [self.Config.secret_word]
70
+ self.scores = [10]
71
+
72
+ if self.secret not in self.embeddings_dict.keys():
73
+ self.embeddings_dict[self.secret] = self.model[self.secret]
74
+
75
+ self.word_vect = [self.embeddings_dict[self.secret].tolist()]
76
+
77
+ self.win = False
78
+ self.n = 0
79
+ self.recent_hint = 0
80
+ self.f_dev_avg = 0
81
+ self.last_hint = -1
82
+ self.difficulty = difficulty
83
+
84
+ if self.difficulty == 1:
85
+ self.n = 3
86
+
87
+ def preproc_vectors(self, repeated):
88
+ ascending_indices = np.argsort(self.scores)
89
+ descending_indices = list(ascending_indices[::-1])
90
+ ranking_data = []
91
+ k = len(self.words) - 1
92
+ if repeated != -1:
93
+ k = repeated
94
+
95
+ ranking_data.append(["#" + str(k), self.words[k], self.scores[k]])
96
+
97
+ ranking_data.append("---------------------------")
98
+ for i in descending_indices:
99
+ if i == 0:
100
+ continue
101
+ ranking_data.append(["#" + str(i), self.words[i], self.scores[i]])
102
+
103
+ with open(self.data_path + "ranking.txt", "w+") as file:
104
+ for item in ranking_data:
105
+ file.write("%s\n" % item)
106
+
107
+ # if len(self.words) > 11:
108
+ # if k in descending_indices[:11]:
109
+ # descending_indices = descending_indices[:11]
110
+ # else:
111
+ # descending_indices = descending_indices[:11]
112
+ # descending_indices.append(k)
113
+ # words_display = [self.words[i] for i in descending_indices]
114
+ # scores_display = [self.scores[i] for i in descending_indices]
115
+ # bold = descending_indices.index(k)
116
+
117
+ # else:
118
+ # words_display = self.words
119
+ # scores_display = self.scores
120
+ # bold = k
121
+
122
+ # return (
123
+ # words_display,
124
+ # scores_display,
125
+ # bold,
126
+ # )
127
+
128
+ def play_game(self, word):
129
+
130
+ word = word.lower()
131
+ if word == "give_up":
132
+ text = (
133
+ "[lose]"
134
+ + self.Config.Feedback_9
135
+ + self.secret
136
+ + "\n\n"
137
+ + self.Config.Feedback_10
138
+ )
139
+ return text
140
+
141
+ if word in self.words:
142
+ repeated = self.words.index(word)
143
+ else:
144
+ repeated = -1
145
+ self.words.append(word)
146
+
147
+ if word not in self.embeddings_dict.keys():
148
+ if word not in self.model.key_to_index.keys():
149
+ self.words.pop(len(self.words) - 1)
150
+ feedback = (
151
+ "I don't know that word. Try again."
152
+ if self.lang == 1
153
+ else "No conozco esa palabra. Inténtalo de nuevo."
154
+ )
155
+ feedback += "[rank]" + open(self.data_path + "ranking.txt", "r").read()
156
+
157
+ return feedback
158
+
159
+ embedding = self.model[word]
160
+ self.embeddings_dict[word] = embedding
161
+
162
+ score = round(self.model.similarity(self.secret, word) * 10, 2)
163
+
164
+ if repeated == -1:
165
+ self.word_vect.append(self.embeddings_dict[word].tolist())
166
+ self.scores.append(score)
167
+
168
+ if score <= 2.5:
169
+ feedback = self.Config.Feedback_0 + str(score)
170
+ elif score > 2.5 and score <= 4.0:
171
+ feedback = self.Config.Feedback_1 + str(score)
172
+ elif score > 4.0 and score <= 6.0:
173
+ feedback = self.Config.Feedback_2 + str(score)
174
+ elif score > 6.0 and score <= 7.5:
175
+ feedback = self.Config.Feedback_3 + str(score)
176
+ elif score > 7.5 and score <= 8.0:
177
+ feedback = self.Config.Feedback_4 + str(score)
178
+ elif score > 8.0 and score < 10.0:
179
+ feedback = self.Config.Feedback_5 + str(score)
180
+ else:
181
+ self.win = True
182
+ feedback = "[win]" + self.Config.Feedback_8
183
+ self.words[0] = self.secret
184
+ self.words.pop(len(self.words) - 1)
185
+ self.word_vect.pop(len(self.word_vect) - 1)
186
+ self.scores.pop(len(self.scores) - 1)
187
+
188
+ if score > self.scores[len(self.scores) - 2] and self.win == False:
189
+ feedback += "\n" + self.Config.Feedback_6
190
+ elif score < self.scores[len(self.scores) - 2] and self.win == False:
191
+ feedback += "\n" + self.Config.Feedback_7
192
+
193
+ if self.difficulty != 4:
194
+ mov_avg = calculate_moving_average(self.scores[1:], 5)
195
+
196
+ if len(mov_avg) > 1 and self.win == False:
197
+ f_dev = calculate_tendency_slope(mov_avg)
198
+ f_dev_avg = calculate_moving_average(f_dev, 3)
199
+ if f_dev_avg[len(f_dev_avg) - 1] < 0 and self.recent_hint == 0:
200
+ i = random.randint(0, len(self.Config.hint_intro) - 1)
201
+ feedback += "\n\n[hint]" + self.Config.hint_intro[i]
202
+ hint_text, self.n, self.last_hint = hint(
203
+ self.secret,
204
+ self.n,
205
+ self.model_st,
206
+ self.last_hint,
207
+ self.lang,
208
+ (
209
+ self.DictWrapper(self.Config_full["ENG"]["Hint"])
210
+ if self.lang == 1
211
+ else self.DictWrapper(self.Config_full["SPA"]["Hint"])
212
+ ),
213
+ )
214
+ feedback += "\n" + hint_text
215
+ self.recent_hint = 3
216
+
217
+ if self.recent_hint != 0:
218
+ self.recent_hint -= 1
219
+
220
+ self.preproc_vectors(repeated)
221
+
222
+ feedback += "[rank]" + open(self.data_path + "ranking.txt", "r").read()
223
+
224
+ if self.win:
225
+ bold_display = 0
226
+
227
+ if self.win:
228
+
229
+ with open(self.data_path + "ranking.txt", "r") as original_file:
230
+ file_content = original_file.readlines()
231
+
232
+ new_file_name = self.secret + "_" + str(datetime.now())
233
+
234
+ with open(self.data_path + "plays/" + new_file_name, "w+") as new_file:
235
+ new_file.writelines(file_content[2:])
236
+
237
+ return feedback
238
+
239
+ def curiosity(self):
240
+
241
+ feedback = curiosity(
242
+ self.secret,
243
+ (
244
+ self.DictWrapper(self.Config_full["ENG"]["Hint"])
245
+ if self.lang == 1
246
+ else self.DictWrapper(self.Config_full["SPA"]["Hint"])
247
+ ),
248
+ )
249
+
250
+ return feedback
pistas.py → hints.py RENAMED
@@ -194,7 +194,7 @@ def hint(secret, n, model, last_pista, lang, Config):
194
  presence_penalty=0,
195
  )
196
  output = str(response.choices[0].message.content)
197
- pista += Config.hint_4_4 + film_title + "\n" + output # type: ignore
198
  last_pista = 4
199
 
200
  return pista, n + 1, last_pista
 
194
  presence_penalty=0,
195
  )
196
  output = str(response.choices[0].message.content)
197
+ pista += Config.hint_4_4 + "\n" + output # type: ignore
198
  last_pista = 4
199
 
200
  return pista, n + 1, last_pista
juego_embbedings_chat.py DELETED
@@ -1,371 +0,0 @@
1
- # %%
2
- import json
3
- import pickle as pk
4
- import random
5
- import threading
6
- from datetime import datetime
7
- import time
8
- import gradio as gr
9
- import numpy as np
10
- from display import display_words
11
- from gensim.models import KeyedVectors
12
- from pistas import curiosity, hint
13
- from seguimiento import calculate_moving_average, calculate_tendency_slope
14
- from sentence_transformers import SentenceTransformer
15
-
16
- model = KeyedVectors(768)
17
- model_st = SentenceTransformer(
18
- "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
19
- )
20
-
21
- embeddings_dict = {}
22
-
23
- config_file_path = "config/lang.json"
24
- secret_file_path = "config/secret.json"
25
-
26
-
27
- class DictWrapper:
28
- def __init__(self, data_dict):
29
- self.__dict__.update(data_dict)
30
-
31
-
32
- with open(config_file_path, "r") as file:
33
- Config_full = json.load(file)
34
-
35
- with open(secret_file_path, "r") as file:
36
- secret = json.load(file)
37
-
38
- lang = 0
39
-
40
- if lang == 0:
41
- Config = DictWrapper(Config_full["SPA"]["Game"])
42
- secret_dict = secret["SPA"]
43
- elif lang == 1:
44
- Config = DictWrapper(Config_full["ENG"]["Game"])
45
- secret_dict = secret["ENG"]
46
- else:
47
- Config = DictWrapper(Config_full["SPA"]["Game"])
48
- secret_dict = secret["SPA"]
49
-
50
-
51
- with open("ranking.txt", "w+") as file:
52
- file.write("---------------------------")
53
-
54
- pca = pk.load(open("pca_mpnet.pkl", "rb"))
55
-
56
- # print(Config.Difficulty_presentation_Full)
57
- # difficulty = int(input(Config.Difficulty + ": "))
58
- difficulty = -1
59
-
60
- def prepare_game(difficulty):
61
- global secret, secret_list, words, scores, word_vect, thread, win, n, recent_hint, f_dev_avg, last_hint
62
-
63
- secret_list = secret_dict["basic"] if difficulty <= 2 else secret_dict["advanced"]
64
-
65
- secret = secret_list.pop(random.randint(0, len(secret_list) - 1))
66
- secret = secret.lower()
67
-
68
- words = [Config.secret_word]
69
- scores = [10]
70
-
71
- if secret not in embeddings_dict.keys():
72
- embeddings_dict[secret] = model_st.encode(secret, convert_to_tensor=True)
73
- model.add_vector(secret, embeddings_dict[secret].tolist())
74
-
75
- word_vect = [embeddings_dict[secret].tolist()]
76
-
77
- thread = threading.Thread(
78
- target=display_words, args=(words, pca.transform(word_vect), scores, -1)
79
- )
80
- thread.start()
81
-
82
- win = False
83
- n = 0
84
- recent_hint = 0
85
- f_dev_avg = 0
86
- last_hint = -1
87
-
88
- if difficulty == 1:
89
- n = 3
90
-
91
-
92
- def preproc_vectors(words, word_vect, scores, repeated):
93
- ascending_indices = np.argsort(scores)
94
- descending_indices = list(ascending_indices[::-1])
95
- ranking_data = []
96
- k = len(words) - 1
97
- if repeated != -1:
98
- k = repeated
99
-
100
- ranking_data.append(["#" + str(k), words[k], scores[k]])
101
-
102
- ranking_data.append("---------------------------")
103
- for i in descending_indices:
104
- if i == 0:
105
- continue
106
- ranking_data.append(["#" + str(i), words[i], scores[i]])
107
-
108
- with open("ranking.txt", "w+") as file:
109
- for item in ranking_data:
110
- file.write("%s\n" % item)
111
-
112
- if len(words) > 11:
113
- if k in descending_indices[:11]:
114
- descending_indices = descending_indices[:11]
115
- else:
116
- descending_indices = descending_indices[:11]
117
- descending_indices.append(k)
118
- words_display = [words[i] for i in descending_indices]
119
- displayvect_display = pca.transform([word_vect[i] for i in descending_indices])
120
- scores_display = [scores[i] for i in descending_indices]
121
- bold = descending_indices.index(k)
122
-
123
- else:
124
- words_display = words
125
- displayvect_display = pca.transform(word_vect)
126
- scores_display = scores
127
- bold = k
128
-
129
- return (
130
- words_display,
131
- displayvect_display,
132
- scores_display,
133
- bold,
134
- )
135
-
136
-
137
-
138
-
139
-
140
- def play_game(word):
141
- global win, n, recent_hint, f_dev_avg, last_hint, words, word_vect, scores, thread
142
-
143
- word = word.lower()
144
- if word == "give_up":
145
- return "Game Over"
146
-
147
- if word in words:
148
- repeated = words.index(word)
149
- else:
150
- repeated = -1
151
- words.append(word)
152
-
153
- thread.join()
154
-
155
- if word not in embeddings_dict.keys():
156
- embedding = model_st.encode(word, convert_to_tensor=True)
157
- embeddings_dict[word] = embedding
158
- model.add_vector(word, embedding.tolist())
159
-
160
- if repeated == -1:
161
- word_vect.append(embeddings_dict[word].tolist())
162
-
163
- score = round(model.similarity(secret, word) * 10, 2)
164
-
165
- if repeated == -1:
166
- scores.append(score)
167
-
168
- if score <= 2.5:
169
- feedback = Config.Feedback_0 + str(score)
170
- elif score > 2.5 and score <= 4.0:
171
- feedback = Config.Feedback_1 + str(score)
172
- elif score > 4.0 and score <= 6.0:
173
- feedback = Config.Feedback_2 + str(score)
174
- elif score > 6.0 and score <= 7.5:
175
- feedback = Config.Feedback_3 + str(score)
176
- elif score > 7.5 and score <= 8.0:
177
- feedback = Config.Feedback_4 + str(score)
178
- elif score > 8.0 and score < 10.0:
179
- feedback = Config.Feedback_5 + str(score)
180
- else:
181
- win = True
182
- feedback = Config.Feedback_8
183
- words[0] = secret
184
- words.pop(len(words) - 1)
185
- word_vect.pop(len(word_vect) - 1)
186
- scores.pop(len(scores) - 1)
187
-
188
- if score > scores[len(scores) - 2] and win == False:
189
- feedback += "\n" + Config.Feedback_6
190
- elif score < scores[len(scores) - 2] and win == False:
191
- feedback += "\n" + Config.Feedback_7
192
-
193
- if difficulty != 4:
194
- mov_avg = calculate_moving_average(scores[1:], 5)
195
-
196
- if len(mov_avg) > 1 and win == False:
197
- f_dev = calculate_tendency_slope(mov_avg)
198
- f_dev_avg = calculate_moving_average(f_dev, 3)
199
- if f_dev_avg[len(f_dev_avg) - 1] < 0 and recent_hint == 0:
200
- i = random.randint(0, len(Config.hint_intro) - 1)
201
- feedback += "\n\n" + Config.hint_intro[i]
202
- hint_text, n, last_hint = hint(
203
- secret,
204
- n,
205
- model_st,
206
- last_hint,
207
- lang,
208
- (
209
- DictWrapper(Config_full["SPA"]["Hint"])
210
- if lang == 0
211
- else DictWrapper(Config_full["ENG"]["Hint"])
212
- ),
213
- )
214
- feedback += "\n" + hint_text
215
- recent_hint = 3
216
-
217
- if recent_hint != 0:
218
- recent_hint -= 1
219
-
220
- (
221
- words_display,
222
- displayvect_display,
223
- scores_display,
224
- bold_display,
225
- ) = preproc_vectors(words, word_vect, scores, repeated)
226
-
227
- if win:
228
- bold_display = 0
229
-
230
- thread = threading.Thread(
231
- target=display_words,
232
- args=(words_display, displayvect_display, scores_display, bold_display),
233
- )
234
- thread.start()
235
-
236
- if win:
237
- feedback += "\nCongratulations! You guessed the secret word."
238
-
239
- return feedback
240
-
241
-
242
-
243
- i = -1
244
-
245
- with gr.Blocks() as demo:
246
- gr.Markdown(
247
- """
248
- <p style="text-align:center"> SEMANTRIX: JUEGO DE LA ADIVINANZA SEMÁNTICA </p>
249
- """
250
- )
251
- lang = {
252
- "Introduction_0": "Bienvenido a Semantrix, el emocionante Juego de la Adivinanza Semántica.",
253
- "Introduction_1": "¿Quieres saber cómo se juega?",
254
- "Rules_1": "Tu misión es adivinar una palabra secreta que yo he escogido, pero no te preocupes, te ayudaré en el camino. \n\nLanza al aire la primera palabra que se te ocurra. Te daré pistas diciéndote si estás caliente, es decir muy cerca de adivinarla o frío, es decir, muy lejos de la palabra.",
255
- "Rules_3": "Adicionalmente, Cada palabra que propongas recibirá una puntuación entre 0 y 10, un puntaje alto significa que estás muy cerca de adivinar la palabra secreta\n\nSi veo que estás un poco perdido, estaré aquí para darte pistas que te ayudarán a acercarte a la palabra secreta.",
256
- "Rules_5": "Como ayuda extra, mostraré un ranking de todas las palabras que has propuesto, ordenadas según su puntuación. Así podrás tener una idea mejor de qué tan cerca están y qué palabras funcionan mejor.",
257
- "Rules_6": "Serás el ganador cuando adivines correctamente la palabra secreta. ¡No desistas, lo tienes al alcance!\n\nAsí que, ¡enciende tu mente, confía en tus ideas y por sobre todo, pasa un buen rato! Este es un juego en el que cada palabra, cada puntuación y cada pista te acerca a tu victoria. ¡Mucha suerte!",
258
- "Difficulty_presentation_Full": "En este emocionante desafío de adivinanza semántica, puedes elegir cuán grande quieres que sea el reto. Aquí te presento los niveles de dificultad:\n\nFácil: ¡Es hora de calentar motores! En este nivel, te daré pistas evidentes para que puedas adivinar la palabra secreta de manera más rápida. Si estás comenzando a jugar o simplemente quieres pasar un buen rato sin mucha presión, ¡este es tu nivel!\n\nNormal: Aquí es donde las cosas comienzan a ponerse interesantes. En este nivel, solo te daré pistas cuando te vea muy perdido. Es bueno para aquellos jugadores que quieren un reto, pero sin ser tan duros consigo mismos.\n\nDifícil: ¿Listo para un verdadero desafío? En este nivel, te ayudaré solo cuando te vea realmente perdido, y prepárate, porque las palabras pueden llegar a ser más complejas. Para esos pensadores agudos que les encanta una buena cabeza rompecabezas.\n\nExperto: ¿Eres un maestro de las palabras? Este es el camino menos transitado, para aquellos campeones de la semántica que buscan la pura adrenalina del reto. No te daré ninguna pista y las palabras serán complejas. Aquí es donde puedes demostrar tu verdadero poder.\n\nRecuerda, ganes o pierdas, cada nivel está diseñado para hacerte disfrutar y mejorar tus habilidades de adivinanza y comprensión de las palabras. ¡Escoge tu nivel y empieza a jugar!",
259
- "Difficulty": "Elige tu nivel de dificultad",
260
- "New_word": "Nueva palabra: ",
261
- "Feedback_0": "Helado, puntuación: ",
262
- "Feedback_1": "Frío, puntuación: ",
263
- "Feedback_2": "Templado, puntuación: ",
264
- "Feedback_3": "Caliente, puntuación: ",
265
- "Feedback_4": "Quemando, puntuación: ",
266
- "Feedback_5": "Ardiendo, puntuación: ",
267
- "Feedback_6": "Te estás acercando",
268
- "Feedback_7": "Te estás alejando",
269
- "Feedback_8": "¡Has ganado, ENHORABUENA!",
270
- "Feedback_9": "La palabra secreta era: ",
271
- "Feedback_10": "Aunque no fue una victoria esta vez, ¡no temas! ¡Cada intento es una nueva oportunidad para brillar! ¡Sigue adelante!",
272
- "secret_word": "PALABRA SECRETA",
273
- "hint_intro": [
274
- "Parece que las palabras están jugando al escondite contigo. ¿Necesitas una ayudita? Aquí va una pista:",
275
- "¡Vamos, estás tan cerca de descifrar el enigma semántico! Pero si sientes que te falta un empujón, aquí tienes una pista:",
276
- "Tu mente está explorando este campo semántico como un detective, ¡pero incluso los detectives a veces necesitan pistas extra! Así que, aquí va una para ti:",
277
- "El camino semántico puede volverse un poco sinuoso a veces. No te preocupes, estoy aquí para allanar el camino con una pista:",
278
- "Las palabras son como piezas de un rompecabezas, y sé que estás cerca de completar la imagen. Aquí va una pista para encajar las piezas restantes:",
279
- "Estás navegando por las aguas semánticas con destreza, ¡pero incluso los capitanes expertos pueden necesitar un faro de vez en cuando! Aquí está tu faro, tu pista:",
280
- "La danza de las palabras puede ser complicada, pero no te preocupes, estoy aquí para ser tu guía de baile. Aquí tienes una pista para que sigas moviéndote con gracia:",
281
- ],
282
- }
283
-
284
- def reset():
285
- global i
286
- i = -1
287
- return gr.Textbox(visible=False, placeholder=lang[list(lang.keys())[0]], min_width=15),gr.Textbox(visible=False),gr.Image(interactive=False, visible=False),gr.Button("Empezar"),gr.Radio(["SÍ", "NO"], visible=False)
288
- def change(radio):
289
- global i
290
- i = i + 1
291
- if i == 2 and radio == "NO":
292
- i = 7
293
- # txt=gr.Textbox(lang[list(lang.keys())[i]],visible=True,label='')
294
- # else:
295
- txt = gr.Textbox(lang[list(lang.keys())[i]], visible=True, label="")
296
- return txt
297
-
298
- def button_name(radio):
299
- global i, difficulty
300
- output = []
301
- if i == 1:
302
- output.extend(
303
- [
304
- gr.Button("Si", visible=False),
305
- gr.Radio(["SÍ", "NO"], label="", visible=True),
306
- ]
307
- )
308
- elif i == 2:
309
- if radio == "NO":
310
- output.extend(
311
- [
312
- gr.Button("Introducir", visible=True),
313
- gr.Radio(["SÍ", "NO"], visible=False),
314
- ]
315
- )
316
- else:
317
- output.extend(
318
- [
319
- gr.Button("Siguiente", visible=True),
320
- gr.Radio(["SÍ", "NO"], visible=False),
321
- ]
322
- )
323
- elif i == 7:
324
- output.extend(
325
- [
326
- gr.Button("Siguiente", visible=False),
327
- gr.Radio(["Fácil", "Normal", "Dificil", "Experto"], visible=True),
328
- ]
329
- )
330
- elif i == 8:
331
- if radio == "Fácil":
332
- difficulty = 1
333
- elif radio == "Normal":
334
- difficulty = 2
335
- elif radio == "Dificil":
336
- difficulty = 3
337
- else:
338
- difficulty = 4
339
- output.extend(
340
- [
341
- gr.Button("Empezar", visible=True),
342
- gr.Radio(["Fácil", "Normal", "Dificil", "Experto"], visible=False),
343
- ]
344
- )
345
- print(difficulty)
346
- else:
347
- output.extend(
348
- [
349
- gr.Button("Siguiente", visible=True),
350
- gr.Radio(["SÍ", "NO"], label="", visible=False),
351
- ]
352
- )
353
- return output
354
-
355
- img = gr.Image(interactive=False, visible=False)
356
- out = gr.Textbox(
357
- visible=False, placeholder=lang[list(lang.keys())[0]], min_width=15
358
- )
359
- radio = gr.Radio(["SÍ", "NO"], visible=False)
360
- with gr.Row():
361
- inp = gr.Textbox(visible=False)
362
- but = gr.Button("Empezar")
363
-
364
- but.click(change, inputs=radio, outputs=out)
365
- radio.input(change, inputs=radio, outputs=out)
366
- demo.load(reset,outputs=[out,inp,img, but, radio])
367
- out.change(button_name, inputs=radio, outputs=[but, radio])
368
-
369
-
370
- if __name__ == "__main__":
371
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
juego_embbedings_text_config.py DELETED
@@ -1,252 +0,0 @@
1
- # %%
2
- import json
3
- import pickle as pk
4
- import random
5
- import threading
6
- from datetime import datetime
7
-
8
- import gradio as gr
9
- import numpy as np
10
- from display import display_words
11
- from gensim.models import KeyedVectors
12
- from pistas import curiosity, hint
13
- from seguimiento import calculate_moving_average, calculate_tendency_slope
14
- from sentence_transformers import SentenceTransformer
15
-
16
- model = KeyedVectors(768)
17
- model_st = SentenceTransformer(
18
- "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
19
- )
20
-
21
- embeddings_dict = {}
22
-
23
- config_file_path = "config/lang.json"
24
- secret_file_path = "config/secret.json"
25
-
26
-
27
- class DictWrapper:
28
- def __init__(self, data_dict):
29
- self.__dict__.update(data_dict)
30
-
31
-
32
- with open(config_file_path, "r") as file:
33
- Config_full = json.load(file)
34
-
35
- with open(secret_file_path, "r") as file:
36
- secret = json.load(file)
37
-
38
- lang = 0
39
-
40
- if lang == 0:
41
- Config = DictWrapper(Config_full["SPA"]["Game"])
42
- secret_dict = secret["SPA"]
43
- elif lang == 1:
44
- Config = DictWrapper(Config_full["ENG"]["Game"])
45
- secret_dict = secret["ENG"]
46
- else:
47
- Config = DictWrapper(Config_full["SPA"]["Game"])
48
- secret_dict = secret["SPA"]
49
-
50
-
51
- with open("ranking.txt", "w+") as file:
52
- file.write("---------------------------")
53
-
54
- pca = pk.load(open("pca_mpnet.pkl", "rb"))
55
-
56
- print(Config.Difficulty_presentation_Full)
57
- difficulty = int(input(Config.Difficulty + ": "))
58
-
59
- secret_list = secret_dict["basic"] if difficulty <= 2 else secret_dict["advanced"]
60
-
61
- secret = secret_list.pop(random.randint(0, len(secret_list) - 1))
62
- secret = secret.lower()
63
-
64
- words = [Config.secret_word]
65
- scores = [10]
66
-
67
- if secret not in embeddings_dict.keys():
68
- embeddings_dict[secret] = model_st.encode(secret, convert_to_tensor=True)
69
- model.add_vector(secret, embeddings_dict[secret].tolist())
70
-
71
- word_vect = [embeddings_dict[secret].tolist()]
72
-
73
- thread = threading.Thread(
74
- target=display_words, args=(words, pca.transform(word_vect), scores, -1)
75
- )
76
- thread.start()
77
-
78
-
79
- def preproc_vectors(words, word_vect, scores, repeated):
80
- ascending_indices = np.argsort(scores)
81
- descending_indices = list(ascending_indices[::-1])
82
- ranking_data = []
83
- k = len(words) - 1
84
- if repeated != -1:
85
- k = repeated
86
-
87
- ranking_data.append(["#" + str(k), words[k], scores[k]])
88
-
89
- ranking_data.append("---------------------------")
90
- for i in descending_indices:
91
- if i == 0:
92
- continue
93
- ranking_data.append(["#" + str(i), words[i], scores[i]])
94
-
95
- with open("ranking.txt", "w+") as file:
96
- for item in ranking_data:
97
- file.write("%s\n" % item)
98
-
99
- if len(words) > 11:
100
- if k in descending_indices[:11]:
101
- descending_indices = descending_indices[:11]
102
- else:
103
- descending_indices = descending_indices[:11]
104
- descending_indices.append(k)
105
- words_display = [words[i] for i in descending_indices]
106
- displayvect_display = pca.transform([word_vect[i] for i in descending_indices])
107
- scores_display = [scores[i] for i in descending_indices]
108
- bold = descending_indices.index(k)
109
-
110
- else:
111
- words_display = words
112
- displayvect_display = pca.transform(word_vect)
113
- scores_display = scores
114
- bold = k
115
-
116
- return (
117
- words_display,
118
- displayvect_display,
119
- scores_display,
120
- bold,
121
- )
122
-
123
-
124
- win = False
125
- n = 0
126
- recent_hint = 0
127
- f_dev_avg = 0
128
- last_hint = -1
129
-
130
- if difficulty == 1:
131
- n = 3
132
-
133
-
134
- def play_game(word):
135
- global win, n, recent_hint, f_dev_avg, last_hint, words, word_vect, scores, thread
136
-
137
- word = word.lower()
138
- if word == "give_up":
139
- return "Game Over"
140
-
141
- if word in words:
142
- repeated = words.index(word)
143
- else:
144
- repeated = -1
145
- words.append(word)
146
-
147
- thread.join()
148
-
149
- if word not in embeddings_dict.keys():
150
- embedding = model_st.encode(word, convert_to_tensor=True)
151
- embeddings_dict[word] = embedding
152
- model.add_vector(word, embedding.tolist())
153
-
154
- if repeated == -1:
155
- word_vect.append(embeddings_dict[word].tolist())
156
-
157
- score = round(model.similarity(secret, word) * 10, 2)
158
-
159
- if repeated == -1:
160
- scores.append(score)
161
-
162
- if score <= 2.5:
163
- feedback = Config.Feedback_0 + str(score)
164
- elif score > 2.5 and score <= 4.0:
165
- feedback = Config.Feedback_1 + str(score)
166
- elif score > 4.0 and score <= 6.0:
167
- feedback = Config.Feedback_2 + str(score)
168
- elif score > 6.0 and score <= 7.5:
169
- feedback = Config.Feedback_3 + str(score)
170
- elif score > 7.5 and score <= 8.0:
171
- feedback = Config.Feedback_4 + str(score)
172
- elif score > 8.0 and score < 10.0:
173
- feedback = Config.Feedback_5 + str(score)
174
- else:
175
- win = True
176
- feedback = Config.Feedback_8
177
- words[0] = secret
178
- words.pop(len(words) - 1)
179
- word_vect.pop(len(word_vect) - 1)
180
- scores.pop(len(scores) - 1)
181
-
182
- if score > scores[len(scores) - 2] and win == False:
183
- feedback += "\n" + Config.Feedback_6
184
- elif score < scores[len(scores) - 2] and win == False:
185
- feedback += "\n" + Config.Feedback_7
186
-
187
- if difficulty != 4:
188
- mov_avg = calculate_moving_average(scores[1:], 5)
189
-
190
- if len(mov_avg) > 1 and win == False:
191
- f_dev = calculate_tendency_slope(mov_avg)
192
- f_dev_avg = calculate_moving_average(f_dev, 3)
193
- if f_dev_avg[len(f_dev_avg) - 1] < 0 and recent_hint == 0:
194
- i = random.randint(0, len(Config.hint_intro) - 1)
195
- feedback += "\n\n" + Config.hint_intro[i]
196
- hint_text, n, last_hint = hint(
197
- secret,
198
- n,
199
- model_st,
200
- last_hint,
201
- lang,
202
- (
203
- DictWrapper(Config_full["SPA"]["Hint"])
204
- if lang == 0
205
- else DictWrapper(Config_full["ENG"]["Hint"])
206
- ),
207
- )
208
- feedback += "\n" + hint_text
209
- recent_hint = 3
210
-
211
- if recent_hint != 0:
212
- recent_hint -= 1
213
-
214
- (
215
- words_display,
216
- displayvect_display,
217
- scores_display,
218
- bold_display,
219
- ) = preproc_vectors(words, word_vect, scores, repeated)
220
-
221
- if win:
222
- bold_display = 0
223
-
224
- thread = threading.Thread(
225
- target=display_words,
226
- args=(words_display, displayvect_display, scores_display, bold_display),
227
- )
228
- thread.start()
229
-
230
- if win:
231
- feedback += "\nCongratulations! You guessed the secret word."
232
-
233
- return feedback
234
-
235
-
236
- def gradio_interface():
237
- return gr.Interface(
238
- fn=play_game,
239
- inputs="text",
240
- outputs="text",
241
- title="Secret Word Game",
242
- description="Guess the secret word!",
243
- examples=[
244
- ["apple"],
245
- ["banana"],
246
- ["cherry"],
247
- ],
248
- )
249
-
250
-
251
- if __name__ == "__main__":
252
- gradio_interface().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pca_mpnet.pkl DELETED
Binary file (25.4 kB)
 
seguimiento.py → tracking.py RENAMED
File without changes