Automatically running a Selective Scan & Selective Auto Tag in a Python script

Hi, I have a Python script I use for auto-sorting content. At the end it outputs a list of directories to autoscan/autotag:
=== DIRECTORIES TO SCAN/AUTOTAG ===
/data/Studio/StudioName

I think it should be easy to feed that into a function which uses either the Python stashapi, or just standard GraphQL, to tell Stash to run selective scans & auto tags on each of those directories - but I’m struggling to get either of those to work correctly.
Does anyone have some example code they could share that I could work from?

This is the helper code I use in my local plugins: if you’re using it outside of a plugin context you can just inline the GraphQL call into scan and call it directly

You’ll want to change:

  • The domain/port if you’re not running default settings
  • The scan settings (I only want to generate phashes on the initial scan)
  • The ApiKey if you’ve got authentication enabled
from requests import post

def exit_plugin(*, msg=None, err=None) -> NoReturn:
    if not any((msg, err)):
        msg = "Normal termination"
    print(json.dumps({"output": msg, "error": err}))
    sys.exit(1 if err else 0)

def callGraphQL(
    query: str, variables: Optional[dict] = None, fatal_errors: bool = True
) -> dict:
    graphql_scheme = "http"
    graphql_domain = "localhost"
    graphql_port = 9999
    graphql_headers = {
        "Accept-Encoding": "gzip, deflate, br",
        "ApiKey": "",
        "Content-Type": "application/json",
    }

    graphql_url = f"{graphql_scheme}://{graphql_domain}:{graphql_port}/graphql"
    query = " ".join(query.split())
    payload = {"query": query, "variables": variables}
    try:
        response = post(
            graphql_url,
            json=payload,
            headers=graphql_headers,
        )
    except Exception as e:
        exit_plugin(err=f"Exception with GraphQL request. {e}")

    result = response.json()
    if "errors" in result and fatal_errors:
        errors = "\n".join(e["message"] for e in result["errors"])
        exit_plugin(err=f"GraphQL error: {errors}")

    return result["data"]

def scan(*paths):
    query = """
    mutation MetadataScan($input: ScanMetadataInput!) {
        metadataScan(input: $input)
    }
    """
    variables = {
        "input": {
            "paths": list(paths),
            "scanGenerateCovers": False,
            "scanGeneratePreviews": False,
            "scanGenerateImagePreviews": False,
            "scanGenerateSprites": False,
            "scanGeneratePhashes": True,
            "scanGenerateThumbnails": False,
            "scanGenerateClipPreviews": False,
        }
    }
    return callGraphQL(query, variables)

Thank you!! This is very helpful