コード例 #1
0
def main(args):
    global testJsonPath
    global outputPath
    if args.pydev:
        print("Enabling debugging with pydev")
        import pydevd
        pydevd.settrace(suspend=False)

    inputPath = args.inputJsonPath
    #outputPath = args.outputPath
    outputPath = "-"
    testJsonPath = args.testJsonPath
    numThreads = args.numThreads
    recursive = args.recursive
    fileFilter = args.filter

    print("Input path: {}\nOutput path: {}\n\n".format(inputPath, outputPath))

    # Initialize the Vam window
    vamWindow = VamWindow(idx=args.vamWindow)

    # Locating the buttons via image comparison does not reliably work. These coordinates are the 'Window' coordinates
    # found via AutoHotKey's Window Spy, cooresponding to the Load Preset button and the location of the test file
    vamWindow.setClickLocations([(130, 39), (248, 178)])

    print("Initializing worker processes...")
    poolWorkQueue = multiprocessing.Queue(maxsize=200)
    doneEvent = multiprocessing.Event()
    if numThreads > 1:
        pool = []
        for idx in range(numThreads):
            proc = multiprocessing.Process(target=worker_process_func,
                                           args=(idx, poolWorkQueue, doneEvent,
                                                 args))
            proc.start()
            pool.append(proc)
    else:
        pool = None
        doneEvent.set()

    angles = [0, 35]
    skipCnt = 0
    screenshots = deque(maxlen=2)
    for root, subdirs, files in os.walk(inputPath):
        print("Entering directory {}".format(root))
        for file in fnmatch.filter(files, fileFilter):
            try:
                anglesToProcess = [] + angles
                for angle in angles:
                    fileName = "{}_angle{}.png".format(
                        os.path.splitext(file)[0], angle)
                    fileName = os.path.join(root, fileName)
                    if os.path.exists(fileName) or os.path.exists(
                            "{}.failed".format(fileName)):
                        anglesToProcess.remove(angle)

                if len(anglesToProcess) == 0:
                    skipCnt += 1
                    #print("Nothing to do for {}".format(file))
                    continue
                print("Processing {} (after skipping {})".format(
                    file, skipCnt))
                skipCnt = 0

                if (GetKeyState(VK_CAPITAL) or GetKeyState(VK_SCROLL)):
                    print(
                        "WARNING: Suspending script due to Caps Lock or Scroll Lock being on. Push CTRL+PAUSE/BREAK or mash CTRL+C to exit script."
                    )
                    while GetKeyState(VK_CAPITAL) or GetKeyState(VK_SCROLL):
                        time.sleep(1)
                # Get screenshots of face and submit them to worker threads
                inputFile = os.path.join(root, file)
                face = VamFace(inputFile)
                for angle in anglesToProcess:
                    face.setRotation(angle)
                    face.save(testJsonPath)
                    vamWindow.loadLook()
                    start = time.time()

                    threshold = 850000000
                    minTime = .3
                    screenshots.append(vamWindow.getScreenShot())

                    while True:
                        screenshots.append(vamWindow.getScreenShot())
                        diff = ImageChops.difference(screenshots[0],
                                                     screenshots[1])
                        imageStat = ImageStat.Stat(diff)
                        s = sum(imageStat.sum2)
                        # Todo: Calculate where blue box will be
                        pix = diff.getpixel((574, 582))
                        if s < threshold and sum(
                                pix) < 50 and time.time() - start >= minTime:
                            break
                        #print( "{} < {}: {}, {} {}".format(s, threshold, s < threshold, pix, sum(pix) ) )
                    outputFileName = "{}_angle{}.png".format(
                        os.path.splitext(os.path.basename(inputFile))[0],
                        angle)
                    outputFileName = os.path.join(root, outputFileName)
                    poolWorkQueue.put((screenshots.pop(), outputFileName))

                    if pool is None:
                        worker_process_func(0, poolWorkQueue, doneEvent, args)
            except Exception as e:
                print("Failed to process {} - {}".format(file, str(e)))

        if not recursive:
            break

    print("Generator done!")
    doneEvent.set()
    if pool:
        for proc in pool:
            proc.join()
