Spaces:
Running on Zero
Running on Zero
File size: 7,311 Bytes
a805048 | 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 | """
Regenerates the complete SYNTHETIC dataset for EvidenceGuard AI:
1. sample_data/*.pdf - 16 fictional university documents (real PDFs)
2. sample_data/corpus_manifest.json - metadata for every document
3. evaluation_data/questions.json - 100 evaluation questions with evidence pages
4. evaluation_data/questions.csv - same, flattened
Every evidence phrase is located in the extracted PDF text; the script fails loudly if
any phrase cannot be found, so the questions are guaranteed to be derived from the PDFs.
Usage: python scripts/generate_dataset.py
"""
from __future__ import annotations
import csv
import json
import sys
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts"))
from reportlab.lib import colors # noqa: E402
from reportlab.lib.enums import TA_CENTER # noqa: E402
from reportlab.lib.pagesizes import A4 # noqa: E402
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet # noqa: E402
from reportlab.lib.units import cm # noqa: E402
from reportlab.platypus import (PageBreak, Paragraph, SimpleDocTemplate, # noqa: E402
Spacer, Table, TableStyle)
from corpus_content import DOCUMENTS, UNIVERSITY # noqa: E402
from questions_spec import Q # noqa: E402
from src.text_utils import normalize # noqa: E402
SAMPLE = ROOT / "sample_data"
EVAL = ROOT / "evaluation_data"
BANNER = "SYNTHETIC DEMONSTRATION DATA - fictional university, not a real policy"
def _styles():
ss = getSampleStyleSheet()
return {
"title": ParagraphStyle("t", parent=ss["Title"], fontSize=16, leading=20, spaceAfter=6),
"sub": ParagraphStyle("s", parent=ss["Normal"], fontSize=9.5, alignment=TA_CENTER,
textColor=colors.HexColor("#444444")),
"h": ParagraphStyle("h", parent=ss["Heading2"], fontSize=12, spaceBefore=10, spaceAfter=4),
"p": ParagraphStyle("p", parent=ss["Normal"], fontSize=10.5, leading=14.5, spaceAfter=6),
}
def render_pdf(doc: dict, path: Path) -> None:
st = _styles()
total_pages = len(doc["pages"])
def on_page(canvas, d):
canvas.saveState()
canvas.setFillColor(colors.HexColor("#B00020"))
canvas.setFont("Helvetica-Bold", 8.5)
canvas.drawCentredString(A4[0] / 2, A4[1] - 1.1 * cm, BANNER)
canvas.setFillColor(colors.HexColor("#555555"))
canvas.setFont("Helvetica", 8.5)
canvas.drawString(2 * cm, 1.2 * cm, f"{doc['doc_no']} | {doc['title']}")
canvas.drawRightString(A4[0] - 2 * cm, 1.2 * cm, f"Page {d.page} of {total_pages}")
canvas.restoreState()
flow = [
Paragraph(UNIVERSITY + " (fictional)", st["sub"]),
Paragraph(doc["title"], st["title"]),
]
meta = Table(
[["Document No.", doc["doc_no"], "Version", doc["version"]],
["Issued", doc["issued"], "Effective from", doc["effective"]]],
colWidths=[3.0 * cm, 5.2 * cm, 3.0 * cm, 5.0 * cm],
)
meta.setStyle(TableStyle([
("FONT", (0, 0), (-1, -1), "Helvetica", 9),
("FONT", (0, 0), (0, -1), "Helvetica-Bold", 9),
("FONT", (2, 0), (2, -1), "Helvetica-Bold", 9),
("GRID", (0, 0), (-1, -1), 0.4, colors.grey),
("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#F4F6F8")),
]))
flow += [meta, Spacer(1, 8)]
for pi, page in enumerate(doc["pages"]):
if pi > 0:
flow.append(PageBreak())
for heading, paras in page:
flow.append(Paragraph(heading, st["h"]))
for para in paras:
flow.append(Paragraph(para, st["p"]))
SimpleDocTemplate(str(path), pagesize=A4, topMargin=2 * cm, bottomMargin=2 * cm,
leftMargin=2 * cm, rightMargin=2 * cm, title=doc["title"],
author="EvidenceGuard AI synthetic data generator",
subject=BANNER).build(flow, onFirstPage=on_page, onLaterPages=on_page)
def extract_pages(path: Path) -> list[str]:
import pymupdf
with pymupdf.open(str(path)) as pdf:
return [p.get_text() for p in pdf]
def main() -> None:
SAMPLE.mkdir(exist_ok=True)
EVAL.mkdir(exist_ok=True)
manifest, page_text = [], {}
for doc in DOCUMENTS:
path = SAMPLE / doc["filename"]
render_pdf(doc, path)
pages = extract_pages(path)
assert len(pages) == len(doc["pages"]), f"{doc['id']}: expected {len(doc['pages'])} pages, got {len(pages)}"
page_text[doc["id"]] = [normalize(p) for p in pages]
manifest.append({k: doc[k] for k in ("id", "filename", "title", "doc_no", "issued",
"effective", "version", "topic")} | {"pages": len(pages)})
(SAMPLE / "corpus_manifest.json").write_text(json.dumps(manifest, indent=2))
by_id = {d["id"]: d for d in DOCUMENTS}
rows = []
for q in Q:
ev = []
for doc_id, phrase in q["evidence"]:
pages = [i + 1 for i, t in enumerate(page_text[doc_id]) if normalize(phrase) in t]
if not pages:
raise SystemExit(f"[{q['id']}] evidence phrase not found in {doc_id}: {phrase!r}")
ev.append({"doc_id": doc_id, "document": by_id[doc_id]["filename"],
"title": by_id[doc_id]["title"], "page": pages[0], "phrase": phrase})
for kw in q["keywords"]: # every key fact must exist in its evidence
alts = [normalize(a).strip() for a in kw.split("|")]
if ev and not any(any(a in page_text[e["doc_id"]][e["page"] - 1] for a in alts) for e in ev):
raise SystemExit(f"[{q['id']}] keyword {kw!r} not present in its evidence pages")
rows.append({
"id": q["id"], "category": q["category"], "question": q["question"],
"expected_answer": q["expected_answer"], "answer_keywords": q["keywords"],
"evidence": ev,
"supporting_document": "; ".join(sorted({e["document"] for e in ev})) or "NONE",
"supporting_page": "; ".join(f"{e['doc_id']} p.{e['page']}" for e in ev) or "NONE",
"expected_evidence_status": q["status"], "expected_behaviour": q["behaviour"],
})
(EVAL / "questions.json").write_text(json.dumps(rows, indent=2))
with open(EVAL / "questions.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["id", "category", "question", "expected_answer", "answer_keywords",
"supporting_document", "supporting_page",
"expected_evidence_status", "expected_behaviour"])
w.writeheader()
for r in rows:
w.writerow({k: ("; ".join(r[k]) if k == "answer_keywords" else r[k]) for k in w.fieldnames})
print(f"Generated {len(manifest)} PDFs ({sum(m['pages'] for m in manifest)} pages) in {SAMPLE}")
print(f"Generated {len(rows)} questions:", dict(Counter(r["category"] for r in rows)))
if __name__ == "__main__":
main()
|