Spaces:
Runtime error
Runtime error
Commit
·
2fe6001
1
Parent(s):
c9a085a
small model
Browse files
app.py
CHANGED
@@ -4,6 +4,7 @@ import json
|
|
4 |
import os
|
5 |
import logging
|
6 |
import time
|
|
|
7 |
|
8 |
# Configura logging para capturar mais detalhes
|
9 |
logging.basicConfig(level=logging.INFO)
|
@@ -27,13 +28,13 @@ def get_model():
|
|
27 |
start_time = time.time()
|
28 |
try:
|
29 |
tokenizer = AutoTokenizer.from_pretrained(
|
30 |
-
"unicamp-dl/ptt5-
|
31 |
legacy=False,
|
32 |
clean_up_tokenization_spaces=True
|
33 |
)
|
34 |
logger.info(f"Tokenizer carregado em {time.time() - start_time:.2f} segundos.")
|
35 |
model = T5ForConditionalGeneration.from_pretrained(
|
36 |
-
"unicamp-dl/ptt5-
|
37 |
device_map="cpu" # Força uso da CPU
|
38 |
)
|
39 |
logger.info(f"Modelo carregado em {time.time() - start_time:.2f} segundos.")
|
@@ -68,23 +69,21 @@ def generate_question_from_prompt(theme, difficulty, example_question=None):
|
|
68 |
f"Explicação: {example_question['explanation']}"
|
69 |
)
|
70 |
prompt = (
|
71 |
-
f"Baseado no exemplo: '{example_text}', gere uma
|
72 |
-
f"sobre
|
73 |
-
"
|
74 |
-
"
|
75 |
-
"Explicação: [texto].'"
|
76 |
)
|
77 |
else:
|
78 |
prompt = (
|
79 |
-
f"Gere uma questão de múltipla escolha sobre
|
80 |
-
f"
|
81 |
-
"
|
82 |
-
"
|
83 |
-
"Explicação: [texto].'"
|
84 |
)
|
85 |
try:
|
86 |
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
87 |
-
outputs = model.generate(**inputs, max_new_tokens=
|
88 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
89 |
parts = response.split("Alternativas:")
|
90 |
if len(parts) > 1:
|
@@ -94,14 +93,20 @@ def generate_question_from_prompt(theme, difficulty, example_question=None):
|
|
94 |
explanation_part = parts[1].split("Explicação:")[1].strip() if "Explicação:" in parts[1] else "Explicação padrão"
|
95 |
options = [opt.strip() for opt in options_part.split(",")]
|
96 |
if len(options) >= 4:
|
97 |
-
|
98 |
"question": f"Enunciado clínico: {question_part}",
|
99 |
"options": [f"A) {options[0]}", f"B) {options[1]}", f"C) {options[2]}", f"D) {options[3]}"],
|
100 |
"answer": answer_part,
|
101 |
"explanation": explanation_part
|
102 |
}
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
104 |
except Exception as e:
|
|
|
105 |
return {"question": f"Erro na geração: {e}", "options": [], "answer": "", "explanation": "Tente novamente."}
|
106 |
|
107 |
@app.get("/generate")
|
|
|
4 |
import os
|
5 |
import logging
|
6 |
import time
|
7 |
+
import gc
|
8 |
|
9 |
# Configura logging para capturar mais detalhes
|
10 |
logging.basicConfig(level=logging.INFO)
|
|
|
28 |
start_time = time.time()
|
29 |
try:
|
30 |
tokenizer = AutoTokenizer.from_pretrained(
|
31 |
+
"unicamp-dl/ptt5-small-portuguese-vocab",
|
32 |
legacy=False,
|
33 |
clean_up_tokenization_spaces=True
|
34 |
)
|
35 |
logger.info(f"Tokenizer carregado em {time.time() - start_time:.2f} segundos.")
|
36 |
model = T5ForConditionalGeneration.from_pretrained(
|
37 |
+
"unicamp-dl/ptt5-small-portuguese-vocab",
|
38 |
device_map="cpu" # Força uso da CPU
|
39 |
)
|
40 |
logger.info(f"Modelo carregado em {time.time() - start_time:.2f} segundos.")
|
|
|
69 |
f"Explicação: {example_question['explanation']}"
|
70 |
)
|
71 |
prompt = (
|
72 |
+
f"Baseado no exemplo: '{example_text}', gere uma questão de múltipla escolha "
|
73 |
+
f"sobre '{theme}', dificuldade {difficulty}, estilo prova de residência médica da USP. "
|
74 |
+
f"Formato: 'Enunciado clínico: [texto]. Alternativas: A) [opção], B) [opção], C) [opção], D) [opção]. "
|
75 |
+
f"Gabarito: [letra]. Explicação: [texto].'"
|
|
|
76 |
)
|
77 |
else:
|
78 |
prompt = (
|
79 |
+
f"Gere uma questão de múltipla escolha sobre '{theme}', dificuldade {difficulty}, "
|
80 |
+
f"estilo prova de residência médica da USP. Formato: "
|
81 |
+
f"'Enunciado clínico: [texto]. Alternativas: A) [opção], B) [opção], C) [opção], D) [opção]. "
|
82 |
+
f"Gabarito: [letra]. Explicação: [texto].'"
|
|
|
83 |
)
|
84 |
try:
|
85 |
inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
86 |
+
outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.7, top_p=0.9)
|
87 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
88 |
parts = response.split("Alternativas:")
|
89 |
if len(parts) > 1:
|
|
|
93 |
explanation_part = parts[1].split("Explicação:")[1].strip() if "Explicação:" in parts[1] else "Explicação padrão"
|
94 |
options = [opt.strip() for opt in options_part.split(",")]
|
95 |
if len(options) >= 4:
|
96 |
+
result = {
|
97 |
"question": f"Enunciado clínico: {question_part}",
|
98 |
"options": [f"A) {options[0]}", f"B) {options[1]}", f"C) {options[2]}", f"D) {options[3]}"],
|
99 |
"answer": answer_part,
|
100 |
"explanation": explanation_part
|
101 |
}
|
102 |
+
# Libera memória
|
103 |
+
gc.collect()
|
104 |
+
return result
|
105 |
+
result = {"question": response, "options": [], "answer": "", "explanation": "Explicação padrão"}
|
106 |
+
gc.collect()
|
107 |
+
return result
|
108 |
except Exception as e:
|
109 |
+
gc.collect()
|
110 |
return {"question": f"Erro na geração: {e}", "options": [], "answer": "", "explanation": "Tente novamente."}
|
111 |
|
112 |
@app.get("/generate")
|