import gradio as gr from transformers import pipeline import os # Añade esto para verificar la versión de Gradio en tiempo de ejecución print(f"Gradio version at runtime: {gr.__version__}") # --- Model Loading --- MODEL_ID = "Light-Dav/sentiment-analysis-full-project" try: # Esto carga tu modelo pre-entrenado desde Hugging Face Hub # top_k=None asegura que se devuelvan las puntuaciones de todas las clases (positivo, negativo, neutral) sentiment_analyzer = pipeline("sentiment-analysis", model=MODEL_ID, top_k=None) model_loaded_successfully = True print("Sentiment analysis model loaded successfully.") except Exception as e: print(f"Error loading model: {e}") sentiment_analyzer = None model_loaded_successfully = False print("Sentiment analysis model failed to load. Please check MODEL_ID and network connection.") # --- Custom CSS with the NEW COLOR PALETTE --- custom_css = """ body { background-color: #1E2B38; /* Fondo General Oscuro */ color: #FFFFFF; /* Blanco para texto principal */ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .gradio-container { box-shadow: 0 4px 8px rgba(0, 122, 204, 0.2); /* Sombra con Azul Oscuro */ border-radius: 10px; overflow: hidden; background-color: #1E2B38; /* Fondo de la tarjeta, coincide con el body para un look unificado */ padding: 20px; margin-bottom: 20px; border: 1px solid #007ACC; /* Borde sutil con Azul Oscuro */ } h1, h2, h3 { color: #00BFFF; /* Azul Brillante para títulos */ text-align: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; animation: fadeIn 1s ease-in-out; margin-top: 5px; /* Reducir margen superior de títulos */ margin-bottom: 15px; /* Reducir margen inferior de títulos */ } p { color: #AAB7C4; /* Gris medio para texto secundario */ text-align: center; margin-bottom: 20px; /* Margen debajo de los párrafos */ } .gr-textbox label, .gradio-output .label { color: #AAB7C4 !important; /* Gris medio para las etiquetas de los componentes */ font-weight: bold; } .gr-textbox textarea { background-color: #007ACC20; /* Azul Oscuro muy transparente para el fondo del textarea */ border: 1px solid #007ACC; /* Borde con Azul Oscuro */ color: #FFFFFF; /* Texto blanco en el textarea */ border-radius: 6px; padding: 10px; } .gr-button.primary { background-color: #00BFFF !important; /* Azul Brillante para el botón primario */ color: #1E2B38 !important; /* Texto oscuro para el botón primario */ border-radius: 6px; transition: background-color 0.3s ease; padding: 12px 25px; /* Ajuste de padding para el botón */ font-size: 1.1em; font-weight: bold; margin-top: 15px; /* Margen superior para separar del textarea */ } .gr-button.primary:hover { background-color: #007ACC !important; /* Azul Oscuro al pasar el ratón */ color: #FFFFFF !important; /* Texto blanco al pasar el ratón */ } .gradio-output { border: 1px solid #4A5B6C; /* Borde sutil con Gris Claro */ border-radius: 8px; padding: 15px; margin-top: 15px; background-color: #007ACC15; /* Fondo más sutil para la salida */ color: #FFFFFF; /* Texto blanco en la salida */ } .sentiment-display { text-align: center; padding: 10px; border-radius: 6px; margin-top: 10px; font-size: 1.2em; /* Un poco más grande para el resultado principal */ font-weight: bold; color: #FFFFFF; /* Texto blanco para todos los sentimientos */ } .sentiment-positive { background-color: #28a745; /* Verde Bootstrap similar */ } .sentiment-negative { background-color: #dc3545; /* Rojo Bootstrap similar */ } .sentiment-neutral { background-color: #007BFF; /* Azul Bootstrap similar */ } .gradio-example-highlighted { background-color: #00BFFF20 !important; /* Un poco de azul brillante para ejemplos seleccionados */ border: 1px solid #00BFFF !important; } .gradio-example-button { background-color: #4A5B6C !important; /* Gris Claro para los botones de ejemplo */ color: #FFFFFF !important; border: 1px solid #4A5B6C; border-radius: 5px; padding: 8px 12px; margin: 5px; transition: background-color 0.3s ease; } .gradio-example-button:hover { background-color: #007ACC !important; /* Azul Oscuro al pasar el ratón por los ejemplos */ border-color: #00BFFF !important; } hr { border-top: 1px solid #4A5B6C; /* Línea divisoria con Gris Claro */ margin-top: 25px; margin-bottom: 25px; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } """ # --- Helper Function for Sentiment Interpretation --- def interpret_sentiment(label, score): emoji = "" description = "" color_class = "" # Asegúrate de que las etiquetas coincidan con las salidas reales de tu modelo # 'LABEL_0' es negativo, 'LABEL_1' es neutral, 'LABEL_2' es positivo if label.lower() == "positive" or label.lower() == "label_2": emoji = "😊" description = "This text expresses a **highly positive** sentiment." if score > 0.9 else "This text expresses a **positive** sentiment." color_class = "sentiment-positive" elif label.lower() == "negative" or label.lower() == "label_0": emoji = "😠" description = "This text expresses a **highly negative** sentiment." if score > 0.9 else "This text expresses a **negative** sentiment." color_class = "sentiment-negative" elif label.lower() == "neutral" or label.lower() == "label_1": emoji = "😐" description = "This text expresses a **neutral** sentiment." color_class = "sentiment-neutral" else: emoji = "❓" description = "Could not confidently determine sentiment. Unexpected label." color_class = "" return f"
{emoji} {label.upper()} ({score:.2f})
" + \ f"

