# AI Label Maker

# Import libraries
from picamera import PiCamera
from time import sleep
import datetime
import requests
import json
import board
import busio
import adafruit_thermal_printer
import serial
import RPi.GPIO as GPIO
from time import sleep

# Setup the arcade button
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# The button GPIO pin
GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# The arcade button's LED GPIO pin
GPIO.setup(16, GPIO.OUT)

# Setup the Adafruit Mini Thermal Receipt Printer
ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.68)
RX = board.RX
TX = board.TX

# For a computer, use the pyserial library for uart access
uart = serial.Serial("/dev/serial0", baudrate=19200, timeout=3000)

# Create the printer instance.
printer = ThermalPrinter(uart, auto_warm_up=True)
camera = PiCamera()

# Function that does all of the label making
def printImageCaption():
    # Set the filename of the picture to the current date and time to give it a unique name
    filename = 'image' + str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.') + '.jpg'

    # Start the camera and sleep for a second to let it settle
    camera.start_preview()
    sleep(1)
    print("taking a picture")
    # Take a picture and give it the unique filename
    camera.capture('/home/pi/Desktop/labelmaker/%s' % filename)
    # Stop the camera
    camera.stop_preview()

    # Set the path to the image location
    imagepath = '/home/pi/Desktop/labelmaker/' + filename
    print("Fetching AI Label")

    # Send a request to DeepAI densecap
    # With the image and API key
    r = requests.post(
        "https://api.deepai.org/api/densecap",
        files={
            'image': open(imagepath, 'rb'),
        },
        headers={'api-key': 'YOUR-API-KEY-HERE'}
    )

    # An array of all the captions
    allcaptions = r.json().get("output").get("captions")

    # The first caption = the label the AI is the most certain of
    firstcaption = allcaptions[0]['caption']

    print(firstcaption)

    # Print the first caption using the Adafruit Mini Thermal Receipt Printer
    print("Printing Label")
    printer.justify = adafruit_thermal_printer.JUSTIFY_CENTER
    printer.print(firstcaption)
    printer.feed(6)

# Run this bit of code forever
while True:
    # If the button has been pressed
    if GPIO.input(26) == GPIO.LOW:
        # Turn on the button's LED
        GPIO.output(16, True)
        print("Button was pushed!")
        # Run the function to take a picture and print the label
        printImageCaption()
    else:
        # Turn off the button's LED
        GPIO.output(16, False)
