Utils
*****

exception psynet.utils.DuplicateKeyError

   Bases: "ValueError"

class psynet.utils.NoArgumentProvided

   Bases: "object"

   We use this class as a replacement for "None" as a default
   argument, to distinguish cases where the user doesn't provide an
   argument from cases where they intentionally provide "None" as an
   argument.

class psynet.utils.PatternDir(pattern, glob_dir)

   Bases: "object"

exception psynet.utils.TranslationNotFoundError

   Bases: "KeyError"

psynet.utils.as_plain_text(html)

   Convert HTML to readable text using "html2text", collapsing
   whitespace to single spaces.

   Parameters:
      **html** (*str** or **markupsafe.Markup*) -- HTML to convert.

   Return type:
      str

psynet.utils.call_function(function, *args, **kwargs)

   Calls a function with "*args" and "**kwargs", but omits any
   "**kwargs" that are not requested explicitly.

psynet.utils.call_if_callable(value, **kwargs)

   Return "value", or the result of calling it with context if it is a
   function.

   Used for settings such as time limits that may be a number or a
   function of "participant" and/or "experiment"; see
   "call_function_with_context()".

psynet.utils.check_for_login_errors(response)

   Raise "RuntimeError" with the form's messages if a dashboard login
   failed.

psynet.utils.content_object_path(digest)

   Return the canonical relative object path for a content digest.

   Return type:
      "str"

psynet.utils.finalize_template_value(value)

   Mark dominate tags as safe HTML before Jinja autoescapes template
   output.

   Dominate escapes the text it is given, so a rendered tag is trusted
   HTML. Plain strings are still escaped; wrap trusted HTML in
   "markupsafe.Markup".

psynet.utils.find_git_repo()

   Finds the origin of the git repository of the current directory.

   Any credentials embedded in the remote URL are removed, because the
   result is stored in deployment records and exports.

psynet.utils.format_bytes(num)

   Formats bytes into a human-readable string.

   Parameters:
      **num** (*float*) -- The number of bytes to format.

   Returns:
      The formatted string.

   Return type:
      str

   -[ Examples ]-

   >>> format_bytes(1024)
   '1.0KB'
   >>> format_bytes(1048576)
   '1.0MB'
   >>> format_bytes(1073741824)
   '1.0GB'

psynet.utils.format_timedelta(timedelta_obj)

   Formats a timedelta object as a human-readable string. Source:
   https://stackoverflow.com/questions/538666/format-timedelta-to-
   string

psynet.utils.get_authenticated_session(base_url, username=None, password=None)

   Returns a requests.Session authenticated with the dashboard login.

   Handles CSRF tokens automatically by fetching the login page first.

   Parameters:
      * **base_url** (*str*) -- The root URL of the server (e.g.,
        'http://localhost:5000').

      * **username** (*str**, **optional*) -- Dashboard username. If
        None, will use config.

      * **password** (*str**, **optional*) -- Dashboard password. If
        None, will use config.

   Returns:
      **session** -- Authenticated session for making further
      requests.

   Return type:
      requests.Session

   Raises:
      **RuntimeError** -- If login fails due to invalid credentials.

   -[ Examples ]-

   >>> from psynet.utils import get_authenticated_session
   >>> session = get_authenticated_session('http://localhost:5000', 'admin', 'secret')
   >>> response = session.get('http://localhost:5000/bot/1')
   >>> response.raise_for_status()

psynet.utils.get_config()

   Return the Dallinger configuration object, loading it first if
   needed.

   Read values with "get_config().get(key)".

   Return type:
      dallinger.config.Configuration

psynet.utils.get_custom_sql_classes()

   Returns:
      * *A dictionary of all custom SQLAlchemy classes defined in the
        local experiment*

      * *(excluding any which are defined within packages).*

psynet.utils.get_descendent_class_by_name(parent_class, name)

   Attempt to return a subclass by name.

   Actual class names and known nicknames are both supported.

psynet.utils.get_experiment_url(app=None, server=None)

   Return the experiment's URL.

   Without "app" or "server", this is the URL the running experiment
   registered in Redis, unless the "PSYNET_EXPERIMENT_URL" environment
   variable gives another address for this process to reach it by.

psynet.utils.get_fitting_font_size(text, font_path, max_width, max_height, min_font_size, max_font_size)

   Find the largest font size that allows the text to fit within the
   given width and height.

psynet.utils.get_installed_package_source_directory(package_name)

   Get the source directory of an installed package.

   Parameters:
      **package_name** (*str*) -- The name of the package.

   Returns:
      The path to the package root directory.

   Return type:
      Path

   Raises:
      **FileNotFoundError** -- If the package root directory cannot be
      found.

psynet.utils.get_logger(name='psynet')

   Return a standard-library logger, by default the shared "psynet"
   logger.

   Parameters:
      **name** (*str*) -- Logger name passed to "logging.getLogger()".

   Return type:
      logging.Logger

psynet.utils.get_object_from_module(module_name, object_name)

   Finds and returns an object from a module.

   Parameters:
      * **module_name** ("str") -- The name of the module.

      * **object_name** ("str") -- The name of the object.

psynet.utils.get_package_name(path='.')

   Find the package name by inspecting a directory.

   Parameters:
      **path** (*str** or **Path**, **optional*) -- Path to the
      directory containing "pyproject.toml" or "setup.py".

   Returns:
      The package name from the configuration file.

   Return type:
      str

   Raises:
      **FileNotFoundError** -- If neither "pyproject.toml" nor
      "setup.py" is present in "path".

psynet.utils.get_package_name_from_pyproject(path='.')

   Get package name from pyproject.toml file.

   Parameters:
      **path** (*str** or **Path**, **optional*) -- Path to the
      directory containing pyproject.toml.

   Returns:
      The package name from pyproject.toml.

   Return type:
      str

psynet.utils.get_package_name_from_setup(path='.')

   Get package name from setup.py file.

   Parameters:
      **path** (*str** or **Path**, **optional*) -- Path to the
      directory containing setup.py.

   Returns:
      The package name from setup.py.

   Return type:
      str

psynet.utils.get_package_source_directory(path='.')

   Get the source directory of the package by inspecting
   pyproject.toml or setup.py. Does not assume that the package is
   installed.

   Parameters:
      **path** (*str*) -- The path to the package source directory.

   Returns:
      The path to the package source directory.

   Return type:
      str

   Raises:
      **FileNotFoundError** -- If the package source directory cannot
      be found.

psynet.utils.get_translator(context=False, locale=None, namespace=None, locales_dir=None)

   Return a translator.

   In most cases this function should be called with no arguments, in
   which case the locale will be taken from the config.txt file, the
   namespace will be inferred from the context in which the function
   was called, and the locales directory will be inferred from the
   namespace.

   The default translator is context-free, which means that it only
   takes a message argument. We recommend using this in most cases.
   You can obtain a context-aware translator by setting "context =
   True"; such a translator takes both a context and a message
   argument.

   PsyNet uses automated code inspection tools to extract all
   translatable strings from your code. In order for these tools to
   work properly, you should save the returned translator with the
   name "_" if "context = False" or "_p" if "context = True".

   Once you have marked up your code with the "_" and "_p" functions,
   you can then run "psynet translate" to generate automatically
   translated versions of your strings.


   Example usage
   =============

   >>> _ = get_translator()
   >>> _("Hello")  # Translate "Hello" into the current locale.

   >>> _p = get_translator(context=True)
   >>> _p("welcome message", "Hello")  # Translate "Hello" into the current locale, with context "welcome message".

   type context:
   param context:
      Whether to use the context argument. If True, the translator
      will be a function that takes a context argument and a message
      argument. If False, the translator will be a function that just
      takes a message argument.

   type context:
      bool, optional

   type locale:
   param locale:
      The locale to use for translations. If not provided, the locale
      will be taken from the experiment config.

   type locale:
      str, optional

   type namespace:
   param namespace:
      The namespace to use for translations. If not provided, the
      namespace will be inferred from the context in which the
      function was called. The experiment directory has a namespace of
      "experiment", and the package directory has a namespace of the
      package name.

   type namespace:
      str, optional

   type locales_dir:
   param locales_dir:
      The directory to use for translations. If not provided, the
      locales directory will be inferred from the namespace. In the
      case of an experiment, the locales directory will be the
      "locales" directory of the experiment's source directory. In the
      case of a package, the locales directory will be the "locales"
      directory of the package's source directory.

   type locales_dir:
      str, optional

psynet.utils.in_python_package()

   Test whether the current directory is the root of a Python package.

   Returns:
      See "is_a_package()".

   Return type:
      bool

