streamlit-demo / app.py
athan37's picture
matplotlib close
88a09c6
import streamlit as st
import pandas as pd
import numpy as np
import requests
import time
from datetime import datetime
from timeit import default_timer as timer
from datetime import timedelta
import matplotlib.pyplot as plt
# import warnings
# warnings.filterwarnings("ignore")
# import seaborn as sns
st.set_page_config(
page_title="Real-Time IoT",
page_icon="βœ…",
layout="wide",
)
st.title("Iot Data")
DATA_URL = 'https://trace.vfsc.vn/iot/xxx'
# def stream():
# s = requests.Session()
# with requests.get(DATA_URL, headers=None, stream=True, params={"items":160}) as response:
# # print(response.status_code)
# for line in response.iter_lines():
# if line: print(line)
# # print(line.decode('utf-8')['data'])
# stream()
def load_data(n):
response = requests.get(DATA_URL) if n <= 0 else requests.get(DATA_URL, params = {"items": n})
plan = response.json()['plan']
data = response.json()['data']
return data
def is_duplicate(s):
# st.write(s)
res = False
if "duplicates" in st.session_state:
check_candidate = (s["Id"], s["Time"])
res = check_candidate in st.session_state["duplicates"]
else:
st.session_state["duplicates"] = set()
st.session_state["duplicates"].add(check_candidate)
return res
if 'time' not in st.session_state:
st.session_state['time'] = timer()
df = pd.DataFrame.from_dict(load_data(10))
df.rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns', inplace=True)
st.session_state["duplicates"] = set(zip(df["Id"], df["Time"]))
col1, col2 = st.columns(2)
graph_type = "Bar"
data_col = "STemp"
with col1:
data_col = st.selectbox(
"Choose column to plot",
[col for col in df.columns if col.lower() in "upt, batv, solv, stemp".split(", ")],
)
# st.checkbox("Disable selectbox widget", key="disabled")
graph_type = st.radio(
"Choose graph type πŸ‘‰",
('Bar', 'Line'),
)
with col2:
placeholder = st.empty()
while True:
# new_df = pd.DataFrame.from_dict(load_data(st.session_state["count"]))
# new_df.rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns', inplace=True)
curr_time = timer()
# st.write(timedelta(seconds = curr_time - st.session_state['time']))
if curr_time - st.session_state['time'] >= 2:
# st.write("Passed")
new_data = pd.DataFrame.from_dict(load_data(0)).rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns').iloc[-1]
# print(df.iloc[-1]["Id"], new_data["Id"])
if is_duplicate(new_data):
pass
# st.write("Dup")
else:
df.loc[len(df)] = new_data
st.session_state['time'] = curr_time
# df = pd.concat([df, pd.DataFrame(new_ele)])
chart_data = (
df[data_col].tolist(),
df["moment"].apply(lambda timestr : datetime.strptime(timestr, '%d/%m/%Y %H:%M:%S').time().strftime("%H:%M:%S")).tolist()
)
# chart_data.set_index('date')
with placeholder.container():
plt.rcParams["figure.figsize"] = (20, 8)
plt.close()
fig, ax = plt.subplots()
try:
if graph_type == 'Line':
ax.plot(range(len(chart_data[0])), chart_data[0])
elif graph_type == 'Bar':
ax.bar(range(len(chart_data[0])), chart_data[0])
plt.xticks(range(len(chart_data[0])), chart_data[1])
# st.bar_chart(chart_data)
except Exception as e:
pass
st.pyplot(fig)
# st.map(df)
st.write(df)
# time.sleep(15)
# st.write(st.session_state)
# st.session_state["count"] += 1