File size: 2,016 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Direct PlotQA observation comparisons, without digest validation.

These are the production drawing primitives. They are not an independent
renderer; independence applies to the two semantic executors only.
"""

from __future__ import annotations

import copy
import io
from pathlib import Path

_FONT_READY = False


def pixels(blob):
    import numpy as np
    from PIL import Image

    return np.asarray(Image.open(io.BytesIO(blob)).convert("RGBA"))


def render_direct(world, manifest):
    global _FONT_READY
    import matplotlib

    matplotlib.use("Agg")
    from matplotlib import font_manager

    from explicit_learning.renderers import plot

    if not _FONT_READY:
        root = Path(matplotlib.get_data_path()) / "fonts" / "ttf"
        for name in ("DejaVuSans.ttf", "DejaVuSerif.ttf"):
            font_manager.fontManager.addfont(root / name)
        _FONT_READY = True
    family = plot.PLOT_FAMILIES[manifest["renderer_id"]]
    series = plot._parse_series(world)
    domain = plot._build_domain(world, series)
    canvas = plot._Canvas(manifest["width"], manifest["height"], family)
    visible = plot._draw_plot(canvas, world, series, domain, family)
    image, owners, counts = canvas.finish()
    glyphs = [
        {"node_id": g.node_id, "text": g.text, "bbox": [g.x0, g.y0, g.x1, g.y1]}
        for g in sorted(canvas.glyphs, key=lambda x: (x.node_id, x.text, x.x0, x.y0))
    ]
    return {
        "image": image,
        "owners": owners,
        "glyphs": glyphs,
        "node_table": ["__background__", *canvas.owner_ids],
        "coverage": {n: counts.get(n, 0) for n in sorted(visible)},
        "domain": domain.manifest_record(),
    }


def visible_projection(world):
    world = copy.deepcopy(world)
    hidden = {n for n, flag in world.get("_node_visibility", {}).items() if flag == "hidden"}
    for series in world.get("series", []):
        for point in series.get("points", []):
            if point["id"] in hidden:
                point["y"] = None
    return world