Exemple #1
0
def test_generate_kwargs_height():
    kwargs = {'text': 'a', 'width': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(height=128, **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(height=None, **kwargs)
    with pytest.raises(TypeError):
        generate(height='', **kwargs)
    with pytest.raises(ValueError):
        generate(height=-1, **kwargs)
    with pytest.raises(ValueError):
        generate(height=0, **kwargs)
Exemple #2
0
def main():
    data = emojilib.generate(
        text="絵文\n字。",
        width=128,
        height=128,
        typeface_file='./example/NotoSansMonoCJKjp-Bold.otf')

    with open('./example/emoji.png', 'wb') as f:
        f.write(data)
Exemple #3
0
def test_generate_kwargs_size_fixed():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(size_fixed=None, **kwargs), bytes)
    assert isinstance(generate(size_fixed=True, **kwargs), bytes)
    assert isinstance(generate(size_fixed=1, **kwargs), bytes)
    assert isinstance(generate(size_fixed='a', **kwargs), bytes)
    assert isinstance(generate(size_fixed=False, **kwargs), bytes)
    assert isinstance(generate(size_fixed=0, **kwargs), bytes)
    assert isinstance(generate(size_fixed='', **kwargs), bytes)
Exemple #4
0
def test_generate_kwargs_disable_stretch():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(disable_stretch=None, **kwargs), bytes)
    assert isinstance(generate(disable_stretch=True, **kwargs), bytes)
    assert isinstance(generate(disable_stretch=1, **kwargs), bytes)
    assert isinstance(generate(disable_stretch='a', **kwargs), bytes)
    assert isinstance(generate(disable_stretch=False, **kwargs), bytes)
    assert isinstance(generate(disable_stretch=0, **kwargs), bytes)
    assert isinstance(generate(disable_stretch='', **kwargs), bytes)
Exemple #5
0
def test_generate_kwargs_text():
    kwargs = {'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(text='a', **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(text=None, **kwargs)
    with pytest.raises(TypeError):
        generate(text=0, **kwargs)
    with pytest.raises(ValueError):
        generate(text='', **kwargs)
Exemple #6
0
def generate(text,font,color,back_color, \
                    size_fixed = False, \
                    align = 'center', \
                    stretch = True):
    hash_text = text + \
            ':' + color +\
            ':' + back_color +\
            ':' + font +\
            ':' + ('true' if size_fixed else 'false') +\
            ':' + align +\
            ':' + ('true' if stretch else 'false') +\
            ':' + str(app.config['CACHE_VERSION'])
    r = int(color[0] +color[1],16)
    g = int(color[2] +color[3],16)
    b = int(color[4] +color[5],16)
    if len(color) == 6:
        a = 0xff
    elif len(color) == 8:
        a = int(color[6] + color[7],16)
    br = int(back_color[0] + back_color[1],16)
    bg = int(back_color[2] + back_color[3],16)
    bb = int(back_color[4] + back_color[5],16)
    if len(back_color) == 6:
        ba = 0xff
    elif len(back_color) == 8:
        ba = int(back_color[6] + back_color[7],16)
    cache_id = hashlib.md5(hash_text.encode('utf-8')).hexdigest()
    img_png = cache.get(cache_id)
    if img_png is None:
        lines = text.splitlines()

        if len(text) > 100: # XXX: 100 文字以上
            return None

        if len(lines) == 1 and len(lines[0]) > 10: # XXX: 1 列 10 文字以上
            return None

        if len(lines) > 10: # XXX: 10 行以上
            return None

        img_png = emojilib.generate(
            text=text,
            width=128,
            height=128,
            color=color,
            background_color=back_color,
            size_fixed=size_fixed,
            disable_stretch=not stretch,
            align=align,
            typeface_file='assets/fonts/' + font,
            format='png'
        )
        cache.set(cache_id,img_png)
    return img_png
Exemple #7
0
async def view(request):
    code = request.query.get('code')
    dl = request.query.get('dl', None) == '1'
    try:
        ecode = EcodeDecoder().decode(code)
    except Exception as e:
        print(e)
        return HTTPBadRequest()

    # Locale
    locales_config = ContextHolder.context.config.locales_config
    locale = ecode.locale.code
    if locale not in locales_config.locales:
        return HTTPBadRequest()

    # Fonts
    fonts_config = ContextHolder.context.config.fonts_config
    fonts = fonts_config.by_locale(locale)
    font = next(filter(lambda f: f['id'] == ecode.font_id, fonts), None)
    if font is None:
        return HTTPBadRequest()
    font_path = str(fonts_config.fonts_path.joinpath(font['path']))

    try:
        img_data = emojilib.generate(
            text=ecode.text,
            width=ecode.size.width,
            height=ecode.size.height,
            color='{:08X}'.format(ecode.foreground_color),
            background_color='{:08X}'.format(ecode.background_color),
            size_fixed=EcodeFlag.SIZE_FIXED in ecode.flags,
            disable_stretch=EcodeFlag.STRETCH not in ecode.flags,
            align=ecode.align.code,
            typeface_file=font_path,
            format=ecode.fmt.code
        )
    except Exception as e:
        print(e)
        return HTTPBadRequest()

    headers = {}
    headers['Cache-Control'] = 'public, max-age={}'.format(60 * 60 * 24) # 1 day
    if dl:
        filename = '{}.{}'.format(re.sub(r'\s','_', ecode.text), ecode.fmt.code)
        desposition = 'attachment; filename=\"{}\"'.format(filename)
        headers['Content-Disposition'] = desposition

    return Response(
        body=img_data,
        headers=headers,
        content_type='image/{}'.format(ecode.fmt.code)
    )
Exemple #8
0
def test_generate_kwargs_typeface_name():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}
    typeface_name = 'Roboto' if sys.platform.startswith(
        'linux') else 'Helvetica'

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(typeface_name=typeface_name, **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(typeface_name=1, **kwargs)
    with pytest.raises(ValueError):
        generate(typeface_name='', **kwargs)
Exemple #9
0
def test_generate_kwargs_typeface_file():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}
    typeface_file = Path(__file__) \
        .resolve().parents[1].joinpath('assets', 'Roboto-Regular.ttf')

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(typeface_file=str(typeface_file), **kwargs),
                      bytes)

    with pytest.raises(TypeError):
        generate(typeface_file=1, **kwargs)
    with pytest.raises(ValueError):
        generate(typeface_file='', **kwargs)