コード例 #2
0
def main(args):
    if args.pydev:
        print("Enabling debugging with pydev")
        import pydevd
        pydevd.settrace(suspend=False)

    # Delay heavy imports
    from keras.models import load_model

    # Work around low-memory GPU issue
    import tensorflow as tf
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    session = tf.Session(config=config)

    modelFile = args.modelFile
    inputGlob = args.inputEncoding
    outputDir = args.outputDir
    baseJson = args.baseJson
    archiveDir = args.archiveDir

    face = VamFace(baseJson)
    face.trimToAnimatable()
    model = load_model(modelFile)
    modelName = os.path.splitext(os.path.basename(modelFile))[0]

    if archiveDir:
        try:
            os.makedirs(archiveDir)
        except:
            pass

    for entry in glob.glob(inputGlob):
        try:
            encodingFile = "{}_angle0.encoding".format(
                os.path.splitext(entry)[0])
            encodingFile1 = "{}_angle35.encoding".format(
                os.path.splitext(entry)[0])
            outArray = []
            if os.path.exists(encodingFile) and os.path.exists(encodingFile1):
                with open(encodingFile) as f:
                    encoding = f.read().splitlines()
                outArray = encoding

                with open(encodingFile1) as f:
                    encoding = f.read().splitlines()
                outArray.extend(encoding)
            else:
                print("Missing encoding file {} or {}".format(
                    encodingFile, encodingFile1))

            dataSet = numpy.array([outArray])
            predictions = model.predict(dataSet)
            rounded = [float(round(x, 5)) for x in predictions[0]]
            face.importFloatList(rounded)
            entryName = os.path.splitext(os.path.basename(entry))[0]
            outputFile = "{}_{}.json".format(entryName, modelName)
            outputFile = os.path.join(outputDir, outputFile)
            if args.archiveDir and os.path.exists(outputFile):
                dateString = datetime.datetime.now().strftime(
                    "%Y-%m-%d_%H_%M_%S")
                backupFileName = os.path.splitext(
                    os.path.basename(outputFile))[0]
                backupFileName = os.path.join(
                    args.archiveDir,
                    "{}_{}.json".format(backupFileName, dateString))
                print("Backing up {} to {}".format(outputFile, backupFileName))
                shutil.copyfile(outputFile, backupFileName)
            face.save(outputFile)
            print("Prediction saved to {}".format(outputFile))
        except Exception as e:
            print("Failed to process {}: {}".format(entry, e))
コード例 #3
0
def main(args):
    if args.pydev:
        print("Enabling debugging with pydev")
        import pydevd
        pydevd.settrace(suspend=False)
    inputPath = args.inputJsonPath
    basePath = args.baseJsonPath
    outputPath = args.outputPath
    dirRotateInterval = args.rotateDirectoryInterval
    baseFace = VamFace(basePath)
    baseFace.trimToAnimatable()

    # Read in all of the files from inputpath
    inputFaces = []
    print("Loading input faces from  {}".format(inputPath))
    for entry in glob.glob(os.path.join(inputPath, '*.json')):
        try:
            newFace = VamFace(entry)
            # Only keep the relevant morphs
            morphCnt = len(newFace.morphFloats)
            newFace.matchMorphs(baseFace)
            inputFaces.append(newFace)
        except:
            print("Error loading {}".format(entry))

    print("Loaded {} faces".format(len(inputFaces)))
    if len(inputFaces) == 0:
        print("No starting point faces were loaded!")
        exit(-1)
    faceCnt = 0
    print("Generating variations")

    mutateChance = .6
    mateChance = .7
    faceVariants = [] + inputFaces
    nextRotation = faceCnt + dirRotateInterval
    rotatedOutputPath = getNextDir(outputPath)
    while faceCnt < args.numFaces:
        #for face1 in faceVariants:
        face1 = faceVariants[random.randint(0, len(faceVariants) - 1)]

        # Randomly take parameters from the other face
        shouldMate = random.random() < mateChance
        shouldMutate = random.random() < mutateChance

        if shouldMate or shouldMutate:
            newFace = copy.deepcopy(face1)

            if shouldMate:
                mateIdx = random.randint(0, len(faceVariants) - 1)
                mate(newFace, faceVariants[mateIdx],
                     random.randint(1, len(newFace.morphFloats)))

            # Randomly apply mutations to the current face
            if shouldMutate:
                mutate(newFace, random.randint(0, random.randint(1, 50)))

            newFace.save(
                os.path.join(
                    rotatedOutputPath,
                    "face_variant_{}_{}.json".format(faceCnt,
                                                     random.randint(0,
                                                                    99999))))
            faceVariants.append(newFace)
            faceCnt += 1
            if faceCnt % 500 == 0:
                print("{}/{}".format(faceCnt, args.numFaces))
            if faceCnt >= nextRotation:
                nextRotation = faceCnt + dirRotateInterval
                rotatedOutputPath = getNextDir(outputPath)
