demo / page1.py
xerubin
update streamlit pages
0e1ede7
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 13:22:00 2023
@author: Essio Rubin C.
"""
from PIL import Image
import streamlit as st
from st_pages import Page, show_pages, add_page_title
import time
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from as_bert_df import batch_predict_sentiment_stars
c1 = st.container()
c2 = st.container()
data_df = pd.DataFrame(
{
"review": ["",], "predict":[0,]
}
)
# function to show base page
def show_base_page():
with c1:
# the title and icon to the current page
add_page_title()
# show text
text_css = """
<p style="font-family: Verdana; font-size: 15px; font-weight: 400; ; color: #5b5f62;">
Una reseña debe ser un texto que tenga una o varias oraciones que incluyan opiniones referidas a servicios que brinda
un Hotel.
La reseña puede estar escrita en idioma español, holandés, italiano, alemán, francés o inglés.
</p>
<p style="font-family: Verdana; font-size: 15px; font-weight: 400; ; color: #5b5f62;">
El resultado de la predicción (sentimiento) es un numero de extrellas, entre 1 y 5.
<ul style="font-family: Verdana; font-size: 15px; font-weight: 400; ; color: #5b5f62;">
<li>1 estrellas: DEPLORABLE</li>
<li>2 estrellas: MALO</li>
<li>3 estrellas: NEUTRAL</li>
<li>4 estrellas: BUENO</li>
<li>5 estrellas: EXCELENTE</li>
<ul>
</p>
<p>&nbsp;</p>
"""
st.write(text_css, unsafe_allow_html=True)
# show image
img = Image.open("assets/flags.jpg")
st.image(img, width=200)
# function to show data editor
def show_data_editor(data):
with c1:
# dataframe editor
global st_data
global placeholder
placeholder = st.empty()
#st_data = st.data_editor(
st_data = placeholder.data_editor(
data,
column_config={
"review": st.column_config.TextColumn(
"review",
help="Ingrese la reseña.",
width="large",
required=True,
max_chars=500,
validate="[a-zA-Záéíóúñ.,]+$"
),
"predict": st.column_config.NumberColumn(
"predict",
help="Sentimiento expresado en cantidad de estrellas.",
width="small",
required=False,
default=0,
min_value=0,
max_value=5,
format="%d ⭐",
)
},
hide_index=True,
num_rows="dynamic",
height = 260,
width = 900,
)
def show_button():
global placeholder2
placeholder2 = st.empty()
with c1:
# show buttons
global button_1
button_1 = placeholder2.button(" :gear: Predecir", type="primary", key='but_1')
# define action funtion for button
def predecir():
#st.session_state.disabled = True
data_df = st_data
if data_df.shape[0] > 0:
st.write(data_df.shape[0])
# progress bar
progress_text = "Procesando. Espere."
my_bar = st.progress(0, text=progress_text)
for percent_complete in range(100):
time.sleep(0.01)
my_bar.progress(percent_complete + 1, text=progress_text)
time.sleep(1)
my_bar.empty()
result = batch_predict_sentiment_stars(data_df)
placeholder.empty()
placeholder2.empty()
show_data_editor(result)
show_chart(result)
else:
st.error("Debe ingresar una reseña.")
def show_chart(data):
with c2:
fig, ax = plt.subplots()
fig.set_figwidth(5)
fig.set_figheight(3)
# title
ax.set_title("Histograma de Frecuencias", fontsize = 8)
# axis
ax.set_xlim([0, 6])
# x label
ax.set_xlabel('Sentimiento (Número de estrellas)', fontsize = 6)
ax.set_ylabel('Frecuencia', fontsize = 6)
# Crear un histograma
ax.hist(data['predict'], bins=20, color ="green")
# Mostrar el gráfico en Streamlit
st.pyplot(fig)
#------------------------------------------
# main flow
#------------------------------------------
show_base_page()
show_data_editor(data_df)
show_button()
if button_1:
predecir()