alignlyPhotos 0.3.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.
@@ -0,0 +1,58 @@
1
+ """alignlyPhotos: check brand photos against rules written in code, with any vision model.
2
+
3
+ from alignlyphotos import Card, Rule, OpenAICompatibleModel, check_photo
4
+
5
+ card = Card(name="My brand", rules=[Rule(name="Bright, natural light", meets=[...], misses=[...])])
6
+ model = OpenAICompatibleModel.from_env()
7
+ result = check_photo("photo.jpg", card, model)
8
+ for r in result.rules:
9
+ print(r.name, r.level, r.justification)
10
+
11
+ The building blocks (request builders, the picture-kind check, the reply reader) are in
12
+ `alignlyphotos.scorer`, the same module the Alignly app scores with.
13
+ """
14
+
15
+ from alignlyphotos import scorer
16
+ from alignlyphotos.adapters import AnthropicModel, model_from_env
17
+ from alignlyphotos.batch import check_many, find_photos, write_csv
18
+ from alignlyphotos.card import Card, InvalidCard, Rule, load_card
19
+ from alignlyphotos.check import CallInfo, PhotoResult, RuleResult, check_photo
20
+ from alignlyphotos.evaluate import evaluate, read_labels
21
+ from alignlyphotos.model import (
22
+ ModelBudgetExceeded,
23
+ ModelReply,
24
+ ModelUnavailable,
25
+ OpenAICompatibleModel,
26
+ VisionModel,
27
+ )
28
+ from alignlyphotos.report import write_html
29
+ from alignlyphotos.scorer import AnswerCutOff, AnswerFailed
30
+
31
+ __version__ = "0.3.0"
32
+
33
+ __all__ = [
34
+ "AnswerCutOff",
35
+ "AnswerFailed",
36
+ "AnthropicModel",
37
+ "CallInfo",
38
+ "Card",
39
+ "InvalidCard",
40
+ "ModelBudgetExceeded",
41
+ "ModelReply",
42
+ "ModelUnavailable",
43
+ "OpenAICompatibleModel",
44
+ "PhotoResult",
45
+ "Rule",
46
+ "RuleResult",
47
+ "VisionModel",
48
+ "check_many",
49
+ "check_photo",
50
+ "evaluate",
51
+ "find_photos",
52
+ "load_card",
53
+ "model_from_env",
54
+ "read_labels",
55
+ "scorer",
56
+ "write_csv",
57
+ "write_html",
58
+ ]
@@ -0,0 +1,147 @@
1
+ """Ready-made models besides OpenAICompatibleModel, and picking one from the environment.
2
+
3
+ AnthropicModel runs alignlyphotos on Claude. Install it with `pip install alignlyPhotos[anthropic]`.
4
+ Claude does not return token log-probabilities.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+
12
+ from alignlyphotos.model import (
13
+ ModelBudgetExceeded,
14
+ ModelReply,
15
+ ModelUnavailable,
16
+ OpenAICompatibleModel,
17
+ )
18
+
19
+ PROVIDERS = ("openai", "anthropic")
20
+
21
+
22
+ class AnthropicModel:
23
+ """Claude through the Anthropic API. The JSON shape is enforced by asking Claude to call
24
+ one tool whose input schema is the schema alignlyphotos wants."""
25
+
26
+ def __init__(self, *, api_key: str, model: str, timeout: float = 120.0, client=None):
27
+ self.api_key = api_key
28
+ self.model = model
29
+ self.timeout = timeout
30
+ self._client = client # for tests; normally made on each call
31
+
32
+ @classmethod
33
+ def from_env(cls) -> AnthropicModel:
34
+ return cls(
35
+ api_key=os.environ.get("ANTHROPIC_API_KEY")
36
+ or os.environ.get("VISION_MODEL_API_KEY", ""),
37
+ model=os.environ.get("VISION_MODEL_NAME", ""),
38
+ timeout=float(os.environ.get("VISION_MODEL_TIMEOUT_SECONDS", "120")),
39
+ )
40
+
41
+ def complete(
42
+ self,
43
+ messages: list[dict],
44
+ schema: dict,
45
+ *,
46
+ name: str = "alignlyphotos",
47
+ max_tokens: int = 2048,
48
+ timeout: float | None = None,
49
+ logprobs: bool = False,
50
+ require_stop: bool = True,
51
+ ) -> ModelReply:
52
+ if not (self.api_key and self.model):
53
+ raise ModelUnavailable("not_configured")
54
+ try:
55
+ import anthropic
56
+ except ImportError:
57
+ raise ModelUnavailable("not_configured") from None
58
+
59
+ client = self._client or anthropic.Anthropic(
60
+ api_key=self.api_key, timeout=timeout or self.timeout, max_retries=0
61
+ )
62
+ system, chat = _to_anthropic(messages)
63
+ tool_name = (name or "answer")[:64]
64
+ try:
65
+ reply = client.messages.create(
66
+ model=self.model,
67
+ max_tokens=max_tokens,
68
+ temperature=0,
69
+ system=system,
70
+ messages=chat,
71
+ tools=[
72
+ {
73
+ "name": tool_name,
74
+ "description": "Give the answer. Fill every field the schema asks for.",
75
+ "input_schema": schema,
76
+ }
77
+ ],
78
+ tool_choice={"type": "tool", "name": tool_name},
79
+ )
80
+ except anthropic.APITimeoutError:
81
+ raise ModelUnavailable("timeout") from None
82
+ except anthropic.APIConnectionError:
83
+ raise ModelUnavailable("connection") from None
84
+ except anthropic.APIStatusError as exc:
85
+ if exc.status_code == 400 and "too long" in str(exc).lower():
86
+ raise ModelBudgetExceeded from None
87
+ raise ModelUnavailable("http", exc.status_code) from None
88
+
89
+ if reply.stop_reason == "max_tokens" and require_stop:
90
+ raise ModelBudgetExceeded
91
+ block = next((b for b in reply.content if getattr(b, "type", "") == "tool_use"), None)
92
+ if block is None:
93
+ raise ModelUnavailable("bad_finish", request_id=getattr(reply, "id", "") or "")
94
+ usage = getattr(reply, "usage", None)
95
+ return ModelReply(
96
+ json.dumps(block.input),
97
+ self.model,
98
+ getattr(reply, "model", self.model) or self.model,
99
+ None,
100
+ "length" if reply.stop_reason == "max_tokens" else "stop",
101
+ getattr(reply, "id", "") or "",
102
+ None
103
+ if usage is None
104
+ else {"prompt_tokens": usage.input_tokens, "output_tokens": usage.output_tokens},
105
+ )
106
+
107
+
108
+ def _to_anthropic(messages: list[dict]) -> tuple[str, list[dict]]:
109
+ """OpenAI-style messages to Anthropic's: the system text apart, image data URLs as
110
+ base64 image blocks."""
111
+ system = []
112
+ chat = []
113
+ for m in messages:
114
+ if m["role"] == "system":
115
+ system.append(m["content"] if isinstance(m["content"], str) else str(m["content"]))
116
+ continue
117
+ content = m["content"]
118
+ if isinstance(content, str):
119
+ blocks = [{"type": "text", "text": content}]
120
+ else:
121
+ blocks = []
122
+ for part in content:
123
+ if part.get("type") == "text":
124
+ blocks.append({"type": "text", "text": part["text"]})
125
+ elif part.get("type") == "image_url":
126
+ url = part["image_url"]["url"]
127
+ header, data = url.split(",", 1)
128
+ media_type = header.removeprefix("data:").split(";")[0]
129
+ blocks.append(
130
+ {
131
+ "type": "image",
132
+ "source": {"type": "base64", "media_type": media_type, "data": data},
133
+ }
134
+ )
135
+ chat.append({"role": m["role"], "content": blocks})
136
+ return "\n\n".join(system), chat
137
+
138
+
139
+ def model_from_env(provider: str | None = None):
140
+ """The model named by `provider` or VISION_MODEL_PROVIDER: openai (any OpenAI-compatible
141
+ server, the default) or anthropic."""
142
+ provider = (provider or os.environ.get("VISION_MODEL_PROVIDER") or "openai").lower()
143
+ if provider == "openai":
144
+ return OpenAICompatibleModel.from_env()
145
+ if provider == "anthropic":
146
+ return AnthropicModel.from_env()
147
+ raise ValueError(f"unknown provider '{provider}', use one of: {', '.join(PROVIDERS)}")
alignlyphotos/batch.py ADDED
@@ -0,0 +1,144 @@
1
+ """Check many photos: a few at a time, a cap on model calls in flight, one failure never stops
2
+ the rest, CSV out."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import csv
7
+ import threading
8
+ from concurrent.futures import ThreadPoolExecutor, as_completed
9
+ from pathlib import Path
10
+
11
+ from alignlyphotos.card import Card, InvalidCard
12
+ from alignlyphotos.check import DEFAULT_RETRIES, call_groups, check_photo, model_label
13
+ from alignlyphotos.model import ModelUnavailable, VisionModel
14
+
15
+ PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png"}
16
+ DEFAULT_WORKERS = 4
17
+ DEFAULT_MAX_CALLS = 16
18
+
19
+
20
+ def find_photos(paths) -> list[Path]:
21
+ """Expand files and folders into a sorted list of photos. Folders are searched one level
22
+ deep for .jpg, .jpeg and .png. Files are kept as given, whatever their suffix."""
23
+ found = []
24
+ for raw in paths:
25
+ path = Path(raw)
26
+ if path.is_dir():
27
+ found += sorted(
28
+ p for p in path.iterdir() if p.is_file() and p.suffix.lower() in PHOTO_SUFFIXES
29
+ )
30
+ else:
31
+ found.append(path)
32
+ return list(dict.fromkeys(found)) # drop repeats, keep order
33
+
34
+
35
+ class _Capped:
36
+ """A model that lets at most `limit` calls run at once, across every photo."""
37
+
38
+ def __init__(self, model: VisionModel, limit: int):
39
+ self._model = model
40
+ self._slots = threading.BoundedSemaphore(max(1, limit))
41
+ self.label = model_label(model) # the cache key names the real model
42
+
43
+ def complete(self, *args, **kwargs):
44
+ with self._slots:
45
+ return self._model.complete(*args, **kwargs)
46
+
47
+
48
+ def check_many(
49
+ photos,
50
+ card: Card,
51
+ model: VisionModel,
52
+ *,
53
+ calls="per_rule",
54
+ workers: int = DEFAULT_WORKERS,
55
+ max_calls: int = DEFAULT_MAX_CALLS,
56
+ retries: int = DEFAULT_RETRIES,
57
+ user_context: str = "",
58
+ cache_dir=None,
59
+ on_result=None,
60
+ ) -> list[dict]:
61
+ """Check every photo. Returns one row per photo, in the order given:
62
+ {"photo", "ok", "result" (a PhotoResult), "error"}. `workers` photos are checked at once
63
+ and at most `max_calls` model calls run at once in all. A photo that fails gets ok=False
64
+ and the error message, and the others carry on. `on_result(row, done, total)` is called as
65
+ each photo finishes.
66
+ """
67
+ if not isinstance(card, Card):
68
+ raise InvalidCard(["card must be a Card"])
69
+ call_groups(card, calls) # a bad packing stops the run before any model call
70
+ photos = [str(p) for p in photos]
71
+ capped = _Capped(model, max_calls)
72
+ total, done = len(photos), 0
73
+
74
+ def one(photo):
75
+ try:
76
+ result = check_photo(
77
+ photo,
78
+ card,
79
+ capped,
80
+ calls=calls,
81
+ user_context=user_context,
82
+ retries=retries,
83
+ cache_dir=cache_dir,
84
+ )
85
+ return {"photo": photo, "ok": True, "result": result, "error": None}
86
+ except Exception as exc: # noqa: BLE001 any failure belongs to this photo only
87
+ if stops_everything(exc):
88
+ raise
89
+ return {"photo": photo, "ok": False, "result": None, "error": describe(exc)}
90
+
91
+ rows = [None] * total
92
+ pool = ThreadPoolExecutor(max_workers=max(1, workers))
93
+ try:
94
+ futures = {pool.submit(one, photo): i for i, photo in enumerate(photos)}
95
+ for future in as_completed(futures):
96
+ row = future.result()
97
+ rows[futures[future]] = row
98
+ done += 1
99
+ if on_result:
100
+ on_result(row, done, total)
101
+ except BaseException:
102
+ pool.shutdown(wait=False, cancel_futures=True) # don't wait for photos not started
103
+ raise
104
+ pool.shutdown()
105
+ return rows
106
+
107
+
108
+ def stops_everything(exc: Exception) -> bool:
109
+ """Errors every photo would hit: no model settings, a wrong key or a wrong model name."""
110
+ if not isinstance(exc, ModelUnavailable):
111
+ return False
112
+ return exc.kind == "not_configured" or (
113
+ exc.kind == "http" and exc.status_code in (401, 403, 404)
114
+ )
115
+
116
+
117
+ def describe(exc: Exception) -> str:
118
+ kind = getattr(exc, "kind", None)
119
+ if kind == "http":
120
+ return f"model unavailable (http {getattr(exc, 'status_code', '')})"
121
+ if kind:
122
+ return f"model unavailable ({kind})"
123
+ return f"{type(exc).__name__}: {str(exc) or type(exc).__name__}"[:300]
124
+
125
+
126
+ def write_csv(rows: list[dict], path, card: Card) -> None:
127
+ """One row per photo, in the order checked. After the summary columns comes one column
128
+ per rule (its name) with the level. Failed photos have an error and no levels."""
129
+ names = [rule.name for rule in card.rules]
130
+ header = ["photo", "status", "misses", "mixed", "meets", "error", *names]
131
+ with open(path, "w", newline="", encoding="utf-8") as handle:
132
+ writer = csv.writer(handle)
133
+ writer.writerow(header)
134
+ for row in rows:
135
+ if not row["ok"]:
136
+ blanks = [""] * len(names)
137
+ writer.writerow([row["photo"], "failed", "", "", "", row["error"], *blanks])
138
+ continue
139
+ result = row["result"]
140
+ levels = {r.name: r.level for r in result.rules}
141
+ counts = [result.count(level) for level in ("misses", "mixed", "meets")]
142
+ writer.writerow(
143
+ [row["photo"], "ok", *counts, ""] + [levels.get(name, "") for name in names]
144
+ )
alignlyphotos/card.py ADDED
@@ -0,0 +1,147 @@
1
+ """A brand's photo rules, written in code.
2
+
3
+ card = Card(name="Capital One photography", rules=[
4
+ Rule(
5
+ name="Bright, natural light",
6
+ applies_to=None, # every photo
7
+ meets=["The scene is bright and evenly lit, like daylight."],
8
+ misses=["Shadows across faces are dark and hard-edged."],
9
+ mixed=["The light is mostly natural, but a small area has hard shadows."],
10
+ not_a_fault=["Soft, gradual shadows that give faces shape are fine."],
11
+ ),
12
+ ])
13
+
14
+ The model reads each rule as written: its name and its Meets, Misses, Mixed and Not a fault
15
+ lines. Each rule gets a hidden id made from its name; it names the rule inside the model call
16
+ and is never shown.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import runpy
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+
27
+ from alignlyphotos import scorer
28
+
29
+
30
+ class InvalidCard(ValueError):
31
+ """A rule or card is not usable. `problems` says why."""
32
+
33
+ def __init__(self, problems: list[str]):
34
+ super().__init__("; ".join(problems)[:600])
35
+ self.problems = problems
36
+
37
+
38
+ def _lines(value) -> tuple[str, ...]:
39
+ if isinstance(value, str): # a lone string would otherwise become one line per character
40
+ return (value,)
41
+ return tuple(value or ())
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Rule:
46
+ """One rule. `applies_to` is the kind of photo it judges, or None for every photo.
47
+ `meets` and `misses` need at least one line each; `mixed` and `not_a_fault` are optional.
48
+ """
49
+
50
+ name: str
51
+ applies_to: str | None = None
52
+ meets: tuple[str, ...] = ()
53
+ misses: tuple[str, ...] = ()
54
+ mixed: tuple[str, ...] = ()
55
+ not_a_fault: tuple[str, ...] = ()
56
+
57
+ def __post_init__(self):
58
+ for kind in scorer.LINE_KINDS:
59
+ object.__setattr__(self, kind, _lines(getattr(self, kind)))
60
+ if isinstance(self.applies_to, str):
61
+ object.__setattr__(self, "applies_to", scorer.applies_to(self.applies_to))
62
+ problems = _rule_problems(self)
63
+ if problems:
64
+ raise InvalidCard(problems)
65
+
66
+
67
+ def _rule_problems(rule: Rule) -> list[str]:
68
+ name = rule.name if isinstance(rule.name, str) else ""
69
+ label = f"rule '{name.strip()}'" if name.strip() else "a rule"
70
+ problems = []
71
+ if not _is_line(name):
72
+ problems.append(f"{label}: give it a name on one line")
73
+ if rule.applies_to is not None and not _is_line(rule.applies_to):
74
+ problems.append(f"{label}: applies_to must be text on one line, or None")
75
+ for kind, title in scorer.LINE_KINDS.items():
76
+ lines = getattr(rule, kind)
77
+ if kind in scorer.REQUIRED_LINES and not lines:
78
+ problems.append(f"{label}: needs at least one {title} line")
79
+ if not all(_is_line(line) for line in lines):
80
+ problems.append(f"{label}: every {title} line must be non-empty text on one line")
81
+ return problems
82
+
83
+
84
+ def _is_line(text) -> bool:
85
+ return isinstance(text, str) and bool(text.strip()) and "\n" not in text and "\r" not in text
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Card:
90
+ """A brand's name and all its rules. Rule names must be unique."""
91
+
92
+ name: str
93
+ rules: tuple[Rule, ...] = ()
94
+ _ids: tuple[str, ...] = field(default=(), init=False, repr=False, compare=False)
95
+
96
+ def __post_init__(self):
97
+ object.__setattr__(self, "rules", tuple(self.rules))
98
+ problems = []
99
+ if not _is_line(self.name):
100
+ problems.append("give the card a name on one line")
101
+ if not self.rules:
102
+ problems.append("a card needs at least one rule")
103
+ if not all(isinstance(rule, Rule) for rule in self.rules):
104
+ problems.append("every rule must be a Rule")
105
+ raise InvalidCard(problems)
106
+ if problems:
107
+ raise InvalidCard(problems)
108
+ used: set[str] = set()
109
+ object.__setattr__(self, "_ids", tuple(scorer.rule_id(r.name, used) for r in self.rules))
110
+ problems = scorer.validate_card(self.to_dict()) # the app's rules: unique names, lengths
111
+ if problems:
112
+ raise InvalidCard(problems)
113
+
114
+ def to_dict(self) -> dict:
115
+ """The card as the scorer and the Alignly app store it (card-meta-4), ids included."""
116
+ return {
117
+ "card_version": scorer.CARD_VERSION,
118
+ "rules": [
119
+ {
120
+ "id": rule_id,
121
+ "name": rule.name,
122
+ "applies_to": rule.applies_to,
123
+ **{kind: list(getattr(rule, kind)) for kind in scorer.LINE_KINDS},
124
+ }
125
+ for rule_id, rule in zip(self._ids, self.rules, strict=True)
126
+ ],
127
+ }
128
+
129
+ def fingerprint(self) -> str:
130
+ """A short hash of the name and every rule, to tell card versions apart."""
131
+ data = json.dumps([self.name, self.to_dict()], sort_keys=True).encode()
132
+ return hashlib.sha256(data).hexdigest()[:16]
133
+
134
+ def ids_by_name(self) -> dict[str, str]:
135
+ return {rule.name: rule_id for rule_id, rule in zip(self._ids, self.rules, strict=True)}
136
+
137
+
138
+ def load_card(path) -> Card:
139
+ """Run a Python file and return the `card` it defines. Only load files you trust: this
140
+ runs the file's code."""
141
+ path = Path(path)
142
+ if not path.is_file():
143
+ raise InvalidCard([f"no card file at {path}"])
144
+ card = runpy.run_path(str(path)).get("card")
145
+ if not isinstance(card, Card):
146
+ raise InvalidCard([f"{path.name} must define `card = Card(...)`"])
147
+ return card