{description}

" # Asegurar que la descripción también sea blanca # --- Sentiment Analysis Function --- def analyze_sentiment(text): if not model_loaded_successfully: return ( "
⚠️ Model Not Loaded ⚠️

Please contact the administrator. The sentiment analysis model failed to load.

", {}, {"error": "Model loading failed."} ) if not text.strip(): return ( "
✍️ Please enter some text! ✍️

Start typing to analyze its sentiment.

", {}, {"info": "No text entered."} ) try: results = sentiment_analyzer(text)[0] results_sorted = sorted(results, key=lambda x: x['score'], reverse=True) top_sentiment = results_sorted[0] label = top_sentiment['label'] score = top_sentiment['score'] confidence_scores_output = {item['label']: item['score'] for item in results} overall_sentiment_display = interpret_sentiment(label, score) return (overall_sentiment_display, confidence_scores_output, results) except Exception as e: return ( f"
❌ Error ❌

An error occurred during analysis: {e}

", {}, {"error_message": str(e)} ) # --- Gradio Interface --- with gr.Blocks(css=custom_css, theme=None) as demo: gr.Markdown("

🌌 Sentiment Analyzer 🌌

") gr.Markdown("

Uncover the emotional tone of your English text instantly.

") with gr.Column(elem_classes="gradio-container"): text_input = gr.Textbox( lines=7, placeholder="Type your English text here...", label="Your Text", interactive=True, value="This movie was absolutely brilliant! A masterpiece of storytelling and emotion." ) analyze_btn = gr.Button("Analyze Sentiment", variant="primary") gr.Markdown("
") gr.Markdown("

Try some examples:

") examples = gr.Examples( examples=[ ["This product exceeded my expectations, truly amazing!"], ["I found the customer service to be quite disappointing and slow."], ["The weather forecast predicts light rain for tomorrow morning."], ["What a fantastic experience! Highly recommend it."], ["I'm so frustrated with this slow internet connection."], ["The meeting concluded without any major decisions."] ], inputs=text_input, fn=analyze_sentiment, outputs=[gr.HTML(label="Overall Sentiment"), gr.Label(num_top_classes=3, label="Confidence Scores"), gr.JSON(label="Raw Model Output", visible=False)], cache_examples=False ) gr.Markdown("
") gr.Markdown("

📊 Analysis Results

") overall_sentiment_output = gr.HTML(label="Overall Sentiment") confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores") # Deja Raw Model Output como visible=False para ahorrar espacio en el iframe por defecto raw_output = gr.JSON(label="Raw Model Output", visible=False) # --- Event Listeners --- analyze_btn.click( fn=analyze_sentiment, inputs=text_input, outputs=[overall_sentiment_output, confidence_scores_output, raw_output] ) text_input.change( fn=analyze_sentiment, inputs=text_input, outputs=[overall_sentiment_output, confidence_scores_output, raw_output], # live=True # Puedes descomentar si quieres actualizaciones en vivo (consume más recursos) ) # Launch the Gradio application demo.launch()