-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfw
More file actions
executable file
·190 lines (169 loc) · 6.43 KB
/
fw
File metadata and controls
executable file
·190 lines (169 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python
import argparse
import pandas as pd
import json
from pathlib import Path
from threading import Thread
from time import sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from textual.app import App, ComposeResult
from textual.containers import Horizontal, Container
from textual.widgets import DataTable, ContentSwitcher, Button, ListView, ListItem, Input
class ConfigFileHandler(FileSystemEventHandler):
def __init__(self, app, config_file, file, num_rows):
self.app = app
self.config_file = Path(config_file).resolve()
self.file = file
self.num_rows = num_rows
def on_modified(self, event):
if Path(event.src_path).resolve() == self.config_file:
print("\nConfig file changed. Reloading...\n")
self.app.refresh_table(self.config_file, self.file, self.num_rows)
class DataFrameApp(App):
CSS_PATH = "dom.tcss"
def __init__(self, config_file, file, num_rows, **kwargs):
super().__init__(**kwargs)
self.config_file = config_file
self.file = file
self.num_rows = num_rows
self.df = self.load_dataframe()
def compose(self) -> ComposeResult:
yield Container(
Horizontal(
Button("Data", id="data-table", classes="sheet-selector"),
Button("Config", id="config-editor", classes="sheet-selector"),
classes="buttons",
),
id="dialog",
)
with ContentSwitcher(initial="data-table", id="content-switcher"):
yield DataTable(id="data-table")
yield ListView(id="config-editor")
def on_mount(self) -> None:
self.update_table()
self.display_config()
def save_config_row(self):
new_rows = []
list_view = self.query_one(ListView)
for idx, li in enumerate(list_view.children):
label_input = li.query_one(f"#label_{idx}", Input)
start_input = li.query_one(f"#start_{idx}", Input)
width_input = li.query_one(f"#width_{idx}", Input)
new_rows.append({
"label": label_input.value,
"start": int(start_input.value),
"width": int(width_input.value),
})
with open(self.config_file, "w") as c_file:
json.dump(new_rows, c_file, indent=2)
async def on_button_pressed(self, event):
button_id = event.button.id
if button_id.startswith("save_"):
self.save_config_row()
else:
switcher = self.query_one(ContentSwitcher)
if button_id == "data-table":
switcher.current = "data-table"
elif button_id == "config-editor":
switcher.current = "config-editor"
def load_dataframe(self):
try:
with open(self.config_file, "r") as c_file:
config = json.load(c_file)
pd.set_option("display.show_dimensions", False)
labels = []
col_spec = []
for key in config:
label = key["label"]
labels.append(label)
start = int(key["start"]) - 1
width = int(key["width"])
col_spec.append((start, start + width))
df = pd.read_fwf(
self.file,
colspecs=col_spec,
nrows=self.num_rows,
names=None,
dtype=str,
)
df.fillna("", inplace=True)
df.columns = labels
return df
except Exception as e:
print(f"Error loading DataFrame: {e}")
return pd.DataFrame()
def update_table(self):
table = self.query_one(DataTable)
for column in self.df.columns:
table.add_column(column)
for _, row in self.df.iterrows():
table.add_row(*map(str, row))
def refresh_table(self, config_file, file, num_rows):
table = self.query_one(DataTable)
table.clear(columns=True)
self.config_file = config_file
self.file = file
self.num_rows = num_rows
self.df = self.load_dataframe()
self.update_table()
def display_config(self):
data_config = self.query_one(ListView)
data_config.clear()
try:
with open(self.config_file, "r") as c_file:
config = json.load(c_file)
except Exception as e:
config = []
for i, entry in enumerate(config):
list_item = ListItem(
Input(entry.get("label", ""), placeholder="Label", id=f"label_{i}", classes="row-item"),
Input(str(entry.get("start", "")), placeholder="Start", type="integer", id=f"start_{i}", classes="row-item"),
Input(str(entry.get("width", "")), placeholder="Width", type="integer", id=f"width_{i}", classes="row-item"),
Button("Save", id=f"save_{i}", classes="row-item"),
id=f"config_row_{i}",
)
list_item.styles.layout = "grid"
list_item.styles.width = "1fr"
list_item.styles.grid_size_columns = 4
list_item.styles.overflow_x = "auto"
data_config.append(list_item)
return data_config
def watch_config_file(app, config_file, file, num_rows):
event_handler = ConfigFileHandler(app, config_file, file, num_rows)
observer = Observer()
observer.schedule(
event_handler, path=str(Path(config_file).parent), recursive=False
)
observer.start()
try:
while True:
sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
def main():
parser = argparse.ArgumentParser(
description="Read file and config file paths as arguments."
)
parser.add_argument(
"-f", "--file", type=str, required=True, help="Path to the file."
)
parser.add_argument(
"-c", "--config", type=str, required=True, help="Path to the config file."
)
parser.add_argument(
"-n", "--num-lines", type=int, required=False, help="Number of lines to display"
)
args = parser.parse_args()
file = args.file
config = args.config
num_lines = args.num_lines or 5
app = DataFrameApp(config, file, num_lines)
watcher_thread = Thread(
target=watch_config_file, args=(app, config, file, num_lines), daemon=True
)
watcher_thread.start()
app.run()
if __name__ == "__main__":
main()