-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinstagiffer.py
executable file
·7337 lines (5593 loc) · 290 KB
/
instagiffer.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013-2019 Exhale Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
# must display the following acknowledgement:
# This product includes software developed by Exhale Software Inc.
# 4. Neither Exhale Software Inc., nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY EXHALE SOFTWARE INC. ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL EXHALE SOFTWARE INC. BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
###############################################################################
"""instagiffer.py: The easy way to make GIFs"""
# Only use odd-numbered minor revisions for pre-release builds
INSTAGIFFER_VERSION="1.77"
# If not a pre-release set to "", else set to "pre-X"
INSTAGIFFER_PRERELEASE=""
__author__ = "Justin Todd"
__copyright__ = "Copyright 2013-2019, Exhale Software Inc."
__maintainer__ = "Justin Todd"
__email__ = "[email protected]"
__imgurcid__ = "58fc34d08ab311d"
__status__ = "Production"
__version__ = INSTAGIFFER_VERSION+INSTAGIFFER_PRERELEASE
__release__ = True # If this is false, bindep output, and info-level statements will be displayed stdout
__changelogUrl__ = "http://instagiffer.com/post/146636589471/instagiffer-175-macpc"
__faqUrl__ = "http://www.instagiffer.com/post/51787746324/frequently-asked-questions"
import hashlib
import argparse
import base64
import json
import urllib
import urllib2
import sys
import os
import shutil
import subprocess
import re
import glob
import uuid
import time
import itertools
import logging
import random
import locale
import shlex
import traceback
import codecs
from random import randrange
from os.path import expanduser
from ConfigParser import SafeConfigParser, RawConfigParser
from threading import Thread
from Queue import Queue, Empty
from fractions import gcd
# PIL
import PIL
from PIL import Image, ImageTk, ImageFilter, ImageDraw
# TK
import ttk
import tkFont
import tkMessageBox
from Tkinter import *
from tkColorChooser import *
from tkFileDialog import askopenfilename, askdirectory, asksaveasfilename
# Win32 specific includes
if sys.platform == 'win32':
import winsound
import win32api
# Windows uses the PIL ImageGrab module for screen capture
from PIL import ImageGrab
# Return true if running on a MAC
#
def ImAMac():
return sys.platform == 'darwin'
#
# Return true if running on a PC
#
def ImAPC():
return sys.platform == 'win32'
#
# Open a file in the application associated with this file extension
#
def OpenFileWithDefaultApp(fileName):
if sys.platform == 'darwin':
os.system('open ' + fileName)
else:
try:
os.startfile(fileName)
except:
tkMessageBox.showinfo("Unable to open!", "I wasn't allowed to open '" + fileName + "'. You will need to perform this task manually.")
def GetFileExtension(filename):
try:
fname, fext = os.path.splitext(filename)
except:
return ""
if fext is None:
return ""
fext = str(fext).lower()
fext = fext.strip('.')
return fext
def AudioPlay(wavPath):
if ImAMac():
if wavPath is not None:
subprocess.call(["afplay", wavPath]) # blocks
elif ImAPC():
if wavPath is None:
winsound.PlaySound(None, 0)
else:
winsound.PlaySound(wavPath, winsound.SND_FILENAME|winsound.SND_ASYNC)
return True
def IsPictureFile(fileName):
return GetFileExtension(fileName) in [ 'jpeg', 'jpg', 'png', 'bmp', 'tif' ]
def IsUrl(s):
urlPatterns = re.compile('^(www\.|https://|http://)', re.I)
return urlPatterns.match(s)
def GetLogPath():
return os.path.dirname(os.path.realpath(sys.argv[0])) + os.sep + 'instagiffer-event.log'
#
# Mostly for Windows. Converts path into short form to bypass unicode headaches
#
def CleanupPath(path):
#
# Deal with Unicode video paths. On Windows, simply DON'T
# deal with it. Use short names and paths instead :S
#
if ImAPC():
try:
path.decode('ascii')
except:
path = win32api.GetShortPathName(path)
return path
#
# Re-scale a value
#
def ReScale(val, oldScale, newScale):
OldMax = oldScale[1]
OldMin = oldScale[0]
NewMax = newScale[1]
NewMin = newScale[0]
OldValue = val
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
return NewValue
#
# norecurse decorator
#
def norecurse(func):
func.called = False
def f(*args, **kwargs):
if func.called:
print "Recursion!"
return False
else:
func.called = True
result = func(*args, **kwargs)
func.called = False
return result
return f
#
# Convert a time or duration (hh:mm:ss.ms) string into a value in milliseconds
#
def DurationStrToMillisec(str, throwParseError=False):
if str is not None:
r = re.compile('[^0-9]+')
tokens = r.split(str)
vidLen = ((int(tokens[0]) * 3600) + (int(tokens[1]) * 60) + (int(tokens[2]))) * 1000 + int(tokens[3])
return vidLen
else:
if throwParseError:
raise ValueError("Invalid duration format")
return 0
def DurationStrToSec(durationStr):
ms = DurationStrToMillisec(durationStr)
if ms == 0:
return 0
else:
#return int((ms + 500) / 1000) # Rouding
return int(ms/1000) # Floor
def MillisecToDurationComponents(msTotal):
secTotal = msTotal / 1000
h = int(secTotal / 3600)
m = int((secTotal % 3600) / 60)
s = int(secTotal % 60)
ms = int(msTotal % 1000)
return [h, m, s, ms]
def MillisecToDurationStr(msTotal):
dur = MillisecToDurationComponents(msTotal)
return "%02d:%02d:%02d.%03d" % (dur[0],dur[1],dur[2],dur[3])
def CountFilesInDir(dirname, filenamePattern=None):
if filenamePattern is None:
return len([name for name in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, name))])
else:
fileglobber = dirname + filenamePattern + '*'
return len(glob.glob(fileglobber))
#
# Run non-blocking
#
#
# Converts process output to status bar messages - there is some cross-cutting here
#
def DefaultOutputHandler(stdoutLines, stderrLines, cmd):
s = None
i = False
for outData in [stdoutLines, stderrLines, cmd]:
if outData is None or len(outData) == 0:
continue
if ImAMac() and type(outData) == list:
outData = " ".join('"{0}"'.format(arg) for arg in outData)
# youtube dl
youtubeDlSearch = re.search(r'\[download\]\s+([0-9\.]+)% of', outData, re.MULTILINE)
if youtubeDlSearch:
i = int(float(youtubeDlSearch.group(1)))
s = "Downloaded %d%%..." % (i)
# ffmpeg frame extraction progress
ffmpegSearch = re.search(r'frame=.+time=(\d+:\d+:\d+\.\d+)', outData, re.MULTILINE)
if ffmpegSearch:
secs = DurationStrToMillisec(ffmpegSearch.group(1))
s = "Extracted %.1f seconds..." % (secs/1000.0)
# imagemagick - figure out what we're doing based on comments
imSearch = re.search(r'^".+(convert\.exe|convert)".+-comment"? "([^"]+):(\d+)"', outData)
if imSearch:
n = int(imSearch.group(3))
if n == -1:
s = "%s" % (imSearch.group(2))
else:
i = n
s = "%d%% %s" % (i, imSearch.group(2))
return s, i
ON_POSIX = 'posix' in sys.builtin_module_names
def EnqueueProcessOutput(streamId, inStream, outQueue):
for line in iter(inStream.readline, b''):
#logging.info(streamId + ": " + line)
outQueue.put(line)
#
# Prompt User
#
def NotifyUser(title, msg):
return tkMessageBox.showinfo(title, msg)
#
# Run a process
#
def RunProcess(cmd, callback = None, returnOutput = False, callBackFinalize = True, outputTranslator = DefaultOutputHandler):
if not __release__:
logging.info("Running Command: " + cmd)
try:
cmd = cmd.encode(locale.getpreferredencoding())
except UnicodeError:
logging.error("RunProcess: Command '" + cmd + "' contained undecodable unicode. Local encoding: " + str(locale.getpreferredencoding()))
if returnOutput:
return "",""
else:
return False
env = os.environ.copy()
if ImAPC():
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
elif ImAMac():
startupinfo = None
cmd = shlex.split(cmd)
pipe = subprocess.Popen(cmd, startupinfo=startupinfo, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, bufsize=1, close_fds=ON_POSIX)
qOut = Queue()
qErr = Queue()
tOut = Thread(target=EnqueueProcessOutput, args=("OUT", pipe.stdout, qOut))
tErr = Thread(target=EnqueueProcessOutput, args=("ERR", pipe.stderr, qErr))
tOut.start()
tErr.start()
callbackReturnedFalse = False
stdout = ""
stderr = ""
percent = None
while True:
statusStr = None
stderrLines = None
stdoutLines = None
try:
while True: # Exhaust the queue
stdoutLines = qOut.get_nowait()
stdout += stdoutLines
except: pass
try:
while True:
stderrLines = qErr.get_nowait()
stderr += stderrLines
except: pass
if outputTranslator is not None:
#try:
statusStr, percentDoneInt = outputTranslator(stdoutLines, stderrLines, cmd)
if type(percentDoneInt) == int:
percent = percentDoneInt
elif percent is not None:
percentDoneInt = percent
#except:
# pass
# Caller wants to abort!
if callback is not None and callback(percentDoneInt, statusStr) == False:
try:
pipe.terminate()
pipe.kill()
except:
logging.error("RunProcess: kill() or terminate() caused an exception")
callbackReturnedFalse = True
break
# Check if done
if pipe.poll() is not None:
break
time.sleep(0.1) # Polling frequency. Lengthening this will decrease responsiveness
# Notify callback of exit. Check callballFinalize so we don't prematurely reset the progress bar
if callback is not None and callBackFinalize is True:
callback(True)
# Callback aborted command
if callbackReturnedFalse:
logging.error("RunProcess was aborted by caller")
#return False
# result
try:
remainingStdout = ""
remainingStderr = ""
remainingStdout, remainingStderr = pipe.communicate()
except IOError as e:
logging.error("Encountered error communicating with sub-process" + str(e))
success = (pipe.returncode == 0)
stdout += remainingStdout
stderr += remainingStderr
# Logging
if not __release__:
logging.info("return: " + str(success))
logging.info("stdout: " + stdout)
logging.error("stderr: " + stderr)
if returnOutput:
return stdout, stderr #, success
else:
return success
#
# Create working directory
#
def CreateWorkingDir(conf):
tempDir = None
# See if they specified a custom dir
if conf.ParamExists('paths', 'workingDir'):
tempDir = conf.GetParam('paths', 'workingDir')
appDataRoot = ''
# No temp dir configured
if tempDir == None or tempDir == '':
if ImAMac():
appDataRoot = expanduser("~") + '/Library/Application Support/'
tempDir = appDataRoot + 'Instagiffer/'
else:
appDataRoot = expanduser("~") + os.sep
tempDir = appDataRoot + '.instagiffer' + os.sep + 'working'
# Pre-emptive detection and correction of language issues
try:
tempDir.encode(locale.getpreferredencoding())
except UnicodeError:
logging.info("Users home directory is problematic due to non-latin characters: " + tempDir)
tempDir = GetFailSafeDir(conf, tempDir)
# Try to create temp directory
if not os.path.exists(tempDir):
os.makedirs(tempDir)
if not os.path.exists(tempDir):
logging.error("Failed to create working directory: " + tempDir)
return ""
logging.info("Working directory created: " + tempDir)
return tempDir
#
# For language auto-fix
#
def GetFailSafeDir(conf, badPath):
path = badPath
if ImAPC():
goodPath = conf.GetParam('paths', 'failSafeDir')
if not os.path.exists(goodPath):
if tkMessageBox.askyesno("Automatically Fix Language Issue?", "It looks like you are using a non-latin locale. Can Instagiffer create directory " + goodPath + " to solve this issue?"):
err = False
try:
os.makedirs(goodPath)
except:
err = True
if os.path.exists(goodPath):
path = goodPath
else:
err = True
if err:
tkMessageBox.showinfo("Error Fixing Language Issue", "Failed to create '" + goodPath + "'. Please make this directory manually in Windows Explorer, then restart Instagiffer.")
else:
path = goodPath
return path
#
# Configuration Class
#
class InstaConfig:
description = "Configuration Class"
author = "Justin Todd"
def __init__(self, configPath):
self.path = configPath
# Load configuration file
if not os.path.exists(self.path):
logging.error("Unable to find configuration file: " + self.path)
self.ReloadFromFile()
def ReloadFromFile(self):
self.config = None
self.config = SafeConfigParser()
self.config.read(self.path)
def ParamExists(self, category, key):
if not category in self.config._sections:
return False
if not key.lower() in self.config._sections[category.lower()]:
#self.Dump()
#logging.error("Configuration parameter %s.%s does not exist" % (category, key))
return False
else:
#logging.info("Configuration parameter %s.%s exists" % (category, key))
return True
def GetParam(self, category, key):
retVal = u""
if self.ParamExists(category, key):
retVal = self.config._sections[category.lower()][key.lower()]
elif self.ParamExists(category + '-' + sys.platform, key):
retVal = self.config._sections[category.lower() + '-' + sys.platform][key.lower()] # platform specific config
if isinstance(retVal, bool) or isinstance(retVal, int):
return retVal
# We are dealing with strings or unicode
# Expand variables
try:
retVal = os.path.expandvars(retVal)
except:
pass
# Config file encoding is UTF-8
if not isinstance(retVal, unicode):
retVal = unicode(retVal, 'utf-8')
if retVal.startswith(";"):
retVal = ""
return retVal
#
def GetParamBool(self, category, key):
val = self.GetParam(category, key)
boolVal = True
if isinstance(val, int):
boolVal = not (val == 0)
elif val == None:
boolVal = False
elif val == "":
boolVal = False
elif val.lower() == "false" or val == "0":
boolVal = False
return boolVal
#
def SetParam(self, category, key, value):
try:
current = self.config._sections[category.lower()][key.lower()]
except KeyError:
current = None
self.config._sections[category.lower()][key.lower()] = value
if value != current:
return 1
else:
return 0
def SetParamBool(self, category, key, val):
boolVal = True
if isinstance(val, int):
boolVal = not (val == 0)
elif val == None:
boolVal = False
elif val == "":
boolVal = False
elif val.lower() == "false" or val == "0":
boolVal = False
boolVal = str(boolVal)
changed = self.SetParam(category, key, val)
return changed
def Dump(self):
logging.info("=== GIF Configuration =========================================")
for cat in self.config._sections:
logging.info("%s:" % (str(cat)))
for k in self.config._sections[cat]:
dumpStr = u" - " + k + u": "
val = self.GetParam(cat, k)
if isinstance(val, bool):
dumpStr += str(val) + " (boolean)"
elif isinstance(val, int):
dumpStr += str(val) + " (int)"
else:
dumpStr += val
logging.info(dumpStr)
logging.info("===============================================================")
#
# Wrapper around the Imagemagick font engine
#
class ImagemagickFont:
def __init__(self, imagemagickFontData):
self.fonts = dict()
fonts = re.findall(r'\s*Font: (.+?)\n\s*family: (.+?)\n\s*style: (.+?)\n\s*stretch: (.+?)\n\s*weight: (.+?)\n\s*glyphs: (.+?)\n', imagemagickFontData, re.DOTALL|re.M|re.UNICODE)
for font in fonts:
fontFamily = font[1].strip()
fontId = font[0].strip()
fontFile = font[5].strip()
fontStyle = font[2].strip()
fontStretch = font[3].strip()
fontWeight = font[4].strip()
try:
fontFamily.decode('ascii')
fontId.decode('ascii')
fontFile.decode('ascii')
except:
logging.error("Unable to load font: " + fontFamily)
continue
# ignore stretched fonts, and styles other than italic, and weights we don't know about
if fontFamily != 'unknown' and fontStretch == "Normal" and (fontStyle == 'Italic' or fontStyle == 'Normal') and (fontWeight == '400' or fontWeight == '700'):
overallStyle = None
if fontStyle == 'Normal' and fontWeight =='400':
overallStyle = "Regular"
elif fontStyle == 'Normal' and fontWeight =='700':
overallStyle = "Bold"
elif fontStyle == 'Italic' and fontWeight =='400':
overallStyle = "Italic"
elif fontStyle == 'Italic' and fontWeight == '700':
overallStyle = "Bold Italic"
if overallStyle is not None:
if fontFamily not in self.fonts:
self.fonts[fontFamily] = dict()
self.fonts[fontFamily][overallStyle] = fontId
def GetFontCount(self):
return len(self.fonts.keys())
def GetFamilyList(self):
ret = self.fonts.keys()
ret.sort()
return tuple(ret)
def GetFontAttributeList(self, fontFamily):
ret = self.fonts[fontFamily].keys()
ret.sort(reverse=True)
return tuple(ret)
def GetFontId(self, fontFamily, fontStyle):
return self.fonts[fontFamily][fontStyle]
def GetBestFontFamilyIdx(self, userChoice=""):
fontFamilyList = self.GetFamilyList()
if len(userChoice) and userChoice in fontFamilyList:
return fontFamilyList.index(userChoice)
elif 'Impact' in fontFamilyList:
return fontFamilyList.index('Impact')
elif 'Arial Rounded MT Bold' in fontFamilyList:
return fontFamilyList.index('Arial Rounded MT Bold')
elif 'Arial' in fontFamilyList:
return fontFamilyList.index('Arial')
else:
return 0
#
# Animated Gif Engine
#
# Try to keep this class fully de-coupled from the GUI
#
class AnimatedGif:
description = "Animated Gif Engine"
author = "Justin Todd"
def __init__(self, config, mediaLocator, workDir, periodicCallback, rootWindow):
self.conf = config
self.workDir = workDir
self.callback = periodicCallback
self.origURL = mediaLocator
self.isUrl = False
self.videoWidth = 0
self.videoHeight = 0
self.videoLength = None
self.videoFps = 0.0
self.videoPath = None
self.videoFileName = ""
self.imageSequence = []
self.imageSequenceCropParams = None # At the moment, used for mac screen grab only. When the image sequence is "extracted" we sneak in the crop operation instead of resizing
self.fonts = None
self.rootWindow = rootWindow # Needed for mouse cursor
self.gifCreated = False
self.gifOutPath = None # Warning: Don't use this directly!
self.lastSavedGifPath = None
self.overwriteGif = True
self.frameDir = workDir + os.sep + 'original'
self.resizeDir = workDir + os.sep + 'resized'
self.processedDir = workDir + os.sep + 'processed'
self.captureDir = workDir + os.sep + 'capture'
self.maskDir = workDir + os.sep + 'mask'
self.downloadDir = workDir + os.sep + 'downloads'
self.previewFile = workDir + os.sep + 'preview.gif'
self.vidThumbFile = workDir + os.sep + 'thumb.png'
self.blankImgFile = workDir + os.sep + 'blank.gif'
self.audioClipFile = workDir + os.sep + 'audio.wav'
self.OverwriteOutputGif(self.conf.GetParamBool('settings', 'overwriteGif'))
if self.conf.GetParam('paths', 'gifOutputPath').lower() == 'default':
self.gifOutPath = self.GetDefaultOutputDir() + os.sep + 'insta.gif'
else:
self.gifOutPath = self.conf.GetParam('paths', 'gifOutputPath')
startupLog = "AnimatedGif:: media: ["+mediaLocator+"], workingDir: ["+workDir+"], gifOut: ["+self.GetNextOutputPath()+"]"
logging.info(startupLog)
# if mediaLocator == self.GetGifOutputPath():
# self.FatalError("This file is in-use by Instagiffer!")
if not os.path.exists(os.path.dirname(self.gifOutPath)):
os.makedirs(os.path.dirname(self.gifOutPath))
if not os.path.exists(os.path.dirname(self.gifOutPath)):
self.FatalError("Failed to create gif output directory: " + os.path.dirname(self.gifOutPath))
if not os.path.exists(self.frameDir):
os.makedirs(self.frameDir)
if not os.path.exists(self.frameDir):
self.FatalError("Failed to create working directory: " + self.frameDir)
if not os.path.exists(self.resizeDir):
os.makedirs(self.resizeDir)
if not os.path.exists(self.resizeDir):
self.FatalError("Failed to create working directory: " + self.resizeDir)
if not os.path.exists(self.processedDir):
os.makedirs(self.processedDir)
if not os.path.exists(self.processedDir):
self.FatalError("Failed to create working directory: " + self.processedDir)
if not os.path.exists(self.downloadDir):
os.makedirs(self.downloadDir)
if not os.path.exists(self.downloadDir):
self.FatalError("Failed to create working directory: " + self.downloadDir)
if not os.path.exists(self.captureDir):
os.makedirs(self.captureDir)
if not os.path.exists(self.captureDir):
self.FatalError("Failed to create working directory: " + self.captureDir)
if not os.path.exists(self.maskDir):
os.makedirs(self.maskDir)
if not os.path.exists(self.maskDir):
self.FatalError("Failed to create working directory: " + self.maskDir)
self.LoadFonts()
self.CheckPaths()
self.DeleteResizedImages()
self.DeleteExtractedImages()
self.DeleteProcessedImages()
self.DeleteCapturedImages()
self.DeleteMaskImages()
self.DeleteAudioClip()
#self.DeleteGifOutput()
mediaLocator = self.ResolveUrlShortcutFile(mediaLocator)
logging.info("Analyzing the media path to determine what kind of video this is...")
self.isUrl = IsUrl(mediaLocator)
captureRe = re.findall('^::capture ([\.0-9]+) ([\.0-9]+) ([0-9]+)x([0-9]+)\+(\-?[0-9]+)\+(\-?[0-9]+) cursor=(\d+) retina=(\d+) web=(\d+)$', mediaLocator)
isImgSeq = "|" in mediaLocator or IsPictureFile(mediaLocator)
if captureRe and len(captureRe[0]) == 9:
logging.info("Media locator indicates screen capture")
capDuration = float(captureRe[0][0])
capTargetFps = float(captureRe[0][1])
capWidth = int(captureRe[0][2])
capHeight = int(captureRe[0][3])
capX = int(captureRe[0][4])
capY = int(captureRe[0][5])
cursorOn = int(captureRe[0][6])
retina = int(captureRe[0][7])
web = int(captureRe[0][8])
self.Capture(capDuration, capTargetFps, capWidth, capHeight, capX, capY, cursorOn, retina, web)
elif isImgSeq:
logging.info("Media Locator is an image sequence")
for fname in mediaLocator.split("|"):
if len(fname):
self.imageSequence.append(fname)
# Arbitrarily pick an FPS of 10 for image sequences
self.videoFps = 10.0
else:
if self.isUrl:
logging.info("Media locator is a URL")
self.downloadQuality = self.conf.GetParam('settings', 'downloadQuality')
self.videoPath = self.DownloadVideo(mediaLocator)
else:
logging.info("Media locator points to a local file")
self.videoPath = CleanupPath(mediaLocator)
self.videoFileName = os.path.basename(mediaLocator)
self.GetVideoParameters()
def ResolveUrlShortcutFile(self, filename):
"""Given a Windows .url filename, returns the main URL, or argument passed in if it can't
find one."""
fname, fext = os.path.splitext(filename)
if not fext or len(fext) == 0 or str(fext.lower()) != '.url':
return filename
# Windows .URL file format is compatible with built-in ConfigParser class.
config = RawConfigParser()
try:
config.read(filename)
except:
return filename
# Return the URL= value from the [InternetShortcut] section.
if config.has_option('InternetShortcut', 'url'):
return config.get('InternetShortcut', 'url').strip('"')
# If there is none, return the BASEURL= value from the [DEFAULT] section.
if 'baseurl' in config.defaults().keys():
return config.defaults()['baseurl'].strip('"')
else:
return filename
def GetConfig(self):
return self.conf
def Capture(self, seconds, targetFps, width, height, x, y, showCursor, retinaDisplay, web):
if seconds < 1:
return False
# Capture as fast as possible
imgIdx = 1
nowTs = time.time()
endTs = nowTs + seconds
nextFrameTs = nowTs
#
imgDataArray = []
imgDimensions = ()
if retinaDisplay:
width *= 2
height *= 2
x *= 2
y *= 2
resizeRatio = 1.0
# Max width/height restrictions
if web:
maxWH = int(self.conf.GetParam('screencap', 'webMaxWidthHeight'))
targetFps = int(self.conf.GetParam('screencap', 'webMaxFps'))
if width >= height and width > maxWH:
resizeRatio = maxWH / float(width)
elif height >= width and height > maxWH:
resizeRatio = maxWH / float(height)
while time.time() < endTs:
# Rate-limiting
if targetFps != 0:
nowTs = time.time()
if nowTs < nextFrameTs:
time.sleep(nextFrameTs - nowTs)
nextFrameTs = time.time() + 1.0/targetFps
# Filename
capFileName = self.GetCapturedImagesDir() + 'cap%04d' % (imgIdx)
if ImAPC():
capFileName += '.bmp'
try:
img = ImageGrab.grab((x, y, x+width, y+height))
except MemoryError:
self.callback(True)
self.FatalError("Ran out of memory during screen capture. Try recording a smaller area, or decreasing your duration.")
return False
imgDimensions = img.size
if showCursor:
# Get mouse cursor position
cursorX, cursorY = self.rootWindow.winfo_pointerxy()
if cursorX > x and cursorX < x+width and cursorY > y and cursorY < y + height:
# Draw Cursor (Just a dot for now)
r = 2 # radius
draw = ImageDraw.Draw(img)
draw.ellipse((cursorX-x-r, cursorY-y-r, cursorX-x+r, cursorY-y+r), fill="#ffffff", outline="#000000")
if self.conf.GetParamBool('screencap', 'DirectToDisk'):
img.save(capFileName)
else:
#imgDataArray.append(img.tostring()) # PIL
imgDataArray.append(img.tobytes()) # PILLOW
elif ImAMac():
capFileName += '.bmp' # Supported formats: png, bmp jpg
scrCapCmd = "screencapture -x "
if showCursor:
scrCapCmd += "-C "
scrCapCmd += "\"%s\"" % (capFileName)
os.system(scrCapCmd)
self.imageSequence.append(capFileName)
imgIdx += 1
self.callback(False)
# Post-process
if ImAPC():
if not self.conf.GetParamBool('screencap', 'DirectToDisk'):
logging.info("Using fps-optimized screen cap")
frameCount = 0
for x in range(0, len(imgDataArray)):
try:
capPath = self.imageSequence[frameCount]
except IndexError:
break
# PIL uses fromstring
PIL.Image.frombytes('RGB', imgDimensions, imgDataArray[x]).resize((int(width*resizeRatio), int(height*resizeRatio)), PIL.Image.ANTIALIAS).save(capPath)
if os.path.exists(capPath):
frameCount += 1
else:
logging.error("Capture file " + capPath + " was not saved to disk for some reason")
# Trim the list to the actual size
missingCount = len(self.imageSequence) - frameCount
if missingCount != 0:
logging.error("Not all capture files were accounted for: %d missing " % (missingCount))
self.imageSequence = self.imageSequence[0:min(frameCount, len(self.imageSequence))]