-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path__init__.py
More file actions
244 lines (198 loc) · 6.54 KB
/
__init__.py
File metadata and controls
244 lines (198 loc) · 6.54 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
"""Support for animated stickers"""
from __future__ import annotations
import gzip
import json
import os
from math import ceil
from pathlib import Path
from shutil import rmtree
from install_playwright import install
from PIL import Image
from playwright.sync_api import sync_playwright
THISDIR = str(Path(__file__).resolve().parent)
def convertLottie2ALL(fileName: str, newFileName: str, quality: int = 1):
"""Convert to gif and webp
Args:
----
fileName (str): file path of the lottie file
newFileName (str): name of the file to write (omit file ext)
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
convertMultLottie2ALL([fileName], [newFileName], quality)
def convertLottie2GIF(fileName: str, newFileName: str, quality: int = 1):
"""Convert to gif
Args:
----
fileName (str): file path of the lottie file
newFileName (str): name of the file to write
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
convertMultLottie2GIF([fileName], [newFileName], quality)
def convertLottie2Webp(fileName: str, newFileName: str, quality: int = 1):
"""Convert to webp
Args:
----
fileName (str): file path of the lottie file
newFileName (str): name of the file to write
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
convertMultLottie2Webp([fileName], [newFileName], quality)
def convertMultLottie2ALL(fileNames: list[str], newFileNames: list[str], quality: int = 1):
"""Convert to gif and webp
Args:
----
fileNames (list[str]): list of file path to the lottie files
newFileNames (list[str]): name of the files to write (omit file ext)
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
imageDataList = convertLotties2PIL(fileNames, quality)
for index, imageData in enumerate(imageDataList):
images = imageData[0]
duration = imageData[1]
images[0].save(
newFileNames[index] + ".gif",
append_images=images[1:],
duration=duration * 1000 / len(images),
version="GIF89a",
transparency=0,
disposal=2,
save_all=True,
loop=0,
)
images[0].save(
newFileNames[index] + ".webp",
save_all=True,
append_images=images[1:],
duration=int(duration * 1000 / len(images)),
loop=0,
)
rmtree("temp", ignore_errors=True)
def convertMultLottie2GIF(fileNames: list[str], newFileNames: list[str], quality: int = 1):
"""Convert to gif
Args:
----
fileNames (list[str]): list of file path to the lottie files
newFileNames (list[str]): name of the files to write
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
imageDataList = convertLotties2PIL(fileNames, quality)
for index, imageData in enumerate(imageDataList):
images = imageData[0]
duration = imageData[1]
images[0].save(
newFileNames[index],
save_all=True,
append_images=images[1:],
duration=duration * 1000 / len(images),
loop=0,
transparency=0,
disposal=2,
)
rmtree("temp", ignore_errors=True)
def convertMultLottie2Webp(fileNames: list[str], newFileNames: list[str], quality: int = 1):
"""Convert to webp
Args:
----
fileNames (list[str]): list of file path to the lottie files
newFileNames (list[str]): name of the files to write
quality (int, optional): Quality of the returned sequence. Defaults to 1.
"""
imageDataList = convertLotties2PIL(fileNames, quality)
for index, imageData in enumerate(imageDataList):
images = imageData[0]
duration = imageData[1]
images[0].save(
newFileNames[index],
save_all=True,
append_images=images[1:],
duration=int(duration * 1000 / len(images)),
loop=0,
)
rmtree("temp", ignore_errors=True)
def _resQuality(quality: int, numFrames: int, duration: int):
qualityMap = [10, 15, 20, 30]
if quality >= len(qualityMap) or quality < 0:
return 2
return ceil((numFrames / duration) / qualityMap[quality])
def convertLotties2PIL(
fileNames: list[str], quality: int = 1
) -> list[tuple[list[Image.Image], float]]:
"""Convert list of lottie files to a list of images with a duration.
Args:
----
fileNames (list[str]): list of file paths of the lottie files
quality (int, optional): Quality of the returned sequence. Defaults to 1.
Returns:
-------
list[tuple[list[Image], float]]: pil images to write to gif/ webp and duration
"""
lotties = []
for fileName in fileNames:
with open(fileName, "rb") as binfile:
magicNumber = binfile.read(2)
binfile.seek(0)
if magicNumber == b"\x1f\x8b": # gzip magic number
try:
archive = gzip.open(fileName, "rb")
lottie = json.load(archive)
except gzip.BadGzipFile:
continue
else:
lottie = json.loads(Path(fileName).read_text(encoding="utf-8"))
lotties.append(lottie)
frameData = recordLotties([json.dumps(lottie) for lottie in lotties], quality)
imageDataList = []
for index, frameDataInstance in enumerate(frameData):
images = []
duration = frameDataInstance[0]
numFrames = frameDataInstance[1]
step = frameDataInstance[2]
for frame in range(0, numFrames, step):
images.append(Image.open(f"temp/temp{index}_{frame}.png"))
imageDataList.append([images, duration])
return imageDataList
def recordLotties(lottieData: list[str], quality: int) -> list[list[int]]:
"""Record the lottie data to a set of images
Args:
----
lottieData (str): lottie data as string
quality (int, optional): Quality of the returned sequence.
Returns:
-------
list[list[int]]: duration and number of frames
"""
# Make temp dir
if os.path.isdir("temp"):
pass
else:
os.mkdir("temp")
with sync_playwright() as p:
install(p.chromium)
browser = p.chromium.launch()
frameData = [
recordSingleLottie(browser, lottieDataInstance, quality, index)
for index, lottieDataInstance in enumerate(lottieData)
]
browser.close()
return frameData
def recordSingleLottie(browser, lottieDataInstance, quality, index) -> list[int]:
page = browser.new_page()
lottie = json.loads(lottieDataInstance)
html = (
Path(THISDIR + "/lottie.html")
.read_text(encoding="utf-8")
.replace("lottieData", lottieDataInstance)
.replace("WIDTH", str(lottie["w"]))
.replace("HEIGHT", str(lottie["h"]))
)
page.set_content(html)
duration = page.evaluate("() => duration")
numFrames = page.evaluate("() => numFrames")
rootHandle = page.main_frame.wait_for_selector("#root")
# Take a screenshot of each frame
step = _resQuality(quality, numFrames, duration)
for frame in range(0, numFrames, step):
rootHandle.screenshot(path=f"temp/temp{index}_{frame}.png", omit_background=True)
page.evaluate(f"animation.goToAndStop({frame + 1}, true)")
page.close()
return [duration, numFrames, step]