diff options
| -rwxr-xr-x | Pb/Breaker/__init__.py | 190 | ||||
| -rw-r--r-- | Pb/Params/__init__.py | 8 | ||||
| -rw-r--r-- | Pb/__init__.py | 49 |
3 files changed, 102 insertions, 145 deletions
diff --git a/Pb/Breaker/__init__.py b/Pb/Breaker/__init__.py index 262ac4f..14e33b5 100755 --- a/Pb/Breaker/__init__.py +++ b/Pb/Breaker/__init__.py @@ -4,8 +4,10 @@ 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' @@ -13,82 +15,53 @@ EXTREME_BREAK_MARK = 'sugar' HEADER_OFFSET = 2000 -# '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', - class Breaker(Pb): - def __init__(self, **kwargs): - self.params = {} + def __init__(self, url=None, breaktype=None, finalformat=DEFAULT_FINALFORMAT, + breakmode=None, breakangle=None, username=None, expanded=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 not in ['breaktype', 'url']: + self.params.__setattr__(arg, self.bool_correct(_args_vals.locals[arg])) + + self.params = Params(**self.params); + self.tag = "imBreak" self.commands = []; - self._required_keys = [ - "url", - "breaktype", - "finalformat", - "breakmode", - "breakangle", - "username", - "expanded" - ] self._now = self.now() self.files_created = [] - for k in self._required_keys: - if k in kwargs: - if k == 'breaktype': - self.params['breaktype'] = self._get_breaktype(kwargs[k]) - elif k == 'url': - self.params[k] = kwargs[k] - else: - self.params[k] = self.bool_correct(self.sanitize(kwargs[k])) - else: - self.params[k] = False; - - - self.params = self.make_dotdict(self.params) - self.basename, self._first_format = self._get_filename(); - self._downloaded_file = os.path.join(WORKING_DIR, "IMBREAKTMP{}.{}".format(self.basename, self._first_format)) # same here + 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: - sys.stderr.write(str(e)) - raise; + 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: - self.params.finalformat = DEFAULT_FINALFORMAT - if self._gif_frames: - self.params.finalformat = 'gif' + 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(WORKING_DIR, self.filename) - self._conversion_file = os.path.join(WORKING_DIR, "IMBREAKTMP{}.{}".format(self.basename, self.params.breaktype)) # this - + 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, error=""): - try: - self.call_cmd(cmd) - self.commands.append(" ".join(cmd)); - except Exception: - raise Exception("Unable to call cmd {}".format(str(cmd))) + def _call_cmd(self, cmd): + super(Breaker,self)._call_cmd(cmd, error) + self.commands.append(" ".join(cmd)); def _get_breaktype(self, key): #{{{ conversion table @@ -109,32 +82,6 @@ class Breaker(Pb): } #}}} return breaktypeTranslate[key] - - def _get_filename (self): - url = self.params.url - name_part = ""; - file_format = ""; - if "?" in url: - url = url.split("?")[0] - if "/" in url: - url = urllib.unquote(url).replace(" ","") - name_part = url.split("/")[-1] - try: - parts = name_part.split(".") - name_part = self.sanitize(parts[-2]) - file_format = self.sanitize(parts[-1]) - if not name_part or not file_format: - sys.stderr.write( "Incompatible input file type") - raise; - except Exception as e: - sys.stderr.write( "Incompatible input file type") - raise; - else: - sys.stderr.write( "Incompatible url") - raise; - if (len(name_part) > 20): - name_part = name_part[:-20] - return "{}{}_{}_{}".format(self.tag, name_part, self._now, self.params.username or ""), file_format #{{{#########rotatefunctions####################################### def _rotate(self): @@ -153,10 +100,9 @@ class Breaker(Pb): def _subtle_break(self): #assume the header is no longer than HEADER_OFFSET bytes breakpoint = random.randint(HEADER_OFFSET, len(self.file_data)) - newfile = "" - newfile = self.file_data[0:breakpoint]; - newfile += SUBTLE_BREAK_MARK; - newfile += self.file_data[breakpoint:] + 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): @@ -172,32 +118,22 @@ class Breaker(Pb): def _choose_frame(self): frame = random.choice(self._gif_frames) - cmd = [BIN_CONVERT, frame, self._downloaded_file] - self._call_cmd(cmd) + 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 = os.path.join(WORKING_DIR, "{}.{}".format(self.basename, "jpg")) - cmd = [BIN_CONVERT,self._downloaded_file,jpg_file] - self._call_cmd(cmd) - cmd = ["rm",self._downloaded_file] - self._call_cmd(cmd) - + 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 - cmd = [BIN_CONVERT, self._downloaded_file, self._conversion_file] - self._call_cmd(cmd) + self._call_cmd([BIN_CONVERT, self._downloaded_file, self._conversion_file]) self.files_created.append(self._conversion_file) - def _read_data(self, filepath): - f = open(filepath, 'r'); - data = f.read() - f.close() - return data - def _prepare_filedata(self): if self._gif_frames: self._choose_frame() @@ -205,10 +141,9 @@ class Breaker(Pb): self._rotate() self._enforce_jpg(); self._first_conversion(); - self.file_data = self._read_data(self._conversion_file) + self.file_data = self._file_read(self._conversion_file) if not self.file_data: - sys.stderr.write("Unable to get file_data") - raise; + self.err_warn("Unable to get file data"); def _add_false_data(self, breakmode): if breakmode == "subtle": @@ -219,26 +154,16 @@ class Breaker(Pb): f.write(self.file_data) f.close(); -#{{{ SHRINK (UNUSED) - def _shrink(self): - cmd = [ BIN_CONVERT, "-resize", "500x500", self._downloaded_file, self._downloaded_file ]; - self._call_cmd(cmd) -#}}} - def _final_conversion(self): - cmd = [BIN_CONVERT, self._conversion_file, self.filepath] - self._call_cmd(cmd) + self._call_cmd( [BIN_CONVERT, self._conversion_file, self.filepath]) def psd_psbfilepath(num): - return os.path.join(WORKING_DIR, "{}-{}.{}".format(self.basename, num, self.params.finalformat)) + return os.path.join(self._working_dir, "{}-{}.{}".format(self.basename, num, self.params.finalformat)) if self.params.breaktype == 'psd': - cmd = ['mv', psd_psbfilepath(1), self.filepath] - self._call_cmd(cmd) + self._call_cmd(['mv', psd_psbfilepath(1), self.filepath]) self.files_created.append(psd_psbfilepath(0)) if self.params.breaktype == 'psb': - cmd = ['mv', psd_psbfilepath(0), self.filepath] - self._call_cmd(cmd) + self._call_cmd(['mv', psd_psbfilepath(0), self.filepath]) self.files_created.append(psd_psbfilepath(1)) - if self.params.breakangle: self._rotate_back() @@ -253,16 +178,17 @@ class Breaker(Pb): self._final_conversion() self._cleanup() -if __name__ == "__main__": - 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 = Breaker(**TEST_PARAMS) - b.create(); - print b.filepath + @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 diff --git a/Pb/Params/__init__.py b/Pb/Params/__init__.py new file mode 100644 index 0000000..114b117 --- /dev/null +++ b/Pb/Params/__init__.py @@ -0,0 +1,8 @@ +class Params(object): + def __init__(self, **kwargs): + for key, value in kwargs.items(): + setattr(self, key, value) + def __getattr__(self, attr): + return self.get(attr, None) + + diff --git a/Pb/__init__.py b/Pb/__init__.py index f584f00..5e5aa65 100644 --- a/Pb/__init__.py +++ b/Pb/__init__.py @@ -5,7 +5,9 @@ import urllib import urllib2 import sys import os +import random from subprocess import Popen,PIPE,call +from Pb.Params import Params Request = urllib2.Request urlencode = urllib.urlencode urlopen = urllib2.urlopen @@ -13,14 +15,15 @@ urlopen = urllib2.urlopen class Pb(object): def __init__(self): - pass; + self.params = Params(); + self._working_dir = WORKING_DIR - @staticmethod - def call_cmd(cmd, error=""): + def _call_cmd(self, cmd): try: call(cmd) except Exception as e: - raise (str(e)) + self.err_warn("Could not call cmd: {}".format(str(cmd))) + self.err_warn(str(e)) @staticmethod def is_color(s): @@ -130,14 +133,34 @@ class Pb(object): sys.stderr.write(str(e)) raise; - @staticmethod - def make_dotdict(d): - return dotdict(d) + def tempname_create(self, basename=None, fmt="png"): + if not basename: basename = self.random_string_create() + return os.path.join(self._working_dir, "{}{}.{}".format(self.__class__.__name__, basename, fmt)) # this + + def _get_filename_and_type_from_url (self, url): + name = re.sub(r'(?:\s|\?.*|.*/)', '', urllib.unquote(url)); + try: + basename, ext = map(lambda s: self.santize(s), re.search(r'(^.*)\.(.*$)', name).groups()); + except Exception as e: + self.err_warn("Incompatible input file type") + if (len(name_part) > 20): + name_part = name_part[:-20] + return "{}{}_{}_{}".format(self.tag, basename, self._now, self.params.username or ""), ext + + def random_string_create(self): + return "{}".format(random.uniform(0, 100000)); + + + def _file_read(self, filepath): + f = open(filepath, 'r'); + data = f.read() + f.close() + return data -class dotdict(dict): - """dot.notation access to dictionary attributes""" - def __getattr__(self, attr): - return self.get(attr) - __setattr__= dict.__setitem__ - __delattr__= dict.__delitem__ + def err_warn(self, s): + sys.stderr.write("ERROR:{} - {}\n".format(self.__class__.__name__, s)) + + def err_fatal(self, s): + sys.stderr.write("ERROR[FATAL]:{} - {}\n".format(self.__class__.__name__, s)) + sys.exit(1); |
