code: def decode_encoded_tree_stream(
      stream: Iterator[bytes], concat_chunks=False
  ) -> bytes:
      # TODO: handle case when chunk ends at the middle of key/value
      # TODO: if remaining part of chunk cannot be unpacked, prepend to next one and try with new chunk
      prev_chunk_tail = b""
      if concat_chunks:
          data = b""
          for chunk in stream:
              data += chunk
          while data:
              (key_size,), data_tail = (
                  struct.unpack("I", data[:4]),
                  data[4:],
              )
              key, data_tail = (
                  data_tail[:key_size],
                  data_tail[key_size:],
              )
  
              (value_size,), data_tail = (
                  struct.unpack("I", data_tail[:4]),
                  data_tail[4:],
              )
              value, data_tail = (
                  data_tail[:value_size],
                  data_tail[value_size:],
              )
              data = data_tail
              yield key, value
      else:
          for chunk in stream:
              data = prev_chunk_tail + chunk
              prev_chunk_tail = b""
              while data:
                  try:
                      (key_size,), data_tail = (
                          struct.unpack("I", data[:4]),
                          data[4:],
                      )
                      key, data_tail = (
                          data_tail[:key_size],
                          data_tail[key_size:],
                      )
  
                      (value_size,), data_tail = (
                          struct.unpack("I", data_tail[:4]),
                          data_tail[4:],
                      )
                      value, data_tail = (
                          data_tail[:value_size],
                          data_tail[value_size:],
                      )
                      data = data_tail
                  except Exception:
                      prev_chunk_tail = data
                      break
  
                  yield key, value
  
          assert prev_chunk_tail == b""
  
imports: import datetime
  import itertools
  import os.path
  import shutil
  import numpy
  from PIL import Image
  from typing import Iterator
  import struct
  from sqlalchemy import text
  from aim.sdk.repo import Repo
  from aim.sdk.run import Run
  from aim.sdk.objects.image import Image
  from aim.storage.structured.sql_engine.models import Base
  from aim.web.api.db import get_contexted_session
  from aim.web.api.db import Base
label_desc: Use image node_id 1 for calling a global function with example usage: decode_encoded_tree_stream(stream, concat_chunks) without return types