Metadata-Version: 2.4
Name: neuralhive
Version: 2.1.0
Summary: NeuralHive Python SDK for model access and inference
Author-email: Muhammad Khazq <mrkhaziq.dev@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://neuralhive.ai
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.33.1
Requires-Dist: Pillow>=12.2.0
Requires-Dist: typing_extensions>=4.12.0
Requires-Dist: questionary>=2.1.0
Dynamic: license-file

# NeuralHive SDK

Python SDK client for NeuralHive model access.

## Installation

```bash
pip install neuralhive
```

## Authentication Setup

### Option 1: Configure once (recommended)

```bash
neuralhive configure --api-key nh_live_your_api_key
```

Then use SDK without passing key in code.

### Option 2: Environment variable

```bash
export NEURALHIVE_API_KEY="nh_live_your_api_key"
```

### Option 3: Pass key directly in code

```python
neuralhive = NeuralhiveClient("nh_live_your_api_key")
```

## Quick Start

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()
models = neuralhive.list_models()
print(models)
```

> 2.0.0: `Client` is renamed to `NeuralhiveClient`.

## Client settings and threads

```python
from concurrent.futures import ThreadPoolExecutor

from neuralhive import NeuralhiveClient

with NeuralhiveClient(timeout=600, max_retries=2, poll_interval=5, job_timeout=5000, max_connections=20) as neuralhive:
    with ThreadPoolExecutor(max_workers=8) as pool:
        vectors = list(pool.map(lambda t: neuralhive.embed(text=t), ["a bus", "a dog"]))
