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
|
#!/usr/bin/python2.7
import sys
import os
from pb.config import *
import pb.lib.utils as utils
#FIXME these guys can do stuff wider than 1000
LIKE_A_BOSS = "ryz pepper seamonkey JAMES".split(" ")
DEFAULT_FINALFORMAT = "gif"
DEFAULT_TAG = "im";
GRAVITY_PARAMS = ["NorthWest","North","NorthEast","West","Center","East","SouthWest","South","SouthEast"]
GRAVITY_DEFAULT = "center"
FORMAT_PARAMS = ["jpg", "gif", "png"]
COMPOSE_PARAMS = [ "Over", "ATop", "Dst_Over", "Dst_In", "Dst_Out", "Multiply",
"Screen", "Divide", "Plus", "Difference", "Exclusion",
"Lighten", "Darken", "Overlay", "Hard_Light", "Soft_Light",
"Linear_Dodge", "Linear_Burn", "Color_Dodge", "Color_Burn" ]
DISPOSE_PARAMS = ["None","Previous","Background"]
DISPOSE_DEFAULT = "None"
class Generate():
def __init__(self, **kwargs):
self.params = {}
self.now = utils.now()
self.files_created = []
self.commands = [];
self._required_keys = [
#{{{ required_keys
#IMAGES
"url",
"background",
#BOOLS
"coalesce",
"dispose",
"nearest",
"merge_early",
"flip",
"flop",
"tile",
"transparent",
#COLORS
"black",
"white",
"subtract",
#INTS
"fuzz",
"width",
"height",
"brightness",
"contrast",
"saturation",
"rotate",
"hue",
#ENUMS
"compose",
"gravity",
"format",
#STRINGS
"name",
"callback",
#}}}
]
for k in self._required_keys:
if k in kwargs:
if k in [ 'url', 'background' ] and utils.bool_correct(kwargs[k]):
self.params[k] = {
'url' : kwargs[k],
'filename' : self._make_tempname(k),
'path' : os.path.join(WORKING_DIR, self._make_tempname(k)) ,
}
try:
utils.download(self.params[k]['url'], self.params[k]['path'])
self.files_created.append(self.params[k]['path'])
self.params[k]['mimetype'] = utils.get_mimetype(self.params[k]['path'])
except Exception as e:
sys.stderr.write(str(e))
raise Exception ("BAD PARAMS");
elif k in [ 'black', 'white', 'subtract' ]:
try:
self.params[k] = utils.is_color(kwargs[k])
except Exception:
raise Exception("Unable to process color for:\n{}".format(k))
elif k in [
"coalesce", "dispose", "nearest", "merge_early",
"flip", "flop", "tile", "transparent",
]:
self.params[k] = utils.bool_correct(utils.sanitize(kwargs[k]))
elif k == 'gravity' and self._test_enum(kwargs[k], GRAVITY_PARAMS):
self.params[k] = kwargs[k]
elif k == 'format' and self._test_enum(kwargs[k], FORMAT_PARAMS):
self.params[k] = kwargs[k]
elif k == 'compose' and self._test_enum(kwargs[k], COMPOSE_PARAMS):
self.params[k] = kwargs[k]
elif k == 'dispose' and self._test_enum(kwargs[k], DISPOSE_PARAMS):
self.params[k] = kwargs[k]
elif k in [ "fuzz", "width", "height", "brightness", "contrast", "saturation", "rotate", "hue" ]:
self.params[k] = str(int(kwargs[k]))
else:
self.params[k] = utils.sanitize(kwargs[k])
if self.params.get('background'):
self.tag = self.params.get('compose')
else:
self.tag = self.params.get('transparent', DEFAULT_TAG)
self.basename = self._get_filename();
self.filename = "{}.{}".format(self.basename, self.params.get('format', DEFAULT_FINALFORMAT))
self.filepath = os.path.join(WORKING_DIR, self.filename)
def _make_tempname(self, s):
return "PBTMP{}{}".format(self.now, s);
def _test_enum(self, e, arr):
if e in arr: return True
raise Exception ("Bad value: {}".format(e))
def _get_filename(self):
return "{}_{}_{}".format(
self.tag,
self.now,
self.params.get('username',"")
);
def _call_cmd(self, cmd):
try:
utils.call_cmd(cmd)
self.commands.append(" ".join(cmd));
except Exception:
raise Exception("Unable to call cmd {}".format(str(cmd)))
def _cleanup(self):
if not len(self.files_created):
pass
cmd = ["rm", "-f"] + self.files_created
self._call_cmd(cmd)
def _composite (self):
cmd = [
BIN_CONVERT, self.params['background']['path'],
"null:", self.filepath, "-matte",
"-dispose", self.params.get('dispose', DISPOSE_DEFAULT),
"-gravity", self.params.get("gravity",GRAVITY_DEFAULT),
"-compose", self.params['compose'], "-layers", "composite",
self.filepath ]
self._call_cmd(cmd);
def _convert(self):
cmd = [BIN_CONVERT, self.params['url']['path'] ]
if self.params.get('rotate'): cmd += ["-rotate", self.params['rotate'] ]
if self.params.get('flip'): cmd += ["-flip"]
if self.params.get('flop'): cmd += ["-flop"]
if self.params.get('transparent'):
if self.params.get('fuzz'):
cmd += ["-fuzz", "{}%".format(self.params['fuzz']) ]
cmd += [ "-transparent", self.params.get('subtract', "white") ]
if self.params.get('width') or self.params.get('height'):
if self.params.get('nearest'):
if self.params.get('format') == "gif":
cmd += [ "-coalesce","+map","-interpolate","Nearest","-interpolative-resize" ]
else:
cmd.append("-resize")
cmd.append("{}x{}".format(self.params.get('width') or "", self.params.get('height') or ""))
if self.params.get('black') != "black" or self.params.get('white') != 'white':
cmd += [ "+level-colors" , "{},{}".format(self.params.get('black','black'), self.params.get('white', 'white')) ]
if self.params.get('contrast'): cmd += [ '-contrast-stretch', self.params['contrast'] ]
if any( e in self.params.keys() for e in ['brightness', 'saturation', 'hue' ]):
cmd += [
"-modulate", "{},{},{}".format(
self.params.get('brightness', 100),
self.params.get('contrast', 100),
self.params.get('hue', 100)
)]
cmd.append("-coalesce"); #why? #FIXME
cmd += [ self.filepath ];
self._call_cmd(cmd);
def create(self):
self._convert()
if self.params.get('background'):
self._composite()
self._cleanup();
if __name__ == "__main__":
TEST_PARAMS = {
'nearest': 'true',
# 'height': None,
'compose': 'Soft_Light',
'coalesce': 'true',
'dispose': 'None',
'gravity': 'Center',
'width': '200',
'black': 'black',
'tile': 'true',
'white': 'white',
'contrast': '100',
'hue': '90',
'saturation': '100',
'merge_early': 'true',
'format': 'gif',
'background': 'http://i.asdf.us/im/bc/new_1430440747.gif',
'subtract': '#EE7AE9',
'transparent': 'true',
# 'rotate': None,
'name': 'yo',
# 'brightness': None,
'url': 'http://asdf.us/im/new.gif',
'flop': 'true',
'flip': 'false',
'callback': 'jsonp1430442384162',
'fuzz': '5'
}
g = Generate(**TEST_PARAMS);
g.create()
|