alexander1010 commited on
Commit
48c1d12
·
verified ·
1 Parent(s): ee2af14

Update service sentiment_analysis_service

Browse files
src/expon/presentation/domain/services/sentiment_analysis_service.py CHANGED
@@ -2,28 +2,18 @@ import os
2
  from transformers import pipeline
3
  from typing import Dict
4
 
5
- # 👇 Redirigir el caché de Hugging Face a /tmp
6
  os.environ["TRANSFORMERS_CACHE"] = "/tmp/transformers"
7
  os.environ["HF_HOME"] = "/tmp/huggingface"
8
 
9
  class SentimentAnalysisService:
10
  def __init__(self):
11
  try:
12
- print("[LOG] Cargando token de Hugging Face...")
13
- token = os.getenv("HUGGINGFACE_TOKEN")
14
- if not token:
15
- raise ValueError("No se encontró HUGGINGFACE_TOKEN en variables de entorno")
16
- except Exception as e:
17
- print("[ERROR] Token inválido:", e)
18
- raise
19
-
20
- try:
21
- print("[LOG] Cargando pipeline...")
22
  self.pipeline = pipeline(
23
  "text-classification",
24
- model="mrm8488/t5-base-spanish-emotion",
25
- top_k=1,
26
- use_auth_token=token # 👈 Se usa directamente el token aquí
27
  )
28
  print("[LOG] Pipeline cargado correctamente.")
29
  except Exception as e:
@@ -35,7 +25,7 @@ class SentimentAnalysisService:
35
  try:
36
  result = self.pipeline(transcript)[0]
37
  print("[LOG] Resultado del modelo:", result)
38
- label = result['label'].lower()
39
  score = result['score']
40
  except Exception as e:
41
  print("[ERROR] Falló la predicción:", e)
@@ -45,14 +35,13 @@ class SentimentAnalysisService:
45
  "confidence": 0.0
46
  }
47
 
 
48
  emotion_mapping = {
49
- "confianza": "motivado",
50
- "alegría": "entusiasta",
51
- "tristeza": "desmotivado",
52
- "miedo": "ansioso",
53
- "enfado": "frustrado",
54
- "amor": "conectado",
55
- "sorpresa": "sorprendido",
56
  }
57
 
58
  mapped_emotion = emotion_mapping.get(label, "desconocido")
@@ -62,5 +51,5 @@ class SentimentAnalysisService:
62
  "emotion_probabilities": {
63
  mapped_emotion: 1.0
64
  },
65
- "confidence": 1.0
66
  }
 
2
  from transformers import pipeline
3
  from typing import Dict
4
 
5
+ # 👇 Redirigir el caché de Hugging Face a /tmp para compatibilidad en Hugging Face Spaces
6
  os.environ["TRANSFORMERS_CACHE"] = "/tmp/transformers"
7
  os.environ["HF_HOME"] = "/tmp/huggingface"
8
 
9
  class SentimentAnalysisService:
10
  def __init__(self):
11
  try:
12
+ print("[LOG] Cargando pipeline con modelo público...")
 
 
 
 
 
 
 
 
 
13
  self.pipeline = pipeline(
14
  "text-classification",
15
+ model="nlptown/bert-base-multilingual-uncased-sentiment", # ✅ modelo público
16
+ top_k=1
 
17
  )
18
  print("[LOG] Pipeline cargado correctamente.")
19
  except Exception as e:
 
25
  try:
26
  result = self.pipeline(transcript)[0]
27
  print("[LOG] Resultado del modelo:", result)
28
+ label = result['label'].lower() # Ejemplo: "1 star", "5 stars"
29
  score = result['score']
30
  except Exception as e:
31
  print("[ERROR] Falló la predicción:", e)
 
35
  "confidence": 0.0
36
  }
37
 
38
+ # Mapeo muy simple de estrellas a emociones (puedes personalizar esto más)
39
  emotion_mapping = {
40
+ "1 star": "frustrado",
41
+ "2 stars": "desmotivado",
42
+ "3 stars": "neutro",
43
+ "4 stars": "motivado",
44
+ "5 stars": "entusiasta"
 
 
45
  }
46
 
47
  mapped_emotion = emotion_mapping.get(label, "desconocido")
 
51
  "emotion_probabilities": {
52
  mapped_emotion: 1.0
53
  },
54
+ "confidence": round(score, 2)
55
  }