-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththwart_utils.py
executable file
·256 lines (183 loc) · 7.23 KB
/
thwart_utils.py
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import os
import os.path
from subprocess import Popen
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson
import copy
import random
from chiplotle import *
from chiplotle.hpgl.commands import PA, PR, PU, PD, IN, SP
# tranpose, rotate, scale and return munged copy
# connect is whether or not we insert PU/PD between chunks to avoid connection lines
def munge(orig, steps = 10, connect = False):
i = 0
i_incr = 1
i_float_incr = i_incr * (1.0 / steps)
len_cleaned = len(orig)
bounds = tools.hpgltools.get_bounding_box(orig)
width = bounds[1].x - bounds[0].x
height = bounds[1].y - bounds[0].y
print "w:", width, "h:", height
munged = []
#copy.deepcopy(orig)
while i < steps:
i_float = i * i_float_incr
start = int(len_cleaned * i_float)
end = int(len_cleaned * (i_float + i_float_incr))
#print "start:", start, "end:", end
chunk = copy.deepcopy(orig[start:end])
tools.hpgltools.transpose(chunk, [random.randint(0,int(width * 0.25)), random.randint(0, int(width * 0.25))])
tools.hpgltools.rotate_hpglprimitives(chunk, random.randint(0,360))
tools.hpgltools.scale(chunk, random.random() + 0.5)
if not connect:
first = -1
j = 0
while first < 0:
if isinstance(chunk[j], (PA, PR)):
first = j
else:
j += 1
chunk.insert(j, PU())
chunk.insert(j + 2, PD())
#print chunk[j], chunk[j+1], chunk[j+2]
munged.extend(chunk)
i += i_incr
return munged
# get list of pu/pd/pa commands from file
def clean_commands_from_file(filename):
hpgl_commands = tools.io.import_hpgl_file(filename)
stripped_hpgl_commands = tools.hpgltools.pens_updown_to_papr(hpgl_commands)
cleaned = []
for command in stripped_hpgl_commands:
if isinstance(command, (PU, PD, PA, PR)):
cleaned.append(command)
return cleaned
# the whole enchilada
def search_to_hpgl(search_term, save_dir = "./", num_sets = 1):
if not save_dir.endswith("/"):
save_dir += "/"
images = get_images(search_term, save_dir, num_sets)
image_num = 0
saved_filenames = []
for image in images:
out_filename = save_dir + search_term + "_" + str(image_num) + ".hpgl"
file_saved = image_to_hpgl(image, out_filename)
if file_saved == None:
print "uh oh, couldn't save", out_filename
else:
saved_filenames.append(file_saved)
image_num += 1
return saved_filenames
'''
search for images
'''
def get_images(search_term, save_dir = "./", num_sets = 1):
# Replace spaces ' ' in search term for '%20' in order to comply with request
search_term = search_term.replace(' ','%20')
myopener = MyOpener()
# make sure our save_dir is gonna work right...
if not os.path.exists(save_dir):
#print "making:", save_dir
os.makedirs(save_dir)
if not save_dir.endswith("/"):
save_dir += "/"
save_filenames = []
# Set count to 0
count= 0
for i in range(0,num_sets):
# Notice that the start changes for each iteration in order to request a new set of images for each loop
url = ('https://ajax.googleapis.com/ajax/services/search/images?' + 'v=1.0&q='+search_term+'&start='+str(i*4)+'&userip=MyIP'+'&imgtype=lineart')
#print url
request = urllib2.Request(url, None, {'Referer': 'testing'})
response = urllib2.urlopen(request)
# Get results using JSON
results = simplejson.load(response)
data = results['responseData']
dataInfo = data['results']
# Iterate for each result and get unescaped url
# i think these are always sets of four images
for myUrl in dataInfo:
count = count + 1
#print "URL:", myUrl['unescapedUrl']
ending = myUrl['url'].split('.')[-1]
# in case there's weird stuff after then file type
ending = ending[0:3]
out_filename = save_dir + str(count)+"." + ending
#print "saving:", out_filename
myopener.retrieve(myUrl['unescapedUrl'], out_filename)
save_filenames.append(out_filename)
# Sleep for one second to prevent IP blocking from Google
time.sleep(1)
return save_filenames
# Start FancyURLopener with defined version
class MyOpener(FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
'''
convert images to hpgl code
'''
def image_to_hpgl(in_file, out_file):
#print "converting", in_file, "to hpgl..."
out_path = os.path.dirname(out_file)
saved_bmp = image_to_bmp(in_file, out_path + "/tmp.bmp")
if saved_bmp == None:
print "couldn't do image_to_bmp() for", in_file
return None
#print "saved:", saved_bmp
saved_bmpbmp = bmp_to_bmpbmp(saved_bmp, out_path + "/tmp.bmp.bmp")
if saved_bmpbmp == None:
print "couldn't do bmp_to_bmpbmp() for", saved_bmp
return None
#print "saved:", saved_bmpbmp
saved_eps = bmpbmp_to_eps(saved_bmpbmp, out_path + "/tmp.eps")
if saved_eps == None:
print "couldn't do bmpbmp_to_eps() for", saved_bmpbmp
return None
#print "saved:", saved_eps
saved_hpgl = eps_to_hpgl(saved_eps, out_file)
if saved_hpgl == None:
print "couldn't do eps_to_hpgl() for", saved_eps
return None
#print "saved:", saved_hpgl
os.remove(saved_bmp)
os.remove(saved_bmpbmp)
os.remove(saved_eps)
return saved_hpgl
# sips -s format bmp images/1.jpg --out images/1.bmp
def image_to_bmp(in_file, out_file):
# sips doesn't like ./ notation in paths!?!
#print "doing:", in_file, out_file
p = Popen(["sips", "-s", "format", "bmp", in_file, "--out", out_file])
p.communicate()
if not os.path.exists(out_file):
print "operation failed for", out_file
return None
return out_file
# mkbitmap -f 2 -s 2 -t 0.48 -o images/1.bmp.bmp images/1.bmp
def bmp_to_bmpbmp(in_file, out_file):
#print "bmp_to_bmpbmp doing:", in_file, out_file
p = Popen(["mkbitmap", "-f", "2", "-s", "1", "-t", "0.48", "-o", out_file, in_file])
p.communicate()
if not os.path.exists(out_file):
print "operation failed for", out_file
return None
return out_file
# potrace -t 5 images/1.bmp.bmp -o images/1.eps
def bmpbmp_to_eps(in_file, out_file):
#print "bmpbmp_to_eps doing:", in_file, out_file
p = Popen(["potrace", "-t", "5", in_file, "-o", out_file])
p.communicate()
if not os.path.exists(out_file):
print "operation failed for", out_file
return None
return out_file
# pstoedit -f hpgl images/1.eps images/1.hpgl
def eps_to_hpgl(in_file, out_file):
p = Popen(["pstoedit", "-f", "hpgl", in_file, out_file])
p.communicate()
if not os.path.exists(out_file):
print "operation failed for", out_file
return None
return out_file