File size: 4,642 Bytes
1f9bcbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383b5a4
1f9bcbb
 
73f3ef4
 
0e1ede7
73f3ef4
 
 
 
 
 
 
1f9bcbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee0547d
1f9bcbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# -*- 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 add_page_title
import time
import pandas as pd
import matplotlib.pyplot as plt
from as_bert_df import batch_predict_sentiment_stars

c1 = st.container()
c2 = st.container()

# function to show base page
def show_base_page():
    with c1:
        # show 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;">
        El archivo de reseñas debe ser un archivo de texto que contenga una reseña por cada línea.
        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) 
    
        # placeholder for hide widget
        global placeholder, placeholder2
        placeholder = st.empty()
        placeholder2 = st.empty()
    
        # file upload    
        global uploaded_file
        uploaded_file = placeholder.file_uploader("Cargar archivo de reseñas ...", type=['txt', 'csv'], key='uploader')      

        global button_1
        button_1 = placeholder2.button(" :gear: Predecir", type="primary", key='but_1')

        

# define action funtion for button     
def predecir():
    if uploaded_file is not None:
        global data_df
        # 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()
        
        data_df = pd.read_csv(uploaded_file, sep=";") 
        if data_df.shape[0] > 0:
            # formatear columnas
            if data_df.shape[1] < 2:
                data_df['review'] = 0
                data_df.columns = ["review","predict"]
        
            result = batch_predict_sentiment_stars(data_df)
            
            # mostrar resulyados
            show_data_editor(result) 
            show_chart(result)
            placeholder.empty()
            placeholder2.empty()
        else:
            st.error("Archivo se encuentra vacío.")     
    else:
        st.error("Debe subir un archivo de texto")

def show_data_editor(data_df):
    with c2:
        st.data_editor(
            data_df,
            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_chart(data):
    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()

if button_1:
    predecir()