summaryrefslogtreecommitdiff
path: root/imgrid.py
diff options
context:
space:
mode:
authoryo mama <pepper@scannerjammer.com>2015-04-30 15:08:01 -0700
committeryo mama <pepper@scannerjammer.com>2015-04-30 15:08:01 -0700
commit03f45bb4225740f2ebe4adfd8de24f67d33ee0e3 (patch)
treef555265c798f7d1dff25315e79eb90055f4bab74 /imgrid.py
parentda8255b0ad5703837c315c082a6f69edc47754a7 (diff)
good
Diffstat (limited to 'imgrid.py')
-rwxr-xr-ximgrid.py198
1 files changed, 40 insertions, 158 deletions
diff --git a/imgrid.py b/imgrid.py
index ece50b0..e294066 100755
--- a/imgrid.py
+++ b/imgrid.py
@@ -1,136 +1,20 @@
#!/usr/bin/python2.7
-
import sys
import re
import os
-import string
import simplejson as json
import random
-import time
-import urllib
-import urllib2
-from subprocess import Popen,PIPE,call
-urlencode = urllib.urlencode
-urlopen = urllib2.urlopen
-Request = urllib2.Request
-
-MAX_SIZE = 1024 * 1024 * 1.2 * 1.5
-WORKING_DIR = "/var/www/cache"
-#WORKING_DIR = "/tmp"
-
-BIN_CONVERT = "/usr/bin/convert"
-BIN_COMPOSITE = "/usr/bin/composite"
-BIN_IDENTIFY = "/usr/bin/identify"
-THREEDROTATE = "./3Drotate"
-GRID = "./grid"
-DB_TAG = "grid";
+import lib.utils as utils
+from config import *
+import tempfile
DEFAULT_HEIGHT = 400
DEFAULT_WIDTH = 600
DEFAULT_LINE_COLOR = "silver"
-DEFAULT_FINALFORMAT = "png"
-
-#{{{Utility functions
-def is_color(s):
- if s == "":
- return "transparent"
- if re.match('(rgba?\([0-9]+,[0-9]+,[0-9]+\))|([a-zA-Z]+)|(\#[A-Ha-h0-9]+)', s):
- return s.replace(' ', '');
- else:
- sys.stderr.write("Not a color: {}\n".format(s))
- raise ValueError
-def bool_correct(s):
- if re.match(r'^false$', s, re.IGNORECASE):
- return False
- elif re.match(r'^true$', s, re.IGNORECASE):
- return True
- else:
- return s
-
-class dotdict(dict):
- """dot.notation access to dictionary attributes"""
- def __getattr__(self, attr):
- return self.get(attr)
- __setattr__= dict.__setitem__
- __delattr__= dict.__delitem__
-
-def get_mimetype(f):
- try:
- mimetype = Popen(
- [BIN_IDENTIFY, f], stdout=PIPE
- ).communicate()[0].split(" ")[1].lower()
- return mimetype
- except Exception as e:
- sys.stderr.write("IMGRID couldn't determine mimetype")
- sys.stderr.write(str(e))
- raise;
-
-def sanitize (str):
- return re.sub(r'\W+', '', str)
-
-def now():
- return int(time.time())
-
-def browser_request (url, data=None):
- headers = {
- 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
- 'Accept': '*/*',
- }
- try:
- req = Request(url, data, headers)
- response = urlopen(req)
- except IOError, e:
- if hasattr(e, 'code'):
- sys.stderr.write( '%s - ERROR %s' % (url, e.code) )
- raise;
- return None
- else:
- return response
-
-def download(url, destination, max_size=MAX_SIZE):
- response = browser_request(url, None)
- rawimg = response.read()
- if len(rawimg) == 0:
- sys.stderr.write("got zero-length file")
- raise;
- if len(rawimg) > max_size:
- sys.stderr.write("file too big: max size {} KB / {} is {} KB".format(
- str(MAX_SIZE/1024),
- destination,
- str(len(rawimg)/1024)
- ))
- raise;
- f = open(destination, "w")
- f.write(rawimg)
- f.close()
-
-def file_size (filepath):
- try:
- return os.stat(file)[6]
- except Exception as e:
- sys.stderr.write("IMGRID couldn't determine file size")
- sys.stderr.write(str(e))
- raise;
-
-def gif_frames(filepath):
- try:
- info = Popen([BIN_IDENTIFY,filepath], stdout=PIPE).communicate()[0]
- frames = filter((lambda x: x), map(
- (lambda x: x.split(" ")[0]),
- (info).split('\n')
- ))
- return frames
- except Exception as e:
- sys.stderr.write("IMGRID couldn't get gif frames")
- sys.stderr.write(str(e))
- raise;
-#}}}
class Imgrid():
- def __init__(self, params):
- self.params = {}
+ def __init__(self, **kwargs):
self.tag = "imGrid"
- self.now = now()
self.files_created = []
self.commands = [];
self._required_keys = [
@@ -160,47 +44,48 @@ class Imgrid():
"username"
#}}}
]
+
+ #Work out params ...
+ #note, tmpfile lib is pretty much useless here, given imagemagick's behavior with gifs (it splits them) etc...
+ #instead we're just making our own in /var/www/cache (tmpfs mounted there)
+ self.params = {}
for k in self._required_keys:
- if k in params:
- if k in [ 'bgimage', 'planebgimage', 'imageinstead' ] and bool_correct(params[k]):
- self.params[k] = {}
- self.params[k]['url'] = params[k]
- self.params[k]['filename'] = "IMGRIDTMP{}_{}".format(now(), k)
-
- self.params[k]['path'] = os.path.join(WORKING_DIR, self.params[k]['filename'])
+ if k in kwargs:
+ if k in [ 'bgimage', 'planebgimage', 'imageinstead' ] 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:
- download(self.params[k]['url'], self.params[k]['path'])
+ utils.download(self.params[k]['url'], self.params[k]['path'])
self.files_created.append(self.params[k]['path'])
- self.params[k]['mimetype'] = get_mimetype(self.params[k]['path'])
- frames = gif_frames(self.params[k]['path'])
+ self.params[k]['mimetype'] = utils.get_mimetype(self.params[k]['path'])
+ frames = utils.gif_frames(self.params[k]['path'])
if len(frames) > 1:
self.params[k]['path'] = random.choice(frames)
-
- except Exception as e:
- sys.stderr.write("BAD PARAMS\n")
+ except Exception:
sys.stderr.write(str(e))
- raise;
+ raise Exception ("BAD PARAMS");
elif k in [ 'skycolor', 'bgcolor', 'planebgcolor','linecolor' ]:
try:
self.params[k] = is_color(params[k])
- except Exception as e:
- sys.stderr.write("Unable to process color for:\n")
- sys.stderr.write(k)
- raise e
+ except Exception:
+ raise Exception("Unable to process color for:\n{}".format(k))
elif k == 'opacity':
self.params[k] = str(float(params[k]))
elif k == 'zoom':
self.params[k] = int(float(params[k]))
else:
- self.params[k] = bool_correct(sanitize(params[k]))
+ self.params[k] = utils.bool_correct(utils.sanitize(kwargs[k]))
else:
- self.params[k] = False;
-
- self.params = dotdict(self.params)
+ self.params[k] = None;
+
+ self.params = utils.dotdict(self.params)
self.basename = self._get_filename();
-
+
if not self.params.finalformat:
self.params.finalformat = DEFAULT_FINALFORMAT
self.filename = "{}.{}".format(self.basename, self.params.finalformat)
@@ -210,21 +95,20 @@ class Imgrid():
def _get_filename(self):
return "{}_{}_{}".format(
self.tag,
- now(),
+ utils.now(),
self.params.username or ""
);
- def _call_cmd(self, cmd, error=""):
- try:
- call(cmd)
- self.commands.append(" ".join(cmd));
- except Exception as e:
- sys.stderr.write("IT HIT AN ERROR")
- sys.stderr.write(str(cmd))
- if error:
- sys.stderr.write(error)
- else:
- sys.stderr.write(str(e))
+ 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 _make_tempname(self, s):
+ return "IMGRIDTMP{}{}".format(utils.now(), s);
+
#makes a canvas file...step 1 (if not bgimage)
def _make_canvas(self):
@@ -332,7 +216,7 @@ class Imgrid():
self._cleanup()
if __name__ == "__main__":
- g = Imgrid({
+ g = Imgrid(**{
'bgimage' : 'http://i.asdf.us/im/1a/imBreak_1424909483_xx_abridged___.gif',
'planebgimage' : 'http://i.imgur.com/FICZtph.png',
'tilt' : '30',
@@ -343,6 +227,4 @@ if __name__ == "__main__":
'trim' : 'true'
})
g.create()
- print g.now
- print g.filepath
print g.commands