juancmamacias commited on
Commit
32b2884
·
verified ·
1 Parent(s): 29126f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -104
app.py CHANGED
@@ -1,104 +1,104 @@
1
- # Para Spaces de Hugging Face, la app principal debe llamarse app.py
2
- # Este archivo es una copia de ejemplo_2_.py
3
-
4
- import streamlit as st
5
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, pipeline
6
-
7
- @st.cache_resource
8
- def load_models():
9
- # FLAN-T5 para QA
10
- flan_name = "google/flan-t5-small"
11
- flan_tokenizer = AutoTokenizer.from_pretrained(flan_name)
12
- flan_model = AutoModelForSeq2SeqLM.from_pretrained(flan_name)
13
-
14
- # DistilBERT para clasificación (modelo base)
15
- distil_name = "distilbert-base-uncased-finetuned-sst-2-english"
16
- sentiment_analyzer = pipeline("sentiment-analysis", model=distil_name)
17
-
18
- # DistilBERT fine-tuned propio
19
- custom_name = "juancmamacias/jd-jcms"
20
- custom_analyzer = pipeline("sentiment-analysis", model=custom_name)
21
-
22
- return flan_tokenizer, flan_model, sentiment_analyzer, custom_analyzer
23
-
24
-
25
-
26
- # Cargar modelos antes de cualquier uso
27
- st.set_page_config(page_title="SLM Demo: QA + Sentiment", page_icon="🧠", layout="wide")
28
-
29
- # Ocultar header, footer y menú de Streamlit
30
- hide_streamlit_style = """
31
- <style>
32
- #MainMenu {visibility: hidden;}
33
- header {visibility: hidden;}
34
- footer {visibility: hidden;}
35
- </style>
36
- """
37
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
38
- flan_tokenizer, flan_model, sentiment_analyzer, custom_analyzer = load_models()
39
-
40
- # Layout con dos columnas
41
- col1, col2 = st.columns([1,2])
42
-
43
-
44
- with col1:
45
- st.title("🧠 Small Language Models Demo")
46
- st.markdown("""
47
- Esta app compara tres Small Language Models:
48
- - `flan-t5-small` para responder preguntas.
49
- - `distilBERT` para análisis de sentimiento.
50
- - `distilBERT` fine-tuned para análisis de sentimiento.
51
- """)
52
- st.markdown("""
53
- ## Autores
54
- - Juan Domingo ([GitHub](https://github.com/jdomdev))
55
- - Juan Carlos Macías ([GitHub](https://github.com/juancmacias))
56
- """)
57
-
58
- with col2:
59
- if "history" not in st.session_state:
60
- st.session_state.history = []
61
-
62
- question = st.text_input("💬 Escribe una pregunta o frase para analizar:")
63
-
64
- if st.button("Procesar") and question:
65
- with st.spinner("Procesando..."):
66
- # ➤ Respuesta con FLAN-T5 usando prompt explícito
67
- prompt = f"Answer the following question: {question}"
68
- input_ids = flan_tokenizer(prompt, return_tensors="pt").input_ids
69
- outputs = flan_model.generate(input_ids, max_length=50)
70
- flan_answer = flan_tokenizer.decode(outputs[0], skip_special_tokens=True)
71
-
72
- # ➤ Clasificación con DistilBERT base
73
- sentiment = sentiment_analyzer(question)[0]
74
- sentiment_label = sentiment['label']
75
- sentiment_score = round(sentiment['score'], 3)
76
-
77
- # Traducción de etiquetas para ambos modelos
78
- label_map = {"LABEL_0": "NEGATIVO", "LABEL_1": "POSITIVO", "NEGATIVE": "NEGATIVO", "POSITIVE": "POSITIVO"}
79
- sentiment_label = label_map.get(sentiment_label, sentiment_label)
80
-
81
- # ➤ Clasificación con DistilBERT fine-tuned propio
82
- custom_sentiment = custom_analyzer(question)[0]
83
- custom_label = custom_sentiment['label']
84
- custom_score = round(custom_sentiment['score'], 3)
85
- custom_label = label_map.get(custom_label, custom_label)
86
-
87
- # Guardar en historial
88
- st.session_state.history.append({
89
- "question": question,
90
- "answer": flan_answer,
91
- "sentiment": f"{sentiment_label} ({sentiment_score})",
92
- "custom_sentiment": f"{custom_label} ({custom_score})"
93
- })
94
-
95
- # Mostrar historial
96
- if st.session_state.history:
97
- st.markdown("### 📜 Historial")
98
- for i, item in enumerate(reversed(st.session_state.history), 1):
99
- st.markdown(f"""
100
- **{i}. Entrada:** {item['question']}
101
- 🧠 **Respuesta (FLAN):** {item['answer']}
102
- ❤️ **Sentimiento (base):** {item['sentiment']}
103
- 💙 **Sentimiento (propio):** {item['custom_sentiment']}
104
- ---""")
 
