This commit is contained in:
jaseg 2019-04-03 00:35:23 +09:00
parent 38de96de6d
commit 989a175fa5
5 changed files with 173 additions and 2 deletions

1
agents/F1/agent.json Normal file

File diff suppressed because one or more lines are too long

View file

@ -282,8 +282,8 @@ if __name__ == '__main__':
else: else:
for img_pf, img_dsp, img_term in agents[0](args.action, not args.nosleep): for img_pf, img_dsp, img_term in agents[0](args.action, not args.nosleep):
if args.terminal: if args.terminal:
print(pixelterm.termify_pixels( print(img_term) #pixelterm.termify_pixels(
resize_image(img, termsize))) #resize_image(img, termsize)))
if args.display: if args.display:
dsp.sendframe(img_dsp) dsp.sendframe(img_dsp)
if args.pixelflut: if args.pixelflut:

17
misc.py Normal file
View file

@ -0,0 +1,17 @@
from PIL import Image
def resize_image(img, size, blackbg=True):
tw, th = size
w, h = img.size
a, b = w/tw, h/th
f = 1/max(a, b)
pos = int((tw-w*f)/2), int((th-h*f)/2)
buf = Image.new('RGBA', (tw, th))
buf.paste(img.resize((int(w*f), int(h*f))).convert('RGBA'), pos)
if blackbg:
buf2 = Image.new('RGBA', (tw, th), (0, 0, 0, 255))
return Image.alpha_composite(buf2, buf)
else:
return buf

50
pxf.py Normal file
View file

@ -0,0 +1,50 @@
import numpy as np
import ctypes
import time
from misc import resize_image
class Pixelflut:
def __init__(self, host, port, x, y, w, h, reps):
self.host, self.port = host.encode(), port
self.x, self.y = x, y
self.w, self.h = w, h
self.reps = reps
self.dbuf = np.zeros(w*h*4, dtype=np.uint8)
self.so = ctypes.CDLL('./pixelflut.so')
self.sock = None
def reset_images(self):
self.so.reset_images()
def sendframe(self, idx):
for _ in range(self.reps):
if self.sock is None:
while self.sock is None or self.sock < 0:
time.sleep(1)
self.sock = self.so.cct(self.host, self.port)
if self.so.sendframe(self.sock, idx, self.w, self.h, self.x, self.y):
self.so.discct(self.sock)
self.sock = None
def encode_image(self, img, idx=None):
frame = np.array(resize_image(img, (self.w, self.h), blackbg=False)).reshape(self.w*self.h*4)
np.copyto(self.dbuf, frame)
cptr = self.dbuf.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8))
if idx is None:
return self.so.store_image(cptr, self.w, self.h)
else:
self.so.store_image_idx(cptr, self.w, self.h, idx)
return None
class Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

103
redditor.py Executable file
View file

@ -0,0 +1,103 @@
#!/usr/bin/env python3
import json
import random
import socket
import struct
import time
import bz2
import os
import functools
import contextlib
import math
import ctypes
import io
from urllib.parse import *
import numpy as np
from PIL import Image
import praw
import bs4
import requests
from pixelterm import pixelterm
import pxf
def lesearchiter(term):
last = None
print('Searching term="{}", [initial]'.format(term))
for s in r.search(term):
last = s
yield s
while True:
print('Searching term="{}", after={}'.format(term, last.fullname))
for s in r.search(term, limit=100, after=last.fullname):
last = s
yield s
if __name__ == '__main__':
import argparse, pathlib, sys
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--pixelflut', type=str, default='94.45.232.225:1234')
parser.add_argument('term')
args = parser.parse_args()
target, *params = args.pixelflut.split('@')
host, port = target.split(':')
port = int(port)
x, y, *_r = params[0].split(',') if params else (0, 0, None)
w, h, reps = _r if _r else (320, 240)
x, y, w, h, reps = map(int, (x, y, w, h, reps))
pf = pxf.Pixelflut(host, port, x, y, w, h, reps) if args.pixelflut else None
r = praw.Reddit('Pixelflut search test by /u/jaseg')
r.refresh_access_information()
terms = args.term.split(',')
print('Search terms:', terms)
imgnum = 0
for s in lesearchiter(random.choice(terms)):
try:
url = s.url
# print(url)
if s.stickied:
# print(' → stickied')
continue
if s.is_self:
# print(' → self')
continue
stripped_down = urlunparse(urlparse(url)[:3] + (None,None,None))
l = stripped_down.lower()
if any(l.endswith(e) for e in ('.gif')):
# print(' → GIF filter')
continue
rq = requests.get(url)
if not rq.headers.get('content-type', '').startswith('image/'):
soup = bs4.BeautifulSoup(rq.text, 'lxml')
img = soup.find('img')
newurl = img.attrs['src']
if newurl.startswith('//'):
newurl = 'http:'+newurl
# print('Fetching', newurl)
rq = requests.get(newurl)
if not rq.headers.get('content-type', '').startswith('image/'):
# print(' → image filter:', rq.headers.get('content-type'))
continue
with open('/tmp/testdir/img_{}'.format(imgnum), 'wb') as f:
f.write(rq.content)
imgnum += 1
if imgnum >= 20:
sys.exit(0)
# bio = io.BytesIO()
# bio.write(rq.content)
# bio.seek(0)
# pimg = Image.open(bio)
# pf.encode_image(pimg, idx=0)
# pf.sendframe(0)
except Exception as e:
print(' → Exception:', e)