jdomdev commited on
Commit
de1c092
·
verified ·
1 Parent(s): 8bacc4c

Upload Streamlit file(app.py) and requirements.txt

Browse files
Files changed (2) hide show
  1. app.py +102 -0
  2. requirements.txt +14 -3
app.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline
3
+ from huggingface_hub import InferenceClient
4
+
5
+ # --- Configuración de la Página ---
6
+ st.set_page_config(
7
+ page_title="Sentiment Analysis Comparator",
8
+ page_icon="🎭",
9
+ layout="wide"
10
+ )
11
+
12
+ st.title("Sentiment Analysis: SLM vs. LLM Comparator 🚀")
13
+ st.markdown("""
14
+ Introduce una reseña de una película en inglés y compara las predicciones de sentimiento
15
+ de diferentes modelos de Hugging Face.
16
+ """)
17
+
18
+ # --- Modelos a Comparar ---
19
+ YOUR_SLM_MODEL = "jdomdev/imdb-slm-vs-llm-pill"
20
+ DISTILBERT_MODEL = "distilbert-base-uncased-finetuned-sst-2-english"
21
+ INFERENCE_API_LLM = "meta-llama/Meta-Llama-3-8B-Instruct"
22
+
23
+ # --- Carga de Modelos con Pipeline (en caché para eficiencia) ---
24
+ @st.cache_resource
25
+ def load_pipeline(model_name):
26
+ """Carga un pipeline de Hugging Face."""
27
+ st.info(f"Cargando el modelo pipeline: {model_name}...")
28
+ return pipeline("sentiment-analysis", model=model_name)
29
+
30
+ # --- Implementación con InferenceClient (Tu método mejorado) ---
31
+
32
+ @st.cache_resource
33
+ def get_inference_client():
34
+ """Inicializa y cachea el InferenceClient."""
35
+ st.info(f"Inicializando cliente para: {INFERENCE_API_LLM}...")
36
+ hf_token = st.secrets.get("HUGGINGFACE_TOKEN")
37
+ if not hf_token:
38
+ st.error("Token de Hugging Face no encontrado. Por favor, configúralo en los 'Secrets' de tu Space.")
39
+ return None
40
+ return InferenceClient(model=INFERENCE_API_LLM, token=hf_token)
41
+
42
+ def query_inference_api(review: str):
43
+ """Consulta un LLM usando InferenceClient.chat_completion."""
44
+ client = get_inference_client()
45
+ if client is None:
46
+ return {"error": "No se pudo inicializar el cliente de Hugging Face."}
47
+
48
+ try:
49
+ # Usamos el formato de mensajes que funciona para modelos de chat
50
+ messages = [
51
+ {"role": "system", "content": "You are a sentiment analysis expert. Analyze the sentiment of the user's movie review. Respond with only one word: POSITIVE or NEGATIVE."},
52
+ {"role": "user", "content": review}
53
+ ]
54
+
55
+ response = client.chat_completion(
56
+ messages=messages,
57
+ max_tokens=5, # Suficiente para "POSITIVE" o "NEGATIVE"
58
+ temperature=0.1,
59
+ )
60
+
61
+ # Extraemos el contenido de la respuesta
62
+ sentiment = response.choices[0].message.content.strip().upper()
63
+ return {"label": sentiment}
64
+
65
+ except Exception as e:
66
+ st.error(f"Error al consultar el LLM: {e}")
67
+ return {"error": str(e)}
68
+
69
+ # --- Interfaz de Usuario ---
70
+ user_input = st.text_area("Escribe aquí la reseña de la película:", "I loved this movie, the acting was superb and the plot was gripping!", height=150)
71
+
72
+ if st.button("Analizar Sentimiento"):
73
+ if user_input:
74
+ st.subheader("Resultados del Análisis:")
75
+
76
+ col1, col2, col3 = st.columns(3)
77
+
78
+ # 1. Tu modelo SLM afinado
79
+ with col1:
80
+ st.info(f"Tu SLM: `{YOUR_SLM_MODEL}`")
81
+ with st.spinner("Analizando..."):
82
+ your_model_pipeline = load_pipeline(YOUR_SLM_MODEL)
83
+ result = your_model_pipeline(user_input)
84
+ st.json(result)
85
+
86
+ # 2. Modelo DistilBERT estándar
87
+ with col2:
88
+ st.info(f"Otro SLM: `{DISTILBERT_MODEL}`")
89
+ with st.spinner("Analizando..."):
90
+ distilbert_pipeline = load_pipeline(DISTILBERT_MODEL)
91
+ result = distilbert_pipeline(user_input)
92
+ st.json(result)
93
+
94
+ # 3. LLM vía API de Inferencia con InferenceClient
95
+ with col3:
96
+ st.info(f"LLM (API): `{INFERENCE_API_LLM}`")
97
+ with st.spinner("Consultando al LLM..."):
98
+ result = query_inference_api(user_input)
99
+ st.json(result)
100
+
101
+ else:
102
+ st.warning("Por favor, introduce una reseña para analizar.")
requirements.txt CHANGED
@@ -1,3 +1,14 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers[torch]
2
+ datasets
3
+ evaluate
4
+ scikit-learn
5
+ accelerate
6
+ streamlit
7
+ openai
8
+ huggingface_hub
9
+ aiohttp
10
+ dotenv
11
+ pipdeptree
12
+ pipreqs
13
+ tinycss2
14
+ pip-tools