Metadata-Version: 2.4
Name: nutricamp
Version: 0.1.0a1
Summary: Official Python library for the NutriCamp API: meal photo analysis, HEI-2020 scoring and daily nutrition goals.
Author: NutriCamp
Author-email: NutriCamp <support@nutricamp.ai>
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Dist: httpx2>=2.12,<3
Requires-Dist: pydantic>=2.4,<3
Requires-Dist: typing-extensions>=4.14
Requires-Python: >=3.10
Project-URL: Homepage, https://platform.nutricamp.ai
Project-URL: Documentation, https://platform.nutricamp.ai/docs
Description-Content-Type: text/markdown

# NutriCamp Python library

The official Python library for the [NutriCamp API](https://platform.nutricamp.ai/docs): meal photo analysis with DietAI24, HEI-2020 diet scores and daily nutrition goals, grounded in USDA FNDDS 2019-2020.

It needs Python 3.10 or later and has typed models for every response.

## Install

```sh
pip install --pre nutricamp
# or
uv add --prerelease allow nutricamp
```

The library is in alpha, so installing it needs `--pre` until 0.1.0.

## Usage

Create a key at [platform.nutricamp.ai](https://platform.nutricamp.ai) and set it as `NUTRICAMP_API_KEY`.

```python
from pathlib import Path

from nutricamp import NutriCamp

client = NutriCamp()  # reads NUTRICAMP_API_KEY

with open("lunch.jpg", "rb") as f:
    meal = client.dietai24.analyze(image=f, locale="es-MX")
print(meal.meal_name, meal.totals["energy_kcal"])

meal = client.dietai24.analyze(image_url="https://example.com/lunch.jpg")

score = client.hei.score(
    meals=[{"eaten_at": "2026-09-20", "foods": [{"food_code": 11111000, "grams": 244}]}],
    timezone="America/New_York",
)
print(score.score, score.weakest)

goal = client.goal.calculate(sex="female", age=30, height=165, weight=60, goal="maintain")
print(goal.energy_kcal, goal.macros.protein_g)
```

`image` takes bytes, a binary file, a `Path`, or a `(filename, bytes)` tuple. Images must be JPEG, PNG, WEBP or GIF and 10 MB or less. A larger image raises `RequestTooLargeError` before anything is uploaded. Pass a URL as `image_url`, never as `image`.

## Streaming

A DietAI24 analysis usually takes 20 to 30 seconds. `stream()` sends progress while it runs:

```python
with client.dietai24.stream(image=Path("lunch.jpg")) as stream:
    for event in stream:
        if event.type == "progress":
            print(event.stage, event.progress)
    meal = stream.final_analysis()
```

Use `stream()` in a `with` block so the connection closes even if you leave the loop early.

## Async

```python
import asyncio

from nutricamp import AsyncNutriCamp


async def main() -> None:
    async with AsyncNutriCamp() as client:
        meal = await client.dietai24.analyze(image_url="https://example.com/lunch.jpg")
        async with client.dietai24.stream(image_url="https://example.com/lunch.jpg") as stream:
            async for event in stream:
                print(event.type)


asyncio.run(main())
```

## Errors

Errors from the API and the network are `nutricamp.NutriCampError` subclasses. Bad arguments, such as passing both `image` and `image_url`, raise `ValueError` or `TypeError` before any request. A response with a 4xx or 5xx status raises a subclass of `APIStatusError` with `status_code`, `code`, `message` and `request_id`. Branch on `code`, which is stable:

```python
import nutricamp

try:
    meal = client.dietai24.analyze(image=Path("lunch.jpg"))
except nutricamp.UnprocessableEntityError as e:
    print("No food found:", e.code)
except nutricamp.RateLimitError as e:
    print(e.code, "retry after", e.retry_after, "seconds")
except nutricamp.APIConnectionError:
    print("Network problem")
```

| Status | Class |
|---|---|
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 413 | `RequestTooLargeError` |
| 415 | `UnsupportedMediaTypeError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| 500 and other 5xx | `InternalServerError` |
| 503 | `ServiceUnavailableError` |
| no response | `APIConnectionError`, and `APITimeoutError` for timeouts |
| any other status | `APIStatusError` |

An `error` event inside a stream raises the same class its status would.

## Retries and timeouts

Connection errors, timeouts, 408, 409, 500, 502, 504, 503 other than `daily_capacity_reached`, and 429 `rate_limit_exceeded` are retried twice with exponential backoff, or after `Retry-After` for the rate limit. 429 `quota_exceeded` and 503 `daily_capacity_reached` are never retried, since they last until the next month or the next UTC day.

The server has no idempotency keys, so a retried DietAI24 request that the server had already accepted counts toward your quota again. For large batches, pass `max_retries=0` and handle errors yourself.

Requests time out after 60 seconds, and `dietai24.analyze` after 300. A timeout set on the client or with `with_options` replaces both defaults, including the one for `dietai24.analyze`, so keep it above the analysis time or set `timeout` per call. For streams the timeout is the longest wait between bytes, and the server sends a ping every 15 seconds.

```python
client = NutriCamp(max_retries=0)
client.with_options(timeout=120).hei.score(meals=meals)
client.goal.calculate(sex="male", age=40, height=180, weight=80, timeout=10)
```

## Options

| Option | Default |
|---|---|
| `api_key` | `NUTRICAMP_API_KEY` |
| `base_url` | `NUTRICAMP_BASE_URL`, else `https://api.nutricamp.ai` |
| `timeout` | 60 s, and 300 s for `dietai24.analyze` |
| `max_retries` | 2 |
| `http_client` | an `httpx2.Client` or `httpx2.AsyncClient` |

Call the API from your server. The API rejects keys sent from browsers.

## Data retention

NutriCamp stores no images, descriptions or results. Images and descriptions sent to DietAI24 are analyzed by OpenAI under OpenAI's API data usage policies. Outputs are estimates for informational and research use, not medical advice.
