Exemplo n.º 1
0
def test_worker():
    text = get_long_text()
    template = get_default_template()
    cpu_count = multiprocessing.cpu_count()
    workers = {1, cpu_count // 2, cpu_count, 2 * cpu_count}
    workers.discard(0)
    workers.discard(1)
    prev_images = None
    for worker in workers:
        images = handwrite(text, template, worker=worker, seed=SEED)
        if prev_images is not None:
            assert prev_images == images
        prev_images = images
Exemplo n.º 2
0
def test_outside_box():
    text = get_short_text()
    template = get_default_template()
    for box in ((-2 * DEFAULT_WIDTH, 0, -DEFAULT_WIDTH, DEFAULT_HEIGHT),
                (0, -2 * DEFAULT_HEIGHT, DEFAULT_WIDTH, -DEFAULT_HEIGHT),
                (2 * DEFAULT_WIDTH, 0, 3 * DEFAULT_WIDTH, DEFAULT_HEIGHT),
                (0, 2 * DEFAULT_HEIGHT, DEFAULT_WIDTH, 3 * DEFAULT_HEIGHT),
                (-2 * DEFAULT_WIDTH, -2 * DEFAULT_HEIGHT, -DEFAULT_WIDTH, -DEFAULT_HEIGHT)):
        template['box'] = box
        for anti_aliasing in (True, False):
            ims = handwrite(text, template, anti_aliasing=anti_aliasing, seed=SEED)
            for im in ims:
                assert absolute_equal(im, template['background'])
Exemplo n.º 3
0
def main():
    template = dict(
        background=Image.open("./pictures/树信笺纸.jpg"),
        box=(50, 500, 800 - 80, 800 - 50),
        font=ImageFont.truetype("./fonts/Bo Le Locust Tree Handwriting Pen Chinese Font-Simplified Chinese Fonts.ttf"),
        font_size=60,
    )
    text = "我能吞下玻璃而不伤身体。"
    images = handwrite(text, template)

    # 剪切出图片中含有字的一部分
    assert len(images) == 1
    images[0].crop((0, 450, 800, 800-200)).save("./out/motto.png")
Exemplo n.º 4
0
def test_line_and_page_breaks():
    text = "哈" * 4
    template = {
        "background": PIL.Image.new(mode="L", size=(100, 100), color="white"),
        "font": get_default_font(),
        "margin": {"left": 10, "right": 10, "top": 10, "bottom": 10},
        "line_spacing": 40,
        "font_size": 40,
        "word_spacing_sigma": 0,
        "font_size_sigma": 0,
    }
    images = handwrite(text, template)
    assert len(images) == 1
Exemplo n.º 5
0
 def test_oversized_box(self):
     text = self.get_default_text()
     template = self.get_default_template()
     background = template['background']
     template['box'] = (-100, -50, background.width + 100,
                        background.height + 50)
     ims = pylf.handwrite(text * 10, template)
     assert len(ims) == 1
     # ims[0].save("./data/images/test_oversized_box.png")
     self.assertTrue(
         self.compare(
             ims[0],
             PIL.Image.open("./data/images/test_oversized_box.png")))
Exemplo n.º 6
0
def test_is_end_char():
    text = '。' * 30
    template = get_default_template()
    template['color'] = 'rgb(0, 0, 0)'
    template['is_end_char'] = lambda c: True
    images = handwrite(text, template, anti_aliasing=False)
    assert len(images) == 1
    standard_image = template['background'].copy()
    image_draw.Draw(standard_image).multiline_text(
        xy=(template['box'][0], template['box'][1]),
        text=('。' * 6 + '\n') * 5,
        fill=template['color'],
        font=template['font'].font_variant(size=template['font_size']))
    assert compare_histogram(standard_image, images[0]) >= THRESHOLD
Exemplo n.º 7
0
def main():
    template = {
        'background': Image.open("./pictures/树信笺纸.jpg"),
        'box': (50, 500, 800 - 80, 800 - 50),
        'font': ImageFont.truetype("./fonts/Gsllchb_lf.ttf"),
        'font_size': 60,
        'font_size_sigma': 1,
        'line_spacing': 60,
        'line_spacing_sigma': 0.5,
        'word_spacing_sigma': 1,
    }
    text = "我能吞下玻璃而不伤身体。"
    images = handwrite(text, template)
    images[0].crop((0, 450, 800, 800-200)).save("./out/i_can_eat_glass.jpg")
Exemplo n.º 8
0
def test_worker():
    text = get_short_text()
    template = get_default_template()
    template['color'] = 'rgb(0, 0, 0)'
    standard_image = template['background'].copy()
    image_draw.Draw(standard_image).text(xy=(template['box'][0], template['box'][1]), text=text, fill=template['color'],
                                         font=template['font'].font_variant(size=template['font_size']))
    cpu_count = multiprocessing.cpu_count()
    workers = [0, 1, cpu_count // 2, cpu_count, 2 * cpu_count, 2 * cpu_count + 1]
    if cpu_count > 1:
        workers.append(-1)
    for worker in set(workers):
        images = handwrite((text + '\n' * 8) * max(worker, cpu_count), template, worker=worker, anti_aliasing=False)
        for image in images:
            assert compare_histogram(standard_image, image) < THRESHOLD
Exemplo n.º 9
0
def test_is_end_char_fn():
    text = "。" * 30
    template = get_default_template()
    template["color"] = "black"
    template["is_end_char_fn"] = lambda c: False
    images = handwrite(text, template)
    assert len(images) == 1
    standard_image = template["background"].copy()
    draw = PIL.ImageDraw.Draw(standard_image)
    draw.multiline_text(
        xy=(template["margin"]["left"] + 1, template["margin"]["top"] + 1),
        text=("。" * 6 + "\n") * 5,
        fill=template["color"],
        font=template["font"].font_variant(size=template["font_size"]),
    )
    assert diff_histogram(standard_image, images[0]) < THRESHOLD
Exemplo n.º 10
0
def test_multiprocessing():
    text = get_short_text()
    template = get_default_template()
    template['color'] = 'rgb(0, 0, 0)'
    standard_image = template['background'].copy()
    image_draw.Draw(standard_image).text(
        xy=(template['box'][0], template['box'][1]),
        text=text,
        fill=template['color'],
        font=template['font'].font_variant(size=template['font_size']))
    for worker in (1, multiprocessing.cpu_count()):
        images = handwrite((text + '\n' * 8) * 3 * worker,
                           template,
                           worker=worker,
                           anti_aliasing=False)
        for image in images:
            assert compare_histogram(standard_image, image) < THRESHOLD
Exemplo n.º 11
0
def test_font_size():
    text = get_short_text()
    template = get_default_template()
    template["color"] = "black"
    for font_size in (1, 10, 30):
        standard_image = template["background"].copy()
        draw = PIL.ImageDraw.Draw(standard_image)
        draw.text(
            xy=(template["margin"]["left"] + 1, template["margin"]["top"] + 1),
            text=text,
            fill=template["color"],
            font=template["font"].font_variant(size=font_size),
        )
        template["font_size"] = font_size
        images = handwrite(text, template)
        assert len(images) == 1
        assert diff_histogram(standard_image, images[0]) < THRESHOLD
Exemplo n.º 12
0
def main():
    template = dict(
        background=Image.open("./pictures/letter.png"),
        box=(65, 203, 926, 1325),
        font=ImageFont.truetype(
            "./fonts/Bo Le Locust Tree Handwriting Pen Chinese Font-Simplified Chinese Fonts.ttf"
        ),
        font_size=40,
        line_spacing=14)
    images = handwrite(TEXT, template)
    assert len(images) == 4
    width, height = images[0].size
    res = Image.new(mode=images[0].mode, size=(width * 2, height * 2))
    res.paste(images[0], (0, 0))
    res.paste(images[1], (width, 0))
    res.paste(images[2], (0, height))
    res.paste(images[3], (width, height))
    res.save("./out/荷塘月色.png")
Exemplo n.º 13
0
 def test_articles(self):
     print('Test by naked eyes:')
     template = dict(
         background=PIL.Image.open("./data/backgrounds/letter.png"),
         box=(68, 130, 655, 925),
         font=PIL.ImageFont.truetype(
             "./data/fonts/Bo Le Locust Tree Handwriting Pen Chinese Font-Simplified Chinese Fonts.ttf"
         ),
         font_size=27,
         line_spacing=6)
     for file in pathlib.Path("./data/texts").iterdir():
         print(file)
         with file.open() as f:
             text = f.read()
         images = handwrite(text, template)
         for im in images:
             im.show()
         self.assertTrue(input("Like it? [Y/N] ").upper() == 'Y')
Exemplo n.º 14
0
def test_run():
    shutil.rmtree(abs_path(TEMP_DIR), ignore_errors=True)
    os.makedirs(abs_path(TEMP_DIR), exist_ok=True)

    background = PIL.Image.new(mode="L", size=(400, 500), color="white")
    background.save(abs_path(TEMP_DIR, "background.png"))

    font = PIL.ImageFont.truetype(abs_path(FONT_PATH))
    shutil.copy(abs_path(FONT_PATH), abs_path(TEMP_DIR, "font.ttf"))

    text = get_long_text()
    with open(abs_path(TEMP_DIR, "content.txt"), mode="x",
              encoding="utf-8") as f:
        f.write(text)

    template = {
        "margin": {
            "left": 25,
            "right": 25,
            "top": 50,
            "bottom": 50
        },
        "line_spacing": 22,
        "font_size": 20,
    }
    with open(abs_path(TEMP_DIR, "template.yml"), mode="x",
              encoding="utf-8") as f:
        f.write(yaml.safe_dump(template))
    template["background"] = background
    template["font"] = font

    images1 = pylf.handwrite(text, template, seed=SEED)
    pylf.__main__.run(abs_path(TEMP_DIR), "--quiet", "--seed", SEED)
    images_dir = abs_path(TEMP_DIR, "out",
                          os.listdir(abs_path(TEMP_DIR, "out"))[0])
    images2 = [
        PIL.Image.open(abs_path(images_dir, n))
        for n in sorted(os.listdir(images_dir))
    ]

    assert all(map(visually_equal, images1, images2))

    shutil.rmtree(abs_path(TEMP_DIR))
Exemplo n.º 15
0
 def test_color(self):
     text = self.get_default_text()
     template = self.get_default_template()
     colors = {
         'black': 'rgb(0, 0, 0)',
         'red': 'rgb(255, 0, 0)',
         'green': 'rgb(0, 255, 0)',
         'blue': 'rgb(0, 0, 255)',
         'white': 'rgb(255, 255, 255)'
     }
     for k, v in colors.items():
         template['color'] = v
         ims = pylf.handwrite(text, template)
         assert len(ims) == 1
         # ims[0].save("./data/images/test_color_{}.png".format(k))
         self.assertTrue(
             self.compare(
                 ims[0],
                 PIL.Image.open(
                     "./data/images/test_color_{}.png".format(k))))
Exemplo n.º 16
0
    def test_exception(self):
        txt, tmp = self.__copy()
        font_size = tmp['font_size']

        tmp['box'] = (100, 100, 100 + font_size + 1, 100 + font_size)
        with self.assertRaises(ValueError):
            handwrite(txt, tmp)

        tmp['box'] = (100, 100, 100 + font_size, 100 + font_size + 1)
        with self.assertRaises(ValueError):
            handwrite(txt, tmp)

        tmp['box'] = (100, 100, 100 + font_size, 100 + font_size)
        with self.assertRaises(ValueError):
            handwrite(txt, tmp)
Exemplo n.º 17
0
def test_worker():
    text = get_short_text()
    template = get_default_template()
    template["color"] = "rgb(0, 0, 0)"
    standard_image = template["background"].copy()
    draw = PIL.ImageDraw.Draw(standard_image)
    draw.text(
        xy=(template["margin"]["left"] + 1, template["margin"]["top"] + 1),
        text=text,
        fill=template["color"],
        font=template["font"].font_variant(size=template["font_size"]),
    )
    cpu_count = multiprocessing.cpu_count()
    workers = {1, cpu_count // 2, cpu_count, 2 * cpu_count}
    workers.discard(0)
    for worker in workers:
        images = handwrite((text + "\n" * 8) * max(worker, cpu_count),
                           template,
                           worker=worker)
        for i in images:
            assert diff_histogram(standard_image, i) < THRESHOLD
Exemplo n.º 18
0
def test_error_box():
    text = get_short_text()
    template = get_default_template()
    font_size = template['font_size']

    template['box'] = (100, 100, 100 + font_size + 1, 100 + font_size)
    with pytest.raises(ValueError):
        handwrite(text, template)

    template['box'] = (100, 100, 100 + font_size, 100 + font_size + 1)
    with pytest.raises(ValueError):
        handwrite(text, template, anti_aliasing=False)

    template['box'] = (100, 100, 100 + font_size, 100 + font_size)
    with pytest.raises(ValueError):
        handwrite(text, template)
Exemplo n.º 19
0
    def test_error_box(self):
        text = self.get_default_text()
        template = self.get_default_template()
        font_size = template['font_size']

        template['box'] = (100, 100, 100 + font_size + 1, 100 + font_size)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)

        template['box'] = (100, 100, 100 + font_size, 100 + font_size + 1)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template, anti_aliasing=False)

        template['box'] = (100, 100, 100 + font_size, 100 + font_size)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)
