Пример #1
0
 def updateText( self ):
     debugMsg( "Current user input: " + self.userInput )
     if not self.hideInput:
         self.userInputLabel.setText( self.userInput )
     else:
         self.userInputLabel.setText( len( self.userInput ) * "*" )
     return
Пример #2
0
    def mouseDoubleClickEvent( self, event ):
        """ Ask password and move to the admin mode """

        globalData = GlobalData()

        keyboard = ui.findForm( 'DigitKeyboard' )
        keyboard.hideInput = True
        keyboard.raise_()
        keyboard.exec_()

        if keyboard.cancelled:
            return

        debugMsg( "User input: " + keyboard.userInput )
        debugMsg( "Admin password: " + Settings().adminPassword )

        if keyboard.userInput != Settings().adminPassword:
            return


        ui.hideForm( 'TopBar' )
        ui.showForm( 'AdminTopBar' )

        globalData.isAdmin = True
        return
Пример #3
0
    def flushButtonClicked(self):
        """ processing click() on the Flush button """

        debugMsg("Sending a test notification")
        GlobalData().application.sendNotification("something")
        debugMsg("Sent")

        QtGui.QMessageBox.information(None, "Not implemented yet",
                                      "Not implemented yet")
        return
Пример #4
0
def showForm(formName, left=-1, top=-1, width=-1, height=-1):
    """ shows the required form """

    theForm = findForm(formName)

    if width > 0 and height > 0:
        theForm.resize(width, height)
        theForm.setLayoutGeometry(width, height)

    theForm.show()
    debugMsg("Showing form '" + formName + "'")
    return
Пример #5
0
def buildCSSFilesList(path, cssFiles):
    """ builds a list of the .css files to be processed """

    debugMsg("buildCSSFilesList(): processing " + path)
    for item in os.listdir(path):
        if os.path.isdir(path + item):
            buildCSSFilesList(path + item + '/', cssFiles)
            continue
        if item.endswith('.css'):
            cssFiles.append(path + item)
            debugMsg("Found CSS: " + path + item)
            continue
    return
Пример #6
0
def ru_morpher(imgpaths, width=500, height=600, num_frames=20, fps=10, \
               out_frames=None, out_video=None, alpha=False, plot=False,
               obj=None, sessionid=None):
    """
    Create a morph sequence from multiple images in imgpaths
    :param imgpaths: array or generator of image paths
    :param callback: callback function on each point
    """
    oBack = {'status': 'ok', 'msg': ''}
    try:
        video = videoer.Video(out_video, fps, width, height)
        images_points_gen = load_valid_image_points(imgpaths, (height, width))
        src_img, src_points = next(images_points_gen)
        iStep = 0
        for dest_img, dest_points in images_points_gen:

            debugMsg("ru_morpher step {}".format(iStep))

            morph(src_img,
                  src_points,
                  dest_img,
                  dest_points,
                  video,
                  width,
                  height,
                  num_frames,
                  fps,
                  out_frames,
                  out_video,
                  alpha,
                  plot,
                  obj=obj,
                  sessionid=sessionid,
                  result_type="image")

            # Set the new source = old destination
            src_img, src_points = dest_img, dest_points

            iStep += 1

        # Check if any faces could be found in the image
        if iStep == 0:
            # This means that the points could not be found on the image
            print('debug point #3 in: ru_morpher')
            # No points were found
            oBack['status'] = "error"
            oBack['msg'] = "Er kan geen gezicht gevonden worden in dit beeld"
            debugMsg(oBack['msg'])

        debugMsg("ru_morpher video.end")
        video.end()
    except:
        sMsg = get_error_message()
        DoError("ru_morpher: ")
        oBack['status'] = 'error'
        oBack['msg'] = sMsg
    finally:
        return oBack
