-
Notifications
You must be signed in to change notification settings - Fork 7
/
thinkcell.py
303 lines (249 loc) 路 9.83 KB
/
thinkcell.py
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import json
import warnings
from datetime import datetime
from pprint import pprint
class DataFrameError(Exception):
pass
class Thinkcell(object):
"""The Thinkcell object base class.
Attributes
----------
charts : list
A list of that contains a dictionnary for every template added. That dictionnary
contains two objects, `template` and `data`.
The `data` object contains itself two keys: `name` (the name of the chart) and
`table` (the actual data).
"""
def __init__(self):
"""Initializes the Thinkcell object. Takes no arguments.
"""
self.charts = []
def __str__(self):
"""Prints the data inside of the Thinkcell object.
"""
return str(self.charts)
@staticmethod
def verify_template(template_name):
"""Function that verifies the validity of a template.
Parameters
----------
template_name : str
The name of the template file to be added.
Returns
-------
template_name: str
Returns the name of the template if exceptions are not raised.
Raises
------
TypeError
Raises if template name is not a string or does not end in ".pptx".
"""
if not isinstance(template_name, str):
raise TypeError(f"'{template_name}' is not a valid template file.")
if not template_name.endswith(".pptx"):
raise TypeError(
f"'{template_name}' is not a valid Powerpoint file."
)
else:
return template_name
@staticmethod
def transform_input(data_element, color=None):
"""Transforms a `data element` into an object like {"type": data element}.
Parameters
----------
data_element : str, int, float, datetime
A data element can be a string, int, float or datetime.
color : str
The hex or rgb string for the element color. If None, then
no fill will be included.
Returns
-------
dict
Returns an object of type {"type": input}
Raises
------
ValueError
Raises if object is not of type int, float, str, or datetime.
Examples
--------
For a float or int, the dict will have "number" as key.
>>> print(Thinkcell.transform_input(5))
{"number": 5}
For a str input, the dict will have a "string" as key.
>>> print(Thinkcell.transform_input("test"))
{"string": "test"}
"""
fill = {}
if color is not None:
fill = {"fill": color}
if isinstance(data_element, datetime):
return {"date": data_element.strftime("%Y-%m-%d"), **fill}
if isinstance(data_element, str):
return {"string": data_element, **fill}
if isinstance(data_element, (int, float)):
return {"number": data_element, **fill}
else:
raise ValueError(
f"{data_element} of type {type(data_element)} is not acceptable."
)
def add_template(self, template_name):
"""Adds a template to the Thinkcell object.
Parameters
----------
template_name : str
The name of the template to be added.
"""
self.verify_template(template_name)
self.charts.append({"template": template_name, "data": []})
def add_chart(
self, template_name, chart_name, categories, data, fill=None
):
"""Adds a chart to the template object.
Parameters
----------
template_name : str
The name of the template where the chart will be added
chart_name : str
The name of the chart in the specified template
categories : list
A list containing the header of the chart. Headers can
be categories, years, companies, etc.
data : list
A list of lists. Each list contains the row of data to be added. Be
aware that the first element of each of these lists should be a
category as well.
fill : list
A list containing strings of either the hex or rgb values for fill
for each series. Must match the length of the series. Can specify None
to use no fill.
Raises
------
ValueError
If template does not exist, if the length of the categories does not
make sense reltively to the header data.
"""
available_templates = [page["template"] for page in self.charts]
if template_name not in available_templates:
raise ValueError(
f"{template_name} does not exist, please create one first."
)
if not isinstance(chart_name, str):
warnings.warn(
f"Your chart name is not a string, we will convert it into one. But wanted to make sure you were aware.",
UserWarning,
)
for data_list in data:
if len(data_list) != len(categories) + 1:
raise ValueError(
f"Your categories should be the equal to the length of your data lists - 1. Your data element {data_list} is of size {len(data_list)} but should be of size {len(categories) + 1}."
)
if fill is not None and len(fill) != len(data):
raise ValueError(
f"Your fill colors should be the equal to the length of your data (the number of series). Your fill element {fill} is of size {len(fill)} but should be of size {len(data)}."
)
if fill is None:
fill = [None for _ in data]
chart_dict = {}
chart_dict["name"] = str(chart_name)
chart_categories = [None] + [
self.transform_input(element) for element in categories
]
chart_dict["table"] = [chart_categories, []]
for data_list, color in zip(data, fill):
chart_dict["table"].append(
[self.transform_input(el, color) for el in data_list]
)
if self.charts[-1]["template"] == template_name:
self.charts[-1]["data"].append(chart_dict)
def add_chart_from_dataframe(
self, template_name, chart_name, dataframe, fill=None
):
"""Adds a chart based on a dataframe to the template object.
Parameters
----------
template_name : str
The name of the template where the chart will be added
chart_name : str
The name of the chart in the specified template
dataframe : pandas.DataFrame
A dictionary of Pandas dataframes
fill : list
A list of strings the length of the number of series for specifying
the fill colors with the hex or rgb
Raises
------
DataFrameError
If an invalid or empty DataFrame is passed
"""
try:
categories = dataframe.columns.to_list()[1:]
assert isinstance(categories, list)
data = dataframe.values.tolist()
assert isinstance(data, list)
except (AttributeError, AssertionError):
raise DataFrameError("You did not pass a valid Pandas DataFrame")
try:
assert len(categories) >= 1
assert len(data)
except AssertionError:
raise DataFrameError(
"The DataFrame you passed does not contain data"
)
self.add_chart(template_name, chart_name, categories, data, fill=fill)
def add_textfield(self, template_name, field_name, text):
"""Adds a text field to the template object.
Parameters
----------
template_name : str
The name of the template where the text field will be added
field_name : str
The name of the text field in the specified template
text : str
A string containing the text
Raises
------
ValueError
If template does not exist
"""
available_templates = [page["template"] for page in self.charts]
if template_name not in available_templates:
raise ValueError(
f"{template_name} does not exist, please create one first."
)
if not isinstance(field_name, str):
warnings.warn(
f"Your field name is not a string, we will convert it into one. But wanted to make sure you were aware.",
UserWarning,
)
field_dict = {}
field_dict["name"] = str(field_name)
field_text = [self.transform_input(text)]
field_dict["table"] = [field_text]
if self.charts[-1]["template"] == template_name:
self.charts[-1]["data"].append(field_dict)
def save_ppttc(self, filename):
"""Saves the Thinkcell object as a `.ppttc` file.
Parameters
----------
filename : str
The name of the file to be saved.
Raises
------
ValueError
If the filename specified is not a string or does
not end in `.ppttc`.
"""
if not isinstance(filename, str):
raise ValueError(f"A filename is normally a string, yours is not.")
if not filename.endswith(".ppttc"):
raise ValueError(
f"You want to save your file as a '.ppttc' file, not a '{filename}'. Visit https://www.think-cell.com/en/support/manual/jsondataautomation.shtml for more information."
)
if not self.charts:
raise ValueError(
f"Please add data before saving to a template file by using 'add_template' and then 'add_chart'."
)
else:
with open(filename, "w") as outfile:
json.dump(self.charts, outfile)
return True