psynet.utils.is_a_package(path)

   Test whether a directory is the root of a Python package rather
   than an experiment.

   Parameters:
      **path** (*str** or **Path*) -- Directory to inspect.

   Returns:
      True if the directory contains "pyproject.toml" or "setup.py"
      and no "experiment.py". Experiment directories may carry their
      own "pyproject.toml" (for example from "uv init").

   Return type:
      bool

psynet.utils.is_method_overridden(obj, ancestor, method)

   Test whether a method has been overridden.

   Parameters:
      * **obj** -- Object to test.

      * **ancestor** ("Type") -- Ancestor class to test against.

      * **method** ("str") -- Method name.

   Returns:
      * Returns "True" if the object shares a method with its
        ancestor,

      * or "False" if that method has been overridden.

psynet.utils.is_release_branch()

   Return whether the current CI job is on a "release-*" branch.

psynet.utils.keep_alive_session(retry_posts=False)

   Return a "requests.Session" that reuses connections and retries
   dropped ones.

   A server or proxy may close an idle keep-alive connection just as
   the client reuses it (gunicorn's default keep-alive is 2 seconds),
   which shows up as "Connection reset by peer". The session retries
   such a request once. Responses with error statuses are never
   retried.

   Parameters:
      **retry_posts** (*bool*) -- Also retry POST and other non-
      idempotent requests. The server may already have handled a
      request whose connection then dropped, so only enable this when
      a repeat is harmless, as for bots' "/response" POSTs, which the
      server rejects for a page the participant has left.

psynet.utils.linspace(lower, upper, length)

   Returns a list of equally spaced numbers between two closed bounds.

   Parameters:
      * **lower** (*number*) -- The lower bound.

      * **upper** (*number*) -- The upper bound.

      * **length** (*int*) -- The length of the resulting list.

psynet.utils.list_experiment_dirs(for_ci_tests=False)

   List in-repo experiment directories under
   "_IN_REPO_EXPERIMENT_ROOTS".

   Skips hidden directories while walking so leftover virtualenvs
   under a demo (e.g. ".venv") are not mistaken for experiments when
   they contain an "experiment.py" inside "site-packages".

psynet.utils.load_runtime_server_config(config=None, deployment_id=None)

   Return the configuration of the running server, including runtime
   values.

   Runtime values such as dashboard credentials come from the config
   of the running debug server, or else from the launch info of
   "deployment_id".

   Parameters:
      * **config** (*dallinger.config.Configuration**, **optional*) --
        The configuration to extend; by default Dallinger's
        configuration.

      * **deployment_id** (*str**, **optional*) -- The deployment
        whose saved launch info to read when no debug server is
        running.

   Return type:
      dallinger.config.Configuration

psynet.utils.loading_experiment_classes()

   Suppress SQLAlchemy warnings about redeclaring the experiment's
   classes.

   Wrap any call that may execute "experiment.py". Other warnings
   raised while loading the experiment are left alone.

psynet.utils.make_parents(path)

   Creates the parent directories for a specified file if they don't
   exist already.

   Returns:
      * *The original path.*

psynet.utils.md5_file(filename)

   Return the MD5 hex digest of a single file.

   Return type:
      "str"

psynet.utils.md5_update_from_dir(directory, hash)

   Recursively update *hash* with all non-hidden files under
   *directory*.

   Return type:
      "HASH"

psynet.utils.md5_update_from_file(filename, hash)

   Update *hash* with the contents of *filename* and return it.

   Return type:
      "HASH"

psynet.utils.merge_dicts(*args, overwrite)

   Merges a collection of dictionaries, with later dictionaries taking
   precedence when the same key appears twice.

   Parameters:
      * ***args** -- Dictionaries to merge.

      * **overwrite** ("bool") -- If "True", when the same key appears
        twice in multiple dictionaries, the key from the latter
        dictionary takes precedence. If "False", an error is thrown if
        such duplicates occur.

psynet.utils.merge_two_dicts(x, y, overwrite)

   Merges two dictionaries.

   Parameters:
      * **x** ("dict") -- First dictionary.

      * **y** ("dict") -- Second dictionary.

      * **overwrite** ("bool") -- If "True", when the same key appears
        twice in the two dictionaries, the key from the latter
        dictionary takes precedence. If "False", an error is thrown if
        such duplicates occur.

psynet.utils.negate(f)

   Negates a function.

   Parameters:
      **f** -- Function to negate.

psynet.utils.null_translator(message)

   A translator that returns the message unchanged.

psynet.utils.null_translator_with_context(context, message)

   A translator that returns the message unchanged.

psynet.utils.organize_by_key(lst, key, sort_key=None)

   Sorts a list of items into groups.

   Parameters:
      * **lst** -- List to sort.

      * **key** -- Function applied to elements of "lst" which defines
        the grouping key.

   Returns:
      * A dictionary keyed by the outputs of "key".

psynet.utils.patch_yaspin_jupyter_detection()

   Patch yaspin's is_jupyter detection to be more accurate. The
   default implementation just checks if stdout is not a TTY, which is
   not reliable as there are many cases where stdout might not be a
   TTY that are not Jupyter.

psynet.utils.psynet_source_prefixes()

   Return path prefixes for PsyNet's own source files.

   "warn_from_caller()" uses these so a warning issued behind PsyNet
   wrappers refers to the first caller outside this package. Uses the
   "psynet" package directory, not the repository root, so demos and
   tests still count as caller code.

   Returns:
      A one-element tuple suitable for "warnings.warn".

   Return type:
      tuple of str

psynet.utils.require_exp_directory(f)

   Decorator to verify that a command is run inside a valid PsyNet
   experiment directory.

psynet.utils.require_requirements_txt(f)

   Decorator to verify that a command is run inside a directory which
   contains a requirements.txt file.

psynet.utils.safe(func)

   Decorator to catch exceptions, log them, and continue execution.

   Parameters:
      **func** (*Callable*) -- The function to wrap.

   Returns:
      The wrapped function.

   Return type:
      callable

psynet.utils.serialise(obj)

   Serialise objects not serialisable by default

psynet.utils.serialise_datetime(x)

   Return a datetime as an ISO 8601 string, or "None" for "None".

psynet.utils.sha256_directory(directory)

   Return a SHA-256 hex digest of a directory's names and file
   contents.

   Return type:
      "str"

psynet.utils.sha256_file(filename)

   Return a SHA-256 hex digest of a file's contents.

   Return type:
      "str"

psynet.utils.sha256_object(x)

   Return a SHA-256 hex digest of a JSON-pickled object.

psynet.utils.shuffle_with_max_run(items, key, max_run, max_attempts=100)

   Return a shuffled copy of "items" with at most "max_run"
   consecutive items sharing a key.

   Useful for planned trial orders, for example "node_order=lambda
   nodes: shuffle_with_max_run(nodes, key=lambda n:
   n.definition["condition"], max_run=2)". "key" must return a
   hashable value. The order is built item by item, choosing at random
   among the keys allowed next, weighted by how many items each has
   left. Raises "ValueError" if no order is found within
   "max_attempts" attempts, which in practice means none exists.

psynet.utils.suppress_stdout()

   Context manager to suppress stdout within its context. Useful for
   silencing noisy third-party library output.

psynet.utils.time_logger(label, threshold=0.1)

   Log the time taken by the enclosed block if it exceeds "threshold"
   seconds.

   The line is at INFO if the block took at least a second, otherwise
   at DEBUG.

psynet.utils.wait_until(condition, max_wait, poll_interval=0.5, error_message=None, *args, **kwargs)

   Poll "condition" until it returns a truthy value.

   Parameters:
      * **condition** (*callable*) -- Called as "condition(*args,
        **kwargs)".

      * **max_wait** (*float*) -- Maximum time to wait, in seconds.

      * **poll_interval** (*float*) -- Time between checks, in
        seconds.

      * **error_message** (*str**, **optional*) -- Message for the
        error raised on timeout.

   Returns:
      "True" once the condition is satisfied.

   Return type:
      bool

   Raises:
      **RuntimeError** -- If the condition is not satisfied within
      "max_wait" seconds.

psynet.utils.warn_from_caller(message, category)

   Issue a warning located at the first caller outside PsyNet.

   Works on every supported Python version, unlike
   "warnings.warn(skip_file_prefixes=...)", which needs Python 3.12.

   Parameters:
      * **message** (*str*) -- The warning text.

      * **category** (*Warning subclass*) -- The warning class, such
        as "DeprecationWarning".