Пример #7
0
    def onConnectionStatus(self, host, isAlive):
        """ Called by ping agent.
            isAlive shows the current connection status """

        if isAlive == utils.GlobalData().isConnected:
            return

        # The status has been changed
        self.connectionTimer.stop()
        utils.GlobalData().isConnected = isAlive
        if isAlive:
            # Connection restored
            # Check the connection every 5 minutes
            self.connectionTimer.start(5 * 60 * 1000)
            utils.debugMsg(
                "Connection restored. Switch interval to 5 minutes.")
        else:
            # Connection lost
            # Check the connection every 16 seconds
            self.connectionTimer.start(16 * 1000)
            utils.debugMsg("Connection lost. Switch interval to 10 seconds.")

        self.emit(SIGNAL("connectionStatus"), isAlive)
        return
Пример #8
0
    def onNotification(self):
        """ Called when a notification has been received """

        while self.socketFrom.hasPendingDatagrams():
            datagramSize = self.socketFrom.pendingDatagramSize()
            datagram, host, port = self.socketFrom.readDatagram(datagramSize)

            values = parseNotification(str(datagram))

            # Check that it is a correct diagramm
            if not values.has_key('kioskID') or not values.has_key('what'):
                # Unexpected diagramm
                utils.debugMsg("Unexpected diagram format. Skipping.")
                continue

            if values['kioskID'] == utils.GlobalData().uuid:
                # Self sent diagram
                utils.debugMsg("Self sent diagram. Skipping.")
                continue

            # emit a signal
            self.emit(SIGNAL("peerNotification"), values)

        return
Пример #9
0
def buildFormsList(path):
    """ Populates the kioskForms map """

    global kioskForms

    debugMsg("buildFormsList(): processing " + path + "...")
    if not os.path.exists(path) or not os.path.isdir(path):
        raise Exception( "buildFormsList() expects a path. The '" + \
                         path + "' does not exist or is not a directory" )
    if not path.endswith('/'):
        path += '/'

    # Alter the list of pathes where modules are searched
    if not path in sys.path:
        sys.path.append(path)

    for item in os.listdir(path):
        if os.path.isdir(path + item):
            buildFormsList(path + item + '/')
            continue

        if item.endswith('.py'):
            debugMsg("Form file found: " + path + item)
            formName = item.replace('.py', '')

            if kioskForms.has_key(formName):
                raise Exception( "Form names clash detected. Name: " + \
                                 formName )

            # import the module and get the form class
            module = __import__(formName, globals(), locals(), ['*'])
            formClass = getattr(module, formName)

            kioskForms[formName] = formClass(path)

            # Dirty: update the utils global variable to have the messages
            #        added to the list on the screen
            if formName == 'DebugBar':
                # ugly - I don't know how to update this variable from the
                # other module another way
                utils.debugWindow = kioskForms[formName]
            debugMsg("Form '" + formName + "' has been registered.")

    return
Пример #10
0
def applySkin(path, application):
    """ Searches for the skin files, processes them and applies them to the
        forms """

    if not os.path.exists(path) or not os.path.isdir(path):
        raise Exception( "applySkin() expects a path. The '" + \
                         path + "' does not exist or is not a directory" )
    if not path.endswith('/'):
        path += '/'

    cssFiles = []
    buildCSSFilesList(path, cssFiles)

    # The Application.css file must be applied first
    for fileName in cssFiles:
        if os.path.basename(fileName) == 'Application.css':
            # Apply the application CSS
            content = getCSSContent(fileName).strip()
            if len(content) != 0:
                application.setStyleSheet(content)
                debugMsg("Setting APPLICATION level CSS")
                break

    # Apply all the other CSS files
    for fullFileName in cssFiles:
        fileName = os.path.basename(fullFileName)
        if fileName == 'Application.css':
            continue

        formName = fileName.replace(".css", "")
        if not kioskForms.has_key(formName):
            message = "WARNING. Style sheet file " + fullFileName + \
                      " is skipped because the '" + formName + "'" \
                      " form is not registered"
            debugMsg(message)
            writeToLog(message)
            continue

        content = getCSSContent(fullFileName).strip()
        if len(content) != 0:
            kioskForms[formName].setStyleSheet(content)
            debugMsg("Setting CSS for '" + formName + "' form")

    return
Пример #11
0
def parsing(fp):
	if fp is None:
		return None

	ret = list()
	symbol = list()
	layerNum = 0

	lineNum = sum(1 for line in fp)
	fp.seek(0)
	idx = 0
	action = 0
	while idx < lineNum:
		action = 0
		line = fp.readline().strip()
		lib.debugMsg("------------------ %s ------------------------" % idx)
		# Empty line
		if not line or lib.isStartwith(S[0], line):
			idx += 1
			continue
		# End of Attr.
		if lib.isStartwith(S[2], line):
			lib.debugMsg("POP  "+str(line.split()[0]))
			t = symbol.pop()
			if t[1:] not in line.split()[0]:
				lib.debugMsg("Error")
				return None
			action = -1
		# New Attr.
		elif lib.isStartwith(S[1], line):
			if (not lib.isEndwith(S[4], line)) and (not lib.isEndwith(S[3], line)):
				line = line + str(fp.readline().strip())
				idx += 1
			lib.debugMsg("PUSH  " + str(line.split()[0]))
			if lib.isEndwith(S[3], line):
				lib.debugMsg("POP  "+str(line.split()[0]))
			else:
				symbol.append(line.split()[0])
				action = 1
		sig, attrL = classisfy(removeSign(line))
		ret.append([layerNum, sig, attrL])
		idx += 1
		layerNum += action
		lib.debugMsg(symbol)

	if symbol:
		lib.debugMsg("Error")
		return None
	return ret
Пример #12
0
def setFormArguments(formName, arguments):
    """ passes arguments to the required form """

    findForm(formName).setArguments(arguments)
    debugMsg("Setting arguments for '" + formName + "' form")
    return
Пример #13
0
def hideForm(formName):
    """ hides the required form """

    findForm(formName).hide()
    debugMsg("Hiding form '" + formName + "'")
    return
