-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslide.py
More file actions
405 lines (304 loc) · 13.2 KB
/
slide.py
File metadata and controls
405 lines (304 loc) · 13.2 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import os
import simplify
import io
import simplify
import matplotlib.colors
from PIL import Image, ImageDraw, ImageFont
from pptx.util import Inches, Length
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
def split_sentence(sentence, times):
"""Splits the sentence in ``times`` parts"""
idxs = [int((i+1) * (len(sentence) / times)) for i in range(times-1)]
spc_idxs = [0]
for i, char in enumerate(sentence):
if char == " ":
spc_idxs.append(i)
spc_idxs.append(None)
splited = []
if len(spc_idxs) - 2 < times:
raise Exception(
"\"times\" must be less or equal the number of blank spaces!")
elif len(spc_idxs) - 2 == times:
for i, idx in enumerate(spc_idxs):
if idx == None:
break
next = spc_idxs[i+1]
splited.append(sentence[idx:next])
else:
difference = 100
closest_idx = 0
idxs_mapping = [0]
spc_idxs[-1] = len(spc_idxs)
for i, idx in enumerate(idxs):
for j, spc_idx in enumerate(spc_idxs):
if abs(spc_idx - idx) < difference:
difference = abs(spc_idx - idx)
closest_idx = spc_idx
idxs_mapping.append(closest_idx)
spc_idxs.remove(closest_idx)
difference = 100
idxs_mapping = sorted(idxs_mapping)
idxs_mapping.append(None)
for i, idx in enumerate(idxs_mapping):
if idx == None:
break
next = idxs_mapping[i+1]
splited.append(sentence[idx:next])
return [i.strip() for i in splited]
class Px(Length):
"""
Convenience value class for specifying a length in pixels
"""
def __new__(cls, px):
return Inches(px / 100)
class Colors(object):
"""
Its attributes are color names and their values are rgb tuples
"""
def __init__(self):
for name, hex in matplotlib.colors.cnames.items():
color = tuple([int(i * 255)
for i in matplotlib.colors.to_rgb(hex)])
setattr(self, name, color)
class Positions(object):
"""
Maps all possible positions
"""
def __init__(self, width, height, w, h, shadow=False):
self.width = width
self.height = height
self.w = w
self.h = h
self.shadow = shadow
self.border = 80
self.extra = 5
self.update()
def update(self):
top = self.border - self.extra * self.shadow
bottom = self.height - self.border - self.h - self.extra * self.shadow
h_center = int((self.height - self.h) / 2 - self.extra * self.shadow)
w_center = int((self.width - self.w) / 2) - self.extra * self.shadow
right = self.width - self.w - self.border * \
(self.width / self.height) - self.extra * self.shadow
left = self.border * (self.width / self.height) - \
self.extra * self.shadow
self.middle = (w_center, h_center)
self.center_left = (left, h_center)
self.center_right = (right, h_center)
self.bottom_left = (left, bottom)
self.bottom_right = (right, bottom)
self.bottom_center = (w_center, bottom)
self.top_left = (left, top)
self.top_right = (right, top)
self.top_center = (w_center, top)
@staticmethod
def get_font_size(text, font_type):
if "\n" in text:
greater = 0
h = 0
for sentence in text.split("\n"):
size = font_type.getsize(sentence)
w = size[0]
greater = w if w > greater else greater
# h += font_type.getsize("A")[1]
h += font_type.getsize(sentence)[1]
w = greater
else:
w, h = font_type.getsize(text)
return w, h
@staticmethod
def check_alignment(font_name):
translate_alignment = {
'middle': 'center',
'center_left': 'left',
'center_right': 'right',
'bottom_left': 'left',
'bottom_right': 'right',
'bottom_center': 'center',
'top_left': 'left',
'top_right': 'right',
'top_center': 'center',
}
if font_name in translate_alignment:
return translate_alignment[font_name]
else:
raise Exception("Invalid position!")
class FontType(object):
def __init__(self, family_font, size, text_format=None):
self._family_font = family_font
self._size = size
self._text_format = text_format
def get_path(self):
return simplify.get_font_path(self._family_font, self._text_format)
def get_size(self):
return self._size
def get_family(self):
return self._family_font
def get_text_format(self):
return self._text_format
def set_size(self, size):
self._size = size
def set_family(self, family):
self._family_font = family
def set_text_format(self, text_format):
self._text_format = text_format
class Slide(object):
def __init__(self, image):
self.width = 1920
self.height = 1080
self.image = image
self.font_type = FontType("Ubuntu", 40)
self.shadow = False
self.color = getattr(Colors(), "white")
self.stacks = 2 # Number of sentences per slide
self.directory = "../slides/Slides"
self.border = 20
self.extra = 5 # Shadow distance
self.position = "middle"
self.prs = None
def adapt_size(self, lyrics, limit):
"""
Returns a new list with the verses that are larger then the limit splited
"""
new = []
for i, estrofe in enumerate(lyrics):
new.append([])
for j, verso in enumerate(estrofe):
font_type = ImageFont.truetype(
self.font_type.get_path(), self.font_type.get_size())
text_width = Positions.get_font_size(verso, font_type)[0]
if text_width > limit:
split_times = text_width // limit
for subverso in split_sentence(verso, split_times):
new[i].append(subverso)
else:
new[i].append(verso)
return new
def create_imageshow(self, lyrics):
"""
Creates an image show
"""
image = simplify.assign_image(self.image)
os.mkdir(self.directory)
font_type = ImageFont.truetype(
self.font_type.get_path(), self.font_type.get_size())
normal_positions = None
shadow_positions = None
LIMIT = self.width - self.border * 2
count = 1
for estrofe in self.adapt_size(lyrics, LIMIT):
for i in range(0, len(estrofe), self.stacks):
if i < len(estrofe) - (self.stacks - 1):
text = "\n".join([estrofe[j].split()[0].capitalize()
+ " " + " ".join(estrofe[j].split()[1:]) for j in range(i, i+self.stacks)])
else:
last = len(estrofe)
text = "\n".join([estrofe[j].split()[0].capitalize()
+ " " + " ".join(estrofe[j].split()[1:]) for j in range(i, last)])
w, h = Positions.get_font_size(text, font_type)
if not normal_positions or not shadow_positions:
normal_positions = Positions(self.width, self.height, w, h)
shadow_positions = Positions(
self.width, self.height, w, h, shadow=True)
else:
normal_positions.w, normal_positions.h = w, h
shadow_positions.w, shadow_positions.h = w, h
normal_positions.extra = self.extra
normal_positions.border = self.border
shadow_positions.extra = self.extra
shadow_positions.border = self.border
normal_positions.update()
shadow_positions.update()
normal_position = getattr(normal_positions, self.position)
shadow_position = getattr(shadow_positions, self.position)
image = simplify.assign_image(self.image)
if self.shadow:
image = image.copy()
draw = ImageDraw.Draw(image)
draw.text(xy=shadow_position, text=text, fill=getattr(Colors(), "black"),
font=font_type, align=Positions.check_alignment(self.position))
image = image.copy()
draw = ImageDraw.Draw(image)
draw.text(xy=normal_position, text=text, fill=self.color,
font=font_type, align=Positions.check_alignment(self.position))
image.save(f"{self.directory}/{count}.png")
count += 1
def create_pwp(self, text):
"""
Creates a pptx presentation based on the music lyrics
"""
font_type = ImageFont.truetype(
self.font_type.get_path(), self.font_type.get_size())
layout = self.prs.slide_layouts[6]
slide = self.prs.slides.add_slide(layout)
if type(self.image) is str:
slide.shapes.add_picture(self.image, 0, 0, height=Px(self.height))
else:
slide.shapes.add_picture(io.BytesIO(
self.image), 0, 0, height=Px(self.height))
alignment = Positions.check_alignment(self.position)
if "_" in self.position:
h_alignment = self.position.split(
"_")[0].replace("center", "middle").upper()
else:
h_alignment = self.position.upper()
if self.shadow:
txBox = slide.shapes.add_textbox(Px(-self.extra), Px(-self.extra),
Px(self.width), Px(self.height))
tf = txBox.text_frame
tf.vertical_anchor = getattr(MSO_ANCHOR, h_alignment)
if len(self.position.split("_")) > 1 and self.position.split("_")[1] == "left":
tf.margin_left = Px(self.border)
elif len(self.position.split("_")) > 1 and self.position.split("_")[1] == "right":
tf.margin_right = Px(self.border)
if len(self.position.split("_")) > 1 and self.position.split("_")[0] == "top":
tf.margin_top = Px(self.border)
elif len(self.position.split("_")) > 1 and self.position.split("_")[0] == "bottom":
tf.margin_bottom = Px(self.border)
tf.word_wrap = True
p = tf.paragraphs[0]
p.text = text
p.alignment = getattr(PP_ALIGN, alignment.upper())
font = p.font
font.name = self.font_type.get_family()
font.size = Px(self.font_type.get_size())
font.color.rgb = RGBColor(*getattr(Colors(), "black"))
font.bold = True if self.font_type.get_text_format() == "bold" else False
font.italic = True if self.font_type.get_text_format() == "italic" else False
txBox = slide.shapes.add_textbox(0, 0, Px(self.width), Px(self.height))
tf = txBox.text_frame
tf.vertical_anchor = getattr(MSO_ANCHOR, h_alignment)
if len(self.position.split("_")) > 1 and self.position.split("_")[1] == "left":
tf.margin_left = Px(self.border)
elif len(self.position.split("_")) > 1 and self.position.split("_")[1] == "right":
tf.margin_right = Px(self.border)
if len(self.position.split("_")) > 1 and self.position.split("_")[0] == "top":
tf.margin_top = Px(self.border)
elif len(self.position.split("_")) > 1 and self.position.split("_")[0] == "bottom":
tf.margin_bottom = Px(self.border)
tf.word_wrap = True
p = tf.paragraphs[0]
p.text = text
p.alignment = getattr(PP_ALIGN, alignment.upper())
font = p.font
font.name = self.font_type.get_family()
font.size = Px(self.font_type.get_size())
font.color.rgb = RGBColor(*self.color)
font.bold = True if self.font_type.get_text_format() == "bold" else False
font.italic = True if self.font_type.get_text_format() == "italic" else False
def create_slideshow(self, lyrics, font_format=[]):
self.prs.slide_width = Px(self.width)
self.prs.slide_height = Px(self.height)
LIMIT = self.width - self.border * 2
for i, estrofe in enumerate(self.adapt_size(lyrics, LIMIT)):
for i in range(0, len(estrofe), self.stacks):
if i < len(estrofe) - (self.stacks - 1):
text = "\n".join([estrofe[j].split()[0].capitalize()
+ " " + " ".join(estrofe[j].split()[1:]) for j in range(i, i+self.stacks)])
else:
last = len(estrofe)
text = "\n".join([estrofe[j].split()[0].capitalize()
+ " " + " ".join(estrofe[j].split()[1:]) for j in range(i, last)])
# font_type = ImageFont.truetype(self.font_type.get_path(), self.font_type.get_size())
self.create_pwp(text)