How to use fingerprint method in avocado

Best Python code snippet using avocado_python

FingerprintLib.py

Source:FingerprintLib.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4PyFingerprint5Copyright (C) 2015 Bastian Raschke <bastian.raschke@posteo.de>6All rights reserved.7"""8import os9import serial10from PIL import Image11import struct12## Baotou start byte13FINGERPRINT_STARTCODE = 0xEF0114## Packet identification15##16FINGERPRINT_COMMANDPACKET = 0x0117FINGERPRINT_ACKPACKET = 0x0718FINGERPRINT_DATAPACKET = 0x0219FINGERPRINT_ENDDATAPACKET = 0x0820## Instruction codes21##22FINGERPRINT_VERIFYPASSWORD = 0x1323FINGERPRINT_SETPASSWORD = 0x1224FINGERPRINT_SETADDRESS = 0x1525FINGERPRINT_SETSYSTEMPARAMETER = 0x0E26FINGERPRINT_GETSYSTEMPARAMETERS = 0x0F27FINGERPRINT_TEMPLATEINDEX = 0x1F28FINGERPRINT_TEMPLATECOUNT = 0x1D29FINGERPRINT_READIMAGE = 0x0130## Note: The documentation mean upload to host computer.31FINGERPRINT_DOWNLOADIMAGE = 0x0A32FINGERPRINT_CONVERTIMAGE = 0x0233FINGERPRINT_CREATETEMPLATE = 0x0534FINGERPRINT_STORETEMPLATE = 0x0635FINGERPRINT_SEARCHTEMPLATE = 0x0436FINGERPRINT_LOADTEMPLATE = 0x0737FINGERPRINT_DELETETEMPLATE = 0x0C38FINGERPRINT_CLEARDATABASE = 0x0D39FINGERPRINT_GENERATERANDOMNUMBER = 0x1440FINGERPRINT_COMPARECHARACTERISTICS = 0x0341## Note: The documentation mean download from host computer.42FINGERPRINT_UPLOADCHARACTERISTICS = 0x0943## Note: The documentation mean upload to host computer.44FINGERPRINT_DOWNLOADCHARACTERISTICS = 0x0845## Parameters of setSystemParameter()46##47FINGERPRINT_SETSYSTEMPARAMETER_BAUDRATE = 448FINGERPRINT_SETSYSTEMPARAMETER_SECURITY_LEVEL = 549FINGERPRINT_SETSYSTEMPARAMETER_PACKAGE_SIZE = 650## Packet reply confirmations51##52FINGERPRINT_OK = 0x0053FINGERPRINT_ERROR_COMMUNICATION = 0x0154FINGERPRINT_ERROR_WRONGPASSWORD = 0x1355FINGERPRINT_ERROR_INVALIDREGISTER = 0x1A56FINGERPRINT_ERROR_NOFINGER = 0x0257FINGERPRINT_ERROR_READIMAGE = 0x0358FINGERPRINT_ERROR_MESSYIMAGE = 0x0659FINGERPRINT_ERROR_FEWFEATUREPOINTS = 0x0760FINGERPRINT_ERROR_INVALIDIMAGE = 0x1561FINGERPRINT_ERROR_CHARACTERISTICSMISMATCH = 0x0A62FINGERPRINT_ERROR_INVALIDPOSITION = 0x0B63FINGERPRINT_ERROR_FLASH = 0x1864FINGERPRINT_ERROR_NOTEMPLATEFOUND = 0x0965FINGERPRINT_ERROR_LOADTEMPLATE = 0x0C66FINGERPRINT_ERROR_DELETETEMPLATE = 0x1067FINGERPRINT_ERROR_CLEARDATABASE = 0x1168FINGERPRINT_ERROR_NOTMATCHING = 0x0869FINGERPRINT_ERROR_DOWNLOADIMAGE = 0x0F70FINGERPRINT_ERROR_DOWNLOADCHARACTERISTICS = 0x0D71## Unknown error codes72##73FINGERPRINT_ADDRCODE = 0x2074FINGERPRINT_PASSVERIFY = 0x2175FINGERPRINT_PACKETRESPONSEFAIL = 0x0E76FINGERPRINT_ERROR_TIMEOUT = 0x0177FINGERPRINT_ERROR_BADPACKET = 0xFE78## Char buffers79##80FINGERPRINT_CHARBUFFER1 = 0x0181FINGERPRINT_CHARBUFFER2 = 0x0282class PyFingerprint(object):83 """84 A python written library for the ZhianTec ZFM-20 fingerprint sensor.85 @attribute integer(4 bytes) __address86 Address to connect to sensor.87 @attribute integer(4 bytes) __password88 Password to connect to sensor.89 @attribute Serial __serial90 UART serial connection via PySerial.91 """92 __address = None93 __password = None94 __serial = None95 def __init__(self, port = '/dev/ttyUSB0', baudRate = 57600, address = 0xFFFFFFFF, password = 0x00000000):96 """97 Constructor98 @param string port99 @param integer baudRate100 @param integer(4 bytes) address101 @param integer(4 bytes) password102 """103 self.timeReadNoData = 0104 if ( baudRate < 9600 or baudRate > 115200 or baudRate % 9600 != 0 ):105 raise ValueError('The given baudrate is invalid!')106 if ( address < 0x00000000 or address > 0xFFFFFFFF ):107 raise ValueError('The given address is invalid!')108 if ( password < 0x00000000 or password > 0xFFFFFFFF ):109 raise ValueError('The given password is invalid!')110 self.__address = address111 self.__password = password112 ## Initialize PySerial connection113 self.__serial = serial.Serial(port = port, baudrate = baudRate, bytesize = serial.EIGHTBITS, timeout = 0.5)114 if ( self.__serial.isOpen() == True ):115 self.__serial.close()116 self.__serial.open()117 def __del__(self):118 """119 Destructor120 """121 ## Close connection if still established122 if ( self.__serial is not None and self.__serial.isOpen() == True ):123 self.__serial.close()124 def __rightShift(self, n, x):125 """126 Shift a byte.127 @param integer n128 @param integer x129 @return integer130 """131 return (n >> x & 0xFF)132 def __leftShift(self, n, x):133 """134 Shift a byte.135 @param integer n136 @param integer x137 @return integer138 """139 return (n << x)140 def __bitAtPosition(self, n, p):141 """142 Get the bit of n at position p.143 @param integer n144 @param integer p145 @return integer146 """147 ## A bitshift 2 ^ p148 twoP = 1 << p149 ## Binary AND composition (on both positions must be a 1)150 ## This can only happen at position p151 result = n & twoP152 return int(result > 0)153 def __byteToString(self, byte):154 """155 Converts a byte to string.156 @param byte byte157 @return string158 """159 return struct.pack('@B', byte)160 def __stringToByte(self, string):161 """162 Convert one "string" byte (like '0xFF') to real integer byte (0xFF).163 @param string string164 @return byte165 """166 return struct.unpack('@B', string)[0]167 def __writePacket(self, packetType, packetPayload):168 """169 Send a packet to fingerprint sensor.170 @param integer(1 byte) packetType171 @param tuple packetPayload172 @return void173 """174 ## Write header (one byte at once)175 self.__serial.write(self.__byteToString(self.__rightShift(FINGERPRINT_STARTCODE, 8)))176 self.__serial.write(self.__byteToString(self.__rightShift(FINGERPRINT_STARTCODE, 0)))177 self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 24)))178 self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 16)))179 self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 8)))180 self.__serial.write(self.__byteToString(self.__rightShift(self.__address, 0)))181 self.__serial.write(self.__byteToString(packetType))182 ## The packet length = package payload (n bytes) + checksum (2 bytes)183 packetLength = len(packetPayload) + 2184 self.__serial.write(self.__byteToString(self.__rightShift(packetLength, 8)))185 self.__serial.write(self.__byteToString(self.__rightShift(packetLength, 0)))186 ## The packet checksum = packet type (1 byte) + packet length (2 bytes) + payload (n bytes)187 packetChecksum = packetType + self.__rightShift(packetLength, 8) + self.__rightShift(packetLength, 0)188 ## Write payload189 for i in range(0, len(packetPayload)):190 self.__serial.write(self.__byteToString(packetPayload[i]))191 packetChecksum += packetPayload[i]192 ## Write checksum (2 bytes)193 self.__serial.write(self.__byteToString(self.__rightShift(packetChecksum, 8)))194 self.__serial.write(self.__byteToString(self.__rightShift(packetChecksum, 0)))195 def __readPacket(self):196 """197 Receive a packet from fingerprint sensor.198 Return a tuple that contain the following information:199 0: integer(1 byte) The packet type.200 1: integer(n bytes) The packet payload.201 @return tuple202 """203 receivedPacketData = []204 i = 0205 self.timeReadNoData = 0206 while ( True ):207 ## Read one byte208 receivedFragment = self.__serial.read()209 if ( len(receivedFragment) != 0 ):210 receivedFragment = self.__stringToByte(receivedFragment)211 self.timeReadNoData = 0212 ## print 'Received packet fragment = ' + hex(receivedFragment)213 else:214 self.timeReadNoData += 1215 if(self.timeReadNoData == 3):216 return217 ## Insert byte if packet seems valid218 receivedPacketData.insert(i, receivedFragment)219 i += 1220 ## Packet could be complete (the minimal packet size is 12 bytes)221 if ( i >= 12 ):222 ## Check the packet header223 if ( receivedPacketData[0] != self.__rightShift(FINGERPRINT_STARTCODE, 8) or receivedPacketData[1] != self.__rightShift(FINGERPRINT_STARTCODE, 0) ):224 raise Exception('The received packet do not begin with a valid header!')225 ## Calculate packet payload length (combine the 2 length bytes)226 packetPayloadLength = self.__leftShift(receivedPacketData[7], 8)227 packetPayloadLength = packetPayloadLength | self.__leftShift(receivedPacketData[8], 0)228 ## Check if the packet is still fully received229 ## Condition: index counter < packet payload length + packet frame230 if ( i < packetPayloadLength + 9 ):231 continue232 ## At this point the packet should be fully received233 packetType = receivedPacketData[6]234 ## Calculate checksum:235 ## checksum = packet type (1 byte) + packet length (2 bytes) + packet payload (n bytes)236 packetChecksum = packetType + receivedPacketData[7] + receivedPacketData[8]237 packetPayload = []238 ## Collect package payload (ignore the last 2 checksum bytes)239 for j in range(9, 9 + packetPayloadLength - 2):240 packetPayload.append(receivedPacketData[j])241 packetChecksum += receivedPacketData[j]242 ## Calculate full checksum of the 2 separate checksum bytes243 receivedChecksum = self.__leftShift(receivedPacketData[i - 2], 8)244 receivedChecksum = receivedChecksum | self.__leftShift(receivedPacketData[i - 1], 0)245 if ( receivedChecksum != packetChecksum ):246 raise Exception('The received packet is corrupted (the checksum is wrong)!')247 return (packetType, packetPayload)248 def verifyPassword(self):249 """250 Verify password of the fingerprint sensor.251 @return boolean252 """253 packetPayload = (254 FINGERPRINT_VERIFYPASSWORD,255 self.__rightShift(self.__password, 24),256 self.__rightShift(self.__password, 16),257 self.__rightShift(self.__password, 8),258 self.__rightShift(self.__password, 0),259 )260 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)261 receivedPacket = self.__readPacket()262 receivedPacketType = receivedPacket[0]263 receivedPacketPayload = receivedPacket[1]264 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):265 raise Exception('The received packet is no ack packet!')266 ## DEBUG: Sensor password is correct267 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):268 return True269 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):270 raise Exception('Communication error')271 elif ( receivedPacketPayload[0] == FINGERPRINT_ADDRCODE ):272 raise Exception('The address is wrong')273 ## DEBUG: Sensor password is wrong274 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_WRONGPASSWORD ):275 return False276 else:277 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))278 def setPassword(self, newPassword):279 """280 Set the password of the sensor.281 @param integer(4 bytes) newPassword282 @return boolean283 """284 ## Validate the password (maximum 4 bytes)285 if ( newPassword < 0x00000000 or newPassword > 0xFFFFFFFF ):286 raise ValueError('The given password is invalid!')287 packetPayload = (288 FINGERPRINT_SETPASSWORD,289 self.__rightShift(newPassword, 24),290 self.__rightShift(newPassword, 16),291 self.__rightShift(newPassword, 8),292 self.__rightShift(newPassword, 0),293 )294 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)295 receivedPacket = self.__readPacket()296 receivedPacketType = receivedPacket[0]297 receivedPacketPayload = receivedPacket[1]298 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):299 raise Exception('The received packet is no ack packet!')300 ## DEBUG: Password set was successful301 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):302 self.__password = newPassword303 return True304 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):305 raise Exception('Communication error')306 else:307 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))308 def setAddress(self, newAddress):309 """310 Set the module address of the sensor.311 @param integer(4 bytes) newAddress312 @return boolean313 """314 ## Validate the address (maximum 4 bytes)315 if ( newAddress < 0x00000000 or newAddress > 0xFFFFFFFF ):316 raise ValueError('The given address is invalid!')317 packetPayload = (318 FINGERPRINT_SETADDRESS,319 self.__rightShift(newAddress, 24),320 self.__rightShift(newAddress, 16),321 self.__rightShift(newAddress, 8),322 self.__rightShift(newAddress, 0),323 )324 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)325 receivedPacket = self.__readPacket()326 receivedPacketType = receivedPacket[0]327 receivedPacketPayload = receivedPacket[1]328 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):329 raise Exception('The received packet is no ack packet!')330 ## DEBUG: Address set was successful331 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):332 self.__address = newAddress333 return True334 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):335 raise Exception('Communication error')336 else:337 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))338 def setSystemParameter(self, parameterNumber, parameterValue):339 """340 Set a system parameter of the sensor.341 @param integer(1 byte) parameterNumber342 @param integer(1 byte) parameterValue343 @return boolean344 """345 ## Validate the baudrate parameter346 if ( parameterNumber == FINGERPRINT_SETSYSTEMPARAMETER_BAUDRATE ):347 if ( parameterValue < 1 or parameterValue > 12 ):348 raise ValueError('The given baudrate parameter is invalid!')349 ## Validate the security level parameter350 elif ( parameterNumber == FINGERPRINT_SETSYSTEMPARAMETER_SECURITY_LEVEL ):351 if ( parameterValue < 1 or parameterValue > 5 ):352 raise ValueError('The given security level parameter is invalid!')353 ## Validate the package length parameter354 elif ( parameterNumber == FINGERPRINT_SETSYSTEMPARAMETER_PACKAGE_SIZE ):355 if ( parameterValue < 0 or parameterValue > 3 ):356 raise ValueError('The given package length parameter is invalid!')357 ## The parameter number is not valid358 else:359 raise ValueError('The given parameter number is invalid!')360 packetPayload = (361 FINGERPRINT_SETSYSTEMPARAMETER,362 parameterNumber,363 parameterValue,364 )365 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)366 receivedPacket = self.__readPacket()367 receivedPacketType = receivedPacket[0]368 receivedPacketPayload = receivedPacket[1]369 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):370 raise Exception('The received packet is no ack packet!')371 ## DEBUG: Parameter set was successful372 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):373 return True374 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):375 raise Exception('Communication error')376 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDREGISTER ):377 raise Exception('Invalid register number')378 else:379 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))380 def setBaudRate(self, baudRate):381 """382 Sets the baudrate.383 baudRate (int): The baudrate384 """385 if (baudRate % 9600 != 0):386 raise ValueError("Invalid baudrate")387 self.setSystemParameter(FINGERPRINT_SETSYSTEMPARAMETER_BAUDRATE, baudRate // 9600)388 def setSecurityLevel(self, securityLevel):389 """390 Sets the security level of the sensor.391 securityLevel (int): Value between 1 and 5 where 1 is lowest and 5 highest.392 """393 self.setSystemParameter(FINGERPRINT_SETSYSTEMPARAMETER_SECURITY_LEVEL, securityLevel)394 def setMaxPacketSize(self, packetSize):395 """396 Sets the maximum packet size of sensor.397 packetSize (int): 32, 64, 128 and 256 are supported.398 """399 try:400 packetSizes = {32: 0, 64: 1, 128: 2, 256: 3}401 packetMaxSizeType = packetSizes[packetSize]402 except KeyError:403 raise ValueError("Invalid packet size")404 self.setSystemParameter(FINGERPRINT_SETSYSTEMPARAMETER_PACKAGE_SIZE, packetMaxSizeType)405 def getSystemParameters(self):406 """407 Get all available system information of the sensor.408 Return a tuple that contain the following information:409 0: integer(2 bytes) The status register.410 1: integer(2 bytes) The system id.411 2: integer(2 bytes) The storage capacity.412 3: integer(2 bytes) The security level.413 4: integer(4 bytes) The sensor address.414 5: integer(2 bytes) The packet length.415 6: integer(2 bytes) The baudrate.416 @return tuple417 """418 packetPayload = (419 FINGERPRINT_GETSYSTEMPARAMETERS,420 )421 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)422 receivedPacket = self.__readPacket()423 receivedPacketType = receivedPacket[0]424 receivedPacketPayload = receivedPacket[1]425 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):426 raise Exception('The received packet is no ack packet!')427 ## DEBUG: Read successfully428 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):429 statusRegister = self.__leftShift(receivedPacketPayload[1], 8) | self.__leftShift(receivedPacketPayload[2], 0)430 systemID = self.__leftShift(receivedPacketPayload[3], 8) | self.__leftShift(receivedPacketPayload[4], 0)431 storageCapacity = self.__leftShift(receivedPacketPayload[5], 8) | self.__leftShift(receivedPacketPayload[6], 0)432 securityLevel = self.__leftShift(receivedPacketPayload[7], 8) | self.__leftShift(receivedPacketPayload[8], 0)433 deviceAddress = ((receivedPacketPayload[9] << 8 | receivedPacketPayload[10]) << 8 | receivedPacketPayload[11]) << 8 | receivedPacketPayload[12] ## TODO434 packetLength = self.__leftShift(receivedPacketPayload[13], 8) | self.__leftShift(receivedPacketPayload[14], 0)435 baudRate = self.__leftShift(receivedPacketPayload[15], 8) | self.__leftShift(receivedPacketPayload[16], 0)436 return (statusRegister, systemID, storageCapacity, securityLevel, deviceAddress, packetLength, baudRate)437 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):438 raise Exception('Communication error')439 else:440 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))441 def getStorageCapacity(self):442 """443 Get the sensor storage capacity.444 @return int445 The storage capacity.446 """447 return self.getSystemParameters()[2]448 def getSecurityLevel(self):449 """450 Gets the security level of the sensor.451 @return int452 The security level453 """454 return self.getSystemParameters()[3]455 def getMaxPacketSize(self):456 """457 Get the maximum allowed size of packet by sensor.458 @return int459 Return the max size.460 """461 packetMaxSizeType = self.getSystemParameters()[5]462 try:463 packetSizes = [32, 64, 128, 256]464 packetSize = packetSizes[packetMaxSizeType]465 except KeyError:466 raise ValueError("Invalid packet size")467 return packetSize468 def getBaudRate(self):469 """470 Gets the baudrate.471 @return int472 The baudrate473 """474 return self.getSystemParameters()[6] * 9600475 def getTemplateIndex(self, page):476 """477 Get a list of the template positions with usage indicator.478 @param integer(1 byte) page479 @return list480 """481 if ( page < 0 or page > 3 ):482 raise ValueError('The given index page is invalid!')483 packetPayload = (484 FINGERPRINT_TEMPLATEINDEX,485 page,486 )487 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)488 receivedPacket = self.__readPacket()489 receivedPacketType = receivedPacket[0]490 receivedPacketPayload = receivedPacket[1]491 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):492 raise Exception('The received packet is no ack packet!')493 ## DEBUG: Read index table successfully494 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):495 templateIndex = []496 ## Contain the table page bytes (skip the first status byte)497 pageElements = receivedPacketPayload[1:]498 for pageElement in pageElements:499 ## Test every bit (bit = template position is used indicator) of a table page element500 for p in range(0, 7 + 1):501 positionIsUsed = (self.__bitAtPosition(pageElement, p) == 1)502 templateIndex.append(positionIsUsed)503 return templateIndex504 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):505 raise Exception('Communication error')506 else:507 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))508 def getTemplateCount(self):509 """510 Get the number of stored templates.511 @return integer(2 bytes)512 """513 packetPayload = (514 FINGERPRINT_TEMPLATECOUNT,515 )516 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)517 receivedPacket = self.__readPacket()518 receivedPacketType = receivedPacket[0]519 receivedPacketPayload = receivedPacket[1]520 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):521 raise Exception('The received packet is no ack packet!')522 ## DEBUG: Read successfully523 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):524 templateCount = self.__leftShift(receivedPacketPayload[1], 8)525 templateCount = templateCount | self.__leftShift(receivedPacketPayload[2], 0)526 return templateCount527 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):528 raise Exception('Communication error')529 else:530 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))531 def readImage(self):532 """533 Read the image of a finger and stores it in ImageBuffer.534 @return boolean535 """536 packetPayload = (537 FINGERPRINT_READIMAGE,538 )539 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)540 receivedPacket = self.__readPacket()541 if(type(receivedPacket) is bool):542 return False543 receivedPacketType = receivedPacket[0]544 receivedPacketPayload = receivedPacket[1]545 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):546 raise Exception('The received packet is no ack packet!')547 ## DEBUG: Image read successful548 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):549 return True550 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):551 raise Exception('Communication error')552 ## DEBUG: No finger found553 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_NOFINGER ):554 return False555 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_READIMAGE ):556 raise Exception('Could not read image')557 else:558 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))559 ## TODO:560 ## Implementation of uploadImage()561 def downloadImage(self, imageDestination):562 """563 Download the image of a finger to host computer.564 @param string imageDestination565 @return void566 """567 destinationDirectory = os.path.dirname(imageDestination)568 if ( os.access(destinationDirectory, os.W_OK) == False ):569 raise ValueError('The given destination directory "' + destinationDirectory + '" is not writable!')570 packetPayload = (571 FINGERPRINT_DOWNLOADIMAGE,572 )573 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)574 ## Get first reply packet575 receivedPacket = self.__readPacket()576 receivedPacketType = receivedPacket[0]577 receivedPacketPayload = receivedPacket[1]578 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):579 raise Exception('The received packet is no ack packet!')580 ## DEBUG: The sensor will sent follow-up packets581 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):582 pass583 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):584 raise Exception('Communication error')585 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_DOWNLOADIMAGE ):586 raise Exception('Could not download image')587 else:588 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))589 imageData = []590 ## Get follow-up data packets until the last data packet is received591 while ( receivedPacketType != FINGERPRINT_ENDDATAPACKET ):592 receivedPacket = self.__readPacket()593 receivedPacketType = receivedPacket[0]594 receivedPacketPayload = receivedPacket[1]595 if ( receivedPacketType != FINGERPRINT_DATAPACKET and receivedPacketType != FINGERPRINT_ENDDATAPACKET ):596 raise Exception('The received packet is no data packet!')597 imageData.append(receivedPacketPayload)598 ## Initialize image599 resultImage = Image.new('L', (256, 288), 'white')600 pixels = resultImage.load()601 (resultImageWidth, resultImageHeight) = resultImage.size602 row = 0603 column = 0604 for y in range(resultImageHeight):605 for x in range(resultImageWidth):606 ## One byte contains two pixels607 ## Thanks to Danylo Esterman <soundcracker@gmail.com> for the "multiple with 17" improvement:608 if (x % 2 == 0):609 ## Draw left 4 Bits one byte of package610 pixels[x, y] = (imageData[row][column] >> 4) * 17611 else:612 ## Draw right 4 Bits one byte of package613 pixels[x, y] = (imageData[row][column] & 0x0F) * 17614 column += 1615 ## Reset616 if (column == len(imageData[row])):617 row += 1618 column = 0619 resultImage.save(imageDestination)620 def convertImage(self, charBufferNumber = FINGERPRINT_CHARBUFFER1):621 """622 Convert the image in ImageBuffer to finger characteristics and store in CharBuffer1 or CharBuffer2.623 @param integer(1 byte) charBufferNumber624 @return boolean625 """626 if ( charBufferNumber != FINGERPRINT_CHARBUFFER1 and charBufferNumber != FINGERPRINT_CHARBUFFER2 ):627 raise ValueError('The given charbuffer number is invalid!')628 packetPayload = (629 FINGERPRINT_CONVERTIMAGE,630 charBufferNumber,631 )632 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)633 receivedPacket = self.__readPacket()634 receivedPacketType = receivedPacket[0]635 receivedPacketPayload = receivedPacket[1]636 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):637 raise Exception('The received packet is no ack packet!')638 ## DEBUG: Image converted639 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):640 return True641 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):642 raise Exception('Communication error')643 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_MESSYIMAGE ):644 raise Exception('The image is too messy')645 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_FEWFEATUREPOINTS ):646 raise Exception('The image contains too few feature points')647 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDIMAGE ):648 raise Exception('The image is invalid')649 else:650 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))651 def createTemplate(self):652 """653 Combine the characteristics which are stored in CharBuffer1 and CharBuffer2 to a template.654 The created template will be stored again in CharBuffer1 and CharBuffer2 as the same.655 @return boolean656 """657 packetPayload = (658 FINGERPRINT_CREATETEMPLATE,659 )660 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)661 receivedPacket = self.__readPacket()662 receivedPacketType = receivedPacket[0]663 receivedPacketPayload = receivedPacket[1]664 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):665 raise Exception('The received packet is no ack packet!')666 ## DEBUG: Template created successful667 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):668 return True669 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):670 raise Exception('Communication error')671 ## DEBUG: The characteristics not matching672 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_CHARACTERISTICSMISMATCH ):673 return False674 else:675 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))676 def storeTemplate(self, positionNumber = -1, charBufferNumber = FINGERPRINT_CHARBUFFER1):677 """678 Save a template from the specified CharBuffer to the given position number.679 @param integer(2 bytes) positionNumber680 @param integer(1 byte) charBufferNumber681 @return integer682 """683 ## Find a free index684 if ( positionNumber == -1 ):685 for page in range(0, 4):686 ## Free index found?687 if ( positionNumber >= 0 ):688 break689 templateIndex = self.getTemplateIndex(page)690 for i in range(0, len(templateIndex)):691 ## Index not used?692 if ( templateIndex[i] == False ):693 positionNumber = (len(templateIndex) * page) + i694 break695 if ( positionNumber < 0x0000 or positionNumber >= self.getStorageCapacity() ):696 raise ValueError('The given position number is invalid!')697 if ( charBufferNumber != FINGERPRINT_CHARBUFFER1 and charBufferNumber != FINGERPRINT_CHARBUFFER2 ):698 raise ValueError('The given charbuffer number is invalid!')699 packetPayload = (700 FINGERPRINT_STORETEMPLATE,701 charBufferNumber,702 self.__rightShift(positionNumber, 8),703 self.__rightShift(positionNumber, 0),704 )705 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)706 receivedPacket = self.__readPacket()707 receivedPacketType = receivedPacket[0]708 receivedPacketPayload = receivedPacket[1]709 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):710 raise Exception('The received packet is no ack packet!')711 ## DEBUG: Template stored successful712 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):713 return positionNumber714 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):715 raise Exception('Communication error')716 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDPOSITION ):717 raise Exception('Could not store template in that position')718 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_FLASH ):719 raise Exception('Error writing to flash')720 else:721 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))722 def searchTemplate(self):723 """724 Search the finger characteristics in CharBuffer in database.725 Return a tuple that contain the following information:726 0: integer(2 bytes) The position number of found template.727 1: integer(2 bytes) The accuracy score of found template.728 @return tuple729 """730 ## CharBuffer1 and CharBuffer2 are the same in this case731 charBufferNumber = FINGERPRINT_CHARBUFFER1732 ## Begin search at index 0733 positionStart = 0x0000734 templatesCount = self.getStorageCapacity()735 packetPayload = (736 FINGERPRINT_SEARCHTEMPLATE,737 charBufferNumber,738 self.__rightShift(positionStart, 8),739 self.__rightShift(positionStart, 0),740 self.__rightShift(templatesCount, 8),741 self.__rightShift(templatesCount, 0),742 )743 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)744 receivedPacket = self.__readPacket()745 receivedPacketType = receivedPacket[0]746 receivedPacketPayload = receivedPacket[1]747 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):748 raise Exception('The received packet is no ack packet!')749 ## DEBUG: Found template750 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):751 positionNumber = self.__leftShift(receivedPacketPayload[1], 8)752 positionNumber = positionNumber | self.__leftShift(receivedPacketPayload[2], 0)753 accuracyScore = self.__leftShift(receivedPacketPayload[3], 8)754 accuracyScore = accuracyScore | self.__leftShift(receivedPacketPayload[4], 0)755 return (positionNumber, accuracyScore)756 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):757 raise Exception('Communication error')758 ## DEBUG: Did not found a matching template759 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_NOTEMPLATEFOUND ):760 return (-1, -1)761 else:762 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))763 def loadTemplate(self, positionNumber, charBufferNumber = FINGERPRINT_CHARBUFFER1):764 """765 Load an existing template specified by position number to specified CharBuffer.766 @param integer(2 bytes) positionNumber767 @param integer(1 byte) charBufferNumber768 @return boolean769 """770 if ( positionNumber < 0x0000 or positionNumber >= self.getStorageCapacity() ):771 raise ValueError('The given position number is invalid!')772 if ( charBufferNumber != FINGERPRINT_CHARBUFFER1 and charBufferNumber != FINGERPRINT_CHARBUFFER2 ):773 raise ValueError('The given charbuffer number is invalid!')774 packetPayload = (775 FINGERPRINT_LOADTEMPLATE,776 charBufferNumber,777 self.__rightShift(positionNumber, 8),778 self.__rightShift(positionNumber, 0),779 )780 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)781 receivedPacket = self.__readPacket()782 receivedPacketType = receivedPacket[0]783 receivedPacketPayload = receivedPacket[1]784 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):785 raise Exception('The received packet is no ack packet!')786 ## DEBUG: Template loaded successful787 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):788 return True789 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):790 raise Exception('Communication error')791 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_LOADTEMPLATE ):792 raise Exception('The template could not be read')793 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDPOSITION ):794 raise Exception('Could not load template from that position')795 else:796 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))797 def deleteTemplate(self, positionNumber, count = 1):798 """799 Delete templates from fingerprint database. Per default one.800 @param integer(2 bytes) positionNumber801 @param integer(2 bytes) count802 @return boolean803 """804 capacity = self.getStorageCapacity()805 if ( positionNumber < 0x0000 or positionNumber >= capacity ):806 raise ValueError('The given position number is invalid!')807 if ( count < 0x0000 or count > capacity - positionNumber ):808 raise ValueError('The given count is invalid!')809 packetPayload = (810 FINGERPRINT_DELETETEMPLATE,811 self.__rightShift(positionNumber, 8),812 self.__rightShift(positionNumber, 0),813 self.__rightShift(count, 8),814 self.__rightShift(count, 0),815 )816 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)817 receivedPacket = self.__readPacket()818 receivedPacketType = receivedPacket[0]819 receivedPacketPayload = receivedPacket[1]820 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):821 raise Exception('The received packet is no ack packet!')822 ## DEBUG: Template deleted successful823 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):824 return True825 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):826 raise Exception('Communication error')827 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_INVALIDPOSITION ):828 raise Exception('Invalid position')829 ## DEBUG: Could not delete template830 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_DELETETEMPLATE ):831 return False832 else:833 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))834 def clearDatabase(self):835 """836 Clear the complete template database.837 @return boolean838 """839 packetPayload = (840 FINGERPRINT_CLEARDATABASE,841 )842 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)843 receivedPacket = self.__readPacket()844 receivedPacketType = receivedPacket[0]845 receivedPacketPayload = receivedPacket[1]846 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):847 raise Exception('The received packet is no ack packet!')848 ## DEBUG: Database cleared successful849 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):850 return True851 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):852 raise Exception('Communication error')853 ## DEBUG: Could not clear database854 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_CLEARDATABASE ):855 return False856 else:857 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))858 def compareCharacteristics(self):859 """860 Compare the finger characteristics of CharBuffer1 with CharBuffer2 and return the accuracy score.861 @return integer(2 bytes)862 """863 packetPayload = (864 FINGERPRINT_COMPARECHARACTERISTICS,865 )866 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)867 receivedPacket = self.__readPacket()868 receivedPacketType = receivedPacket[0]869 receivedPacketPayload = receivedPacket[1]870 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):871 raise Exception('The received packet is no ack packet!')872 ## DEBUG: Comparison successful873 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):874 accuracyScore = self.__leftShift(receivedPacketPayload[1], 8)875 accuracyScore = accuracyScore | self.__leftShift(receivedPacketPayload[2], 0)876 return accuracyScore877 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):878 raise Exception('Communication error')879 ## DEBUG: The characteristics do not matching880 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_NOTMATCHING ):881 return 0882 else:883 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))884 def uploadCharacteristics(self, charBufferNumber = FINGERPRINT_CHARBUFFER1, characteristicsData = [0]):885 """886 Upload finger characteristics to CharBuffer1 or CharBuffer2.887 @author: David Gilson <davgilson@live.fr>888 @param integer(1 byte) charBufferNumber889 @param integer(list) characteristicsData890 @return boolean891 Return true if everything is right.892 """893 if ( charBufferNumber != FINGERPRINT_CHARBUFFER1 and charBufferNumber != FINGERPRINT_CHARBUFFER2 ):894 raise ValueError('The given charbuffer number is invalid!')895 if ( characteristicsData == [0] ):896 raise ValueError('The characteristics data is required!')897 maxPacketSize = self.getMaxPacketSize()898 ## Upload command899 packetPayload = (900 FINGERPRINT_UPLOADCHARACTERISTICS,901 charBufferNumber902 )903 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)904 ## Get first reply packet905 receivedPacket = self.__readPacket()906 receivedPacketType = receivedPacket[0]907 receivedPacketPayload = receivedPacket[1]908 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):909 raise Exception('The received packet is no ack packet!')910 ## DEBUG: The sensor will sent follow-up packets911 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):912 pass913 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):914 raise Exception('Communication error')915 elif ( receivedPacketPayload[0] == FINGERPRINT_PACKETRESPONSEFAIL ):916 raise Exception('Could not upload characteristics')917 else:918 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))919 ## Upload data packets920 packetNbr = len(characteristicsData) / maxPacketSize921 if ( packetNbr <= 1 ):922 self.__writePacket(FINGERPRINT_ENDDATAPACKET, characteristicsData)923 else:924 i = 1925 while ( i < packetNbr ):926 lfrom = (i-1) * maxPacketSize927 lto = lfrom + maxPacketSize928 self.__writePacket(FINGERPRINT_DATAPACKET, characteristicsData[lfrom:lto])929 i += 1930 lfrom = (i-1) * maxPacketSize931 lto = lfrom + maxPacketSize932 self.__writePacket(FINGERPRINT_ENDDATAPACKET, characteristicsData[lfrom:lto])933 ## Verify uploaded characteristics934 characterics = self.downloadCharacteristics(charBufferNumber)935 # for i in range(0, 512):936 # print( str(characterics[i]) + " " + str(characteristicsData[i]))937 # if(characterics[i] != characteristicsData[i]):938 # print("err " +str(characterics[i]) + ' '+str(characteristicsData[i] ))939 return (characterics == characteristicsData)940 def generateRandomNumber(self):941 """942 Generate a random 32-bit decimal number.943 @author: Philipp Meisberger <team@pm-codeworks.de>944 @return int945 The generated random number946 """947 packetPayload = (948 FINGERPRINT_GENERATERANDOMNUMBER,949 )950 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)951 receivedPacket = self.__readPacket()952 receivedPacketType = receivedPacket[0]953 receivedPacketPayload = receivedPacket[1]954 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):955 raise Exception('The received packet is no ack packet!')956 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):957 pass958 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):959 raise Exception('Communication error')960 else:961 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))962 number = 0963 number = number | self.__leftShift(receivedPacketPayload[1], 24)964 number = number | self.__leftShift(receivedPacketPayload[2], 16)965 number = number | self.__leftShift(receivedPacketPayload[3], 8)966 number = number | self.__leftShift(receivedPacketPayload[4], 0)967 return number968 def downloadCharacteristics(self, charBufferNumber = FINGERPRINT_CHARBUFFER1):969 """970 Download the finger characteristics of CharBuffer1 or CharBuffer2.971 @param integer(1 byte) charBufferNumber972 @return list973 Return a list that contains 512 integer(1 byte) elements of the characteristic.974 """975 if ( charBufferNumber != FINGERPRINT_CHARBUFFER1 and charBufferNumber != FINGERPRINT_CHARBUFFER2 ):976 raise ValueError('The given charbuffer number is invalid!')977 packetPayload = (978 FINGERPRINT_DOWNLOADCHARACTERISTICS,979 charBufferNumber,980 )981 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)982 ## Get first reply packet983 receivedPacket = self.__readPacket()984 receivedPacketType = receivedPacket[0]985 receivedPacketPayload = receivedPacket[1]986 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):987 raise Exception('The received packet is no ack packet!')988 ## DEBUG: The sensor will sent follow-up packets989 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):990 pass991 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):992 raise Exception('Communication error')993 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_DOWNLOADCHARACTERISTICS ):994 raise Exception('Could not download characteristics')995 else:996 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))997 completePayload = []998 ## Get follow-up data packets until the last data packet is received999 while ( receivedPacketType != FINGERPRINT_ENDDATAPACKET ):1000 receivedPacket = self.__readPacket()1001 receivedPacketType = receivedPacket[0]1002 receivedPacketPayload = receivedPacket[1]1003 if ( receivedPacketType != FINGERPRINT_DATAPACKET and receivedPacketType != FINGERPRINT_ENDDATAPACKET ):1004 raise Exception('The received packet is no data packet!')1005 for i in range(0, len(receivedPacketPayload)):1006 completePayload.append(receivedPacketPayload[i])1007 return completePayload1008 def LayAnhVanTay(self):1009 """1010 Download the image of a finger to host computer.1011 @param string imageDestination1012 @return void1013 """1014 packetPayload = (1015 FINGERPRINT_DOWNLOADIMAGE,1016 )1017 self.__writePacket(FINGERPRINT_COMMANDPACKET, packetPayload)1018 ## Get first reply packet1019 receivedPacket = self.__readPacket()1020 receivedPacketType = receivedPacket[0]1021 receivedPacketPayload = receivedPacket[1]1022 if ( receivedPacketType != FINGERPRINT_ACKPACKET ):1023 raise Exception('The received packet is no ack packet!')1024 ## DEBUG: The sensor will sent follow-up packets1025 if ( receivedPacketPayload[0] == FINGERPRINT_OK ):1026 pass1027 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_COMMUNICATION ):1028 raise Exception('Communication error')1029 elif ( receivedPacketPayload[0] == FINGERPRINT_ERROR_DOWNLOADIMAGE ):1030 raise Exception('Could not download image')1031 else:1032 raise Exception('Unknown error '+ hex(receivedPacketPayload[0]))1033 imageData = []1034 ## Get follow-up data packets until the last data packet is received1035 while ( receivedPacketType != FINGERPRINT_ENDDATAPACKET ):1036 receivedPacket = self.__readPacket()1037 receivedPacketType = receivedPacket[0]1038 receivedPacketPayload = receivedPacket[1]1039 if ( receivedPacketType != FINGERPRINT_DATAPACKET and receivedPacketType != FINGERPRINT_ENDDATAPACKET ):1040 raise Exception('The received packet is no data packet!')1041 imageData.append(receivedPacketPayload)1042 ## Initialize image1043 resultImage = Image.new('L', (256, 288), 'white')1044 pixels = resultImage.load()1045 (resultImageWidth, resultImageHeight) = resultImage.size1046 row = 01047 column = 01048 for y in range(resultImageHeight):1049 for x in range(resultImageWidth):1050 ## One byte contains two pixels1051 ## Thanks to Danylo Esterman <soundcracker@gmail.com> for the "multiple with 17" improvement:1052 if (x % 2 == 0):1053 ## Draw left 4 Bits one byte of package1054 pixels[x, y] = (imageData[row][column] >> 4) * 171055 else:1056 ## Draw right 4 Bits one byte of package1057 pixels[x, y] = (imageData[row][column] & 0x0F) * 171058 column += 11059 ## Reset1060 if (column == len(imageData[row])):1061 row += 11062 column = 0...

Full Screen

Full Screen

test_model.py

Source:test_model.py Github

copy

Full Screen

...65 shutil.rmtree(os.path.join(unpacked, "core"))66 unpacked_core, unpacked_nlu = get_model_subdirectories(unpacked)67 assert not unpacked_core68 assert unpacked_nlu69def _fingerprint(70 config: Optional[Text] = None,71 config_nlu: Optional[Text] = None,72 config_core: Optional[Text] = None,73 domain: Optional[int] = None,74 rasa_version: Text = "1.0",75 stories: Optional[int] = None,76 nlu: Optional[int] = None,77):78 return {79 FINGERPRINT_CONFIG_KEY: config if config is not None else ["test"],80 FINGERPRINT_CONFIG_CORE_KEY: config_core81 if config_core is not None82 else ["test"],83 FINGERPRINT_CONFIG_NLU_KEY: config_nlu if config_nlu is not None else ["test"],84 FINGERPRINT_DOMAIN_KEY: domain if domain is not None else ["test"],85 FINGERPRINT_TRAINED_AT_KEY: time.time(),86 FINGERPRINT_RASA_VERSION_KEY: rasa_version,87 FINGERPRINT_STORIES_KEY: stories if stories is not None else ["test"],88 FINGERPRINT_NLU_DATA_KEY: nlu if nlu is not None else ["test"],89 }90def test_persist_and_load_fingerprint():91 from rasa.model import persist_fingerprint, fingerprint_from_path92 fingerprint = _fingerprint()93 output_directory = tempfile.mkdtemp()94 persist_fingerprint(output_directory, fingerprint)95 actual = fingerprint_from_path(output_directory)96 assert actual == fingerprint97@pytest.mark.parametrize(98 "fingerprint2",99 [100 _fingerprint(config=["other"]),101 _fingerprint(domain=["other"]),102 _fingerprint(domain=Domain.empty()),103 _fingerprint(stories=["test", "other"]),104 _fingerprint(rasa_version="100"),105 _fingerprint(config=["other"], domain=["other"]),106 ],107)108def test_core_fingerprint_changed(fingerprint2):109 fingerprint1 = _fingerprint()110 assert core_fingerprint_changed(fingerprint1, fingerprint2)111@pytest.mark.parametrize(112 "fingerprint2",113 [114 _fingerprint(config=["other"]),115 _fingerprint(nlu=["test", "other"]),116 _fingerprint(rasa_version="100"),117 _fingerprint(rasa_version="100", config=["other"]),118 ],119)120def test_nlu_fingerprint_changed(fingerprint2):121 fingerprint1 = _fingerprint()122 assert nlu_fingerprint_changed(fingerprint1, fingerprint2)123def _project_files(124 project,125 config_file=DEFAULT_CONFIG_PATH,126 domain="domain.yml",127 training_files=DEFAULT_DATA_PATH,128):129 paths = {130 "config_file": config_file,131 "domain_path": domain,132 "training_data_paths": training_files,133 }134 paths = {k: v if v is None else os.path.join(project, v) for k, v in paths.items()}135 paths["training_data_paths"] = [paths["training_data_paths"]]136 return RasaFileImporter(**paths)137async def test_create_fingerprint_from_paths(project):138 project_files = _project_files(project)139 assert await model_fingerprint(project_files)140@pytest.mark.parametrize(141 "project_files", [["invalid", "invalid", "invalid"], [None, None, None]]142)143async def test_create_fingerprint_from_invalid_paths(project, project_files):144 from rasa.nlu.training_data import TrainingData145 from rasa.core.training.structures import StoryGraph146 project_files = _project_files(project, *project_files)147 expected = _fingerprint(148 config="",149 config_nlu="",150 config_core="",151 domain=hash(Domain.empty()),152 rasa_version=rasa.__version__,153 stories=hash(StoryGraph([])),154 nlu=hash(TrainingData()),155 )156 actual = await model_fingerprint(project_files)157 assert actual[FINGERPRINT_TRAINED_AT_KEY] is not None158 del actual[FINGERPRINT_TRAINED_AT_KEY]159 del expected[FINGERPRINT_TRAINED_AT_KEY]160 assert actual == expected161@pytest.mark.parametrize("use_fingerprint", [True, False])162async def test_rasa_packaging(trained_model, project, use_fingerprint):163 unpacked_model_path = get_model(trained_model)164 os.remove(os.path.join(unpacked_model_path, FINGERPRINT_FILE_PATH))165 if use_fingerprint:166 fingerprint = await model_fingerprint(_project_files(project))167 else:168 fingerprint = None169 tempdir = tempfile.mkdtemp()170 output_path = os.path.join(tempdir, "test.tar.gz")171 create_package_rasa(unpacked_model_path, output_path, fingerprint)172 unpacked = get_model(output_path)173 assert (174 os.path.exists(os.path.join(unpacked, FINGERPRINT_FILE_PATH)) == use_fingerprint175 )176 assert os.path.exists(os.path.join(unpacked, "core"))177 assert os.path.exists(os.path.join(unpacked, "nlu"))178 assert not os.path.exists(unpacked_model_path)179@pytest.mark.parametrize(180 "fingerprint",181 [182 {183 "new": _fingerprint(),184 "old": _fingerprint(stories=["others"]),185 "retrain_core": True,186 "retrain_nlu": False,187 },188 {189 "new": _fingerprint(nlu=["others"]),190 "old": _fingerprint(),191 "retrain_core": False,192 "retrain_nlu": True,193 },194 {195 "new": _fingerprint(config="others"),196 "old": _fingerprint(),197 "retrain_core": True,198 "retrain_nlu": True,199 },200 {201 "new": _fingerprint(config_core="others"),202 "old": _fingerprint(),203 "retrain_core": True,204 "retrain_nlu": False,205 },206 {207 "new": _fingerprint(),208 "old": _fingerprint(config_nlu="others"),209 "retrain_core": False,210 "retrain_nlu": True,211 },212 {213 "new": _fingerprint(),214 "old": _fingerprint(),215 "retrain_core": False,216 "retrain_nlu": False,217 },218 ],219)220def test_should_retrain(trained_model, fingerprint):221 old_model = set_fingerprint(trained_model, fingerprint["old"])222 retrain_core, retrain_nlu = should_retrain(223 fingerprint["new"], old_model, tempfile.mkdtemp()224 )225 assert retrain_core == fingerprint["retrain_core"]226 assert retrain_nlu == fingerprint["retrain_nlu"]227def set_fingerprint(228 trained_model: Text, fingerprint: Fingerprint, use_fingerprint: bool = True229) -> Text:230 unpacked_model_path = get_model(trained_model)231 os.remove(os.path.join(unpacked_model_path, FINGERPRINT_FILE_PATH))232 if use_fingerprint:233 fingerprint = fingerprint234 else:235 fingerprint = None236 tempdir = tempfile.mkdtemp()237 output_path = os.path.join(tempdir, "test.tar.gz")238 create_package_rasa(unpacked_model_path, output_path, fingerprint)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful