-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.py
More file actions
678 lines (554 loc) · 20.2 KB
/
bootstrap.py
File metadata and controls
678 lines (554 loc) · 20.2 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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
# AXIO_BOOTSTRAP
"""
Axio Bootstrap Utilities
------------------------
Paste this cell into a fresh ChatGPT Python environment after uploading
your latest `search-index.json`. Then run it once.
Assumptions:
- The uploaded file is available as: /mnt/data/search-index.json
(If the path or name differ, change AXIO_INDEX_PATH below.)
Provides:
- Navigation & browsing over the Axio corpus
- Simple TUI-like viewer
- Search and analysis helpers
- Sequence and Index generators
- A consolidated help() menu
"""
import json
import math
import re
from pathlib import Path
from typing import List, Dict, Optional
# ---------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------
AXIO_INDEX_PATH = Path("/mnt/data/search-index.json")
# Global cache of the corpus and pagination state
_AXIO_DATA: Optional[List[Dict]] = None
_PAGINATION = {
"page": 1, # 1-based current page
"page_size": 20, # posts per page
}
# ---------------------------------------------------------------------
# Internal loading
# ---------------------------------------------------------------------
def _load_axio_data() -> List[Dict]:
"""
Internal: load and cache the Axio JSON corpus from AXIO_INDEX_PATH.
The JSON must be a list of dicts with at least:
- id
- title
- subtitle (optional)
- date
- content
"""
global _AXIO_DATA
if _AXIO_DATA is None:
if not AXIO_INDEX_PATH.exists():
raise FileNotFoundError(
f"Axio index not found at {AXIO_INDEX_PATH}. "
f"Upload `search-index.json` and/or adjust AXIO_INDEX_PATH."
)
with AXIO_INDEX_PATH.open("r", encoding="utf-8") as f:
_AXIO_DATA = json.load(f)
return _AXIO_DATA
# Initialize corpus and total count
_AXIO_DATA = _load_axio_data()
TOTAL_POSTS = len(_AXIO_DATA)
# ---------------------------------------------------------------------
# NEW STEP 2 — Minimal content loader for full-article reconstruction
# ---------------------------------------------------------------------
# Build a simple ID → post map for direct content access.
# This powers show_full(post_id) in the chat layer without truncation.
AXIO = { d["id"]: d for d in _AXIO_DATA }
def content_of(post_id: str) -> str:
"""
Return the full article content for the given post ID.
Used only by the chat layer to reconstruct complete articles
beyond python stdout limits.
"""
if post_id not in AXIO:
raise KeyError(f"No post with ID {post_id}")
return AXIO[post_id].get("content", "")
# ---------------------------------------------------------------------
# Core browsing: list_posts
# ---------------------------------------------------------------------
def list_posts(
limit: Optional[int] = None,
contains: Optional[str] = None,
page: Optional[int] = None,
page_size: Optional[int] = None,
) -> List[Dict]:
"""
List basic metadata for posts (date, id, title).
Modes:
- If `page` is provided: show that page (pagination mode).
- Else if `limit` is provided: show newest `limit` posts (ignores pagination).
- Else (no page, no limit): show the *current* pagination page.
Args:
limit (int or None):
Max number of posts to show in non-paginated mode (newest-first).
Ignored if `page` is set. If both `page` and `limit` are None,
the current pagination page is shown.
contains (str or None):
Case-insensitive substring filter applied to title OR subtitle.
page (int or None):
1-based page index for pagination mode.
page_size (int or None):
Number of posts per page. If None, uses current pagination page_size.
Returns:
List[Dict] with keys: date, id, title.
"""
data = _load_axio_data()
# Sort newest first by ISO timestamp
sorted_data = sorted(data, key=lambda d: d.get("date", ""))[::-1]
# Optional text filter on title/subtitle
if contains:
needle = contains.lower()
sorted_data = [
d for d in sorted_data
if needle in (d.get("title") or "").lower()
or needle in (d.get("subtitle") or "").lower()
]
# Decide mode: explicit page, explicit limit, or current page
if page is not None:
# Explicit pagination request
if page < 1:
page = 1
ps = page_size if page_size is not None else _PAGINATION["page_size"]
start = (page - 1) * ps
end = start + ps
sliced = sorted_data[start:end]
_PAGINATION["page"] = page
_PAGINATION["page_size"] = ps
elif limit is not None:
# Non-paginated: top-N newest posts, ignore pagination state
sliced = sorted_data[:limit]
else:
# Default: show the CURRENT pagination page
ps = page_size if page_size is not None else _PAGINATION["page_size"]
p = _PAGINATION["page"]
total = len(sorted_data)
max_page = math.ceil(total / ps) if ps > 0 else 0
if p < 1:
p = 1
if max_page > 0 and p > max_page:
p = max_page
_PAGINATION["page"] = p # keep state consistent
start = (p - 1) * ps
end = start + ps
sliced = sorted_data[start:end]
out = []
for d in sliced:
record = {
"date": d.get("date"),
"id": d.get("id"),
"title": d.get("title"),
}
out.append(record)
print(f"{record['date']} | {record['id']} | {record['title']}")
return out
# ---------------------------------------------------------------------
# Pagination helpers: next, prev, home, end, status, goto
# ---------------------------------------------------------------------
def next() -> List[Dict]: # noqa: A001 - intentionally named next()
"""
Move forward one page using the current pagination state.
Returns:
List[Dict] of the newly displayed posts (same format as list_posts).
"""
data = _load_axio_data()
total = len(data)
ps = _PAGINATION["page_size"]
p = _PAGINATION["page"]
max_page = math.ceil(total / ps) if ps > 0 else 0
if p >= max_page:
print("Already at last page.")
return []
return list_posts(page=p + 1, page_size=ps)
def prev() -> List[Dict]:
"""
Move back one page using the current pagination state.
Returns:
List[Dict] of the newly displayed posts (same format as list_posts).
"""
ps = _PAGINATION["page_size"]
p = _PAGINATION["page"]
if p <= 1:
print("Already at first page.")
return []
return list_posts(page=p - 1, page_size=ps)
def home() -> List[Dict]:
"""
Jump to the first page (newest posts) using current page_size.
Returns:
List[Dict] of the displayed posts.
"""
ps = _PAGINATION["page_size"]
return list_posts(page=1, page_size=ps)
def end() -> List[Dict]:
"""
Jump to the last page (oldest posts) using current page_size.
Returns:
List[Dict] of the displayed posts.
"""
ps = _PAGINATION["page_size"]
total = len(_load_axio_data())
max_page = math.ceil(total / ps) if ps > 0 else 0
return list_posts(page=max_page, page_size=ps)
def status() -> Dict:
"""
Show current pagination status.
Returns:
Dict with:
- page
- page_size
- total_posts
- total_pages
"""
total = len(_load_axio_data())
ps = _PAGINATION["page_size"]
p = _PAGINATION["page"]
total_pages = math.ceil(total / ps) if ps > 0 else 0
info = {
"page": p,
"page_size": ps,
"total_posts": total,
"total_pages": total_pages,
}
print(f"Current page: {p}")
print(f"Page size: {ps}")
print(f"Total posts: {total}")
print(f"Total pages: {total_pages}")
return info
def goto(page: int) -> List[Dict]:
"""
Jump directly to a specific page number using the current page_size.
Args:
page (int): 1-based page number.
Returns:
List[Dict] of the displayed posts.
"""
total = len(_load_axio_data())
ps = _PAGINATION["page_size"]
total_pages = math.ceil(total / ps) if ps > 0 else 0
if page < 1 or page > total_pages:
print(f"Page {page} out of range (1..{total_pages}).")
return []
return list_posts(page=page, page_size=ps)
# ---------------------------------------------------------------------
# TUI-like viewer
# ---------------------------------------------------------------------
def view(page: Optional[int] = None) -> None:
"""
TUI-like viewer for the Axio corpus.
- Shows current page (or given page) with a header and navigation hints.
- Uses existing pagination state.
- Use next(), prev(), home(), end(), goto(), status() to navigate.
Args:
page (int or None): page to show; if None, uses current pagination page.
"""
data = _load_axio_data()
total = len(data)
if page is None:
page = _PAGINATION["page"]
ps = _PAGINATION["page_size"]
total_pages = math.ceil(total / ps) if ps > 0 else 0
print("=" * 80)
print(f" Axio Browser | Page {page}/{total_pages} | Page size: {ps} | Total posts: {total}")
print("=" * 80)
print("Commands: home() end() next() prev() goto(n) status()")
print("-" * 80)
list_posts(page=page, page_size=ps)
print("=" * 80)
# ---------------------------------------------------------------------
# Post access
# ---------------------------------------------------------------------
def get_post(post_id: str, show_content: bool = False) -> Optional[Dict]:
"""
Retrieve a single post by its ID.
Args:
post_id (str):
Full ID string from the JSON index, e.g.:
"162560090.the-physics-of-agency-part-5-the"
show_content (bool):
If True, prints the full content to stdout.
Returns:
Dict with keys: id, title, subtitle, date, content; or None if not found.
"""
data = _load_axio_data()
for d in data:
if d.get("id") == post_id:
if show_content:
print(f"# {d.get('title')}\n")
if d.get("subtitle"):
print(f"## {d.get('subtitle')}\n")
print(d.get("content") or "")
return d
print(f"Post not found: {post_id}")
return None
# ---------------------------------------------------------------------
# Search utilities
# ---------------------------------------------------------------------
def find_posts(pattern: str, field: str = "all", limit: int = 50) -> List[Dict]:
"""
Search posts by case-insensitive pattern (substring or regex).
Args:
pattern (str):
Substring or regex to search.
field (str):
'title', 'subtitle', 'content', or 'all' (default).
limit (int):
Maximum number of matches to return.
Returns:
List[Dict] with keys: id, title, subtitle, date, snippet.
"""
data = _load_axio_data()
regex = re.compile(pattern, re.IGNORECASE)
matches = []
def match_text(text: Optional[str]) -> bool:
return bool(text and regex.search(text))
for d in data:
title = d.get("title") or ""
subtitle = d.get("subtitle") or ""
content = d.get("content") or ""
if field == "title":
found = match_text(title)
elif field == "subtitle":
found = match_text(subtitle)
elif field == "content":
found = match_text(content)
else: # all
found = match_text(title) or match_text(subtitle) or match_text(content)
if found:
snippet = ""
if content:
m = regex.search(content)
if m:
start = max(m.start() - 40, 0)
end = min(m.end() + 40, len(content))
snippet = content[start:end].replace("\n", " ")
matches.append(
{
"id": d.get("id"),
"date": d.get("date"),
"title": title,
"subtitle": subtitle,
"snippet": snippet,
}
)
if len(matches) >= limit:
break
print(f"Found {len(matches)} result(s) matching /{pattern}/ in field='{field}':\n")
for m in matches:
date = (m["date"] or "")[:19]
print(f"- {date} {m['id']}")
print(f" {m['title']}")
if m["snippet"]:
print(f" ...{m['snippet']}...")
print()
return matches
# ---------------------------------------------------------------------
# Sequence & index helpers
# ---------------------------------------------------------------------
def _id_to_slug(post_id: str) -> str:
"""
Convert an Axio post ID like:
'162560090.the-physics-of-agency-part-5-the'
into a slug:
'the-physics-of-agency-part-5-the'
"""
if "." in post_id:
return post_id.split(".", 1)[1]
return post_id
def generate_sequence(name: str, ids: List[str], as_markdown: bool = True) -> str:
"""
Generate a markdown (or plain text) block for an Axio sequence.
Args:
name (str): sequence name (human-readable).
ids (list[str]): list of post IDs in desired order.
as_markdown (bool):
If True, output markdown with links: https://axio.fyi/p/<slug>.
Returns:
str – sequence listing.
"""
data = _load_axio_data()
by_id = {d.get("id"): d for d in data}
lines = []
if as_markdown:
lines.append(f"# {name}\n")
for pid in ids:
post = by_id.get(pid)
if not post:
continue
title = post.get("title") or pid
slug = _id_to_slug(pid)
url = f"https://axio.fyi/p/{slug}"
date = (post.get("date") or "")[:10]
if as_markdown:
lines.append(f"- **{title}** ({date}) \n {url}")
else:
lines.append(f"- {title} ({date}) :: {url}")
result = "\n".join(lines)
print(result)
return result
def update_axio_index(as_markdown: bool = True) -> str:
"""
Generate a simple Axio Index of all posts, sorted by date (ascending).
Args:
as_markdown (bool):
If True, returns markdown; else plain text.
Returns:
str – index listing.
"""
data = _load_axio_data()
sorted_data = sorted(data, key=lambda d: d.get("date", ""))
lines = []
if as_markdown:
lines.append("# Axio Index (auto-generated)\n")
for d in sorted_data:
pid = d.get("id")
title = d.get("title") or pid
date = (d.get("date") or "")[:10]
slug = _id_to_slug(pid)
url = f"https://axio.fyi/p/{slug}"
if as_markdown:
lines.append(f"- **{title}** ({date}) \n {url}")
else:
lines.append(f"- {title} ({date}) :: {url}")
result = "\n".join(lines)
# Preview first chunk for sanity
print(result[:2000] + ("\n...\n" if len(result) > 2000 else ""))
return result
# ---------------------------------------------------------------------
# Definition & concept helpers
# ---------------------------------------------------------------------
def extract_definitions() -> List[Dict]:
"""
Scan the corpus for lines starting with 'Definition:' (case-insensitive).
Returns:
List[Dict]: each with 'id', 'title', 'definition'.
"""
data = _load_axio_data()
results = []
pattern = re.compile(r"^\s*definition\s*:", re.IGNORECASE)
for d in data:
content = d.get("content") or ""
lines = content.splitlines()
for line in lines:
if pattern.match(line):
results.append(
{
"id": d.get("id"),
"title": d.get("title"),
"definition": line.strip(),
}
)
print(f"Found {len(results)} definition line(s).")
return results
def map_concepts(terms: List[str], top_k: int = 20) -> Dict[str, List[Dict]]:
"""
Build a simple concept-to-post mapping.
Args:
terms (list[str]):
Concept strings to track (case-insensitive).
top_k (int):
Maximum posts per term.
Returns:
Dict: { term: [ { 'id', 'title', 'count' }, ... ] }
"""
data = _load_axio_data()
results: Dict[str, List[Dict]] = {}
lowered_terms = [t.lower() for t in terms]
for term in lowered_terms:
counts = []
term_regex = re.compile(re.escape(term), re.IGNORECASE)
for d in data:
content = d.get("content") or ""
count = len(term_regex.findall(content))
if count > 0:
counts.append(
{"id": d.get("id"), "title": d.get("title"), "count": count}
)
counts.sort(key=lambda x: x["count"], reverse=True)
results[term] = counts[:top_k]
print(f"Concept '{term}' appears in {len(counts)} post(s) (top {top_k}):")
for p in counts[:5]:
print(f" - {p['id']} ({p['count']} hits): {p['title']}")
print()
return results
# ---------------------------------------------------------------------
# Consolidated help()
# ---------------------------------------------------------------------
def help():
"""
Axio utilities – available functions:
CORE:
- help()
Show this help message.
BROWSING & NAVIGATION:
- list_posts(limit=None, contains=None, page=None, page_size=None)
List basic metadata for posts (date, id, title).
Modes:
- If page is provided: show that page (pagination mode).
- Else if limit is provided: show newest `limit` posts (ignores pagination).
- Else: show the current pagination page.
- next()
Move forward one page using the current pagination state.
- prev()
Move back one page using the current pagination state.
- home()
Jump to the first page (newest posts) using current page_size.
- end()
Jump to the last page (oldest posts) using current page_size.
- status()
Show current pagination status: page, page_size, total_pages, total_posts.
- goto(page)
Jump directly to a page number using current page_size.
- view(page=None)
TUI-like browser for the corpus. Shows a framed page with navigation hints.
If page is None, uses the current page from the pagination state.
POST ACCESS:
- get_post(post_id, show_content=False)
Retrieve a single post by its ID.
Args:
post_id (str): e.g. "162560090.the-physics-of-agency-part-5-the"
show_content (bool): if True, prints the full content.
Returns:
dict with keys: id, title, subtitle, date, content.
SEARCH & ANALYSIS:
- find_posts(pattern, field='all', limit=50)
Search posts by case-insensitive pattern.
Args:
pattern (str): substring or regex to search for.
field (str): 'title', 'subtitle', 'content', or 'all' (default).
limit (int): maximum number of matches to return.
- extract_definitions()
Scan all posts for lines starting with 'Definition:' (case-insensitive).
Returns:
list of dicts: { 'id', 'title', 'definition' }.
- map_concepts(terms, top_k=20)
Build a simple concept-to-post mapping for given terms.
Args:
terms (list[str]): list of concept strings to track (case-insensitive).
top_k (int): max posts per term.
Returns:
dict: { term: [ { 'id', 'title', 'count' }, ... ] }.
SEQUENCES & INDEX:
- generate_sequence(name, ids, as_markdown=True)
Generate a markdown (or plain text) block for an Axio sequence.
Args:
name (str): human-readable sequence name.
ids (list[str]): list of post IDs in desired order.
as_markdown (bool): if True, returns markdown with links.
Returns:
str – sequence listing suitable for Axio.
- update_axio_index(as_markdown=True)
Generate a simple Axio Index of all posts, sorted by date.
Args:
as_markdown (bool): if True, returns markdown; otherwise plain text.
Returns:
str – index listing (markdown or plain text).
"""
print(help.__doc__)
print(f"Axio bootstrap loaded. Total posts: {TOTAL_POSTS}. Use view(), list_posts(), help(), etc.")