/
Home.py
216 lines (184 loc) · 8.26 KB
/
Home.py
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#------------------------------------------------------------------------------
# PA nº 1 - Dashboard Projeto Fome Zero
#
# Curso . . .: Análise de dados com Python
# Instituição: COMUNIDADE DS
# Arquivo . .: HOME.PY
# Finalidade : Página de apresentação do APP
# Start: 18.6.2023
# manoelmendonca@hotmail.com Last: 27.6.2023
#------------------------------------------------------------------------------
# SOME STREAMLIT REF:
# IMAGE . . . : https://docs.streamlit.io/library/api-reference/media/st.image
# MARKDOWN. . : https://docs.streamlit.io/library/api-reference/text/st.markdown
# WRITE . . . : https://docs.streamlit.io/library/api-reference/write-magic/st.write
# MULTISELECT : https://docs.streamlit.io/library/api-reference/widgets/st.multiselect
# DOWNLOAD. . : https://docs.streamlit.io/knowledge-base/using-streamlit/how-download-file-streamlit
# https://docs.streamlit.io/library/api-reference/widgets/st.download_button
# PLOTLY CHART: https://docs.streamlit.io/library/api-reference/charts/st.plotly_chart
import pandas as pd
import numpy as np
import streamlit as st
from PIL import Image
import folium
from streamlit_folium import folium_static
from locale import atof, setlocale, LC_NUMERIC
from dbutil import dbutil
#--------- CLASSE: PÁGINA 'HOME' ----------------------------------------------
class app_home():
#..... CONSTRUCTOR
def __init__(self) -> None:
self.dfhome: pd.core.frame.DataFrame = None
#self.util: dbutil = None
return
#..... BARRA LATERAL
def BarraLateral(self) -> None:
#..... ICONE+TÍTULO DO APP
image_path = 'Restaurant_Icon.png'
image = Image.open( image_path )
# OBS: elemento 'image' não prevê incluir texto lateral
st.sidebar.image( image, width=80 )
st.sidebar.markdown( '# Fome Zero' )
#..... FILTROS
st.sidebar.markdown( '## Filtros' )
st.sidebar.write('Escolha os **PAÍSES** cujas **INFORMAÇÕES** deseja visualizar:')
# Radio Button - todos ou só alguns países...
the_countries = self.util.get_all_countries()
default_countries = self.util.countries_with_more_restaurants( 6 )
qty_countries = st.sidebar.radio(
"",
('Os principais','Todos'),
label_visibility="collapsed" )
if qty_countries == 'Todos':
default_countries = the_countries
# Critérios de filtragem
country_options = st.sidebar.multiselect(
label='Seleção:',
options=the_countries,
default=default_countries )
# Obtém dataframe filtrado
self.dfhome = self.util.get_items_with_these_countries(country_options)
#..... Download Button
st.sidebar.markdown("""---""")
csv_file = self.dfhome.to_csv()
txt = 'Dados tratados e com filtragem do usuário'
if st.sidebar.download_button('Baixar dados', csv_file, None, 'text/csv', help=txt):
st.sidebar.write( 'Download OK :thumbsup:' )
#..... Assinatura do autor
st.sidebar.markdown("""---""")
st.sidebar.write('')
st.sidebar.caption('Autor.....: Manoel Mendonça - 2023')
st.sidebar.caption(':blue[manoelmendonca@hotmail.com]')
st.sidebar.caption('[menezes.mendonca.nom.br](http://menezes.mendonca.nom.br)')
# fim
return
#..... PÁGINA PRINCIPAL
def MainPage(self):
#..... Título
with st.container():
col1, col2, col3 = st.columns( 3 )
with col1:
image_path = 'Restaurant_Icon.png'
image = Image.open( image_path )
st.image( image, width=160 )
with col2:
st.write('# Fome Zero!')
#..... SubTítulo
st.write( "### O melhor lugar para encontrar o seu mais novo restaurante favorito" )
#..... Indicadores gerais de desempenho
st.markdown("""---""")
st.write( "### Nossa plataforma vem alcançando as seguintes marcas:" )
with st.container():
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
st.write('**Países selecionados**')
with col2:
st.write('**Cidades cadastradas**')
with col3:
st.write('**Restaurantes cadastrados**')
with col4:
st.write('**Avaliações feitas na plataforma**')
with col5:
st.write('**Tipos de culinárias ofertadas**')
with st.container():
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
tot = len( self.dfhome['country_name'].unique() ) # países
st.markdown('## **'+str(tot)+'**')
with col2:
tot = len( self.dfhome['city'].unique() ) # cidades
st.markdown('## **'+str(tot)+'**')
with col3:
tot = len( self.dfhome['restaurant_name'].unique() ) # restaurantes
#txt = '{:,.0f}'.format(tot)
txt = self.num_to_str( tot )
st.markdown('## **'+txt+'**')
with col4:
df1 = self.dfhome['votes'] # avaliações
tot = df1.sum()
txt = self.num_to_str( tot )
st.markdown('## **'+txt+'**')
with col5:
tot = len( self.dfhome['unique_cuisine'].unique() ) # culinárias
st.markdown('## **'+str(tot)+'**')
#..... MAPA MUNDI
st.markdown("""---""")
self.country_map()
# FIM
return
#..... MAPA MUNDI
def country_map( self ) -> None:
colunas = ['city','aggregate_rating','rating_color','latitude','longitude']
df2 = self.dfhome.loc[: ,colunas]
# df3 = pontos a colocar no mapa
# --> [ city, aggregate_rating, latitude, longitude ]
df3 = ( df2.loc[:,:].groupby(['city','aggregate_rating','rating_color'])
.median()
.reset_index() )
# Desenhar MAPA
CityMap = folium.Map( zoom_start=11 )
for index, location_info in df3.iterrows():
# Insere, um por um, os pinos no mapa.
folium.Marker( [location_info['latitude'],
location_info['longitude']],
popup=location_info[['city','aggregate_rating']],
icon=folium.Icon( color=self.util.color_name(location_info['rating_color']) ) ).add_to(CityMap)
folium_static( CityMap, width=1024, height=600 )
# FIM
return
def num_to_str( self, inNUM: float ) -> str:
txt = ''
# Se o número for menor que 10.000, só converte e pronto
if inNUM < 10000:
txt = '{:,.0f}'.format( inNUM )
# Se o número for entre 10.000 e 999.999, divide por mil e responde: 10 mil
elif inNUM < 999999:
num = inNUM / 1000
txt = '{:,.1f}'.format( num ) + ' mil'
# Se o número for menor que bilhão, divide por milhao e responde: 13 milhões
elif inNUM < 999999999:
num = inNUM / 1000000
txt = '{:,.2f}'.format( num ) + ' mi'
else:
num = inNUM / 1000000000
txt = '{:,.2f}'.format( num ) + ' bi'
return txt
#--------- MAIN HOME PROCEDURE ------------------------------------------------
def main():
st.set_page_config(
page_title="Home",
page_icon="🍴",
layout='wide'
)
MyCSV = 'http://menezes.mendonca.nom.br/datasets/zomato.csv'
util = dbutil()
util.LoadDataframe( MyCSV )
util.GeneralCleansing() # clean & adjust data
#..... Cria a Home e inclui BarraLateral e PáginaPrincipal
HomePage = app_home()
HomePage.util = util
HomePage.BarraLateral()
HomePage.MainPage()
return
#--------- START ME UP --------------------------------------------------------
main()