afondiel commited on
Commit
a933b83
Β·
verified Β·
1 Parent(s): 26d6954

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import json
4
+ import argparse
5
+ import time
6
+ import os
7
+
8
+ # Read demo data received from AWS IoT MQTT Broker
9
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
10
+ LOG_FILE = os.path.join(CURRENT_DIR, "demo.json")
11
+
12
+ def load_data():
13
+ try:
14
+ if not os.path.exists(LOG_FILE):
15
+ return pd.DataFrame(columns=["timestamp", "energy_kW"])
16
+ with open(LOG_FILE, "r") as file:
17
+ data = json.load(file)
18
+ df = pd.DataFrame(data)
19
+ df['energy_kW'] = df['energy_kW'].astype(float)
20
+ df['timestamp'] = pd.to_datetime(df['timestamp'], format='%d/%m/%Y')
21
+ return df.head(10) # Show first 10 readings
22
+ except json.JSONDecodeError:
23
+ print("Error decoding JSON from log file.")
24
+ return pd.DataFrame(columns=["timestamp", "energy_kW"])
25
+ except Exception as e:
26
+ print(f"Error loading data: {e}")
27
+ return pd.DataFrame(columns=["timestamp", "energy_kW"])
28
+
29
+ def update_data(df):
30
+ while True:
31
+ time.sleep(1)
32
+ new_data = load_data() # Load only new or changed data
33
+ df.update(value=new_data)
34
+ yield
35
+
36
+ def generate_dashboard(plot_type, show_power, show_timestamp):
37
+ df = load_data()
38
+ if df.empty:
39
+ return df, gr.update(visible=False), gr.update(visible=False)
40
+
41
+ # Filter columns based on checkboxes
42
+ columns_to_show = []
43
+ if show_timestamp:
44
+ columns_to_show.append("timestamp")
45
+ if show_power:
46
+ columns_to_show.append("energy_kW")
47
+
48
+ df_filtered = df[columns_to_show]
49
+
50
+ table_update = gr.update(value=df_filtered, visible=(plot_type == "Table"))
51
+ line_plot_update = gr.update(
52
+ value=df_filtered,
53
+ x="timestamp" if show_timestamp else None,
54
+ y="energy_kW" if show_power else None,
55
+ title="Energy Consumption Over Time",
56
+ tooltip=columns_to_show,
57
+ visible=(plot_type == "Line Plot"),
58
+ height="50vh"
59
+ )
60
+ bar_plot_update = gr.update(
61
+ value=df_filtered,
62
+ x="timestamp" if show_timestamp else "energy_kW",
63
+ y="energy_kW" if show_power else None,
64
+ title="Energy Consumption Distribution",
65
+ tooltip=columns_to_show,
66
+ visible=(plot_type == "Histogram"),
67
+ height="50vh"
68
+ )
69
+
70
+ return table_update, line_plot_update, bar_plot_update
71
+
72
+ custom_css = """
73
+ @media (min-width: 768px) {
74
+ .plot-container {
75
+ height: 500px !important;
76
+ }
77
+ }
78
+ @media (max-width: 767px) {
79
+ .plot-container {
80
+ height: 50vh !important;
81
+ }
82
+ }
83
+ """
84
+
85
+ with gr.Blocks(css=custom_css) as app:
86
+ gr.Markdown("<h1 style='text-align: center;'>⚑ SmartMeterSim Dashboard ⚑</h1>")
87
+ gr.Markdown("<h3 style='text-align: center;'>πŸ“ˆ Optimize your energy footprint instantly with real-time usage data.</h3>")
88
+
89
+ with gr.Row():
90
+ with gr.Column(scale=2): # Sidebar (20% width)
91
+ gr.Markdown("## πŸ’‘ Measurements")
92
+ measure_power = gr.Checkbox(label="Power", value=True)
93
+ measure_timestamp = gr.Checkbox(label="Timestamp", value=True)
94
+
95
+ gr.Markdown("## πŸ“Š Graphs")
96
+ plot_type = gr.Dropdown(["Table", "Line Plot", "Histogram"], value="Table", label="Select Visualization")
97
+
98
+ refresh_btn = gr.Button("πŸ”„ Refresh Data")
99
+
100
+ with gr.Column(scale=8): # Main content (80% width)
101
+ df_display = gr.Dataframe(value=load_data(), label="Energy Data Table", interactive=False)
102
+ app.load(lambda: update_data(df_display))
103
+ line_plot = gr.LinePlot(visible=False, height="50vh", elem_classes="plot-container")
104
+ bar_plot = gr.BarPlot(visible=False, height="50vh", elem_classes="plot-container")
105
+
106
+ refresh_btn.click(
107
+ fn=generate_dashboard,
108
+ inputs=[plot_type, measure_power, measure_timestamp],
109
+ outputs=[df_display, line_plot, bar_plot]
110
+ )
111
+
112
+ plot_type.change(
113
+ fn=generate_dashboard,
114
+ inputs=[plot_type, measure_power, measure_timestamp],
115
+ outputs=[df_display, line_plot, bar_plot]
116
+ )
117
+
118
+ app.queue()
119
+ app.launch()