      logger.trace("Requested batch: '%s'", filenames)
      executor = futures.ThreadPoolExecutor()
      with executor:
          images = {executor.submit(read_image, filename,
                                    raise_error=True, with_metadata=with_metadata): filename
                    for filename in filenames}
          batch = [None for _ in range(len(filenames))]
          if with_metadata:
              meta = [None for _ in range(len(filenames))]
          # There is no guarantee that the same filename will not be passed through multiple times
          # (and when shuffle is true this can definitely happen), so we can't just call
          # filenames.index().
          return_indices = {filename: [idx for idx, fname in enumerate(filenames)
                                       if fname == filename]
                            for filename in set(filenames)}
          for future in futures.as_completed(images):
              return_idx = return_indices[images[future]].pop()
              if with_metadata:
                  batch[return_idx], meta[return_idx] = future.result()
              else:
 
</s> remove     executor = futures.ThreadPoolExecutor()
    with executor:
 </s> add     batch = [None for _ in range(len(filenames))]
    if with_metadata:
        meta = [None for _ in range(len(filenames))]

    with futures.ThreadPoolExecutor() as executor: </s> remove             return_idx = return_indices[images[future]].pop()
 </s> add             ret_idx = images[future] </s> remove                 batch[return_idx], meta[return_idx] = future.result()
 </s> add                 batch[ret_idx], meta[ret_idx] = future.result() </s> remove         keys = [os.path.basename(filename) for filename in filenames]
        with self._lock:
            if _check_reset(self):
                self._reset_cache(False)

            needs_cache = [filename
                           for filename, key in zip(filenames, keys)
                           if not self._cache[key]["cached"]]
            logger.trace("Needs cache: %s", needs_cache)

            if not needs_cache:
                # Don't bother reading the metadata if no images in this batch need caching
                logger.debug("All metadata already cached for: %s", keys)
                return read_image_batch(filenames)

            batch, metadata = read_image_batch(filenames, with_metadata=True)

            if len(batch.shape) == 1:
                folder = os.path.dirname(filenames[0])
                details = [
                    "{0} ({1})".format(
                        key, f"{img.shape[1]}px" if isinstance(img, np.ndarray) else type(img))
                    for key, img in zip(keys, batch)]
                msg = (f"There are mismatched image sizes in the folder '{folder}'. All training "
                       "images for each side must have the same dimensions.\nThe batch that "
                       f"failed contains the following files:\n{details}.")
                raise FaceswapError(msg)

            # Populate items into cache
            for filename in needs_cache:
                key = os.path.basename(filename)
                meta = metadata[filenames.index(filename)]

                # Version Check
                self._validate_version(meta, filename)
                if self._partial_load:  # Faces already loaded for Warp-to-landmarks
                    detected_face = self._cache[key]["detected_face"]
                else:
                    detected_face = self._add_aligned_face(filename,
                                                           meta["alignments"],
                                                           batch.shape[1])

                self._add_mask(filename, detected_face)
                for area in ("eye", "mouth"):
                    self._add_localized_mask(filename, detected_face, area)

                self._cache[key]["cached"] = True
            # Update the :attr:`cache_full` attribute
            cache_full = all(item["cached"] for item in self._cache.values())
            if cache_full:
                logger.verbose("Cache filled: '%s'", os.path.dirname(filenames[0]))
                self._cache_full = cache_full

        return batch

    def pre_fill(self, filenames, side):
        """ When warp to landmarks is enabled, the cache must be pre-filled, as each side needs
        access to the other side's alignments.
 </s> add         if not self._face_cache.cache_full:
            raw_faces = self._face_cache.cache_metadata(filenames)
        else:
            raw_faces = read_image_batch(filenames)

        detected_faces = self._face_cache.get_items(filenames)
        logger.trace("filenames: %s, raw_faces: '%s', detected_faces: %s",  # type: ignore
                     filenames, raw_faces.shape, len(detected_faces))
        return raw_faces, detected_faces

    def _crop_to_coverage(self,
                          filenames: List[str],
                          images: np.ndarray,
                          detected_faces: List[DetectedFace],
                          batch: np.ndarray) -> None:
        """ Crops the training image out of the full extract image based on the centering and
        coveage used in the user's configuration settings.

        If legacy extract images are being used then this just returns the extracted batch with
        their corresponding landmarks.

        Uses thread pool execution for about a 33% speed increase @ 64 batch size </s> remove                 batch[return_idx] = future.result()
 </s> add                 batch[ret_idx] = future.result()
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
      logger.trace("Requested batch: '%s'", filenames)
      executor = futures.ThreadPoolExecutor()
      with executor:
          images = {executor.submit(read_image, filename,
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
                                  raise_error=True, with_metadata=with_metadata): idx
                  for idx, filename in enumerate(filenames)}
          for future in futures.as_completed(images):
              return_idx = return_indices[images[future]].pop()
              if with_metadata:
                  batch[return_idx], meta[return_idx] = future.result()
              else:
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
 Data Augmentation update (#1263)

- lib.detected_face
    - Subclass Masks for Landmark based masks
    - Add training mask propery + methods to DetectedFace
  - lib.training_training
    - subclass TrainingDataGenerator for training and preview data
    - Split cache into own module
    - Reduce thread count to 1 to prevent image corruption + data re-use
    - Process on largest model input/output size rather than stored image size
    - Size and crop masks during caching stage
    - Implement ring buffer for data flow
    - Fix preview reload bug
  - augmentation
    - typing
    - switch color aug order
    - better initialization
    - Fix warp + landmark warp to correctly apply at different image scales
    - Slightly improved warp caching
    - Don't store whether image is_preview. Handle all data as training images implicitly
  - plugins.trainer: Typing and fixes to work with trainingdata refactor 
lib/image.py