Spaces:
Runtime error
Runtime error
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| import gradio as gr | |
| import os | |
| import torch | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| print(device) | |
| # Asegúrate de que tu token de Hugging Face está cargado como una variable de entorno | |
| hf_token = os.environ.get("token") | |
| if hf_token is not None: | |
| from huggingface_hub import HfFolder | |
| HfFolder.save_token(hf_token) | |
| else: | |
| print("No se encontró el token de Hugging Face. Asegúrate de que la variable de entorno HF_TOKEN esté configurada.") | |
| # Cargar el tokenizador | |
| tokenizer = AutoTokenizer.from_pretrained("Juliofc/chaterapia_model") | |
| # Añadir el token especial [PAD] | |
| #tokenizer.add_special_tokens({'pad_token': '[PAD]'}) | |
| # Cargar el modelo base y ajustar el tamaño de los embeddings de tokens | |
| model_base = AutoModelForCausalLM.from_pretrained("google/gemma-2b-it") | |
| model_base.resize_token_embeddings(len(tokenizer)) | |
| # Cargar el modelo con el adaptador | |
| model_with_adapter = PeftModel.from_pretrained(model_base, "Juliofc/chaterapia_model").to(device) | |
| # Suponiendo que `tokenizer` y `model_with_adapter` ya están inicializados | |
| def chat_with_model(user_input, conversation_history=""): | |
| # Asegúrate de que conversation_history tenga un valor inicial adecuado | |
| if conversation_history is None: | |
| conversation_history = "" | |
| conversation_history += f"Usuario: {user_input}\n" | |
| input_tokens = tokenizer.encode(user_input, return_tensors='pt').to(device) | |
| output_tokens = model_with_adapter.generate(input_tokens, max_new_tokens=50, pad_token_id=tokenizer.pad_token_id) | |
| generated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True) | |
| conversation_history += f"Modelo: {generated_text}\n" | |
| return "", conversation_history | |
| # Define los componentes de la interfaz de Gradio | |
| with gr.Blocks() as demo: | |
| gr.Markdown("### Chat con IA") | |
| input_text = gr.Textbox(label="Tu mensaje") | |
| submit_button = gr.Button("Enviar") | |
| output_text = gr.Textbox(label="Historial de la conversación", lines=10, interactive=False) | |
| # Inicializa el estado conversation_history con una cadena vacía | |
| conversation_history = gr.State(value="") | |
| submit_button.click( | |
| fn=chat_with_model, | |
| inputs=[input_text, conversation_history], | |
| outputs=[input_text, conversation_history] | |
| ) | |
| # Asegúrate de lanzar usando un puerto disponible o soluciona el problema del puerto ocupado como se discutió anteriormente. | |
| demo.launch() |