def __init__(self, identityName): super(DecryptorFixture, self).__init__() # Include the code here from the NAC unit-tests class # DecryptorStaticDataEnvironment instead of making it a base class. self._storage = InMemoryStorageRetaining() for array in EncryptStaticData.managerPackets: data = Data() data.wireDecode(array) self._storage.insert(data) for array in EncryptStaticData.encryptorPackets: data = Data() data.wireDecode(array) self._storage.insert(data) # Import the "/first/user" identity. self._keyChain.importSafeBag(SafeBag(EncryptStaticData.userIdentity), Blob("password").buf()) self.addIdentity(Name("/not/authorized")) self._face = InMemoryStorageFace(self._storage) self._validator = ValidatorNull() self._decryptor = DecryptorV2( self._keyChain.getPib().getIdentity(identityName).getDefaultKey(), self._validator, self._keyChain, self._face)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) if sys.version_info[0] <= 2: userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ") else: userPrefixUri = input("Enter your user prefix (e.g. /a): ") if userPrefixUri == "": dump("You must enter a user prefix") return syncPrefixUri = "/sync" nUserPrefixes = 2 maxPublishedSequenceNo = 3 # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri, nUserPrefixes, maxPublishedSequenceNo) # The main event loop. while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() memberName = Name("/first/user") memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6")) memberKeyChain = KeyChain("pib-memory:", "tpm-memory:") memberKeyChain.importSafeBag(SafeBag (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False), Blob(MEMBER_PUBLIC_KEY, False))) # TODO: Use a real Validator. decryptor = DecryptorV2( memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(), ValidatorNull(), memberKeyChain, face) contentPrefix = Name("/testname/content") contentNamespace = Namespace(contentPrefix) contentNamespace.setFace(face) contentNamespace.setDecryptor(decryptor) enabled = [True] def onSegmentedObject(objectNamespace): dump("Got segmented content", objectNamespace.obj.toRawStr()) enabled[0] = False SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded() while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) validator.validate(reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"), makeFailureCallback("Freshly-signed Interest"))
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnValidationFailed("Freshly-signed Interest"))
def main(): backboneFace = Face() pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) backboneFace.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) prefix = Name("/farm1") backboneFace.registerPrefix(prefix, onInterest, onRegisterFailed) print("Ready to go...") while 1: try: backboneFace.processEvents() e.acquire() frame = ieee.wait_read_frame(0.01) e.release() if frame is not None: if frame['rf_data'][0] == b'\x06' or frame['rf_data'][ 0] == b'\x05': #if Data or Interest buffData[0] = frame['rf_data'][0] buffData[1] = ord(frame['rf_data'][1]) + lCP buffData[2] = frame['rf_data'][2] buffData[3] = ord(frame['rf_data'][3]) + lCP buffData[4:lCP + 4] = eCP buffData[lCP + 4:] = frame['rf_data'][4:] print(str(datetime.now().strftime('%X.%f'))) backboneFace.send(buffData) else: print(frame['rf_data'][:]) #time.sleep(0.1) gc.collect() except KeyboardInterrupt: backboneFace.shutdown() ser.close() break
def main(): # Uncomment these lines to print StateVectorSync debug messages. logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) logging.getLogger('').setLevel(logging.INFO) face = Face("localhost") # Set up the key chain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag(SafeBag (Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) screenName = promptAndInput("Enter your user name: ") hubPrefix = "ndn/edu/ucla/remap" chatRoom = "ndnchat" notificationInterestLifetime = 5000.0 sessionNumber = int(round(Common.getNowMilliseconds() / 1000.0)) hmacKey = Blob(bytearray([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ])) memberDataPrefix = Name(hubPrefix).append(screenName).append(chatRoom) def onInitialized(): stateVectorSync.publishNextSequenceNo() stateVectorSync = StateVectorSync2018(onReceivedSyncState, onInitialized, memberDataPrefix, Name("/ndn/broadcast/SvsChat").append(chatRoom), face, keyChain, SigningInfo(), hmacKey, notificationInterestLifetime, onRegisterFailed) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): data = Data() data.wireDecode(TlvData) dump("Decoded Data:") dumpData(data) # Set the content again to clear the cached encoding so we encode again. data.setContent(data.getContent()) encoding = data.wireEncode() reDecodedData = Data() reDecodedData.wireDecode(encoding) dump("") dump("Re-decoded Data:") dumpData(reDecodedData) # Set up the KeyChain. pibImpl = PibMemory() keyChain = KeyChain( pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag(SafeBag (Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"), makeOnValidationFailed("Re-decoded Data")) freshData = Data(Name("/ndn/abc")) freshData.setContent("SUCCESS!") freshData.getMetaInfo().setFreshnessPeriod(5000) freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0]) keyChain.sign(freshData) dump("") dump("Freshly-signed Data:") dumpData(freshData) keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"), makeOnValidationFailed("Freshly-signed Data"))
def main(): data = Data() data.wireDecode(TlvData) dump("Decoded Data:") dumpData(data) # Set the content again to clear the cached encoding so we encode again. data.setContent(data.getContent()) encoding = data.wireEncode() reDecodedData = Data() reDecodedData.wireDecode(encoding) dump("") dump("Re-decoded Data:") dumpData(reDecodedData) # Set up the KeyChain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"), makeFailureCallback("Re-decoded Data")) freshData = Data(Name("/ndn/abc")) freshData.setContent("SUCCESS!") freshData.getMetaInfo().setFreshnessPeriod(5000) freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0]) keyChain.sign(freshData) dump("") dump("Freshly-signed Data:") dumpData(freshData) validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"), makeFailureCallback("Freshly-signed Data"))
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding): """ Loop to decode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useCrypto: If true, verify the signature. If false, don't verify. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :param Blob encoding: The wire encoding to decode. :return: The number of seconds for all iterations. :rtype: float """ # Initialize the private key storage in case useCrypto is true. pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag( Name("/testname/KEY/123"), Blob( DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER, False))) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: keyChain.verifyData(data, onVerified, onValidationFailed) finish = getNowSeconds() return finish - start
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding): """ Loop to decode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useCrypto: If true, verify the signature. If false, don't verify. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :param Blob encoding: The wire encoding to decode. :return: The number of seconds for all iterations. :rtype: float """ # Initialize the KeyChain in case useCrypto is true. keyChain = KeyChain("pib-memory:", "tpm-memory:") # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag( Name("/testname/KEY/123"), Blob( DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.EC else DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.EC else DEFAULT_RSA_PUBLIC_KEY_DER, False))) validator = Validator(ValidationPolicyFromPib(keyChain.getPib())) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: validator.validate(data, onVerifySuccess, onVerifyFailed) finish = getNowSeconds() return finish - start
def main(): # Uncomment these lines to print ChronoSync debug messages. # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) # logging.getLogger('').setLevel(logging.INFO) screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap" hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ") if hubPrefix == "": hubPrefix = defaultHubPrefix defaultChatRoom = "ndnchat" chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ") if chatRoom == "": chatRoom = defaultChatRoom host = "localhost" print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"") face = Face(host) # Set up the key chain. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) chat = Chat(screenName, chatRoom, Name(hubPrefix), face, keyChain, keyChain.getDefaultCertificateName()) # The main loop to process Chat while checking stdin to send a message. print("Enter your chat message. To quit, enter \"leave\" or \"exit\".") while True: # Set timeout to 0 for an immediate check. isReady, _, _ = select.select([sys.stdin], [], [], 0) if len(isReady) != 0: input = promptAndInput("") if input == "leave" or input == "exit": # We will send the leave message below. break chat.sendMessage(input) face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) # The user entered the command to leave. chat.leave() # Wait a little bit to allow other applications to fetch the leave message. startTime = Chat.getNowMilliseconds() while True: if Chat.getNowMilliseconds() - startTime >= 1000.0: break face.processEvents() time.sleep(0.01)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() # Create an in-memory key chain with default keys. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Enable Interest loopback so that the EncryptorV2 can fetch Data packets # from the AccessManagerV2. face.setInterestLoopbackEnabled(True) contentPrefix = Name("/testname/content") contentNamespace = Namespace(contentPrefix, keyChain) # We know the content has two segments. metaInfo = MetaInfo() metaInfo.setFinalBlockId(Name().appendSegment(1)[0]) contentNamespace.setNewDataMetaInfo(metaInfo) ckPrefix = Name("/some/ck/prefix") encryptor = prepareData(ckPrefix, keyChain, face) # Make the callback to produce a Data packet for a content segment. def onObjectNeeded(namespace, neededNamespace, id): if not (len(neededNamespace.name) == len(contentPrefix) + 1 and contentPrefix.isPrefixOf(neededNamespace.name) and neededNamespace.name[-1].isSegment()): # Not a content segment, ignore. return False # Get the segment number. segment = neededNamespace.name[-1].toSegment() if not (segment >= 0 and segment <= 1): # An invalid segment was requested. return False segmentContent = ("This test message was decrypted" if segment == 0 else " from segments.") # Now call serializeObject which will answer the pending incoming Interest. dump("Producing Data", neededNamespace.name) neededNamespace.serializeObject( encryptor.encrypt(Blob(segmentContent)).wireEncodeV2()) return True contentNamespace.addOnObjectNeeded(onObjectNeeded) dump("Register prefix", contentNamespace.name) # Set the face and register to receive Interests. contentNamespace.setFace( face, lambda prefixName: dump("Register failed for prefix", prefixName)) while True: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto, keyType): """ Loop to encode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useComplex: If true, use a large name, large content and all fields. If false, use a small name, small content and only required fields. :param bool useCrypto: If true, sign the data packet. If false, use a blank signature. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :return: A tuple (duration, encoding) where duration is the number of seconds for all iterations and encoding is the wire encoding. :rtype: (float, Blob) """ if useComplex: # Use a large name and content. name = Name( "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00" ) contentString = "" count = 1 contentString += "%d" % count count += 1 while len(contentString) < 1115: contentString += " %d" % count count += 1 content = Name.fromEscapedString(contentString) else: # Use a small name and content. name = Name("/test") content = Name.fromEscapedString("abc") finalBlockId = Name("/%00")[0] # Initialize the KeyChain in case useCrypto is true. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag( Name("/testname/KEY/123"), Blob( DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.EC else DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.EC else DEFAULT_RSA_PUBLIC_KEY_DER, False))) certificateName = keyChain.getDefaultCertificateName() # Set up signatureBits in case useCrypto is false. signatureBits = Blob(bytearray(256)) start = getNowSeconds() for i in range(nIterations): data = Data(name) data.setContent(content) if useComplex: data.getMetaInfo().setFreshnessPeriod(1000) data.getMetaInfo().setFinalBlockId(finalBlockId) if useCrypto: # This sets the signature fields. keyChain.sign(data) else: # Imitate IdentityManager.signByCertificate to set up the signature # fields, but don't sign. sha256Signature = data.getSignature() keyLocator = sha256Signature.getKeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.setKeyName(certificateName) sha256Signature.setSignature(signatureBits) encoding = data.wireEncode() finish = getNowSeconds() return (finish - start, encoding)
def main(index_f, weight_f): sl = SegmentLabel(index_f, weight_f) # The default Face will connect using a Unix socket, or to "localhost". face_producer = Face() # Create an in-memory key chain with default keys. keyChain = KeyChain("pib-memory:", "tpm-memory:") keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) face_producer.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Use default keys # keyChain = KeyChain() # face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) publishIntervalMs = 1000.0 / 10 # stream_producer = Namespace("/ndn/eb/stream/run/28/annotation", keyChain) stream_producer = Namespace("/eb/proto/test/ml_processing/yolo/seglab", keyChain) handler = GeneralizedObjectStreamHandler() stream_producer.setHandler(handler) dump("Register prefix", stream_producer.name) # Set the face and register to receive Interests. stream_producer.setFace( face_producer, lambda prefixName: dump("Register failed for prefix", prefixName)) # Loop, producing a new object every previousPublishMs milliseconds (and # also calling processEvents()). previousPublishMs = 0 #test with publishing existing jason file by json string input jsonString = "data/faith.json" curr = [] for line in open(jsonString, 'r'): curr.append(json.loads(line)) # curr_list = [] # for ann in curr: # temp = [] # frameName = ann['frameName'] # # print(frameName) # for k in ann["annotations"]: # # temp.append({"label": ''.join([i for i in k["label"] if not i.isdigit()]), "prob": k["prob"]}) # temp.append({"label": ''.join([i for i in k["label"] if not i.isdigit()]), "ytop": k["ytop"], # "ybottom": k["ybottom"], "xleft": k["xleft"], "xright": k["xright"], "prob": k["prob"], # "frameName": frameName}) # # curr_list.append(temp) cnt = 0 total_cnt = len(curr) # while True: while cnt < total_cnt: now = Common.getNowMilliseconds() if now >= previousPublishMs + publishIntervalMs: dump("Preparing data for sequence", handler.getProducedSequenceNumber() + 1) seg_result = sl.processAnnotation(curr[cnt]) if seg_result: print(seg_result) handler.addObject(Blob(json.dumps(seg_result)), "application/json") # handler.addObject( # Blob(json.dumps() + str(handler.getProducedSequenceNumber() + 1)), # "application/json") cnt += 1 previousPublishMs = now face_producer.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)