code: def safe_encode(x, as_literal=True):
      """
      Encodes a python value for prov
      """
      if x is None:
          value = "Unknown"
          if as_literal:
              return pm.Literal(value, pm.XSD["string"])
          else:
              return value
  
      if isinstance(x, (str, bytes)):
          if isinstance(x, bytes):
              x = str(x, "utf-8")
          if os.path.exists(x):
              if x[0] != os.pathsep:
                  x = os.path.abspath(x)
              value = f"file://{platform.node().lower()}{x}"
              if not as_literal:
                  return value
              try:
                  return pm.URIRef(value)
              except AttributeError:
                  return pm.Literal(value, pm.XSD["anyURI"])
          else:
              value = x
              if len(x) > max_text_len:
                  cliptxt = "...Clipped..."
                  value = x[: max_text_len - len(cliptxt)] + cliptxt
  
              if not as_literal:
                  return value
  
              return pm.Literal(value, pm.XSD["string"])
      if isinstance(x, int):
          if not as_literal:
              return x
          return pm.Literal(int(x), pm.XSD["integer"])
      if isinstance(x, float):
          if not as_literal:
              return x
          return pm.Literal(x, pm.XSD["float"])
      if isinstance(x, dict):
          outdict = {}
          for key, value in list(x.items()):
              encoded_value = safe_encode(value, as_literal=False)
              if isinstance(encoded_value, pm.Literal):
                  outdict[key] = encoded_value.json_representation()
              else:
                  outdict[key] = encoded_value
  
          try:
              jsonstr = json.dumps(outdict)
          except UnicodeDecodeError as excp:
              jsonstr = f"Could not encode dictionary. {excp}"
              logger.warning("Prov: %s", jsonstr)
  
          if not as_literal:
              return jsonstr
          return pm.Literal(jsonstr, pm.XSD["string"])
      if isinstance(x, (list, tuple)):
          x = list(x)
          is_object = False
          try:
              nptype = np.array(x).dtype
              is_object = nptype == np.dtype(object)
          except ValueError:
              is_object = True
  
          # If the array contains an heterogeneous mixture of data types
          # they should be encoded sequentially
          if is_object:
              outlist = []
              for value in x:
                  encoded_value = safe_encode(value, as_literal=False)
                  if isinstance(encoded_value, pm.Literal):
                      outlist.append(
                          encoded_value.json_representation()
                      )
                  else:
                      outlist.append(encoded_value)
              x = outlist
  
          try:
              jsonstr = json.dumps(x)
          except UnicodeDecodeError as excp:
              jsonstr = f"Could not encode list/tuple. {excp}"
              logger.warning("Prov: %s", jsonstr)
  
          if not as_literal:
              return jsonstr
          return pm.Literal(jsonstr, pm.XSD["string"])
  
      # If is a literal, and as_literal do nothing.
      # else bring back to json.
      if isinstance(x, pm.Literal):
          if as_literal:
              return x
          return dumps(x.json_representation())
  
      jsonstr = None
      ltype = pm.XSD["string"]
      try:
          jsonstr = json.dumps(x.__dict__)
      except AttributeError:
          pass
  
      if jsonstr is None:
          try:
              jsonstr = dumps(x)
              ltype = nipype_ns["pickle"]
          except TypeError as excp:
              jsonstr = f"Could not encode object. {excp}"
  
      if not as_literal:
          return jsonstr
      return pm.Literal(jsonstr, ltype)
  
imports: from collections import OrderedDict
  from copy import deepcopy
  from pickle import dumps
  import os
  import getpass
  import platform
  from uuid import uuid1
  import simplejson
  import numpy
  import prov.model
  from ..None import get_info, logging, __version__
  from .filemanip import md5, hashlib, hash_infile
label_desc: Use image node_id 4 for calling a global function with example usage: safe_encode(x, as_literal) and returns: pm, pm, pm, pm, pm, dumps, jsonstr, pm, value, pm, x, x, jsonstr, jsonstr, x, value, pm, value, pm