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asets import load_dataset, Dataset, DatasetDict
|
| 4 |
+
from huggingface_hub import HfApi, HfFolder
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 6 |
+
|
| 7 |
+
# -------------------------------------
|
| 8 |
+
# CONFIGURAÇÕES DO MODELO LOCAL
|
| 9 |
+
# -------------------------------------
|
| 10 |
+
MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 11 |
+
DATASET_REPO = "caarleexx/AM"
|
| 12 |
+
LOCAL_DATA_FILE = "data.json"
|
| 13 |
+
|
| 14 |
+
print("[LOG] Carregando modelo...")
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 16 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 17 |
+
MODEL_NAME,
|
| 18 |
+
device_map="cpu"
|
| 19 |
+
)
|
| 20 |
+
generator = pipeline(
|
| 21 |
+
"text-generation",
|
| 22 |
+
model=model,
|
| 23 |
+
tokenizer=tokenizer,
|
| 24 |
+
max_new_tokens=200,
|
| 25 |
+
temperature=0.9
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# -------------------------------------
|
| 29 |
+
# FUNÇÃO: gerar pergunta + N opções
|
| 30 |
+
# -------------------------------------
|
| 31 |
+
def gerar_pergunta_e_opcoes():
|
| 32 |
+
N = random.randint(2, 6) # número aleatório de alternativas
|
| 33 |
+
prompt = (
|
| 34 |
+
f"Crie uma pergunta curta. "
|
| 35 |
+
f"A pergunta deve ter exatamente {N} respostas possíveis, todas bem diferentes entre si."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
print(f"[LOG] Gerando pergunta com N={N} opções...")
|
| 39 |
+
pergunta = generator(prompt)[0]["generated_text"]
|
| 40 |
+
|
| 41 |
+
return pergunta, N
|
| 42 |
+
|
| 43 |
+
# -------------------------------------
|
| 44 |
+
# FUNÇÃO: gerar resposta principal
|
| 45 |
+
# -------------------------------------
|
| 46 |
+
def gerar_resposta(pergunta):
|
| 47 |
+
print(f"[LOG] Gerando resposta principal...")
|
| 48 |
+
resp = generator(f"Pergunta: {pergunta}\nResponda de forma curta e direta.")[0]["generated_text"]
|
| 49 |
+
return resp
|
| 50 |
+
|
| 51 |
+
# -------------------------------------
|
| 52 |
+
# FUNÇÃO: gerar alternativas divergentes
|
| 53 |
+
# -------------------------------------
|
| 54 |
+
def gerar_alternativas(pergunta, N):
|
| 55 |
+
prompt = (
|
| 56 |
+
f"Pergunta: {pergunta}\n"
|
| 57 |
+
f"Liste {N} respostas possíveis, todas diferentes entre si, "
|
| 58 |
+
f"sem justificativas. Apenas a lista."
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
print(f"[LOG] Gerando {N} alternativas divergentes...")
|
| 62 |
+
texto = generator(prompt)[0]["generated_text"]
|
| 63 |
+
|
| 64 |
+
alternativas = []
|
| 65 |
+
for linha in texto.split("\n"):
|
| 66 |
+
linha = linha.strip("-•1234567890. ")
|
| 67 |
+
if len(linha) > 2:
|
| 68 |
+
alternativas.append(linha)
|
| 69 |
+
|
| 70 |
+
return alternativas[:N]
|
| 71 |
+
|
| 72 |
+
# -------------------------------------
|
| 73 |
+
# FUNÇÃO: calcular divergência
|
| 74 |
+
# -------------------------------------
|
| 75 |
+
def divergencia(resposta_principal, alternativas):
|
| 76 |
+
print("[LOG] Calculando divergência...")
|
| 77 |
+
divs = []
|
| 78 |
+
base = resposta_principal.lower()
|
| 79 |
+
|
| 80 |
+
for alt in alternativas:
|
| 81 |
+
alt_l = alt.lower()
|
| 82 |
+
diff = abs(len(base) - len(alt_l))
|
| 83 |
+
divs.append(diff)
|
| 84 |
+
|
| 85 |
+
return divs
|
| 86 |
+
|
| 87 |
+
# -------------------------------------
|
| 88 |
+
# FUNÇÃO: gerar explicação final
|
| 89 |
+
# -------------------------------------
|
| 90 |
+
def gerar_explicacao(pergunta):
|
| 91 |
+
prompt = (
|
| 92 |
+
f"Explique, de forma detalhada, por que a pergunta abaixo pode gerar respostas tão diferentes:\n"
|
| 93 |
+
f"{pergunta}"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
print("[LOG] Gerando explicação...")
|
| 97 |
+
return generator(prompt)[0]["generated_text"]
|
| 98 |
+
|
| 99 |
+
# -------------------------------------
|
| 100 |
+
# INICIAR OU CARREGAR DATASET
|
| 101 |
+
# -------------------------------------
|
| 102 |
+
def carregar_dataset():
|
| 103 |
+
try:
|
| 104 |
+
print("[LOG] Tentando carregar dataset remoto...")
|
| 105 |
+
ds = load_dataset(DATASET_REPO)
|
| 106 |
+
return ds
|
| 107 |
+
except:
|
| 108 |
+
print("[LOG] Criando dataset novo...")
|
| 109 |
+
return DatasetDict({"train": Dataset.from_dict({"pergunta": [], "resposta": [], "alternativas": [], "divergencias": [], "explicacao": []})})
|
| 110 |
+
|
| 111 |
+
# -------------------------------------
|
| 112 |
+
# SALVAR NO HF DATASET A CADA LOOP
|
| 113 |
+
# -------------------------------------
|
| 114 |
+
def salvar_dataset(ds):
|
| 115 |
+
print("[LOG] Salvando dataset no HuggingFace...")
|
| 116 |
+
ds.push_to_hub(DATASET_REPO)
|
| 117 |
+
|
| 118 |
+
# -------------------------------------
|
| 119 |
+
# LOOP PRINCIPAL
|
| 120 |
+
# -------------------------------------
|
| 121 |
+
def loop_geracao(qtd=10):
|
| 122 |
+
ds = carregar_dataset()
|
| 123 |
+
|
| 124 |
+
for i in range(qtd):
|
| 125 |
+
print("\n====================================")
|
| 126 |
+
print(f"[LOG] ITERAÇÃO {i+1}")
|
| 127 |
+
print("====================================")
|
| 128 |
+
|
| 129 |
+
pergunta, N = gerar_pergunta_e_opcoes()
|
| 130 |
+
resposta = gerar_resposta(pergunta)
|
| 131 |
+
alternativas = gerar_alternativas(pergunta, N)
|
| 132 |
+
divergencias = divergencia(resposta, alternativas)
|
| 133 |
+
explicacao = gerar_explicacao(pergunta)
|
| 134 |
+
|
| 135 |
+
novo_registro = {
|
| 136 |
+
"pergunta": pergunta,
|
| 137 |
+
"resposta": resposta,
|
| 138 |
+
"alternativas": alternativas,
|
| 139 |
+
"divergencias": divergencias,
|
| 140 |
+
"explicacao": explicacao
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
print("[LOG] Adicionando exemplo ao dataset...")
|
| 144 |
+
ds["train"] = ds["train"].add_item(novo_registro)
|
| 145 |
+
|
| 146 |
+
salvar_dataset(ds)
|
| 147 |
+
|
| 148 |
+
time.sleep(1)
|
| 149 |
+
|
| 150 |
+
print("[LOG] Concluído.")
|
| 151 |
+
|
| 152 |
+
# -------------------------------------
|
| 153 |
+
# EXECUTAR O GERADOR
|
| 154 |
+
# -------------------------------------
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
loop_geracao(qtd=50)
|
| 157 |
+
|