-
-
Save lexman/37b0ca6784561f28293496feafec12f9 to your computer and use it in GitHub Desktop.
My solution for Drivy dontclickhere riddle
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
#!/usr/bin/env python | |
import sys | |
from StringIO import StringIO | |
import requests | |
from PIL import Image | |
BASE_URL = 'http://dontclickhere.drivy.com' | |
CACHE = {} | |
BIT_COLOR_MAPPING = { | |
# Mapping of RGB color tuples to the binary value associated. | |
# Coming in 2 different flavors: for RGB and RGBA images. | |
'RGB': { | |
(238, 46, 129): 0, | |
(51, 131, 196): 1, | |
}, | |
'RGBA': { | |
(51, 131, 196): 0, | |
(53, 132, 197): 1, | |
} | |
} | |
def img2slices(image, slices): | |
"""Takes an Image object and returns a list of smaller | |
Image objects sliced from it, vertically. | |
Keyword arguments: | |
image -- An Image object | |
slices -- An integer on how many slices we want (vertically) | |
""" | |
width, height = image.size | |
for slice_index in range(slices): | |
slice_width = width // slices | |
box = ( | |
slice_width * slice_index, 0, | |
slice_width * (slice_index + 1), height | |
) | |
yield image.crop(box) | |
def img2byte(image): | |
"""Takes an Image object and returns a byte in the form of a list | |
of 8 binary numbers. | |
Keyword arguments: | |
image -- An Image object | |
""" | |
slices = img2slices(image, 8) | |
for slice in slices: | |
sample = tuple(slice.quantize(colors=2, method=2).getpalette()[3:6]) | |
yield BIT_COLOR_MAPPING[image.mode][sample] | |
def byte2char(byte): | |
"""Convert a byte in the form of a list of binary numbers to | |
its ASCII char value. | |
Keyword arguments: | |
byte -- A list of 8 binary numbers, forming together a byte | |
""" | |
return chr(int(''.join(map(str, byte)), 2)) | |
def main(): | |
i = 0 | |
while True: | |
url = '%s/img/img%d.png' % (BASE_URL, i) | |
res = requests.head(url) | |
if res.status_code != 200: | |
break | |
tag = res.headers['ETag'] | |
if tag in CACHE: | |
char = CACHE[tag] | |
else: | |
res = requests.get(url) | |
image = Image.open(StringIO(res.content)) | |
char = byte2char(img2byte(image)) | |
CACHE[tag] = char | |
sys.stdout.write(char) | |
i += 1 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment