Light-Dav commited on
Commit
51ebb55
·
verified ·
1 Parent(s): 94adeb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -38
app.py CHANGED
@@ -1,47 +1,203 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
- # ID de tu modelo de análisis de sentimientos que ya subiste
 
 
5
  MODEL_ID = "Light-Dav/sentiment-analysis-full-project"
6
 
7
- # Cargar el pipeline del modelo
8
  try:
9
- classifier = pipeline("sentiment-analysis", model=MODEL_ID)
 
 
 
10
  except Exception as e:
11
- print(f"Error al cargar el modelo {MODEL_ID}: {e}")
12
- classifier = None # Para evitar errores si classifier no se inicializa
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def analyze_sentiment(text):
15
- if not text:
16
- return {"Positive": 0.0, "Negative": 0.0, "Neutral": 0.0}
17
-
18
- if classifier is None:
19
- return {"Error": "Modelo no cargado. Contactar al administrador."}
20
-
21
- # Realizar la inferencia
22
- # pipeline devuelve una lista de diccionarios, tomamos el primero
23
- results = classifier(text)[0]
24
-
25
- # Formatear el resultado para Gradio (diccionario de etiqueta a score)
26
- formatted_results = {}
27
- for item in results:
28
- formatted_results[item['label']] = item['score']
29
-
30
- return formatted_results
31
-
32
- # Crear la interfaz de Gradio
33
- iface = gr.Interface(
34
- fn=analyze_sentiment,
35
- inputs=gr.Textbox(lines=3, placeholder="Escribe tu texto aquí..."),
36
- outputs=gr.Label(num_top_classes=3), # Mostrar las 3 clases principales (Positivo, Negativo, Neutro)
37
- title="🤖 Análisis de Sentimientos en Español",
38
- description="Introduce un texto en español y el modelo predecirá su sentimiento (Positivo, Negativo, Neutro).",
39
- examples=[
40
- ["Me encantó este libro, es fascinante y lo recomiendo totalmente."],
41
- ["El servicio fue terrible, muy lento y poco amable."],
42
- ["La reunión se programó para el jueves a las 10 AM."]
43
- ]
44
- )
45
-
46
- # Iniciar la aplicación Gradio (esto se hace automáticamente en Hugging Face Spaces)
47
- iface.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  from transformers import pipeline
3
 
4
+ # --- Model Loading ---
5
+ # Using the model ID you've been working with, which is fine-tuned on an English dataset (IMDB).
6
+ # It's crucial that this model is indeed fine-tuned for sentiment analysis in English.
7
  MODEL_ID = "Light-Dav/sentiment-analysis-full-project"
8
 
 
9
  try:
10
+ # Attempt to load the pipeline. This needs to be outside the function for efficiency.
11
+ # The 'return_all_scores=True' is important for getting scores for all labels.
12
+ sentiment_analyzer = pipeline("sentiment-analysis", model=MODEL_ID, return_all_scores=True)
13
+ model_loaded_successfully = True
14
  except Exception as e:
15
+ print(f"Error loading model: {e}")
16
+ sentiment_analyzer = None
17
+ model_loaded_successfully = False
18
 
19
+ # --- Custom CSS for a unique look ---
20
+ custom_css = """
21
+ body {
22
+ background-color: #f0f2f5; /* Light grey background */
23
+ }
24
+ .gradio-container {
25
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
26
+ border-radius: 15px;
27
+ overflow: hidden;
28
+ background-color: #ffffff; /* White card background */
29
+ }
30
+ h1, h2, h3 {
31
+ color: #4CAF50; /* Green accents */
32
+ text-align: center;
33
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
34
+ animation: fadeIn 1s ease-in-out;
35
+ }
36
+ .gr-button.primary {
37
+ background-color: #4CAF50 !important;
38
+ color: white !important;
39
+ border-radius: 8px;
40
+ transition: background-color 0.3s ease;
41
+ }
42
+ .gr-button.primary:hover {
43
+ background-color: #45a049 !important;
44
+ }
45
+ .gradio-output {
46
+ border: 1px solid #e0e0e0;
47
+ border-radius: 10px;
48
+ padding: 15px;
49
+ margin-top: 20px;
50
+ background-color: #f9f9f9;
51
+ }
52
+ .sentiment-display {
53
+ text-align: center;
54
+ padding: 10px;
55
+ border-radius: 8px;
56
+ margin-top: 15px;
57
+ font-size: 1.2em;
58
+ font-weight: bold;
59
+ }
60
+ .sentiment-positive {
61
+ background-color: #e6ffe6; /* Light green */
62
+ color: #28a745; /* Darker green */
63
+ }
64
+ .sentiment-negative {
65
+ background-color: #ffe6e6; /* Light red */
66
+ color: #dc3545; /* Darker red */
67
+ }
68
+ .sentiment-neutral {
69
+ background-color: #e6f7ff; /* Light blue */
70
+ color: #007bff; /* Darker blue */
71
+ }
72
+ @keyframes fadeIn {
73
+ from { opacity: 0; }
74
+ to { opacity: 1; }
75
+ }
76
+ """
77
+
78
+ # --- Helper Function for Sentiment Interpretation ---
79
+ def interpret_sentiment(label, score):
80
+ emoji = ""
81
+ description = ""
82
+ color_class = ""
83
+
84
+ if label.lower() == "positive": # Your model might output 'LABEL_2' or 'POS'
85
+ emoji = "😊"
86
+ description = "This text expresses a **highly positive** sentiment." if score > 0.9 else "This text expresses a **positive** sentiment."
87
+ color_class = "sentiment-positive"
88
+ elif label.lower() == "negative": # Your model might output 'LABEL_0' or 'NEG'
89
+ emoji = "😠"
90
+ description = "This text expresses a **highly negative** sentiment." if score > 0.9 else "This text expresses a **negative** sentiment."
91
+ color_class = "sentiment-negative"
92
+ elif label.lower() == "neutral": # Your model might output 'LABEL_1' or 'NEUTRAL'
93
+ emoji = "😐"
94
+ description = "This text expresses a **neutral** sentiment."
95
+ color_class = "sentiment-neutral"
96
+ else:
97
+ emoji = "❓"
98
+ description = "Could not confidently determine sentiment."
99
+ color_class = ""
100
+
101
+ return f"<div class='sentiment-display {color_class}'>{emoji} {label.upper()} ({score:.2f})</div>" + \
102
+ f"<p>{description}</p>"
103
+
104
+ # --- Sentiment Analysis Function ---
105
  def analyze_sentiment(text):
