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
|
import re
from Config import *
import time
import urllib
import urllib2
import sys
import os
from subprocess import Popen,PIPE,call
Request = urllib2.Request
urlencode = urllib.urlencode
urlopen = urllib2.urlopen
class Pb(object):
def __init__(self):
pass;
@staticmethod
def call_cmd(cmd, error=""):
try:
call(cmd)
except Exception as e:
raise (str(e))
@staticmethod
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
@staticmethod
def dimensions (filepath):
#works in lieu of a mimetype check (it reads the header as well)
ident = (Popen([BIN_IDENTIFY, filepath], stdout=PIPE).communicate()[0]).split(" ")
return ident[2].split("x")
@staticmethod
def is_number(s):
try:
return int(s)
except (ValueError, TypeError):
return False
@staticmethod
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
@staticmethod
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("couldn't determine mimetype")
sys.stderr.write(str(e))
raise;
@staticmethod
def sanitize (s):
return re.sub(r'\W+', '', s)
@staticmethod
def now():
return int(time.time())
@staticmethod
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(self, url, destination, max_size=MAX_SIZE):
response = self.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()
@staticmethod
def file_size (filepath):
try:
return os.stat(filepath)[6]
except Exception as e:
sys.stderr.write("Couldn't determine filesize\n")
sys.stderr.write(str(e)+"\n")
raise;
def gif_frames(self, 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("{} couldn't get gif frames".format(self.__class__.__name__))
sys.stderr.write(str(e))
raise;
@staticmethod
def make_dotdict(d):
return dotdict(d)
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
def __getattr__(self, attr):
return self.get(attr)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
|