Debian Codegraph @

pbcommand/pb_io/report.py

raw symbols SCIP
1 """
2 Loading a report from JSON
3
4 This manual marshalling/de-marshalling is not awesome.
5 """
6
7 import json
8 import logging
9 import uuid as U
10
11 from pbcommand.models.report import (Report, Plot, PlotGroup, Attribute,
12 Table, Column, ReportSpec, PlotlyPlot)
13 from pbcommand.schemas import validate_report, validate_report_spec
14
15
16 log = logging.getLogger(__name__)
17
18 __all__ = [
19 "load_report_from_json",
20 "load_report_from",
21 "load_report_spec_from_json",
22 ]
23
24
25 def _to_id(s):
26 if '.' in s:
27 return s.split('.')[-1]
28 else:
29 return s
30
31
32 def _to_plot(d):
33 id_ = _to_id(d['id'])
34 caption = d.get('caption', None)
35 image = d['image']
36 thumbnail = d.get('thumbnail', None)
37 title = d.get('title', None)
38 plot_type = d.get("plotType", Plot.PLOT_TYPE)
39 plotly_version = d.get("plotlyVersion", None)
40 if plot_type == Plot.PLOT_TYPE:
41 return Plot(id_, image, caption=caption,
42 thumbnail=thumbnail, title=title)
43 elif plot_type == PlotlyPlot.PLOT_TYPE:
44 return PlotlyPlot(id_, image, caption=caption, thumbnail=thumbnail,
45 title=title, plotly_version=plotly_version)
46 else:
47 raise ValueError("Unrecognized plotType '{t}'".format(t=plot_type))
48
49
50 def _to_plot_group(d):
51 id_ = _to_id(d['id'])
52 legend = d.get('legend', None)
53 thumbnail = d.get('thumbnail', None)
54 # is this optional?
55 title = d.get('title', None)
56
57 if 'plots' in d:
58 plots = [_to_plot(pd) for pd in d['plots']]
59 else:
60 plots = []
61
62 return PlotGroup(id_, title=title, legend=legend, plots=plots,
63 thumbnail=thumbnail)
64
65
66 def _to_attribute(d):
67 id_ = _to_id(d['id'])
68 name = d.get('name', None)
69 # this can't be none
70 value = d['value']
71 return Attribute(id_, value, name=name)
72
73
74 def _to_column(d):
75 id_ = _to_id(d['id'])
76 header = d.get('header', None)
77 values = d.get('values', [])
78 return Column(id_, header=header, values=values)
79
80
81 def _to_table(d):
82 id_ = _to_id(d['id'])
83 title = d.get('title', None)
84
85 columns = []
86 for column_d in d.get('columns', []):
87 c = _to_column(column_d)
88 columns.append(c)
89
90 # assert that all the columns have the same number of values
91 nvalues = {len(c.values) for c in columns}
92 assert len(nvalues) == 1
93
94 return Table(id_, title=title, columns=columns)
95
96
97 def dict_to_report(dct):
98 # Use `load_report_from` instead.
99 # FIXME. Add support for different version schemas in a cleaner, more
100 # concrete manner.
101
102 report_id = dct['id']
103
104 # Make this optional for now
105 report_uuid = dct.get('uuid', str(U.uuid4()))
106
107 tags = dct.get('tags', [])
108
109 # Make sure the UUID is well formed
110 _ = U.UUID(report_uuid)
111
112 # Legacy Reports > 0.3.9 will not have the title key
113 title = dct.get('title', "Report {i}".format(i=report_id))
114
115 plot_groups = []
116 if 'plotGroups' in dct:
117 pg = dct['plotGroups']
118 if pg:
119 plot_groups = [_to_plot_group(d) for d in pg]
120
121 attributes = []
122 for r_attr in dct.get('attributes', []):
123 attr = _to_attribute(r_attr)
124 attributes.append(attr)
125
126 tables = []
127 for table_d in dct.get('tables', []):
128 t = _to_table(table_d)
129 tables.append(t)
130
131 report = Report(report_id,
132 title=title,
133 plotgroups=plot_groups,
134 tables=tables,
135 attributes=attributes,
136 dataset_uuids=dct.get('dataset_uuids', ()),
137 uuid=report_uuid, tags=tags)
138
139 return report
140
141
142 def __load_json_or_dict(processor_func):
143 def wrapper(json_path_or_dict):
144 if isinstance(json_path_or_dict, dict):
145 return processor_func(json_path_or_dict)
146 else:
147 with open(json_path_or_dict, 'r') as f:
148 d = json.loads(f.read())
149 return processor_func(d)
150 return wrapper
151
152
153 def load_report_from(json_path_or_dict):
154 """
155 Load a Report from a raw dict or path to JSON file
156
157 :param json_path_or_dict:
158 :type json_path_or_dict: dict | str
159 :return:
160 """
161 return __load_json_or_dict(dict_to_report)(json_path_or_dict)
162
163
164 def load_report_from_json(json_file):
165 """Convert a report json file to Report instance."""
166 # This should go way in favor of `load_report_from`
167 return load_report_from(json_file)
168
169
170 def _to_report(nfiles, attribute_id, report_id):
171 # this should have version of the bax/bas files, chemistry
172 attributes = [Attribute(attribute_id, nfiles)]
173 return Report(report_id, attributes=attributes)
174
175
176 def fofn_to_report(nfofns):
177 return _to_report(nfofns, "nfofns", "fofn_report")
178
179
180 def load_report_spec_from_json(json_file, validate=True):
181 with open(json_file, 'r') as f:
182 d = json.loads(f.read())
183 if validate:
184 validate_report_spec(d)
185 return ReportSpec.from_dict(d)