```

- One client is thread-safe. Share it between threads.
- Each client keeps its own API key, so clients with different keys can run in the same process.
- Every successful inference call is billed, also in parallel.

### List inputs

`generate_image`, `edit_image`, `transcribe_audio`, `parse_document` and `generate_3d` also take a list. The SDK runs the items in parallel and returns a list of results in the same order. Each item is its own job and its own bill. If some items fail, `BatchError` is raised; `error.results` keeps the finished items and `error.errors` maps index to exception.

```python
results = neuralhive.parse_document(["a.pdf", "b.pdf"], export_to="parsed")
```

## Finetune

### Start finetuning

- Run `neuralhive finetune`.
- Select a task, model, and dataset.
- Review the final cost and start training.

### Dataset requirements

- For `slm`, provide a file path.
- For other finetune tasks, provide a directory path.
- You can save a local dataset for future use.

### Track progress

- Run `neuralhive trainings`.
- View active training names and progress.
- You can leave training running in the background.

## Usage

### 1. Get model details

```python
model = neuralhive.get_model("your_model_id")
print(model)
```

### 2. Run model inference

```python
from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.detect(
    image_path="/absolute/path/to/image.jpg",
)
```

For all other methods, see **API Reference** below.

## API Reference

### `NeuralhiveClient(api_key: str | None = None)`

| Parameter | Type  | Required | Description             |
| --------- | ----- | -------- | ----------------------- |
| `api_key` | `str` | No       | Your NeuralHive API key |

Returns:

- `NeuralhiveClient` instance

### `neuralhive.list_models()`

Parameters:

- None

Returns:

- `list[dict]` containing allowed models for this API key

### `neuralhive.get_model(model_id)`

| Parameter  | Type  | Required | Description             |
| ---------- | ----- | -------- | ----------------------- |
| `model_id` | `str` | Yes      | Target model identifier |

Returns:

- `dict` with model details

### `neuralhive.detect(image_path, model_id=None, prompt=None, export_to=None)`

| Parameter    | Type  | Required | Description                                  |
| ------------ | ----- | -------- | -------------------------------------------- |
| `image_path` | `str` | Yes      | Local image file path                        |
| `model_id`   | `str` | No       | Target model identifier                      |
| `prompt`     | `str` | No       | Optional prompt (required for SAM-like IDs)  |
| `export_to`  | `str` | No       | Export directory path for box-rendered image |

Notes:

- If `model_id` is not provided, SDK uses default `object_detection` model from your allowed models.

Returns:

- `dict`

### `neuralhive.segment(image_path, model_id=None, prompt=None, export_to=None)`

| Parameter    | Type  | Required | Description                                   |
| ------------ | ----- | -------- | --------------------------------------------- |
| `image_path` | `str` | Yes      | Local image file path                         |
| `model_id`   | `str` | No       | Target model identifier                       |
| `prompt`     | `str` | No       | Optional prompt (required for SAM-like IDs)   |
| `export_to`  | `str` | No       | Export directory path for mask-rendered image |

Returns:

- `dict`

Notes:

- If `model_id` is not provided, SDK uses default `instance_segmentation` model from your allowed models.

### `neuralhive.detect_and_segment(image_path, prompt, export_to=None)`

| Parameter    | Type  | Required | Description                                       |
| ------------ | ----- | -------- | ------------------------------------------------- |
| `image_path` | `str` or `list[str]` | Yes      | Local image file path, or a list of paths         |
| `prompt`     | `str` or `list[str]` | Yes      | What to find, e.g. `"hard hat, vest"`. With a list of images: one prompt for all, or one per image |
| `export_to`  | `str` | No       | Export directory path for mask+box-rendered image |

Notes:

- Uses SAM3 / prompt-based segmentation models.
- A list of images is sent 8 images per request; longer lists are split and run in parallel.

Returns:

- One image: `dict`
- A list of images: `list[dict]`, one per image, with `masks`, `boxes`, `scores`, `labels`, `concepts`, `dropped_concepts`, `image_height`, `image_width`

### `neuralhive.recognize(image_path)`

| Parameter    | Type  | Required | Description           |
| ------------ | ----- | -------- | --------------------- |
| `image_path` | `str` | Yes      | Local image file path |

Returns:

- `list[list[float]]` (face embeddings per detected face)

### `neuralhive.reidentify(image_path, model_id=None)`

| Parameter    | Type  | Required | Description             |
| ------------ | ----- | -------- | ----------------------- |
| `image_path` | `str` | Yes      | Local image file path   |
| `model_id`   | `str` | No       | Target model identifier |

Returns:

- `dict`

### `neuralhive.estimate_pose(image_path, export_to=None)`

| Parameter    | Type  | Required | Description                                   |
| ------------ | ----- | -------- | --------------------------------------------- |
| `image_path` | `str` | Yes      | Local image file path                         |
| `export_to`  | `str` | No       | Export directory path for pose-rendered image |

Returns:

- `dict` with:
- `keypoints`: `list[object]`
- `scores`: `list[object]`
- `saved_path`: `str | None`

### `neuralhive.embed(text=None, image_path=None, model_id=None)`

| Parameter    | Type  | Required | Description             |
| ------------ | ----- | -------- | ----------------------- |
| `text`       | `str` | No       | Text input              |
| `image_path` | `str` | No       | Local image file path   |
| `model_id`   | `str` | No       | Target model identifier |

Notes:

- Exactly one input is required: `text` or `image_path`
- If `model_id` is not provided, SDK uses the default `clip` model from your allowed models.

Returns:

- `list[float]` or `list[list[float]]`

### `neuralhive.generate_text(prompt, model_id=None, image_paths=None, video_paths=None, system_prompt=None)`

| Parameter     | Type                 | Required | Description                          |
| ------------- | -------------------- | -------- | ------------------------------------ |
| `prompt`      | `str`                | Yes      | Text prompt                          |
| `model_id`    | `str`                | No       | Target model identifier              |
| `image_paths` | `str` or `list[str]` | No       | Local image file path(s)             |
| `video_paths` | `str` or `list[str]` | No       | Local video path(s) or public URL(s) |
| `system_prompt` | `str`              | No       | Optional system prompt for SLM models |

Notes:

- If `model_id` is not provided, SDK uses default `vlm` model from your allowed models.
- `system_prompt` is only sent when the selected model is an `slm` model.

Returns:

- `str`

### `neuralhive.analyze(text=None, image_paths=None, video_paths=None)`

| Parameter     | Type                 | Required | Description                          |
| ------------- | -------------------- | -------- | ------------------------------------ |
| `text`        | `str`                | No       | Text input                           |
| `image_paths` | `str` or `list[str]` | No       | Local image file path(s)             |
| `video_paths` | `str` or `list[str]` | No       | Local video path(s) or public URL(s) |

Notes:

- At least one input is required: `text` or `image_paths` or `video_paths`

Returns:

- `str`

### `neuralhive.generate_image(prompt, export_to=None, height=None, width=None)`

| Parameter   | Type  | Required | Description                                              |
| ----------- | ----- | -------- | -------------------------------------------------------- |
| `prompt`    | `str` | Yes      | Text prompt (1–3000 characters)                          |
| `export_to` | `str` | No       | Export directory path (filename comes from response URL) |
| `height`    | `int` | No       | 512–2048, multiple of 32. Server default is 1024         |
| `width`     | `int` | No       | 512–2048, multiple of 32. Server default is 1024         |

This is a queued job. The SDK waits for the result (usually 1–2 minutes).
If the job fails or does not finish, the method raises an error.
If the model is cold (not running), the first call can take a few minutes: the SDK retries a `503` up to 2 times.

Returns:

- `dict` with:
- `download_url`: `str`
- `saved_path`: `str | None`

### `neuralhive.edit_image(image_path, prompt, export_to=None)`

| Parameter    | Type  | Required | Description                                              |
| ------------ | ----- | -------- | -------------------------------------------------------- |
| `image_path` | `str` | Yes      | Local image file path                                    |
| `prompt`     | `str` | Yes      | Text instruction for the edit                            |
| `export_to`  | `str` | No       | Export directory path (filename comes from response URL) |

Returns:

- `dict` with:
- `download_url`: `str`
- `saved_path`: `str | None`

### `neuralhive.transcribe_audio(audio_path)`

| Parameter    | Type  | Required | Description           |
| ------------ | ----- | -------- | --------------------- |
| `audio_path` | `str` | Yes      | Local audio file path |

Returns:

- `str`

### `neuralhive.read_text(file_path, export_to=None, task="ocr")`

| Parameter   | Type  | Required | Description                                                          |
| ----------- | ----- | -------- | -------------------------------------------------------------------- |
| `file_path` | `str` | Yes      | Local image file path (JPEG or PNG). PDF is not supported.           |
| `export_to` | `str` | No       | Directory to save the text as `ocr-result.txt`                       |
| `task`      | `str` | No       | `ocr` (default), `table`, `formula`, `chart`, `spotting` or `seal`   |

Returns:

- `str`
- Without `export_to`: the text read from the image
- With `export_to`: saved local file path

### `neuralhive.detect_layout(file_path, export_to=None)`

| Parameter   | Type  | Required | Description                                                     |
| ----------- | ----- | -------- | --------------------------------------------------------------- |
| `file_path` | `str` | Yes      | Local image file path (JPEG or PNG). PDF is not supported.      |
| `export_to` | `str` | No       | Directory to save the result as `layout-detection-result.json`  |

Returns:

- `dict`
- `count`: number of regions found
- `pages`: one item per page. Each page has `detections`, and each detection has `order`, `label`, `score` and `box`.
- `saved_path`: saved `.json` file path (only when `export_to` is given)

### `neuralhive.parse_document(file_path, export_to, parse_mode="page")`

Turns a PDF or image into Markdown, and downloads the `.md` file to `export_to`. It is a queued job: the SDK waits until the result is ready.

| Parameter    | Type  | Required | Description                                                                                   |
| ------------ | ----- | -------- | --------------------------------------------------------------------------------------------- |
| `file_path`  | `str` | Yes      | Local PDF or image path (the SDK uploads it, up to 2 GB), or an `s3://` URL                   |
| `export_to`  | `str` | Yes      | Directory to save the `.md` file in. It is created if it does not exist.                      |
| `parse_mode` | `str` | No       | `page` (default): each page is read whole. `region`: the layout is found first, then each region is read. |

