File size: 6,007 Bytes
8a3fe26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render a stored bag run with the designed renderer - Word, and PDF when LibreOffice is present.

    python scripts/render_designed_bag.py tests/fixtures/bag_run_98f70313.json \
        --brand brand.json --auto-images --out var/designed

    --brand        brand settings JSON (family, colours, logo, author …; see design/brand.py).
                   Without it: --family / --palette / --primary / --secondary / --logo …
    --family all   one file per family, same brand otherwise.
    --image-specs  JSON {image_key: {"subject": …, "orientation": …}} merged onto the
                   content, as if the content JSON had carried it (design/images.py).
    --images       folder of content images named <image_key>.png|.jpg
    --auto-images  mark محاور for an image where the content does not say.

Next to each file: `<name>.report.json` (what is still missing, which fixed
images came from the library) and `<name>.image-requests.json` (the content
images to make, with their prompts).
"""

from __future__ import annotations

import argparse
import json
import shutil
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from app.agents.arabic_bag.context import using  # noqa: E402
from app.agents.arabic_bag.design import (  # noqa: E402
    FAMILIES,
    PALETTES,
    generate_designed_word,
    theme_from_brand,
)
from app.agents.arabic_bag.design.images import image_key  # noqa: E402


def soffice() -> str | None:
    for c in ("soffice", "libreoffice", r"C:\Program Files\LibreOffice\program\soffice.exe"):
        found = shutil.which(c) or (c if Path(c).exists() else None)
        if found:
            return found
    return None


def to_pdf(docx: Path) -> Path | None:
    exe = soffice()
    if not exe:
        return None
    subprocess.run([exe, "--headless", "--convert-to", "pdf", "--outdir", str(docx.parent), str(docx)],
                   check=True, capture_output=True, timeout=600)
    pdf = docx.with_suffix(".pdf")
    return pdf if pdf.exists() else None


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("fixture")
    ap.add_argument("--brand")
    ap.add_argument("--family", help=f"{sorted(FAMILIES)} or all (overrides the brand's)")
    ap.add_argument("--palette", help=str(sorted(PALETTES)))
    ap.add_argument("--primary")
    ap.add_argument("--secondary")
    ap.add_argument("--logo")
    ap.add_argument("--assets", help="folder of fixed images (see design/assets.py)")
    ap.add_argument("--author")
    ap.add_argument("--org")
    ap.add_argument("--font")
    ap.add_argument("--image-specs")
    ap.add_argument("--images", help="folder of content images named <image_key>.png")
    ap.add_argument("--auto-images", action="store_true")
    ap.add_argument("--no-placeholders", action="store_true")
    ap.add_argument("--out", default="var/designed")
    ap.add_argument("--no-pdf", action="store_true")
    args = ap.parse_args()

    data = json.loads(Path(args.fixture).read_text(encoding="utf-8"))
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)

    brand: dict = {}
    base_dir = None
    if args.brand:
        brand = json.loads(Path(args.brand).read_text(encoding="utf-8"))
        base_dir = str(Path(args.brand).parent)
    for key, val in (("palette", args.palette), ("primary", args.primary),
                     ("secondary", args.secondary), ("logo", args.logo),
                     ("assets_dir", args.assets), ("author", args.author),
                     ("org_name", args.org), ("font", args.font)):
        if val:
            brand[key] = str(Path(val).resolve()) if key in ("logo", "assets_dir") else val

    def stored(key):
        v = data.get(key) or {}
        return (v.get("value") if isinstance(v, dict) else v) or []

    specs = json.loads(Path(args.image_specs).read_text(encoding="utf-8")) if args.image_specs else {}
    files = {}
    if args.images:
        for p in Path(args.images).iterdir():
            if p.suffix.lower() in (".png", ".jpg", ".jpeg"):
                files[p.stem] = str(p)

    family_arg = args.family or brand.get("family") or "ribbon"
    families = sorted(FAMILIES) if family_arg == "all" else [family_arg]
    for family in families:
        theme = theme_from_brand({**brand, "family": family}, base_dir=base_dir)
        content = json.loads(json.dumps(stored("bag_ar.content")))
        for c in content:
            if image_key(c) in specs:
                c["image"] = {"wanted": True, **specs[image_key(c)]}
        path = out / f"bag_{family}.docx"
        with using(data["bag_ar.blueprint"]):
            _, report = generate_designed_word(
                str(path), theme=theme,
                preamble=data.get("bag_ar.preamble") or {}, intro=data.get("bag_ar.intro") or {},
                content=content, activities=json.loads(json.dumps(stored("bag_ar.activities"))),
                quizzes=stored("bag_ar.quiz"), references=stored("bag_ar.references"),
                images=files, auto_images=args.auto_images,
                placeholders=not args.no_placeholders,
            )
        requests = report.pop("image_requests")
        (out / f"bag_{family}.report.json").write_text(
            json.dumps({"theme": {"primary": theme.primary, "secondary": theme.secondary,
                                  "family": family}, **report}, ensure_ascii=False, indent=1),
            encoding="utf-8")
        (out / f"bag_{family}.image-requests.json").write_text(
            json.dumps(requests, ensure_ascii=False, indent=1), encoding="utf-8")
        pdf = None if args.no_pdf else to_pdf(path)
        print(f"{family}: {path}" + (f" + {pdf.name}" if pdf else "")
              + f" | colours #{theme.primary} #{theme.secondary}"
              + f" | {len(report['missing'])} missing, {len(report['library'])} from library,"
              + f" {len(requests)} content images to make")


if __name__ == "__main__":
    main()