1
+ # Para Spaces de Hugging Face, la app principal debe llamarse app.py
2
+ # Este archivo es una copia de ejemplo_2_.py
3
+
4
+ import streamlit as st
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, pipeline
6
+
7
+ @st.cache_resource
8
+ def load_models():
9
+ # FLAN-T5 para QA
10
+ flan_name = "google/flan-t5-small"
11
+ flan_tokenizer = AutoTokenizer.from_pretrained(flan_name)
12
+ flan_model = AutoModelForSeq2SeqLM.from_pretrained(flan_name)
13
+
14
+ # DistilBERT para clasificación (modelo base)
15
+ distil_name = "distilbert-base-uncased-finetuned-sst-2-english"
16
+ sentiment_analyzer = pipeline("sentiment-analysis", model=distil_name)
17
+
18
+ # DistilBERT fine-tuned propio
19
+ custom_name = "juancmamacias/jd-jcms"
20
+ custom_analyzer = pipeline("sentiment-analysis", model=custom_name)
21
+
22
+ return flan_tokenizer, flan_model, sentiment_analyzer, custom_analyzer
23
+
24
+
25
+
26
+ # Cargar modelos antes de cualquier uso
27
+ st.set_page_config(page_title="SLM Demo: QA + Sentiment", page_icon="🧠", layout="wide")
28
+
29
+ # Ocultar header, footer y menú de Streamlit
30
+ hide_streamlit_style = """
31
+ <style>
32
+ #MainMenu {visibility: hidden;}
33
+ header {visibility: hidden;}
34
+ footer {visibility: hidden;}
35
+ </style>
36
+ """
37
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
38
+ flan_tokenizer, flan_model, sentiment_analyzer, custom_analyzer = load_models()
39
+
40
+ # Layout con dos columnas
41
+ col1, col2 = st.columns([1,2])
42
+
43
+
44
+ with col1:
45
+ st.title("🧠 Small Language Models Demo")
46
+ st.markdown("""
47
+ Esta app compara tres Small Language Models:
48
+ - `flan-t5-small` para responder preguntas.
49
+ - `distilBERT` para análisis de sentimiento.
50
+ - `distilBERT` fine-tuned para análisis de sentimiento.
51
+ """)
52
+ st.markdown("""
53
+ ## Autores
54
+ - Juan Domingo ([GitHub](https://github.com/jdomdev))
55
+ - Juan Carlos Macías ([GitHub](https://github.com/juancmacias))([Porfolio](https://www.juancarlosmacias.es))
56
+ """)
57
+
58
+ with col2:
59
+ if "history" not in st.session_state:
60
+ st.session_state.history = []
61
+
62
+ question = st.text_input("💬 Escribe una pregunta o frase para analizar: improve in English")
63
+
64
+ if st.button("Procesar") and question:
65
+ with st.spinner("Procesando..."):
66
+ # ➤ Respuesta con FLAN-T5 usando prompt explícito
67
+ prompt = f"Answer the following question: {question}"
68
+ input_ids = flan_tokenizer(prompt, return_tensors="pt").input_ids
69
+ outputs = flan_model.generate(input_ids, max_length=50)
70
+ flan_answer = flan_tokenizer.decode(outputs[0], skip_special_tokens=True)
71
+
72
+ # ➤ Clasificación con DistilBERT base
73
+ sentiment = sentiment_analyzer(question)[0]
74
+ sentiment_label = sentiment['label']
75
+ sentiment_score = round(sentiment['score'], 3)
76
+
77
+ # Traducción de etiquetas para ambos modelos
78
+ label_map = {"LABEL_0": "NEGATIVO", "LABEL_1": "POSITIVO", "NEGATIVE": "NEGATIVO", "POSITIVE": "POSITIVO"}
79
+ sentiment_label = label_map.get(sentiment_label, sentiment_label)
80
+
81
+ # ➤ Clasificación con DistilBERT fine-tuned propio
82
+ custom_sentiment = custom_analyzer(question)[0]
83
+ custom_label = custom_sentiment['label']
84
+ custom_score = round(custom_sentiment['score'], 3)
85
+ custom_label = label_map.get(custom_label, custom_label)
86
+
87
+ # Guardar en historial
88
+ st.session_state.history.append({
89
+ "question": question,
90
+ "answer": flan_answer,
91
+ "sentiment": f"{sentiment_label} ({sentiment_score})",
92
+ "custom_sentiment": f"{custom_label} ({custom_score})"
93
+ })
94
+
95
+ # Mostrar historial
96
+ if st.session_state.history:
97
+ st.markdown("### 📜 Historial")
98
+ for i, item in enumerate(reversed(st.session_state.history), 1):
99
+ st.markdown(f"""
100
+ **{i}. Entrada:** {item['question']}
101
+ 🧠 **Respuesta (FLAN):** {item['answer']}
102
+ ❤️ **Sentimiento (base):** {item['sentiment']}
103
+ 💙 **Sentimiento (propio):** {item['custom_sentiment']}
104
+ ---""")