-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHomepage.py
204 lines (172 loc) Β· 8.05 KB
/
Homepage.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
import streamlit as st
from functions import mongoConnect
from pymongo import MongoClient, GEOSPHERE, ASCENDING
from functions import get_coordinates
import datetime
from functions import filter_events
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut, GeocoderUnavailable, GeocoderInsufficientPrivileges
import time
import random
import uuid
from pages.Load import tags_opt
from functions import filter_query, get_and_resize_artist_image, get_user_location
st.set_page_config(
page_title="Homepage",
page_icon="π₯",
layout='wide'
)
st.title('π₯ Ticket:orange[***quack***]')
'In this page you will be able to see the upcoming events and buy tickets for them. '
past_events = st.toggle('Show Past Events π
')
# Mi collego al client
client = mongoConnect()
# Carico il database
db = client['ufs_data_lake']
# Inizializzo le 4 collections e le carico su streamlit
st.session_state['db'] = client['ufs_data_lake']
st.session_state['artists'] = db['artists']
st.session_state['events'] = db['events']
st.session_state['locations'] = db['locations']
st.session_state['tickets'] = db['tickets']
st.session_state['tickets'] = db['tickets']
# Questi index mi servono per usare le geoqueries
db['locations'].create_index([("location", "2dsphere")])
db['events'].create_index([("location_coordinates", "2dsphere")])
# La current date mi serve per qualcosa dopo
current_datetime = datetime.datetime.now()
# Mi serve la lista degli artisti per poterla usare nei filtri
artisti = db['artists'].find({})
#if 'artisti_pictures' not in st.session_state:
# try:
# st.session_state.artisti_pictures = {a['artist'].strip():get_and_resize_artist_image(a['artist'].strip()) for a in artisti}
# except:
# print("Non sono riuscito a caricare le immagini degli artisti")
# Carico gli eventi da mostrare nella homepage in base al toggle past_events
if past_events:
events = db['events'].find({}).sort('date', ASCENDING)
elif not past_events:
current_datetime = datetime.datetime.now()
events = db['events'].find({
'date': {'$gte': current_datetime} # gte current datetime = da oggi in poi. Non mostro la roba vecchia
}).sort('date', ASCENDING) # Il sort Γ¨ per ordinare dal piu' recente
# luoghi = db['locations'].find({})
# luoghi = [luogo for luogo in luoghi]
events = [event for event in events]
filters = {}
# Inizializzo il dizionario per i filtri
with st.expander('Search Filters'):
filtered_events = {}
# E quello per gli eventi filtrati
col1,col2,col3= st.columns(3)
with col1:
artista_filtro = st.selectbox("Nome artista", options=[a['artist'] for a in artisti], index = None)
nome_evento_filtro = st.text_input("Nome evento")
with col2:
data_start = st.date_input("Da")
data_end = st.date_input("A", value=None)
with col3:
luogo_filtro = st.text_input("Luogo")
distanza_filtro = st.text_input(label='Distanza dal luogo in km', value=None)
with col1:
add = st.button('β
Conferma')
reset = st.button('π Resetta i filtri')
posizione = st.button('π Posizione ')
with col3:
tags = st.selectbox(label='Tags', options=tags_opt, index=None)
if add:
if artista_filtro:
filters['artisti'] = artista_filtro
if nome_evento_filtro:
filters['nome_evento'] = nome_evento_filtro
if data_start and data_end:
filters['date'] = {'start' : data_start, 'end' : data_end}
if luogo_filtro and distanza_filtro:
try:
distanza_filtro_km = int(distanza_filtro.strip())
coordinates = get_coordinates(luogo_filtro)
if coordinates != 'Non ho trovato il luogo':
filters['coordinate'] = (coordinates[1], coordinates[0]) # [longitude, latitude]
filters['distanza'] = distanza_filtro_km
except:
st.error('Distanza non valida')
if tags:
filters['tags'] = tags
query = str(filter_query(filters))
# Per mostrare la query che sto eseguendo
filtered_events = filter_events(db['events'], filters)
events = [event for event in filtered_events]
st.code('db.events.find('+query+')')
if posizione:
user_location = get_user_location()
filters['coordinate'] = (user_location[1], user_location[0])
if distanza_filtro:
distanza_filtro_km = int(distanza_filtro.strip())
filters['distanza'] = distanza_filtro_km
if not distanza_filtro:
filters['distanza'] = 1
if artista_filtro:
filters['artisti'] = artista_filtro
if nome_evento_filtro:
filters['nome_evento'] = nome_evento_filtro
if data_start and data_end:
filters['date'] = {'start' : data_start, 'end' : data_end}
if tags:
filters['tags'] = tags
query = str(filter_query(filters))
# Per mostrare la query che sto eseguendo
filtered_events = filter_events(db['events'], filters)
events = [event for event in filtered_events]
st.code('db.events.find('+query+')')
# Mostro i filtri
with col2:
filters
c1, c2 = st.columns(2)
columns = [c1,c2]
def print_event(event:dict):
st.subheader(f":violet[**{event['event_name']}**]")
if ('Concerto' or 'Spettacolo' or 'Musica' or 'Classica' or 'Jazz' or 'Rock' or 'Arte' or 'Musica') in event['tags']:
try:
artista_main = event['artist'][0].strip()
if not 'artists_covers' in st.session_state:
st.session_state['artists_covers'] = {}
st.session_state['artists_covers'][artista_main] = get_and_resize_artist_image(artista_main)
st.image(image=st.session_state['artists_covers'][artista_main])
elif 'artists_covers' in st.session_state:
if artista_main in st.session_state['artists_covers']:
st.image(image=st.session_state['artists_covers'][artista_main])
elif artista_main not in st.session_state['artists_covers']:
st.session_state['artists_covers'][artista_main] = get_and_resize_artist_image(artista_main)
st.image(image=st.session_state['artists_covers'][artista_main])
except:
print(f"Non ho trovato l'immagine per '{event['artist'][0]}'")
f"π
:blue[*Data:*] {event['date'].strftime('**%d/%m**, %H:%M')}, :orange[***| {', '.join(event['tags'])}***]"
f"π¨βπ¨ :blue[*Artisti:*] {', '.join(event['artist'])}"
f"πΊοΈ :blue[*Location:*] {event['location']}, {event['location_city']}"
f"ποΈ :blue[*Posti disponibili:*] {event['freeSlots']}"
f"π€ :blue[*Prezzo:*] {event['price']} π"
f"{event['description']}"
confirm_event = st.form_submit_button("Add to cart")
if confirm_event:
if int(event['freeSlots']) != 0:
if int(event['freeSlots'])>0 and event['date'] > current_datetime:
try:
st.session_state['cart'].append({'evento':event['event_name'], 'price':event['price'], 'artist':event['artist'], '_id':event['_id']})
st.toast(f"Ho aggiunto {event['event_name']} al carrello π")
except:
st.session_state['cart'] = []
else:
st.error("Il concerto non Γ¨ piu' disponibile")
for i in range(0,len(events),2):
with c1:
with st.form(f'{i}'):
print_event(events[i])
with c2:
try:
with st.form(f'{i+1}'):
print_event(events[i+1])
except:
pass
#artist_name = "George Benson"
#result_image = get_and_resize_artist_image(artist_name)
#st.image(result_image)