Javierss
commited on
Commit
•
f2a23c8
1
Parent(s):
e2b757a
add init test
Browse files- 3d_rotation.gif +0 -0
- __pycache__/display.cpython-311.pyc +0 -0
- __pycache__/pistas.cpython-311.pyc +0 -0
- __pycache__/seguimiento.cpython-311.pyc +0 -0
- data/lima_2024-02-16 13:43:11.426509 +1 -0
- flagged/log.csv +3 -0
- gradiotest.py +115 -0
- juego_embbedings_chat.py +269 -0
- juego_embbedings_text_config.py +66 -101
- ranking.txt +1 -0
3d_rotation.gif
ADDED
__pycache__/display.cpython-311.pyc
ADDED
Binary file (6.31 kB). View file
|
|
__pycache__/pistas.cpython-311.pyc
ADDED
Binary file (8.17 kB). View file
|
|
__pycache__/seguimiento.cpython-311.pyc
ADDED
Binary file (1.09 kB). View file
|
|
data/lima_2024-02-16 13:43:11.426509
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
['#1', 'amigo', 7.63]
|
flagged/log.csv
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
word,output,flag,username,timestamp
|
2 |
+
silla,"Caliente, puntuación: 6.9
|
3 |
+
Te estás acercando",,,2024-02-16 13:51:47.368924
|
gradiotest.py
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
i = -1
|
4 |
+
|
5 |
+
with gr.Blocks() as demo:
|
6 |
+
gr.Markdown(
|
7 |
+
"""
|
8 |
+
<p style="text-align:center"> SEMANTRIX: JUEGO DE LA ADIVINANZA SEMÁNTICA </p>
|
9 |
+
"""
|
10 |
+
)
|
11 |
+
lang = {
|
12 |
+
"Introduction_0": "Bienvenido a Semantrix, el emocionante Juego de la Adivinanza Semántica.",
|
13 |
+
"Introduction_1": "¿Quieres saber cómo se juega?",
|
14 |
+
"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.",
|
15 |
+
"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.",
|
16 |
+
"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.",
|
17 |
+
"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!",
|
18 |
+
"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!",
|
19 |
+
"Difficulty": "Elige tu nivel de dificultad",
|
20 |
+
"New_word": "Nueva palabra: ",
|
21 |
+
"Feedback_0": "Helado, puntuación: ",
|
22 |
+
"Feedback_1": "Frío, puntuación: ",
|
23 |
+
"Feedback_2": "Templado, puntuación: ",
|
24 |
+
"Feedback_3": "Caliente, puntuación: ",
|
25 |
+
"Feedback_4": "Quemando, puntuación: ",
|
26 |
+
"Feedback_5": "Ardiendo, puntuación: ",
|
27 |
+
"Feedback_6": "Te estás acercando",
|
28 |
+
"Feedback_7": "Te estás alejando",
|
29 |
+
"Feedback_8": "¡Has ganado, ENHORABUENA!",
|
30 |
+
"Feedback_9": "La palabra secreta era: ",
|
31 |
+
"Feedback_10": "Aunque no fue una victoria esta vez, ¡no temas! ¡Cada intento es una nueva oportunidad para brillar! ¡Sigue adelante!",
|
32 |
+
"secret_word": "PALABRA SECRETA",
|
33 |
+
"hint_intro": [
|
34 |
+
"Parece que las palabras están jugando al escondite contigo. ¿Necesitas una ayudita? Aquí va una pista:",
|
35 |
+
"¡Vamos, estás tan cerca de descifrar el enigma semántico! Pero si sientes que te falta un empujón, aquí tienes una pista:",
|
36 |
+
"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:",
|
37 |
+
"El camino semántico puede volverse un poco sinuoso a veces. No te preocupes, estoy aquí para allanar el camino con una pista:",
|
38 |
+
"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:",
|
39 |
+
"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:",
|
40 |
+
"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:",
|
41 |
+
],
|
42 |
+
}
|
43 |
+
|
44 |
+
def reset():
|
45 |
+
global i
|
46 |
+
i = -1
|
47 |
+
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)
|
48 |
+
def change(radio):
|
49 |
+
global i
|
50 |
+
i = i + 1
|
51 |
+
if i == 2 and radio == "NO":
|
52 |
+
i = 7
|
53 |
+
# txt=gr.Textbox(lang[list(lang.keys())[i]],visible=True,label='')
|
54 |
+
# else:
|
55 |
+
txt = gr.Textbox(lang[list(lang.keys())[i]], visible=True, label="")
|
56 |
+
return txt
|
57 |
+
|
58 |
+
def button_name(radio):
|
59 |
+
global i
|
60 |
+
output = []
|
61 |
+
if i == 1:
|
62 |
+
output.extend(
|
63 |
+
[
|
64 |
+
gr.Button("Si", visible=False),
|
65 |
+
gr.Radio(["SÍ", "NO"], label="", visible=True),
|
66 |
+
]
|
67 |
+
)
|
68 |
+
elif i == 2:
|
69 |
+
if radio == "NO":
|
70 |
+
output.extend(
|
71 |
+
[
|
72 |
+
gr.Button("Introducir", visible=True),
|
73 |
+
gr.Radio(["SÍ", "NO"], visible=False),
|
74 |
+
]
|
75 |
+
)
|
76 |
+
else:
|
77 |
+
output.extend(
|
78 |
+
[
|
79 |
+
gr.Button("Siguiente", visible=True),
|
80 |
+
gr.Radio(["SÍ", "NO"], visible=False),
|
81 |
+
]
|
82 |
+
)
|
83 |
+
elif i == 7:
|
84 |
+
output.extend(
|
85 |
+
[
|
86 |
+
gr.Button("Siguiente", visible=False),
|
87 |
+
gr.Radio(["Fácil", "Normal", "Dificil", "Experto"], visible=True),
|
88 |
+
]
|
89 |
+
)
|
90 |
+
else:
|
91 |
+
output.extend(
|
92 |
+
[
|
93 |
+
gr.Button("Siguiente", visible=True),
|
94 |
+
gr.Radio(["SÍ", "NO"], label="", visible=False),
|
95 |
+
]
|
96 |
+
)
|
97 |
+
return output
|
98 |
+
|
99 |
+
img = gr.Image(interactive=False, visible=False)
|
100 |
+
out = gr.Textbox(
|
101 |
+
visible=False, placeholder=lang[list(lang.keys())[0]], min_width=15
|
102 |
+
)
|
103 |
+
radio = gr.Radio(["SÍ", "NO"], visible=False)
|
104 |
+
with gr.Row():
|
105 |
+
inp = gr.Textbox(visible=False)
|
106 |
+
but = gr.Button("Empezar")
|
107 |
+
|
108 |
+
but.click(change, inputs=radio, outputs=out)
|
109 |
+
radio.input(change, inputs=radio, outputs=out)
|
110 |
+
demo.load(reset,outputs=[out,inp,img, but, radio])
|
111 |
+
out.change(button_name, inputs=radio, outputs=[but, radio])
|
112 |
+
|
113 |
+
|
114 |
+
if __name__ == "__main__":
|
115 |
+
demo.launch()
|
juego_embbedings_chat.py
ADDED
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
secret_list = secret_dict["basic"] if difficulty <= 2 else secret_dict["advanced"]
|
61 |
+
|
62 |
+
secret = secret_list.pop(random.randint(0, len(secret_list) - 1))
|
63 |
+
secret = secret.lower()
|
64 |
+
|
65 |
+
words = [Config.secret_word]
|
66 |
+
scores = [10]
|
67 |
+
|
68 |
+
if secret not in embeddings_dict.keys():
|
69 |
+
embeddings_dict[secret] = model_st.encode(secret, convert_to_tensor=True)
|
70 |
+
model.add_vector(secret, embeddings_dict[secret].tolist())
|
71 |
+
|
72 |
+
word_vect = [embeddings_dict[secret].tolist()]
|
73 |
+
|
74 |
+
thread = threading.Thread(
|
75 |
+
target=display_words, args=(words, pca.transform(word_vect), scores, -1)
|
76 |
+
)
|
77 |
+
thread.start()
|
78 |
+
|
79 |
+
|
80 |
+
def preproc_vectors(words, word_vect, scores, repeated):
|
81 |
+
ascending_indices = np.argsort(scores)
|
82 |
+
descending_indices = list(ascending_indices[::-1])
|
83 |
+
ranking_data = []
|
84 |
+
k = len(words) - 1
|
85 |
+
if repeated != -1:
|
86 |
+
k = repeated
|
87 |
+
|
88 |
+
ranking_data.append(["#" + str(k), words[k], scores[k]])
|
89 |
+
|
90 |
+
ranking_data.append("---------------------------")
|
91 |
+
for i in descending_indices:
|
92 |
+
if i == 0:
|
93 |
+
continue
|
94 |
+
ranking_data.append(["#" + str(i), words[i], scores[i]])
|
95 |
+
|
96 |
+
with open("ranking.txt", "w+") as file:
|
97 |
+
for item in ranking_data:
|
98 |
+
file.write("%s\n" % item)
|
99 |
+
|
100 |
+
if len(words) > 11:
|
101 |
+
if k in descending_indices[:11]:
|
102 |
+
descending_indices = descending_indices[:11]
|
103 |
+
else:
|
104 |
+
descending_indices = descending_indices[:11]
|
105 |
+
descending_indices.append(k)
|
106 |
+
words_display = [words[i] for i in descending_indices]
|
107 |
+
displayvect_display = pca.transform([word_vect[i] for i in descending_indices])
|
108 |
+
scores_display = [scores[i] for i in descending_indices]
|
109 |
+
bold = descending_indices.index(k)
|
110 |
+
|
111 |
+
else:
|
112 |
+
words_display = words
|
113 |
+
displayvect_display = pca.transform(word_vect)
|
114 |
+
scores_display = scores
|
115 |
+
bold = k
|
116 |
+
|
117 |
+
return (
|
118 |
+
words_display,
|
119 |
+
displayvect_display,
|
120 |
+
scores_display,
|
121 |
+
bold,
|
122 |
+
)
|
123 |
+
|
124 |
+
|
125 |
+
win = False
|
126 |
+
n = 0
|
127 |
+
recent_hint = 0
|
128 |
+
f_dev_avg = 0
|
129 |
+
last_hint = -1
|
130 |
+
|
131 |
+
if difficulty == 1:
|
132 |
+
n = 3
|
133 |
+
|
134 |
+
|
135 |
+
def play_game(word):
|
136 |
+
global win, n, recent_hint, f_dev_avg, last_hint, words, word_vect, scores, thread
|
137 |
+
|
138 |
+
word = word.lower()
|
139 |
+
if word == "give_up":
|
140 |
+
return "Game Over"
|
141 |
+
|
142 |
+
if word in words:
|
143 |
+
repeated = words.index(word)
|
144 |
+
else:
|
145 |
+
repeated = -1
|
146 |
+
words.append(word)
|
147 |
+
|
148 |
+
thread.join()
|
149 |
+
|
150 |
+
if word not in embeddings_dict.keys():
|
151 |
+
embedding = model_st.encode(word, convert_to_tensor=True)
|
152 |
+
embeddings_dict[word] = embedding
|
153 |
+
model.add_vector(word, embedding.tolist())
|
154 |
+
|
155 |
+
if repeated == -1:
|
156 |
+
word_vect.append(embeddings_dict[word].tolist())
|
157 |
+
|
158 |
+
score = round(model.similarity(secret, word) * 10, 2)
|
159 |
+
|
160 |
+
if repeated == -1:
|
161 |
+
scores.append(score)
|
162 |
+
|
163 |
+
if score <= 2.5:
|
164 |
+
feedback = Config.Feedback_0 + str(score)
|
165 |
+
elif score > 2.5 and score <= 4.0:
|
166 |
+
feedback = Config.Feedback_1 + str(score)
|
167 |
+
elif score > 4.0 and score <= 6.0:
|
168 |
+
feedback = Config.Feedback_2 + str(score)
|
169 |
+
elif score > 6.0 and score <= 7.5:
|
170 |
+
feedback = Config.Feedback_3 + str(score)
|
171 |
+
elif score > 7.5 and score <= 8.0:
|
172 |
+
feedback = Config.Feedback_4 + str(score)
|
173 |
+
elif score > 8.0 and score < 10.0:
|
174 |
+
feedback = Config.Feedback_5 + str(score)
|
175 |
+
else:
|
176 |
+
win = True
|
177 |
+
feedback = Config.Feedback_8
|
178 |
+
words[0] = secret
|
179 |
+
words.pop(len(words) - 1)
|
180 |
+
word_vect.pop(len(word_vect) - 1)
|
181 |
+
scores.pop(len(scores) - 1)
|
182 |
+
|
183 |
+
if score > scores[len(scores) - 2] and win == False:
|
184 |
+
feedback += "\n" + Config.Feedback_6
|
185 |
+
elif score < scores[len(scores) - 2] and win == False:
|
186 |
+
feedback += "\n" + Config.Feedback_7
|
187 |
+
|
188 |
+
if difficulty != 4:
|
189 |
+
mov_avg = calculate_moving_average(scores[1:], 5)
|
190 |
+
|
191 |
+
if len(mov_avg) > 1 and win == False:
|
192 |
+
f_dev = calculate_tendency_slope(mov_avg)
|
193 |
+
f_dev_avg = calculate_moving_average(f_dev, 3)
|
194 |
+
if f_dev_avg[len(f_dev_avg) - 1] < 0 and recent_hint == 0:
|
195 |
+
i = random.randint(0, len(Config.hint_intro) - 1)
|
196 |
+
feedback += "\n\n" + Config.hint_intro[i]
|
197 |
+
hint_text, n, last_hint = hint(
|
198 |
+
secret,
|
199 |
+
n,
|
200 |
+
model_st,
|
201 |
+
last_hint,
|
202 |
+
lang,
|
203 |
+
(
|
204 |
+
DictWrapper(Config_full["SPA"]["Hint"])
|
205 |
+
if lang == 0
|
206 |
+
else DictWrapper(Config_full["ENG"]["Hint"])
|
207 |
+
),
|
208 |
+
)
|
209 |
+
feedback += "\n" + hint_text
|
210 |
+
recent_hint = 3
|
211 |
+
|
212 |
+
if recent_hint != 0:
|
213 |
+
recent_hint -= 1
|
214 |
+
|
215 |
+
(
|
216 |
+
words_display,
|
217 |
+
displayvect_display,
|
218 |
+
scores_display,
|
219 |
+
bold_display,
|
220 |
+
) = preproc_vectors(words, word_vect, scores, repeated)
|
221 |
+
|
222 |
+
if win:
|
223 |
+
bold_display = 0
|
224 |
+
|
225 |
+
thread = threading.Thread(
|
226 |
+
target=display_words,
|
227 |
+
args=(words_display, displayvect_display, scores_display, bold_display),
|
228 |
+
)
|
229 |
+
thread.start()
|
230 |
+
|
231 |
+
if win:
|
232 |
+
feedback += "\nCongratulations! You guessed the secret word."
|
233 |
+
|
234 |
+
return feedback
|
235 |
+
|
236 |
+
|
237 |
+
def gradio_interface():
|
238 |
+
return gr.ChatInterface(
|
239 |
+
fn=play_game,
|
240 |
+
inputs="text",
|
241 |
+
outputs="text",
|
242 |
+
title="Secret Word Game",
|
243 |
+
description="Guess the secret word!",
|
244 |
+
examples=[
|
245 |
+
["apple"],
|
246 |
+
["banana"],
|
247 |
+
["cherry"],
|
248 |
+
],
|
249 |
+
)
|
250 |
+
|
251 |
+
|
252 |
+
|
253 |
+
|
254 |
+
with gr.Blocks() as demo:
|
255 |
+
chatbot = gr.Chatbot([{"text": "Config.Difficulty_presentation_Full"}])
|
256 |
+
msg = gr.Textbox()
|
257 |
+
clear = gr.ClearButton([msg, chatbot])
|
258 |
+
|
259 |
+
def respond(message, chat_history):
|
260 |
+
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
|
261 |
+
chat_history.append((message, bot_message))
|
262 |
+
time.sleep(2)
|
263 |
+
return "", chat_history
|
264 |
+
|
265 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
266 |
+
|
267 |
+
|
268 |
+
if __name__ == "__main__":
|
269 |
+
demo.launch()
|
juego_embbedings_text_config.py
CHANGED
@@ -5,21 +5,19 @@ import random
|
|
5 |
import threading
|
6 |
from datetime import datetime
|
7 |
|
|
|
8 |
import numpy as np
|
9 |
-
from gensim.models import KeyedVectors
|
10 |
-
from sentence_transformers import SentenceTransformer
|
11 |
-
|
12 |
from display import display_words
|
|
|
13 |
from pistas import curiosity, hint
|
14 |
from seguimiento import calculate_moving_average, calculate_tendency_slope
|
|
|
15 |
|
16 |
-
# %%
|
17 |
model = KeyedVectors(768)
|
18 |
model_st = SentenceTransformer(
|
19 |
"sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
|
20 |
)
|
21 |
-
|
22 |
-
# embeddings_dict = torch.load(file_path)
|
23 |
embeddings_dict = {}
|
24 |
|
25 |
config_file_path = "config/lang.json"
|
@@ -32,72 +30,54 @@ class DictWrapper:
|
|
32 |
|
33 |
|
34 |
with open(config_file_path, "r") as file:
|
35 |
-
# Load JSON from the file into a dictionary
|
36 |
Config_full = json.load(file)
|
37 |
|
38 |
with open(secret_file_path, "r") as file:
|
39 |
-
# Load JSON from the file into a dictionary
|
40 |
secret = json.load(file)
|
41 |
|
42 |
lang = 0
|
43 |
|
44 |
if lang == 0:
|
45 |
-
Config = DictWrapper(Config_full["SPA"]["Game"])
|
46 |
secret_dict = secret["SPA"]
|
47 |
elif lang == 1:
|
48 |
-
Config = DictWrapper(Config_full["ENG"]["Game"])
|
49 |
secret_dict = secret["ENG"]
|
50 |
else:
|
51 |
-
Config = DictWrapper(Config_full["SPA"]["Game"])
|
52 |
secret_dict = secret["SPA"]
|
53 |
|
54 |
|
55 |
with open("ranking.txt", "w+") as file:
|
56 |
file.write("---------------------------")
|
57 |
|
58 |
-
# %%
|
59 |
pca = pk.load(open("pca_mpnet.pkl", "rb"))
|
60 |
|
61 |
-
print(Config.Difficulty_presentation_Full)
|
62 |
-
|
63 |
-
difficulty = int(input(Config.Difficulty + ": ")) # type: ignore
|
64 |
-
|
65 |
|
66 |
-
# with open(file_path, "r") as file:
|
67 |
-
# secret_list = file.readlines()
|
68 |
-
|
69 |
-
# Write a function
|
70 |
-
|
71 |
-
|
72 |
-
# Optional: Remove newline characters from each element in the list
|
73 |
secret_list = secret_dict["basic"] if difficulty <= 2 else secret_dict["advanced"]
|
74 |
|
75 |
secret = secret_list.pop(random.randint(0, len(secret_list) - 1))
|
76 |
secret = secret.lower()
|
77 |
|
78 |
-
words = [Config.secret_word]
|
79 |
scores = [10]
|
80 |
|
81 |
-
|
82 |
-
|
83 |
-
embeddings_dict[secret]
|
84 |
-
model.add_vector(secret, embeddings_dict[secret].tolist())
|
85 |
|
86 |
word_vect = [embeddings_dict[secret].tolist()]
|
87 |
|
88 |
-
# model.add_vector(secret, embedding.tolist())
|
89 |
-
|
90 |
thread = threading.Thread(
|
91 |
target=display_words, args=(words, pca.transform(word_vect), scores, -1)
|
92 |
)
|
93 |
-
|
94 |
-
# Start the thread
|
95 |
thread.start()
|
96 |
|
97 |
|
98 |
def preproc_vectors(words, word_vect, scores, repeated):
|
99 |
ascending_indices = np.argsort(scores)
|
100 |
-
# Reverse the order to get descending indices
|
101 |
descending_indices = list(ascending_indices[::-1])
|
102 |
ranking_data = []
|
103 |
k = len(words) - 1
|
@@ -107,7 +87,7 @@ def preproc_vectors(words, word_vect, scores, repeated):
|
|
107 |
ranking_data.append(["#" + str(k), words[k], scores[k]])
|
108 |
|
109 |
ranking_data.append("---------------------------")
|
110 |
-
for i in descending_indices:
|
111 |
if i == 0:
|
112 |
continue
|
113 |
ranking_data.append(["#" + str(i), words[i], scores[i]])
|
@@ -141,8 +121,6 @@ def preproc_vectors(words, word_vect, scores, repeated):
|
|
141 |
)
|
142 |
|
143 |
|
144 |
-
# Example usage:
|
145 |
-
|
146 |
win = False
|
147 |
n = 0
|
148 |
recent_hint = 0
|
@@ -152,93 +130,82 @@ last_hint = -1
|
|
152 |
if difficulty == 1:
|
153 |
n = 3
|
154 |
|
155 |
-
|
156 |
-
|
|
|
|
|
|
|
157 |
if word == "give_up":
|
158 |
-
|
|
|
159 |
if word in words:
|
160 |
repeated = words.index(word)
|
161 |
-
|
162 |
else:
|
163 |
repeated = -1
|
164 |
words.append(word)
|
165 |
|
166 |
thread.join()
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
# model.add_vector(word, embedding.tolist())
|
174 |
if repeated == -1:
|
175 |
word_vect.append(embeddings_dict[word].tolist())
|
176 |
|
177 |
score = round(model.similarity(secret, word) * 10, 2)
|
178 |
|
179 |
if repeated == -1:
|
180 |
-
scores.append(score)
|
181 |
-
#
|
182 |
-
# score = round(score * 10, 2)
|
183 |
-
# %%
|
184 |
-
if score <= 2.5:
|
185 |
-
feedback = Config.Feedback_0 + str(score) # type: ignore
|
186 |
|
|
|
|
|
187 |
elif score > 2.5 and score <= 4.0:
|
188 |
-
feedback = Config.Feedback_1 + str(score)
|
189 |
-
|
190 |
elif score > 4.0 and score <= 6.0:
|
191 |
-
feedback = Config.Feedback_2 + str(score)
|
192 |
-
|
193 |
elif score > 6.0 and score <= 7.5:
|
194 |
-
feedback = Config.Feedback_3 + str(score)
|
195 |
-
|
196 |
elif score > 7.5 and score <= 8.0:
|
197 |
-
feedback = Config.Feedback_4 + str(score)
|
198 |
-
|
199 |
elif score > 8.0 and score < 10.0:
|
200 |
-
feedback = Config.Feedback_5 + str(score)
|
201 |
-
|
202 |
else:
|
203 |
win = True
|
204 |
-
feedback = Config.Feedback_8
|
205 |
words[0] = secret
|
206 |
words.pop(len(words) - 1)
|
207 |
word_vect.pop(len(word_vect) - 1)
|
208 |
scores.pop(len(scores) - 1)
|
209 |
-
# print(model.most_similar(secret, topn=20))
|
210 |
|
211 |
-
print(feedback)
|
212 |
if score > scores[len(scores) - 2] and win == False:
|
213 |
-
|
214 |
elif score < scores[len(scores) - 2] and win == False:
|
215 |
-
|
216 |
|
217 |
if difficulty != 4:
|
218 |
mov_avg = calculate_moving_average(scores[1:], 5)
|
219 |
|
220 |
-
# print (mov_avg)
|
221 |
if len(mov_avg) > 1 and win == False:
|
222 |
f_dev = calculate_tendency_slope(mov_avg)
|
223 |
-
# print(f_dev[len(f_dev) - 3 :])
|
224 |
f_dev_avg = calculate_moving_average(f_dev, 3)
|
225 |
-
# print(f_dev_avg[len(f_dev_avg) - 3 :])
|
226 |
-
# print(f_dev_avg)
|
227 |
if f_dev_avg[len(f_dev_avg) - 1] < 0 and recent_hint == 0:
|
228 |
-
i = random.randint(0, len(Config.hint_intro) - 1)
|
229 |
-
|
230 |
-
print(Config.hint_intro[i]) # type: ignore
|
231 |
hint_text, n, last_hint = hint(
|
232 |
secret,
|
233 |
n,
|
234 |
model_st,
|
235 |
last_hint,
|
236 |
lang,
|
237 |
-
|
238 |
-
|
239 |
-
|
|
|
|
|
240 |
)
|
241 |
-
|
242 |
recent_hint = 3
|
243 |
|
244 |
if recent_hint != 0:
|
@@ -258,30 +225,28 @@ while win == False:
|
|
258 |
target=display_words,
|
259 |
args=(words_display, displayvect_display, scores_display, bold_display),
|
260 |
)
|
261 |
-
|
262 |
-
# Start the thread
|
263 |
thread.start()
|
264 |
|
265 |
-
if win
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
|
|
|
|
282 |
|
283 |
-
with open("data/" + new_file_name, "w") as new_file:
|
284 |
-
new_file.writelines(file_content[2:])
|
285 |
|
286 |
-
|
287 |
-
|
|
|
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"
|
|
|
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
|
|
|
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]])
|
|
|
121 |
)
|
122 |
|
123 |
|
|
|
|
|
124 |
win = False
|
125 |
n = 0
|
126 |
recent_hint = 0
|
|
|
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:
|
|
|
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()
|
ranking.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
---------------------------
|