1
mirror of git://git.acid.vegas/scroll.git synced 2024-11-22 08:06:39 +00:00

img2irc improvements (props wrk) and fixed img_width

This commit is contained in:
Dionysus 2023-06-26 05:32:13 -04:00
parent f2f015c7f6
commit 6566bce064
Signed by: acidvegas
GPG Key ID: EF4B922DB85DC9DE
3 changed files with 49 additions and 41 deletions

Binary file not shown.

View File

@ -17,40 +17,54 @@ try:
except ImportError: except ImportError:
raise SystemExit('missing required \'pillow\' library (https://pypi.org/project/pillow/)') raise SystemExit('missing required \'pillow\' library (https://pypi.org/project/pillow/)')
async def convert(data, img_width=80): def convert(data, max_line_len, img_width=80):
image = Image.open(io.BytesIO(data)) image = Image.open(io.BytesIO(data))
del data del data
return convert_image(image, max_line_len, img_width)
def convert_image(image, max_line_len, img_width):
(width, height) = image.size (width, height) = image.size
img_height = img_width / width * height img_height = img_width / width * height
del height, width del height, width
image.thumbnail((img_width, img_height), Image.Resampling.LANCZOS) image.thumbnail((img_width, img_height), Image.Resampling.LANCZOS)
del img_height, img_width del img_height
ansi_image = AnsiImage(image)
del image
CHAR = '\u2580' CHAR = '\u2580'
buf = '' buf = list()
for (y, row) in enumerate(ansi_image.halfblocks): print(image.size)
last_fg = -1 for i in range(0, image.size[1], 2):
last_bg = -1 if i+1 >= image.size[1]:
for (x, pixel_pair) in enumerate(row): bitmap = [[rgb_to_hex(image.getpixel((x, i))) for x in range(image.size[0])]]
bitmap += [[0 for _ in range(image.size[0])]]
else:
bitmap = [[rgb_to_hex(image.getpixel((x, y))) for x in range(image.size[0])] for y in [i, i+1]]
top_row = [AnsiPixel(px) for px in bitmap[0]]
bottom_row = [AnsiPixel(px) for px in bitmap[1]]
buf += [""]
last_fg = last_bg = -1
ansi_row = list()
for j in range(image.size[0]):
top_pixel = top_row[j]
bottom_pixel = bottom_row[j]
pixel_pair = AnsiPixelPair(top_pixel, bottom_pixel)
fg = pixel_pair.top.irc fg = pixel_pair.top.irc
bg = pixel_pair.bottom.irc bg = pixel_pair.bottom.irc
if x != 0: if j != 0:
if fg == last_fg and bg == last_bg: if fg == last_fg and bg == last_bg:
buf += CHAR buf[-1] += CHAR
elif bg == last_bg: elif bg == last_bg:
buf += f'\x03{fg}{CHAR}' buf[-1] += f'\x03{fg}{CHAR}'
else: else:
buf += f'\x03{fg},{bg}{CHAR}' buf[-1] += f'\x03{fg},{bg}{CHAR}'
else: else:
buf += f'\x03{fg},{bg}{CHAR}' buf[-1] += f'\x03{fg},{bg}{CHAR}'
last_fg = fg last_fg = fg
last_bg = bg last_bg = bg
if y != len(ansi_image.halfblocks) - 1: print(len(buf[-1].encode('utf-8', 'ignore')), max_line_len)
buf += '\n' if len(buf[-1].encode('utf-8', 'ignore')) > max_line_len:
else: if img_width - 5 < 10:
buf += '\x0f' raise Exception('internal error')
return buf.splitlines() return convert_image(image, max_line_len, img_width-5)
return buf
def hex_to_rgb(color): def hex_to_rgb(color):
r = color >> 16 r = color >> 16
@ -59,7 +73,9 @@ def hex_to_rgb(color):
return (r,g,b) return (r,g,b)
def rgb_to_hex(rgb): def rgb_to_hex(rgb):
(r,g,b) = rgb r = rgb[0]
g = rgb[1]
b = rgb[2]
return (r << 16) + (g << 8) + b return (r << 16) + (g << 8) + b
def color_distance_squared(c1, c2): def color_distance_squared(c1, c2):
@ -97,23 +113,3 @@ class AnsiPixelPair:
def __init__(self, top, bottom): def __init__(self, top, bottom):
self.top = top self.top = top
self.bottom = bottom self.bottom = bottom
class AnsiImage:
def __init__(self, image):
self.bitmap = [[rgb_to_hex(image.getpixel((x, y))) for x in range(image.size[0])] for y in range(image.size[1])]
if len(self.bitmap) % 2 != 0:
self.bitmap.append([0 for x in range(image.size[0])])
ansi_bitmap = [[AnsiPixel(y) for y in x] for x in self.bitmap]
ansi_canvas = list()
for two_rows in range(0, len(ansi_bitmap), 2):
top_row = ansi_bitmap[two_rows]
bottom_row = ansi_bitmap[two_rows+1]
ansi_row = list()
for i in range(len(self.bitmap[0])):
top_pixel = top_row[i]
bottom_pixel = bottom_row[i]
pixel_pair = AnsiPixelPair(top_pixel, bottom_pixel)
ansi_row.append(pixel_pair)
ansi_canvas.append(ansi_row)
self.image = image
self.halfblocks = ansi_canvas

