Ejemplo n.º 1
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of Python Challenge Solutions
# https://github.com/scorphus/PythonChallengeSolutions

# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <*****@*****.**>

# http://www.pythonchallenge.com/pc/ring/bell.html

from auth import get_last_src_url
from auth import read_url
from io import BytesIO
from itertools import islice
from PIL import Image as Image


img_url = get_last_src_url("http://www.pythonchallenge.com/pc/ring/bell.html")
greens = islice(Image.open(BytesIO(read_url(img_url))).tobytes(), 1, None, 3)
for curr, prev in zip(greens, greens):
    if abs(curr - prev) != 42:  # 😱 the ultimate answer! Boring mission 😒
        print(chr(abs(curr - prev)), end="")
print(" (hint: ‘it’ is Python)")
Ejemplo n.º 2
0
ImageFile.LOAD_TRUNCATED_IMAGES = True


def get_next_jpg_images(jpg_url, from_to):
    """Gets next images by changing the number in the URL"""
    for i in range(*from_to):
        jpg_content = read_url(jpg_url.replace("1", f"{i}"))
        try:
            jpg = Image.open(BytesIO(jpg_content))
            yield image_to_text(jpg, 10, 8)
        except UnidentifiedImageError:
            yield jpg_content.decode()


def get_images_in_gfx(jpg_url):
    """Gets the 5 images, distributed in noncontiguous 5*n indexes"""
    gfx_url = jpg_url.replace("1", "2").replace("jpg", "gfx")
    gfx = read_url(gfx_url)
    for i in range(5):
        img = Image.open(BytesIO(bytes(gfx[i::5])))
        yield image_to_text(img)


url = "http://www.pythonchallenge.com/pc/return/evil.html"
jpg_url = get_last_src_url(url)

if __name__ == "__main__":
    print("\n".join(get_next_jpg_images(jpg_url, (2, 5))))
    print("\n".join(get_images_in_gfx(jpg_url)))
