diff options
Diffstat (limited to 'lib/Pb/Break')
| -rwxr-xr-x | lib/Pb/Break/__init__.py | 169 | ||||
| -rwxr-xr-x | lib/Pb/Break/__init__.py~ | 205 |
2 files changed, 374 insertions, 0 deletions
diff --git a/lib/Pb/Break/__init__.py b/lib/Pb/Break/__init__.py new file mode 100755 index 0000000..cf12cc2 --- /dev/null +++ b/lib/Pb/Break/__init__.py @@ -0,0 +1,169 @@ +#!/usr/bin/python2.7 +import os +import sys +import random +import re +import urllib +import inspect +from Config import * +from Pb import Pb +from Params import Params + +DEFAULT_FINALFORMAT = "png"; + +_subtle_break_mark = 'pron' +_extreme_break_mark = 'sugar' + +_header_offset = 2000 +_default_breakmode = "subtle" + +class PbBreak(Pb): #FIXME in db gallery + example_params = { + "url" : "http://i.asdf.us/im/de/HolyMountain2_1322275112_seamonkey.gif", + "breaktype" : "RGB_WASH", + "finalformat" : "png", + "breakmode" : "extreme", + "breakangle" : "10", + "username" : "donkey", + "expanded" : "false" + } + def __init__(self, **kwargs): + super(PbBreak,self).__init__(); + _definitions = { + 'username': { 'type': 'string' }, + 'breaktype': { 'type': 'string' }, + 'breakmode': { + 'type': 'enum', + 'enum_values' : ['subtle', 'extreme', 'gradual'] , + 'default' : _default_breakmode + }, + 'breakangle': { 'type': 'float' }, + 'expanded': { 'type': 'bool' }, + 'url': { 'type': 'img_url' }, + 'finalformat': { 'type': 'enum', 'enum_values' : ['png', 'gif', 'jpg' ] } + } + self.params.definitions_import(_definitions, kwargs, classname=self.__class__.__name__); + self._files_created.append(self.params.url.path) + self.params.breaktype.set_val(self._get_breaktype(str(self.params.breaktype))) + + #psd returns an animation + if not self.params.finalformat and self.params.url.mimetype == "gif": + self.params.finalformat.set_val("gif") + elif self.params.breaktype == 'miff': + self.params.finalformat.set_val("jpg") + self.params.breakmode.set_val("subtle") + elif not self.params.finalformat: + self.params.finalformat.set_val(DEFAULT_FINALFORMAT) + self._width_and_height_set(filepath=self.params.url.path) + + self.filename, self.filepath = self._filename_filepath_create(url=self.params.url.url, extension=self.params.finalformat) + self._conversion_file = self._tempfilepath_create(namepart="conversion", extension=self.params.breaktype) + + def _get_breaktype(self, key): + #{{{ conversion table + breaktypeTranslate = { + 'CLASSIC':'jpg', + 'REDUX':'pcds', + 'BLURRY_BREAK':'viff', + 'BLURRY_BREAK_2':'mat', + 'SWIPE':'miff', + 'RGB_WASH':'psd', + 'RGB_WASH_2':'psb', + 'NOISY_BREAK':'palm', + 'NOISY_BREAK_2':'fig', + 'BROKEN_VIGNETTE':'pbm', + 'FAX_MACHINE':'cals', + 'STRIPES':'exr', + 'PHOTOCOPY':'art', + } + #}}} + return breaktypeTranslate[key] + +#{{{#########rotatefunctions####################################### + def _rotate(self): + cmd = [BIN_CONVERT,self.params.url.path,"-rotate",self.params.breakangle,"+repage",self.params.url.path] + self._call_cmd(cmd) + + def _rotate_back(self): + angle = str(360-int(self.params.breakangle)) + cmd = [BIN_CONVERT,self.filepath,"-rotate",angle,"+repage",self.filepath] + self._call_cmd(cmd) + if not self.params.expanded: + cmd = [BIN_CONVERT,self.filepath,"-gravity","Center","-crop","{}x{}+0+0".format( + self.width, self.height),"+repage",self.filepath] + self._call_cmd(cmd) +#}}} + + def _subtle_break(self): + #assume the header is no longer than _header_offset bytes + breakpoint = random.randint(_header_offset, len(self._file_data)) + newfile = self._file_data[0:breakpoint] \ + + _subtle_break_mark \ + + self._file_data[breakpoint:] + self._file_data = newfile[0:len(self._file_data)] + + def _extreme_break(self): + increment = len(self._file_data)/10; + i = 0 + newfile = ""; + for b in self._file_data: + if i > _header_offset and not (i % increment): + b += _extreme_break_mark + newfile += b + i += 1 + self._file_data = newfile[0:len(self._file_data)] + + + def _enforce_jpg(self): + if self.params.breaktype in [ "exr", "bmp", "miff" ] and not re.match(r'jpe?g$', self.params.url.mimetype, re.IGNORECASE): + jpg_file = self._tempfilepath_create(extension="jpg") + self._call_cmd([BIN_CONVERT,self.params.url.path, jpg_file]) + self._files_created.append(jpg_file) + self._conversion_file = jpg_file + + def _first_conversion(self): + if self.params.url.mimetype == self.params.breaktype: + self._conversion_file = self.params.url.path + return + self._call_cmd([BIN_CONVERT, self.params.url.path, self._conversion_file]) + self._files_created.append(self._conversion_file) + + def _prepare_filedata(self): + if self.params.url.mimetype == "gif" and self.params.breaktype not in [ 'mat', 'psd' ]: + self._choose_gif_frame(self.params.url.path) + if self.params.breakangle: + self._rotate() + self._enforce_jpg(); + self._first_conversion(); + self._file_data = self._file_read(self._conversion_file) + if not self._file_data: + self.err_warn("Unable to get file data"); + + def _add_false_data(self): + if self.params.breakmode == "subtle": + self._subtle_break() + elif self.params.breakmode == "extreme": + self._extreme_break() + f = open(self._conversion_file, 'w') + f.write(self._file_data) + f.close(); + + def _final_conversion(self): + self._call_cmd( [BIN_CONVERT, self._conversion_file, self.filepath]) + def psd_psbfilepath(num): + return os.path.join(re.sub(r'\.', "-%s." % num, self.filepath)) + if str(self.params.breaktype) == 'psd': + self._call_cmd(['mv', psd_psbfilepath(1), self.filepath]) + self._files_created.append(psd_psbfilepath(0)) + if str(self.params.breaktype) == 'psb': + self._call_cmd(['mv', psd_psbfilepath(0), self.filepath]) + self._files_created.append(psd_psbfilepath(1)) + if self.params.breakangle: + self._rotate_back() + + def create(self): + self._prepare_filedata(); + self._add_false_data(); + self._final_conversion() + self._cleanup() + diff --git a/lib/Pb/Break/__init__.py~ b/lib/Pb/Break/__init__.py~ new file mode 100755 index 0000000..c1064e2 --- /dev/null +++ b/lib/Pb/Break/__init__.py~ @@ -0,0 +1,205 @@ +#!/usr/bin/python2.7 +import os +import sys +import random +import re +import urllib +import inspect +from Config import * +from Pb import Pb +from Pb.Params import Params + +DEFAULT_FINALFORMAT = "png"; +SUBTLE_BREAK_MARK = 'pron' +EXTREME_BREAK_MARK = 'sugar' + +HEADER_OFFSET = 2000 + +class Breaker(Pb): + def __init__(self, url=None, breaktype=None, finalformat=DEFAULT_FINALFORMAT, + breakmode=None, breakangle=None, username=None, expanded=None, firsttime=None): + super(Breaker,self).__init__(); + + self.params.breaktype = self._get_breaktype(breaktype); + self.params.url = url + + _frame = inspect.currentframe(); + _args_vals = inspect.getargvalues(_frame); + for arg in _args_vals.args: + if arg == "self": + continue + sys.stderr.write(str(arg) + "\n") + try: + if arg not in ['breaktype', 'url']: + sys.stderr.write("Yoooo"); + sys.stderr.write(arg) + strarg = str(_args_vals.locals.get(arg)) + django self.bool_correct(strarg) + self.params.__setattr__("dingo", django) +# self.params.__setattr__(arg, self.bool_correct(_args_vals.locals.get(arg))) + except Exception as e: + sys.stderr.write("\n"+str(e)+"\n") + sys.exit(1); + self.params = Params(**self.params); + + self.tag = "imBreak" + self.commands = []; + self._now = self.now() + self.files_created = [] + + self.basename, self._first_format = self._get_filename_and_type_from_url(); + self._downloaded_file = self.tempname_create(basename=self.basename, fmt=self._first_format) + + try: + self.download(self.params.url, self._downloaded_file) + self.files_created.append(self._downloaded_file) + except Exception as e: + self.err_warn(str(e)) + + self._gif_frames = self.gif_frames(self._downloaded_file) + self._gif_frames = self._gif_frames if len(self._gif_frames) > 1 else False + self.width, self.height = self.dimensions(self._downloaded_file) # same here + + if not self.params.finalformat and self._gif_frames: + self.params.finalformat = 'gif' + if self.params.breaktype == 'miff': + self.params.finalformat = 'jpg' + self.params.breakmode = 'subtle' + #final filepath is stored in self.filepath + self.filename = "{}.{}".format(self.basename, self.params.finalformat) + self.filepath = os.path.join(self._working_dir, self.filename) + self._conversion_file = self.tempname_create(basename=self.basename, fmt=self.params.breaktype); + + def _call_cmd(self, cmd): + super(Breaker,self)._call_cmd(cmd, error) + self.commands.append(" ".join(cmd)); + + def _get_breaktype(self, key): + #{{{ conversion table + breaktypeTranslate = { + 'CLASSIC':'jpg', + 'REDUX':'pcds', + 'BLURRY_BREAK':'viff', + 'BLURRY_BREAK_2':'mat', + 'SWIPE':'miff', + 'RGB_WASH':'psd', + 'RGB_WASH_2':'psb', + 'NOISY_BREAK':'palm', + 'NOISY_BREAK_2':'fig', + 'BROKEN_VIGNETTE':'pbm', + 'FAX_MACHINE':'cals', + 'STRIPES':'exr', + 'PHOTOCOPY':'art', + } + #}}} + return breaktypeTranslate[key] + +#{{{#########rotatefunctions####################################### + def _rotate(self): + cmd = [BIN_CONVERT,self._downloaded_file,"-rotate",self.params.breakangle,"+repage",self._downloaded_file] + self._call_cmd(cmd) + + def _rotate_back(self): + angle = str(360-int(self.params.breakangle)) + cmd = [BIN_CONVERT,self.filepath,"-rotate",angle,"+repage",self.filepath] + self._call_cmd(cmd) + if not self.params.expanded: + cmd = [BIN_CONVERT,self.filepath,"-gravity","Center","-crop","{}x{}+0+0".format( + self.width, self.height),"+repage",self.filepath] + self._call_cmd(cmd) +#}}} + def _subtle_break(self): + #assume the header is no longer than HEADER_OFFSET bytes + breakpoint = random.randint(HEADER_OFFSET, len(self.file_data)) + newfile = self.file_data[0:breakpoint] \ + + SUBTLE_BREAK_MARK \ + + self.file_data[breakpoint:] + self.file_data = newfile[0:len(self.file_data)] + + def _extreme_break(self): + increment = len(self.file_data)/10; + i = 0 + newfile = ""; + for b in self.file_data: + if i > HEADER_OFFSET and not (i % increment): + b += EXTREME_BREAK_MARK + newfile += b + i += 1 + self.file_data = newfile[0:len(self.file_data)] + + def _choose_frame(self): + frame = random.choice(self._gif_frames) + self._call_cmd([BIN_CONVERT, frame, self._downloaded_file]) + + def _enforce_jpg(self): + if self.params.breaktype in [ "exr", "bmp", "miff" ] and not re.match(r'jpe?g$', self._first_format, re.IGNORECASE): + jpg_file = self.tempname_create(basename=self.basename, fmt="jpg") + self._call_cmd([BIN_CONVERT,self._downloaded_file,jpg_file]) + self._call_cmd(["rm",self._downloaded_file]) + self._downloaded_file = jpg_file + + def _first_conversion(self): + if self._first_format == self.params.breaktype: + self._downloaded_file = self._conversion_file + return + self._call_cmd([BIN_CONVERT, self._downloaded_file, self._conversion_file]) + self.files_created.append(self._conversion_file) + + def _prepare_filedata(self): + if self._gif_frames: + self._choose_frame() + if self.params.breakangle: + self._rotate() + self._enforce_jpg(); + self._first_conversion(); + self.file_data = self._file_read(self._conversion_file) + if not self.file_data: + self.err_warn("Unable to get file data"); + + def _add_false_data(self, breakmode): + if breakmode == "subtle": + self._subtle_break() + elif breakmode == "extreme": + self._extreme_break() + f = open(self._conversion_file, 'w') + f.write(self.file_data) + f.close(); + + def _final_conversion(self): + self._call_cmd( [BIN_CONVERT, self._conversion_file, self.filepath]) + def psd_psbfilepath(num): + return os.path.join(self._working_dir, "{}-{}.{}".format(self.basename, num, self.params.finalformat)) + if self.params.breaktype == 'psd': + self._call_cmd(['mv', psd_psbfilepath(1), self.filepath]) + self.files_created.append(psd_psbfilepath(0)) + if self.params.breaktype == 'psb': + self._call_cmd(['mv', psd_psbfilepath(0), self.filepath]) + self.files_created.append(psd_psbfilepath(1)) + if self.params.breakangle: + self._rotate_back() + + def _cleanup(self): + cmd = ["rm"]+self.files_created + self._call_cmd(cmd) + + def create(self, breakmode=""): + if not breakmode: breakmode = self.params.breakmode + self._prepare_filedata(); + self._add_false_data(breakmode); + self._final_conversion() + self._cleanup() + + @classmethod + def test(cls): + TEST_PARAMS = { + "url" : "http://i.asdf.us/im/27/1424816234661dumpfmpfifferkinggr_1424816412_pfifferking.gif" , + "breaktype" : "RGB_WASH", + "finalformat" : "png", + "breakmode" : "extreme", + "breakangle" : "10", + "username" : "donkey", + "expanded" : "false" + } + b = cls(**TEST_PARAMS) + b.create(); + print b.filepath |
