code: def run():
      """Create pileup images from examples, filtered in various ways."""
      with errors.clean_commandline_error_exit():
          if not _EXAMPLES.value:
              raise ValueError("--examples is required")
          examples_path = _EXAMPLES.value
  
          if _COLUMN_LABELS.value and _EXAMPLE_INFO_JSON.value:
              raise ValueError(
                  "Set at most one of --column_labels or --example_info_json."
              )
  
          if _COLUMN_LABELS.value:
              column_labels = _COLUMN_LABELS.value.split(",")
          else:
              column_labels = None
  
          if _EXAMPLE_INFO_JSON.value:
              example_info = json.load(
                  tf.io.gfile.GFile(_EXAMPLE_INFO_JSON.value, "r")
              )
              column_labels = [
                  deepvariant_pb2.DeepVariantChannelEnum.Name(x)
                  for x in example_info["channels"]
              ]
  
          filter_to_vcf = _VCF.value is not None
          if filter_to_vcf:
              ids_from_vcf = parse_vcf(_VCF.value)
              logging.info(
                  (
                      "Found %d loci in VCF. "
                      "Only examples matching these loci will be output."
                  ),
                  len(ids_from_vcf),
              )
  
          filter_to_region = _REGIONS.value is not None
          if filter_to_region:
              passes_region_filter = create_region_filter(
                  region_flag_string=_REGIONS.value,
                  verbose=_VERBOSE.value,
              )
          if _FILTER_BY_TSV.value:
              tsv_df = pd.read_csv(
                  _FILTER_BY_TSV.value, sep="\t", header=None
              )
              ids_from_tsv = set(tsv_df[0])
  
          # Use nucleus.io.tfrecord to read all shards.
          dataset = tfrecord.read_tfrecords(examples_path)
  
          make_rgb = _IMAGE_TYPE.value in ["both", "RGB"]
          make_channels = _IMAGE_TYPE.value in ["both", "channels"]
  
          # Prepare output directory:
          output_prefix = (
              "{}_".format(_OUTPUT.value)
              if _OUTPUT.value is not None
              else ""
          )
          if output_prefix:
              tf.io.gfile.makedirs(os.path.dirname(output_prefix))
  
          if _WRITE_TFRECORDS.value:
              tfrecord_writer = tf.io.TFRecordWriter(
                  f"{output_prefix}examples.tfrecord.gz",
                  options=tf.io.TFRecordOptions(
                      compression_type="GZIP"
                  ),
              )
  
          if _CURATE.value:
              curation_tags = []
  
          num_scanned = 0
          num_output = 0
          for example in dataset:
              num_scanned += 1
              if (
                  _MAX_EXAMPLES_TO_SCAN.value is not None
                  and num_scanned > _MAX_EXAMPLES_TO_SCAN.value
              ):
                  break
              # Only when scanning many examples, print a dot for each one to
              # indicate that the script is making progress and not stalled.
              if num_scanned % UPDATE_EVERY_N_EXAMPLES == 0:
                  if num_scanned == UPDATE_EVERY_N_EXAMPLES:
                      print(
                          "Reporting progress below. Writing one dot every time {} "
                          "examples have been scanned:".format(
                              UPDATE_EVERY_N_EXAMPLES
                          )
                      )
                  # Print another dot on the same line, using print since logging does
                  # not support printing without a newline.
                  print(".", end="", flush=True)
  
              # Extract variant from example.
              variant = vis.variant_from_example(example)
              locus_id = vis.locus_id_from_variant(variant)
              indices = vis.alt_allele_indices_from_example(example)
              # Use locus ID in the filename, replacing long alleles with INS/DEL sizes.
              locus_with_alt_id = get_short_id(variant, indices)
  
              # Optionally filter to variants in the VCF.
              if filter_to_vcf:
                  # Check if the locus is in the VCF.
                  if locus_id not in ids_from_vcf:
                      # Skip this example since it doesn't match the VCF.
                      continue
  
              if filter_to_region and not passes_region_filter(variant):
                  continue
  
              if (
                  _FILTER_BY_TSV.value
                  and locus_with_alt_id not in ids_from_tsv
              ):
                  continue
  
              if _VERBOSE.value:
                  logging.info(
                      "\nOutputting image for: %s", locus_with_alt_id
                  )
                  full_id = get_full_id(variant, indices)
                  if locus_with_alt_id != full_id:
                      logging.info(
                          (
                              "ID above was shortened due to long ref/alt strings. "
                              "Original: %s"
                          ),
                          full_id,
                      )
  
              # If the example has a truth label, optionally include it.
              optional_truth_label = ""
              if _TRUTH_LABELS.value:
                  truth_label = get_label(example)
                  if truth_label is not None:
                      optional_truth_label = "_label{}".format(
                          truth_label
                      )
  
              # Extract and format example into channels.
              channels = vis.channels_from_example(example)
              if column_labels is not None and len(
                  column_labels
              ) != len(channels):
                  raise ValueError(
                      "--column_labels must have {} names separated by commas, since "
                      "there are {} channels in the examples. "
                      "However, {} column labels were found: {}".format(
                          len(channels),
                          len(channels),
                          len(column_labels),
                          ",".join(
                              ['"{}"'.format(x) for x in column_labels]
                          ),
                      )
                  )
  
              # Create image with a grey-scale row of channels and save to file.
              if make_channels:
                  channels_output = "{}{}{}.png".format(
                      output_prefix,
                      locus_with_alt_id,
                      optional_truth_label,
                  )
  
                  vis.draw_deepvariant_pileup(
                      channels=channels,
                      path=channels_output,
                      scale=_SCALE.value,
                      show=False,
                      annotated=_ANNOTATION.value,
                      labels=column_labels,
                  )
  
              # Create RGB image and save to file.
              if make_rgb:
                  rgb_output = "{}{}{}.rgb.png".format(
                      output_prefix,
                      locus_with_alt_id,
                      optional_truth_label,
                  )
                  vis.draw_deepvariant_pileup(
                      channels=channels,
                      composite_type="RGB",
                      path=rgb_output,
                      scale=_SCALE.value,
                      show=False,
                      annotated=_ANNOTATION.value,
                      labels=column_labels,
                  )
              if _CURATE.value:
                  tags = vis.curate_pileup(channels=channels)
                  tags = curation_to_dict(tags)
                  example_width = channels[0].shape[1]
                  buffer = int(example_width / 2)
                  curation_tags.append(
                      {
                          "id": locus_with_alt_id,
                          "pos": f"{variant.reference_name}:{variant.start}",
                          # Pileup window, e.g. for IGV automation "goto" command:
                          "window": (
                              f"{variant.reference_name}:{variant.start - buffer}-"
                              f"{variant.start + buffer + 1}"
                          ),
                          "label": optional_truth_label,
                          **tags,
                      }
                  )
              if _WRITE_TFRECORDS.value:
                  tfrecord_writer.write(example.SerializeToString())
  
              # Check if --num_records quota has been hit yet.
              num_output += 1
              if (
                  _NUM_RECORDS.value is not None
                  and num_output >= _NUM_RECORDS.value
              ):
                  break
  
          logging.info(
              "Scanned %d examples and output %d images.",
              num_scanned,
              num_output,
          )
  
          if _WRITE_TFRECORDS.value:
              tfrecord_writer.close()
  
          if _CURATE.value:
              df = pd.DataFrame(curation_tags)
              df.to_csv(
                  f"{output_prefix}curation.tsv", index=False, sep="\t"
              )
  
          if num_scanned == 0 and examples_path.startswith("gs://"):
              if sharded_file_utils.is_sharded_file_spec(examples_path):
                  paths = sharded_file_utils.generate_sharded_filenames(
                      examples_path
                  )
                  special_gcs_message = (
                      "WARNING: --examples sharded files are either "
                      "all empty or do not exist. Please check that "
                      "the paths are correct:\n"
                  )
                  for p in paths[0:3]:
                      special_gcs_message += "gsutil ls {}\n".format(p)
                  logging.warning(special_gcs_message)
              else:
                  logging.warning(
                      (
                          "WARNING: --examples file is either empty or does not exist. "
                          "Please check that the path is correct: \n"
                          "gsutil ls %s"
                      ),
                      examples_path,
                  )
  
imports: import gzip
  import json
  import os
  from typing import Any, Callable, Dict, Optional, Sequence, Set
  from absl import app
  from absl import flags
  from absl import logging
  import pandas
  import tensorflow
  from deepvariant.protos import deepvariant_pb2
  from third_party.nucleus.io import sharded_file_utils
  from third_party.nucleus.io import tfrecord
  from third_party.nucleus.protos import variants_pb2
  from third_party.nucleus.util import errors
  from third_party.nucleus.util import ranges
  from third_party.nucleus.util import vis
label_desc: Use image node_id 7 for calling a global function with example usage: run() without return types