-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtui.py
More file actions
444 lines (374 loc) · 14.1 KB
/
Copy pathtui.py
File metadata and controls
444 lines (374 loc) · 14.1 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/env python3
"""Drillbit TUI: AI-powered Fedora package discovery."""
from __future__ import annotations
import datetime
import httpx
from rich.text import Text
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Center, Horizontal, Vertical
from textual.reactive import reactive
from textual.widgets import (
DataTable,
Footer,
Input,
Label,
LoadingIndicator,
SelectionList,
Static,
)
from textual.widgets.selection_list import Selection
BACKEND_URL = "http://localhost:8000"
# (package dict key, display label, visible by default)
AVAILABLE_COLUMNS: list[tuple[str, str, bool]] = [
("name", "Package", True),
("copr_description", "Description", True),
("reason", "Reason", True),
("version", "Version", False),
("submitted_on", "Submitted", False),
("ended_on", "Last Built", False),
("copr_project", "COPR Project", False),
]
DRILLBIT_ASCII = """\
██████╗ ██████╗ ██╗██╗ ██╗ ██████╗ ██╗████████╗
██╔══██╗██╔══██╗██║██║ ██║ ██╔══██╗██║╚══██╔══╝
██║ ██║██████╔╝██║██║ ██║ ██████╔╝██║ ██║
██║ ██║██╔══██╗██║██║ ██║ ██╔══██╗██║ ██║
██████╔╝██║ ██╗██║███████╗ ███████╗ ██████╔╝██║ ██║
╚═════╝ ╚═╝ ╚═╝╚═╝╚══════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝"""
DRILLBIT_CSS = """
Screen {
background: transparent;
}
#header {
height: auto;
align: center middle;
padding: 1 0 0 0;
background: transparent;
}
#ascii-art {
text-align: center;
background: transparent;
padding: 0 2;
}
/* ── Search view ────────────────────────────────────── */
#search-view {
height: 1fr;
align: center middle;
background: transparent;
}
#search-view.hidden {
display: none;
}
#search-label {
text-align: center;
height: auto;
padding: 0 0 1 0;
background: transparent;
}
#search-input {
width: 70%;
padding: 0 2;
background: transparent;
border: solid $panel;
}
#search-input:focus {
border: solid white 60%;
}
#status-bar {
height: auto;
text-align: center;
padding: 1 4;
background: transparent;
}
#status-bar.error {
color: red;
}
#status-bar.success {
color: green;
}
#loading {
height: 3;
display: none;
background: transparent;
}
#loading.visible {
display: block;
}
/* ── Results view ───────────────────────────────────── */
#results-view {
display: none;
height: 1fr;
background: transparent;
}
#results-view.visible {
display: block;
}
#results-container {
height: 1fr;
padding: 0 2 1 2;
background: transparent;
}
#results-header {
height: auto;
padding: 0 0 1 0;
background: transparent;
color: green;
}
#results-table {
height: 1fr;
background: transparent;
}
#column-picker {
width: 26;
display: none;
background: transparent;
border-left: solid $panel;
padding: 1 1;
}
#column-picker.visible {
display: block;
}
#column-picker-title {
height: auto;
padding: 0 0 1 0;
text-align: center;
background: transparent;
}
SelectionList {
background: transparent;
border: none;
height: auto;
}
Footer {
background: transparent;
}
"""
class DrillbitApp(App):
"""Drillbit: AI-powered Fedora package discovery TUI."""
CSS = DRILLBIT_CSS
THEME = "textual-ansi"
BINDINGS = [
Binding("ctrl+q", "quit", "Quit", show=True),
Binding("ctrl+l", "clear_results", "Clear", show=True),
Binding("c", "toggle_columns", "Columns", show=True),
Binding("escape", "escape_pressed", "Back", show=False),
Binding("f1", "focus_search", "Search", show=True),
]
is_loading: reactive[bool] = reactive(False)
status_message: reactive[str] = reactive("")
status_type: reactive[str] = reactive("info")
columns_open: reactive[bool] = reactive(False)
showing_results: reactive[bool] = reactive(False)
def __init__(self) -> None:
super().__init__()
self.last_results: list[dict] = []
def compose(self) -> ComposeResult:
with Vertical(id="header"):
yield Static(DRILLBIT_ASCII, id="ascii-art")
with Vertical(id="search-view"):
with Center():
yield Label(
"What do you need? Describe it in plain English:", id="search-label"
)
with Center():
yield Input(
placeholder='e.g. "a tool for editing video files" or "screen recorder"',
id="search-input",
)
yield Static("", id="status-bar")
yield LoadingIndicator(id="loading")
with Horizontal(id="results-view"):
with Vertical(id="results-container"):
yield Static("", id="results-header")
yield DataTable(
id="results-table", zebra_stripes=False, cursor_type="row"
)
with Vertical(id="column-picker"):
yield Static("Columns", id="column-picker-title")
yield SelectionList(
*[
Selection(label, key, initial)
for key, label, initial in AVAILABLE_COLUMNS
],
id="column-list",
)
yield Footer()
def on_mount(self) -> None:
self.rebuild_columns()
self.query_one("#search-input", Input).focus()
# ── view switching ─────────────────────────────────────────────────────
def show_search_view(self) -> None:
self.showing_results = False
self.query_one("#search-view").remove_class("hidden")
self.query_one("#results-view").remove_class("visible")
self.query_one("#search-input", Input).focus()
def show_results_view(self) -> None:
self.showing_results = True
self.query_one("#search-view").add_class("hidden")
self.query_one("#results-view").add_class("visible")
self.query_one("#results-table", DataTable).focus()
# ── column picker ──────────────────────────────────────────────────────
def visible_columns(self) -> list[tuple[str, str]]:
"""Return (key, label) for every currently selected column."""
selected: set[str] = set(self.query_one("#column-list", SelectionList).selected)
return [(key, label) for key, label, _ in AVAILABLE_COLUMNS if key in selected]
def rebuild_columns(self) -> None:
table = self.query_one("#results-table", DataTable)
table.clear(columns=True)
for _, label in self.visible_columns():
table.add_column(label, key=label)
if self.last_results:
self.fill_rows()
def fill_rows(self) -> None:
table = self.query_one("#results-table", DataTable)
table.clear()
visible = self.visible_columns()
for i, pkg in enumerate(self.last_results, 1):
row: list = []
for key, _ in visible:
row.append(self.render_cell(key, pkg, i))
table.add_row(*row)
def render_cell(self, key: str, pkg: dict, rank: int) -> str | Text:
value = pkg.get(key, "—") or "—"
if key == "name":
return Text(str(value), style="bold" if rank == 1 else "")
if key == "score":
try:
s = float(value)
pct = f"{s * 100:.0f}%"
if s >= 0.7:
return Text(pct, style="bold green")
if s >= 0.4:
return Text(pct, style="bold yellow")
return Text(pct, style="bold red")
except (TypeError, ValueError):
return str(value)
if key == "copr_description":
return str(value)[:80] + "…" if len(str(value)) > 80 else str(value)
if key == "reason":
return str(value)[:80] + "…" if len(str(value)) > 80 else str(value)
if key in ("submitted_on", "ended_on"):
try:
return datetime.datetime.fromtimestamp(int(value)).strftime("%Y-%m-%d")
except (TypeError, ValueError):
return "—"
return str(value)
@on(SelectionList.SelectedChanged, "#column-list")
def on_column_selection_changed(self) -> None:
self.rebuild_columns()
def watch_columns_open(self, value: bool) -> None:
picker = self.query_one("#column-picker")
if value:
picker.add_class("visible")
else:
picker.remove_class("visible")
def action_toggle_columns(self) -> None:
if not self.showing_results:
return
self.columns_open = not self.columns_open
if self.columns_open:
self.query_one("#column-list", SelectionList).focus()
else:
self.query_one("#results-table", DataTable).focus()
# ── loading / status ───────────────────────────────────────────────────
def watch_is_loading(self, value: bool) -> None:
loading = self.query_one("#loading", LoadingIndicator)
if value:
loading.add_class("visible")
else:
loading.remove_class("visible")
def watch_status_message(self, value: str) -> None:
self.query_one("#status-bar", Static).update(value)
def watch_status_type(self, value: str) -> None:
bar = self.query_one("#status-bar", Static)
bar.remove_class("error", "success")
if value in ("error", "success"):
bar.add_class(value)
# ── search ─────────────────────────────────────────────────────────────
@on(Input.Submitted, "#search-input")
def on_search_submitted(self, event: Input.Submitted) -> None:
query = event.value.strip()
if query:
self.run_search(query)
@work(exclusive=True, thread=True)
def run_search(self, query: str) -> None:
self.call_from_thread(self.set_loading, True)
self.call_from_thread(
self.set_status, f'Drilling into packages for: "{query}"...', "info"
)
try:
with httpx.Client(timeout=60.0) as client:
resp = client.get(
f"{BACKEND_URL}/search", params={"q": query, "limit": 7}
)
resp.raise_for_status()
packages = resp.json()
except httpx.ConnectError:
self.call_from_thread(
self.set_status,
"Cannot reach backend at localhost:8000 — is the stack running? (podman-compose up -d)",
"error",
)
self.call_from_thread(self.set_loading, False)
return
except httpx.HTTPStatusError as e:
self.call_from_thread(
self.set_status,
f"Backend error: {e.response.status_code}",
"error",
)
self.call_from_thread(self.set_loading, False)
return
except Exception as e:
self.call_from_thread(self.set_status, f"Error: {e}", "error")
self.call_from_thread(self.set_loading, False)
return
self.call_from_thread(self.update_results, packages, query)
self.call_from_thread(self.set_loading, False)
def set_loading(self, value: bool) -> None:
self.is_loading = value
def set_status(self, msg: str, kind: str = "info") -> None:
self.status_message = msg
self.status_type = kind
def update_results(self, packages: list[dict], query: str) -> None:
if not packages:
self.set_status(
f'No packages found for "{query}". Try a different description.',
"error",
)
return
self.last_results = packages
self.rebuild_columns()
count = len(packages)
header = self.query_one("#results-header", Static)
header.update(
f'Found {count} package{"s" if count != 1 else ""} for "{query}"'
" — c: columns | ctrl+l: new search"
)
self.show_results_view()
# ── misc actions ───────────────────────────────────────────────────────
def action_clear_results(self) -> None:
self.last_results = []
self.query_one("#results-table", DataTable).clear()
self.query_one("#results-header", Static).update("")
self.query_one("#search-input", Input).clear()
self.set_status("", "info")
self.columns_open = False
self.show_search_view()
def action_escape_pressed(self) -> None:
if self.columns_open:
self.columns_open = False
self.query_one("#results-table", DataTable).focus()
elif self.showing_results:
self.action_clear_results()
else:
self.query_one("#search-input", Input).blur()
def action_focus_search(self) -> None:
if self.showing_results:
self.action_clear_results()
else:
self.query_one("#search-input", Input).focus()
if __name__ == "__main__":
DrillbitApp().run()