Exemple #10
0
def generate_moji(
    text,
    filename,
    typeface_file=_DEFAULT_FONT_FILE,
    width=128,
    height=128,
    default_align="left",
    color=None,
    background_color=None,
    size_fixed=None,
    disable_stretch=None,
):
    if pathlib.Path(typeface_file).exists() is False:
        raise ValueError("font file not found: " + typeface_file)
    generate_options = {}
    if color:
        generate_options["color"] = color
    if background_color:
        generate_options["background_color"] = background_color
    if size_fixed:
        generate_options["size_fixed"] = size_fixed
    if disable_stretch:
        generate_options["disable_stretch"] = disable_stretch
    align = "center" if _is_every_line_1_char(text) else default_align

    data = emojilib.generate(
        text=text,
        # typeface_name='游ゴシック体',
        typeface_file=typeface_file,
        width=width,
        height=height,
        align=align,
        **generate_options,
        # format='PNG',  # PING or WEBP
    )

    with open(filename, "wb") as f:
        f.write(data)
    logger.info('Generated Moji: {}'.format(filename))
Exemple #11
0
async def _execute(request, download_fg=False):
    fonts_config = ContextHolder.context.config.fonts_config
    locales_config = ContextHolder.context.config.locales_config

    # Locales
    locale = request.query.get('locale', 'ja')
    if locale not in locales_config.locales:
        return HTTPBadRequest()

    # Fonts
    font_key = request.query.get('font')
    fonts = fonts_config.by_locale(locale)
    font = fonts[0]
    if font_key:
        font = next(filter(lambda f: f['key'] == font_key, fonts), None)
        if font is None:
            return HTTPBadRequest()

    font_path = str(fonts_config.fonts_path.joinpath(font['path']))

    default_text = request.app['config']['routes']['default_text']
    default_color = request.app['config']['routes']['default_color']
    default_background_color = request.app['config']['routes']['default_background_color']


    text = request.query.get('text', default_text)
    color = request.query.get('color', default_color).upper()
    background_color = request.query.get('back_color', default_background_color).upper()
    size_fixed = request.query.get('size_fixed',default='false').lower() == 'true'
    align = request.query.get('align', 'center').lower()
    disable_stretch = request.query.get('stretch', 'true').lower() == 'false'
    public_fg = request.query.get('public_fg', 'true').lower() == 'true'


    # TODO: Slack 通知

    # 絵文字を生成
    try:
        img_data = emojilib.generate(
            text=text,
            width=128,
            height=128,
            color=color,
            background_color=background_color,
            size_fixed=size_fixed,
            disable_stretch=disable_stretch,
            align=align,
            typeface_file=font_path,
            format='png'
        )
    except Exception as err:
        print(err)
        print('color:{}\tbackground_color:{}'.format(color, background_color))
        return HTTPBadRequest()

    # 生成ログを記録
    if download_fg:
        await emoji_log_repository.add({
            'text': text,
            'color': color,
            'back_color': background_color,
            'font': font['key'],
            'size_fixed': size_fixed,
            'align': align,
            'stretch': not disable_stretch,
            'public_fg': public_fg,
            'locale': locale,
        })

    headers = {}
    if download_fg:
        desposition = 'attachment; filename=\"{}.png\"'.format(re.sub(r'\s','_',text))
        headers['Content-Disposition'] = desposition
        headers['Cache-Control'] = 'private, no-store, no-cache, must-revalidate'
    else:
        if request.app.debug:
            headers['Cache-Control'] = 'private, no-store, no-cache, must-revalidate'
        else:
            headers['Cache-Control'] = 'public, max-age={}'.format(60 * 60 * 24) # 1 day

    return Response(
        body=img_data,
        headers=headers,
        content_type='image/png'
    )
