🔍 Code Extractor

class Cassette_Printer

Maturity: 56

A class that generates and saves cassette label images for printing by writing cassette information to a shared folder monitored by a Windows virtual PC.

File:
/tf/active/vicechatdev/resources/printers.py
Lines:
13 - 52
Complexity:
moderate

Purpose

The Cassette_Printer class is responsible for creating cassette label files for physical printing. It retrieves cassette information (parblock and customer data) from a Neo4j graph database using a unique identifier, then writes this information to a text file in a shared directory. The class is designed to integrate with a Windows-based printing system that monitors the shared folder for new files. It supports conditional printing based on configuration settings and includes functionality to save bitmap images of cassette labels.

Source Code

class Cassette_Printer:
    """
    Class to print cassettes. Saves cassette image to shared folder, which is watched from a windows virtual pc to print the file
    
    Parameters
    ----------
    uid : str
        The unique ID of the cassette we wish to print
    
    Attributes
    ----------
    uid : str
        The unique ID of the cassette we wish to print
    graph : py2neo.Graph
        Connection to the database
    """
    def __init__(self, uid):
        self.uid=uid
        self.graph = Graph(config.DB_ADDR, auth=config.DB_AUTH, name=config.DB_NAME)

        self.make_cassete_image()
        
    def make_cassete_image(self):
        # today = dt.datetime.now().strftime('%Y-%m-%d')
        parblock=self.graph.run("match (b:Parblock {UID:'"+self.uid+"'}) return b.N").evaluate()
        filename = parblock.replace("#","_")
        customer=self.graph.run(f"""
            MATCH (b:Parblock {{UID:'{self.uid}'}})<-[*]-(c:Customer) 
            RETURN DISTINCT CASE WHEN c.shorthand IS NOT NULL THEN c.shorthand ELSE c.N END 
        """).evaluate()
        print("PARLBOCK PRINTIGN WITH INFO", parblock, customer)
        if config.PRINT_CASSETTE:
            with open(f"/tf/appserver/cassette/{filename}.txt", "w") as f:
                f.write(f"{parblock},{customer}")
        
    def save_image(self, pil_img, parblock):
        if config.PRINT_CASSETTE:
            pil_img.save("/tf/appserver/cassette/"+parblock.replace('#','_')+".bmp")
            # pil_img.save("./temp/"+parblock.replace('#','_')+".png")
        return

Parameters

Name Type Default Kind
bases - -

Parameter Details

uid: A unique identifier string for the cassette to be printed. This UID is used to query the Neo4j database to retrieve the associated parblock and customer information. The UID should correspond to a Parblock node in the database.

Return Value

The constructor (__init__) returns an instance of Cassette_Printer. The class does not return values from its main methods; instead, it performs side effects by writing files to the filesystem. The make_cassete_image() method returns None implicitly. The save_image() method explicitly returns None after saving the image file.

Class Interface

Methods

__init__(self, uid: str)

Purpose: Initializes the Cassette_Printer instance, establishes database connection, and automatically triggers cassette image generation

Parameters:

  • uid: Unique identifier string for the cassette to be printed, must correspond to a Parblock node in the Neo4j database

Returns: None (constructor)

make_cassete_image(self) -> None

Purpose: Queries the database for parblock and customer information, then writes this data to a text file in the shared cassette directory

Returns: None. Side effect: creates a text file in /tf/appserver/cassette/ with format '{parblock},{customer}' if config.PRINT_CASSETTE is True

save_image(self, pil_img: PIL.Image.Image, parblock: str) -> None

Purpose: Saves a PIL Image object as a bitmap file to the cassette directory with the parblock name

Parameters:

  • pil_img: A PIL Image object containing the cassette label image to be saved
  • parblock: The parblock identifier string used as the filename (# characters will be replaced with _)

Returns: None. Side effect: saves a .bmp file to /tf/appserver/cassette/ if config.PRINT_CASSETTE is True

Attributes

Name Type Description Scope
uid str The unique identifier of the cassette to be printed, used for database queries instance
graph py2neo.Graph Connection object to the Neo4j graph database, used to query parblock and customer information instance

Dependencies

  • py2neo
  • PIL
  • datetime
  • math
  • re
  • pylibdmtx
  • numpy
  • config

Required Imports

from neo4j_driver import *
import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageOps
import datetime as dt
import math
import re
from pylibdmtx.pylibdmtx import decode
from pylibdmtx.pylibdmtx import encode
import numpy as np
import config

Usage Example

# Ensure config module has required settings
# config.DB_ADDR = 'bolt://localhost:7687'
# config.DB_AUTH = ('username', 'password')
# config.DB_NAME = 'neo4j'
# config.PRINT_CASSETTE = True

# Instantiate the printer with a cassette UID
printer = Cassette_Printer(uid='CASSETTE_12345')

# The constructor automatically generates and saves the cassette file
# No additional method calls needed for basic usage

# Optionally save a PIL image for the cassette
from PIL import Image
pil_image = Image.new('RGB', (200, 100), color='white')
printer.save_image(pil_image, 'PARBLOCK#001')

Best Practices

  • Ensure the Neo4j database is accessible and properly configured before instantiating the class
  • Verify that the /tf/appserver/cassette/ directory exists and has write permissions
  • The class automatically executes make_cassete_image() upon instantiation, so be aware of immediate side effects
  • Use config.PRINT_CASSETTE flag to control whether files are actually written (useful for testing)
  • The uid parameter must correspond to an existing Parblock node in the database
  • File names are sanitized by replacing '#' characters with '_' to ensure filesystem compatibility
  • The class maintains a database connection (self.graph) throughout its lifetime
  • save_image() method expects a PIL Image object and a parblock identifier string
  • Customer shorthand is preferred over full customer name if available in the database
  • The class is designed for single-use: create an instance per cassette to print

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class print_client 54.0% similar

    A class that generates formatted print messages for different types of laboratory objects (Parblock, Organ, Study, Slide, Reagent) by querying a Neo4j graph database and building a pipe-delimited message string.

    From: /tf/active/vicechatdev/resources/printclient.py
  • class TSC_Label 50.3% similar

    A class for creating and printing TSCPL2 format labels for laboratory information system (LIS) objects, specifically designed for TSC label printers with support for DataMatrix barcodes and text formatting.

    From: /tf/active/vicechatdev/resources/printers.py
  • class Delivery_documents 47.6% similar

    A class that generates delivery documentation (slip and label) as Word documents by querying a Neo4j database for study and customer information and populating predefined templates.

    From: /tf/active/vicechatdev/resources/documents.py
  • function create_node 45.3% similar

    Creates a node in a Neo4j graph database with a specified label and properties, automatically generating a UID and timestamp if not provided.

    From: /tf/active/vicechatdev/CDocs single class/db/db_operations.py
  • class Barcode_checker 44.2% similar

    A parameterized class that continuously monitors a Neo4j database for barcode scans associated with a specific user, updating a reactive parameter when new barcodes are detected.

    From: /tf/active/vicechatdev/resources/barcode_backend.py
← Back to Browse