code: def export_trials_data(args):
      """export experiment metadata and intermediate results to json or csv"""
  
      def groupby_trial_id(intermediate_results):
          sorted(intermediate_results, key=lambda x: x["timestamp"])
          groupby = dict()
          for content in intermediate_results:
              groupby.setdefault(content["trialJobId"], []).append(
                  json.loads(content["data"])
              )
          return groupby
  
      experiments_config = Experiments()
      experiments_dict = experiments_config.get_all_experiments()
      experiment_id = get_config_filename(args)
      rest_port = experiments_dict.get(experiment_id).get("port")
      rest_pid = experiments_dict.get(experiment_id).get("pid")
  
      if not detect_process(rest_pid):
          print_error("Experiment is not running...")
          return
      running, response = check_rest_server_quick(rest_port)
      if not running:
          print_error("Restful server is not running")
          return
      response = rest_get(export_data_url(rest_port), 20)
      if response is not None and check_response(response):
          content = json.loads(response.text)
          if args.intermediate:
              intermediate_results_response = rest_get(
                  metric_data_url(rest_port), REST_TIME_OUT
              )
              if (
                  not intermediate_results_response
                  or not check_response(intermediate_results_response)
              ):
                  print_error("Error getting intermediate results.")
                  return
              intermediate_results = groupby_trial_id(
                  json.loads(intermediate_results_response.text)
              )
              for record in content:
                  record["intermediate"] = intermediate_results[
                      record["trialJobId"]
                  ]
          if args.type == "json":
              with open(args.path, "w") as file:
                  file.write(json.dumps(content))
          elif args.type == "csv":
              trial_records = []
              for record in content:
                  formated_record = dict()
                  if args.intermediate:
                      formated_record["intermediate"] = (
                          "[" + ",".join(record["intermediate"]) + "]"
                      )
                  record_value = json.loads(record["value"])
                  if not isinstance(record_value, (float, int)):
                      formated_record.update(
                          {
                              **record["parameter"],
                              **record_value,
                              **{"trialJobId": record["trialJobId"]},
                          }
                      )
                  else:
                      formated_record.update(
                          {
                              **record["parameter"],
                              **{
                                  "reward": record_value,
                                  "trialJobId": record["trialJobId"],
                              },
                          }
                      )
                  trial_records.append(formated_record)
              if not trial_records:
                  print_error(
                      "No trial results collected! Please check your trial log..."
                  )
                  exit(0)
              with open(args.path, "w", newline="") as file:
                  writer = csv.DictWriter(
                      file,
                      set.union(
                          *[set(r.keys()) for r in trial_records]
                      ),
                  )
                  writer.writeheader()
                  writer.writerows(trial_records)
          else:
              print_error("Unknown type: %s" % args.type)
              return
      else:
          print_error("Export failed...")
  
imports: import csv
  import os
  import sys
  import json
  import time
  import shutil
  import subprocess
  from functools import cmp_to_key
  import traceback
  from datetime import datetime, timezone
  from subprocess import Popen
  from .rest_utils import rest_get, rest_delete, check_rest_server_quick, check_response
  from .url_utils import trial_jobs_url, experiment_url, trial_job_id_url, export_data_url, metric_data_url
  from .config_utils import Config, Experiments
  from .constants import NNI_HOME_DIR, EXPERIMENT_INFORMATION_FORMAT, EXPERIMENT_DETAIL_FORMAT, EXPERIMENT_MONITOR_INFO, TRIAL_MONITOR_HEAD, TRIAL_MONITOR_CONTENT, TRIAL_MONITOR_TAIL, REST_TIME_OUT
  from .common_utils import print_normal, print_error, print_warning, detect_process, get_yml_content, generate_temp_dir
  from .common_utils import print_green
  from .command_utils import check_output_command, kill_command
  from .ssh_utils import create_ssh_sftp_client, remove_remote_directory
label_desc: Use image node_id 32 for calling a global function with example usage: export_trials_data(args) and returns: groupby