From 710bfdcd2bd3f4cacddcae4f9eaa0a69c0f99da7 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 2 Jun 2019 18:10:41 +0200 Subject: [PATCH] updates --- __pycache__/apirequest.cpython-37.pyc | Bin 0 -> 765 bytes __pycache__/imageprinter.cpython-37.pyc | Bin 0 -> 2551 bytes apirequest.py | 33 ++++++ imageprinter.py | 95 ++++++++++++++++ print.py | 142 ++++++++++++++++++++---- print_image.py | 83 ++++++-------- 6 files changed, 283 insertions(+), 70 deletions(-) create mode 100644 __pycache__/apirequest.cpython-37.pyc create mode 100644 __pycache__/imageprinter.cpython-37.pyc create mode 100644 apirequest.py create mode 100644 imageprinter.py diff --git a/__pycache__/apirequest.cpython-37.pyc b/__pycache__/apirequest.cpython-37.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c3ec9e8ccf9d7bfcdc2616ce6df404c9d4e8345 GIT binary patch literal 765 zcmZ9K&2G~`5P)aaYsaKbgsNV8LxPJhaf(DMRTV;%1E;7GNJthSx!ENNB(}R=OKD}F z%7Y|FF1!b?uvbn!bK}H}lk&H#ncbb4{h4p}d9T+6YG1$oczYuNzVqU)c{F)OQXY{~ zpl}Y!X2b+Ftb`J4Og!zaa1Du6o|2y-@s+Ov8im4F5Or>8FO04qO|30X;`s3K@nA^( z@Z`yGIE>R`7EiPt=b6=+9U})*lO#UL8AGk`5urvUkD|Ecn^}098 z?R1t+9(>5FOhulPDz&K#(xT9ra(-cEnT@0&YT!C!3bNX`Ag^puStpCUv|qsNkoV`q zc$zPCoW{$dx`>Ne*6!uxjlQgOX$QrX+hGpdhjeIHxkn06Qt#q@+{0ZFVkk_HtYf~E z8$OCz8lps*v^1KE0vXKNu{tK#R6r-BTw)Ncs`(vRUEkY_HArvh_kC6Ez!?kIX zHvB&l%Dk;zBn&^q1f(Lr4M>8lT3l#jLU!C^#hE#}aoQIXh58X!QrXrnkvBEWT0TWx|tT48Kb_BivQ zaHv>zW-fIPi@ogr3DR-*uh}z?yC+{am!hXWavay~4ERVsK7PE%-}~`lqv0X=zWx9E zS9^7Y{--)0J_3ygQ1ZWnporoa1yzj$totM&x;6p>Y7(1?6@`c(+~RR|YhcD@1vIUY9k?_n1&l0}dnu4DdZ z7`s4^LXHhZqetfr+&?9YkP$2BOH>kS6xc)tdX4$V)O?NewUl5a5VcP6kC@s8Iv;%q z=)!sLeAEFPkpfSNwsK2jd_xeh#;4>F`u?L55GRa@SwNO9p{YWXq1vmcL~kgd$^cZ= zPX6mZVJYLGV16=+MKp|=ufybnvwrBOqhyzH07&Y`*%1R(O8oh*-IIG; z+Hc5+%#TC9&({1uP8bbUzP!6tD(JtvUFzBIVQtj1r1zcjufuu9rCq^BT95|7M@Alv zr3+BIqfXrd68z2epmyP6P)ovbABILEFqK;p_cd@UaSis74Hy@FxR<`Vkrt?O1x{o) z@e*Kh2{!?qO}wBm`6=l4l>h2ej8=o9F)2VR6e|HrN(^iUsG1Og4vlG5n@V5cLkl?1 z09=`XLzDA@2teDRMaiGgDZU15C7g4Op)}A21TR9X1iOg~Xtja$&|z&#ez%?)GlWx^ z)Ku2m#;a^5Gt^SMi~6JiSl8zOoqgV#odQu)qjba^aH>Ncm`{LXFU~43b!qLC{Nrz$ zWt(E2dduJ^Fl=q2dNa$2)_fugRk)B_*MX_k?5ko4&OCQY zfZs2#x~y#fiQn9SEUR{DRx7=Lckmmujb1_x**Cux{Q$Aoh~po@b?ifd@8_>1-jw(@ z{|j_Z+;z&{t_yK2$6v=4bpK9krQ%vM171{vj zwR@fZoqMw83FA$e7Swjboax7aUr}otARb@P z_c9#ZG$pYrRMr~W4XueC literal 0 HcmV?d00001 diff --git a/apirequest.py b/apirequest.py new file mode 100644 index 0000000..ae99ae7 --- /dev/null +++ b/apirequest.py @@ -0,0 +1,33 @@ +import requests +import json + +r = requests.get("http://127.0.0.1:5000/api/getcontent") +data = r.json() + +def getcategory(category): + counter = 0 + output=[] + for post in data: + if data[post]["category"] == category: + output.append(data[post]["title"]) + counter+=1 + + if counter == 0: + print("Nothing found") + + return output + +def get(category, number): + counter = 1 + output = [] + for post in data: + if data[post]["category"] == category: + if counter == number: + output.append(data[post]["title"]) + output.append(data[post]["content"]) + counter+=1 + return output + + +#getcategory("thesis") +#get("thesis", 2) #thesis, exercise or term diff --git a/imageprinter.py b/imageprinter.py new file mode 100644 index 0000000..b31255b --- /dev/null +++ b/imageprinter.py @@ -0,0 +1,95 @@ +import argparse +import sys +import os +import six +from random import randint +from PIL import Image, ImageOps + +ESC = b'\x1B' +ETX = b'\x03' +SO = b'\x0E' + +GRAPHIC = b'\x1B'+b'\x2A'+b'\x01' #1B 2A +LINE_FEED = b'\n' +CARIDGE_RET = b'\x0D' +DATA = bytearray() +COLUMNS = 2000 +H = COLUMNS // 256 +L = COLUMNS % 256 + +def _to_column_format(im, line_height): + """ + Extract slices of an image as equal-sized blobs of column-format data. + + :param im: Image to extract from + :param line_height: Printed line height in dots + """ + width_pixels, height_pixels = im.size + top = 0 + left = 0 + blobs = [] + while left < width_pixels: + remaining_pixels = width_pixels - left + box = (left, top, left + line_height, top + height_pixels) + #transform: (size, method, data=None, resample=0, fill=1) + slice = im.transform((line_height, height_pixels), Image.EXTENT, box) + bytes = slice.tobytes() + blobs.append(bytes) + left += line_height + return blobs + +def _int_low_high(inp_number, out_bytes): + """ Generate multiple bytes for a number: In lower and higher parts, or more parts as needed. + to generate the H and L value + :param inp_number: Input number + :param out_bytes: The number of bytes to output (1 - 4). + """ + max_input = (256 << (out_bytes * 8) - 1); + if not 1 <= out_bytes <= 4: + raise ValueError("Can only output 1-4 byes") + if not 0 <= inp_number <= max_input: + raise ValueError("Number too large. Can only output up to {0} in {1} byes".format(max_input, out_bytes)) + outp = b''; + for _ in range(0, out_bytes): + outp += six.int2byte(inp_number % 256) + inp_number = inp_number // 256 + return outp + + +def print(filename): + im = Image.open(filename) + + basewidth = 350 + # Initial rotate. mirror, and extract blobs for each 8 or 24-pixel row + # Convert to black & white via greyscale (so that bits can be inverted) + + im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT) + height_pixels, width_pixels = im.size + + if width_pixels > basewidth: + wpercent = (basewidth/float(im.size[0])) + hsize = int((float(im.size[1])*float(wpercent))) + im = im.resize((basewidth,hsize), Image.NEAREST) + + height_pixels, width_pixels = im.size + im = im.resize((height_pixels,int(width_pixels*1.5)), Image.ANTIALIAS) + + im = im.convert("L") # Invert: Only works on 'L' images + im = ImageOps.invert(im) # Bits are sent with 0 = white, 1 = black in ESC/POS + im = im.convert("1") # Pure black and white + #im.show() + line_height = 1 + blobs = _to_column_format (im, line_height * 8); + + height_pixels, width_pixels = im.size + + with open('/dev/tty', 'wb') as fp: + fp.write(ESC+b"@") + fp.write(ESC+b"\x7B"+b"\x41") + fp.write(ESC + b"3" + six.int2byte(22)); # Adjust line-feed size + fp.write(CARIDGE_RET) + for blob in blobs: + fp.write(GRAPHIC + _int_low_high( width_pixels, 2 ) + blob) + fp.write(LINE_FEED) + #fp.write(GRAPHIC + bytes([L,H]) + DATA) + fp.write(ESC + b"2"); # Reset line-feed size diff --git a/print.py b/print.py index e9bc7db..46ccb0e 100644 --- a/print.py +++ b/print.py @@ -3,10 +3,13 @@ import sys import os import six from random import randint +import random from PIL import Image, ImageOps import curses import sys, termios, tty, os, time - +import apirequest +import imageprinter +import requests class Printer(): ESC = b'\x1B' @@ -22,6 +25,9 @@ class Printer(): def printchar(self,char): with open(self.target, 'wb') as printer: + if self.debug: + printer.write(bytes(str(char), 'utf-8')) + else: printer.write(self.ESC+b"\x7B"+b"\x41") char=self.strokes*" "+char printer.write(bytes(str(char), 'utf-8')) @@ -33,9 +39,12 @@ class Printer(): def printstring(self,string): with open(self.target, 'wb') as printer: - printer.write(self.ESC+b"\x7B"+b"\x41") - printer.write(bytes(str(string), 'utf-8')) - printer.write(self.ESC+b"\x25"+b"\x46"+b"\x0F"+b"\x00"+b"\x04"+b"\x08"+b"\x00") + if self.debug: + printer.write(bytes(str(string), 'utf-8')) + else: + printer.write(self.ESC+b"\x7B"+b"\x41") + printer.write(bytes(str(string), 'utf-8')) + printer.write(self.ESC+b"\x25"+b"\x46"+b"\x0F"+b"\x00"+b"\x04"+b"\x08"+b"\x00") self.newline() @@ -49,27 +58,34 @@ class Printer(): class Terminal(): lineinput = "" - commandMode = False + commandMode = True writeloop = True - def __init__(self,printer): + def __init__(self,printer, persons): self.printer = printer + self.persons = persons + + def waittostart(self): + self.writeloop = True + while self.writeloop: + char = self.getch() + self.writeloop = False + self.lineinput = "" + continue def waitforinput(self): - term.writeloop = True + self.writeloop = True while self.writeloop: char = self.getch() - self.lineinput+=char - print(self.lineinput) if (ord(char) == 27): print("exit publication :-(") exit(0) if (ord(char) == 13): self.printer.newline() - self.checkforcommand(self.lineinput) + self.command(self.lineinput) self.lineinput = "" else: - print(char) + self.lineinput+=char self.printer.printchar(char) def getch(self): @@ -83,21 +99,99 @@ class Terminal(): termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch - def checkforcommand(self, command): - print("received command:"+command) - if command == "help": + def command(self, command): + #print("received command: "+str(command)) + if "help" == str(command): + self.printer.printstring("type commands to print the publication") + self.printer.printstring("help:") + self.printer.printstring(" get help on the commands") + #self.writeloop = False + + elif str(command).split(" ")[0] == "exercise" or str(command).split(" ")[0] == "thesis": + part = str(command).split(" ")[0] + try: + arguments = str(command.strip()).split(" ") + arguments.pop(0) + for i,arg in enumerate(arguments): + if arg.isdigit(): + number = int(arg) + if number > len(apirequest.getcategory(part)): + self.printer.printstring("Number must be inbetween 1 and "+ str(len(apirequest.getcategory(part)))) + else: + result = apirequest.get(part, number) + for line in result: + self.printer.printstring(line) + self.printer.newline() + else: + raise Exeption("not a number") + except: + self.printer.printstring("ERROR: no argument given. Usage: "+part+" ") + + elif str(command).split(" ")[0] == "whois": + if str(command).split(" ")[1] in self.persons: + self.printer.printstring(self.persons[str(command).split(" ")[1]]) + else: + self.printer.printstring("Sorry not found, try " + random.choice(list(self.persons))) + + elif "exit" == str(command): + self.printer.printstring("Imprint") + result = apirequest.get("imprint", 1) + for line in result: + self.printer.printstring(line) + self.printer.newline() + main() + + else: + self.printer.printstring("~ command not found. try help for a list of available commands") + + self.printer.newline() #if the command is valid we want to execute the command and continue the story #self.writeloop = False - +persons = { +"Kittler":"Friedrich A. Kittler (June 12, 1943 – October 18, 2011) was a literary scholar and a media theorist. His works relate to media, technology, and the military. ", +"Alex":"Alexander Roidl created Poetic Software as part of his Master's thesis" +} printer = Printer() -term = Terminal(printer) -printer.printstring("W E L C O M E !") -printer.printstring("---------------") -printer.printstring("POETIC SOFTWARE") -printer.printstring("---------------") -printer.printstring("type help for help") -term.waitforinput() -printer.printstring("write a command") -term.waitforinput() +term = Terminal(printer, persons) + +def printimagefromurl(url): + page = requests.get(url) + f_ext = os.path.splitext(url)[-1] + f_name = 'img{}'.format(f_ext) + with open(f_name, 'wb') as f: + f.write(page.content) + + imageprinter.print(f_name) + +def main(): + term.waittostart() + printer.printstring("W E L C O M E !") + + printimagefromurl('https://apod.nasa.gov/apod/image/1701/potw1636aN159_HST_2048.jpg') + + printer.printstring("---------------") + printer.printstring("POETIC SOFTWARE") + printer.printstring("---------------") + printer.printstring("type help for help") + printer.newline() + result = apirequest.get("introduction", 1) + for line in result: + printer.printstring(line) + printer.newline() + printer.printstring("theses on POETIC SOFTWARE") + result = apirequest.getcategory("thesis") + for i, line in enumerate(result): + printer.printstring(str(i+1)+" "+line) + printer.newline() + printer.printstring("exercises in POETIC SOFTWARE") + result = apirequest.getcategory("exercise") + for i, line in enumerate(result): + printer.printstring(str(i+1)+" "+line) + printer.newline() + printer.printstring("SELECT which one to see, for exercise type: exercise and for thesis type: thesis ") + printer.newline() + term.waitforinput() + +main() diff --git a/print_image.py b/print_image.py index 96434a9..469c248 100644 --- a/print_image.py +++ b/print_image.py @@ -56,49 +56,40 @@ def _int_low_high(inp_number, out_bytes): return outp -parser = argparse.ArgumentParser(description='Process some imagefile') -parser.add_argument('--img',dest="img", - help='pass image to print') -args = parser.parse_args() -filename = args.img -im = Image.open(filename) - -basewidth = 350 -# Initial rotate. mirror, and extract blobs for each 8 or 24-pixel row -# Convert to black & white via greyscale (so that bits can be inverted) - -im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT) -height_pixels, width_pixels = im.size - -if width_pixels > basewidth: - wpercent = (basewidth/float(im.size[0])) - hsize = int((float(im.size[1])*float(wpercent))) - im = im.resize((basewidth,hsize), Image.NEAREST) - -height_pixels, width_pixels = im.size -im = im.resize((height_pixels,int(width_pixels*1.5)), Image.ANTIALIAS) - -im = im.convert("L") # Invert: Only works on 'L' images -im = ImageOps.invert(im) # Bits are sent with 0 = white, 1 = black in ESC/POS -im = im.convert("1") # Pure black and white - -line_height = 1 -blobs = _to_column_format (im, line_height * 8); - - -#generate random Data -for i in range(COLUMNS): - DATA.append(randint(0,255)) - -height_pixels, width_pixels = im.size - -with open('/dev/usb/lp0', 'wb') as fp: - fp.write(ESC+b"@") - fp.write(ESC+b"\x7B"+b"\x41") - fp.write(ESC + b"3" + six.int2byte(22)); # Adjust line-feed size - fp.write(CARIDGE_RET) - for blob in blobs: - fp.write(GRAPHIC + _int_low_high( width_pixels, 2 ) + blob) - fp.write(LINE_FEED) - #fp.write(GRAPHIC + bytes([L,H]) + DATA) - fp.write(ESC + b"2"); # Reset line-feed size +def print(filename): + im = Image.open(filename) + + basewidth = 350 + # Initial rotate. mirror, and extract blobs for each 8 or 24-pixel row + # Convert to black & white via greyscale (so that bits can be inverted) + + im = im.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT) + height_pixels, width_pixels = im.size + + if width_pixels > basewidth: + wpercent = (basewidth/float(im.size[0])) + hsize = int((float(im.size[1])*float(wpercent))) + im = im.resize((basewidth,hsize), Image.NEAREST) + + height_pixels, width_pixels = im.size + im = im.resize((height_pixels,int(width_pixels*1.5)), Image.ANTIALIAS) + + im = im.convert("L") # Invert: Only works on 'L' images + im = ImageOps.invert(im) # Bits are sent with 0 = white, 1 = black in ESC/POS + im = im.convert("1") # Pure black and white + + line_height = 1 + blobs = _to_column_format (im, line_height * 8); + + height_pixels, width_pixels = im.size + + with open('/dev/tty', 'wb') as fp: + fp.write(ESC+b"@") + fp.write(ESC+b"\x7B"+b"\x41") + fp.write(ESC + b"3" + six.int2byte(22)); # Adjust line-feed size + fp.write(CARIDGE_RET) + for blob in blobs: + fp.write(GRAPHIC + _int_low_high( width_pixels, 2 ) + blob) + fp.write(LINE_FEED) + #fp.write(GRAPHIC + bytes([L,H]) + DATA) + fp.write(ESC + b"2"); # Reset line-feed size