Exemple #12
0
def test_generate_kwargs_align():
    kwargs = {'text': "a", 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(align='left', **kwargs), bytes)
    assert isinstance(generate(align='Left', **kwargs), bytes)
    assert isinstance(generate(align='LEFT', **kwargs), bytes)
    assert isinstance(generate(align='center', **kwargs), bytes)
    assert isinstance(generate(align='right', **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(align=None, **kwargs)
    with pytest.raises(TypeError):
        generate(align=1, **kwargs)
    with pytest.raises(ValueError):
        generate(align='', **kwargs)
    with pytest.raises(ValueError):
        generate(align='unknown', **kwargs)
Exemple #13
0
def test_generate_kwargs_background_color():
    kwargs = {'text': "a", 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(background_color='FFFFFFFF', **kwargs), bytes)
    assert isinstance(generate(background_color='#FFFFFFFF', **kwargs), bytes)
Exemple #14
0
def test_generate_kwargs_quality():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(quality=0, **kwargs), bytes)
    assert isinstance(generate(quality=1, **kwargs), bytes)
    assert isinstance(generate(quality=99, **kwargs), bytes)
    assert isinstance(generate(quality=100, **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(quality=None, **kwargs)
    with pytest.raises(TypeError):
        generate(quality='', **kwargs)
    with pytest.raises(ValueError):
        generate(quality=-1, **kwargs)
    with pytest.raises(ValueError):
        generate(quality=101, **kwargs)
Exemple #15
0
def test_generate_kwargs_format():
    kwargs = {'text': 'a', 'width': 16, 'height': 16}

    assert isinstance(generate(**kwargs), bytes)
    assert isinstance(generate(format='png', **kwargs), bytes)
    assert isinstance(generate(format='Png', **kwargs), bytes)
    assert isinstance(generate(format='PNG', **kwargs), bytes)
    assert isinstance(generate(format='webp', **kwargs), bytes)
    assert isinstance(generate(format='Webp', **kwargs), bytes)
    assert isinstance(generate(format='WEBP', **kwargs), bytes)

    with pytest.raises(TypeError):
        generate(format=None, **kwargs)
    with pytest.raises(TypeError):
        generate(format=1, **kwargs)
    with pytest.raises(ValueError):
        generate(format='', **kwargs)
    with pytest.raises(ValueError):
        generate(format='unknown', **kwargs)