Created
November 4, 2013 18:56
-
-
Save akx/7307462 to your computer and use it in GitHub Desktop.
Exploring cairocffi/#22
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cairocffi as cairo | |
import hashlib | |
from cStringIO import StringIO | |
from collections import Counter | |
import threading, sys, traceback, time | |
class ImageGenerator(object): | |
def __init__(self, text): | |
self.text = text | |
def render(self, context): | |
with context: | |
context.set_source_rgb(1, 1, 1) | |
context.paint() | |
for y in xrange(0, 255, 5): | |
with context: | |
context.select_font_face("Arial") | |
context.set_font_size(10 + y % 25) | |
context.set_source_rgb(y / 256.0, y / 512.0, 0) | |
context.move_to(y * 2, (y * 3) % 300) | |
context.rotate(y * 1.5705) | |
context.show_text(self.text) | |
def get_output(self): | |
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 400, 300) | |
context = cairo.Context(surface) | |
self.render(context) | |
sio = StringIO() | |
surface.write_to_png(sio) | |
return sio.getvalue() | |
hashes = Counter() | |
tracebacks = Counter() | |
outputs = {} | |
def render(n): | |
for x in xrange(n): | |
ig = ImageGenerator("derp") | |
try: | |
output = ig.get_output() | |
hash = hashlib.md5(output).hexdigest() | |
if hash not in outputs: | |
outputs[hash] = output | |
except: | |
tb = traceback.format_exc() | |
tracebacks[tb] += 1 | |
hash = "Exception:%s" % sys.exc_info()[1] | |
hashes[hash] += 1 | |
return hash | |
def thread_test(): | |
correct_hash = render(1) | |
threads = [] | |
for x in xrange(5): | |
th = threading.Thread(target=render, args=(50,)) | |
threads.append(th) | |
th.start() | |
time.sleep(0.05) | |
for th in threads: | |
th.join() | |
print "correct hash:", correct_hash | |
for hash, count in hashes.most_common(): | |
print "%-80s %8d" % (hash, count) | |
for hash, output_data in outputs.iteritems(): | |
with file("%s%s.png" % ("CORRECT-" if hash == correct_hash else "", hash), "wb") as outf: | |
outf.write(output_data) | |
for traceback, count in tracebacks.most_common(5): | |
print "=" * 40 | |
print traceback | |
if __name__ == '__main__': | |
thread_test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment