File size: 5,321 Bytes
4dd8bd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build offline/knowledge_base.sqlite with SQLite FTS5 full-text search. Standard library only.

Usage: python scripts/build_offline_database.py [repo_root]

Creates one table per dataset table (list fields stored as JSON text), a record_sources link table,
FTS5 indexes over every record (`search`, word tokenizer; `search_trigram`, substring/CJK search) and over the
text of archived redistributable documents (`documents_fts`, from offline/permitted_documents_text/*.txt).
"""
import json
import sqlite3
import sys
import time
from pathlib import Path

root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent.parent
schema = json.loads((root / "schema.json").read_text("utf-8"))
db_path = root / "offline" / "knowledge_base.sqlite"
db_path.parent.mkdir(parents=True, exist_ok=True)
db_path.unlink(missing_ok=True)
con = sqlite3.connect(db_path)
con.execute("PRAGMA journal_mode=OFF")


def load(name):
    p = root / "json" / f"{name}.json"
    return json.loads(p.read_text("utf-8")) if p.exists() else []


def cell(v):
    if isinstance(v, (list, dict)):
        return json.dumps(v, ensure_ascii=False)
    if isinstance(v, bool):
        return int(v)
    return v


def create(name, rows, key):
    cols = list(dict.fromkeys(c for r in rows for c in r)) or [key]
    con.execute(f'CREATE TABLE "{name}" (' + ", ".join(f'"{c}" TEXT' + (" PRIMARY KEY" if c == key else "") for c in cols) + ")")
    con.executemany(f'INSERT INTO "{name}" VALUES (' + ",".join("?" * len(cols)) + ")",
                    [[cell(r.get(c)) for c in cols] for r in rows])
    return cols


counts = {}
con.execute("CREATE VIRTUAL TABLE search USING fts5(record_id UNINDEXED, table_name UNINDEXED, title, body, tokenize='unicode61 remove_diacritics 2')")
con.execute("CREATE VIRTUAL TABLE search_trigram USING fts5(record_id UNINDEXED, table_name UNINDEXED, title, body, tokenize='trigram')")
con.execute("CREATE TABLE record_sources (record_id TEXT, source_id TEXT, PRIMARY KEY (record_id, source_id))")
for t, spec in schema["tables"].items():
    rows = load(t)
    counts[t] = len(rows)
    create(t, rows, "id")
    for r in rows:
        title = str(r.get(spec["title_field"]) or r["id"])
        if t == "accreditation_relationships":
            title = f"{r.get('subject_id')} {r.get('relationship_type')} {r.get('object_id')}"
        if t == "certification_procedures":
            title = f"{r.get('scheme_id')} step {r.get('step_no')}: {r.get('step_name')}"
        body = " \n".join(f"{k}: {cell(v)}" for k, v in r.items() if k not in ("source_ids", "contributors", "merged_from", "extra") and v not in ("", None, [], "unknown"))
        for fts in ("search", "search_trigram"):
            con.execute(f"INSERT INTO {fts} VALUES (?,?,?,?)", (r["id"], t, title, body))
        con.executemany("INSERT OR IGNORE INTO record_sources VALUES (?,?)", [(r["id"], s) for s in r.get("source_ids") or []])

sources = load("official_sources")
counts["official_sources"] = len(sources)
create("official_sources", sources, "source_id")
docs = load("document_metadata")
counts["document_metadata"] = len(docs)
create("document_metadata", docs, "doc_id") if docs else con.execute("CREATE TABLE document_metadata (doc_id TEXT PRIMARY KEY)")

con.execute("CREATE VIRTUAL TABLE documents_fts USING fts5(doc_id UNINDEXED, source_id UNINDEXED, title, content, tokenize='unicode61 remove_diacritics 2')")
text_dir = root / "offline" / "permitted_documents_text"
n_text = 0
for d in docs:
    p = text_dir / f"{d['doc_id']}.txt"
    if p.exists():
        con.execute("INSERT INTO documents_fts VALUES (?,?,?,?)", (d["doc_id"], d["source_id"], d.get("title", ""), p.read_text("utf-8")))
        n_text += 1
counts["documents_fts"] = n_text

con.executescript("""
CREATE VIEW scheme_overview AS
  SELECT s.id, s.name, s.scheme_type, s.jurisdiction, s.mandatory_or_voluntary, o.name AS owner, s.validity_period, s.fees, s.public_verification
  FROM certification_schemes s LEFT JOIN organizations o ON o.id = s.owner_org_id;
CREATE VIEW relationship_names AS
  SELECT r.id, r.subject_id, COALESCE(a.name, r.subject_id) AS subject_name, r.relationship_type, r.object_id,
         COALESCE(b.name, sc.name, st.designation, r.object_id) AS object_name, r.scope
  FROM accreditation_relationships r
  LEFT JOIN organizations a ON a.id = r.subject_id
  LEFT JOIN organizations b ON b.id = r.object_id
  LEFT JOIN certification_schemes sc ON sc.id = r.object_id
  LEFT JOIN standards st ON st.id = r.object_id;
CREATE VIEW record_citations AS
  SELECT rs.record_id, s.source_id, s.url, s.title, s.issuing_org, s.pub_date, s.licence_category
  FROM record_sources rs JOIN official_sources s ON s.source_id = rs.source_id;
""")
con.execute("CREATE TABLE kb_metadata (key TEXT PRIMARY KEY, value TEXT)")
con.executemany("INSERT INTO kb_metadata VALUES (?,?)", [
    ("dataset", "Global Eco-Certification Knowledge Base"), ("schema_version", schema["version"]),
    ("research_cutoff", schema["research_cutoff"]), ("built_at_utc", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())),
    ("counts", json.dumps(counts))])
con.commit()
con.execute("INSERT INTO search(search) VALUES('optimize')")
con.commit()
con.close()
print(json.dumps({"database": str(db_path), "bytes": db_path.stat().st_size, "counts": counts}, indent=1))