106
+ if not model_loaded_successfully:
107
+ return {
108
+ "Overall Sentiment": "<div class='sentiment-display'>⚠️ Model Not Loaded ⚠️</div><p>Please contact the administrator. The sentiment analysis model failed to load.</p>",
109
+ "Confidence Scores": {},
110
+ "Raw Output": "Model loading failed."
111
+ }
112
+
113
+ if not text.strip():
114
+ return {
115
+ "Overall Sentiment": "<div class='sentiment-display'>✍️ Please enter some text! ✍️</div><p>Start typing to analyze its sentiment.</p>",
116
+ "Confidence Scores": {},
117
+ "Raw Output": ""
118
+ }
119
+
120
+ try:
121
+ # The pipeline returns a list of dictionaries if return_all_scores=True
122
+ # e.g., [[{'label': 'LABEL_0', 'score': 0.9}, {'label': 'LABEL_1', 'score': 0.05}]]
123
+ results = sentiment_analyzer(text)[0] # Get the first (and only) list of results
124
+
125
+ # Sort results by score in descending order
126
+ results_sorted = sorted(results, key=lambda x: x['score'], reverse=True)
127
+
128
+ # Get the top sentiment
129
+ top_sentiment = results_sorted[0]
130
+ label = top_sentiment['label']
131
+ score = top_sentiment['score']
132
+
133
+ # Format for Gradio Label component (Dictionary {label: score})
134
+ # This is for the 'Confidence Scores' output
135
+ confidence_scores_output = {item['label']: item['score'] for item in results}
136
+
137
+ # Interpret sentiment for the 'Overall Sentiment' output
138
+ overall_sentiment_display = interpret_sentiment(label, score)
139
+
140
+ return {
141
+ "Overall Sentiment": overall_sentiment_display,
142
+ "Confidence Scores": confidence_scores_output,
143
+ "Raw Output": str(results)
144
+ }
145
+ except Exception as e:
146
+ return {
147
+ "Overall Sentiment": f"<div class='sentiment-display'>❌ Error ❌</div><p>An error occurred during analysis: {e}</p>",
148
+ "Confidence Scores": {},
149
+ "Raw Output": f"Error: {e}"
150
+ }
151
+
152
+ # --- Gradio Interface ---
153
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo: # Using gr.Blocks for more layout control
154
+ gr.Markdown("# ✨ Sentiment Spark ✨")
155
+ gr.Markdown("---")
156
+ gr.Markdown("### Uncover the emotional tone of your English text instantly!")
157
+
158
+ with gr.Row(): # Horizontal layout for input and outputs
159
+ with gr.Column(scale=2):
160
+ text_input = gr.Textbox(
161
+ lines=7,
162
+ placeholder="Type your English text here...",
163
+ label="Your Text",
164
+ interactive=True,
165
+ value="This movie was absolutely brilliant! A masterpiece of storytelling and emotion."
166
+ )
167
+ analyze_btn = gr.Button("Analyze Sentiment", variant="primary") # The main action button
168
+
169
+ gr.Markdown("---")
170
+ gr.Markdown("### Try some examples:")
171
+ gr.Examples(
172
+ examples=[
173
+ ["This product exceeded my expectations, truly amazing!"],
174
+ ["I found the customer service to be quite disappointing and slow."],
175
+ ["The weather forecast predicts light rain for tomorrow morning."],
176
+ ["What a fantastic experience! Highly recommend it."],
177
+ ["I'm so frustrated with this slow internet connection."],
178
+ ["The meeting concluded without any major decisions."]
179
+ ],
180
+ inputs=text_input,
181
+ cache_examples=True # Caching examples for faster loading
182
+ )
183
+
184
+ with gr.Column(scale=3):
185
+ gr.Markdown("## 📈 Analysis Results 📉")
186
+ overall_sentiment_output = gr.HTML(label="Overall Sentiment") # Using HTML to render custom styled sentiment
187
+ confidence_scores_output = gr.Label(num_top_classes=3, label="Confidence Scores") # Default Gradio Label
188
+ raw_output = gr.JSON(label="Raw Model Output", visible=False) # For debugging/advanced users
189
+
190
+ # --- Event Listeners ---
191
+ text_input.change(
192
+ fn=analyze_sentiment,
193
+ inputs=text_input,
194
+ outputs=[overall_sentiment_output, confidence_scores_output, raw_output],
195
+ # live=True # Uncomment for live updates as user types (can be resource intensive)
196
+ )
197
+ analyze_btn.click(
198
+ fn=analyze_sentiment,
199
+ inputs=text_input,
200
+ outputs=[overall_sentiment_output, confidence_scores_output, raw_output]
201
+ )
202
+
203
+ demo.launch()