-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackager.py
More file actions
1372 lines (1154 loc) · 52 KB
/
Copy pathpackager.py
File metadata and controls
1372 lines (1154 loc) · 52 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Offline knowledge pack builder — SQLite FTS5 + optional corpus-derived vectors.
Builds portable .db packs from any data source (JSON, CSV, GeoJSON, piped stdin).
Packs support three search modes:
1. FTS5 full-text search (always available, zero dependencies)
2. Optional corpus-derived vectors (LSA, TF-IDF SVD, or pre-computed — user/agent decides at build time)
3. LLM rerank via llama.rn on-device (app-side, not in packager)
Pack spec (.db contract):
Required: chunks + fts_chunks (FTS5, content-synced, no data duplication) + pack_metadata
Optional: chunk_vectors (corpus-derived vectors — method described in metadata,
no neural model reference, user/agent decides at build time)
Optional: geo_points (spatial), layers (organisational)
Designed to be called from the command line — by any AI agent, automation
script, or human.
Zero external dependencies — uses only Python stdlib (sqlite3, json, csv, struct).
Usage:
python3 packager.py init --output pack.db --name "au-scams" --country AU
python3 packager.py add-layer --pack pack.db --name hospitals --tier static_reference --file data.json
python3 packager.py add-geo --pack pack.db --layer hospitals --lat-field lat --lon-field lon
python3 packager.py vectorise --pack pack.db --method lsa --dimensions 64
python3 packager.py vectorise --pack pack.db --method file --file vectors.json
python3 packager.py build-index --pack pack.db
python3 packager.py info --pack pack.db
python3 packager.py query --pack pack.db --search "hospital emergency"
python3 packager.py archive --pack pack.db --output pack.oapack.zip
python3 packager.py build --manifest manifest.json --output pack.db --archive
License: Apache-2.0
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import math
import os
import sqlite3
import struct
import sys
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
BUILDER_VERSION = "0.4.0"
ARCHIVE_FORMAT_VERSION = "1.0"
ARCHIVE_ARTIFACT_TYPE = "offlineaid.pack.archive"
ARCHIVE_MANIFEST_FILENAME = "manifest.json"
VALID_TIERS = ("static_reference", "periodic_snapshot", "realtime_cache")
# ── Schema ────────────────────────────────────────────────────────────
SCHEMA_SQL = """
-- Pack metadata (key-value)
CREATE TABLE IF NOT EXISTS pack_metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- Data layers with tier classification
CREATE TABLE IF NOT EXISTS layers (
name TEXT PRIMARY KEY,
tier TEXT NOT NULL CHECK(tier IN ('static_reference','periodic_snapshot','realtime_cache')),
description TEXT,
row_count INTEGER DEFAULT 0,
source_type TEXT,
source_info TEXT,
added_at TEXT NOT NULL,
-- Provenance (per-source, optional). Trust pillar: a pack composed of
-- multiple sources carries each source's own publisher/licence so the
-- on-device nutrition-label UI can attribute every chunk correctly.
publisher TEXT, -- e.g. "ACCC", "NASC", "Department of PM&C"
license TEXT, -- SPDX-style id where possible, e.g. "CC-BY-4.0-AU"
source_url TEXT, -- canonical URL of the upstream source
reviewed_at TEXT, -- ISO-8601 UTC of last human review
cultural_sensitivity TEXT, -- free-text flag (e.g. "indigenous-protocols")
expires_at TEXT, -- ISO-8601 UTC; UI may warn if past
language TEXT -- BCP-47 tag of the source content
);
-- Text chunks — the core data store
-- Each row is a searchable chunk of content from a layer.
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
source TEXT NOT NULL, -- layer name (matches layers.name)
section TEXT DEFAULT '', -- sub-section within layer (optional)
data TEXT, -- full JSON object (original row)
tokens INTEGER DEFAULT 0 -- estimated token count for LLM context budgeting
);
-- FTS5 full-text search index over chunks (Tier 1 search — always available)
CREATE VIRTUAL TABLE IF NOT EXISTS fts_chunks USING fts5(
text, source, section,
content='chunks', content_rowid='id'
);
-- Geo-located points of interest (optional, for map features)
CREATE TABLE IF NOT EXISTS geo_points (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
name_local TEXT, -- local language name (e.g. Traditional Chinese)
category TEXT NOT NULL, -- 'hospital', 'embassy', 'fuel', 'shelter', etc.
lat REAL NOT NULL,
lon REAL NOT NULL,
address TEXT,
address_local TEXT,
district TEXT,
metadata TEXT, -- JSON: opening hours, phone, services, etc.
chunk_id INTEGER REFERENCES chunks(id),
layer TEXT REFERENCES layers(name)
);
CREATE INDEX IF NOT EXISTS idx_geo_category ON geo_points(category);
CREATE INDEX IF NOT EXISTS idx_geo_district ON geo_points(district);
CREATE INDEX IF NOT EXISTS idx_geo_layer ON geo_points(layer);
CREATE INDEX IF NOT EXISTS idx_geo_coords ON geo_points(lat, lon);
CREATE INDEX IF NOT EXISTS idx_chunks_source ON chunks(source);
-- Corpus-derived vectors (optional — user/agent decides at build time)
-- Method (LSA, TF-IDF SVD, etc.) and dimensions stored in pack_metadata,
-- NOT per-row. No neural model reference — these are corpus-derived.
-- Vectors stored as little-endian float32 blobs for portability.
CREATE TABLE IF NOT EXISTS chunk_vectors (
chunk_id INTEGER PRIMARY KEY REFERENCES chunks(id),
vector BLOB NOT NULL -- float32[] as little-endian bytes
);
"""
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
def _file_sha256(path: str) -> str:
"""Compute a hex SHA-256 digest for a file."""
hasher = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(1024 * 1024):
hasher.update(chunk)
return hasher.hexdigest()
def _pack_metadata(path: str) -> dict[str, str]:
"""Read pack metadata from an existing SQLite pack."""
conn: sqlite3.Connection | None = None
try:
conn = sqlite3.connect(path)
meta = dict(conn.execute("SELECT key, value FROM pack_metadata").fetchall())
except sqlite3.Error as exc:
raise ValueError(f"{path} is not a valid OfflineAid pack database: {exc}") from exc
finally:
if conn is not None:
conn.close()
if not meta.get("name"):
raise ValueError(f"{path} is missing required pack metadata ('name').")
return meta
def _default_archive_output(pack_path: str) -> str:
"""Return the default archive output path for a .db pack."""
pack = Path(pack_path)
return str(pack.with_name(f"{pack.stem}.oapack.zip"))
def _archive_checksum_filename(db_filename: str) -> str:
return f"{db_filename}.sha256"
def _checksum_contents(db_filename: str, db_sha256: str) -> str:
return f"{db_sha256} {db_filename}\n"
def _build_archive_manifest(pack_path: str, created_at: str | None = None) -> dict[str, str]:
"""Build the transport manifest for an archived pack."""
meta = _pack_metadata(pack_path)
return {
"format_version": ARCHIVE_FORMAT_VERSION,
"artifact_type": ARCHIVE_ARTIFACT_TYPE,
"pack_name": meta["name"],
"pack_version": meta.get("version", "1.0.0"),
"db_filename": Path(pack_path).name,
"db_sha256": _file_sha256(pack_path),
"builder_version": meta.get("builder_version", BUILDER_VERSION),
"created_at": created_at or _now(),
}
def _parse_checksum_contents(contents: str, db_filename: str) -> str:
"""Parse a checksum sidecar file and return the hex digest."""
stripped = contents.strip()
if not stripped:
raise ValueError("Checksum file is empty.")
parts = stripped.split()
digest = parts[0].lower()
if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
raise ValueError("Checksum file does not contain a valid SHA-256 digest.")
if len(parts) > 1 and parts[1].lstrip("*") != db_filename:
raise ValueError("Checksum file does not reference the archived database filename.")
return digest
def _validate_archive_contract(archive_path: str) -> dict[str, Any]:
"""Validate an OfflineAid archive and return its manifest."""
try:
with zipfile.ZipFile(archive_path, "r") as zf:
file_names = [info.filename for info in zf.infolist() if not info.is_dir()]
if not file_names:
raise ValueError("Archive is empty.")
if any(Path(name).name != name for name in file_names):
raise ValueError("Archive entries must be top-level files.")
db_files = [name for name in file_names if name.lower().endswith(".db")]
if len(db_files) != 1:
raise ValueError("Archive must contain exactly one SQLite .db file.")
manifest_count = file_names.count(ARCHIVE_MANIFEST_FILENAME)
if manifest_count != 1:
raise ValueError("Archive must contain exactly one manifest.json file.")
checksum_files = [name for name in file_names if name.lower().endswith(".sha256")]
if len(checksum_files) > 1:
raise ValueError("Archive may contain at most one checksum file.")
allowed = {db_files[0], ARCHIVE_MANIFEST_FILENAME, *checksum_files}
extras = [name for name in file_names if name not in allowed]
if extras:
raise ValueError(f"Archive contains unexpected files: {', '.join(sorted(extras))}")
try:
manifest = json.loads(zf.read(ARCHIVE_MANIFEST_FILENAME))
except json.JSONDecodeError as exc:
raise ValueError("Archive manifest.json is not valid JSON.") from exc
required_fields = {
"format_version",
"artifact_type",
"pack_name",
"pack_version",
"db_filename",
"db_sha256",
"builder_version",
"created_at",
}
missing = sorted(required_fields - set(manifest))
if missing:
raise ValueError(f"Archive manifest is missing required fields: {', '.join(missing)}")
if manifest["format_version"] != ARCHIVE_FORMAT_VERSION:
raise ValueError(
f"Unsupported archive format version: {manifest['format_version']}"
)
if manifest["artifact_type"] != ARCHIVE_ARTIFACT_TYPE:
raise ValueError(f"Unsupported archive artifact type: {manifest['artifact_type']}")
db_filename = manifest["db_filename"]
if db_filename != db_files[0]:
raise ValueError("Archive manifest db_filename does not match the packaged .db file.")
db_sha256 = hashlib.sha256(zf.read(db_filename)).hexdigest()
if db_sha256 != manifest["db_sha256"]:
raise ValueError("Archive manifest db_sha256 does not match the packaged database.")
if checksum_files:
checksum_name = checksum_files[0]
expected_checksum_name = _archive_checksum_filename(db_filename)
if checksum_name != expected_checksum_name:
raise ValueError(
"Checksum filename must match the archived database filename."
)
checksum_sha256 = _parse_checksum_contents(
zf.read(checksum_name).decode("utf-8"),
db_filename,
)
if checksum_sha256 != manifest["db_sha256"]:
raise ValueError("Checksum file does not match the manifest digest.")
except zipfile.BadZipFile as exc:
raise ValueError(f"{archive_path} is not a valid ZIP archive.") from exc
return manifest
def _estimate_tokens(text: str) -> int:
"""Rough token estimate (~4 chars per token for English, ~2 for CJK)."""
# Count CJK characters
cjk = sum(1 for c in text if '\u4e00' <= c <= '\u9fff' or '\u3400' <= c <= '\u4dbf')
non_cjk = len(text) - cjk
return (non_cjk // 4) + (cjk // 2)
def _flatten_to_text(obj: dict) -> str:
"""Flatten a dict to a searchable text string."""
parts = []
for k, v in obj.items():
if v is None or k.startswith("_"):
continue
if isinstance(v, (dict, list)):
parts.append(json.dumps(v, ensure_ascii=False))
else:
parts.append(str(v))
return " ".join(parts)
def _vector_to_blob(vec: list[float]) -> bytes:
"""Pack a float32 vector into a little-endian bytes blob."""
return struct.pack(f"<{len(vec)}f", *vec)
def _blob_to_vector(blob: bytes) -> list[float]:
"""Unpack a little-endian bytes blob into a float32 list."""
n = len(blob) // 4
return list(struct.unpack(f"<{n}f", blob))
def _cosine_similarity(a: list[float], b: list[float]) -> float:
"""Compute cosine similarity between two vectors."""
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(x * x for x in b))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot / (norm_a * norm_b)
# ── Data readers ──────────────────────────────────────────────────────
def _read_json(path: str) -> list[dict]:
"""Read a JSON file (array of objects, single object, CKAN response, or GeoJSON)."""
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
if "result" in data and isinstance(data["result"], list):
return data["result"]
if "results" in data and isinstance(data["results"], list):
return data["results"]
if "features" in data and isinstance(data["features"], list):
return [
{**feat.get("properties", {}), "_geometry": feat.get("geometry")}
for feat in data["features"]
]
return [data]
if isinstance(data, list):
return data
raise ValueError(f"Unsupported JSON structure in {path}")
def _read_csv(path: str) -> list[dict]:
with open(path, "r", encoding="utf-8-sig") as f:
return list(csv.DictReader(f))
def _read_stdin(fmt: str) -> list[dict]:
if fmt == "csv":
return list(csv.DictReader(sys.stdin))
data = json.load(sys.stdin)
return data if isinstance(data, list) else [data]
def _read_data(file_path: str | None, fmt: str, from_stdin: bool) -> list[dict]:
if from_stdin:
return _read_stdin(fmt)
if file_path is None:
raise ValueError("Either --file or --from-stdin is required")
if fmt == "csv":
return _read_csv(file_path)
if fmt in ("json", "geojson"):
return _read_json(file_path)
try:
return _read_json(file_path)
except (json.JSONDecodeError, ValueError):
return _read_csv(file_path)
# ── API ──────────────────────────────────────────────────────────────
def init_pack(
output: str,
name: str,
version: str = "1.0.0",
country: str = "",
scenario: str = "",
force: bool = False,
) -> str:
"""Initialize a new pack database (API)."""
if os.path.exists(output) and not force:
raise FileExistsError(f"{output} already exists. Use force=True to overwrite.")
if os.path.exists(output) and force:
os.remove(output)
os.makedirs(os.path.dirname(output) or ".", exist_ok=True)
conn = sqlite3.connect(output)
try:
conn.executescript(SCHEMA_SQL)
meta = {
"name": name,
"version": version,
"country": country,
"scenario": scenario,
"created_at": _now(),
"builder_version": BUILDER_VERSION,
"sources": "[]",
}
with conn:
conn.executemany(
"INSERT OR REPLACE INTO pack_metadata (key, value) VALUES (?, ?)",
meta.items(),
)
finally:
conn.close()
return output
def add_layer(
pack_path: str,
name: str,
tier: str,
rows: list[dict[str, Any]],
description: str = "",
section: str = "",
source_info: str = "",
source_type: str = "agent",
provenance: dict[str, str | None] | None = None,
) -> dict[str, Any]:
"""Add a data layer to an existing pack (API)."""
if not os.path.exists(pack_path):
raise FileNotFoundError(f"Pack {pack_path} does not exist.")
if tier not in VALID_TIERS:
raise ValueError(f"Tier must be one of {VALID_TIERS}")
if not rows:
return {"name": name, "row_count": 0, "status": "no_data"}
conn = sqlite3.connect(pack_path)
now = _now()
chunks = []
for row in rows:
if not isinstance(row, dict):
row = {"value": row}
text = _flatten_to_text(row)
tokens = _estimate_tokens(text)
# Allow row to override layer-level section
row_section = row.get("section", section)
chunks.append((
text,
name, # source = layer name
row_section,
json.dumps(row, ensure_ascii=False),
tokens,
))
p = provenance or {}
try:
with conn:
conn.execute(
"""INSERT OR REPLACE INTO layers (
name, tier, description, row_count, source_type, source_info, added_at,
publisher, license, source_url, reviewed_at,
cultural_sensitivity, expires_at, language
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
name, tier, description, len(rows), source_type, source_info, now,
p.get("publisher"),
p.get("license"),
p.get("source_url"),
p.get("reviewed_at"),
p.get("cultural_sensitivity"),
p.get("expires_at"),
p.get("language"),
),
)
# Remove stale chunks so re-running add-layer is idempotent (§26.2.1).
conn.execute("DELETE FROM chunks WHERE source = ?", (name,))
conn.executemany(
"INSERT INTO chunks (text, source, section, data, tokens) VALUES (?, ?, ?, ?, ?)",
chunks,
)
finally:
conn.close()
return {"name": name, "row_count": len(rows), "tier": tier}
def add_geo_points(
pack_path: str,
layer: str,
points: list[dict[str, Any]],
) -> dict[str, Any]:
"""Add geo points for a layer (API).
Expected point format: {
"lat": float, "lon": float, "name": str, "chunk_id": int (optional),
"name_local": str, "address": str, "address_local": str, "district": str,
"category": str, "metadata": dict
}
"""
conn = sqlite3.connect(pack_path)
try:
# Verify layer exists
exists = conn.execute("SELECT name FROM layers WHERE name = ?", (layer,)).fetchone()
if not exists:
raise ValueError(f"Layer '{layer}' not found.")
geo_rows = []
for p in points:
lat = p.get("lat")
lon = p.get("lon")
if lat is None or lon is None:
continue
metadata = p.get("metadata")
geo_rows.append((
str(p.get("name", "")),
p.get("name_local"),
p.get("category") or layer,
float(lat),
float(lon),
p.get("address"),
p.get("address_local"),
p.get("district"),
json.dumps(metadata, ensure_ascii=False) if metadata else None,
p.get("chunk_id"),
layer,
))
with conn:
conn.execute("DELETE FROM geo_points WHERE layer = ?", (layer,))
conn.executemany(
"""INSERT INTO geo_points (name, name_local, category, lat, lon, address,
address_local, district, metadata, chunk_id, layer)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
geo_rows,
)
finally:
conn.close()
return {"layer": layer, "point_count": len(geo_rows)}
def build_index(pack_path: str) -> dict[str, Any]:
"""Rebuild the FTS5 search index (API)."""
conn = sqlite3.connect(pack_path)
try:
with conn:
conn.execute("INSERT INTO fts_chunks(fts_chunks) VALUES('rebuild')")
count = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]
finally:
conn.close()
return {"chunks_indexed": count}
def archive_pack(
pack_path: str,
output: str | None = None,
force: bool = False,
) -> str:
"""Package a built .db into an OfflineAid transport archive (API)."""
if not os.path.exists(pack_path):
raise FileNotFoundError(f"Pack {pack_path} does not exist.")
out = output or _default_archive_output(pack_path)
if os.path.exists(out) and not force:
raise FileExistsError(f"{out} already exists. Use force=True to overwrite.")
if os.path.exists(out) and force:
os.remove(out)
manifest = _build_archive_manifest(pack_path)
db_filename = manifest["db_filename"]
checksum_filename = _archive_checksum_filename(db_filename)
os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
zf.write(pack_path, arcname=db_filename)
zf.writestr(
ARCHIVE_MANIFEST_FILENAME,
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
)
zf.writestr(
checksum_filename,
_checksum_contents(db_filename, manifest["db_sha256"]),
)
_validate_archive_contract(out)
return out
def verify_pack_archive(archive_path: str) -> dict[str, Any]:
"""Verify an OfflineAid archive (API)."""
if not os.path.exists(archive_path):
raise FileNotFoundError(f"{archive_path} does not exist.")
return _validate_archive_contract(archive_path)
# ── Commands ──────────────────────────────────────────────────────────
def cmd_init(args: argparse.Namespace) -> None:
"""Initialize a new pack database."""
try:
init_pack(
output=args.output,
name=args.name,
version=args.version or "1.0.0",
country=args.country or "",
scenario=args.scenario or "",
force=args.force,
)
except FileExistsError as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
print(f"Initialized pack: {args.output} ({args.name})")
def cmd_add_layer(args: argparse.Namespace) -> None:
"""Add a data layer to an existing pack."""
data = _read_data(args.file, args.format or "json", args.from_stdin)
if not data:
print("Warning: no data rows found.", file=sys.stderr)
return
source_type = "stdin" if args.from_stdin else ("file" if args.file else "unknown")
source_info = args.file or "stdin"
provenance = {
"publisher": getattr(args, "publisher", None),
"license": getattr(args, "license", None),
"source_url": getattr(args, "source_url", None),
"reviewed_at": getattr(args, "reviewed_at", None),
"cultural_sensitivity": getattr(args, "cultural_sensitivity", None),
"expires_at": getattr(args, "expires_at", None),
"language": getattr(args, "language", None),
}
try:
res = add_layer(
pack_path=args.pack,
name=args.name,
tier=args.tier,
rows=data,
description=args.description or "",
section=args.section or "",
source_info=source_info,
source_type=source_type,
provenance=provenance,
)
except (FileNotFoundError, ValueError) as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
print(f"Added layer '{res['name']}' ({res['row_count']} rows, tier={res['tier']}) to {args.pack}")
def cmd_add_geo(args: argparse.Namespace) -> None:
"""Extract geo points from an existing layer's chunks."""
conn = sqlite3.connect(args.pack)
try:
layer_row = conn.execute("SELECT name FROM layers WHERE name = ?", (args.layer,)).fetchone()
if not layer_row:
print(f"Error: layer '{args.layer}' not found.", file=sys.stderr)
sys.exit(1)
lat_field = args.lat_field
lon_field = args.lon_field
name_field = args.name_field or "name"
name_local_field = args.name_local_field
category = args.category or args.layer
rows = conn.execute(
"SELECT id, data FROM chunks WHERE source = ?", (args.layer,)
).fetchall()
finally:
conn.close()
points = []
for chunk_id, data_json in rows:
if not data_json:
continue
try:
obj = json.loads(data_json)
except json.JSONDecodeError:
continue
lat = obj.get(lat_field)
lon = obj.get(lon_field)
if lat is None or lon is None:
continue
try:
lat, lon = float(lat), float(lon)
except (ValueError, TypeError):
continue
name = str(obj.get(name_field, ""))
name_local = str(obj.get(name_local_field, "")) if name_local_field else None
address = obj.get("address", obj.get("address_en", ""))
address_local = obj.get("address_local", obj.get("address_tc", ""))
district = obj.get("district", "")
skip = {lat_field, lon_field, name_field, "address", "address_en", "address_tc",
"address_local", "district"}
if name_local_field:
skip.add(name_local_field)
metadata = {k: v for k, v in obj.items() if k not in skip and not k.startswith("_")}
points.append({
"name": name,
"name_local": name_local,
"category": category,
"lat": lat,
"lon": lon,
"address": str(address) if address else None,
"address_local": str(address_local) if address_local else None,
"district": str(district) if district else None,
"metadata": metadata if metadata else None,
"chunk_id": chunk_id,
})
try:
res = add_geo_points(
pack_path=args.pack,
layer=args.layer,
points=points,
)
except ValueError as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
print(f"Added {res['point_count']} geo points for layer '{args.layer}' (category={category})")
def cmd_build_index(args: argparse.Namespace) -> None:
"""Rebuild the FTS5 search index."""
res = build_index(args.pack)
print(f"FTS5 index rebuilt: {res['chunks_indexed']} chunks indexed")
def _tfidf_vectors(texts: list[str], dimensions: int) -> list[list[float]]:
"""Build TF-IDF matrix then reduce to `dimensions` via truncated SVD.
Pure stdlib implementation — no numpy/scipy/sklearn required.
Uses power-iteration SVD approximation for portability.
"""
import re
from collections import Counter
# Tokenise
tokenised = [re.findall(r"\w+", t.lower()) for t in texts]
n_docs = len(tokenised)
# Build vocabulary (top terms by doc frequency, cap at 5000 for speed)
df: dict[str, int] = Counter()
for tokens in tokenised:
for w in set(tokens):
df[w] += 1
# Filter: must appear in ≥2 docs and ≤80 % of docs
vocab_list = [
w for w, c in df.most_common(5000)
if c >= 2 and c <= 0.8 * n_docs
]
if not vocab_list:
vocab_list = [w for w, _ in df.most_common(min(500, len(df)))]
vocab = {w: i for i, w in enumerate(vocab_list)}
v_size = len(vocab)
if v_size == 0 or n_docs == 0:
return [[0.0] * dimensions for _ in texts]
# Build TF-IDF sparse rows
idf = {}
for w, c in df.items():
if w in vocab:
idf[w] = math.log((1 + n_docs) / (1 + c)) + 1
# Sparse matrix as list of dicts
tfidf_rows: list[dict[int, float]] = []
for tokens in tokenised:
tf = Counter(tokens)
row: dict[int, float] = {}
for w, count in tf.items():
if w in vocab:
row[vocab[w]] = (1 + math.log(count)) * idf.get(w, 1.0)
# L2 normalise
norm = math.sqrt(sum(v * v for v in row.values())) or 1.0
row = {k: v / norm for k, v in row.items()}
tfidf_rows.append(row)
# Truncated SVD via power iteration (sparse-friendly)
dims = min(dimensions, v_size, n_docs)
import random
random.seed(42)
# Random projection matrix V: dims x v_size
V = [[random.gauss(0, 1) for _ in range(v_size)] for _ in range(dims)]
# Normalise rows of V
for row in V:
norm = math.sqrt(sum(x * x for x in row)) or 1.0
for j in range(len(row)):
row[j] /= norm
# Power iterations: A^T A V^T (A is n_docs x v_size sparse)
for _ in range(5):
# AV^T => n_docs x dims
AV = []
for sparse_row in tfidf_rows:
r = []
for vi in range(dims):
s = sum(sparse_row.get(j, 0.0) * V[vi][j] for j in sparse_row)
r.append(s)
AV.append(r)
# A^T (AV) => v_size x dims
AtAV = [[0.0] * dims for _ in range(v_size)]
for doc_i, sparse_row in enumerate(tfidf_rows):
for j in sparse_row:
for d in range(dims):
AtAV[j][d] += sparse_row[j] * AV[doc_i][d]
# QR via Gram-Schmidt on AtAV columns (transposed = dims x v_size)
V_new = []
for d in range(dims):
col = [AtAV[j][d] for j in range(v_size)]
# Orthogonalise against previous
for prev in V_new:
dot = sum(a * b for a, b in zip(col, prev))
col = [c - dot * p for c, p in zip(col, prev)]
norm = math.sqrt(sum(x * x for x in col)) or 1.0
V_new.append([x / norm for x in col])
V = V_new
# Project: each doc => dims-dimensional vector
result = []
for sparse_row in tfidf_rows:
vec = []
for vi in range(dims):
s = sum(sparse_row.get(j, 0.0) * V[vi][j] for j in sparse_row)
vec.append(s)
# L2 normalise
norm = math.sqrt(sum(x * x for x in vec)) or 1.0
result.append([x / norm for x in vec])
return result
def cmd_vectorise(args: argparse.Namespace) -> None:
"""Generate corpus-derived vectors for all chunks.
Supports three methods:
1. --method lsa : TF-IDF + truncated SVD (pure stdlib, zero deps)
2. --method tfidf : alias for lsa
3. --method file : reads pre-computed vectors from a JSON file
File format: [{"chunk_id": 1, "vector": [0.1, 0.2, ...]}, ...]
Vector method and dimensions are stored in pack_metadata (NOT per-row).
No neural model reference — these are corpus-derived.
"""
conn = sqlite3.connect(args.pack)
method = args.method
dims = args.dimensions or 64
if method == "file":
# Load pre-computed vectors from JSON
with open(args.file, "r") as f:
vectors = json.load(f)
if not vectors:
print("No vectors found in file.", file=sys.stderr)
return
actual_dims = len(vectors[0]["vector"])
method_name = args.method_name or Path(args.file).stem
conn.execute("DELETE FROM chunk_vectors")
for item in vectors:
conn.execute(
"INSERT INTO chunk_vectors (chunk_id, vector) VALUES (?, ?)",
(item["chunk_id"], _vector_to_blob(item["vector"])),
)
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('has_vectors', 'true')")
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('vector_method', ?)", (method_name,))
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('vector_dimensions', ?)", (str(actual_dims),))
conn.commit()
conn.close()
print(f"Loaded {len(vectors)} vectors from file ({actual_dims}d, method={method_name})")
return
# Corpus-derived: LSA / TF-IDF SVD (pure stdlib)
chunks = conn.execute("SELECT id, text FROM chunks").fetchall()
if not chunks:
print("No chunks in pack — add layers first.", file=sys.stderr)
conn.close()
return
total = len(chunks)
ids = [cid for cid, _ in chunks]
texts = [text for _, text in chunks]
print(f"Computing {method.upper()} vectors for {total} chunks (dimensions={dims})...")
vectors = _tfidf_vectors(texts, dims)
actual_dims = len(vectors[0]) if vectors else dims
conn.execute("DELETE FROM chunk_vectors")
for i, vec in enumerate(vectors):
conn.execute(
"INSERT INTO chunk_vectors (chunk_id, vector) VALUES (?, ?)",
(ids[i], _vector_to_blob(vec)),
)
method_label = f"tfidf-svd-{actual_dims}d"
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('has_vectors', 'true')")
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('vector_method', ?)", (method_label,))
conn.execute("INSERT OR REPLACE INTO pack_metadata VALUES ('vector_dimensions', ?)", (str(actual_dims),))
conn.commit()
conn.close()
print(f"Done: {total} vectors ({actual_dims}d, method={method_label}) written to pack")
def cmd_info(args: argparse.Namespace) -> None:
"""Show pack metadata and statistics."""
conn = sqlite3.connect(args.pack)
meta = dict(conn.execute("SELECT key, value FROM pack_metadata").fetchall())
layers = conn.execute(
"SELECT name, tier, row_count, description FROM layers ORDER BY name"
).fetchall()
total_chunks = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]
total_geo = conn.execute("SELECT COUNT(*) FROM geo_points").fetchone()[0]
try:
fts_count = conn.execute("SELECT COUNT(*) FROM fts_chunks").fetchone()[0]
except sqlite3.OperationalError:
fts_count = 0
try:
vec_count = conn.execute("SELECT COUNT(*) FROM chunk_vectors").fetchone()[0]
except sqlite3.OperationalError:
vec_count = 0
file_size = os.path.getsize(args.pack)
conn.close()
print(f"Pack: {meta.get('name', '?')} v{meta.get('version', '?')}")
print(f"Country: {meta.get('country', '?')} | Scenario: {meta.get('scenario', '?')}")
print(f"Created: {meta.get('created_at', '?')}")
print(f"Builder: v{meta.get('builder_version', '?')}")
print(f"Size: {file_size:,} bytes ({file_size / 1024 / 1024:.1f} MB)")
print(f"Chunks: {total_chunks:,} | FTS indexed: {fts_count:,} | Geo points: {total_geo:,}")
has_vec = meta.get("has_vectors") == "true"
if has_vec:
print(f"Vectors: {vec_count:,} ({meta.get('vector_dimensions', '?')}d, method={meta.get('vector_method', '?')})")
else:
print("Vectors: none (run 'vectorise' command to add)")
print()
if layers:
print(f"{'Layer':<30} {'Tier':<20} {'Rows':>8} Description")
print("-" * 90)
for name, tier, row_count, desc in layers:
print(f"{name:<30} {tier:<20} {row_count:>8} {desc or ''}")
else:
print("No layers added yet.")
def _sanitise_fts_query(q: str) -> str:
"""Strip FTS5 syntax chars that raise OperationalError (§26.2.2).
FTS5 reserves: : * " ( ) ^ - and the operators NEAR AND OR NOT.
Strip punctuation, then quote any token that is a reserved operator so
it is treated as a literal search term rather than a query modifier.
"""
import re
q = re.sub(r'[":*()^-]+', " ", q)
tokens = q.split()
safe = []
for t in tokens:
if t.upper() in {"NEAR", "AND", "OR", "NOT"}:
t = f'"{t}"'
safe.append(t)
return " ".join(safe).strip() or '""'
def cmd_query(args: argparse.Namespace) -> None:
"""Search the pack — FTS5 with optional vector rerank."""
conn = sqlite3.connect(args.pack)
# Step 1: FTS5 search
sql = """