Returns:

- `dict`
- `markdown_path`: saved `.md` file path
- `page_count`: number of pages
- Raises an error if the job fails or does not finish.

### `neuralhive.generate_3d(image_path, export_to=None)`

| Parameter    | Type  | Required | Description                                              |
| ------------ | ----- | -------- | -------------------------------------------------------- |
| `image_path` | `str` | Yes      | Local image file path                                    |
| `export_to`  | `str` | No       | Export directory path (filename comes from response URL) |

Returns:

- `dict` with:
- `download_url`: `str`
- `saved_path`: `str | None`

## Errors

Every error the SDK raises is a subclass of `neuralhive.NeuralHiveError` (which is a subclass of `Exception`).

| Exception | When |
| --- | --- |
| `AuthenticationError` | The API key is missing, wrong, or revoked. |
| `PermissionDeniedError` | The key is not allowed to do this request. |
| `InvalidInputError` | A bad argument or missing file. Raised before sending, so not billed. Also a `ValueError`. |
| `ModelNotFoundError` | Unknown model id, or no default model for this method. |
| `ServiceUnavailableError` | The service cannot be reached, or the model is still starting after the SDK's retries. |
| `RequestError` | The service rejected the input (for example, no face found) or sent an unreadable response. |
| `TaskFailedError` | A long-running job (`generate_image`, `edit_image`, `transcribe_audio`, `parse_document`, `generate_3d`) failed or did not finish. |
| `ExportError` | The result could not be saved to `export_to`. |
| `BatchError` | Some items of a list call failed. `.results` has the finished items (`None` for failed ones), `.errors` maps index to exception. |

```python
from neuralhive import NeuralhiveClient, InvalidInputError

try:
    NeuralhiveClient().generate_image("a car", height=500)
except InvalidInputError as error:
    print(error)
```
