### Run C++ Example Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md Executes the compiled C++ example application. This command assumes the build process was successful and the executable is in the expected location. ```bash build\Debug\main.exe ``` -------------------------------- ### Build C++ Example with CMake Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md Commands to configure and build a C++ example project using CMake. It removes the old build directory, sets up the build with CMake, and then compiles the project in Debug mode. ```bash rmdir /s /q build cmake -S . -B build -DJTRACE=0 cmake --build ./build --config Debug -j12 ``` -------------------------------- ### CMakeLists.txt for C++ Example Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md The CMake configuration file for the C++ example project. It specifies the C++ standard, links the AYON C++ API library, and defines the executable. ```cmake cmake_minimum_required(VERSION 3.10) project(ayon_example) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_subdirectory(ext/ayon-cpp-api) add_executable(main main.cpp) target_link_libraries(main PRIVATE ayon) if (WIN32) set_target_properties(main PROPERTIES) set_property(TARGET main PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif () ``` -------------------------------- ### C++ Example Code Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md A basic C++ program demonstrating the use of the AYON C++ API. It prompts the user for input and shows how to resolve an entity URI. ```cpp #include #include #include int main() { std::string project; std::cout << "Enter a project: "; std::cin >> project; std::string uri; std::cout << "Enter a uri to resolve: "; std::cin >> uri; ayon::API api; std::string resolvedPath = api.resolve(project, uri); std::cout << "The resolved path: " << resolvedPath << std::endl; return 0; } ``` -------------------------------- ### Fetch AYON CPP API and Submodules Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md Clones the AYON C++ API repository and initializes its submodules. This is the first step to getting the necessary code. ```bash git clone https://github.com/ynput/ayon-cpp-api.git cd ayon-cpp-api git submodule update --init --recursive ``` -------------------------------- ### Build AYON CPP Library using AyonBuild.py Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/README.md Commands to update submodules, navigate to the AYON C++ API directory, and execute the AyonBuild.py script to set up and clean the build for the library. ```bash git submodule update --init --recursive cd ext\ayon-cpp-api python AyonBuild.py --setup python AyonBuild.py --runStageGRP CleanBuild ``` -------------------------------- ### CMake Project Setup and Dependencies Source: https://github.com/mustafajafar/ayon-recipes/blob/main/test_cpp_api/CMakelists.txt Configures the CMake build system for the project. It sets the C++ standard to 17, defines the project name, includes the AyonCppApi subdirectory, and adds include directories for AyonCppApi and dotenv-cpp. It also defines the main executable and links it with AyonCppApi. ```cmake cmake_minimum_required(VERSION "3.28.1") set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) project(main) # Include AyonCppApi add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/ext/ayon-cpp-api") include_directories("${CMAKE_CURRENT_SOURCE_DIR}/ext/ayon-cpp-api") include_directories("${CMAKE_CURRENT_SOURCE_DIR}/ext/ayon-cpp-api/ext/ayon-cpp-dev-tools/src/") include_directories("${CMAKE_CURRENT_SOURCE_DIR}/ext/dotenv-cpp/include/laserpants/dotenv") add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} AyonCppApi) ``` -------------------------------- ### Get Products by Type in Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves products of a specified type published to a particular folder path. It first fetches the folder entity by its path and then uses `get_products` to filter products by their type. The output is a list of product names matching the criteria. ```python import ayon_api from ayon_core.pipeline import registered_host host = registered_host() current_context = host.get_current_context() project_name = "Robo" or current_context["project_name"] folder_path = "/Assets/Character/bigrobo" or current_context["folder_path"] my_product_type = "usd" id_only = ["id"] folder_entity = ayon_api.get_folder_by_path(project_name, folder_path, fields=id_only) my_folder_id = folder_entity["id"] my_usd_products = ayon_api.get_products( project_name, folder_ids=[my_folder_id], product_types=[my_product_type] ) print([product["name"] for product in my_usd_products]) ``` -------------------------------- ### Get Product Information from AYON in Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves product information, including versions and representations, for a specific folder path within a project. It utilizes `get_current_context` to obtain project and folder details, then queries for products, their last versions, and associated representations. ```python import ayon_api from ayon_core.pipeline import get_current_context product_name = "pointcacheBgeoCache" # Get Current Context context = get_current_context() project_name = context["project_name"] folder_path = context["folder_path"] folder_entity = ayon_api.get_folder_by_path(project_name, folder_path) product_entities = ayon_api.get_products( project_name, folder_ids={folder_entity["id"]}, product_name_regex=product_name, fields={"id", "name", "productType"} ) for product_entity in product_entities: print("product_entity: ", product_entity) version_entity = ayon_api.get_last_version_by_product_name( project_name, product_name, folder_entity["id"] ) representations = ayon_api.get_representations( project_name, version_ids={version_entity["id"]}, fields={"id", "name", "files.path"} ) for representation in representations: print("representation:", representation) ``` -------------------------------- ### Get AYON Bundle Settings and Addons Info (Python) Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves bundle settings and addon information from the current AYON session. It requires the 'ayon_api' library and checks for an active connection. Outputs specific bundle settings and a list of all addon information. ```python import ayon_api import os if ayon_api.is_connection_created(): con = ayon_api.get_server_api_connection() # Bundle Settings bundle_name = os.getenv("AYON_BUNDLE_NAME") bundle_settings = con.get_addons_settings(bundle_name) print(bundle_settings["houdini"]["publish"]["CollectFilesForCleaningUp"]) # Addons Info (name, title, version, ...) print(con.get_addons_info()) ``` -------------------------------- ### Get AYON Workfile Information (Python) Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves workfile information from AYON. This snippet demonstrates the use of the 'get_workfiles_info' function from the 'ayon_api' library. It requires the project name as input. ```python from ayon_api import get_workfiles_info from ayon_api.operations import OperationsSession project_name = "Animal_Logic_ALab" # Example usage (assuming OperationsSession is initialized elsewhere or not strictly needed for just getting info) # workfiles = get_workfiles_info(project_name=project_name) # print(workfiles) ``` -------------------------------- ### Get Version Links using Ayon API Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves links for a specific version of a published workfile, showing both input references and output generative links. It uses `ayon_api.get_version_by_id`, `ayon_api.get_product_by_id`, and `ayon_api.get_version_links`. ```python import ayon_api def get_product_version_names(project_name, version_id): version_data = ayon_api.get_version_by_id(project_name, version_id, {"name", "productId"}) product_data = ayon_api.get_product_by_id(project_name, version_data["productId"], {"name"}) return product_data["name"], version_data["name"] project_name = "Animal_Logic_ALab" workfile_version_id = "5db3e83420fe11f0ac76c9dd368a2ef7" workfile_name, workfile_version = get_product_version_names(project_name, workfile_version_id) print(f"Find links for '{workfile_name} {workfile_version}':") version_links = ayon_api.get_version_links(project_name, workfile_version_id) for link in version_links: product, version = get_product_version_names(project_name, link["entityId"]) print(" -", link["direction"], product, version) # Link directions: # - "out" direction: generative links (new products published from this workfile) # - "in" direction: reference links (products loaded into this workfile) ``` -------------------------------- ### Get Last Versions by Status in Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Retrieves the last version with a given status for products matching a name pattern within a project and folder. It fetches products, then their versions filtered by status, and finally determines the latest version for each product. The result is a dictionary mapping product IDs to their latest approved versions. ```python import ayon_api from ayon_core.pipeline import get_current_context from collections import defaultdict context = get_current_context() project_name = context["project_name"] folder_path = context["folder_path"] product_name_regex = "render*" status_name = "Approved" folder_entity = ayon_api.get_folder_by_path(project_name, folder_path) product_entities = ayon_api.get_products( project_name, folder_ids={folder_entity["id"]}, product_name_regex=product_name_regex, fields={"id", "name", "productType"} ) product_ids = [product["id"] for product in product_entities] versions_by_product_id = defaultdict(list) for entity in ayon_api.get_versions( project_name, product_ids=product_ids, statuses={status_name}, ): product_id = entity["productId"] versions_by_product_id[product_id].append(entity) output = {product_id: None for product_id in product_ids} for product_id, versions in versions_by_product_id.items(): if not versions: continue versions.sort(key=lambda v: v["version"]) output[product_id] = versions[-1] print(output) ``` -------------------------------- ### Resolve USD Entity URIs Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This code snippet illustrates how to resolve AYON entity URIs to file system paths using the USD Asset Resolver. It constructs an AYON entity URI with project, folder, product, version, and representation details, then uses `Ar.GetResolver().Resolve()` to get the absolute file path. It also notes support for special version specifiers like 'HERO' and 'latest'. ```python from pxr import Ar resolver = Ar.GetResolver() project_name = "Experiments" folder_path = "/things/deadline_submissions" product = "pointcacheTestBgeo" version = "latest" # "v008" # "HERO" representation = "bgeo.sc" unresolved_path = f"ayon+entity://{project_name}{folder_path}?product={product}&version={version}&representation={representation}" resolved_path = resolver.Resolve(unresolved_path) print(f"Resolved path: {resolved_path}") # AYON supports special versions: "HERO" and "latest" ``` -------------------------------- ### Delete Workfiles Below Task with Filtering in Ayon Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Deletes workfiles associated with a specific task, applying conditional filtering. It first retrieves workfile information for a given task ID, then iterates through the results. For each workfile, it checks a condition (commented out in the example) before deleting it using the OperationsSession and committing the changes. ```python task_id = "1046af8120e911f0ba9f59f45369a101" workfiles_info = get_workfiles_info(project_name, task_ids=[task_id]) ayon_session = OperationsSession() for workfile_info in workfiles_info: # Add condition to filter which workfiles to delete ayon_session.delete_entity(project_name, "workfile", workfile_info["id"]) ayon_session.commit() ``` -------------------------------- ### Create User API Source: https://github.com/mustafajafar/ayon-recipes/blob/main/create_ayon_demo_users/README.MD Creates a new user on the AYON server. ```APIDOC ## PUT /api/users/username ### Description Creates a new user account on the AYON server. This endpoint is used to register a new user with the provided username. ### Method PUT ### Endpoint /api/users/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The desired username for the new user. #### Request Body - **email** (string) - Required - The email address for the new user. - **first_name** (string) - Optional - The first name of the new user. - **last_name** (string) - Optional - The last name of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "email": "newuser@example.com", "first_name": "New", "last_name": "User", "password": "securepassword123" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the user was created successfully. #### Response Example ```json { "message": "User 'newuser' created successfully." } ``` ``` -------------------------------- ### Publish with Pyblish Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This snippet demonstrates how to publish data using Pyblish within an Ayon context. It initializes a Pyblish context, sets necessary data, and iterates through publish plugins to execute the publishing process. Errors during publishing are logged. ```python pyblish_context = pyblish.api.Context() pyblish_context.data["create_context"] = create_context pyblish_context.data["comment"] = "publish from code" pyblish_plugins = create_context.publish_plugins error_format = "Failed {plugin.__name__}: {error} -- {error.traceback}" for result in pyblish.util.publish_iter(pyblish_context, pyblish_plugins): for record in result["records"]: log.debug("{}: {}".format(result["plugin"].label, record.msg)) if result["error"]: error_message = error_format.format(**result) log.debug(error_message) ``` -------------------------------- ### Publish from Code using Pyblish API Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Triggers the publish workflow programmatically using the Pyblish API. It initializes a `CreateContext` and allows for optional filtering of instances before publishing. ```python import logging import pyblish from ayon_core.pipeline import registered_host from ayon_core.pipeline.create import CreateContext host = registered_host() assert host, "No registered host." logging.basicConfig() log = logging.getLogger("publish-from-code") log.setLevel(logging.DEBUG) create_context = CreateContext(host) # Optional: filter instances based on some condition # for instance in create_context.instances: # if (some condition): # instance["active"] = False # instance["active"] = True ``` -------------------------------- ### Create Project Hierarchy with Folders and Tasks in AYON using Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This Python snippet demonstrates how to create a project hierarchy, including folders, assets, and tasks, using the AYON EntityHub. It checks for existing entities and creates them if they don't exist, ensuring a robust project structure. The `format_label` function helps in creating human-readable labels. ```python import re import ayon_api from ayon_api.entity_hub import EntityHub def format_label(asset_name): label = asset_name.replace("_", " ").title() label = re.sub(r'(\D)(\d+)$', r'\1 \2', label) return label project_name = "my_project" asset_to_create = [f"asset_{i}" for i in range(1, 101)] tasks_to_create = { "modeling": "Modeling", "lookdev": "Lookdev", } # Get or create Parent Folder parent_folder_name = "my_assets" parent_folder = ayon_api.get_folder_by_path(project_name, parent_folder_name, fields={"id"}) if parent_folder is None: ayon_hub = EntityHub(project_name) parent_folder = ayon_hub.add_new_folder( folder_type="Folder", name=parent_folder_name, label=format_label(parent_folder_name), ) ayon_hub.commit_changes() # Get all asset entities asset_entities = ayon_api.get_folders(project_name, folder_types={"Asset"}, fields={"name", "id", "path"}) asset_entities = {f["name"]:'f' for f in asset_entities} for asset_name in asset_to_create: ayon_hub = EntityHub(project_name) if asset_name in asset_entities: asset_entity = asset_entities[asset_name] else: asset_entity = ayon_hub.add_new_folder( folder_type="Asset", name=asset_name, label=format_label(asset_name), parent_id=parent_folder["id"] ) print(asset_name, ":", asset_entity["id"]) # Get or create tasks task_entities = ayon_api.get_tasks(project_name, folder_ids={asset_entity["id"]}, fields={"name", "id"}) task_entities = {t["name"]:'t' for t in task_entities} for task_name, task_type in tasks_to_create.items(): if task_name in task_entities: task_entity = task_entities[task_name] else: task_entity = ayon_hub.add_new_task( task_type=task_type, name=task_name, label=format_label(task_name), parent_id=asset_entity["id"], ) print(" ", task_name, ":", task_entity["id"]) ayon_hub.commit_changes() ``` -------------------------------- ### Create Publish Instance from Code using Ayon API Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Creates AYON publish instances programmatically within a DCC application. It uses `ayon_api` to fetch folder and task entities and `ayon_core.pipeline.create.CreateContext` to manage the creation process. ```python import ayon_api from ayon_core.pipeline import registered_host from ayon_core.pipeline.create import CreateContext host = registered_host() creator_identifier = "io.openpype.creators.houdini.pointcache" current_context = host.get_current_context() task_name = "cfx" or current_context["task_name"] project_name = "Robo" or current_context["project_name"] folder_path = "/Assets/Character/bigrobo" or current_context["folder_path"] variant = "MyExampleVariant" folder_entity = ayon_api.get_folder_by_path(project_name, folder_path, fields={"id"}) create_context = CreateContext(host) create_context.create( creator_identifier, variant=variant, folder_entity=ayon_api.get_folder_by_path(project_name, folder_path), task_entity=ayon_api.get_task_by_name(project_name, folder_entity["id"], task_name), pre_create_data={"use_selection": True} # creator options ) ``` -------------------------------- ### Create AYON Demo Users in Bulk (Python) Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Creates multiple demo users with avatars in bulk using the AYON API. It reads user data from JSON files and uploads avatar images. Requires 'ayon_api', 'os', and 'json' libraries. It sets AYON server URL and API key via environment variables. ```python import os import json import ayon_api AYON_SERVER_URL = "http://localhost:5000" AYON_API_KEY = "veryinsecureapikey" os.environ["AYON_SERVER_URL"] = AYON_SERVER_URL os.environ["AYON_API_KEY"] = AYON_API_KEY ayon = ayon_api.get_server_api_connection() for i in range(100): user_name = f"demouser{i:0>2}" file_name = os.path.join("users", f"{user_name}") if not os.path.isfile(f"{file_name}.json"): continue with open(f"{file_name}.json") as f: user_data = json.load(f) user_data["attrib"].pop("avatarUrl") user_data["data"] = {"defaultAccessGroups": ["artist"]} user_data["password"] = "ayon" ayon.put(f"users/{user_name}", **user_data) print(f"User '{user_name}' is created.") with open(f"{file_name}.jpg", "rb") as f: ayon.raw_put( f"users/{user_name}/avatar", data=f.read(), headers={"Content-Type": "image/jpeg"}, ) print(f"Avatar for '{user_name}' is uploaded.") ``` -------------------------------- ### Upload AYON Addon Package (Python) Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Uploads an addon zip package to the AYON server programmatically. It requires the 'ayon_api' library and sets environment variables for server URL and API key. The function 'upload_addon_zip' handles the upload, and optionally triggers a server restart. ```python import os import logging import ayon_api logging.basicConfig(level=logging.INFO) log = logging.getLogger("upload_package") trigger_restart = True os.environ["AYON_SERVER_URL"] = "http://127.0.0.1:5000/" os.environ["AYON_API_KEY"] = "service-user-key" ayon_api.init_service() addon_path = "C:/ayon-core/package/core-0.3.1-dev.1.zip" log.info("Uploading: '{}'".format(addon_path)) response = ayon_api.upload_addon_zip(addon_path) if trigger_restart: server = ayon_api.get_server_api_connection() if server: server.trigger_server_restart() ``` -------------------------------- ### Resolve Entity URIs with AYON C++ API Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This C++ code snippet demonstrates how to initialize the AyonApi connection using environment variables and resolve an entity URI to a local file path. It requires the 'dotenv' library for loading environment variables and the 'AyonCppApi.h' header. ```cpp // AYON CPP API Test #include #include "dotenv.h" #include "AyonCppApi.h" int main() { dotenv::init(); // loads from ".env" std::string project_name = ""; std::cout << "Enter a project: "; std::cin >> project_name; AyonApi con = AyonApi( std::getenv("LOG_FILE"), // extension will be always changed to json std::getenv("AYON_API_KEY"), // Bearer access token or AYON_API_KEY std::getenv("AYON_SERVER_URL"), // No trailing forward slash project_name, std::getenv("AYON_SITE_ID") // e.g. military-mouse-of-jest ); std::string uri = ""; std::cout << "Enter a uri to resolve: "; std::cin >> uri; std::pair resolvedAsset = con.resolvePath(uri); std::cout << "The resolved path: " << resolvedAsset.second << std::endl; return 0; } // Expected Output: // Enter a project: Animal_Logic_ALab // Enter a uri to resolve: ayon+entity://Animal_Logic_ALab/assets/book_encyclopedia01?product=usdAsset&version=v002&representation=usd // The resolved path: H:\AYON\projects\Animal_Logic_ALab\assets\book_encyclopedia01\publish\usd\usdAsset\v002\ALA_book_encyclopedia01_usdAsset_v002.usd ``` -------------------------------- ### Authenticate and Connect to AYON Server using Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Demonstrates two methods for connecting to an AYON server: using a service account API key or an authentication bearer token. It retrieves user information and closes the connection. Ensure AYON_SERVER_URL and AYON_API_KEY environment variables are set correctly. ```python import os import ayon_api # Method 1: Using a service account API key (easiest way) ayon_url = "http://localhost:5000" ayon_service_api_key = "veryinsecureapikey" os.environ["AYON_SERVER_URL"] = ayon_url os.environ["AYON_API_KEY"] = ayon_service_api_key ayon = ayon_api.get_server_api_connection() user = ayon.get_user() print(f"Logged in as user \"{user['name']}\"") ayon_api.close_connection() # Expected Output: # >>> Logged in as user "service" # Method 2: Using an authentication bearer token ayon_url = "http://localhost:5000" auth_key = ayon_api.login_to_server( url=ayon_url, username="admin", password="ayon" ) os.environ["AYON_SERVER_URL"] = ayon_url os.environ["AYON_API_KEY"] = auth_key ayon = ayon_api.get_server_api_connection() user = ayon.get_user() print(f"Logged in as user \"{user['name']}\")") ayon_api.close_connection() # Expected Output: # >>> Logged in as user "Admin" ``` -------------------------------- ### Set Addon Settings Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This script shows how to modify addon settings for a specific project or the entire studio using the Ayon API. It constructs the appropriate API endpoint, fetches the current settings, modifies them (e.g., disabling 'IntegrateHeroVersion'), and then sends the updated settings back using a POST request. It requires specifying the addon name, version, project name, and optionally a site ID and variant. ```python import ayon_api from ayon_api.utils import prepare_query_string # Specify Addon and project name addon_name = "core" version = "1.6.13+dev" project_name = "Experiments" variant = "AYON-Dev" site_id = None # Prepare endpoint query = prepare_query_string({ "site": site_id, "variant": variant, }) entrypoint = f"addons/{addon_name}/{version}/settings/{project_name}{query}" # Get Settings response = ayon_api.get(entrypoint) settings = response.data # Modify Settings settings["publish"]["IntegrateHeroVersion"] = False # Set Settings (use POST or PUT depending on endpoint - check API docs) response = ayon_api.post( entrypoint, **settings ) print(response.detail) ``` -------------------------------- ### Load Representations from Code using Ayon API Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Loads published assets programmatically by retrieving representation context and invoking loader plugins. It utilizes functions like `ayon_api.get_folder_by_path`, `ayon_api.get_product_by_name`, `ayon_api.get_versions`, `ayon_api.get_version_by_name`, `ayon_api.get_representation_by_name`, `get_representation_context`, `get_loaders_by_name`, and `load_with_repre_context`. ```python import ayon_api from ayon_core.pipeline.load import ( get_loaders_by_name, load_with_repre_context, get_representation_context ) def get_representation(project_name, folder_path, product_name, version, representation_name): folder_entity = ayon_api.get_folder_by_path(project_name, folder_path, fields={"id"}) product_entity = ayon_api.get_product_by_name( project_name, product_name=product_name, folder_id=folder_entity["id"], fields={"id"}, ) if version in {"hero", "latest"}: hero = version == "hero" latest = version == "latest" versions = ayon_api.get_versions( project_name, product_ids={product_entity["id"]}, fields={"id"}, hero=hero, latest=latest ) version_entity = list(versions)[-1] else: version_entity = ayon_api.get_version_by_name( project_name, version, product_id=product_entity["id"], fields={"id"} ) representation_entity = ayon_api.get_representation_by_name( project_name, representation_name, version_id=version_entity["id"], ) return get_representation_context(project_name, representation_entity) def load_representation(loader_name, representation_context, loader_args=None): loader = get_loaders_by_name().get(loader_name) container = load_with_repre_context( loader, representation_context, options=loader_args ) return container project_name = "Experiments" folder_path = "/things/usd_assets" product_name = "usdAsset" version = "latest" # can be a version number or "latest" or "hero" representation_name = "usd" loader_name = "USDReferenceLoader" representation = get_representation(project_name, folder_path, product_name, version, representation_name) container = load_representation(loader_name, representation) print(container) ``` -------------------------------- ### Interact with AYON REST API using httpx (Python) Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Provides a class to interact with the AYON server using direct REST API calls with the 'httpx' library. It handles authentication, project retrieval, bundle listing, addon information fetching, and addon version deletion. Requires 'httpx' and 'os' libraries. ```python import os import httpx class SimpleAyonRestCommands: def __init__(self, ayon_server_url, username, password): self.ayon_server_url = ayon_server_url self.credentials = {"name": username, "password": password} self.headers = {} self.ayon_login() def ayon_login(self): req = f"{self.ayon_server_url}/api/auth/login" response = httpx.post(req, json=self.credentials) self.token = response.json().get("token") self.headers["Authorization"] = f"Bearer {self.token}" def get_projects(self): req = f"{self.ayon_server_url}/api/projects" response = httpx.get(req, headers=self.headers) return response.json().get("projects") def get_bundles(self): req = f"{self.ayon_server_url}/api/bundles" response = httpx.get(req, params={"archived": False}, headers=self.headers) return response.json() def get_addons(self): req = f"{self.ayon_server_url}/api/addons" response = httpx.get(req, headers=self.headers) return response.json() def delete_addon_version(self, addon_name, addon_version): req = f"{self.ayon_server_url}/api/addons/{addon_name}/{addon_version}" response = httpx.delete(req, params={"purge": True}, headers=self.headers) return response.json() def upload_addon_zip_file(self, addon_filepath): chunk_size = 1024 * 1024 req = f"{self.ayon_server_url}/api/addons/install" with open(addon_filepath, "rb") as stream: response = httpx.post( req, data=self._upload_chunks_iter(stream, chunk_size), headers=self.headers ) response.raise_for_status() return response.json() @staticmethod def _upload_chunks_iter(file_stream, chunk_size): while True: chunk = file_stream.read(chunk_size) if not chunk: break yield chunk # Usage my_ayon = SimpleAyonRestCommands("http://192.168.1.4:5000", "admin", "admin") print(my_ayon.get_projects()) print(my_ayon.get_bundles()) ``` -------------------------------- ### Validate with Pyblish Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This code snippet shows how to programmatically run validation plugins using the Pyblish API within Ayon. It sets up logging, initializes a CreateContext, and then uses `pyblish.util.collect` and `pyblish.util.validate_iter` to perform collection and validation steps, logging any errors encountered. ```python import logging import pyblish from ayon_core.pipeline import registered_host from ayon_core.pipeline.create import CreateContext host = registered_host() assert host, "No registered host." logging.basicConfig() log = logging.getLogger("publish-from-code") log.setLevel(logging.DEBUG) create_context = CreateContext(host) pyblish_context = pyblish.api.Context() pyblish_context.data["create_context"] = create_context pyblish_plugins = create_context.publish_plugins # Run collect and validate order of pyblish plugins pyblish_context = pyblish.util.collect(pyblish_context, pyblish_plugins) # Run validations one by one error_format = "Failed {plugin.__name__}: {error} -- {error.traceback}" for result in pyblish.util.validate_iter(pyblish_context, pyblish_plugins): for record in result["records"]: log.debug("{}: {}".format(result["plugin"].label, record.msg)) if result["error"]: error_message = error_format.format(**result) log.debug(error_message) ``` -------------------------------- ### Resolve Paths Using Template Data Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This Python code demonstrates how to resolve work directory templates using Ayon's anatomy system. It retrieves current host, project, folder, and task entities, gathers template data, adds root information, and then uses `StringTemplate.format_template` to construct the work directory path. It also shows an alternative using the `get_workdir` utility function. ```python from ayon_core.lib import StringTemplate from ayon_core.pipeline import Anatomy from ayon_core.pipeline.template_data import get_template_data from ayon_core.pipeline.context_tools import ( get_current_project_entity, get_current_folder_entity, get_current_task_entity, get_current_host_name ) from ayon_core.pipeline.workfile import get_workdir # Get Current host name host_name = get_current_host_name() # Get Entities project_entity = get_current_project_entity() folder_entity = get_current_folder_entity() task_entity = get_current_task_entity() # Get Template Data template_data = get_template_data( project_entity, folder_entity, task_entity, host_name ) # Add Roots to template data anatomy = Anatomy() template_data["root"] = anatomy.roots # Resolve Path work_dir = anatomy.templates["work"]["default"]["directory"] work_dir = StringTemplate.format_template(work_dir, template_data) print(work_dir) # Alternatively, use the built-in function for work directory work_dir = get_workdir( project_entity, folder_entity, task_entity, host_name ) print(work_dir) ``` -------------------------------- ### Link Loaded Versions to Workfile in Ayon Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Creates links between loaded version entities and the current workfile for traceability. This Python script uses Ayon's API to fetch loaded versions and workfile information, then establishes links between them. ```python import os from collections import defaultdict import ayon_api from ayon_api.graphql import GraphQlQuery from ayon_core.pipeline import registered_host from ayon_core.pipeline.context_tools import ( get_current_project_name, get_current_task_entity, ) def get_workfiles_in_task(project_name: str, task_id: str): query = GraphQlQuery("Workfiles") project_name_var = query.add_variable("projectName", "String!", project_name) task_id_var = query.add_variable("taskId", "String!", task_id) project_query = query.add_field("project") project_query.set_filter("name", project_name_var) task_query = project_query.add_field("task") task_query.set_filter("id", task_id_var) workfiles_query = task_query.add_field("workfiles") edges_query = workfiles_query.add_field("edges") node_query = edges_query.add_field("node") node_query.add_field("id") node_query.add_field("name") parsed_data = query.query(ayon_api.get_server_api_connection()) workfiles = {} for node in parsed_data["project"]["task"]["workfiles"]["edges"]: workfiles[node["node"]["name"]] = node["node"]["id"] return workfiles def get_loaded_versions_ids(host): representation_id_to_containers = defaultdict(list) for container in host.get_containers(): representation_id = container["representation"] representation_id_to_containers[representation_id].append(container) representation_entities = list(ayon_api.get_representations( host.get_current_project_name(), representation_ids=set(representation_id_to_containers.keys()), fields={"versionId"} )) return {repre["versionId"] for repre in representation_entities} host = registered_host() current_workfile = host.get_current_workfile() workfile_name = os.path.basename(current_workfile) task_id = get_current_task_entity({"id"})["id"] project_name = get_current_project_name() link_type = "loaded_versions" workfiles = get_workfiles_in_task(project_name, task_id) workfile_id = workfiles[workfile_name] versions_ids = get_loaded_versions_ids(host) for version_id in versions_ids: ayon_api.create_link( project_name, link_type, version_id, "version", workfile_id, "workfile" ) ``` -------------------------------- ### Change Ayon Context Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt This Python script demonstrates how to change the current working context (project, folder, and task) programmatically using the Ayon API. It retrieves the current project name, specifies a target folder path and task name, and then uses `change_current_context` to switch to the new context. ```python import ayon_api from ayon_core.pipeline.context_tools import ( change_current_context, get_current_project_name ) project_name = get_current_project_name() # "Animal_Logic_ALab" folder_path = "/assets/book_encyclopedia01" task_name = "lookdev" folder_entity = ayon_api.get_folder_by_path(project_name, folder_path) task_entity = ayon_api.get_task_by_folder_path(project_name, folder_path, task_name) changed = change_current_context( folder_entity, task_entity ) ``` -------------------------------- ### User Info API Source: https://github.com/mustafajafar/ayon-recipes/blob/main/create_ayon_demo_users/README.MD Retrieves information for a specific user. ```APIDOC ## GET /api/users/{user_name} ### Description Retrieves detailed information about a specific user identified by their username. ### Method GET ### Endpoint /api/users/{user_name} ### Parameters #### Path Parameters - **user_name** (string) - Required - The username of the user whose information is to be retrieved. ### Response #### Success Response (200) - **user_name** (string) - The username of the user. - **email** (string) - The email address of the user. - **first_name** (string) - The first name of the user. - **last_name** (string) - The last name of the user. - **is_active** (boolean) - Indicates if the user account is active. #### Response Example ```json { "user_name": "testuser", "email": "testuser@example.com", "first_name": "Test", "last_name": "User", "is_active": true } ``` ``` -------------------------------- ### Custom Pyblish Collector Plugin with Instance Attributes Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Defines a custom Pyblish instance plugin that adds a boolean attribute 'a_toggle_instance' to publish instances. This allows for instance-specific toggling during the publishing process. ```python import pyblish.api from ayon_core.lib import BoolDef from ayon_core.pipeline import publish class CollectSomeInstanceAttrs(pyblish.api.InstancePlugin, publish.AYONPyblishPluginMixin): """Add an attrdef to publish instances.""" label = "Collect Some Instance Attrs" order = pyblish.api.CollectorOrder hosts = ["traypublisher"] families = ["*"] def process(self, instance): # do something pass @classmethod def get_attribute_defs(cls): return [ BoolDef( "a_toggle_instance", default=True, label="A Toggle per instance" ) ] ``` -------------------------------- ### Custom Pyblish Collector Plugin with Context Attributes Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Defines a custom Pyblish context plugin that adds a boolean attribute 'a_toggle_context' to the publish context. This enables context-wide toggling during the publishing workflow. ```python import pyblish.api from ayon_core.lib import BoolDef from ayon_core.pipeline import publish class CollectSomeContextAttrs(pyblish.api.ContextPlugin, publish.AYONPyblishPluginMixin): """Add an attrdef to publish context.""" label = "Collect Some Context Attrs" order = pyblish.api.CollectorOrder hosts = ["traypublisher"] def process(self, context): # do something pass @classmethod def get_attribute_defs(cls): return [ BoolDef( "a_toggle_context", default=True, label="A Toggle per context" ) ] ``` -------------------------------- ### Delete Project Hierarchy Entities in Python Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Deletes folders, tasks, and products from a project using OperationsSession for batch operations. It first identifies all related entities to be deleted and then iteratively removes them, committing changes after each entity type. This method ensures a clean removal of hierarchical data. ```python from ayon_api.operations import OperationsSession from ayon_api import get_products, get_tasks, get_folders session = OperationsSession() PROJECT_NAME = "" INPUT_IDS = [ "", "", ] folders_to_remove = [ f for f in get_folders( PROJECT_NAME, fields=["id", "parentId", "name", "folderType"], ) if f["id"] in INPUT_IDS or f["parentId"] in INPUT_IDS ] folders_ids_to_remove = [folder["id"] for folder in folders_to_remove] products_to_remove = [ p for p in get_products( PROJECT_NAME, folder_ids=folders_ids_to_remove, fields=["id", "name"] ) ] tasks_to_remove = [ t for t in get_tasks( PROJECT_NAME, folder_ids=folders_ids_to_remove, fields=["id", "name"] ) ] for task in tasks_to_remove: print("Deleted task", task["name"]) session.delete_entity(PROJECT_NAME, "task", task["id"]) session.commit() for product in products_to_remove: print(f"Deleted product {product['name']}") session.delete_entity(PROJECT_NAME, "product", product["id"]) session.commit() for folder in folders_to_remove: print("Deleted folder", folder["name"]) session.delete_entity(PROJECT_NAME, "folder", folder["id"]) session.commit() ``` -------------------------------- ### Upload User Avatar API Source: https://github.com/mustafajafar/ayon-recipes/blob/main/create_ayon_demo_users/README.MD Uploads or updates the avatar for a specific user. ```APIDOC ## PUT /api/users/{user_name}/avatar ### Description Uploads or updates the avatar image for a specific user. ### Method PUT ### Endpoint /api/users/{user_name}/avatar ### Parameters #### Path Parameters - **user_name** (string) - Required - The username of the user whose avatar is to be uploaded or updated. #### Request Body - **avatar_image** (file) - Required - The image file (e.g., PNG, JPG) to be set as the user's avatar. ### Request Example (Sends a multipart/form-data request with the avatar image file) ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the avatar was updated successfully. #### Response Example ```json { "message": "Avatar for user 'testuser' updated successfully." } ``` ``` -------------------------------- ### Delete Workfiles by ID in Ayon Source: https://context7.com/mustafajafar/ayon-recipes/llms.txt Deletes specific workfiles from a project using their IDs. It initializes an OperationsSession, iterates through a list of workfile IDs, and calls the delete_entity method for each. Finally, it commits the session to apply the changes. ```python workfile_ids = [ "a314146869c84160b88c944230a95bd2", "d87033db1a9e496a8a34597d63471a6c", ] session = OperationsSession() for workfile_id in workfile_ids: session.delete_entity(project_name, "workfile", workfile_id) session.commit() ``` -------------------------------- ### User Avatar API Source: https://github.com/mustafajafar/ayon-recipes/blob/main/create_ayon_demo_users/README.MD Retrieves the avatar for a specific user. ```APIDOC ## GET /api/users/{user_name}/avatar ### Description Retrieves the avatar image for a specific user. ### Method GET ### Endpoint /api/users/{user_name}/avatar ### Parameters #### Path Parameters - **user_name** (string) - Required - The username of the user whose avatar is to be retrieved. ### Response #### Success Response (200) - **avatar_image** (binary) - The binary data of the user's avatar image. #### Response Example (Returns binary image data, e.g., PNG, JPG) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.