streamlit-demo / app.py
athan37's picture
unfix
762f7b9
raw
history blame
3.29 kB
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
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"]
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 = pd.DataFrame(
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():
if graph_type == 'Line':
st.line_chart(chart_data)
elif graph_type == 'Bar':
st.bar_chart(chart_data)
# st.map(df)
st.write(df)
# time.sleep(15)
# st.write(st.session_state)
# st.session_state["count"] += 1