### Query Documentation Dynamically Source: https://docs.unitary.ai/api-references/detoxify.md To get information not explicitly on this page, make a GET request to the page URL with the `ask` query parameter. An optional `goal` parameter can be included to tailor the response. ```http GET https://docs.unitary.ai/api-references/detoxify.md?ask=&goal= ``` -------------------------------- ### Webhook Receiver Example (Python) Source: https://docs.unitary.ai/api-references/integrating_webhooks.md A simple Python (FastAPI) server example that listens for webhook results and logs jobs where at least one policy category is detected. ```APIDOC ## Webhook Receiver Example (Python) The following Python (FastAPI) server will listen for results and log the jobs that have at least one policy category detected. ```python from fastapi import Request, FastAPI app = FastAPI() @app.post("/results") async def get_body(request: Request): result = await request.json() if result["is_error"] is False: policy_categories = result["result"].get("policy_categories", []) if len(policy_categories) > 0: print("Policy category detected") return "OK" ``` ``` -------------------------------- ### Webhook Validation Example (Python) Source: https://docs.unitary.ai/api-references/integrating_webhooks.md An example demonstrating how to validate incoming webhook payloads using the `X-Hub-Signature-256` header and HMAC-SHA256 algorithm with a secret key. ```APIDOC ## Validating Webhooks (Python) In the following example, the payload is validated according to the secret key that has previously been set up. ```python from fastapi import Header, Request, FastAPI import base64 import hashlib import hmac SECRET_KEY = "test_key" app = FastAPI() def compute_signature(payload: str, secret_key: str) -> str: digest = hmac.new( secret_key.encode(), msg=payload.encode("utf-8"), digestmod=hashlib.sha256 ).digest() signature = base64.b64encode(digest).decode() return signature @app.post("/results") async def get_body(request: Request, x_hub_signature_256: str | None = Header(default=None)): result = await request.body() if compute_signature(result.decode(), SECRET_KEY) == x_hub_signature_256: print("Body validated") # .. do processing else: print("Body not validated") return "OK" ``` ``` -------------------------------- ### Querying Documentation Source: https://docs.unitary.ai/api-references/authentication.md You can query this documentation dynamically by performing an HTTP GET request to the page URL with the `ask` query parameter and an optional `goal` parameter. ```http GET https://docs.unitary.ai/api-references/authentication.md?ask=&goal= ``` -------------------------------- ### Query Documentation with a Question Source: https://docs.unitary.ai/llms.txt Use this GET request to ask a specific question about the documentation. The 'ask' parameter is required for the immediate question, and the optional 'goal' parameter helps tailor the response. ```http GET https://docs.unitary.ai/api-references/policy-classification.md?ask=&goal= ``` -------------------------------- ### Query Documentation with HTTP GET Source: https://docs.unitary.ai/api-references/integrating_webhooks.md Use this method to dynamically query the documentation when information is not explicitly present. Include your question in the 'ask' parameter and an optional broader goal in the 'goal' parameter. ```http GET https://docs.unitary.ai/api-references/integrating_webhooks.md?ask=&goal= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.unitary.ai/get-started Use this endpoint to dynamically query the documentation. Include your question in the 'ask' parameter and an optional broader goal in the 'goal' parameter for tailored responses. ```http GET https://docs.unitary.ai/get-started.md?ask=&goal= ``` -------------------------------- ### Example Successful Response Source: https://docs.unitary.ai/api-references/virtual-moderator-endpoint.md This JSON structure represents a successful moderation decision, indicating automated classification and escalation reasons if applicable. ```json { "classification_job_id": "123e4567-e89b-12d3-a456-426614174", "content_type": "image", "decision_type": "fully_automated", "escalate": true, "escalate_reasons": ["self-harm"], "external_id": "the source file_id specified in the request", "is_error": false, "moderation_job_id": "vmod_01h45ytscbebyvny4gc8cr8ma2" "policy_categories": [ { "name": "SEXUAL", "risk_level": "high" } ] } ``` -------------------------------- ### Query Documentation with HTTP GET Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. ```http GET https://docs.unitary.ai/api-references/items-and-characteristics.md?ask=&goal= ``` -------------------------------- ### Retrieve Policy Classification Results via GET Endpoint (Python) Source: https://docs.unitary.ai/api-references/policy-classification.md This Python script demonstrates how to retrieve policy classification results using the GET endpoint. Replace `{BEARER_TOKEN}` and `{JOB_ID}` with your credentials and job identifier. For large-scale applications, consider using the `callback_url` parameter. ```python import requests BEARER_TOKEN = "{BEARER_TOKEN}" JOB_ID = "{JOB_ID}" url = f"https://dev.api.unitary.ai/v1/classify/image/{JOB_ID}" payload={} headers = { 'Authorization': f'Bearer {BEARER_TOKEN}' } response = requests.request("GET", url, headers=headers, data=payload) print(response) ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.unitary.ai/api-references Perform an HTTP GET request to query the documentation dynamically. Use the `ask` parameter for your question and optionally the `goal` parameter to specify the broader objective. This is useful when the answer is not explicitly present on the page or requires clarification. ```http GET https://docs.unitary.ai/api-references.md?ask=&goal= ``` -------------------------------- ### Authenticate with API Key using Javascript Source: https://docs.unitary.ai/api-references/authentication.md This Javascript example shows how to authenticate with the Unitary API using `node-fetch`. It sends your API key to the authentication endpoint and logs the Bearer token and its expiry to the console. ```javascript const fetch = require('node-fetch'); // Make sure you have 'node-fetch' installed for this to work const url = "https://api.unitary.ai/v1/authenticate"; const API_KEY = ""; const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }; const body = `key=${API_KEY}`; fetch(url, { method: 'POST', headers: headers, body: body }) .then(response => response.json()) .then(json => { const token = json.api_token; const expiry = json.expiry; console.log(token, expiry); }) .catch(error => console.error('error:', error)); ``` -------------------------------- ### Generate Random Data for Thresholding Example Source: https://docs.unitary.ai/api-references/how-to-select-thresholds-for-items-and-characteristics.md Creates a pandas DataFrame with random characteristics and corresponding true labels. This is useful for simulating data to test thresholding algorithms. ```python from typing import Tuple import numpy as np import pandas as pd from sklearn.metrics import f1_score def create_random_data(seed: int = 134617456) -> pd.DataFrame: """ Function to create a DataFrame of randomly generated data with two characteristics and corresponding labels. """ np.random.seed(seed) characteristic_A = np.random.rand(10) characteristic_B = np.random.rand(10) true_label_A = np.random.randint(0, 2, 10) true_label_B = np.random.randint(0, 2, 10) df = pd.DataFrame( { "Characteristic A": characteristic_A, "True Label A": true_label_A, "Characteristic B": characteristic_B, "True Label B": true_label_B, } ) return df ``` -------------------------------- ### Webhook Request Payloads Source: https://docs.unitary.ai/api-references/integrating_webhooks.md Examples of success and error JSON payloads that can be received via webhooks. ```APIDOC ## Webhook request payloads {% tabs %} {% tab title="Success" %} ```json { "data": { "job_id": "{JOB_ID}", "callback_url": "{CALLBACK_URL}", "is_error": false, "result": { "policy_categories": [ { "name": "ARMS_AMMO", "description": "Arms & Ammunition", "risk_level": "HIGH" }, { "name": "DEATH_INJURY_MILITARY", "description": "Death, Injury or Military Conflict", "risk_level": "MEDIUM" } ], "metadata": { "width": 720, "height": 480, "fps": 30, "duration": 11.6, "seconds_processed": 11 }, "url": "{RESOURCE_URL}" } } } ``` {% endtab %} {% tab title="Error" %} ```json { "data": { "job_id": "{JOB_ID}", "callback_url": "{CALLBACK_URL}", "is_error": true, "result": { "error": "Failed to decode video." } } } ``` {% endtab %} {% endtabs %} ``` -------------------------------- ### Retrieve Policy Classification Results via GET Endpoint (Javascript) Source: https://docs.unitary.ai/api-references/policy-classification.md This Javascript code snippet shows how to fetch policy classification results using the GET endpoint with `node-fetch`. Remember to substitute `{BEARER_TOKEN}` and `{JOB_ID}`. For large-scale processing, the `callback_url` parameter is recommended. ```javascript const fetch = require("node-fetch"); const BEARER_TOKEN = "{BEARER_TOKEN}"; const JOB_ID = "{JOB_ID}"; const url = `https://dev.api.unitary.ai/v1/classify/image/${JOB_ID}`; fetch(url, { method: "GET", headers: { 'Authorization': `Bearer ${BEARER_TOKEN}`, }, }) .then(response => response.json()) .then(data => { const results = data["results"]; console.log(results); }) .catch((error) => { console.error('Error:', error); }); ``` -------------------------------- ### Get Item Characteristics Classification (Python) Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Python script demonstrates how to fetch item and characteristic classification results from the API. It checks for the presence of firearms based on a confidence threshold. ```python import requests BEARER_TOKEN = "{BEARER_TOKEN}" JOB_ID = "{JOB_ID}" url = f"https://api.unitary.ai/v1/classify/items-characteristics/image/{JOB_ID}" payload={} headers = { 'Authorization': f'Bearer {BEARER_TOKEN}' } response = requests.request("GET", url, headers=headers, data=payload) results = response["results"] violence = results["violence"] has_firearms = violence["firearm"] > 0.8 print(has_firearms) ``` -------------------------------- ### Example Generic Error Response Source: https://docs.unitary.ai/api-references/virtual-moderator-endpoint.md This JSON structure is returned for generic errors after API retries have been exhausted, such as issues with the human moderation platform. ```json { "classification_job_id": "123e4567-e89b-12d3-a456-426614174", "error_message": "the error message for the request", "external_id": "the source file_id specified in the request", "moderation_job_id": "vmod_01h45ytscbebyvny4gc8cr8ma2" } ``` -------------------------------- ### Get Video Classification Results Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Retrieves the results of a video classification job using its unique job ID. ```APIDOC ## GET /classify/items-characteristics/video/{job_id} ### Description Retrieves the results of a video classification job. ### Method GET ### Endpoint /classify/items-characteristics/video/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The unique identifier for the classification job. ``` -------------------------------- ### GET /detoxify/text/{job_id} Source: https://docs.unitary.ai/api-references/detoxify.md This endpoint retrieves the analysis results for a previously submitted text processing job. It requires the job ID generated by the POST request. ```APIDOC ## GET /detoxify/text/{job_id} ### Description This endpoint retrieves the results of a text toxicity analysis job. After submitting text via the POST endpoint, a `job_id` is returned. This ID can be used with this GET endpoint to fetch the detailed toxicity scores and detected language. ### Method GET ### Endpoint /detoxify/text/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The unique identifier for the text analysis job. ### Response #### Success Response (200) - **toxicity** (number) - The predicted toxicity score for the input text. - **severe_toxicity** (number) - The predicted severe toxicity score. - **obscene** (number) - The predicted obscenity score. - **threat** (number) - The predicted threat score. - **insult** (number) - The predicted insult score. - **identity_attack** (number) - The predicted identity attack score. - **sexual_explicit** (number) - The predicted sexual explicit score. - **language** (string) - The detected language of the input text. #### Response Example ```json { "toxicity": 0.98, "severe_toxicity": 0.75, "obscene": 0.82, "threat": 0.1, "insult": 0.9, "identity_attack": 0.5, "sexual_explicit": 0.2, "language": "en" } ``` ``` -------------------------------- ### Retrieve Policy Classification Results via GET Endpoint (cURL) Source: https://docs.unitary.ai/api-references/policy-classification.md Use this cURL command to fetch policy classification results for a given job ID. Ensure you replace `{JOB_ID}` and `{BEARER_TOKEN}` with your actual values. Note that this method may be inadequate for large-scale use; consider using `callback_url` instead. ```bash curl --location --request GET "https://api.unitary.ai/v1/classify/image/{JOB_ID}" \ --header "Authorization: Bearer {BEARER_TOKEN}" ``` -------------------------------- ### Get Video Policy Classification Results Source: https://docs.unitary.ai/api-references/policy-classification.md Retrieve the policy classification results for a video job using its job ID. Note: For large-scale operations, consider using the `callback_url` parameter instead. ```APIDOC ## GET /classify/policy/video/{job_id} ### Description Retrieves the policy classification results for a given video job ID. ### Method GET ### Endpoint /classify/policy/video/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The unique identifier for the video classification job. ### Response #### Success Response (200) - **status** (string) - The status of the job (e.g., "done", "queued", "failed"). - **results** (object) - Contains the classification results if the job is done. - **policy_categories** (array) - A list of identified policy categories. - **name** (string) - The name of the policy category. - **description** (string) - A description of the policy category. - **score** (number) - The confidence score for the category. - **url** (string) - The URL of the processed resource. #### Response Example (Status: successful) ```json { "status": "done", "results": { "policy_categories": [ { "name": "{CATEGORY_NAME}", "description": "{CATEGORY_DESCRIPTION}", "score": 0.99 } ], "url": "{RESOURCE_URL}" } } ``` #### Response Example (Status: queued) ```json { "status": "queued" } ``` #### Response Example (Status: error) ```json { "status": "failed", "msg": "the error message for the request" } ``` ``` -------------------------------- ### Get Image Policy Classification Results Source: https://docs.unitary.ai/api-references/policy-classification.md Retrieve the policy classification results for an image job using its job ID. Note: For large-scale operations, consider using the `callback_url` parameter instead. ```APIDOC ## GET /classify/policy/image/{job_id} ### Description Retrieves the policy classification results for a given image job ID. ### Method GET ### Endpoint /classify/policy/image/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The unique identifier for the image classification job. #### Request Example ```bash curl --location --request GET "https://api.unitary.ai/v1/classify/image/{JOB_ID}" \ --header "Authorization: Bearer {BEARER_TOKEN}" ``` ### Response #### Success Response (200) - **status** (string) - The status of the job (e.g., "done", "queued", "failed"). - **results** (object) - Contains the classification results if the job is done. - **policy_categories** (array) - A list of identified policy categories. - **name** (string) - The name of the policy category. - **description** (string) - A description of the policy category. - **score** (number) - The confidence score for the category. - **url** (string) - The URL of the processed resource. #### Response Example (Status: successful) ```json { "status": "done", "results": { "policy_categories": [ { "name": "{CATEGORY_NAME}", "description": "{CATEGORY_DESCRIPTION}", "score": 0.99 } ], "url": "{RESOURCE_URL}" } } ``` #### Response Example (Status: queued) ```json { "status": "queued" } ``` #### Response Example (Status: error) ```json { "status": "failed", "msg": "the error message for the request" } ``` ``` -------------------------------- ### Get Item Characteristics Classification (cURL) Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Use this cURL command to request the classification of items and characteristics for a given job ID. Ensure you replace placeholders with your actual Bearer Token and Job ID. ```bash curl --location --request GET "https://api.unitary.ai/v1/classify/items-characteristics/image/{JOB_ID}" \ --header "Authorization: Bearer {BEARER_TOKEN}" ``` -------------------------------- ### Get Item Characteristics Classification (Javascript) Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Javascript code snippet shows how to make a GET request to the API to retrieve item and characteristic classification data. It then checks if firearms are detected with a confidence score above 0.8. ```javascript const fetch = require("node-fetch"); const BEARER_TOKEN = "{BEARER_TOKEN}"; const JOB_ID = "{JOB_ID}"; const url = `https://api.unitary.ai/v1/classify/items-characteristics/image/${JOB_ID}`; fetch(url, { method: "GET", headers: { 'Authorization': `Bearer ${BEARER_TOKEN}`, }, }) .then(response => response.json()) .then(data => { const results = data["results"]; const violence = results["violence"]; const has_firearms = violence["firearm"] > 0.8; console.log(has_firearms); }) .catch((error) => { console.error('Error:', error); }); ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.unitary.ai/api-references/how-to-select-thresholds-for-items-and-characteristics.md Use this method to ask questions about the documentation when the answer is not explicitly present. The 'goal' parameter helps tailor the response to your broader objective. ```http GET https://docs.unitary.ai/api-references/how-to-select-thresholds-for-items-and-characteristics.md?ask=&goal= ``` -------------------------------- ### Get Image Classification Results Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Retrieves the results of an image classification job using its unique job ID. ```APIDOC ## GET /classify/items-characteristics/image/{job_id} ### Description Retrieves the results of an image classification job. ### Method GET ### Endpoint /classify/items-characteristics/image/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The unique identifier for the classification job. ``` -------------------------------- ### Optimize Thresholds for Multiple Characteristics Source: https://docs.unitary.ai/api-references/how-to-select-thresholds-for-items-and-characteristics.md Demonstrates how to use the `create_random_data` and `find_best_threshold` functions to find optimal thresholds for multiple characteristics in a dataset and prints the results. ```python if __name__ == "__main__": # Generate some example data data = create_random_data() # Specify a range of thresholds to test thresholds = np.arange(start=0.01, stop=1.01, step=0.01) # For each characteristic, find the best threshold threshold_results = {} threshold_results["Characteristic A"] = find_best_threshold( data, thresholds, characteristic="Characteristic A", true_label="True Label A" ) threshold_results["Characteristic B"] = find_best_threshold( data, thresholds, characteristic="Characteristic B", true_label="True Label B" ) # Print out the best threshold and corresponding F1 score for each characteristic for characteristic, (threshold, f1) in threshold_results.items(): print( f"Best threshold for {characteristic}: {threshold}, Best F1 score: {f1:.2f}" ) ``` -------------------------------- ### Query Documentation API Source: https://docs.unitary.ai/get-started/readme.md Use this mechanism to query the documentation dynamically when information is not explicitly present on the page. The 'ask' parameter is for the immediate question, and 'goal' is optional for tailoring the answer. ```http GET https://docs.unitary.ai/get-started/readme.md?ask=&goal= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.unitary.ai/api-references/items-and-characteristics/list-of-i-and-c-classes.md Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. ```http GET https://docs.unitary.ai/api-references/items-and-characteristics/list-of-i-and-c-classes.md?ask=&goal= ``` -------------------------------- ### Simple Webhook Receiver (Python) Source: https://docs.unitary.ai/api-references/integrating_webhooks.md A basic FastAPI server to listen for webhook POST requests and log detected policy categories from successful job results. Ensure your callback URL is correctly configured. ```python from fastapi import Request, FastAPI app = FastAPI() @app.post("/results") async def get_body(request: Request): result = await request.json() if result["is_error"] is False: policy_categories = result["result"].get("policy_categories", []) if len(policy_categories) > 0: print("Policy category detected") return "OK" ``` -------------------------------- ### Authenticate with API Key using Python Source: https://docs.unitary.ai/api-references/authentication.md This Python script demonstrates how to authenticate with the Unitary API using the `requests` library. It sends your API key to the authentication endpoint and prints the obtained Bearer token and its expiry. ```python import requests url = "https://api.unitary.ai/v1/authenticate" API_KEY = "" payload = f"key={API_KEY}" headers = { 'Content-Type': 'application/x-www-form-urlencoded' } response = requests.request("POST", url, headers=headers, data=payload) token = response.text["api_token"] expiry = response.text["expiry"] print(token, expiry) ``` -------------------------------- ### Authenticate with API Key using cURL Source: https://docs.unitary.ai/api-references/authentication.md Use this cURL command to send your API key to the authentication endpoint and receive a Bearer token. Ensure you replace `{API_KEY}` with your actual API key. ```bash curl --location --request POST 'https://api.unitary.ai/v1/authenticate' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'key={API_KEY}' ``` -------------------------------- ### Send Image for Policy Classification (Python) Source: https://docs.unitary.ai/api-references/policy-classification.md This Python script sends an image for policy classification using the Unitary AI API. It demonstrates how to set up the request with an API token, caption, and resource URL. Replace placeholders with your actual values. ```python import requests api_token = "your_api_token_here" file_path = "/path/to/your/file.jpg" caption = "your_caption_here" url = "https://api.unitary.ai/v1/classify/policy/image" # For sending a URL data = { 'caption': caption, 'url': 'your_resource_url_here' } headers = {'Authorization': f'Bearer {api_token}'} response = requests.post(url, data=data, headers=headers) job_id = resonse.text["job_id"] print(job_id) ``` -------------------------------- ### Custom Payload Data via Query Parameters Source: https://docs.unitary.ai/api-references/integrating_webhooks.md Demonstrates how to append custom data, such as filename or timestamp, to the `callback_url` using query parameters. ```APIDOC ## Custom payload data The `callback_url` is used as is, so you can append custom data to the request by controlling the query parameters. For example, you can send back the original file name or the time of the original request. ```json // with filename "callback_url": "your.callback.server/?filename=original_file_name.mp4" // with timestamp "callback_url": "your.callback.server/?current_timestamp=1687864622" // with filename and timestamp "callback_url": "your.callback.server/?current_timestamp=1687864622&filename=original_file_name.mp4" ``` The additional data will also be part of the payload body. ``` -------------------------------- ### Python: Upload Image File Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Python script uses the `requests` library to send an image file for classification. It includes placeholders for your API token, file path, and caption. The response contains the job ID. ```python import requests api_token = "your_api_token_here" file_path = "/path/to/your/file.jpg" caption = "your_caption_here" url = "https://api.unitary.ai/v1/classify/items-characteristics/image" # For sending a file files = {'file': (file_path, open(file_path, 'rb'), 'image/jpeg')} data = {'caption': caption} headers = {'Authorization': f'Bearer {api_token}'} response = requests.post(url, files=files, data=data, headers=headers) job_id = resonse.text["job_id"] print(job_id) ``` -------------------------------- ### Get Item and Characteristics Classification Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This endpoint retrieves the classification results for a given job ID. It requires an authorization header and the job ID as a path parameter. The response includes a status and detailed results if the job is completed. ```APIDOC ## GET /v1/classify/items-characteristics/image/{JOB_ID} ### Description Retrieves the classification results for a specific job ID, providing detailed insights into the items and characteristics detected in an image. ### Method GET ### Endpoint /v1/classify/items-characteristics/image/{JOB_ID} ### Parameters #### Path Parameters - **JOB_ID** (string) - Required - The unique identifier for the classification job. #### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., Bearer {BEARER_TOKEN}). ### Request Example ```bash curl --location --request GET "https://api.unitary.ai/v1/classify/items-characteristics/image/{JOB_ID}" \ --header "Authorization: Bearer {BEARER_TOKEN}" ``` ### Response #### Success Response (200) - **status** (string) - The status of the job (e.g., "done", "queued", "failed"). - **results** (object) - Contains detailed classification results when status is "done". - **violence** (object) - Classification scores related to violence. - **substances** (object) - Classification scores related to various substances. - **nsfw** (object) - Classification scores for Not Safe For Work content. - **hate_symbols** (object) - Classification scores for hate symbols. - **caption_language_toxicity** (object) - Toxicity scores for caption language. - **visual_content** (object) - Classification scores for visual content types. - **other** (object) - Classification scores for other miscellaneous categories. - **url** (string) - The URL of the processed resource. - **msg** (string | null) - An error message if the status is "failed". #### Response Example (Status: successful) ```json { "status": "done", "results": { "violence": { "violence": 0.006823897361755371, "firearm": 0.06859919428825378, "knife": 0.03536936640739441, "violent_knife": 0.03841346502304077 }, "substances": { "alcohol": 0.09190595149993896, "drink": 0.11272519826889038, "smoking_and_tobacco": 0.1175956130027771, "marijuana": 0.10564917325973511, "pills": 0.1289033591747284, "recreational_pills": 0.12389451265335083 }, "nsfw": { "adult_content": 0.7132323980331421, "suggestive": 0.9982926249504089, "adult_toys": 2.8699636459350586e-05, "medical": 0.9637787342071533, "over_18": 0.8957071900367737, "exposed_anus": 0.0003555417060852051, "exposed_armpits": 0.1219978928565979, "exposed_belly": 0.2361663281917572, "covered_belly": 0.004645615816116333, "covered_buttocks": 0.007969379425048828, "exposed_buttocks": 0.040920644998550415, "covered_feet": 0.004700213670730591, "exposed_feet": 0.0017207860946655273, "covered_breast_f": 0.5827286839485168, "exposed_breast_f": 0.5190947651863098, "covered_genitalia_f": 0.11009037494659424, "exposed_genitalia_f": 0.003075540065765381, "exposed_breast_m": 0.0006746351718902588, "exposed_genitalia_m": 0.005911082029342651 }, "hate_symbols": { "confederate_flag": 0.10465598106384277, "pepe_frog": 0.009708642959594727, "nazi_swastika": 0.07055380940437317 }, "caption_language_toxicity": { "toxicity": 0.0003523826599121094, "severe_toxicity": 4.458427429199219e-05, "obscene": 0.00036585330963134766, "insult": 0.0004227757453918457, "identity_attack": 0.00011718273162841797, "threat": 5.6624412536621094e-05, "sexual_explicit": 4.363059997558594e-05 }, "visual_content": { "artistic": 0.00594728346914053, "comic": 0.0004559260851237923, "meme": 0.00048818273353390396, "screenshot": 0.009867854416370392, "map": 2.6955993234878406e-05, "poster_cover": 4.053880275023403e-06, "game_screenshot": 4.549684308585711e-05, "face_filter": 0.008053907193243504, "promo_info_graphic": 6.63170067127794e-06, "photo": 0.9751037955284119 }, "other": { "child": 0.05087965726852417, "middle_finger_gesture": 0.0770421028137207, "toy": 0.09503969550132751, "gambling_machine": 0.09784704446792603, "face_f": 0.501373291015625, "face_m": 0.0010322332382202148 }, "url": "{RESOURCE_URL}" }, "msg": null } ``` #### Response Example (Status: queued) ```json { "status": "queued" } ``` #### Response Example (Status: error) ```json { "status": "failed", "msg": "the error message for the request" } ``` ``` -------------------------------- ### Send Image for Policy Classification (Javascript) Source: https://docs.unitary.ai/api-references/policy-classification.md This Javascript code snippet sends an image for policy classification via the Unitary AI API. It uses `node-fetch` and `form-data`. Remember to replace the placeholder values with your specific details. ```javascript const fetch = require('node-fetch'); const FormData = require('form-data'); const fs = require('fs'); const apiToken = 'your_api_token_here'; const file_path = '/path/to/your/file.jpg'; const caption = 'your_caption_here'; const url = 'https://api.unitary.ai/v1/classify/image'; // For sending a URL const dataUrl = new URLSearchParams(); dataUrl.append('caption', caption); dataUrl.append('url', 'your_resource_url_here'); fetch(url, { method: 'POST', body: dataUrl, headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(response => response.text()) .then(result => console.log(result["job_id"])) .catch(error => console.log('error', error)); ``` -------------------------------- ### cURL: Upload Image File Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Use this cURL command to send an image file for classification. Ensure to replace placeholders with your API token, file path, file extension, and an optional caption. ```bash curl --location --request POST "https://api.unitary.ai/v1/classify/items-characteristics/image" \ --header "Authorization: Bearer {API_TOKEN}" \ --header "Content-Type: multipart/form-data" \ --form "file=@{FILE};type=image/{FILE_EXTENSION}" \ --form "caption={CAPTION}" ``` -------------------------------- ### POST /classify/policy/image/now Source: https://docs.unitary.ai/api-references/policy-classification/add-on-synchronous-endpoints.md This endpoint allows for synchronous policy classification of an image. The results are returned directly in the response, eliminating the need for webhook integration. ```APIDOC ## POST /classify/policy/image/now ### Description Synchronously classifies an image for policy violations. Results are returned directly in the response. ### Method POST ### Endpoint /classify/policy/image/now ### Request Body This endpoint expects a multipart/form-data request containing the image file. ### Response #### Success Response (200) - **results** (object) - Contains the classification results, including detected policies and confidence scores. #### Response Example ```json { "results": { "policies": [ { "name": "Hate Speech", "confidence": 0.95 }, { "name": "Violence", "confidence": 0.70 } ] } } ``` ``` -------------------------------- ### Python: Send Image URL Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Python script uses the `requests` library to send a resource URL of an image for classification. Replace placeholders with your API token, caption, and the image URL. The response contains the job ID. ```python # For sending a URL data = { 'caption': caption, 'url': 'your_resource_url_here' } headers = {'Authorization': f'Bearer {api_token}'} response = requests.post(url, data=data, headers=headers) job_id = resonse.text["job_id"] print(job_id) ``` -------------------------------- ### Javascript: Upload Image File Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Javascript code uses `node-fetch` and `form-data` to send an image file for classification. Replace placeholders with your API token, file path, and caption. The response contains the job ID. ```javascript const fetch = require('node-fetch'); const FormData = require('form-data'); const fs = require('fs'); const apiToken = 'your_api_token_here'; const file_path = '/path/to/your/file.jpg'; const caption = 'your_caption_here'; const url = 'https://api.unitary.ai/v1/classify/items-characteristics/image'; // For sending a file const formDataFile = new FormData(); formDataFile.append('file', fs.createReadStream(file_path), { type: 'image/jpeg' }); formDataFile.append('caption', caption); fetch(url, { method: 'POST', body: formDataFile, headers: { 'Authorization': `Bearer ${apiToken}`, }, }) .then(response => response.text()) .then(result => console.log(result["job_id"])) .catch(error => console.log('error', error)); ``` -------------------------------- ### Send Image for Policy Classification (cURL) Source: https://docs.unitary.ai/api-references/policy-classification.md Use this cURL command to send an image for policy classification. Ensure you replace placeholders with your actual API token, caption, and resource URL. ```bash curl --location --request POST "https://api.unitary.ai/v1/classify/policy/image" \ --header "Authorization: Bearer {API_TOKEN}" \ --form "caption={CAPTION}" \ --form "url={RESOURCE_URL}" ``` -------------------------------- ### Classify Video Characteristics Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Send a video to the API for item and characteristic classification. ```APIDOC ## POST /classify/items-characteristics/video ### Description Classifies items and their characteristics from an uploaded video. ### Method POST ### Endpoint /classify/items-characteristics/video ### Parameters #### Request Body - **file** (file) - Required - The video file to classify. Use `Content-Type: multipart/form-data`. - **caption** (string) - Optional - A caption describing the video content. ### Request Example (cURL) ```bash curl --location --request POST "https://api.unitary.ai/v1/classify/items-characteristics/video" \ --header "Authorization: Bearer {API_TOKEN}" \ --header "Content-Type: multipart/form-data" \ --form "file=@{FILE};type=video/{FILE_EXTENSION}" \ --form "caption={CAPTION}" ``` ### Response #### Success Response (200) - **job_id** (string) - The ID of the classification job. ### Response Example (JSON) ```json { "job_id": "example_job_id" } ``` ``` -------------------------------- ### cURL: Send Image URL Source: https://docs.unitary.ai/api-references/items-and-characteristics.md Use this cURL command to send a resource URL of an image for classification. Replace placeholders with your API token, caption, and the image URL. ```bash curl --location --request POST "https://api.unitary.ai/v1/classify/items-characteristics/image" \ --header "Authorization: Bearer {API_TOKEN}" \ --form "caption={CAPTION}" \ --form "url={RESOURCE_URL}" ``` -------------------------------- ### Javascript: Send Image URL Source: https://docs.unitary.ai/api-references/items-and-characteristics.md This Javascript code uses `node-fetch` to send a resource URL of an image for classification. Replace placeholders with your API token, caption, and the image URL. The response contains the job ID. ```javascript // For sending a URL const dataUrl = new URLSearchParams(); dataUrl.append('caption', caption); dataUrl.append('url', 'your_resource_url_here'); fetch(url, { method: 'POST', body: dataUrl, headers: { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/x-www-form-urlencoded', }, }) .then(response => response.text()) .then(result => console.log(result["job_id"])) .catch(error => console.log('error', error)); ``` -------------------------------- ### POST /detoxify/text/ Source: https://docs.unitary.ai/api-references/detoxify.md This endpoint processes text to detect hateful or offensive language. It requires API authentication and follows the OpenAPI specification for request and response formats. ```APIDOC ## POST /detoxify/text/ ### Description This endpoint processes input text to detect hateful or offensive language using pre-trained models. It is designed for ease of use, allowing users to integrate toxicity detection without hosting models themselves. ### Method POST ### Endpoint /detoxify/text/ ### Parameters #### Request Body - **text** (string) - Required - The text content to be analyzed for toxicity. ### Request Example ```json { "text": "This is a sample text to check for toxicity." } ``` ### Response #### Success Response (200) - **toxicity** (number) - The predicted toxicity score for the input text. - **severe_toxicity** (number) - The predicted severe toxicity score. - **obscene** (number) - The predicted obscenity score. - **threat** (number) - The predicted threat score. - **insult** (number) - The predicted insult score. - **identity_attack** (number) - The predicted identity attack score. - **sexual_explicit** (number) - The predicted sexual explicit score. - **language** (string) - The detected language of the input text. #### Response Example ```json { "toxicity": 0.98, "severe_toxicity": 0.75, "obscene": 0.82, "threat": 0.1, "insult": 0.9, "identity_attack": 0.5, "sexual_explicit": 0.2, "language": "en" } ``` ``` -------------------------------- ### Find Best Threshold for a Characteristic Source: https://docs.unitary.ai/api-references/how-to-select-thresholds-for-items-and-characteristics.md Iterates through a range of thresholds to find the one that maximizes the F1 score for a given characteristic and its true labels. Requires pandas and scikit-learn. ```python def find_best_threshold( data: pd.DataFrame, thresholds: np.ndarray, characteristic: str, true_label: str ) -> Tuple[float, float]: """ Function to find the best threshold for a given characteristic based on its F1 score. Parameters: data (pd.DataFrame): A DataFrame containing the characteristic and labels. thresholds (np.ndarray): An array of threshold values to test. characteristic (str): The name of the characteristic column. true_label (str): The name of the corresponding ground truth label column. Returns: best_threshold (float): The best threshold for the characteristic. best_f1 (float): The corresponding F1 score. """ best_threshold = None best_f1 = 0 for threshold in thresholds: predicted_labels = (data[characteristic] > threshold).astype(int) f1 = f1_score(data[true_label], predicted_labels) if f1 > best_f1: best_f1 = f1 best_threshold = threshold return best_threshold, best_f1 ``` -------------------------------- ### Authenticate Endpoint Source: https://docs.unitary.ai/api-references/authentication.md This endpoint is used to generate a Bearer token by providing your API key. The token is then used for authenticating subsequent API requests. ```APIDOC ## POST /authenticate ### Description Generates a Bearer token using your API key. This token is required for authenticating subsequent API requests. ### Method POST ### Endpoint /authenticate ### Parameters #### Request Body - **key** (string) - Required - Your Unitary API key. ### Request Example ```bash curl --location --request POST 'https://api.unitary.ai/v1/authenticate' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'key={API_KEY}' ``` ### Response #### Success Response (200) - **api_token** (string) - The generated Bearer token. - **expiry** (string) - The expiration time of the token. #### Response Example ```json { "api_token": "your_generated_token", "expiry": "2023-10-27T10:00:00Z" } ``` ```