コード例 #4
0
def main( args ):
    global testJsonPath
    global outputPath
    if args.pydev:
        print("Enabling debugging with pydev")
        import pydevd
        pydevd.settrace(suspend=False)

    inputPath = args.inputJsonPath
    #outputPath = args.outputPath
    outputPath = "-"
    testJsonPath = args.testJsonPath
    numThreads = args.numThreads
    recursive = args.recursive
    fileFilter = args.filter


    print( "Input path: {}\nOutput path: {}\n\n".format( inputPath, outputPath ) )

    # Initialize the Vam window
    vamWindow = VamWindow()

    # Locating the buttons via image comparison does not reliably work. These coordinates are the 'Window' coordinates
    # found via AutoHotKey's Window Spy, cooresponding to the Load Preset button and the location of the test file
    vamWindow.setClickLocations([(130,39), (248,178)])

    print("Initializing worker processes...")
    poolWorkQueue = multiprocessing.Queue(maxsize=200)
    doneEvent = multiprocessing.Event()
    if numThreads > 1:
        pool = []
        for idx in range(numThreads):
            proc = multiprocessing.Process(target=worker_process_func, args=(idx, poolWorkQueue, doneEvent) )
            proc.start()
            pool.append( proc )
    else:
        pool = None
        doneEvent.set()


    angles = [0, 35, 65]
    for root, subdirs, files in os.walk(inputPath):
        print("Entering directory {}".format(root))
        for file in fnmatch.filter(files, fileFilter):
            print("Processing {}".format(file))
            try:
                alreadyDone = False
                for angle in angles:
                    fileName = "{}_angle{}.png".format( os.path.splitext(file)[0], angle)
                    fileName = os.path.join( root,fileName)
                    if os.path.exists(fileName):
                        alreadyDone = True
                        print("Output file already exists. Skipping.")
                        break

                if alreadyDone:
                    continue

                if (GetKeyState(VK_CAPITAL) or GetKeyState(VK_SCROLL)):
                    print("WARNING: Suspending script due to Caps Lock or Scroll Lock being on. Push CTRL+PAUSE/BREAK or mash CTRL+C to exit script.")
                    while GetKeyState(VK_CAPITAL) or GetKeyState(VK_SCROLL):
                        time.sleep(1)

                # Get screenshots of face and submit them to worker threads
                inputFile = os.path.join( root, file )
                face = VamFace(inputFile)
                for angle in angles:
                    face.setRotation(angle)
                    face.save( testJsonPath )
                    vamWindow.loadLook()
                    time.sleep(.3)
                    img = vamWindow.getScreenShot()

                    outputFileName = "{}_angle{}.png".format( os.path.splitext(os.path.basename(inputFile))[0], angle)
                    outputFileName = os.path.join( root, outputFileName )
                    poolWorkQueue.put( (img, outputFileName))

                    if pool is None:
                        worker_process_func(0, poolWorkQueue, doneEvent)
            except:
                print("Failed to process {}".format(file))

        if not recursive:
            break

    print("Generator done!")
    doneEvent.set()
    if pool:
        for proc in pool:
            proc.join()