Exemplo n.º 20
0
def test_error_alpha():
    text = get_short_text()
    template = get_default_template()

    template['alpha'] = (-1, 0)
    with pytest.raises(ValueError):
        handwrite(text, template)

    template['alpha'] = (-1, -1)
    with pytest.raises(ValueError):
        handwrite(text, template, anti_aliasing=False)

    template['alpha'] = (0, -1)
    with pytest.raises(ValueError):
        handwrite(text, template)

    template['alpha'] = (2, 0)
    with pytest.raises(ValueError):
        handwrite(text, template)

    template['alpha'] = (2, 2)
    with pytest.raises(ValueError):
        handwrite(text, template)

    template['alpha'] = (0, 2)
    with pytest.raises(ValueError):
        handwrite(text, template, anti_aliasing=False)

    template['alpha'] = (-1, 2)
    with pytest.raises(ValueError):
        handwrite(text, template, anti_aliasing=False)

    template['alpha'] = (2, -1)
    with pytest.raises(ValueError):
        handwrite(text, template)
Exemplo n.º 21
0
def test_blank_text():
    temp = get_default_template()
    images = handwrite(" ", temp)
    assert temp["background"] == images[0]
Exemplo n.º 22
0
def test_null_text():
    assert handwrite("", get_default_template()) == []
