IABD12 commited on
Commit
dbe0e4c
·
verified ·
1 Parent(s): f493a2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -51
app.py CHANGED
@@ -1,67 +1,45 @@
1
  from transformers import pipeline
 
2
  import gradio as gr
3
 
4
- # Load multilingual model better suited for Spanish to English analysis
5
- model_name = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
6
- sentiment_pipeline = pipeline("sentiment-analysis", model=model_name, tokenizer=model_name)
7
 
8
- def analyze_sentiment(text):
9
  try:
10
- # Get sentiment prediction
11
- result = sentiment_pipeline(text)
 
 
12
 
13
- # Extract raw results
14
- label = result[0]['label']
15
- score = result[0]['score']
16
 
17
- # Define mapping to English outputs
18
- label_map = {
19
- 'LABEL_0': 'Negative',
20
  'LABEL_1': 'Neutral',
21
- 'LABEL_2': 'Positive'
22
- }
23
-
24
- # Enhanced output format with emojis
25
- emoji_map = {
26
- 'Negative': "🔴",
27
- 'Neutral': "🟡",
28
- 'Positive': "🟢"
29
  }
30
 
31
- english_label = label_map[label]
32
-
33
- # More nuanced classification rules
34
- if score < 0.6:
35
- confidence_desc = "Low confidence"
36
- elif score < 0.8:
37
- confidence_desc = "Moderate confidence"
38
- else:
39
- confidence_desc = "High confidence"
40
-
41
- return f"{emoji_map[english_label]} {english_label} ({confidence_desc}: {score:.2f})"
42
 
43
  except Exception as e:
44
- return f"Error analyzing text: {str(e)}"
 
 
 
 
 
 
45
 
46
- # Create Gradio interface
47
- demo = gr.Interface(
48
- fn=analyze_sentiment,
49
- inputs=gr.Textbox(
50
- lines=5,
51
- placeholder="Enter Spanish or English text here...",
52
- label="Text to Analyze"
53
- ),
54
  outputs="text",
55
- title="Multilingual Sentiment Analysis",
56
- description="""Analyzes sentiment of Spanish/English text using XLM-RoBERTa model.
57
- Outputs: Negative 🔴, Neutral 🟡, or Positive 🟢 with confidence level.""",
58
- examples=[
59
- ["Te odio con toda mi alma"],
60
- ["Estoy muy feliz hoy"],
61
- ["The service was average"],
62
- ["This product is amazing!"]
63
- ],
64
- theme="soft"
65
  )
66
 
67
- demo.launch()
 
1
  from transformers import pipeline
2
+ from deep_translator import GoogleTranslator
3
  import gradio as gr
4
 
5
+ modelo_sentimientos = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")
 
 
6
 
7
+ def analizar_sentimiento(texto):
8
  try:
9
+ if detectar_idioma(texto) == 'es':
10
+ texto_traducido = GoogleTranslator(source='auto', target='en').translate(texto)
11
+ else:
12
+ texto_traducido = texto
13
 
14
+ resultado = modelo_sentimientos(texto_traducido)
15
+ etiqueta = resultado[0]['label']
16
+ confianza = resultado[0]['score']
17
 
18
+ mapa_etiquetas = {
19
+ 'LABEL_0': 'Negativo',
 
20
  'LABEL_1': 'Neutral',
21
+ 'LABEL_2': 'Positivo'
 
 
 
 
 
 
 
22
  }
23
 
24
+ return f"Sentimiento: {mapa_etiquetas[etiqueta]} (Confianza: {confianza:.2f})\nTexto analizado: '{texto_traducido}'"
 
 
 
 
 
 
 
 
 
 
25
 
26
  except Exception as e:
27
+ return f"Error: {str(e)}"
28
+
29
+ def detectar_idioma(texto):
30
+ caracteres_es = set('áéíóúñü¿¡')
31
+ if any(caracter in texto.lower() for caracter in caracteres_es):
32
+ return 'es'
33
+ return 'en'
34
 
35
+ # Interfaz Gradio
36
+ interfaz = gr.Interface(
37
+ fn=analizar_sentimiento,
38
+ inputs=gr.Textbox(lines=5, placeholder="Escribe tu texto en español aquí..."),
 
 
 
 
39
  outputs="text",
40
+ title="Traductor y Analizador de Sentimientos",
41
+ description="""Sistema que traduce textos en español a inglés y analiza su sentimiento.
42
+ Ejemplos válidos: 'Me encanta este lugar', 'Odio cuando esto pasa'"""
 
 
 
 
 
 
 
43
  )
44
 
45
+ interfaz.launch()