Managing assets
***************

An "Asset" is a file or folder that PsyNet keeps track of during an
experiment: a stimulus attached to a module or node, a file generated
by code, or a participant recording. PsyNet uploads assets to storage,
serves them to participants, records them in the database, and exports
the ones created during the experiment.

Assets are stored on the web server that runs the experiment by
default. To store them in Amazon S3 instead, set "asset_storage" on
the experiment class to an "S3Storage":

   import psynet.experiment
   from psynet.asset import S3Storage

   class Exp(psynet.experiment.Experiment):
       asset_storage = S3Storage("my-bucket", "my-experiment")

Warning:

  Deploying thousands of assets can be slow. For large sets of ready-
  made files, see Hosting stimuli on S3.


Creating an asset
=================

"asset()" creates an asset from its source:

   from psynet.asset import asset

   asset("logo.svg")                         # a file or folder
   asset("https://example.com/logo.svg")     # a URL, not uploaded
   asset(make_logo, extension=".svg")        # a function that writes the file
   asset(make_logo, extension=".svg", on_demand=True)  # regenerated on each request

Paths are relative to the experiment directory, or absolute.

Note:

  If you keep asset source files in your experiment directory, put
  them in "data/", which the stock "deploy.toml" leaves out of the
  deployment package. Otherwise they are uploaded twice: once in the
  package and once as assets.

PsyNet uploads an asset only once it is linked to the experiment:
through a module or node in the timeline, as described below, or by
depositing it with a parent while the experiment runs.


Linking assets to modules
-------------------------

Link assets that do not belong to particular trials, such as
calibration sounds, to a "Module" with its "assets" argument, a
dictionary. Pages inside the module read them in a "PageMaker" whose
function takes an "assets" argument. From "demos/features/assets":

   headphone_assets = {
       "stimulus_1": asset(
           "https://s3.amazonaws.com/headphone-check/antiphase_HC_ISO.wav"
       ),
       "stimulus_2": asset(
           "https://s3.amazonaws.com/headphone-check/antiphase_HC_IOS.wav"
       ),
       "stimulus_3": asset(
           "https://s3.amazonaws.com/headphone-check/antiphase_HC_SOI.wav"
       ),
   }


   Module(
       "headphone_check",
       [
           PageMaker(
               lambda assets, i=i: ModularPage(
                   f"headphone_check_{i}",
                   AudioPrompt(
                       assets[f"stimulus_{i}"],
                       text=f"This is headphone check stimulus number {i}.",
                   ),
               ),
               time_estimate=5,
           )
           for i in range(1, 4)
       ],
       assets=headphone_assets,
   ),


Linking assets to nodes
-----------------------

Link assets that belong to particular trials to the nodes, again with
an "assets" dictionary. In "demos/experiments/static_audio", each node
has a stimulus synthesized on demand from its definition:

   def synth_stimulus(path, frequencies):
       synth_prosody(vector=frequencies, output_path=path)


   nodes = [
       StaticNode(
           definition={
               "frequency_gradient": frequency_gradient,
               "start_frequency": start_frequency,
               "frequencies": [start_frequency + i * frequency_gradient for i in range(5)],
           },
           assets={
               "stimulus": asset(
                   synth_stimulus,
                   extension=".wav",
                   on_demand=True,
               )
           },
       )
       for frequency_gradient in [-100, 0, 100]
       for start_frequency in [-100, 0, 100]
   ]



A trial starts with its node's assets, so "show_trial" reads the
stimulus as "self.assets["stimulus"]".


Assets from participant responses
---------------------------------

"AudioRecordControl" and "VideoRecordControl" store each recording as
an asset of the trial, keyed by the page label. In
"demos/experiments/static_audio", the recording page is labeled
""imitation"", so the feedback page plays the recording back from
"self.assets["imitation"]":

       def show_feedback(self, experiment, participant):
           return ModularPage(
               "feedback",
               AudioPrompt(
                   self.assets["imitation"],
                   "Listen back to your recording. Did you do a good job?",
               ),
               time_estimate=self._time_feedback,
           )

To store other files during the experiment, create the asset with a
"parent" and "local_key", and call "deposit()".
"demos/features/assets" saves a participant's text answer this way:

   def save_text(participant):
       text = participant.answer
       with tempfile.NamedTemporaryFile("w") as file:
           file.write(text)
           file.flush()
           _asset = asset(
               file.name,
               local_key="text_input",
               extension=".txt",
               description="Some text that the participant filled out",
               parent=participant,
           )
           _asset.deposit()

