-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgif2tgsticker.py
287 lines (202 loc) · 7.77 KB
/
gif2tgsticker.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
import os
from pathlib import Path
from pprint import pprint
import tkinter as tk
import tkinter.messagebox as tkm
import subprocess
import shutil
import ffmpeg
import tkinterdnd2 as tkd
DEFAULT_FPS = 30
DEFAULT_SMART_DURATION_LIMIT = '2.9'
DEFAULT_RESIZE_MODE = 'fit'
DEFAULT_SPEED_ADJUST_MODE = 'smart'
DEFAULT_FALLBACK_PTS = '1.0'
DEFAULT_CRF = -1
DEFAULT_APNG_DELAY = "-1"
def main():
if os.name == 'nt':
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(1)
check_executables = ['ffmpeg', 'ffprobe', 'magick']
missing_executables = []
for exe in check_executables:
if shutil.which(exe) is None:
missing_executables.append(exe)
if len(missing_executables) > 0:
exe = ', '.join(missing_executables)
msg = f'Cannot find {exe}.'
if 'magick' in missing_executables:
msg += "\nmagick is missing. ImageMagick is needed for WebP conversion. Other features work fine. Install if needed."
if 'ffmpeg' in missing_executables or 'ffprobe' in missing_executables:
msg += "\nffmpeg, ffprobe is required. Make sure it is installed correctly."
tkm.showwarning('Warning', msg)
root = create_app()
root.update_idletasks()
root.deiconify()
root.mainloop()
def create_app():
root = tkd.TkinterDnD.Tk()
root.withdraw()
root.title('gif2tgsticker')
root.grid_columnconfigure(0, minsize=600)
fps_var = tk.IntVar()
fps_var.set(DEFAULT_FPS)
speed_adjust_mode_var = tk.StringVar()
speed_adjust_mode_var.set(DEFAULT_SPEED_ADJUST_MODE)
smart_limit_duration_var = tk.StringVar()
smart_limit_duration_var.set(DEFAULT_SMART_DURATION_LIMIT)
fallback_pts_var = tk.StringVar()
fallback_pts_var.set(DEFAULT_FALLBACK_PTS)
resize_mode_var = tk.StringVar()
resize_mode_var.set(DEFAULT_RESIZE_MODE)
crf_var = tk.IntVar()
crf_var.set(DEFAULT_CRF)
apng_delay_var = tk.StringVar()
apng_delay_var.set(DEFAULT_APNG_DELAY)
option_box = tk.Frame(root)
option_box.grid(row=0, column=0)
width_var = tk.IntVar()
width_var.set(512)
height_var = tk.IntVar()
height_var.set(512)
row = 0
tk.Label(option_box, text="Resolution:")\
.grid(row=row, column=0)
group = tk.Frame(option_box)
group.grid(row=row, column=1)
tk.Entry(group, textvariable=width_var, width=10)\
.grid(row=0, column=0)
tk.Label(group, text="x")\
.grid(row=0, column=1)
tk.Entry(group, textvariable=height_var, width=10)\
.grid(row=0, column=2)
row += 1
tk.Label(option_box, text="FPS:")\
.grid(row=row, column=0)
tk.Entry(option_box, textvariable=fps_var)\
.grid(row=row, column=1)
row += 1
tk.Label(option_box, text="Resize mode:")\
.grid(row=row, column=0)
radio_box = tk.Frame(option_box)
radio_box.grid(row=row, column=1)
tk.Radiobutton(radio_box, text='Fit', value='fit', variable=resize_mode_var)\
.grid(row=0, column=0)
tk.Radiobutton(radio_box, text='Pad', value='pad', variable=resize_mode_var)\
.grid(row=0, column=1)
tk.Radiobutton(radio_box, text='Scale', value='scale', variable=resize_mode_var)\
.grid(row=0, column=2)
row += 1
tk.Label(option_box, text="Smart speed adjust duration limit\n(when video is longer than 3 seconds):")\
.grid(row=row, column=0)
tk.Entry(option_box, textvariable=smart_limit_duration_var)\
.grid(row=row, column=1)
row += 1
tk.Label(option_box, text="Smart speed adjust fallback PTS modifier\n(Used when unable to get duration from video)\n(0.5 = 2x speed):")\
.grid(row=row, column=0)
tk.Entry(option_box, textvariable=fallback_pts_var)\
.grid(row=row, column=1)
row += 1
tk.Label(option_box, text="CRF Value(0-51, higher means lower quality, -1=unset):")\
.grid(row=row, column=0)
tk.Entry(option_box, textvariable=crf_var)\
.grid(row=row, column=1)
row += 1
tk.Label(option_box, text="WebP to APNG delay(lower means faster playback, -1=unset):")\
.grid(row=row, column=0)
tk.Entry(option_box, textvariable=apng_delay_var)\
.grid(row=row, column=1)
row += 1
tk.Label(root, text='Drag and drop files below:')\
.grid(row=row, column=0, padx=10, pady=5)
row += 1
listbox = tk.Listbox(root, width=1, height=20)
listbox.grid(row=row, column=0, padx=5, pady=5, sticky='news')
row += 1
def drop(event):
if event.data:
print('Dropped data:\n', event.data)
if event.widget == listbox:
# event.data is a list of filenames as one string;
# if one of these filenames contains whitespace characters
# it is rather difficult to reliably tell where one filename
# ends and the next begins; the best bet appears to be
# to count on tkdnd's and tkinter's internal magic to handle
# such cases correctly; the following seems to work well
# at least with Windows and Gtk/X11
files = listbox.tk.splitlist(event.data)
for f in files:
if os.path.exists(f):
process_file(f)
print('Dropped file: "%s"' % f)
else:
print('Not dropping file "%s": file does not exist.' % f)
return event.action
def convert_webp_to_apng(filepath: str):
print("Converting WebP to APNG...")
p = Path(filepath)
output_path = p.with_suffix(".png")
subprocess.run(["magick",
*([] if apng_delay_var.get() == "-1" else ["-delay", apng_delay_var.get()]),
filepath,
"apng:" + str(output_path)
])
return str(output_path.absolute())
def process_file(filepath):
if filepath.lower().endswith(".webp"):
filepath = convert_webp_to_apng(filepath)
p = Path(filepath)
job = ffmpeg.input(filepath)
# 30FPS
job = job.filter('fps', fps=fps_var.get())
info = ffmpeg.probe(filepath)
pprint(info)
stream = info['streams'][0]
fmt = info['format']
if resize_mode_var.get() == 'fit':
# Try to scale to 512px
if stream['width'] >= stream['height']:
job = job.filter('scale', width_var.get(), -1)
else:
job = job.filter('scale', -1, height_var.get())
elif resize_mode_var.get() == 'pad':
if stream['width'] >= stream['height']:
job = job.filter('pad', width=width_var.get(), height=f'min(ih,{height_var.get()})', x='(ow-iw)/2', y='(oh-ih)/2', color="white@0")
else:
job = job.filter('pad', width=f'min(iw,{height_var.get()})', height=height_var.get(), x='(ow-iw)/2', y='(oh-ih)/2', color="white@0")
elif resize_mode_var.get() == 'scale':
job = job.filter('scale', width_var.get(), height_var.get())
if 'duration' in fmt:
print("Duration detected: %s" % fmt['duration'])
duration = float(fmt['duration'])
# Try speed up video if it's over 3 seconds
if duration > 3.0:
job = job.filter('setpts', f"({smart_limit_duration_var.get()}/{duration})*PTS")
else:
print("Unable to determine duration")
job = job.filter('setpts', f"{fallback_pts_var.get()}*PTS")
out_path = str(p.with_suffix('.webm'))
if os.path.exists(out_path):
out_path = str(p.with_suffix('.telegram.webm'))
extra_args = {}
if crf_var.get() != -1:
extra_args['crf'] = crf_var.get()
job = (
job
.output(
out_path,
pix_fmt='yuva420p',
vcodec='libvpx-vp9',
an=None, # Remove Audio
**extra_args,
)
.overwrite_output()
)
job.run()
listbox.insert(0, out_path)
listbox.drop_target_register(tkd.DND_FILES, tkd.DND_ALL)
listbox.dnd_bind('<<Drop>>', drop)
return root
if __name__ == '__main__':
main()