semantrix / hints.py
Javierss
Add word check and change ln to log10
f60623c
# """
# This module provides functions to generate dynamic hints and curiosities about a secret word using llms.
# Functions:
# hint(secret, n, model, last_hint, lang, Config):
# Generates a dynamic hint based on the secret word and the number of hints given.
# Parameters:
# secret (str): The secret word.
# n (int): The number of hints already given.
# model: The sentence transformer model used for encoding.
# last_hint (int): The index of the last hint given.
# lang (int): The language code (0 for Spanish, 1 for English).
# Config: Configuration object containing hint templates.
# Returns:
# tuple: A tuple containing the generated hint (str), the updated number of hints (int), and the index of the last hint given (int).
# curiosity(secret, Config):
# Generates a curiosity about the secret word.
# Parameters:
# secret (str): The secret word.
# Config: Configuration object containing the curiosity template.
# Returns:
# str: The generated curiosity.
# ireplace(old, new, text):
# Replaces all occurrences of a substring in a string, case-insensitively.
# Parameters:
# old (str): The substring to be replaced.
# new (str): The substring to replace with.
# text (str): The original string.
# Returns:
# str: The modified string with all occurrences of the old substring replaced by the new substring.
# """
import random
import openai
from sentence_transformers import util
gpt_model = "gpt-3.5-turbo"
# Dynamic hint function that returns a hint based on the secret word and the number of hints given
def hint(secret, n, model, last_hint, lang, Config):
# Initialize hint variable
hint = ""
# Advanced hints
if n >= 3:
j = random.randint(0, 2)
while j == last_hint:
j = random.randint(0, 2)
# Advanced hint 1: Definition of the secret word
if j == 0:
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_0_0 # type: ignore
+ secret
+ Config.hint_0_1 # type: ignore
+ secret
+ Config.hint_0_2, # type: ignore
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0.5,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
output = output.replace('"', "").replace("'", "")
# Replace the secret word with "La palabra secreta" or "The secret word" just in case the model uses the secret word in the definition
if lang == 0:
output = ireplace("la " + secret, "La palabra secreta", output)
output = ireplace("las " + secret, "La palabra secreta", output)
output = ireplace("el " + secret, "La palabra secreta", output)
output = ireplace("los " + secret, "La palabra secreta", output)
output = ireplace("un " + secret, "La palabra secreta", output)
output = ireplace("una " + secret, "La palabra secreta", output)
output = ireplace("unos " + secret, "La palabra secreta", output)
output = ireplace("unas " + secret, "La palabra secreta", output)
elif lang == 1:
output = ireplace("the " + secret, "The secret word", output)
output = ireplace("a " + secret, "The secret word", output)
hint += Config.hint_0_3 + output # type: ignore
last_hint = 0
# Advanced hint 2: Representation of the secret word with emojis
elif j == 1:
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_1_0 + secret + Config.hint_1_1, # type: ignore
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
hint += Config.hint_1_2 + output # type: ignore
last_hint = 1
# Advanced hint 3: Poem about the secret word
elif j == 2:
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_2_0 + secret + Config.hint_2_1, # type: ignore
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
hint += Config.hint_2_2 + output # type: ignore
last_hint = 2
# Initial hints
else:
j = random.randint(3, 4)
while j == last_hint:
j = random.randint(3, 4)
# Initial hint 1: Rank of four words related to the secret word
if j == 3:
words = []
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_3_0, # type: ignore
}
],
temperature=1.25,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
output = (output.replace(" ", "").replace(".", "")).lower()
words.extend(output.strip().split(","))
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_3_1 # type: ignore
+ secret
+ Config.hint_3_2, # type: ignore
}
],
temperature=1.1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
output = (output.replace(".", "")).lower()
words.append(output) # type: ignore
random.shuffle(words)
sentences1 = [secret, secret, secret, secret]
sentences2 = words
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
embeddings2 = model.encode(sentences2, convert_to_tensor=True)
cosine_scores = util.cos_sim(embeddings1, embeddings2)
scores = cosine_scores[0].tolist()
sum_scores = sum(scores)
normalized_scores = [round(score * 100 / sum_scores, 1) for score in scores]
hint += Config.hint_3_3 # type: ignore
max_len = -1
for ele in words:
if len(ele) > max_len:
max_len = len(ele)
longest_word = ele
for i in range(len(words)):
word_hint = words[i].ljust(len(longest_word) + 1)
hint += (
# word_hint[: len(longest_word)]
word_hint
+ "|"
+ ("🟩") * round(normalized_scores[i] * 0.2)
+ " "
+ str(normalized_scores[i])
+ "%\n"
)
last_hint = 3
# Initial hint 2: Film representation with emojis with the secret word
elif j == 4:
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_4_0 # type: ignore
+ secret
+ Config.hint_4_1, # type: ignore
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
film_title = str(response.choices[0].message.content).replace('"', "")
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.hint_4_2 # type: ignore
+ film_title
+ Config.hint_4_3, # type: ignore
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
hint += Config.hint_4_4 + "\n" + output # type: ignore
last_hint = 4
return hint, n + 1, last_hint
# Tell a curiosity about the secret word
def curiosity(secret, Config):
response = openai.chat.completions.create(
model=gpt_model,
messages=[
{
"role": "user",
"content": Config.curiosity + secret + '".',
}
],
temperature=1,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
output = str(response.choices[0].message.content)
return output
# Replace all occurrences of a substring in a string
def ireplace(old, new, text):
idx = 0
while idx < len(text):
index_l = text.lower().find(old.lower(), idx)
if index_l == -1:
return text
text = text[:index_l] + new + text[index_l + len(old) :]
idx = index_l + len(new)
return text