Custom controls that record media can follow the same pattern in
"Control.format_answer"; the recording controls' source shows how.


Assets for new chain nodes
--------------------------

In chain experiments such as imitation chains, a new node may need a
new file. Override the node's "async_on_deploy" method, which runs in
the background after the node is created, and deposit the asset with
the node as its parent. From "MediaImitationChainNode":

       def async_on_deploy(self):
           logger.info("Synthesizing media for node %i...", self.id)

           with tempfile.NamedTemporaryFile() as temp_file:
               from ..asset import FileAsset

               self.synthesize_target(temp_file.name)
               asset = FileAsset(
                   local_key="stimulus",
                   input_path=temp_file.name,
                   extension=self.media_extension,
                   parent=self,
               )
               asset.deposit()


Assets for new trials
---------------------

When "finalize_definition()" adds random variation to a trial, it can
also add an asset generated from the new definition with
"self.add_assets". In "demos/experiments/static_audio_2", each trial
draws a random start frequency and synthesizes its stimulus on demand:

       def finalize_definition(self, definition, experiment, participant):
           definition["start_frequency"] = random.uniform(-100, 100)
           definition["frequencies"] = [
               definition["start_frequency"] + i * definition["frequency_gradient"]
               for i in range(5)
           ]
           self.add_assets(
               {
                   "stimulus": OnDemandAsset(
                       function=synth_stimulus,
                       extension=".wav",
                   )
               }
           )
           return definition


Accessing assets
================

Participants, modules, nodes and trials each have an "assets"
dictionary:

   participant.assets
   module.assets
   node.assets
   trial.assets

The key describes the asset's role for that object, for example
"trial.assets["stimulus"]". The same asset can have different keys on
different objects: a recording can be the response for one trial and
the stimulus for another.


Exporting assets
================

"psynet export" includes assets created while the experiment was
running, such as recordings, but not assets prepared before launch;
see Which assets are included.


Notes for advanced users
========================


Types of assets
---------------

"asset()" returns one of these classes:

* "FileAsset", made from an existing file or folder, such as a
  stimulus file, a recording or an analysis plot.

* "GeneratedAsset", made by running a function that writes the file,
  so stimulus generation code can live in the experiment.

* "OnDemandAsset", like a generated asset but never stored: the file
  is generated each time it is requested. Use it for files that are
  quick to generate.

* "ExternalAsset", a file hosted elsewhere and referenced by URL.
  "ExternalS3Asset" is an external asset in an S3 bucket.

Whether an asset is exported follows from when it was deposited, not
from where it is declared. File and generated assets deposited while
the experiment is running are exported, including assets of a module
built inside a page maker. Assets prepared before launch are not:
files come from the experiment directory, and generated assets are
recreated at every launch. On-demand and external assets are never
exported.

"Before launch" means while PsyNet prepares the deployment, which
covers the timeline's assets and the start nodes of across-participant
chains. Assets deposited later count as created during the experiment
and are exported, even if they come from the experiment directory: for
example, assets deposited in an "on_launch" hook, or the start nodes
of within-participant chains, which are created for each participant.


Storage and URLs
----------------

Managed assets are stored by SHA-256 content hash under
"objects/sha256/<digest>", so bytes that are already stored are not
uploaded again. With local storage, and for on-demand assets, the
browser fetches assets from "/asset/<access_token>", where the token
is random rather than derived from the content. If a local asset is
deposited again with different contents, its token changes and the old
URL stops working. S3-backed assets use a direct public S3 URL, which
changes when the contents change. External assets keep their original
URL.

Files served from "/asset/<access_token>" carry "Content-Security-
Policy: sandbox", so a participant's upload can't run as a page on the
experiment's site; PDF, audio and video files are exempt so browsers
can display them. HTML, XHTML, SVG, XML, XSL and JavaScript files are
sent as downloads. SVGs still work as "img" sources and JavaScript
files as "script" sources, but a page that must open in the browser
belongs in "static/".

Note:

  Earlier PsyNet versions called file assets "ExperimentAsset" or
  "CachedAsset", called generated assets "CachedFunctionAsset", and
  accepted "asset(..., cache=True)". The old names still work but are
  deprecated, and "cache" has no effect.
