diff --git a/src/main.py b/src/main.py index 7466662..2152d2a 100644 --- a/src/main.py +++ b/src/main.py @@ -50,21 +50,24 @@ from printers import Printers # Logging configuration -dictConfig({ - 'version': 1, - 'formatters': {'default': { - 'format': '[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m', - }}, - 'handlers': {'wsgi': { - 'class': 'logging.StreamHandler', - 'stream': 'ext://flask.logging.wsgi_errors_stream', - 'formatter': 'default' - }}, - 'root': { - 'level': 'INFO', - 'handlers': ['wsgi'] +dictConfig( + { + "version": 1, + "formatters": { + "default": { + "format": "[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m", + } + }, + "handlers": { + "wsgi": { + "class": "logging.StreamHandler", + "stream": "ext://flask.logging.wsgi_errors_stream", + "formatter": "default", + } + }, + "root": {"level": "INFO", "handlers": ["wsgi"]}, } -}) +) # We create the main Flask object @@ -147,7 +150,9 @@ except Exception as e: workers = set() for i in range(len(printers_pool)): try: - worker = PrintWorker(app, print_queue, printers_pool=printers_pool, printer_index=i) + worker = PrintWorker( + app, print_queue, printers_pool=printers_pool, printer_index=i + ) workers.add(worker) worker.start() except Exception as e: @@ -157,7 +162,9 @@ for i in range(len(printers_pool)): for i in threading.enumerate(): app.logger.debug(i) -app.logger.info("\n\n\t\033[36m🖶\033[0m \033[93m🖶\033[0m \033[95m🖶\033[0m \033[97mWelcome to LittlePrynter !\n\n") +app.logger.info( + "\n\n\t\033[36m🖶\033[0m \033[93m🖶\033[0m \033[95m🖶\033[0m \033[97mWelcome to LittlePrynter !\n\n" +) # The rate limit @@ -165,6 +172,7 @@ limiter = Limiter( get_remote_address, app=app, default_limits=["104800 per day", "10200 per hour"] ) + # General routes @app.route("/") @limiter.limit("5/second", override_defaults=False) @@ -181,6 +189,7 @@ def webcam(): app.logger.debug("Loading webcam interface") return render_template("webcam.html") + # General routes @app.route("/queue") @limiter.limit("5/second", override_defaults=False) @@ -189,7 +198,12 @@ def queue(): app.logger.debug("Loading queue") current_queue = print_queue.get_queue_state() completed_queue = print_queue.get_queue_completed() - return render_template("queue.html", tasks=current_queue, completed_tasks=completed_queue, worker_state=worker.current_state()) + return render_template( + "queue.html", + tasks=current_queue, + completed_tasks=completed_queue, + worker_state=worker.current_state(), + ) # Form treatement @@ -439,7 +453,7 @@ def api_queue_completed(): @limiter.limit("160/minute", override_defaults=True) def api_worker_state(): """API endpoint to get the worker state""" - return jsonify([ w.current_state() for w in workers ]) + return jsonify([w.current_state() for w in workers]) # TODO : Auth @@ -451,7 +465,8 @@ def api_worker_start(): """ for w in workers: w.start_worker() - return jsonify([ w.current_state() for w in workers ]) + return jsonify([w.current_state() for w in workers]) + # TODO : Auth @app.route("/api/workers/stop") @@ -462,7 +477,8 @@ def api_worker_stop(): """ for w in list(workers): w.stop_worker() - return jsonify([ w.current_state() for w in workers ]) + return jsonify([w.current_state() for w in workers]) + # TODO : Auth @app.route("/api/printers") @@ -474,6 +490,7 @@ def api_printers_info(): ## Authentification + @app.route("/login") @limiter.limit("1/second", override_defaults=False) def login_page(): @@ -526,5 +543,6 @@ def camera_status(): else: socketio.emit("camera_status", False) + if __name__ == "__main__": app.run(use_reloader=False, host="0.0.0.0", ssl_context="adhoc") diff --git a/src/print_queue.py b/src/print_queue.py index e8a20a9..5d7fc5f 100644 --- a/src/print_queue.py +++ b/src/print_queue.py @@ -105,7 +105,7 @@ class PrintQueue: "in_queue": True, "content": task.content, "signature": task.signature, - "log" : task.log, + "log": task.log, } if task.task_type == TaskType.TEXT: @@ -118,7 +118,7 @@ class PrintQueue: "image_path": str(task.image_path), "signature": task.signature, "process": str(task.process), - "log" : task.log, + "log": task.log, } return None diff --git a/src/printer.py b/src/printer.py index ae0aada..f6d2eab 100644 --- a/src/printer.py +++ b/src/printer.py @@ -28,6 +28,7 @@ from brother_ql import create_label # Used for typing from task import PrintTask + class PrinterType(Enum): """ What are the capacities of a Printer ? @@ -115,7 +116,7 @@ class EscPosPrinter(Printer): Making sure it has paper, Define default print settings """ - super().__init__(app, vendor_id, device_id,printer_type=PrinterType.EPSON) + super().__init__(app, vendor_id, device_id, printer_type=PrinterType.EPSON) self.printer = None self.usb_args = {} self.usb_args["idVendor"] = self.vendor_id @@ -257,7 +258,6 @@ class EscPosPrinter(Printer): if do_cut: self._cut() - self.app.logger.info("Printed text") self.ready = True @@ -383,11 +383,16 @@ class EscPosPrinter(Printer): match (task.task_type.value): case "text": - self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"]) + self._print_txt( + data["txt"], signature=data["sign"], do_cut=data["do_cut"] + ) self.ready = True case "image": self._print_img( - data["img"], signature=data["sign"], process=data["process"], do_cut=data["do_cut"] + data["img"], + signature=data["sign"], + process=data["process"], + do_cut=data["do_cut"], ) self.ready = True case "qr": @@ -428,9 +433,7 @@ class BrotherPrinter(Printer): # Match vendor and product IDs so this instance doesn't accidentally # use the identifier belonging to the last device in the backend list. - expected_prefix = ( - f"usb://0x{vendor_id:04x}:0x{device_id:04x}/" - ).lower() + expected_prefix = (f"usb://0x{vendor_id:04x}:0x{device_id:04x}/").lower() matching_identifiers = [] @@ -451,8 +454,16 @@ class BrotherPrinter(Printer): matching_identifiers.append(identifier) if len(matching_identifiers) != 1: - self.app.logger.error("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) ) - raise RuntimeError("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) ) + self.app.logger.error( + "Expected one Brother backend device matching %s, found %s", + expected_prefix, + len(matching_identifiers), + ) + raise RuntimeError( + "Expected one Brother backend device matching %s, found %s", + expected_prefix, + len(matching_identifiers), + ) # Extract connection details from the identifier for this printer only. identifier = matching_identifiers[0] @@ -496,7 +507,6 @@ class BrotherPrinter(Printer): self.app.logger.debug("Created a Brother printer!") self.ready = True - def _has_paper(self): raise NotImplementedError("This printer model does not support this.") @@ -512,21 +522,20 @@ class BrotherPrinter(Printer): if do_cut: self._cut() - - def _print_img( - self, - data, - signature="", - process=False, - do_cut=False - ): + def _print_img(self, data, signature="", process=False, do_cut=False): """ Print a raster image via a Brother QL printer """ - self.app.logger.debug("Printing an image %s via Brother printer ( %s )" , data, self.printer_info.model ) + self.app.logger.debug( + "Printing an image %s via Brother printer ( %s )", + data, + self.printer_info.model, + ) if process: try: - self.app.logger.debug("\t[⚙ %s] Proccessing the image", threading.get_ident()) + self.app.logger.debug( + "\t[⚙ %s] Proccessing the image", threading.get_ident() + ) processed_path = _process_image(self, data) except RuntimeError as e: self.app.logger.error( @@ -547,8 +556,6 @@ class BrotherPrinter(Printer): ) raise e - - try: qlr = BrotherQLRaster(self.printer_info.model) @@ -570,7 +577,7 @@ class BrotherPrinter(Printer): compress=False, dpi_600=False, cut=False, - ) + ) success = send( instructions=instructions, @@ -679,29 +686,47 @@ class BrotherPrinter(Printer): """Execute actual print based on task type""" i_m_ready = self._state() while not i_m_ready: - self.app.logger.debug("\t[⚙ %s] Waiting for the printer to become ready, current state %s ", self.id, str(i_m_ready)) + self.app.logger.debug( + "\t[⚙ %s] Waiting for the printer to become ready, current state %s ", + self.id, + str(i_m_ready), + ) i_m_ready = self._state() time.sleep(0.3) - self.app.logger.debug("\t[⚙ %s] Checked state to start printing %s ", self.id, self._state()) + self.app.logger.debug( + "\t[⚙ %s] Checked state to start printing %s ", self.id, self._state() + ) self.ready = False try: match (task.task_type.value): case "image": - self._print_img(data["img"], signature=data["sign"], do_cut=data["do_cut"]) + self._print_img( + data["img"], signature=data["sign"], do_cut=data["do_cut"] + ) case "text": - self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"]) + self._print_txt( + data["txt"], signature=data["sign"], do_cut=data["do_cut"] + ) case _: raise RuntimeError("This task type is not supported") except ValueError as ve: - self.app.logger.error("\t[⚙ %s] The printer couldn't be found, the printing failed for task %s of type , error : %s ",self.id, task.task_id, task.value, str(ve)) + self.app.logger.error( + "\t[⚙ %s] The printer couldn't be found, the printing failed for task %s of type , error : %s ", + self.id, + task.task_id, + task.value, + str(ve), + ) raise ve except Exception as e: raise e - self.app.logger.debug("\t[⚙ %s] Finished consuming task %s", self.id, task.task_id) + self.app.logger.debug( + "\t[⚙ %s] Finished consuming task %s", self.id, task.task_id + ) self.ready = True @@ -733,7 +758,9 @@ def _process_image(self, path, max_width=575, max_height=1000): "Image is dark; increasing brightness by %.2f", brightness_factor, ) - grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(brightness_factor) + grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance( + brightness_factor + ) contrast = float(np.asarray(grayscale_image, dtype=np.float32).std()) self.app.logger.debug("Grayscale standard deviation: %.2f", contrast) @@ -758,7 +785,7 @@ def text_to_image( background="white", fill="black", output_dir="src/static/uploads", - ): +): """Converts a string to an image""" font = ImageFont.truetype(font_path, font_size) @@ -829,7 +856,13 @@ def text_to_image( return str(image_path) -def _resize_image(self,label_type: str, image_path: str, device_pixel_width: int, printer_model: object): +def _resize_image( + self, + label_type: str, + image_path: str, + device_pixel_width: int, + printer_model: object, +): # """ # Resize an image to the specs needed for a label. Only used in Brother printers # """ @@ -845,7 +878,6 @@ def _resize_image(self,label_type: str, image_path: str, device_pixel_width: int # self.app.logger.debug("Found label %s with maximum dimensions %s", label_type, max_image_dimension) - # # Open image # with Image.open(image_path ) as img: # self.app.logger.debug("Image current dimensions before resizing are %s", img.size) diff --git a/src/printers.py b/src/printers.py index ac4c3e7..dae96f7 100644 --- a/src/printers.py +++ b/src/printers.py @@ -102,8 +102,10 @@ class Printers: app=self.app, vendor_id=vendir, device_id=prid, - configuration_file=self.configuration_file["printer"]["epson"] - ) + configuration_file=self.configuration_file["printer"][ + "epson" + ], + ) except Exception as e: raise e @@ -119,8 +121,10 @@ class Printers: self.app, dev.idVendor, dev.idProduct, - configuration_file=self.configuration_file["printer"]["brother"] - ) + configuration_file=self.configuration_file["printer"][ + "brother" + ], + ) except Exception as e: self.app.logger.error( "Could not create a %s printer class with %s:%s", @@ -132,12 +136,18 @@ class Printers: # If the object creation is successfull, we add it to the list of Printers printers.add(brother_printer) - self.app.logger.debug("Found a %s printer with id %s", manufacturer, brother_printer.printer_info.identifier) + self.app.logger.debug( + "Found a %s printer with id %s", + manufacturer, + brother_printer.printer_info.identifier, + ) case _: self.app.logger.debug( "Found a printer of unknown manufacturer : %s", manufacturer ) - self.app.logger.debug("We are not adding this printer to the printers pool. Ignoring.") + self.app.logger.debug( + "We are not adding this printer to the printers pool. Ignoring." + ) # end match self.app.logger.debug("Found %s printers", len(printers)) @@ -177,9 +187,9 @@ class Printers: printers_info_list.append( { "Name": i.printer_type.name, - "Used" : i.used, - "Ready" : i.ready, - "Info" : i.printer_info, + "Used": i.used, + "Ready": i.ready, + "Info": i.printer_info, } ) @@ -188,6 +198,7 @@ class Printers: def __len__(self): return len(self.printers) + class _FindClass: """ Use by usb.core to modify the way USB devices are found diff --git a/src/task.py b/src/task.py index 32206bb..5c0312c 100644 --- a/src/task.py +++ b/src/task.py @@ -96,12 +96,19 @@ class ImageTask(PrintTask): def get_print_data(self): # Return image data in printer-compatible format - return {"img": self.image_path, "sign": self.signature, "process": self.process, "do_cut": self.do_cut} + return { + "img": self.image_path, + "sign": self.signature, + "process": self.process, + "do_cut": self.do_cut, + } + class RemoveTask(PrintTask): """ This class is used to clear images and leftovers after a print """ + def __init__(self, task_id, image_path): super().__init__(TaskType.REMOVE) self.task_id = self._generate_id() if not task_id else task_id @@ -111,4 +118,4 @@ class RemoveTask(PrintTask): # the task existence in itself is indication of what to do def get_print_data(self): # Return image data in printer-compatible format - return {"img": self.image_path} \ No newline at end of file + return {"img": self.image_path} diff --git a/src/web.py b/src/web.py index bbcb5f6..e32e728 100644 --- a/src/web.py +++ b/src/web.py @@ -30,8 +30,14 @@ class Web: # are added back to back, another task could be # inserted between the two. for i in range(many): - sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign, do_cut=do_cut)) - self.app.logger.info("Added a SMS task at position %s, it should %scut", sms, "" if not do_cut else "not ") + sms = self.print_queue.enqueue( + TextTask(content=texte, signature=sign, do_cut=do_cut) + ) + self.app.logger.info( + "Added a SMS task at position %s, it should %scut", + sms, + "" if not do_cut else "not ", + ) self.app.logger.debug("%s", do_cut) except Exception as e: self.app.logger.error(e) @@ -41,7 +47,7 @@ class Web: def print_image( self, image, sign: str, do_cut: bool, process_image: bool, many: int = 1 - ) -> bool: + ) -> bool: """ Get an image and a signature, prints the image and cuts after that. """ @@ -62,15 +68,19 @@ class Web: ImageTask( os.path.join( self.app.config["UPLOAD_FOLDER"], - secure_filename(str(file_uploaded.split("/").pop())) + secure_filename(str(file_uploaded.split("/").pop())), ), signature=sign, process=process_image, task_id=str(uuid.uuid4()), - do_cut=do_cut + do_cut=do_cut, ) ) - self.app.logger.info("Added a IMG task at position %s, it should %s cut", img, "not " if not do_cut else "") + self.app.logger.info( + "Added a IMG task at position %s, it should %s cut", + img, + "not " if not do_cut else "", + ) except Exception as e: raise RuntimeError("Could not add IMG to queue " + str(e)) from e @@ -107,7 +117,9 @@ class Web: extension = filename.split(".").pop() self.app.logger.debug("File valid") try: - image_uuid_path = os.path.join(self.app.config["UPLOAD_FOLDER"], image_uuid + "." + extension) + image_uuid_path = os.path.join( + self.app.config["UPLOAD_FOLDER"], image_uuid + "." + extension + ) image.save(image_uuid_path) except OSError as e: self.app.logger.error("Could not save file %s", e) diff --git a/src/worker.py b/src/worker.py index fb32037..ab03c32 100644 --- a/src/worker.py +++ b/src/worker.py @@ -10,7 +10,6 @@ import random from uuid import uuid4 - class PrintWorker(threading.Thread): """ A thread used to consume Tasks added to a Print Queue. @@ -23,7 +22,7 @@ class PrintWorker(threading.Thread): tasks. TODO : Change that """ - def __init__(self, app, print_queue, printers_pool, printer_index=0 ): + def __init__(self, app, print_queue, printers_pool, printer_index=0): super().__init__(daemon=True) self.app = app self.print_queue = print_queue @@ -39,7 +38,12 @@ class PrintWorker(threading.Thread): self._printer_index = printer_index self.printer = self._acquire_available_printer() - self.app.logger.debug("\t[⚙ %s][%s] is ready to work with printer %s", self.id, threading.get_ident(), self.printer.printer_info.model) + self.app.logger.debug( + "\t[⚙ %s][%s] is ready to work with printer %s", + self.id, + threading.get_ident(), + self.printer.printer_info.model, + ) def _acquire_available_printer(self): result = self.printers.acquire_available_printer( @@ -56,7 +60,9 @@ class PrintWorker(threading.Thread): def run(self): """Background thread that processes queue items""" - self.app.logger.debug("\t[⚙ %s][%s] started working", self.id, threading.get_ident()) + self.app.logger.debug( + "\t[⚙ %s][%s] started working", self.id, threading.get_ident() + ) while True: # If the printer is dead or asleep, it can't work. @@ -74,12 +80,15 @@ class PrintWorker(threading.Thread): if self.running and self.printer is None: self.app.logger.debug( - "\t[⚙ %s] Trying to find a available printer for the worker.", self.id + "\t[⚙ %s] Trying to find a available printer for the worker.", + self.id, ) self.printer = self._acquire_available_printer() self.app.logger.debug( - "\t[⚙ %s] Got a %s ( %s ) printer and it's %s", self.id , - self.printer.printer_info.name, self.printer.printer_info.model, + "\t[⚙ %s] Got a %s ( %s ) printer and it's %s", + self.id, + self.printer.printer_info.name, + self.printer.printer_info.model, "Ready" if self.printer.ready else "Not ready", ) @@ -92,7 +101,9 @@ class PrintWorker(threading.Thread): # If the printer is not ready, we wait for it to become ready. if not self.printer.ready: - self.app.logger.debug("\t[⚙ %s] Waiting for our printer to become ready...", self.id) + self.app.logger.debug( + "\t[⚙ %s] Waiting for our printer to become ready...", self.id + ) time.sleep(1) continue @@ -108,7 +119,9 @@ class PrintWorker(threading.Thread): # self.app.logger.debug("\t[⚙ %s] Trying to get a task from the queue ", self.id) task = self.print_queue.dequeue() except Exception as e: - self.app.logger.error("\t[⚙ %s] Could not get a new task %s ", self.id, str(e)) + self.app.logger.error( + "\t[⚙ %s] Could not get a new task %s ", self.id, str(e) + ) self.state = "idle" self.printer.free_printer() raise RuntimeError( @@ -116,7 +129,12 @@ class PrintWorker(threading.Thread): ) from e if task: - self.app.logger.debug("\t[⚙ %s] Got a new task %s %s", self.id, task.task_type, task.task_id) + self.app.logger.debug( + "\t[⚙ %s] Got a new task %s %s", + self.id, + task.task_type, + task.task_id, + ) task.status = "processing" @@ -164,9 +182,13 @@ class PrintWorker(threading.Thread): Return the worker state """ return { - "id" : self.id, + "id": self.id, "is_running": self.running, "queue_size": len(self.print_queue), "state": self.state, - "printer": self.printer.printer_info.model if self.printer.printer_info.model else "No printer", + "printer": ( + self.printer.printer_info.model + if self.printer.printer_info.model + else "No printer" + ), }