Пример #14
0
def applySingleLayout(path, startupForms, geometry):
    """ recursive function which parses a layout file """

    if not os.path.exists(path):
        raise Exception("Layout file '" + path + "' has not been found")

    globalData = GlobalData()
    # variables name -> value
    variables = {
        "WIDTH": str(globalData.screenWidth),
        "HEIGHT": str(globalData.screenHeight)
    }
    if utils.debug:
        variables["DEBUG"] = "1"
    else:
        variables["DEBUG"] = "0"

    f = open(path)
    for line in f:
        line = line.strip()
        if len(line) == 0:
            continue
        if line.startswith('#'):
            continue

        if line.upper().startswith('SET'):
            assignment = line[len('SET'):].strip()
            parts = assignment.split('=')
            if len(parts) != 2:
                raise Exception( "Unexpected line format: '" + line + \
                                 "' in file '" + path + "'" )
            varName = parts[0].strip()
            if variables.has_key(varName):
                raise Exception( "Variable '" + varName + \
                                 "' is defined twice in file '" + path + "'" )
            variables[varName] = substAndEvaluate(parts[1].strip(), variables)
            debugMsg( "Found variable '" + varName + \
                      "' in file '" + path + "'" )
            continue

        if line.upper().startswith('STARTUP'):
            parts = line.split()
            if len(parts) != 2:
                raise Exception( "Unexpected line format: '" + line + \
                                 "' in file '" + path + "'" )
            formName = parts[1].strip()
            if not kioskForms.has_key(formName):
                raise Exception( "Unknown startup form '" + formName + \
                                 "' in file '" + path + "'" )

            if not formName in startupForms:
                startupForms.append(formName)
                debugMsg("Found STARTUP form '" + formName + "'")
            continue

        if line.upper().startswith('INCLUDE'):
            parts = line.split()
            if len(parts) != 2:
                raise Exception( "Unexpected line format: '" + line + \
                                 "' in file '" + path + "'" )

            fileName = parts[1].strip()
            if fileName.startswith('/'):
                # absolute path
                if not os.path.exists(fileName):
                    raise Exception( "INCLUDE file '" + fileName + "' in '" + \
                                     path + "' has not been found" )
                applySingleLayout(fileName, startupForms, geometry)
                continue

            # relative path
            includedFileName = os.path.dirname(path) + '/' + fileName
            includedFileName = os.path.normpath(includedFileName)
            if not os.path.exists(includedFileName):
                raise Exception( "INCLUDE file '" + fileName + "' (" + \
                                 includedFileName + ") in '" + path + \
                                 "' has not been found" )
            applySingleLayout(includedFileName, startupForms, geometry)
            continue

        if line.upper().startswith('GEOMETRY'):
            arguments = line[len('GEOMETRY'):].strip()
            if len(arguments) == 0:
                raise Exception( "Unexpected line format: '" + line + \
                                 "' in file '" + path + "'" )
            formName = arguments.split()[0]
            if not kioskForms.has_key(formName):
                raise Exception( "Unknown form '" + formName + \
                                 "' geometry in file '" + path + "'" )
            if geometry.has_key(formName):
                raise Exception( "GEOMETRY for '" + formName + \
                                 "' has been defined twice.\nFirst: " + \
                                 geometry[formName][0] + "\nSecond: " + \
                                 path )

            arguments = arguments[len(formName):].strip()
            parts = arguments.split(',')
            if len(parts) != 4:
                raise Exception( "Unexpected line format: '" + line + \
                                 "' in file '" + path + "'" )

            globalData = GlobalData()
            for index in range(0, 4):
                parts[index] = int(substAndEvaluate(parts[index], variables))

            geometry[formName] = [path, parts[0], parts[1], parts[2], parts[3]]
            debugMsg("Found GEOMETRY for '" + formName + "'")
            continue

        raise Exception("Unexpected line '" + line + "' in " + path)

    f.close()
    return
Пример #15
0
def morph(src_img,
          src_points,
          dest_img,
          dest_points,
          video,
          width=500,
          height=600,
          num_frames=20,
          fps=10,
          out_frames=None,
          out_video=None,
          alpha=False,
          plot=False,
          obj=None,
          sessionid=None,
          result_type="zero"):
    """
    Create a morph sequence from source to destination image
    :param src_img: ndarray source image
    :param src_img: source image array of x,y face points
    :param dest_img: ndarray destination image
    :param dest_img: destination image array of x,y face points
    :param video: facemorpher.videoer.Video object
    """
    size = (height, width)
    stall_frames = np.clip(int(fps * 0.15), 1, fps)  # Show first & last longer
    plt = plotter.Plotter(plot, num_images=num_frames, out_folder=out_frames)
    num_frames -= (stall_frames * 2)  # No need to process src and dest image

    plt.plot_one(src_img)
    video.write(src_img, 1)

    # Produce morph frames!
    for percent in np.linspace(1, 0, num=num_frames):
        points = locator.weighted_average_points(src_points, dest_points,
                                                 percent)
        src_face = warper.warp_image(src_img,
                                     src_points,
                                     points,
                                     size,
                                     result_type=result_type,
                                     bk_img=dest_img)
        end_face = warper.warp_image(dest_img,
                                     dest_points,
                                     points,
                                     size,
                                     result_type=result_type,
                                     bk_img=dest_img)

        # Check for a callback function
        if obj != None:
            debugMsg("morph calls mix_callback session={}".format(sessionid))
            obj.mix_callback(sessionid, percent, points)
        else:
            debugMsg("morph has obj=None")

        average_face = blender.weighted_average(src_face, end_face, percent)
        average_face = alpha_image(average_face,
                                   points) if alpha else average_face

        plt.plot_one(average_face)
        plt.save(average_face)

        video.write(average_face)

    plt.plot_one(dest_img)
    video.write(dest_img, stall_frames)
    plt.show()