Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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()
Ejemplo n.º 3
0
        size = int(sqrt(len(data)))  # that's also one of the hints
        img = Image.new(mode, (size, size))
        for (y, x), pixel in zip(product(range(size), repeat=2), data):
            img.putpixel((x, y), (pixel == pixel_values[-1]) * 255)
        img = img.crop(img.getbbox())
        if 0 not in islice(img.getdata(),
                           img.width):  # is there a top white border?
            img = img.crop((1, 1, img.width - 1, img.height - 1))
            img = img.crop(img.getbbox())
            images.append(img.resize((img.width // 2, img.height // 2)))
    return images


def combine(images):
    width = sum(img.width for img in images) + len(images)
    height = max(img.height for img in images)
    image = Image.new(img_mode, (width, height))
    x_offset = 0
    for img in images:
        image.paste(img, (x_offset, height - img.height))
        x_offset += img.width + 1
    return image


url = "http://www.pythonchallenge.com/pc/rock/beer.html"
img_mode, img_data = read_image(url)
pixel_values = sorted(Counter(img_data))
images = gen_images(img_mode, img_data, pixel_values)
image = combine(images)
print(image_to_text(image, skip=1))
Ejemplo n.º 4
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)))
            left.append(line[0].strip())
            right.append(line[1].strip())
    return left, right


def compare_deltas(delta_left, delta_right):
    """Compares the deltas with difflib and returns, as bytes, the lines that
    are equal, only on the right and on the left delta"""
    equal, right, left = BytesIO(), BytesIO(), BytesIO()
    for diff in Differ().compare(delta_left, delta_right):
        try:
            chunk = bytes(int(b, 16) for b in diff[2:].split())
        except ValueError:
            continue
        if diff[0] == " ":
            equal.write(chunk)
        elif diff[0] == "+":
            right.write(chunk)
        else:
            left.write(chunk)
    return equal, right, left


url = "http://www.pythonchallenge.com/pc/return/brightness.html"
url_base = url.rsplit("/", 1)[0]
new_path = get_nth_comment(url, 1).rstrip().rsplit(maxsplit=1)[-1]
deltas_url = f"{url_base}/{new_path}"
delta_left, delta_right = split_deltas(deltas_url)
diffs = compare_deltas(delta_left, delta_right)
print("\n".join(image_to_text(Image.open(diff)) for diff in diffs))
Ejemplo n.º 6
0
        for x in width_iter:
            pixels.append(image.getpixel((x, y)))
            if pixels[-1] == pivot:
                threshold = image.width - x
                break
        for x, pixel in enumerate(pixels):
            new_image.putpixel(((threshold + x) % image.width, y), pixel)
        for x in width_iter:
            new_image.putpixel((threshold + x - image.width, y), image.getpixel((x, y)))
    cache["new_image"] = new_image.tobytes()
    return new_image


def find_pivot(image, color):
    for i, c in enumerate(zip(*([iter(image.getpalette())] * 3))):
        if c == color:
            return i


url = "http://www.pythonchallenge.com/pc/return/mozart.html"
image_content = read_url(get_last_src_url(url))
image = Image.open(BytesIO(image_content))
pivot = find_pivot(image, (255, 0, 255))
new_image = (
    generate_aligned_image(image, pivot)
    .convert("RGB")
    .crop((50, 50, *[n - 50 for n in image.size]))
    .resize([n // 4 for n in image.size])
)
print(image_to_text(new_image, 95, 3))
Ejemplo n.º 7
0
    dx = width / image_size[0]
    dy = height / image_size[1]
    data = []
    for y in range(image_size[1] - 1, -1,
                   -1):  # is mission's image upside down??? 🤷
        for x in range(image_size[0]):
            c0 = complex(left + x * dx, top + y * dy)
            c, i = complex(), 0
            while True:
                c = c * c + c0
                if abs(c) > 2 or i == max_iter - 1:
                    break
                i += 1
            data.append(i)
    return data


def diff_image(data_a, data_b):
    """Generates a 1-bit black and white image by comparing `data_a` and `data_b`"""
    diff = [int(a > b) for a, b in zip(data_a, data_b) if a != b]
    img = Image.new("1", factorize(len(diff)))
    img.putdata(diff)
    return img


url = "http://www.pythonchallenge.com/pc/rock/grandpa.html"
img, left, top, width, height, iterations = read_riddle_data(url)
mandelbrot = mandelbrot_set(left, top, width, height, img.size, iterations)
diff_img = diff_image(img.getdata(), mandelbrot)
print(image_to_text(diff_img, skip=1, white="â–“â–“"))
Ejemplo n.º 8
0
def extract_image(zip_data):
    """Extracts an image from a corrupt zip file inside `zip_data`"""
    patch_update_crc()
    with zipfile.ZipFile(BytesIO(zip_data)) as outer:
        for name in outer.namelist():
            try:
                with zipfile.ZipFile(outer.open(name)) as inner, inner.open(
                    inner.namelist()[0]
                ) as img_file:
                    # Pillow couldn't read the corrupt gif, even with
                    # PIL.ImageFile.LOAD_TRUNCATED_IMAGES set to True
                    return WandImage(file=img_file)
            except (zipfile.BadZipFile, WandBaseError):
                pass


ambiguity_data = get_ambiguity_data()
image = extract_image(ambiguity_data)
image_data = image.export_pixels()
pil_image = Image.frombytes("RGBA", image.size, bytes(image_data))
print(image_to_text(pil_image, skip=3))

for line in read_riddle(
    "http://www.pythonchallenge.com/pc/hex/decent.html"
).splitlines():
    if not line:
        break
    if "<" in line:
        continue
    print(line.rsplit(maxsplit=1)[-1])
Ejemplo n.º 9
0
def extract_image(data):
    """Tries and extracts the image inside data (which is a zipfile)"""
    with ZipFile(BytesIO(data)) as zip_file:
        for name in zip_file.namelist()[::-1]:
            try:
                return Image.open(BytesIO(zip_file.read(name)))
            except UnidentifiedImageError:
                logging.warning("%s does not seem to be an image", name)


@autocached
def crop_blue_only(image):
    """Returns a cropped image with `image`'s bluest pixels"""
    img = Image.new("L", (image.width, image.height))
    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:
            img.putpixel(xy, b)
    return img.crop((0, img.height // 2, img.width, img.height))


maze, size = load_maze("http://www.pythonchallenge.com/pc/hex/ambiguity.html")
start = find_black_square(maze, size, 0)
finish = find_black_square(maze, size, size[1] - 1)
data = tumble_down(maze, start, finish)

if __name__ == "__main__":
    image = extract_image(data)
    new_image = crop_blue_only(image)
    print(image_to_text(new_image))