@@ -122,33 +122,49 @@ from datetime import datetime, timedelta
122
122
import os
123
123
124
124
def load_existing_data(file_path):
125
- with open(file_path, 'r') as f:
126
- data = json.load(f)
127
-
128
- # Trim old data while loading
129
- current_time = datetime.now()
130
- cutoff = current_time - timedelta(hours=24, minutes=10)
131
- current_year = current_time.year
125
+ # Initialize default empty data structure
126
+ default_data = {
127
+ "timestamps": [],
128
+ "temperatures": [],
129
+ "utilizations": [],
130
+ "memory": [],
131
+ "power": []
132
+ }
132
133
133
- # Find index where to start keeping data
134
- valid_indices = []
135
- for i, timestamp in enumerate(data['timestamps']):
136
- dt = datetime.strptime(f"{current_year} {timestamp}", "%Y %m-%d %H:%M:%S")
137
- if dt >= cutoff:
138
- valid_indices.append(i)
134
+ # If file doesn't exist or is empty, return default data
135
+ if not os.path.exists(file_path) or os.path.getsize(file_path) == 0:
136
+ return default_data
137
+
138
+ try:
139
+ with open(file_path, 'r') as f:
140
+ data = json.load(f)
139
141
140
- # Keep only data within our window
141
- return {
142
- 'timestamps': [data['timestamps'][i] for i in valid_indices],
143
- 'temperatures': [data['temperatures'][i] for i in valid_indices],
144
- 'utilizations': [data['utilizations'][i] for i in valid_indices],
145
- 'memory': [data['memory'][i] for i in valid_indices],
146
- 'power': [data['power'][i] for i in valid_indices]
147
- }
148
-
149
- existing_data = load_existing_data(sys.argv[1])
150
- if existing_data:
151
- data = existing_data
142
+ # Trim old data while loading
143
+ current_time = datetime.now()
144
+ cutoff = current_time - timedelta(hours=24, minutes=10)
145
+ current_year = current_time.year
146
+
147
+ # Find index where to start keeping data
148
+ valid_indices = []
149
+ for i, timestamp in enumerate(data['timestamps']):
150
+ dt = datetime.strptime(f"{current_year} {timestamp}", "%Y %m-%d %H:%M:%S")
151
+ if dt >= cutoff:
152
+ valid_indices.append(i)
153
+
154
+ # Keep only data within our window
155
+ return {
156
+ 'timestamps': [data['timestamps'][i] for i in valid_indices],
157
+ 'temperatures': [data['temperatures'][i] for i in valid_indices],
158
+ 'utilizations': [data['utilizations'][i] for i in valid_indices],
159
+ 'memory': [data['memory'][i] for i in valid_indices],
160
+ 'power': [data['power'][i] for i in valid_indices]
161
+ }
162
+ except (json.JSONDecodeError, KeyError, FileNotFoundError) as e:
163
+ # If any error occurs during loading/parsing, return default data
164
+ return default_data
165
+
166
+ # Initialize data structure
167
+ data = load_existing_data(sys.argv[1])
152
168
153
169
# write test, after loading but before processing
154
170
try:
0 commit comments