View File

@ -82,6 +82,7 @@ class Bot():
self.db = None self.db = None
self.last = time.time() self.last = time.time()
self.loops = dict() self.loops = dict()
self.host = ''
self.playing = False self.playing = False
self.settings = {'flood':1, 'ignore':'big,birds,doc,gorf,hang,nazi,pokemon', 'lines':500, 'msg':0.03, 'paste':True, 'png_width':80, 'results':25} self.settings = {'flood':1, 'ignore':'big,birds,doc,gorf,hang,nazi,pokemon', 'lines':500, 'msg':0.03, 'paste':True, 'png_width':80, 'results':25}
self.slow = False self.slow = False
@ -201,6 +202,11 @@ class Bot():
await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel) await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel)
await self.raw('JOIN #scroll') await self.raw('JOIN #scroll')
await self.sync() await self.sync()
elif args[1] == '311' and len(args) >= 6: # RPL_WHOISUSER
nick = args[2]
host = args[5]
if nick == identity.nickname:
self.host = host
elif args[1] == '433': elif args[1] == '433':
error('The bot is already running or nick is in use.') error('The bot is already running or nick is in use.')
elif args[1] == 'INVITE' and len(args) == 4: elif args[1] == 'INVITE' and len(args) == 4:
@ -208,6 +214,11 @@ class Bot():
chan = args[3][1:] chan = args[3][1:]
if invited == identity.nickname and chan in (connection.channel, '#scroll'): if invited == identity.nickname and chan in (connection.channel, '#scroll'):
await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel) await self.raw(f'JOIN {connection.channel} {connection.key}') if connection.key else await self.raw('JOIN ' + connection.channel)
elif args[1] == 'JOIN' and len(args) >= 3:
nick = args[0].split('!')[0][1:]
host = args[0].split('@')[1]
if nick == identity.nickname:
self.host = host
elif args[1] == 'KICK' and len(args) >= 4: elif args[1] == 'KICK' and len(args) >= 4:
chan = args[2] chan = args[2]
kicked = args[3] kicked = args[3]
@ -241,10 +252,11 @@ class Bot():
await asyncio.sleep(self.settings['msg']) await asyncio.sleep(self.settings['msg'])
elif args[1] == 'img' and len(args) == 3: elif args[1] == 'img' and len(args) == 3:
url = args[2] url = args[2]
width = 512 - len(line.split(' :')[0])+4
if url.startswith('https://') or url.startswith('http://'): if url.startswith('https://') or url.startswith('http://'):
try: try:
content = get_url(url).read() content = get_url(url).read()
ascii = await img2irc.convert(content, int(self.settings['png_width'])) ascii = await img2irc.convert(content, 512 - len(f":{identity.nickname}!{identity.username}@{self.host} PRIVMSG {chan} :\r\n"), int(self.settings['png_width']))
except Exception as ex: except Exception as ex:
await self.irc_error(chan, 'failed to convert image', ex) await self.irc_error(chan, 'failed to convert image', ex)
else: else: