Skip to content
This repository has been archived by the owner on Feb 22, 2024. It is now read-only.

Commit

Permalink
chore: better UI
Browse files Browse the repository at this point in the history
  • Loading branch information
d116626 committed Jan 23, 2024
1 parent 9e0069f commit 2bb09c0
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
from streamlit_folium import st_folium


st.set_page_config(layout="wide", page_title="Pontos Críticos em Tempo Real")
st.image("./data/logo/logo.png", width=300)


def create_map(chart_data):
chart_data = chart_data.fillna("")
# center map on the mean of the coordinates
Expand Down Expand Up @@ -137,8 +141,6 @@ def get_apis_last_updates():

# #### FRONTEND ####

st.set_page_config(layout="wide", page_title="Pontos Críticos em Tempo Real")
st.image("./data/logo/logo.png", width=300)

st.sidebar.dataframe(get_apis_last_updates())

Expand Down
30 changes: 16 additions & 14 deletions app/pages/📷 Pontos de Alagamento | Vision AI.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,19 @@ def load_alagamento_detectado_ia():

chart_data, last_update = load_alagamento_detectado_ia()


# Display images in a grid
num_columns = 2
num_rows = (len(chart_data) + num_columns - 1) // num_columns

for row in range(num_rows):
cols = st.columns(num_columns)
for col in range(num_columns):
index = row * num_columns + col
if index < len(chart_data):
with cols[col]:
st.subheader(f"Camera ID: {chart_data.iloc[index]['id_camera']}")
st.write(f"Last Update: {last_update}")
st.image(chart_data.iloc[index]["image_url"], use_column_width=True)
if len(chart_data) > 0:
# Display images in a grid
num_columns = 2
num_rows = (len(chart_data) + num_columns - 1) // num_columns

for row in range(num_rows):
cols = st.columns(num_columns)
for col in range(num_columns):
index = row * num_columns + col
if index < len(chart_data):
with cols[col]:
st.subheader(f"Camera ID: {chart_data.iloc[index]['id_camera']}")
st.write(f"Last Update: {last_update}")
st.image(chart_data.iloc[index]["image_url"], use_column_width=True)
else:
st.markdown("Não foi identificado nenhum ponto de alagamento.")
125 changes: 104 additions & 21 deletions app/📣 Home.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@


def get_icon_color(label: Union[bool, None]):
if label:
if label is True:
return "red"
elif label is None:
return "gray"
else:
elif label is False:
return "green"
else:
return "gray"


def create_map(chart_data):
Expand All @@ -32,26 +32,31 @@ def create_map(chart_data):
else:
m = folium.Map(location=[-22.917690, -43.413861], zoom_start=11)

for i in range(0, len(chart_data)):
ai_classification = chart_data.iloc[i].get("ai_classification", [])
if ai_classification == []:
ai_classification = [{"label": None}]
for _, row in chart_data.iterrows():
icon_color = get_icon_color(row["label"])
folium.Marker(
location=[chart_data.iloc[i]["latitude"], chart_data.iloc[i]["longitude"]],
# add nome_da_camera and status to tooltip
tooltip=f"""
ID: {chart_data.iloc[i]['id_camera']}""",
# change icon color according to status
location=[row["latitude"], row["longitude"]],
# Adicionar id_camera ao tooltip
tooltip=f"ID: {row['id_camera']}",
# Alterar a cor do ícone de acordo com o status
icon=folium.features.DivIcon(
icon_size=(15, 15),
icon_anchor=(7, 7),
html=f'<div style="width: 20px; height: 20px; background-color: {get_icon_color(ai_classification[0].get("label", None))}; border: 2px solid black; border-radius: 70%;"></div>',
html=f'<div style="width: 20px; height: 20px; background-color: {icon_color}; border: 2px solid black; border-radius: 70%;"></div>',
),
).add_to(m)

return m


def label_emoji(label):
if label is True:
return "🔴"
elif label is False:
return "🟢"
else:
return "⚫"


@st.cache_data
def load_alagamento_detectado_ia():
raw_api_data = requests.get(
Expand All @@ -63,31 +68,109 @@ def load_alagamento_detectado_ia():
).text.strip('"')
)

return pd.DataFrame(raw_api_data), last_update
dataframe = pd.json_normalize(
raw_api_data,
record_path="ai_classification",
meta=[
"datetime",
"id_camera",
"url_camera",
"latitude",
"longitude",
"image_url",
],
)

dataframe = dataframe.sort_values(by="label", ascending=True).reset_index(drop=True)

return dataframe, last_update


def get_table_cameras_with_images(dataframe):
# filter only flooded cameras
table_data = (
dataframe[dataframe["label"].notnull()]
.sort_values(by="label", ascending=False)
.reset_index(drop=True)
)
table_data["emoji"] = table_data["label"].apply(label_emoji)

col_order = [
"emoji",
"id_camera",
"object",
"url_camera",
"image_url",
]
table_data = table_data[col_order]

return table_data


chart_data, last_update = load_alagamento_detectado_ia()
data_with_image = get_table_cameras_with_images(chart_data)

folium_map = create_map(chart_data)

## front

st.markdown("# Mapa de Alagamentos | Vision AI")

st.markdown(
f"""
**Last update**: {str(last_update)}
**Ultima atualização**: {str(last_update)}
Status snapshots:
- Total: {len(chart_data)}
- Sucessos: {len(data_with_image)}
- Falhas:{len(chart_data) - len(data_with_image)}
""",
)


st.dataframe(
data_with_image,
column_config={
"emoji": st.column_config.Column(
"",
),
"id_camera": st.column_config.Column(
"ID Camera",
help="ID Camera",
# width="medium",
required=True,
),
"object": st.column_config.Column(
"Objeto",
help="Objeto",
# width="medium",
required=True,
),
"url_camera": st.column_config.Column(
"URL Camera",
help="ID Camera",
# width="medium",
required=True,
),
"image_url": st.column_config.Column(
"URL Imagem",
help="ID Camera",
# width="medium",
required=True,
),
},
# hide_index=True,
use_container_width=True,
)


map_data = st_folium(folium_map, key="fig1", height=600, width=1200)

# select chart_data obj based on last_object_clicked coordinates
obj_coord = map_data["last_object_clicked"]


if obj_coord is None:
st.write("Click on a marker to view the details")
st.write("Clique no marcador para ver mais detalhes.")
else:
selected_data = chart_data[
(chart_data["latitude"] == obj_coord["lat"])
Expand All @@ -106,11 +189,11 @@ def load_alagamento_detectado_ia():
.T
)

selected_data.columns = ["Informations"]
selected_data.columns = ["Informações"]

st.markdown("### 📷 Camera snapshot")
if image_url is None:
st.markdown("Failed to get snapshot from the camera.")
st.markdown("Falha ao capturar o snapshot da camera.")
else:
st.image(image_url)

Expand Down

0 comments on commit 2bb09c0

Please sign in to comment.