import gradio as gr from transformers import pipeline import logging # Configurar logging para ver información de Transformers (opcional, pero útil para depuración) logging.basicConfig(level=logging.INFO) # --- Funciones para las Pipelines de Transformers --- def sentiment_analysis(text): try: classifier = pipeline("sentiment-analysis") result = classifier(text) return result except Exception as e: return str(e) def text_generation(prompt, max_length=50): try: generator = pipeline("text-generation") result = generator(prompt, max_length=int(max_length), num_return_sequences=1) return result[0]['generated_text'] if result else "No text generated." except Exception as e: return str(e) def zero_shot_classification(text, candidate_labels_str): try: candidate_labels = [label.strip() for label in candidate_labels_str.split(',')] if not candidate_labels or all(not label for label in candidate_labels): return "Por favor, ingresa etiquetas candidatas válidas separadas por comas." classifier = pipeline("zero-shot-classification") result = classifier(text, candidate_labels=candidate_labels) return result except Exception as e: return str(e) def fill_mask(text_with_mask, top_k=2): try: unmasker = pipeline("fill-mask") result = unmasker(text_with_mask, top_k=int(top_k)) return result except Exception as e: return str(e) def named_entity_recognition(text): try: ner_pipeline = pipeline("ner", grouped_entities=True) result = ner_pipeline(text) return result except Exception as e: return str(e) def summarization(text, min_length=30, max_length=130): try: summarizer = pipeline("summarization") result = summarizer(text, min_length=int(min_length), max_length=int(max_length), do_sample=False) return result[0]['summary_text'] if result else "No summary generated." except Exception as e: return str(e) def translation_fr_en(text): try: translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en") result = translator(text) return result[0]['translation_text'] if result else "No translation." except Exception as e: return str(e) # --- Creación de la Interfaz Gradio --- with gr.Blocks(title="Demo de Transformers con Gradio") as demo: gr.Markdown("# Prueba varios modelos de Hugging Face Transformers") gr.Markdown("Recuerda: La primera vez que ejecutes una tarea, el modelo se descargará y puede tardar.") with gr.Tabs(): with gr.TabItem("Análisis de Sentimiento"): with gr.Row(): sa_input = gr.Textbox(label="Ingresa texto para análisis de sentimiento") sa_button = gr.Button("Analizar Sentimiento") sa_output = gr.JSON(label="Resultado del Análisis") sa_button.click(sentiment_analysis, inputs=sa_input, outputs=sa_output) with gr.TabItem("Generación de Texto"): with gr.Row(): tg_input_prompt = gr.Textbox(label="Ingresa un prompt para iniciar la generación") tg_max_length = gr.Number(label="Longitud Máxima", value=50) tg_button = gr.Button("Generar Texto") tg_output = gr.Textbox(label="Texto Generado", lines=5) tg_button.click(text_generation, inputs=[tg_input_prompt, tg_max_length], outputs=tg_output) with gr.TabItem("Clasificación Zero-Shot"): with gr.Row(): zsc_input_text = gr.Textbox(label="Texto a clasificar") zsc_input_labels = gr.Textbox(label="Etiquetas candidatas (separadas por comas)", placeholder="ej: educación, política, negocios") zsc_button = gr.Button("Clasificar (Zero-Shot)") zsc_output = gr.JSON(label="Resultado de la Clasificación") zsc_button.click(zero_shot_classification, inputs=[zsc_input_text, zsc_input_labels], outputs=zsc_output) with gr.TabItem("Rellenar Máscara (Fill-Mask)"): with gr.Row(): fm_input_text = gr.Textbox(label="Texto con para rellenar", placeholder="This course will teach you all about models.") fm_top_k = gr.Number(label="Top K resultados", value=2) fm_button = gr.Button("Rellenar Máscara") fm_output = gr.JSON(label="Posibles Rellenos") fm_button.click(fill_mask, inputs=[fm_input_text, fm_top_k], outputs=fm_output) with gr.TabItem("Reconocimiento de Entidades Nombradas (NER)"): ner_input = gr.Textbox(label="Texto para NER") ner_button = gr.Button("Reconocer Entidades") ner_output = gr.JSON(label="Entidades Reconocidas") ner_button.click(named_entity_recognition, inputs=ner_input, outputs=ner_output) with gr.TabItem("Resumen de Texto (Summarization)"): with gr.Row(): summ_input_text = gr.TextArea(label="Texto largo para resumir", lines=7) with gr.Row(): summ_min_len = gr.Number(label="Longitud Mínima del Resumen", value=30) summ_max_len = gr.Number(label="Longitud Máxima del Resumen", value=130) summ_button = gr.Button("Generar Resumen") summ_output = gr.Textbox(label="Resumen Generado", lines=5) summ_button.click(summarization, inputs=[summ_input_text, summ_min_len, summ_max_len], outputs=summ_output) with gr.TabItem("Traducción (Francés a Inglés)"): tr_input_text = gr.Textbox(label="Texto en Francés para traducir a Inglés", placeholder="Ce cours est produit par Hugging Face.") tr_button = gr.Button("Traducir") tr_output = gr.Textbox(label="Texto Traducido (Inglés)") tr_button.click(translation_fr_en, inputs=tr_input_text, outputs=tr_output) if __name__ == "__main__": demo.launch()