Exemplo n.º 23
0
    def test_error_alpha(self):
        text = self.get_default_text()
        template = self.get_default_template()

        template['alpha'] = (-1, 0)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)

        template['alpha'] = (-1, -1)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template, anti_aliasing=False)

        template['alpha'] = (0, -1)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)

        template['alpha'] = (2, 0)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)

        template['alpha'] = (2, 2)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)

        template['alpha'] = (0, 2)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template, anti_aliasing=False)

        template['alpha'] = (-1, 2)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template, anti_aliasing=False)

        template['alpha'] = (2, -1)
        with self.assertRaises(ValueError):
            pylf.handwrite(text, template)
Exemplo n.º 24
0
    def test_by_naked_eyes(self):
        import os
        print('Test by naked eyes:')
        prompt = "{}\npass test? [Y/N] \n"

        tmp = self.__copy()[1]
        dir_path, dir_names, file_names = list(os.walk("./data/texts"))[0]
        for filename in file_names:
            with open("{}/{}".format(dir_path, filename)) as f:
                txt = f.read()
            images = handwrite(txt, tmp)
            for im in images:
                im.show()
            self.assertTrue(input(prompt.format(filename)).upper() == 'Y')

        txt = "测试关闭SSAA抗锯齿的效果"
        images = handwrite(txt, tmp, anti_aliasing=False)
        for im in images:
            im.show()
        self.assertTrue(input(prompt.format(txt)).upper() == 'Y')

        txt = "测试‘box’比背景图大的情况。"
        tmp = self.__copy()[1]
        tmp['box'] = (-100, -100, image.width + 100, image.height + 100)
        images = handwrite(txt * 150, tmp)
        for im in images:
            im.show()
        self.assertTrue(input(prompt.format(txt)).upper() == 'Y')

        tmp = self.__copy()[1]
        cases = {
            '黑色': (0, 0, 0),
            '白色': (255, 255, 255),
            '红色': (255, 0, 0),
            '绿色': (0, 255, 0),
            '蓝色': (0, 0, 255),
            'color0': (-1, -1, -1),
            'color1': (1000, 1000, 1000),
        }
        for (k, v) in cases.items():
            print('{}: {}'.format(k, v))
            tmp['color'] = v
            images = handwrite(k, tmp)
            for im in images:
                im.show()
        self.assertTrue(input(prompt.format("测试颜色")).upper() == 'Y')

        txt = """测试is_half_char = lambda c: c in ',。'
        ,,,,,,,,。。。。。。。。。。。"""
        tmp = self.__copy()[1]
        tmp['is_half_char'] = lambda c: c in ',。'
        images = handwrite(txt, tmp)
        for im in images:
            im.show()
        self.assertTrue(input(prompt.format("测试is_half_char")).upper() == 'Y')

        txt = """测试is_end_char = lambda c: False
        。。。。。。。。。。。。。。。。。。。。。。。。"""
        tmp = self.__copy()[1]
        tmp['is_end_char'] = lambda c: False
        images = handwrite(txt, tmp)
        for im in images:
            im.show()
        self.assertTrue(input(prompt.format("测试is_end_char")).upper() == 'Y')
Exemplo n.º 25
0
 def test_null_text(self):
     tmp = self.__copy()[1]
     self.assertEqual(handwrite('', tmp), [])
Exemplo n.º 26
0
 def test_null_text(self):
     self.assertEqual(pylf.handwrite('', self.get_default_template()), [])
Exemplo n.º 27
0
def test_result():
    assert isinstance(handwrite("", get_default_template()), list)
    assert isinstance(handwrite(get_short_text(), get_default_template()), list)
    assert isinstance(handwrite(get_long_text(), get_default_template()), list)
Exemplo n.º 28
0
 def test_side_effect(self):
     txt, tmp = self.__copy()
     handwrite(txt, tmp)
     self.assertEqual(txt, text)
     self.assertEqual(tmp, template)