File size: 3,649 Bytes
8ca749b
 
2374982
 
8ca749b
 
 
2374982
8ca749b
 
2374982
8ca749b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2374982
8ca749b
 
 
2374982
 
8ca749b
 
2374982
 
 
 
8ca749b
 
2374982
8ca749b
 
 
 
 
 
 
 
 
2374982
 
 
8ca749b
 
2374982
8ca749b
 
 
 
2374982
8ca749b
 
 
2374982
8ca749b
 
 
2374982
8ca749b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2374982
8ca749b
 
2374982
 
 
 
8ca749b
2374982
8ca749b
 
 
 
 
 
 
2374982
8ca749b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import random
import time
from datasets import Dataset, DatasetDict
from huggingface_hub import HfApi
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline

# -------------------------------------
# CONFIGURAÇÕES DO MODELO LOCAL LEVE
# -------------------------------------
MODEL_NAME = "Qwen/Qwen2.5-0.5B-Instruct"
DATASET_REPO = "caarleexx/AMP"

print("[LOG] Carregando modelo...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    device_map="cpu"
)
generator = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=200,
    temperature=0.9
)

# -------------------------------------
# FUNÇÕES
# -------------------------------------
def gerar_pergunta_e_opcoes():
    N = random.randint(2, 6)  # número aleatório de alternativas
    prompt = f"Crie uma pergunta curta com {N} respostas possíveis diferentes entre si."
    pergunta = generator(prompt)[0]["generated_text"].strip()
    return pergunta, N

def gerar_resposta(principal_pergunta):
    prompt = f"Pergunta: {principal_pergunta}\nResponda de forma direta e objetiva."
    resposta = generator(prompt)[0]["generated_text"].strip()
    return resposta

def gerar_alternativas(pergunta, N):
    prompt = f"Pergunta: {pergunta}\nListe {N} respostas possíveis, diferentes entre si, sem explicações."
    texto = generator(prompt)[0]["generated_text"]
    alternativas = []
    for linha in texto.split("\n"):
        linha = linha.strip("-•1234567890. ")
        if len(linha) > 2:
            alternativas.append(linha)
    return alternativas[:N]

def gerar_explicacao(pergunta):
    prompt = f"Explique de forma objetiva por que esta pergunta pode ter múltiplas respostas possíveis:\n{pergunta}"
    explicacao = generator(prompt)[0]["generated_text"].strip()
    return explicacao

# -------------------------------------
# DATASET
# -------------------------------------
def carregar_dataset():
    try:
        print("[LOG] Tentando carregar dataset remoto...")
        ds = DatasetDict.load_from_disk(DATASET_REPO)
        return ds
    except:
        print("[LOG] Criando dataset novo...")
        return DatasetDict({"train": Dataset.from_dict({"pergunta": [], "resposta": [], "alternativas": [], "explanação": []})})

def salvar_dataset(ds):
    print("[LOG] Salvando dataset no HuggingFace...")
    ds.push_to_hub(DATASET_REPO, private=False)

# -------------------------------------
# LOOP PRINCIPAL
# -------------------------------------
def loop_geracao(qtd=10):
    ds = carregar_dataset()

    for i in range(qtd):
        print("\n====================================")
        print(f"[LOG] ITERAÇÃO {i+1}")
        print("====================================")

        pergunta, N = gerar_pergunta_e_opcoes()
        resposta = gerar_resposta(pergunta)
        alternativas = gerar_alternativas(pergunta, N)
        explicacao = gerar_explicacao(pergunta)

        novo_registro = {
            "pergunta": pergunta,
            "resposta": resposta,
            "alternativas": alternativas,
            "explanação": explicacao
        }

        print(f"[LOG] Pergunta: {pergunta}")
        print(f"[LOG] Resposta: {resposta}")
        print(f"[LOG] Alternativas: {alternativas}")
        print(f"[LOG] Explicação: {explicacao}")

        ds["train"] = ds["train"].add_item(novo_registro)
        salvar_dataset(ds)

        time.sleep(1)

    print("[LOG] Concluído.")

# -------------------------------------
# EXECUTAR
# -------------------------------------
if __name__ == "__main__":
    loop_geracao(qtd=50)