Metadata-Version: 2.5
Name: alignlyPhotos
Version: 0.3.0
Summary: Check brand photos against photo rules written in code, with a vision model
Requires-Python: >=3.10
Requires-Dist: jsonschema>=4.23
Requires-Dist: openai<3,>=2
Requires-Dist: pillow<13,>=11
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40; extra == 'anthropic'
Provides-Extra: mcp
Requires-Dist: mcp>=1.23; extra == 'mcp'
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# alignlyPhotos

Check brand photos against your brand's photo rules with a vision model.

You write the rules in Python. For each photo, alignlyPhotos asks the model about every rule and
gives you, per rule, a level (**meets**, **mixed** or **misses**, or **cannot_assess** /
**not_applicable**) and a short justification saying what in the photo led to it. It is the
same scorer the Alignly app uses, so a card gives the same calls and answers in both.

Every answer is a suggestion for a person to review, not an approval.

## Install

```
pip install alignlyPhotos
```

Needs Python 3.10 or newer. Extras: `alignlyPhotos[anthropic]` to run on Claude,
`alignlyPhotos[mcp]` to use it from a chatbot.

## Set up the model

alignlyPhotos works with any OpenAI-compatible vision model (for example Qwen3-VL served by vLLM,
Ollama, or OpenAI itself). Set three environment variables, with no quotes inside the values:

```
export VISION_MODEL_BASE_URL=https://your-server/v1
export VISION_MODEL_API_KEY=your-key
export VISION_MODEL_NAME=your-model-name
```

On Windows PowerShell use `$env:VISION_MODEL_BASE_URL="https://your-server/v1"` and so on.

To use Claude instead: `pip install alignlyPhotos[anthropic]`, then set
`VISION_MODEL_PROVIDER=anthropic`, `ANTHROPIC_API_KEY` and `VISION_MODEL_NAME` (a Claude model
name).

## 1. Write the card

A card is a name and all of a brand's rules. Each rule has:

- `name`: short and unique within the card.
- `applies_to`: the kind of photo the rule is about, in plain words, or `None` for every photo.
- `meets`: one or more lines saying what a photo that follows the rule visibly shows.
- `misses`: one or more lines naming the visible signs that a photo breaks it.
- `mixed` (optional): when the photo is in between.
- `not_a_fault` (optional): things that look like a fault but are fine.

```python
# card.py
from alignlyphotos import Card, Rule

card = Card(
    name="Capital One photography",
    rules=[
        Rule(
            name="Bright, natural light",
            applies_to=None,
            meets=["The scene is bright and evenly lit, like daylight or soft window light."],
            misses=[
                "Shadows across faces or the main subject are dark and hard-edged.",
                "Large parts of the photo are dark or murky.",
            ],
            mixed=["The light is mostly natural, but a small area has hard shadows."],
            not_a_fault=["Soft, gradual shadows that give faces and objects shape are fine."],
        ),
        Rule(
            name="Real, unposed moments",
            applies_to="lifestyle photos of people in an everyday situation",
            meets=["People are caught in the middle of a real activity."],
            misses=["People have stopped what they are doing to pose for the camera."],
        ),
    ],
)
```

The model reads each rule exactly as written, one line per sentence. Write lines about what can
be seen in the photo. A rule without a `meets` or `misses` line, an empty line, or two rules with
the same name are refused when the card is made.

## 2. Check photos

```python
from alignlyphotos import OpenAICompatibleModel, check_photo
from card import card

model = OpenAICompatibleModel.from_env()
result = check_photo("photo.jpg", card, model)
for r in result.rules:
    print(r.name, r.level, r.justification)
```

By default each rule is asked in its own model call, and all of a photo's calls are sent at
once. When some rules apply only to a kind of photo, one more call asks which of those kinds the
photo is; a rule whose kind the photo is not comes back `not_applicable`, decided by that check.
You can pack rules into fewer calls; the result has the same shape either way:

```python
check_photo("photo.jpg", card, model, calls="one")  # every rule in one call
check_photo("photo.jpg", card, model, calls=[["Rule A", "Rule B"], ["Rule C"]])
```

Rules left out of a `calls` list get a call of their own. One rule per call caught the most
faults in testing; packing saves tokens.

A result has:

- `rules`: one `RuleResult` per rule, in card order: `name`, `level`, `justification`,
  `applies_to` and `decided_by` (`model` or `picture_kind_check`).
- `card`, `card_fingerprint`, `prompt_version` and `model`: what produced it.
- `calls`: each call's rules, seconds, tries and token counts; `seconds`, `prompt_tokens` and
  `output_tokens` for the photo; `picture_kinds`, the kind check's answers.
- `to_dict()` for JSON, `count("misses")`, `rule("Rule A")`.

Other options: `user_context="live event"` (background for the model), `retries=2` (extra tries
when a call times out, the server is busy or a reply is broken), `max_calls=8` (calls at once),
`cache_dir=".alignlyphotos-cache"` (a photo checked with the same card, settings, prompt version
and model is read back instead of sent again). `photo` can be a path or the file's bytes.

Many photos:

```python
from alignlyphotos import check_many, write_csv, write_html

rows = check_many(["a.jpg", "b.jpg"], card, model, workers=4, max_calls=16)
write_csv(rows, "results.csv", card)  # one row per photo, a level column per rule
write_html(rows, "report.html")  # thumbnails, levels and justifications
```

`workers` photos run at once, and at most `max_calls` model calls are in flight over all of
them. A photo that fails gets an error in its row and the rest carry on.

## Command line

The card comes from a Python file that defines `card`:

