Update app.py
Browse files
app.py
CHANGED
|
@@ -1,224 +1,118 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import torch
|
| 4 |
-
import pickle
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import requests
|
| 7 |
from huggingface_hub import snapshot_download
|
| 8 |
|
| 9 |
-
# ======================================================
|
| 10 |
-
# CONFIGURACIΓN GENERAL
|
| 11 |
-
# ======================================================
|
| 12 |
MODEL_REPO = "teszenofficial/mtptz"
|
| 13 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
|
| 15 |
-
APP_TITLE = "π€ MTP"
|
| 16 |
-
APP_SUBTITLE = "MTP-1 Β· Modelo de Lenguaje Experimental"
|
| 17 |
-
|
| 18 |
-
# ======================================================
|
| 19 |
-
# DESCARGAR REPO DEL MODELO
|
| 20 |
-
# ======================================================
|
| 21 |
repo_path = snapshot_download(
|
| 22 |
repo_id=MODEL_REPO,
|
| 23 |
repo_type="model",
|
| 24 |
local_dir="mtptz_repo",
|
| 25 |
local_dir_use_symlinks=False
|
| 26 |
)
|
| 27 |
-
|
| 28 |
sys.path.insert(0, repo_path)
|
| 29 |
|
| 30 |
from model import MTPMiniModel
|
| 31 |
from tokenizer import MTPTokenizer
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
# ======================================================
|
| 36 |
-
MODEL_PATH = os.path.join(repo_path, "mtp_mini.pkl")
|
| 37 |
-
TOKENIZER_PATH = os.path.join(repo_path, "mtp_tokenizer.model")
|
| 38 |
-
|
| 39 |
-
with open(MODEL_PATH, "rb") as f:
|
| 40 |
-
model_data = pickle.load(f)
|
| 41 |
|
| 42 |
-
tokenizer = MTPTokenizer(
|
| 43 |
-
|
| 44 |
|
| 45 |
model = MTPMiniModel(
|
| 46 |
-
vocab_size=
|
| 47 |
-
d_model=
|
| 48 |
-
n_layers=
|
| 49 |
-
n_heads=
|
| 50 |
-
d_ff=
|
| 51 |
-
max_seq_len=
|
| 52 |
dropout=0.0
|
| 53 |
)
|
| 54 |
-
|
| 55 |
-
model.load_state_dict(model_data["model_state_dict"])
|
| 56 |
model.to(DEVICE)
|
| 57 |
model.eval()
|
| 58 |
|
| 59 |
-
#
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
"""
|
| 64 |
-
BΓΊsqueda externa usando Wikipedia.
|
| 65 |
-
Deep = mΓ‘s artΓculos relacionados.
|
| 66 |
-
"""
|
| 67 |
-
search_url = "https://es.wikipedia.org/w/api.php"
|
| 68 |
-
|
| 69 |
-
params = {
|
| 70 |
"action": "query",
|
| 71 |
"list": "search",
|
| 72 |
-
"srsearch":
|
| 73 |
"format": "json"
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
r = requests.get(search_url, params=params, timeout=10)
|
| 77 |
-
data = r.json()
|
| 78 |
|
| 79 |
-
if
|
| 80 |
return ""
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
return "\n".join(extracts)
|
| 101 |
-
|
| 102 |
-
# ======================================================
|
| 103 |
-
# PROMPT RAG OPTIMIZADO PARA MTP
|
| 104 |
-
# ======================================================
|
| 105 |
-
def build_prompt(question, context, deepthink=False):
|
| 106 |
if context:
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
- No inventes datos.
|
| 114 |
-
- Si la informaciΓ³n no es suficiente, dilo claramente.
|
| 115 |
-
"""
|
| 116 |
-
else:
|
| 117 |
-
base = ""
|
| 118 |
-
|
| 119 |
-
if deepthink:
|
| 120 |
-
thinking = """
|
| 121 |
-
Modo DeepThink activado:
|
| 122 |
-
- Razona con cuidado.
|
| 123 |
-
- Explica las ideas de forma ordenada.
|
| 124 |
-
- Evita asociaciones incorrectas.
|
| 125 |
-
- Prioriza claridad sobre cantidad.
|
| 126 |
-
"""
|
| 127 |
-
else:
|
| 128 |
-
thinking = ""
|
| 129 |
|
| 130 |
-
|
| 131 |
-
{
|
| 132 |
-
{thinking}
|
| 133 |
-
Pregunta:
|
| 134 |
-
{question}
|
| 135 |
|
| 136 |
-
|
| 137 |
"""
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
# ======================================================
|
| 142 |
-
def generate_response(
|
| 143 |
-
message,
|
| 144 |
-
history,
|
| 145 |
-
temperature,
|
| 146 |
-
max_tokens,
|
| 147 |
-
use_web,
|
| 148 |
-
deep_search,
|
| 149 |
-
deepthink
|
| 150 |
-
):
|
| 151 |
-
context = ""
|
| 152 |
-
if use_web:
|
| 153 |
-
context = web_search(message, deep=deep_search)
|
| 154 |
-
|
| 155 |
-
prompt = build_prompt(message, context, deepthink)
|
| 156 |
-
|
| 157 |
-
tokens = [tokenizer.bos_id()] + tokenizer.encode(prompt)
|
| 158 |
-
input_ids = torch.tensor([tokens], dtype=torch.long).to(DEVICE)
|
| 159 |
|
| 160 |
with torch.no_grad():
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
max_new_tokens=
|
| 164 |
-
temperature=
|
| 165 |
-
top_k=
|
| 166 |
top_p=0.9
|
| 167 |
)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
generated = generated[:generated.index(tokenizer.eos_id())]
|
| 173 |
|
| 174 |
-
|
|
|
|
|
|
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
# ======================================================
|
| 185 |
-
with gr.Blocks(css="footer {visibility: hidden;}") as demo:
|
| 186 |
-
gr.Markdown(f"# {APP_TITLE}")
|
| 187 |
-
gr.Markdown(APP_SUBTITLE)
|
| 188 |
|
| 189 |
-
|
| 190 |
-
state = gr.State([])
|
| 191 |
|
| 192 |
-
|
| 193 |
-
placeholder="Escribe tu preguntaβ¦",
|
| 194 |
-
show_label=False
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
with gr.Row():
|
| 198 |
-
temperature = gr.Slider(0.1, 2.0, value=0.6, label="Temperature")
|
| 199 |
-
max_tokens = gr.Slider(20, 150, value=80, label="Max tokens")
|
| 200 |
-
|
| 201 |
-
with gr.Row():
|
| 202 |
-
use_web = gr.Checkbox(label="π Buscar en la web", value=False)
|
| 203 |
-
deep_search = gr.Checkbox(label="π§ Deep Search", value=False)
|
| 204 |
-
deepthink = gr.Checkbox(label="π§© DeepThink", value=True)
|
| 205 |
-
|
| 206 |
-
textbox.submit(
|
| 207 |
-
generate_response,
|
| 208 |
-
inputs=[
|
| 209 |
-
textbox,
|
| 210 |
-
state,
|
| 211 |
-
temperature,
|
| 212 |
-
max_tokens,
|
| 213 |
-
use_web,
|
| 214 |
-
deep_search,
|
| 215 |
-
deepthink
|
| 216 |
-
],
|
| 217 |
-
outputs=[chatbot, state]
|
| 218 |
-
)
|
| 219 |
-
|
| 220 |
-
gr.Markdown(
|
| 221 |
-
"β οΈ MTP puede cometer errores. La informaciΓ³n externa puede ser incompleta o inexacta."
|
| 222 |
-
)
|
| 223 |
|
| 224 |
demo.launch()
|
|
|
|
| 1 |
+
import os, sys, torch, pickle, gradio as gr, requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import snapshot_download
|
| 3 |
|
|
|
|
|
|
|
|
|
|
| 4 |
MODEL_REPO = "teszenofficial/mtptz"
|
| 5 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
repo_path = snapshot_download(
|
| 8 |
repo_id=MODEL_REPO,
|
| 9 |
repo_type="model",
|
| 10 |
local_dir="mtptz_repo",
|
| 11 |
local_dir_use_symlinks=False
|
| 12 |
)
|
|
|
|
| 13 |
sys.path.insert(0, repo_path)
|
| 14 |
|
| 15 |
from model import MTPMiniModel
|
| 16 |
from tokenizer import MTPTokenizer
|
| 17 |
|
| 18 |
+
with open(os.path.join(repo_path, "mtp_mini.pkl"), "rb") as f:
|
| 19 |
+
data = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
tokenizer = MTPTokenizer(os.path.join(repo_path, "mtp_tokenizer.model"))
|
| 22 |
+
cfg = data["config"]
|
| 23 |
|
| 24 |
model = MTPMiniModel(
|
| 25 |
+
vocab_size=data["vocab_size"],
|
| 26 |
+
d_model=cfg["model"]["d_model"],
|
| 27 |
+
n_layers=cfg["model"]["n_layers"],
|
| 28 |
+
n_heads=cfg["model"]["n_heads"],
|
| 29 |
+
d_ff=cfg["model"]["d_ff"],
|
| 30 |
+
max_seq_len=cfg["model"]["max_seq_len"],
|
| 31 |
dropout=0.0
|
| 32 |
)
|
| 33 |
+
model.load_state_dict(data["model_state_dict"])
|
|
|
|
| 34 |
model.to(DEVICE)
|
| 35 |
model.eval()
|
| 36 |
|
| 37 |
+
# ---------- WIKIPEDIA SEARCH (RECORTADO) ----------
|
| 38 |
+
def wiki_search(term):
|
| 39 |
+
url = "https://es.wikipedia.org/w/api.php"
|
| 40 |
+
r = requests.get(url, params={
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
"action": "query",
|
| 42 |
"list": "search",
|
| 43 |
+
"srsearch": term,
|
| 44 |
"format": "json"
|
| 45 |
+
}, timeout=10).json()
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
if not r.get("query", {}).get("search"):
|
| 48 |
return ""
|
| 49 |
|
| 50 |
+
title = r["query"]["search"][0]["title"]
|
| 51 |
+
r2 = requests.get(url, params={
|
| 52 |
+
"action": "query",
|
| 53 |
+
"prop": "extracts",
|
| 54 |
+
"explaintext": True,
|
| 55 |
+
"titles": title,
|
| 56 |
+
"format": "json"
|
| 57 |
+
}, timeout=10).json()
|
| 58 |
+
|
| 59 |
+
page = next(iter(r2["query"]["pages"].values()))
|
| 60 |
+
text = page.get("extract", "")
|
| 61 |
+
return text[:500] # π₯ CLAVE
|
| 62 |
+
|
| 63 |
+
# ---------- GENERACIΓN GUIADA ----------
|
| 64 |
+
def chat(msg, hist, use_web):
|
| 65 |
+
context = wiki_search(msg) if use_web else ""
|
| 66 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
if context:
|
| 68 |
+
prompt = f"""
|
| 69 |
+
RESPONDE SOLO CON ESTA INFORMACIΓN.
|
| 70 |
+
NO INVENTES.
|
| 71 |
+
NO CAMBIES EL TEMA.
|
| 72 |
|
| 73 |
+
TEXTO:
|
| 74 |
+
{context}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
PREGUNTA:
|
| 77 |
+
{msg}
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
RESPUESTA CORTA:
|
| 80 |
"""
|
| 81 |
+
else:
|
| 82 |
+
prompt = f"Pregunta:\n{msg}\nRespuesta:\n"
|
| 83 |
|
| 84 |
+
ids = [tokenizer.bos_id()] + tokenizer.encode(prompt)
|
| 85 |
+
x = torch.tensor([ids], device=DEVICE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
with torch.no_grad():
|
| 88 |
+
out = model.generate(
|
| 89 |
+
x,
|
| 90 |
+
max_new_tokens=60,
|
| 91 |
+
temperature=0.4,
|
| 92 |
+
top_k=30,
|
| 93 |
top_p=0.9
|
| 94 |
)
|
| 95 |
|
| 96 |
+
gen = out[0, len(ids):].tolist()
|
| 97 |
+
if tokenizer.eos_id() in gen:
|
| 98 |
+
gen = gen[:gen.index(tokenizer.eos_id())]
|
|
|
|
| 99 |
|
| 100 |
+
resp = tokenizer.decode(gen).strip()
|
| 101 |
+
hist = hist + [(msg, resp)]
|
| 102 |
+
return hist, hist
|
| 103 |
|
| 104 |
+
# ---------- UI ----------
|
| 105 |
+
with gr.Blocks(css="footer{display:none}") as demo:
|
| 106 |
+
gr.Markdown("# π€ MTP β MTP-1")
|
| 107 |
|
| 108 |
+
bot = gr.Chatbot()
|
| 109 |
+
state = gr.State([])
|
| 110 |
|
| 111 |
+
txt = gr.Textbox(placeholder="Escribe una entidad o preguntaβ¦")
|
| 112 |
+
web = gr.Checkbox(label="π Usar Wikipedia", value=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
txt.submit(chat, [txt, state, web], [bot, state])
|
|
|
|
| 115 |
|
| 116 |
+
gr.Markdown("β οΈ MTP-1 es experimental. BΓΊsqueda guiada y respuestas cortas.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
demo.launch()
|