code: def _init_frames(
      dataset,
      src_collection,
      sample_frames,
      output_dir,
      rel_dir,
      frames_patt,
      fps,
      max_fps,
      sparse,
      force_sample,
      verbose,
  ):
      if (
          (sample_frames != False and not sparse)
          or fps is not None
          or max_fps is not None
      ):
          # We'll need frame counts to determine what frames to include/sample
          src_collection.compute_metadata()
  
      if sample_frames == True and verbose:
          logger.info("Determining frames to sample...")
  
      #
      # Initialize frames dataset with proper frames
      #
  
      docs = []
      src_docs = []
      src_inds = []
      missing_filepaths = []
  
      id_map = {}
      sample_map = defaultdict(set)
      frame_map = defaultdict(set)
  
      src_dataset = src_collection._root_dataset
      is_clips = src_collection._dataset._is_clips
      if src_collection.has_frame_field("filepath"):
          view = src_collection.select_fields("frames.filepath")
      else:
          view = src_collection.select_fields()
  
      # If we're sampling frames on a view that may have filtered frames, we must
      # consult the full dataset to see which frames already have docs/filepaths
      has_docs_map = None
      has_filepaths_map = None
      if (
          sample_frames == True
          and not sparse
          and isinstance(src_collection, fov.DatasetView)
          and src_collection._needs_frames()
      ):
          id_field = "sample_id" if is_clips else "id"
          _view = src_dataset.select(src_collection.values(id_field))
          ids, fns = _view.values(["_id", "frames.frame_number"])
  
          has_docs_map = {_id: set(_fns) for _id, _fns in zip(ids, fns)}
  
          if src_dataset.has_frame_field("filepath"):
              ids, fns = _view.match_frames(
                  fo.ViewField("filepath") != None,
                  omit_empty=False,
              ).values(["_id", "frames.frame_number"])
              has_filepaths_map = {
                  _id: set(_fns) for _id, _fns in zip(ids, fns)
              }
  
      for sample in view._aggregate(attach_frames=True):
          video_path = sample["filepath"]
          tags = sample.get("tags", [])
          metadata = sample.get("metadata", None) or {}
          frame_rate = metadata.get("frame_rate", None)
          total_frame_count = metadata.get("total_frame_count", -1)
          frames = sample.get("frames", [])
  
          frame_ids_map = {}
          frames_with_docs = set()
          frames_with_filepaths = set()
          for frame in frames:
              _frame_id = frame["_id"]
              fn = frame["frame_number"]
              filepath = frame.get("filepath", None)
  
              if sample_frames != False or filepath is not None:
                  frame_ids_map[fn] = _frame_id
  
              if sample_frames == True:
                  frames_with_docs.add(fn)
                  if filepath is not None:
                      frames_with_filepaths.add(fn)
  
          if is_clips:
              _sample_id = sample["_sample_id"]
              support = sample["support"]
          else:
              _sample_id = sample["_id"]
              support = None
  
          _outpath = fouv._get_outpath(
              video_path, output_dir=output_dir, rel_dir=rel_dir
          )
          images_patt = os.path.join(
              os.path.splitext(_outpath)[0], frames_patt
          )
  
          # Determine which frame numbers to include in the frames dataset and
          # whether any frame images need to be sampled
          doc_frame_numbers, sample_frame_numbers = _parse_video_frames(
              video_path,
              sample_frames,
              images_patt,
              support,
              total_frame_count,
              frame_rate,
              frame_ids_map,
              force_sample,
              sparse,
              fps,
              max_fps,
              verbose,
          )
  
          # Record things that need to be sampled
          # Note: [] means no frames, None means all frames
          if sample_frame_numbers != []:
              id_map[video_path] = str(_sample_id)
  
              if sample_frame_numbers is None:
                  sample_map[video_path] = None
              elif sample_map[video_path] is not None:
                  sample_map[video_path].update(sample_frame_numbers)
  
          # Determine if any docs/filepaths are missing from the source dataset
          if sample_frames == True:
              if has_docs_map is not None:
                  frames_with_docs = has_docs_map[_sample_id]
  
              if has_filepaths_map is not None:
                  frames_with_filepaths = has_filepaths_map[_sample_id]
  
              target_frames = set(doc_frame_numbers)
              missing_docs = target_frames - frames_with_docs
              missing_fps = target_frames - frames_with_filepaths
          else:
              missing_docs = None
              missing_fps = None
  
          # Create necessary frame documents
          for fn in doc_frame_numbers:
              if is_clips:
                  fns = frame_map[video_path]
                  if fn in fns:
                      continue  # frame has already been sampled
  
                  fns.add(fn)
  
              _id = frame_ids_map.get(fn, None)
              _filepath = images_patt % fn
              _rand = foos._generate_rand(_filepath)
              _dataset_id = dataset._doc.id
  
              if missing_fps is not None and fn in missing_fps:
                  missing_filepaths.append((_sample_id, fn, _filepath))
  
              if sample_frames == "dynamic":
                  filepath = video_path
              else:
                  # This will be overwritten in the final merge if the actual
                  # filepath is different
                  filepath = _filepath
  
              doc = {
                  "filepath": filepath,
                  "tags": tags,
                  "metadata": None,
                  "frame_number": fn,
                  "_media_type": "image",
                  "_rand": _rand,
                  "_sample_id": _sample_id,
                  "_dataset_id": _dataset_id,
              }
  
              if _id is not None:
                  doc["_id"] = _id
              elif missing_docs is not None and fn in missing_docs:
                  # Found a frame that we want to include in the frames dataset
                  # whose image is already sampled but for which there is no
                  # frame doc in the source collection. We need to create a frame
                  # doc so that the frames dataset can use the same frame ID
                  src_docs.append(
                      {"_sample_id": _sample_id, "frame_number": fn}
                  )
                  src_inds.append(len(docs))
  
              docs.append(doc)
  
              # Commit batch of docs to frames dataset
              if len(docs) >= 10000:
                  _insert_docs(
                      docs, src_docs, src_inds, dataset, src_dataset
                  )
  
      # Add remaining docs to frames dataset
      _insert_docs(docs, src_docs, src_inds, dataset, src_dataset)
  
      # Add missing frame filepaths to source collection
      if missing_filepaths:
          logger.info(
              "Setting %d frame filepaths on the input collection that exist "
              "on disk but are not recorded on the dataset",
              len(missing_filepaths),
          )
          src_dataset.add_frame_field("filepath", fof.StringField)
          ops = [
              UpdateOne(
                  {"_sample_id": _sample_id, "frame_number": fn},
                  {"$set": {"filepath": filepath}},
              )
              for _sample_id, fn, filepath in missing_filepaths
          ]
          src_dataset._bulk_write(ops, frames=True)
  
      #
      # Finalize which frame images need to be sampled, if any
      #
      # We first populate `sample_map` and then convert to `ids_to_sample` and
      # `frames_to_sample` here to avoid resampling frames when working with clip
      # views with multiple overlapping clips into the same video
      #
  
      ids_to_sample = []
      frames_to_sample = []
      for video_path, sample_frame_numbers in sample_map.items():
          ids_to_sample.append(id_map[video_path])
          if sample_frame_numbers is not None:
              sample_frame_numbers = sorted(sample_frame_numbers)
  
          frames_to_sample.append(sample_frame_numbers)
  
      if ids_to_sample:
          if src_dataset.media_type == fom.GROUP:
              sample_view = src_dataset.select_group_slices(
                  media_type=fom.VIDEO
              )
          else:
              sample_view = src_dataset
  
          sample_view = sample_view.select(ids_to_sample, ordered=True)
      else:
          sample_view = None
  
      return sample_view, frames_to_sample
  
imports: from collections import defaultdict
  from copy import deepcopy
  import logging
  import os
  from bson import ObjectId
  from pymongo import UpdateOne
  import eta.core.utils
  import fiftyone
  import fiftyone.core.dataset
  import fiftyone.core.fields
  import fiftyone.core.media
  import fiftyone.core.sample
  import fiftyone.core.odm
  import fiftyone.core.odm.sample
  import fiftyone.core.utils
  import fiftyone.core.validation
  import fiftyone.core.view
label_desc: Use image node_id 3 for calling a global function with example usage: _init_frames(dataset, src_collection, sample_frames, output_dir, rel_dir, frames_patt, fps, max_fps, sparse, force_sample, verbose) and returns: sample_view,  frames_to_sample