adshot 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adshot/__init__.py +1 -0
- adshot/__main__.py +4 -0
- adshot/cli.py +130 -0
- adshot/config.py +178 -0
- adshot/estimate.py +95 -0
- adshot/manifest.py +174 -0
- adshot/mcp_server.py +282 -0
- adshot/perfume.csv +5 -0
- adshot/plan.py +95 -0
- adshot/providers.py +131 -0
- adshot/runner.py +240 -0
- adshot/stitch.py +105 -0
- adshot/storyboard.py +149 -0
- adshot-0.2.0.data/data/share/adshot/SKILL.md +30 -0
- adshot-0.2.0.data/data/share/adshot/examples/perfume/storyboard.csv +5 -0
- adshot-0.2.0.dist-info/METADATA +169 -0
- adshot-0.2.0.dist-info/RECORD +21 -0
- adshot-0.2.0.dist-info/WHEEL +5 -0
- adshot-0.2.0.dist-info/entry_points.txt +2 -0
- adshot-0.2.0.dist-info/licenses/LICENSE +202 -0
- adshot-0.2.0.dist-info/top_level.txt +1 -0
adshot/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shot-by-shot video production."""
|
adshot/__main__.py
ADDED
adshot/cli.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Command-line entry point for an adshot project."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import csv
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .config import init_project, load_config
|
|
9
|
+
from .estimate import quote, show_estimate, spent
|
|
10
|
+
from .manifest import Manifest
|
|
11
|
+
from .plan import plan
|
|
12
|
+
from .runner import abandon, run
|
|
13
|
+
from .stitch import stitch
|
|
14
|
+
from .storyboard import read_storyboard
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parser():
|
|
18
|
+
cli = argparse.ArgumentParser(prog="adshot", description="Render product ads shot by shot.")
|
|
19
|
+
commands = cli.add_subparsers(dest="command", required=True)
|
|
20
|
+
init = commands.add_parser("init", help="Create an offline-ready project")
|
|
21
|
+
init.add_argument("dir", type=Path)
|
|
22
|
+
planner = commands.add_parser("plan", help="Draft a storyboard with a vision chat model")
|
|
23
|
+
planner.add_argument("--image", required=True)
|
|
24
|
+
planner.add_argument("--brief", required=True)
|
|
25
|
+
planner.add_argument("--shots", type=int, default=4)
|
|
26
|
+
planner.add_argument("--seconds", type=int, default=16)
|
|
27
|
+
estimate = commands.add_parser("estimate", help="Price the storyboard offline")
|
|
28
|
+
estimate.add_argument("--only", help="Comma-separated shot IDs")
|
|
29
|
+
render = commands.add_parser("run", help="Price and render the selected shots")
|
|
30
|
+
group = render.add_mutually_exclusive_group()
|
|
31
|
+
group.add_argument("--only", help="Comma-separated shot IDs")
|
|
32
|
+
group.add_argument("--reconcile", metavar="SHOT_ID", help="Resolve an uncertain submission")
|
|
33
|
+
render.add_argument("--yes", action="store_true", help="Approve the displayed video estimate")
|
|
34
|
+
render.add_argument("--accept-unverified-prices", action="store_true",
|
|
35
|
+
help="Allow new submissions at rates unverified for this endpoint")
|
|
36
|
+
render.add_argument("--budget", type=float, metavar="USD", help="Override the per-run cap")
|
|
37
|
+
commands.add_parser("status", help="Show shot states and usage-based spend")
|
|
38
|
+
drop = commands.add_parser("abandon", help="Mark an unrecoverable task failed for a fresh quote")
|
|
39
|
+
drop.add_argument("shot_id", metavar="SHOT_ID")
|
|
40
|
+
drop.add_argument("--confirm", metavar="RETRY", help="Confirm that a future run may charge again")
|
|
41
|
+
join = commands.add_parser("stitch", help="Join the current shots in storyboard order")
|
|
42
|
+
join.add_argument("--out", type=Path, default=Path("ad.mp4"))
|
|
43
|
+
commands.add_parser("mcp", help="Serve adshot to an MCP client over stdio")
|
|
44
|
+
return cli
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _dispatch(args):
|
|
48
|
+
root = Path.cwd()
|
|
49
|
+
if args.command == "mcp":
|
|
50
|
+
from .mcp_server import main as serve
|
|
51
|
+
serve()
|
|
52
|
+
return 0
|
|
53
|
+
if args.command == "init":
|
|
54
|
+
init_project(args.dir)
|
|
55
|
+
print(f"Created {args.dir.resolve()}. Run adshot estimate from that directory.")
|
|
56
|
+
return 0
|
|
57
|
+
if args.command == "estimate" and not (root / "adshot.toml").is_file():
|
|
58
|
+
children = [p for p in root.iterdir() if not p.name.startswith((".", "_"))
|
|
59
|
+
and p.is_dir() and (p / "adshot.toml").is_file()]
|
|
60
|
+
if len(children) == 1:
|
|
61
|
+
root = children[0]
|
|
62
|
+
print(f"Project: {root}")
|
|
63
|
+
elif len(children) > 1:
|
|
64
|
+
raise ValueError("Several adshot projects found. Change into the one to estimate.")
|
|
65
|
+
config = load_config(root)
|
|
66
|
+
if args.command == "plan":
|
|
67
|
+
plan(root, config, args.image, args.brief, args.shots, args.seconds)
|
|
68
|
+
print(f"Wrote storyboard.csv with {args.shots} shots totaling {args.seconds} seconds.")
|
|
69
|
+
return 0
|
|
70
|
+
|
|
71
|
+
shots = read_storyboard(root, config)
|
|
72
|
+
if args.command == "abandon":
|
|
73
|
+
if args.shot_id not in {shot.shot_id for shot in shots}:
|
|
74
|
+
raise ValueError(f"Unknown shot ID: {args.shot_id!r}.")
|
|
75
|
+
abandon(Manifest(root), args.shot_id, args.confirm)
|
|
76
|
+
return 0
|
|
77
|
+
if args.command == "stitch":
|
|
78
|
+
stitch(root, [shot.shot_id for shot in shots], args.out)
|
|
79
|
+
print(f"Wrote {args.out.resolve()}")
|
|
80
|
+
return 0
|
|
81
|
+
|
|
82
|
+
reconcile = getattr(args, "reconcile", None)
|
|
83
|
+
selection = getattr(args, "only", None)
|
|
84
|
+
if selection is not None or reconcile is not None:
|
|
85
|
+
wanted = {reconcile} if reconcile is not None else {s.strip() for s in selection.split(",")}
|
|
86
|
+
unknown = wanted.difference(shot.shot_id for shot in shots)
|
|
87
|
+
if unknown:
|
|
88
|
+
raise ValueError(f"Unknown shot ID(s): {', '.join(sorted(unknown))!r}.")
|
|
89
|
+
shots = [shot for shot in shots if shot.shot_id in wanted]
|
|
90
|
+
manifest = Manifest(root)
|
|
91
|
+
history = manifest.recover(shot.shot_id for shot in shots)
|
|
92
|
+
quotes = [quote(root, config, shot, history.get(shot.shot_id, [])) for shot in shots]
|
|
93
|
+
if args.command == "estimate":
|
|
94
|
+
show_estimate(quotes)
|
|
95
|
+
elif args.command == "run":
|
|
96
|
+
budget = config.budget_usd if args.budget is None else args.budget
|
|
97
|
+
return run(manifest, config, quotes, budget=budget, yes=args.yes, reconcile=reconcile,
|
|
98
|
+
accept_unverified_prices=args.accept_unverified_prices)
|
|
99
|
+
elif args.command == "status":
|
|
100
|
+
print("SHOT STATE SPENT USD (usage x saved rate) TASK ID")
|
|
101
|
+
for item in quotes:
|
|
102
|
+
shot_id = item.shot.shot_id
|
|
103
|
+
attempts = history.get(shot_id, [])
|
|
104
|
+
latest = attempts[-1] if attempts else {}
|
|
105
|
+
if item.state == "done":
|
|
106
|
+
latest = next(a for a in reversed(attempts) if a["state"] == "done")
|
|
107
|
+
task_id = latest.get("task_id", "-")
|
|
108
|
+
amount = spent(attempts)
|
|
109
|
+
if any(not a.get("verified") for a in attempts):
|
|
110
|
+
amount += " [unverified price]"
|
|
111
|
+
print(f"{shot_id:<10} {item.state:<17} {amount:<33} {task_id}")
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main(argv=None):
|
|
116
|
+
args = parser().parse_args(argv)
|
|
117
|
+
try:
|
|
118
|
+
return _dispatch(args)
|
|
119
|
+
except (ValueError, OSError, RuntimeError, csv.Error) as exc:
|
|
120
|
+
print(f"adshot: {exc}", file=sys.stderr)
|
|
121
|
+
except EOFError:
|
|
122
|
+
print("adshot: Confirmation requires interactive input.", file=sys.stderr)
|
|
123
|
+
except KeyboardInterrupt:
|
|
124
|
+
print("adshot: Interrupted. Use adshot status to inspect saved tasks.", file=sys.stderr)
|
|
125
|
+
return 130
|
|
126
|
+
return 1
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
if __name__ == "__main__":
|
|
130
|
+
sys.exit(main())
|
adshot/config.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Project settings and the offline starter storyboard."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import tomllib
|
|
11
|
+
except ModuleNotFoundError: # Python 3.10
|
|
12
|
+
import tomli as tomllib
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
OPENLUX = "https://api.openlux.ai"
|
|
16
|
+
ARK = "https://ark.cn-beijing.volces.com"
|
|
17
|
+
MINI = "doubao-seedance-2-0-mini-260615"
|
|
18
|
+
FAST = "doubao-seedance-2-0-fast-260128"
|
|
19
|
+
STD = "doubao-seedance-2-0-260128"
|
|
20
|
+
PRO = "doubao-seedance-2-5-260628"
|
|
21
|
+
|
|
22
|
+
TEMPLATE = f'''# Video generation. An empty base_url selects the provider's default endpoint.
|
|
23
|
+
provider = "openlux"
|
|
24
|
+
base_url = ""
|
|
25
|
+
model = "{FAST}"
|
|
26
|
+
resolution = "720p"
|
|
27
|
+
ratio = "9:16"
|
|
28
|
+
budget_usd = 5.0
|
|
29
|
+
concurrency = 2
|
|
30
|
+
|
|
31
|
+
# Optional vision planner. Defaults to the video origin + /api/v3 for Ark or /v1 for OpenLux.
|
|
32
|
+
plan_model = "gpt-4o-mini"
|
|
33
|
+
plan_base_url = ""
|
|
34
|
+
|
|
35
|
+
# USD per million video tokens. Update these values using your provider's rates.
|
|
36
|
+
# Set verified = true and base_url to the endpoint whose price you confirmed.
|
|
37
|
+
[prices."{MINI}"]
|
|
38
|
+
usd_per_million = 2.41
|
|
39
|
+
verified = true
|
|
40
|
+
base_url = "{OPENLUX}" # Measured on OpenLux on 2026-11-19.
|
|
41
|
+
|
|
42
|
+
[prices."{FAST}"]
|
|
43
|
+
usd_per_million = 3.61
|
|
44
|
+
verified = true
|
|
45
|
+
base_url = "{OPENLUX}" # Measured on OpenLux on 2026-11-19, 720p portrait with a first frame.
|
|
46
|
+
|
|
47
|
+
# Standard and Pro prices are unverified budget placeholders.
|
|
48
|
+
[prices."{STD}"]
|
|
49
|
+
usd_per_million = 8.0
|
|
50
|
+
verified = false
|
|
51
|
+
|
|
52
|
+
[prices."{PRO}"]
|
|
53
|
+
usd_per_million = 12.0
|
|
54
|
+
verified = false
|
|
55
|
+
'''
|
|
56
|
+
|
|
57
|
+
PROJECT_IGNORE = """# Local settings and generated media
|
|
58
|
+
.env*
|
|
59
|
+
.adshot/
|
|
60
|
+
manifest.json
|
|
61
|
+
shots/
|
|
62
|
+
ad.mp4
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Price:
|
|
68
|
+
usd_per_million: float
|
|
69
|
+
verified: bool
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Config:
|
|
74
|
+
provider: str
|
|
75
|
+
base_url: str
|
|
76
|
+
model: str
|
|
77
|
+
resolution: str
|
|
78
|
+
ratio: str
|
|
79
|
+
budget_usd: float
|
|
80
|
+
concurrency: int
|
|
81
|
+
plan_model: str
|
|
82
|
+
plan_base_url: str
|
|
83
|
+
prices: dict[str, Price]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def init_project(root: Path) -> None:
|
|
87
|
+
"""Create a standalone project without overwriting existing files."""
|
|
88
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
starter = files("adshot").joinpath("perfume.csv").read_bytes()
|
|
90
|
+
content = {
|
|
91
|
+
"adshot.toml": TEMPLATE.encode("utf-8"),
|
|
92
|
+
"storyboard.csv": starter,
|
|
93
|
+
".gitignore": PROJECT_IGNORE.encode("utf-8"),
|
|
94
|
+
}
|
|
95
|
+
for name in content:
|
|
96
|
+
if (root / name).exists():
|
|
97
|
+
raise ValueError(f"{name} already exists in {root}. Choose a new project directory.")
|
|
98
|
+
created = []
|
|
99
|
+
try:
|
|
100
|
+
for name, data in content.items():
|
|
101
|
+
path = root / name
|
|
102
|
+
with path.open("xb") as stream:
|
|
103
|
+
created.append(path)
|
|
104
|
+
stream.write(data)
|
|
105
|
+
except OSError:
|
|
106
|
+
for path in created:
|
|
107
|
+
path.unlink(missing_ok=True)
|
|
108
|
+
raise
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def validate_base_url(value: str, field: str = "base_url") -> str:
|
|
112
|
+
parts = urlsplit(value)
|
|
113
|
+
local_http = parts.scheme == "http" and parts.hostname in {"localhost", "127.0.0.1"}
|
|
114
|
+
if ((parts.scheme != "https" and not local_http) or not parts.hostname or
|
|
115
|
+
parts.username is not None or parts.password is not None or
|
|
116
|
+
parts.query or parts.fragment or any(c.isspace() for c in value)):
|
|
117
|
+
raise ValueError(f"{field} requires HTTPS without credentials, query or fragment. "
|
|
118
|
+
"HTTP is allowed only for localhost and 127.0.0.1.")
|
|
119
|
+
return value.rstrip("/")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _number(value, field: str) -> float:
|
|
123
|
+
if type(value) not in {int, float} or not math.isfinite(value) or value < 0:
|
|
124
|
+
raise ValueError(f"{field} must be a finite, nonnegative number.")
|
|
125
|
+
return float(value)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _text(doc: dict, field: str, default: str) -> str:
|
|
129
|
+
value = doc.get(field, default)
|
|
130
|
+
if not isinstance(value, str) or (not value.strip() and default):
|
|
131
|
+
raise ValueError(f"{field} must be a string{' containing a value' if default else ''}.")
|
|
132
|
+
return value.strip()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def load_config(root: Path) -> Config:
|
|
136
|
+
path = root / "adshot.toml"
|
|
137
|
+
if not path.is_file():
|
|
138
|
+
raise ValueError(f"No adshot.toml in {root}. Run adshot init or change into a project.")
|
|
139
|
+
with path.open("rb") as stream:
|
|
140
|
+
doc = tomllib.load(stream)
|
|
141
|
+
provider = _text(doc, "provider", "openlux")
|
|
142
|
+
endpoints = {"openlux": OPENLUX, "ark": ARK}
|
|
143
|
+
custom = _text(doc, "base_url", "")
|
|
144
|
+
if not custom and provider not in endpoints:
|
|
145
|
+
raise ValueError("Unknown provider. Choose openlux or ark, or set base_url.")
|
|
146
|
+
base_url = validate_base_url(custom or endpoints[provider])
|
|
147
|
+
plan_path = "/api/v3" if provider == "ark" else "/v1"
|
|
148
|
+
plan_base = _text(doc, "plan_base_url", "") or base_url + plan_path
|
|
149
|
+
concurrency = doc.get("concurrency", 2)
|
|
150
|
+
if type(concurrency) is not int or concurrency < 1:
|
|
151
|
+
raise ValueError("concurrency must be a positive integer.")
|
|
152
|
+
table = doc.get("prices")
|
|
153
|
+
if not isinstance(table, dict) or not table:
|
|
154
|
+
raise ValueError("adshot.toml needs a prices table with a rate for each model.")
|
|
155
|
+
prices = {}
|
|
156
|
+
for model, entry in table.items():
|
|
157
|
+
if not isinstance(entry, dict):
|
|
158
|
+
raise ValueError(f"prices.{model} must be a table.")
|
|
159
|
+
rate = _number(entry.get("usd_per_million"), f"prices.{model}.usd_per_million")
|
|
160
|
+
verified = entry.get("verified", False)
|
|
161
|
+
if type(verified) is not bool:
|
|
162
|
+
raise ValueError(f"prices.{model}.verified must be true or false.")
|
|
163
|
+
scope = _text(entry, "base_url", "")
|
|
164
|
+
if scope and validate_base_url(scope, "price base_url") != base_url:
|
|
165
|
+
verified = False
|
|
166
|
+
prices[model] = Price(rate, verified)
|
|
167
|
+
return Config(
|
|
168
|
+
provider=provider,
|
|
169
|
+
base_url=base_url,
|
|
170
|
+
model=_text(doc, "model", FAST),
|
|
171
|
+
resolution=_text(doc, "resolution", "720p"),
|
|
172
|
+
ratio=_text(doc, "ratio", "9:16"),
|
|
173
|
+
budget_usd=_number(doc.get("budget_usd", 5.0), "budget_usd"),
|
|
174
|
+
concurrency=concurrency,
|
|
175
|
+
plan_model=_text(doc, "plan_model", "gpt-4o-mini"),
|
|
176
|
+
plan_base_url=validate_base_url(plan_base, "plan_base_url"),
|
|
177
|
+
prices=prices,
|
|
178
|
+
)
|
adshot/estimate.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Quote incremental spend and calculate costs from reported usage."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
|
|
6
|
+
from .config import PRO
|
|
7
|
+
from .storyboard import Shot
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def token_estimate(shot):
|
|
11
|
+
# Ark's nominal resolutions are pixel buckets; e.g. portrait 480p is
|
|
12
|
+
# 496 x 864 for Seedance 2.0. Adaptive uses the larger supported area.
|
|
13
|
+
landscape, square = {
|
|
14
|
+
"480p": (496 * 864, 640 * 640),
|
|
15
|
+
"720p": (1280 * 720, 960 * 960),
|
|
16
|
+
"1080p": (1920 * 1080, 1440 * 1440),
|
|
17
|
+
}[shot.resolution]
|
|
18
|
+
if shot.model == PRO and shot.resolution == "480p":
|
|
19
|
+
landscape = 480 * 854
|
|
20
|
+
area = landscape
|
|
21
|
+
if shot.ratio == "1:1":
|
|
22
|
+
area = square
|
|
23
|
+
elif shot.ratio == "adaptive":
|
|
24
|
+
area = max(landscape, square)
|
|
25
|
+
return round(shot.seconds * area * 24 / 1024)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def token_cost(tokens, price):
|
|
29
|
+
return Decimal(tokens) * Decimal(str(price)) / 1_000_000
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Quote:
|
|
34
|
+
shot: Shot
|
|
35
|
+
state: str
|
|
36
|
+
action: str
|
|
37
|
+
attempts: int
|
|
38
|
+
tokens: int
|
|
39
|
+
usd: Decimal
|
|
40
|
+
verified: bool
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def quote(root, config, shot, attempts):
|
|
44
|
+
state, action = "pending", "submit"
|
|
45
|
+
if attempts:
|
|
46
|
+
last = attempts[-1]
|
|
47
|
+
state = last["state"]
|
|
48
|
+
path = root / "shots" / f"{shot.shot_id}.mp4"
|
|
49
|
+
if state == "failed":
|
|
50
|
+
# A failed replacement leaves the last published video in place.
|
|
51
|
+
published = next((a for a in reversed(attempts) if a["state"] == "done"), None)
|
|
52
|
+
if (published and published["signature"] == shot.signature
|
|
53
|
+
and path.is_file() and path.stat().st_size):
|
|
54
|
+
last, state = published, "done"
|
|
55
|
+
if state == "done":
|
|
56
|
+
if last["signature"] != shot.signature:
|
|
57
|
+
state, action = "changed", "submit"
|
|
58
|
+
elif path.is_file() and path.stat().st_size:
|
|
59
|
+
action = "skip"
|
|
60
|
+
else:
|
|
61
|
+
state, action = "running", "resume"
|
|
62
|
+
elif state == "submitting":
|
|
63
|
+
state, action = "running", "busy"
|
|
64
|
+
elif state == "needs_reconcile":
|
|
65
|
+
action = "blocked"
|
|
66
|
+
elif state == "publishing":
|
|
67
|
+
state, action = "running", "publish"
|
|
68
|
+
elif state == "running":
|
|
69
|
+
action = "resume"
|
|
70
|
+
price = config.prices[shot.model]
|
|
71
|
+
tokens = token_estimate(shot) if action == "submit" else 0
|
|
72
|
+
return Quote(shot, state, action, len(attempts), tokens,
|
|
73
|
+
token_cost(tokens, price.usd_per_million), price.verified)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def show_estimate(quotes):
|
|
77
|
+
print("SHOT STATE ACTION NEW TOKENS NEW USD MODEL")
|
|
78
|
+
for item in quotes:
|
|
79
|
+
flag = "" if item.verified else " [unverified price]"
|
|
80
|
+
print(f"{item.shot.shot_id:<10} {item.state:<17} {item.action:<10} "
|
|
81
|
+
f"{item.tokens:>10} ${item.usd:.4f} {item.shot.model}{flag}")
|
|
82
|
+
total = sum((item.usd for item in quotes), start=Decimal(0))
|
|
83
|
+
print(f"Total new spend: ${total:.4f}", flush=True)
|
|
84
|
+
return total
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def spent(attempts):
|
|
88
|
+
total = Decimal(0)
|
|
89
|
+
unknown = False
|
|
90
|
+
for attempt in attempts:
|
|
91
|
+
if attempt.get("tokens") is None:
|
|
92
|
+
unknown = True
|
|
93
|
+
else:
|
|
94
|
+
total += token_cost(attempt["tokens"], attempt["price"])
|
|
95
|
+
return f"${total:.4f}" + (" + unknown" if unknown else "")
|
adshot/manifest.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Atomic manifest updates and filesystem claims for a local project."""
|
|
2
|
+
|
|
3
|
+
import errno
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import tempfile
|
|
9
|
+
import time
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _try_lock(handle):
|
|
15
|
+
try:
|
|
16
|
+
if os.name == "nt":
|
|
17
|
+
import msvcrt
|
|
18
|
+
|
|
19
|
+
handle.seek(0)
|
|
20
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
21
|
+
else:
|
|
22
|
+
import fcntl
|
|
23
|
+
|
|
24
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
25
|
+
return True
|
|
26
|
+
except OSError as exc:
|
|
27
|
+
if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
|
|
28
|
+
raise
|
|
29
|
+
return False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@contextmanager
|
|
33
|
+
def file_guard(path, *, wait=False):
|
|
34
|
+
# A stable inode gives each process the same OS lock. Closing the handle
|
|
35
|
+
# (including on process death) releases it. Never unlink these guard files.
|
|
36
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
with path.open("a+b") as handle:
|
|
38
|
+
while not _try_lock(handle):
|
|
39
|
+
if not wait:
|
|
40
|
+
yield False
|
|
41
|
+
return
|
|
42
|
+
time.sleep(0.025)
|
|
43
|
+
yield True
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Manifest:
|
|
47
|
+
def __init__(self, root: Path):
|
|
48
|
+
self.root = root
|
|
49
|
+
self.path = root / "manifest.json"
|
|
50
|
+
self.private = root / ".adshot"
|
|
51
|
+
|
|
52
|
+
def _read(self):
|
|
53
|
+
try:
|
|
54
|
+
with self.path.open(encoding="utf-8") as handle:
|
|
55
|
+
document = json.load(handle)
|
|
56
|
+
except FileNotFoundError:
|
|
57
|
+
return {"version": 1, "shots": {}}
|
|
58
|
+
if not isinstance(document, dict) or document.get("version") != 1:
|
|
59
|
+
raise ValueError("Unsupported manifest.json version. Restore the project manifest.")
|
|
60
|
+
shots = document.get("shots")
|
|
61
|
+
if not isinstance(shots, dict):
|
|
62
|
+
raise ValueError("Invalid manifest.json shots. Restore the project manifest.")
|
|
63
|
+
for shot_id, attempts in shots.items():
|
|
64
|
+
if not isinstance(attempts, list) or not attempts:
|
|
65
|
+
raise ValueError(f"Invalid manifest history for {shot_id}.")
|
|
66
|
+
for attempt in attempts:
|
|
67
|
+
if (not isinstance(attempt, dict) or not attempt.get("signature")
|
|
68
|
+
or attempt.get("state") not in {
|
|
69
|
+
"submitting", "needs_reconcile", "running", "publishing", "done", "failed"
|
|
70
|
+
}):
|
|
71
|
+
raise ValueError(f"Invalid manifest attempt for {shot_id}.")
|
|
72
|
+
price = attempt.get("price")
|
|
73
|
+
if (type(price) not in (int, float) or not math.isfinite(price) or price < 0
|
|
74
|
+
or not isinstance(attempt.get("base_url"), str)):
|
|
75
|
+
raise ValueError(f"Invalid manifest rate or endpoint for {shot_id}.")
|
|
76
|
+
if attempt["state"] in ("running", "publishing", "done", "failed"):
|
|
77
|
+
if not isinstance(attempt.get("task_id"), str) or not attempt["task_id"]:
|
|
78
|
+
raise ValueError(f"Missing task ID in manifest.json for {shot_id}.")
|
|
79
|
+
if attempt["state"] == "publishing":
|
|
80
|
+
backup = attempt.get("backup")
|
|
81
|
+
if backup != "" and not (isinstance(backup, str) and re.fullmatch(
|
|
82
|
+
re.escape(shot_id) + r"\.v[1-9][0-9]*\.mp4", backup)):
|
|
83
|
+
raise ValueError(f"Invalid backup filename in manifest.json for {shot_id}.")
|
|
84
|
+
return document
|
|
85
|
+
|
|
86
|
+
def _write(self, document):
|
|
87
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.private,
|
|
88
|
+
delete=False, suffix=".tmp") as handle:
|
|
89
|
+
tmp = Path(handle.name)
|
|
90
|
+
try:
|
|
91
|
+
json.dump(document, handle, indent=2, allow_nan=False)
|
|
92
|
+
handle.write("\n")
|
|
93
|
+
handle.flush()
|
|
94
|
+
os.fsync(handle.fileno())
|
|
95
|
+
except BaseException:
|
|
96
|
+
handle.close()
|
|
97
|
+
tmp.unlink(missing_ok=True)
|
|
98
|
+
raise
|
|
99
|
+
try:
|
|
100
|
+
os.replace(tmp, self.path)
|
|
101
|
+
finally:
|
|
102
|
+
tmp.unlink(missing_ok=True)
|
|
103
|
+
|
|
104
|
+
def snapshot(self):
|
|
105
|
+
with file_guard(self.private / "manifest.guard", wait=True):
|
|
106
|
+
return self._read()["shots"]
|
|
107
|
+
|
|
108
|
+
def record(self, shot_id, *, new=False, reconcile=False, **fields):
|
|
109
|
+
# Callers hold the per-shot claim. The shorter manifest lock also
|
|
110
|
+
# serializes read/modify/write across workers processing different shots.
|
|
111
|
+
with file_guard(self.private / "manifest.guard", wait=True):
|
|
112
|
+
document = self._read()
|
|
113
|
+
if reconcile:
|
|
114
|
+
task_id = fields["task_id"]
|
|
115
|
+
for owner, history in document["shots"].items():
|
|
116
|
+
if owner != shot_id and any(a.get("task_id") == task_id for a in history):
|
|
117
|
+
raise ValueError(f"Task ID already recorded for {owner}. Check provider history.")
|
|
118
|
+
attempts = document["shots"].setdefault(shot_id, [])
|
|
119
|
+
if new:
|
|
120
|
+
attempts.append(fields)
|
|
121
|
+
else:
|
|
122
|
+
attempts[-1].update(fields)
|
|
123
|
+
self._write(document)
|
|
124
|
+
return attempts[-1]
|
|
125
|
+
|
|
126
|
+
def discard_unsent_intent(self, shot_id):
|
|
127
|
+
"""Undo the caller's intent while it still holds the claim and has sent no POST."""
|
|
128
|
+
with file_guard(self.private / "manifest.guard", wait=True):
|
|
129
|
+
document = self._read()
|
|
130
|
+
attempts = document["shots"][shot_id]
|
|
131
|
+
if attempts[-1]["state"] != "submitting":
|
|
132
|
+
raise ValueError(f"{shot_id} has no unsent intent to discard.")
|
|
133
|
+
attempts.pop()
|
|
134
|
+
if not attempts:
|
|
135
|
+
del document["shots"][shot_id]
|
|
136
|
+
self._write(document)
|
|
137
|
+
|
|
138
|
+
@contextmanager
|
|
139
|
+
def claim(self, shot_id):
|
|
140
|
+
folder = self.private / "claims"
|
|
141
|
+
with file_guard(folder / f"{shot_id}.guard") as acquired:
|
|
142
|
+
if not acquired:
|
|
143
|
+
yield False
|
|
144
|
+
return
|
|
145
|
+
path = folder / f"{shot_id}.lock"
|
|
146
|
+
# The OS guard proves that any leftover exclusive claim is orphaned.
|
|
147
|
+
path.unlink(missing_ok=True)
|
|
148
|
+
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
149
|
+
os.close(fd)
|
|
150
|
+
try:
|
|
151
|
+
yield True
|
|
152
|
+
finally:
|
|
153
|
+
path.unlink(missing_ok=True)
|
|
154
|
+
|
|
155
|
+
def recover(self, ids):
|
|
156
|
+
snapshot = self.snapshot()
|
|
157
|
+
for shot_id in ids:
|
|
158
|
+
attempts = snapshot.get(shot_id)
|
|
159
|
+
if attempts and attempts[-1]["state"] == "submitting":
|
|
160
|
+
with self.claim(shot_id) as acquired:
|
|
161
|
+
if acquired and self.snapshot()[shot_id][-1]["state"] == "submitting":
|
|
162
|
+
self.record(shot_id, state="needs_reconcile")
|
|
163
|
+
return self.snapshot()
|
|
164
|
+
|
|
165
|
+
@contextmanager
|
|
166
|
+
def slot(self, count, stop):
|
|
167
|
+
while not stop.is_set():
|
|
168
|
+
for slot in range(count):
|
|
169
|
+
with file_guard(self.private / f"worker-{slot}.guard") as acquired:
|
|
170
|
+
if acquired:
|
|
171
|
+
yield True
|
|
172
|
+
return
|
|
173
|
+
stop.wait(0.05)
|
|
174
|
+
yield False
|