```
alignlyphotos check photo.jpg --card card.py
alignlyphotos check photos/ --card card.py --csv results.csv --html report.html
alignlyphotos check photos/ --card card.py --calls one
alignlyphotos check photos/ --card card.py --calls "Rule A|Rule B;Rule C"
```

Options: `--context`, `--workers 4`, `--max-calls 16`, `--retries 2`, `--cache DIR`, `--json`,
`-q`. Exit codes: 0 all good, 1 something failed.

Only load card files you trust: loading one runs its code.

## Check accuracy against people's labels

Make a CSV with a `photo` column (path relative to the CSV) and one column per rule, named
exactly as the rule, holding `meets`, `mixed`, `misses`, `cannot_assess` or `not_applicable`.
Blank cells are skipped.

```
photo,"Bright, natural light","Real, unposed moments"
shoot1/a.jpg,meets,meets
shoot1/b.jpg,misses,
```

```
alignlyphotos evaluate labels.csv --card card.py
```

The report shows how often alignlyPhotos gave the label's level, a label-against-alignlyPhotos
table, per rule agreement with the misses caught and the misses given wrongly, and the
disagreements with alignlyPhotos's justification. In Python: `read_labels` and `evaluate`.

## Using a different model

Anything with a matching `complete` method works. Pass it in place of `OpenAICompatibleModel`:

```python
from alignlyphotos import ModelReply


class MyModel:
    def complete(
        self,
        messages,
        schema,
        *,
        name="",
        max_tokens=2048,
        timeout=None,
        logprobs=False,
        require_stop=True,
    ):
        # call your model with the OpenAI-style messages, ask for JSON matching `schema`
        return ModelReply(
            content=json_text,
            requested_model="mine",
            returned_model="mine",
            finish_reason="stop",
            usage={"prompt_tokens": 1200, "output_tokens": 90},
        )
```

The model has to accept an image with text and return JSON in the requested shape. Return
`finish_reason="length"` when the reply was cut off. `usage` is optional. The prompts were
tuned on Qwen3-VL, so check a new model with `alignlyphotos evaluate` first.

## Building on top

`alignlyphotos.scorer` holds the parts the Alignly app and `check_photo` both use, as plain
functions on the card's dictionary form (`card.to_dict()`):

- `requests_for(card_dict, image_data_url, groups=..., ...)`: every model call of one photo as
  data (`CallRequest`: messages, JSON schema, output budget), the picture-kind check first.
- `read_reply(request, content, finish_reason)`: checks one reply against its schema and
  returns it, or raises `AnswerFailed` / `AnswerCutOff`.
- `answers_from(card_dict, replies_by_call_key)`: one answer per rule, applying the kind check.
- `call_ids(card_dict)`: the id each rule goes by inside the calls, made from its current name,
  so a card with other stored ids (the app keeps them on rename) sends the same calls.
- `kinds_of`, `rule_block`, `rules_schema`, `SYSTEM`, `INSTRUCTION`, `KINDS_PROMPT`,
  `PROMPT_VERSION`.

`alignlyphotos.images.prepare(data).data_url()` makes the photo copy the model sees (upright,
sRGB, at most 1024 px, JPEG without metadata).

## Use it from a chatbot (MCP)

```
pip install alignlyPhotos[mcp]
```

Put your card files in `~/.alignlyphotos/cards` (change with `ALIGNLYPHOTOS_HOME`), for example
`~/.alignlyphotos/cards/capital-one.py`. Then add alignlyPhotos to Claude Desktop's config
(`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "alignlyphotos": {
      "command": "alignlyphotos-mcp",
      "env": {
        "VISION_MODEL_BASE_URL": "https://your-server/v1",
        "VISION_MODEL_API_KEY": "your-key",
        "VISION_MODEL_NAME": "your-model-name"
      }
    }
  }
}
```

If Claude Desktop can't find `alignlyphotos-mcp`, use its full path instead (run
`which alignlyphotos-mcp` on Mac/Linux or `where alignlyphotos-mcp` on Windows to get it).

Then ask things like "check the photos in ~/shoot1 against capital-one". The chatbot can list
cards and check photos and folders. It picks cards by name from the cards folder only and cannot
make or change them.

## Moving from 0.2 to 0.3

The package was called `brandcheck` up to 0.2. Uninstall it and install `alignlyPhotos`, then
change `import brandcheck` to `import alignlyphotos`.

0.3 breaks 0.2 code and cards. It removes `make_card` (AI guideline-to-card), JSON and
Markdown cards, 0-100 scores, weights, must-pass, the brand score, confidence, mood words, the
photo summary, `show-card`, `edit-card` and `--min-score`.

- Rewrite the card in Python as `card = Card(...)`. For each old criterion write a `Rule`:
  what the 100 anchor described goes in `meets`, what the 0 or 25 anchors described goes in
  `misses` (one visible sign per line), and drop weights and must-pass. Rule names must be
  unique.
- `check_photo(photo, card, model)` returns a `PhotoResult`: read `result.rules` (each with
  `level` and `justification`) instead of `result["brand_score"]` and `result["answers"]`.
  Drop `summary=` and `logprobs=`.
- Command line: `alignlyphotos score photos/ --card card.json` is now
  `alignlyphotos check photos/ --card card.py`. Labels for `evaluate` hold a level per rule name
  instead of scores and `on_brand`.
- MCP cards are Python files in `~/.alignlyphotos/cards`; the chatbot no longer makes or edits
  them.

## Run the tests

```
pip install -e ".[test,mcp,anthropic]"
pytest
```

The tests use a fake model, so they need no network or API key.
