|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Create one activity after showing the space and its estimated cost. |
| 4 | +
|
| 5 | +This script runs the complete detection lifecycle through `analyze()`. It creates the |
| 6 | +activity, uploads the media, confirms it, polls until completion, and prints the final |
| 7 | +scores. Be aware that running this against a live API will spend real tokens. You can |
| 8 | +pass `--list-only` to see the cost estimate without creating anything, or use |
| 9 | +`--engine local` to run the detection on your device for free. |
| 10 | +
|
| 11 | +Only `GUARD_API_KEY` and a space ID are required. Everything else resolves through the |
| 12 | +standard client precedence using arguments, the environment, or a `.env` file. The |
| 13 | +media file is taken from the first argument or the `GUARD_MEDIA` environment variable. |
| 14 | +
|
| 15 | +Example: |
| 16 | + ```bash |
| 17 | + # preview the cost without creating anything |
| 18 | + uv run python scripts/create_activity.py photo.jpg --list-only |
| 19 | +
|
| 20 | + # run the activity against the cloud API |
| 21 | + uv run python scripts/create_activity.py photo.jpg |
| 22 | + uv run python scripts/create_activity.py photo.jpg --space-id <uuid> |
| 23 | +
|
| 24 | + # run on-device instead, which requires no space and consumes no tokens |
| 25 | + uv run python scripts/create_activity.py photo.jpg --engine local |
| 26 | + ``` |
| 27 | +""" |
| 28 | + |
| 29 | +from __future__ import annotations |
| 30 | + |
| 31 | +import argparse |
| 32 | +import os |
| 33 | +import sys |
| 34 | +from pathlib import Path |
| 35 | +from typing import Optional |
| 36 | + |
| 37 | +from guard_client import GuardClient, GuardError, probe_media, read_env_file |
| 38 | + |
| 39 | + |
| 40 | +def parse_args() -> argparse.Namespace: |
| 41 | + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 42 | + parser.add_argument("media", nargs="?", help="media file; defaults to GUARD_MEDIA") |
| 43 | + parser.add_argument("--space-id", help="the space to run in; or GUARD_SPACE_ID") |
| 44 | + parser.add_argument("--user-id", help="create a user-owned activity") |
| 45 | + parser.add_argument("--account-id", help="create a service-account-owned activity") |
| 46 | + parser.add_argument( |
| 47 | + "--engine", choices=["cloud", "local"], help="client default: cloud" |
| 48 | + ) |
| 49 | + parser.add_argument( |
| 50 | + "--timeout", type=float, help="seconds to wait for processing to finish" |
| 51 | + ) |
| 52 | + parser.add_argument( |
| 53 | + "--list-only", |
| 54 | + action="store_true", |
| 55 | + help="print the space and the estimate, then exit without creating anything", |
| 56 | + ) |
| 57 | + return parser.parse_args() |
| 58 | + |
| 59 | + |
| 60 | +def from_env(name: str) -> Optional[str]: |
| 61 | + """Read one setting the way the client does: real environment first, then .env.""" |
| 62 | + return os.environ.get(name) or read_env_file().get(name) |
| 63 | + |
| 64 | + |
| 65 | +def media_path(argument: Optional[str]) -> Path: |
| 66 | + """The one setting the client does not resolve for us.""" |
| 67 | + media = argument or from_env("GUARD_MEDIA") |
| 68 | + if not media: |
| 69 | + sys.exit("Pass a media file path as the first argument or set GUARD_MEDIA") |
| 70 | + |
| 71 | + path = Path(media) |
| 72 | + if not path.is_file(): |
| 73 | + sys.exit(f"No such file: {path}") |
| 74 | + return path |
| 75 | + |
| 76 | + |
| 77 | +def print_media(path: Path) -> None: |
| 78 | + """Show what the probe read out of the file headers.""" |
| 79 | + info = probe_media(path) |
| 80 | + print(f"Media: {path.name}") |
| 81 | + print(f" type {info.media_type.value}") |
| 82 | + print(f" size {path.stat().st_size} bytes") |
| 83 | + print(f" pixels {info.width}x{info.height}") |
| 84 | + print(f" frames {info.frames} ({info.duration_seconds:.1f}s)") |
| 85 | + |
| 86 | + |
| 87 | +def print_space(client: GuardClient, space_id: str, media: Path) -> None: |
| 88 | + """Show the space this will run in, and what it is expected to cost.""" |
| 89 | + space = client.spaces.get(space_id) |
| 90 | + tasks = ", ".join(task.name for task in space.enabled_tasks) or "-" |
| 91 | + |
| 92 | + print(f"\nSpace: {space.name}") |
| 93 | + print(f" id {space.id}") |
| 94 | + print(f" predictor {space.predictor_name} (x{space.predictor_multiplier})") |
| 95 | + print(f" max media {space.max_media_size or '-'} bytes") |
| 96 | + print(f" tasks {tasks}") |
| 97 | + |
| 98 | + print(f"\nEstimated cost: {client.estimate_tokens(media, space_id=space_id)}") |
| 99 | + print(" An estimate: the API reserves the minimum, payed_tokens is final.") |
| 100 | + |
| 101 | + |
| 102 | +def main() -> int: |
| 103 | + args = parse_args() |
| 104 | + media = media_path(args.media) |
| 105 | + local = args.engine == "local" |
| 106 | + |
| 107 | + space_id = args.space_id or from_env("GUARD_SPACE_ID") |
| 108 | + if not local and not space_id: |
| 109 | + sys.exit( |
| 110 | + "Pass --space-id or set GUARD_SPACE_ID (scripts/list_spaces.py finds one)" |
| 111 | + ) |
| 112 | + |
| 113 | + try: |
| 114 | + with GuardClient(space_id=space_id, engine=args.engine) as client: |
| 115 | + print(f"Connected to {client.base_url}\n") |
| 116 | + |
| 117 | + print_media(media) |
| 118 | + if local: |
| 119 | + print("\nEngine: local. No space, no network, no tokens.") |
| 120 | + else: |
| 121 | + print_space(client, str(space_id), media) |
| 122 | + |
| 123 | + if args.list_only: |
| 124 | + print("\n--list-only: nothing was created.") |
| 125 | + return 0 |
| 126 | + |
| 127 | + print(f"\nAnalyzing {media.name}...") |
| 128 | + result = client.analyze( |
| 129 | + media, |
| 130 | + user_id=args.user_id, |
| 131 | + account_id=args.account_id, |
| 132 | + **({} if args.timeout is None else {"timeout": args.timeout}), |
| 133 | + ) |
| 134 | + |
| 135 | + print(f"\nDone: engine={result.engine.value}") |
| 136 | + print(f" activity {result.activity_id or '-'}") |
| 137 | + for item in result.results: |
| 138 | + print(f" - {item.label}: {item.score}/100") |
| 139 | + if not result.results: |
| 140 | + print(" (no results returned)") |
| 141 | + print(f" max_score {result.max_score}") |
| 142 | + except GuardError as exc: |
| 143 | + # Covers a missing API key or space id too, which the client reports itself. |
| 144 | + print(f"\nFAILED: {type(exc).__name__}: {exc}", file=sys.stderr) |
| 145 | + return 1 |
| 146 | + |
| 147 | + return 0 |
| 148 | + |
| 149 | + |
| 150 | +if __name__ == "__main__": |
| 151 | + raise SystemExit(main()) |
0 commit comments