Ejemplo n.º 3
0
def create_image(waves):
    """Creates an image out of the WAVE frames"""
    wav_size = int((len(waves[0]) / 3) ** 0.5)  # a square with len(waves[0]) RGB pixels
    size = int(len(waves) ** 0.5) * wav_size  # a square with len(waves) subsquares
    ratio = size // wav_size
    new_image = Image.new("RGB", (size, size))
    for i, wav in enumerate(waves):
        new_image.paste(
            Image.frombytes("RGB", (wav_size, wav_size), wav),
            (i % ratio * wav_size, i // ratio * wav_size),
        )
    return new_image


@autocached
def highlight_blue(image):
    """Highlights the bluest pixels of image"""
    for xy in product(range(image.width), range(image.height)):
        r, g, b = image.getpixel(xy)
        if b > 1.2 * r and b > 1.2 * g:
            image.putpixel(xy, (255,) * 3)
        else:
            image.putpixel(xy, (0,) * 3)
    return image


url = get_last_src_url("http://www.pythonchallenge.com/pc/hex/lake.html")
image = create_image(read_waves(url.replace("jpg", "wav")))
print(image_to_text(highlight_blue(image)))
Ejemplo n.º 4
0
        try:
            msg, headers = read_url_and_headers(img_url, range_header(start))
            msg = msg.decode().strip()
        except UnicodeDecodeError:
            pass
        except HTTPError:
            return msg.split(maxsplit=2)[1].rstrip(".")[::-1], int(size)
        content_range = headers["Content-Range"].split(maxsplit=1)[1]
        start_end, size = content_range.split("/", 1)
        start = int(start_end.rsplit("-", 1)[-1]) + 1


def advance_rewind_and_extract(img_url, pwd, size):
    """Finds the correct range start and use the password to ultimately extract
    and display next mission's content"""
    msg = read_riddle(img_url, range_header(size)).strip()
    msg = read_riddle(img_url, range_header(size - len(msg) - 2)).strip()
    start = msg.rstrip(".").rsplit(maxsplit=1)[-1]
    zip_content = read_url(img_url, range_header(start)).strip()
    with ZipFile(BytesIO(zip_content), "r") as zip_file:
        readme, package = zip_file.namelist()
        print(zip_file.read(readme, pwd=pwd.encode()).decode())
        print(zip_file.extract(package, pwd=pwd.encode()))


url = "http://www.pythonchallenge.com/pc/hex/idiot.html"
next_url = get_last_href_url(url)
img_url = get_last_src_url(next_url)
pwd, size = get_pwd_and_size(img_url)
advance_rewind_and_extract(img_url, pwd, size)
Ejemplo n.º 5
0
def read_image(url):
    img_url = get_last_src_url(url).replace("1", "2").replace("jpg", "png")
    img = Image.open(BytesIO(read_url(img_url)))
    return img.mode, img.getdata()
Ejemplo n.º 6
0
    new_image = Image.new(image.mode, (100, 100))
    for pixel in reversed(image.getdata()):
        if -50 < x <= 50 and -50 < y <= 50:
            new_image.putpixel((x + 49, 50 - y), pixel)
        if x == y or x < 0 and x == -y or x > 0 and x == 1 - y:
            dx, dy = -dy, dx
        x, y = x + dx, y + dy
    return new_image


class CatNameSayer(HTMLParser):
    """Parses an HTML and display data for <b> tags"""
    def handle_starttag(self, tag, _):
        self.show = tag == "b"

    def handle_data(self, data):
        if self.show:
            print(data)
        self.show = False


url = "http://www.pythonchallenge.com/pc/return/italy.html"
image_content = read_url(get_last_src_url(url))
image = Image.open(BytesIO(image_content))

spiral_and_transform(image).save("14-italy.png", "PNG")
print("Open 14-italy.png only to see a cat")

cat = read_riddle(url.replace("italy", "cat"))
CatNameSayer().feed(cat)
Ejemplo n.º 7
0
def read_riddle_data(url):
    img_url = get_last_src_url(url)
    return (Image.open(BytesIO(read_url(img_url))), *read_riddle_numbers(url))
Ejemplo n.º 8
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of Python Challenge Solutions
# https://github.com/scorphus/PythonChallengeSolutions

# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <*****@*****.**>

# http://www.pythonchallenge.com/pc/def/peak.html
# Source mentions banner.p

from auth import get_last_src_url
from auth import read_url

import pickle

url = "http://www.pythonchallenge.com/pc/def/peak.html"
for row in pickle.loads(read_url(get_last_src_url(url))):
    print("".join(char * times for char, times in row))
Ejemplo n.º 9
0
def load_maze(url):
    """Fetches and loads maze.png then returns its pixels and size"""
    maze_url = get_last_src_url(url)
    maze = Image.open(BytesIO(read_url(maze_url)))
    return maze.load(), maze.size
Ejemplo n.º 10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of Python Challenge Solutions
# https://github.com/scorphus/PythonChallengeSolutions

# Licensed under the BSD-3-Clause license:
# https://opensource.org/licenses/BSD-3-Clause
# Copyright (c) 2018-2020, Pablo S. Blum de Aguiar <*****@*****.**>

# http://www.pythonchallenge.com/pc/return/5808.html

from auth import get_last_src_url
from auth import read_url
from io import BytesIO
from PIL import Image

img_url = get_last_src_url(
    "http://www.pythonchallenge.com/pc/return/5808.html")
img = Image.open(BytesIO(read_url(img_url))).convert("L")
for y in range(0, 2 * img.height // 5, 4):
    for x in range(img.width // 2, img.width, 4):
        if (x + y) % 2 == 0:
            if img.getpixel((x, y)) > 14:
                print("##", end="")
            else:
                print("  ", end="")
    print()
def read_csv_cells(url):
    """Reads the cells of the CSV mentioned in the riddle"""
    csv_url = get_last_src_url(url).replace("jpg", "csv")
    rows = (line.rstrip(",").split(", ")
            for line in read_riddle(csv_url).splitlines())
    return list(chain.from_iterable(rows))