rock1110 commited on
Commit
6c38fca
·
verified ·
1 Parent(s): 7e43bf8

Upload cytek_log_parser.py

Browse files
Files changed (1) hide show
  1. cytek_log_parser.py +247 -0
cytek_log_parser.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import re
4
+ from io import StringIO, BytesIO
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ from datetime import datetime
8
+
9
+ st.set_page_config(
10
+ page_title="Cytek Log Parser v.1.0.0",
11
+ layout="wide"
12
+ )
13
+
14
+ # ---- Helper Functions ----
15
+
16
+ def strip_timestamp(s):
17
+ s = re.sub(r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', '', s)
18
+ s = re.sub(r'\b\d{4}-\d{1,2}-\d{1,2}\b', '', s)
19
+ s = re.sub(r'\b\d{4}/\d{1,2}/\d{1,2}\b', '', s)
20
+ s = re.sub(r'\b\d{1,2}:\d{2}(?::\d{2})?\s*(am|pm)?\b', '', s, flags=re.IGNORECASE)
21
+ s = re.sub(r'\b\d{1,2}\s*(am|pm)\b', '', s, flags=re.IGNORECASE)
22
+ s = re.sub(r'\b(am|pm)\b', '', s, flags=re.IGNORECASE)
23
+ s = re.sub(r'[-:\.,/]{2,}', ' ', s)
24
+ s = re.sub(r'[\s:\-\[\],\.]+', ' ', s)
25
+ return s.strip()
26
+
27
+ def parse_log_file(file):
28
+ errors = []
29
+ lines = []
30
+ file.seek(0)
31
+ for i, line in enumerate(file):
32
+ if isinstance(line, bytes):
33
+ line = line.decode('utf-8', errors='ignore')
34
+ lines.append(line.rstrip('\n'))
35
+ if "error" in line.lower():
36
+ errors.append((i, line.rstrip('\n')))
37
+ return lines, errors
38
+
39
+ def aggregate_errors(logs_errors):
40
+ summary = {}
41
+ total = 0
42
+ for errors in logs_errors.values():
43
+ for _, err in errors:
44
+ err_stripped = err.strip()
45
+ no_time = strip_timestamp(err_stripped)
46
+ no_time_lower = no_time.lower()
47
+ # Remove extra symbols and 'Error' prefix for grouping
48
+ new_no_time = re.sub(r'^error(\s*\([^\)]*\))?[\s:\-\[\]\(\)\.]*', '', no_time, flags=re.IGNORECASE)
49
+ new_no_time = re.sub(r'^[^a-zA-Z]+', '', new_no_time)
50
+ if new_no_time:
51
+ new_no_time = new_no_time[0].upper() + new_no_time[1:]
52
+ # Group certain Cytek errors
53
+ if "cytek device readafpgaregister" in no_time_lower:
54
+ key = "Cytek device readafpgaregister"
55
+ elif "cytek device readmfpgaregisterrmt" in no_time_lower:
56
+ key = "Cytek device readmfpgaregisterrmt"
57
+ elif "cytek device writemfpgaregisterrmt" in no_time_lower:
58
+ key = "Cytek device writemfpgaregisterrmt"
59
+ else:
60
+ key = new_no_time
61
+ summary[key] = summary.get(key, 0) + 1
62
+ total += 1
63
+ # Sort errors descending
64
+ display_summary = dict(sorted(summary.items(), key=lambda x: x[1], reverse=True))
65
+ percentages = {k: f"{int(v)} ({(100*v/total):.1f}%)" for k, v in display_summary.items()} if total else {}
66
+ return display_summary, percentages
67
+
68
+ def pareto_chart(df):
69
+ fig, ax = plt.subplots(figsize=(10, max(4, len(df)*0.45)))
70
+ bar_vals = [int(p.split()[0]) for p in df["Count (Percent)"]]
71
+ bar_containers = ax.barh(
72
+ df["Error"], bar_vals, color="#3399FF", edgecolor="#2176ae", height=0.5, zorder=2
73
+ )
74
+ ax.invert_yaxis()
75
+ ax.set_title("Errors (Pareto)", fontsize=13, fontweight='bold')
76
+ ax.set_xlabel("Count", fontsize=11)
77
+ ax.set_ylabel("Error", fontsize=11)
78
+ ax.grid(True, axis='x', color="#d9e8f6", linestyle="--", linewidth=0.8, zorder=1)
79
+ max_bar = max(bar_vals) if bar_vals else 1
80
+ ax.set_xlim(0, max_bar * 1.15)
81
+ for i, txt in enumerate(df["Count (Percent)"]):
82
+ bar_end = bar_vals[i]
83
+ chart_max = max_bar * 1.15
84
+ label_x = bar_end + max_bar * 0.02
85
+ text_width = len(txt) * 0.015 * chart_max
86
+ if label_x + text_width > chart_max:
87
+ label_x = chart_max - text_width - max_bar * 0.02
88
+ ax.text(label_x, i, txt, va='center', fontsize=10, color="#2176ae", fontweight='bold')
89
+ plt.subplots_adjust(left=0.32, right=0.98)
90
+ fig.tight_layout()
91
+ return fig
92
+
93
+ # ---- Streamlit App ----
94
+
95
+ st.title("Cytek Flow Cytometer Log Parser v.1.0.0")
96
+ st.markdown("**Upload your log files (can select multiple):**")
97
+
98
+ uploaded_files = st.file_uploader(
99
+ "Upload .txt log files",
100
+ type=["txt"], accept_multiple_files=True, key="file_uploader"
101
+ )
102
+
103
+ # -- File select list (checkboxes) --
104
+ if uploaded_files:
105
+ # Use a stable name key for each file
106
+ files_metadata = [
107
+ {
108
+ "name": file.name,
109
+ "mtime": file.file_id if hasattr(file, "file_id") else 0, # Streamlit doesn't provide mtime, but name is enough
110
+ "idx": idx
111
+ }
112
+ for idx, file in enumerate(uploaded_files)
113
+ ]
114
+ # Find latest ApplicationLog
115
+ app_logs = [f for f in files_metadata if "applicationlog" in f["name"].lower()]
116
+ if app_logs:
117
+ default_idx = max(app_logs, key=lambda f: f["name"])[
118
+ "idx"
119
+ ] # Use "latest" by name sort (approximation for upload)
120
+ else:
121
+ default_idx = 0
122
+
123
+ # --- Sidebar for file selection ---
124
+ st.sidebar.subheader("Select log files for analysis (Pareto):")
125
+ file_checks = []
126
+ for idx, meta in enumerate(files_metadata):
127
+ checked = True
128
+ file_checks.append(
129
+ st.sidebar.checkbox(meta["name"], value=checked, key=f"chk_{idx}")
130
+ )
131
+ # Bulk select/deselect/app/setupengine toggles
132
+ cols = st.sidebar.columns(2)
133
+ if cols[0].button("Select All"):
134
+ for idx in range(len(file_checks)):
135
+ st.session_state[f"chk_{idx}"] = True
136
+ if cols[1].button("Deselect All"):
137
+ for idx in range(len(file_checks)):
138
+ st.session_state[f"chk_{idx}"] = False
139
+ cols2 = st.sidebar.columns(2)
140
+ if cols2[0].button("Select ApplicationLog"):
141
+ for idx, meta in enumerate(files_metadata):
142
+ st.session_state[f"chk_{idx}"] = "applicationlog" in meta["name"].lower()
143
+ if cols2[1].button("Select SetupEngineLog"):
144
+ for idx, meta in enumerate(files_metadata):
145
+ st.session_state[f"chk_{idx}"] = "setupenginelog" in meta["name"].lower()
146
+
147
+ # -- Main file selector: always highlight latest ApplicationLog by default
148
+ st.subheader("View a Log File")
149
+ selected_file = st.selectbox(
150
+ "Choose a log file to view its content:",
151
+ [meta["name"] for meta in files_metadata],
152
+ index=default_idx
153
+ )
154
+
155
+ # Parse all files once and store in dict
156
+ parsed_files = {}
157
+ all_errors = {}
158
+ for idx, file in enumerate(uploaded_files):
159
+ lines, errors = parse_log_file(file)
160
+ parsed_files[file.name] = lines
161
+ all_errors[file.name] = errors
162
+
163
+ # -- Log content search --
164
+ log_search = st.text_input("Search log content:")
165
+ error_search = st.text_input("Search errors:")
166
+
167
+ # --- Log content and error display (side by side) ---
168
+ left, right = st.columns(2)
169
+ # --- Log content ---
170
+ with left:
171
+ st.markdown("#### Log Content")
172
+ lines = parsed_files[selected_file]
173
+ if log_search:
174
+ filtered = [
175
+ (i, line)
176
+ for i, line in enumerate(lines)
177
+ if log_search.lower() in line.lower()
178
+ ]
179
+ else:
180
+ filtered = list(enumerate(lines))
181
+ highlighted = set(i for i, line in all_errors[selected_file])
182
+ # Show as code for monospace
183
+ log_disp = [
184
+ f"{i+1:>5}: " +
185
+ (f"**:red[{line}]**" if i in highlighted else line)
186
+ for i, line in filtered
187
+ ]
188
+ st.code("\n".join(log_disp), language="")
189
+
190
+ # --- Error List ---
191
+ with right:
192
+ st.markdown("#### Error Entries")
193
+ errors = all_errors[selected_file]
194
+ if error_search:
195
+ err_filtered = [
196
+ (i, err)
197
+ for i, err in errors
198
+ if error_search.lower() in err.lower()
199
+ ]
200
+ else:
201
+ err_filtered = errors
202
+ error_disp = [
203
+ f"Line {i+1}: {err}" for i, err in err_filtered
204
+ ]
205
+ st.code("\n".join(error_disp), language="")
206
+
207
+ # --- Pareto chart and summary (selected files only) ---
208
+ st.divider()
209
+ st.subheader("Errors (Pareto)")
210
+ selected_names = [
211
+ meta["name"] for idx, meta in enumerate(files_metadata)
212
+ if st.session_state.get(f"chk_{idx}", True)
213
+ ]
214
+ sel_errors = {name: all_errors[name] for name in selected_names}
215
+ display_summary, percentages = aggregate_errors(sel_errors)
216
+ df = pd.DataFrame([(k, percentages[k]) for k in display_summary.keys()],
217
+ columns=["Error", "Count (Percent)"])
218
+ if not df.empty:
219
+ fig = pareto_chart(df)
220
+ buf = BytesIO()
221
+ fig.savefig(buf, format="png", bbox_inches="tight", dpi=150)
222
+ st.pyplot(fig, use_container_width=True)
223
+ col1, col2 = st.columns(2)
224
+ with col1:
225
+ # PNG Export
226
+ st.download_button(
227
+ label="Export Pareto PNG",
228
+ data=buf.getvalue(),
229
+ file_name=f"Pareto {datetime.now().strftime('%m-%d %H-%M')}.png",
230
+ mime="image/png"
231
+ )
232
+ with col2:
233
+ # CSV Export
234
+ csv_buf = StringIO()
235
+ df.to_csv(csv_buf, index=False)
236
+ st.download_button(
237
+ label="Export Pareto CSV",
238
+ data=csv_buf.getvalue(),
239
+ file_name=f"Pareto {datetime.now().strftime('%m-%d %H-%M')}.csv",
240
+ mime="text/csv"
241
+ )
242
+ else:
243
+ st.info("No error data in the selected files.")
244
+
245
+ else:
246
+ st.info("Upload at least one .txt log file to get started.")
247
+