Spaces:
Sleeping
Sleeping
Download app.py from alex-roc/simigpt-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 2.92 kB
-
https://huggingface.co/spaces/alex-roc/simigpt-chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/alex-roc/simigpt-chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/alex-roc/simigpt-chatbot/resolve/main/app.py
2.92 kB
| """SimiGPT — Chatbot en quechua. HF Space (Gradio, ZeroGPU). | |
| Carga el modelo instruido fusionado (privado lab-tecnosocial/simigpt-qwen3-1.7b-instruct) | |
| con el secreto HF_TOKEN del Space. ZeroGPU: la GPU solo existe dentro de @spaces.GPU, | |
| por eso el modelo se carga de forma perezosa. | |
| """ | |
| import os | |
| import re | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| MODEL = os.environ.get("SIMIGPT_CHAT_MODEL", "lab-tecnosocial/simigpt-qwen3-1.7b-instruct") | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| _tok = None | |
| _model = None | |
| def _load(): | |
| global _tok, _model | |
| if _model is None: | |
| _tok = AutoTokenizer.from_pretrained(MODEL, token=HF_TOKEN) | |
| _model = AutoModelForCausalLM.from_pretrained( | |
| MODEL, token=HF_TOKEN, dtype=torch.float16).to("cuda").eval() | |
| return _tok, _model | |
| def _clean(text: str) -> str: | |
| """Limpia artefactos del modelo mini: bloque 'thinking', tokens de scripts no latinos | |
| (ruido), fugas de rol y espacios repetidos.""" | |
| text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL) | |
| # el quechua/español usan alfabeto latino: quita caracteres de otros scripts (ruido). | |
| text = re.sub(r"[^\x20-\x7E\náéíóúÁÉÍÓÚñÑüÜ¿¡«»\"'—–-]", "", text) | |
| text = re.sub(r"\b(user|assistant|system)\b\s*", "", text) # fugas de rol | |
| text = re.sub(r"[ \t]{2,}", " ", text) | |
| text = re.sub(r"\n{2,}", "\n", text).strip() | |
| return text or "…" | |
| def chat(message, history): | |
| tok, model = _load() | |
| msgs = [] | |
| for u, a in (history or []): | |
| msgs += [{"role": "user", "content": u}, {"role": "assistant", "content": a}] | |
| msgs.append({"role": "user", "content": message}) | |
| enc = tok.apply_chat_template(msgs, add_generation_prompt=True, | |
| return_tensors="pt", return_dict=True).to("cuda") | |
| with torch.no_grad(): | |
| out = model.generate(**enc, max_new_tokens=150, temperature=0.7, top_p=0.9, | |
| do_sample=True, repetition_penalty=1.3, no_repeat_ngram_size=3, | |
| pad_token_id=tok.eos_token_id) | |
| gen = out[0][enc["input_ids"].shape[-1]:] | |
| return _clean(tok.decode(gen, skip_special_tokens=True)) | |
| demo = gr.ChatInterface( | |
| fn=chat, | |
| title="SimiGPT — Chatbot en quechua (prototipo)", | |
| description=( | |
| "Modelo mini (Qwen3-1.7B) con *continued pretraining* + instrucciones en quechua, " | |
| "por [Lab Tecnosocial](https://labtecnosocial.org). **Prototipo experimental**: los " | |
| "datos de instrucción son traducción automática; puede alucinar o mezclar. Sirve para " | |
| "demostrar y recibir feedback, no es producto final." | |
| ), | |
| examples=["Napaykuykichik. Imaynalla kachkanki?", | |
| "Bolivia suyumanta huk chiqan willaway.", | |
| "Imataq quechua simi?"], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |