Parses single video from the input tfrecords.

    Args:
      example_proto: tfExample proto with a single video.

    Returns:
      dict with all frames, positions and actions.
183937
def _parse_single_video(self, example_proto):
    
    context_features = {
        "game_duration_loops": tf.io.FixedLenFeature([1], tf.int64),
        "game_duration_seconds": tf.io.FixedLenFeature([1], tf.float32),
        "n_steps": tf.io.FixedLenFeature([1], tf.int64),
        "screen_size": tf.io.FixedLenFeature([2], tf.int64),
    }

    sequence_features = {
        "rgb_screen": tf.io.FixedLenSequenceFeature([], tf.string),
    }

    _, seq_feat = tf.io.parse_single_sequence_example(
        example_proto,
        context_features=context_features,
        sequence_features=sequence_features)

    video_frames = tf.map_fn(
        tf.image.decode_png, seq_feat["rgb_screen"], dtype=tf.uint8)
    return video_frames
332259
def __render_videoframe(self):
		

		new_videoframe = self.clip.get_frame(self.clock.time)
		# Pass it to the callback function if this is set
		if callable(self.__videorenderfunc):
			self.__videorenderfunc(new_videoframe)
		# Set current_frame to current frame (...)
		self.__current_videoframe = new_videoframe
1170516
def parseRtspReply(self, data):
    print("Parsing Received Rtsp data...")

    """"""
    lines = data.split('\n')
    seqNum = int(lines[1].split(' ')[1])

    # Process only if the server reply's sequence number is the same as the request's
    if seqNum == self.rtspSeq:
      session = int(lines[2].split(' ')[1])
      # New RTSP session ID
      if self.sessionId == 0:
        self.sessionId = session

      # Process only if the session ID is the same
      if self.sessionId == session:
        if int(lines[0].split(' ')[1]) == 200:
          if self.requestSent == self.SETUP:
            #-------------
            # TO COMPLETE
            #-------------
            # Update RTSP state.
            print("Updating RTSP state...")
            # self.state = ...
            self.state = self.READY
            # Open RTP port.
            #self.openRtpPort()
            print("Setting Up RtpPort for Video Stream")
            self.openRtpPort()

          elif self.requestSent == self.PLAY:
             self.state = self.PLAYING
             print('-'*60 + "\nClient is PLAYING...\n" + '-'*60)
          elif self.requestSent == self.PAUSE:
             self.state = self.READY

            # The play thread exits. A new thread is created on resume.
             self.playEvent.set()

          elif self.requestSent == self.TEARDOWN:
            # self.state = ...

            # Flag the teardownAcked to close the socket.
            self.teardownAcked = 1
314993
def batch_parse_tf_example(batch_size, example_batch):
    
    features = {
        'x': tf.FixedLenFeature([], tf.string),
        'pi': tf.FixedLenFeature([], tf.string),
        'outcome': tf.FixedLenFeature([], tf.float32),
    }
    parsed = tf.parse_example(example_batch, features)
    x = tf.decode_raw(parsed['x'], tf.uint8)
    x = tf.cast(x, tf.float32)
    x = tf.reshape(x, [batch_size, go.N, go.N,
                       features_lib.NEW_FEATURES_PLANES])
    pi = tf.decode_raw(parsed['pi'], tf.float32)
    pi = tf.reshape(pi, [batch_size, go.N * go.N + 1])
    outcome = parsed['outcome']
    outcome.set_shape([batch_size])
    return x, {'pi_tensor': pi, 'value_tensor': outcome}
197494
def _parse_tensor_info_proto(tensor_info):
  """"""
  encoding = tensor_info.WhichOneof("encoding")
  dtype = tf.DType(tensor_info.dtype)
  shape = tf.TensorShape(tensor_info.tensor_shape)
  if encoding == "name":
    return ParsedTensorInfo(dtype=dtype, shape=shape, is_sparse=False)
  elif encoding == "coo_sparse":
    return ParsedTensorInfo(dtype=dtype, shape=shape, is_sparse=True)
  else:
    raise ValueError("Unsupported TensorInfo encoding %r" % encoding)
1003763
def validate_examples(example_file):
    

    def test_example(raw):
        example = tf.train.Example()
        example.ParseFromString(raw)

        pi = np.frombuffer(example.features.feature['pi'].bytes_list.value[0], np.float32)
        value = example.features.feature['outcome'].float_list.value[0]
        assert abs(pi.sum() - 1) < 1e-4, pi.sum()
        assert value in (-1, 1), value

    opts = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)
    for record in tqdm(tf.python_io.tf_record_iterator(example_file, opts)):
        test_example(record)
778376
def _parseAtFrame(self, src):
        
        src = src[len('@frame '):].lstrip()
        box, src = self._getIdent(src)
        src, properties = self._parseDeclarationGroup(src.lstrip())
        result = [self.cssBuilder.atFrame(box, properties)]
        return src.lstrip(), result
808386
def read(cls, proto):
    
    regionImpl = proto.regionImpl.as_struct(cls.getSchema())
    return cls.readFromProto(regionImpl)
186979
def record_take(self, model, env_instance, device, take_number):
        
        frames = []

        observation = env_instance.reset()

        if model.is_recurrent:
            hidden_state = model.zero_state(1).to(device)

        frames.append(env_instance.render('rgb_array'))

        print("Evaluating environment...")

        while True:
            observation_array = np.expand_dims(np.array(observation), axis=0)
            observation_tensor = torch.from_numpy(observation_array).to(device)

            if model.is_recurrent:
                output = model.step(observation_tensor, hidden_state, **self.sample_args)
                hidden_state = output['state']
                actions = output['actions']
            else:
                actions = model.step(observation_tensor, **self.sample_args)['actions']

            actions = actions.detach().cpu().numpy()

            observation, reward, done, epinfo = env_instance.step(actions[0])

            frames.append(env_instance.render('rgb_array'))

            if 'episode' in epinfo:
                # End of an episode
                break

        takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
        pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)

        fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
        video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))

        for i in tqdm.trange(len(frames), file=sys.stdout):
            video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))

        video.release()
        print("Written {}".format(takename))
235788
def parse(self, stream, media_type=None, parser_context=None):
        
        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META.copy()
        meta['CONTENT_TYPE'] = media_type
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
189323
def __parseFormat(self, fmt, content, fps = 25):
        ''''''

        headerFound = False
        subSection = ''
        for lineNo, line in enumerate(content):
            line = self._initialLinePrepare(line, lineNo)
            if not fmt.WITH_HEADER and not self._formatFound and lineNo > self._maxFmtSearch:
                return

            subSection = ''.join([subSection, line])
            if fmt.WITH_HEADER and not headerFound:
                if lineNo > self._maxHeaderLen:
                    return
                headerFound = fmt.addHeaderInfo(subSection, self._subtitles.header())
                if headerFound:
                    self._formatFound = True
                    subSection = ''
            elif fmt.subtitleEnds(line) or (lineNo + 1) == len(content):
                subtitle = fmt.createSubtitle(fps, subSection)
                if subtitle is None:
                    if subSection in ('\n', '\r\n', '\r'):
                        subSection = ''
                        continue
                    elif self._subtitles.size() > 0:
                        raise SubParsingError(_("Parsing error"), lineNo)
                    else:
                        return

                # store parsing result if new end marker occurred, then clear results
                if subtitle.start and subtitle.text:
                    self._formatFound = True
                    try:
                        self._subtitles.append(subtitle)
                    except SubException as msg:
                        raise SubParsingError(msg, lineNo)
                elif subtitle.start and not subtitle.text:
                    pass
                else:
                    return
                subSection = ''
1250189
def from_proto(brain_param_proto):
        
        resolution = [{
            "height": x.height,
            "width": x.width,
            "blackAndWhite": x.gray_scale
        } for x in brain_param_proto.camera_resolutions]
        brain_params = BrainParameters(brain_param_proto.brain_name,
                                       brain_param_proto.vector_observation_size,
                                       brain_param_proto.num_stacked_vector_observations,
                                       resolution,
                                       list(brain_param_proto.vector_action_size),
                                       list(brain_param_proto.vector_action_descriptions),
                                       brain_param_proto.vector_action_space_type)
        return brain_params
13253
def parse_frame(frame):
    
    f = Frame()
    if frame == b'\x0a':
        f.cmd = 'heartbeat'
        return f

    mat = PREAMBLE_END_RE.search(frame)
    if mat:
        preamble_end = mat.start()
        body_start = mat.end()
    else:
        preamble_end = len(frame)
        body_start = preamble_end
    preamble = decode(frame[0:preamble_end])
    preamble_lines = LINE_END_RE.split(preamble)
    preamble_len = len(preamble_lines)
    f.body = frame[body_start:]

    # Skip any leading newlines
    first_line = 0
    while first_line < preamble_len and len(preamble_lines[first_line]) == 0:
        first_line += 1

    if first_line >= preamble_len:
        return None

    # Extract frame type/command
    f.cmd = preamble_lines[first_line]

    # Put headers into a key/value map
    f.headers = parse_headers(preamble_lines, first_line + 1)

    return f
539457
def make_dataset_from_selfplay(data_extracts):
    
    tf_examples = (make_tf_example(features_lib.extract_features(pos), pi, result)
                   for pos, pi, result in data_extracts)
    return tf_examples
551082
def to_array(self):
        
        array = super(VideoNoteMessage, self).to_array()
        if isinstance(self.video_note, InputFile):
            array['video_note'] = self.video_note.to_array()  # type InputFile
        elif isinstance(self.video_note, str):
            array['video_note'] = u(self.video_note)  # py2: type unicode, py3: type str
        else:
            raise TypeError('Unknown type, must be one of InputFile, str.')
        # end if

        if self.receiver is not None:
            if isinstance(self.receiver, None):
                array['chat_id'] = None(self.receiver)  # type Noneelif isinstance(self.receiver, str):
                array['chat_id'] = u(self.receiver)  # py2: type unicode, py3: type str
            elif isinstance(self.receiver, int):
                array['chat_id'] = int(self.receiver)  # type intelse:
                raise TypeError('Unknown type, must be one of None, str, int.')
            # end if

        if self.reply_id is not None:
            if isinstance(self.reply_id, DEFAULT_MESSAGE_ID):
                array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id)  # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int):
                array['reply_to_message_id'] = int(self.reply_id)  # type intelse:
                raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.')
            # end if

        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        if self.length is not None:
            array['length'] = int(self.length)  # type int
        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.disable_notification is not None:
            array['disable_notification'] = bool(self.disable_notification)  # type bool
        if self.reply_markup is not None:
            if isinstance(self.reply_markup, InlineKeyboardMarkup):
                array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
            elif isinstance(self.reply_markup, ReplyKeyboardMarkup):
                array['reply_markup'] = self.reply_markup.to_array()  # type ReplyKeyboardMarkup
            elif isinstance(self.reply_markup, ReplyKeyboardRemove):
                array['reply_markup'] = self.reply_markup.to_array()  # type ReplyKeyboardRemove
            elif isinstance(self.reply_markup, ForceReply):
                array['reply_markup'] = self.reply_markup.to_array()  # type ForceReply
            else:
                raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.')
            # end if

        return array
800849
def frame_to_seconds(self, frame_index, sr):
        
        start_sample, end_sample = self.frame_to_sample(frame_index)
        return sample_to_seconds(start_sample, sampling_rate=sr), sample_to_seconds(end_sample, sampling_rate=sr)
727501
def pixelFormat(self):
        
        f=None
        if self.isVideo():
            if self.__dict__['pix_fmt']:
                f=self.__dict__['pix_fmt']
        return f