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

Commit

Permalink
feat: connect to API
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel-milan committed Nov 14, 2023
1 parent 78979e1 commit 7440c49
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 27 deletions.
5 changes: 4 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Install virtualenv and create a virtual environment
RUN pip install --no-cache-dir -U poetry && \
RUN apt-get update && \
apt-get install --no-install-recommends -y ffmpeg libsm6 libxext6 && \
rm -rf /var/lib/apt/lists/* && \
pip install --no-cache-dir -U poetry && \
poetry config virtualenvs.create false

# Copy the poetry.lock and pyproject.toml files
Expand Down
99 changes: 74 additions & 25 deletions app/📣 Alagamentos em Tempo Real.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from pathlib import Path
import base64
from datetime import datetime
import io

import folium
import pandas as pd
from PIL import Image
import requests
import streamlit as st
from streamlit_folium import st_folium

Expand All @@ -16,31 +21,76 @@
identificar alagamentos em imagens."""
)

tmp_data_path = Path(__file__).parent.parent / "data" / "cameras_h3_1.csv"
chart_data = pd.read_csv(tmp_data_path)[:100]
# dropna status_right from chart_data
chart_data = chart_data.dropna(subset=["status_right"])
# remove all Unnamed columns
chart_data = chart_data.loc[:, ~chart_data.columns.str.contains("^Unnamed")]
chart_data.to_csv(index=False)

# center map on the mean of the coordinates
m = folium.Map(
location=[chart_data["latitude"].mean(), chart_data["longitude"].mean()],
zoom_start=11,
def generate_image(image_b64: str) -> Image:
"""Generate image from base64 string"""
image_bytes = base64.b64decode(image_b64)
image = Image.open(io.BytesIO(image_bytes))
return image


if "error" not in st.session_state:
st.session_state["error"] = False

try:
raw_api_data = requests.get(
"https://api.dados.rio/v2/clima_alagamento/alagamento_detectado_ia/"
).json()
# raw_api_data = [
# {
# "datetime": "2023-11-14 19:01:26",
# "id_camera": "001",
# "url_camera": "rtsp://url:port",
# "latitude": -22.881833,
# "longitude": -43.371461,
# "image_base64": base64.b64encode(
# open("./data/imgs/flooded2.jpg", "rb").read()
# ).decode("utf-8"),
# "ai_classification": [
# {
# "object": "alagamento",
# "label": True,
# "confidence": 0.7,
# },
# ],
# },
# ]
last_update = requests.get(
"https://api.dados.rio/v2/clima_alagamento/ultima_atualizacao_alagamento_detectado_ia/"
).text.strip('"')
st.session_state["error"] = False
except Exception as exc:
raw_api_data = []
last_update = ""
st.session_state["error"] = True

st.markdown(
f"""
**Conexão com API**: {"✅" if not st.session_state["error"] else "❌"}
**Última atualização**: {datetime.strptime(last_update, "%Y-%m-%d %H:%M:%S").strftime("%d/%m/%Y %H:%M:%S")}
""",
)

chart_data = pd.DataFrame(raw_api_data)

# center map on the mean of the coordinates
if len(chart_data) > 0:
m = folium.Map(
location=[chart_data["latitude"].mean(), chart_data["longitude"].mean()],
zoom_start=11,
)
else:
m = folium.Map(location=[-22.917690, -43.413861], zoom_start=11)

for i in range(0, len(chart_data)):
folium.Marker(
location=[chart_data.iloc[i]["latitude"], chart_data.iloc[i]["longitude"]],
# add nome_da_camera and status to tooltip
tooltip=f"""
Status: {chart_data.iloc[i]['status']}<br>
Endereço: {chart_data.iloc[i]['nome_da_camera']}""",
ID: {chart_data.iloc[i]['id_camera']}""",
# change icon color according to status
icon=folium.Icon(
color="green" if chart_data.iloc[i]["status"] == "normal" else "red"
),
icon=folium.Icon(color="orange"),
# icon=folium.CustomIcon(
# icon_data["url"],
# icon_size=(icon_data["width"], icon_data["height"]),
Expand All @@ -63,23 +113,22 @@
& (chart_data["longitude"] == obj_coord["lng"])
]

image_b64 = selected_data["image_base64"].values[0]

selected_data = (
selected_data[["nome_da_camera", "bairro", "zona", "chuva_15min", "rtsp"]]
selected_data[["id_camera", "url_camera"]]
.rename(
columns={
"nome_da_camera": "Endereço",
"bairro": "Bairro",
"zona": "Zona",
"chuva_15min": "🌧️ Chuva 15min",
"rtsp": "🎥 Camera",
"id_camera": "Identificador",
"url_camera": "🎥 Camera",
}
)
.T
)

selected_data.columns = ["Infos"]

st.markdown("## 📷 Imagem da Camera")
st.image("./data/imgs/flooded1.jpg")
st.markdown("### 📷 Imagem da Câmera")
st.image(generate_image(image_b64))

selected_data
16 changes: 15 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ streamlit = "^1.28.1"
folium = "0.14.0"
streamlit-folium = "^0.15.1"
streamlit-extras = "^0.3.5"
streamlit-autorefresh = "^1.0.1"
pillow = "^10.1.0"


[build-system]
Expand Down

0 comments on commit 7440c49

Please sign in to comment.