Developer Documentation

Build with NeuralHive from installation to inference.

The NeuralHive Python SDK gives developers a simple client for model access, authentication, model discovery, and inference workflows.

This guide is for neuralhive 2.1.0.

Overview

NeuralHive SDK is a Python client for accessing NeuralHive models through a consistent API. It helps developers discover available models, run inference, and build AI workflows without working directly with low-level API requests.

The SDK supports common computer vision, multimodal, embedding, generation, document, audio, and 3D asset workflows through simple Python methods.

Pricing and billing

  • Every successful inference call is a real request and is billed to the account that owns the API key. See Pricing for the price of each model.
  • Inference calls are the methods listed in Inference Tasks. list_models() and get_model() do not run a model.
  • If the SDK rejects a call before sending it (it raises InvalidInputError), nothing is sent, so nothing is billed.
  • Calls are not free while you test. Do not call inference methods in a loop until you have checked one result. Keep test inputs small.

Installation

Install the SDK from pip:

pip install neuralhive

To upgrade an existing installation:

pip install --upgrade neuralhive

Requirements

  • Python 3.9 or newer.
  • pip installs the other packages the SDK needs.

Check the installed version

neuralhive --version

or in Python:

import neuralhive

print(neuralhive.__version__)  # 2.1.0

If a method in this guide is missing (for example parse_document), upgrade with pip install --upgrade neuralhive.

What changed in 2.1.0

  • detect_and_segment() takes a list of images, with one prompt for all images or one prompt per image. The SDK sends up to 8 images in one request. See detect_and_segment().
  • Results now also have scores, labels (which object each detection is), concepts and dropped_concepts. This is true for one image too, and for detect() and segment() with a sam3 model.
  • One prompt can name up to 10 objects, separated by , or ;, for example "hard hat, vest, person".
  • Code written for 2.0.0 keeps working: the one-image result still has masks, boxes, score, image_height and image_width, with the same types.

What changed in 2.0.0

2.0.0 is a major release. Code written for 1.x must change in one place: the class name.

  • Breaking: Client is renamed to NeuralhiveClient. Change from neuralhive import Client to from neuralhive import NeuralhiveClient.
  • Each client now keeps its own API key. Several clients with different keys can run in the same process, at the same time.
  • A client is thread-safe and reuses HTTP connections (a connection pool). See Parallel calls.
  • New client settings: timeout, max_retries, poll_interval, job_timeout, max_connections. See Settings.
  • A client can be closed: neuralhive.close(), or use it in a with block.
  • detect() and segment() have a new conf parameter (minimum score).
  • detect() and segment() with an instance_segmentation model now return class_names, image_height and image_width.
  • detect_layout() has a new detection_threshold parameter.
  • generate_text() has a new enable_thinking parameter (VLM models).
  • neuralhive.__version__ gives the installed version.
  • generate_image(), edit_image(), transcribe_audio(), parse_document() and generate_3d() accept a list of inputs. The SDK runs them in parallel and returns a list of results. See List inputs.
  • New exception: BatchError.
  • parse_document() saves one Markdown (.md) file and returns markdown_path and page_count. There is no JSON file and no json_path any more.

What changed in 1.2.0

  • New method: parse_document().
  • read_text() now returns the text itself (a str), and has a new task parameter.
  • detect_layout() now returns the layout result (a dict with count and pages).
  • generate_image() has new height and width parameters.
  • generate_image(), edit_image(), transcribe_audio(), and generate_3d() now raise TaskFailedError when the job fails. Before, they returned an empty result.
  • New public exception classes (see Error Handling).
  • The SDK now retries automatically while a model is starting (cold start).

Authentication

The SDK needs a NeuralHive API key. The recommended approach is to configure it once from the command line.

Generate an API key

  1. Sign in to your NeuralHive account.
  2. Open Account Settings / API Keys.
  3. Create a new API key.
  4. Copy the key and keep it secure.

Store the key securely. For security reasons, you may not be able to view it again after closing.

Option 1: Configure once

neuralhive configure --api-key nh_live_your_api_key

The key is saved in ~/.neuralhive/credentials.

Option 2: Environment variable

export NEURALHIVE_API_KEY="nh_live_your_api_key"

Option 3: Direct key in code

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient("nh_live_your_api_key")

Avoid hardcoding API keys in production code. Prefer the CLI configuration or environment variable setup.

Which key is used

NeuralhiveClient() looks for the key in this order and uses the first one it finds:

  1. The key passed to NeuralhiveClient("nh_live_...").
  2. The NEURALHIVE_API_KEY environment variable.
  3. The key saved by neuralhive configure.

The key is checked on the first method call, not when the client is created. A wrong key raises AuthenticationError on that first call.

Quick Start

Create a client and list the models allowed for your API key.

from neuralhive import NeuralhiveClient

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

Models

List models

from neuralhive import NeuralhiveClient

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

Returns a list with one dict per model your API key can use:

[
    {"_id": "668384b260d316759df76666", "name": "Ready-Made Object Detection", "task": "object_detection", "is_default": True},
    {"_id": "6a4239916a5c33ece3f9c39d", "name": "Ready-Made OCR", "task": "ocr", "is_default": True},
    ...
]
KeyTypeMeaning
_idstrThe model id. Pass it as model_id.
namestrDisplay name.
taskstrThe model family. It decides which SDK methods can use the model (see Inference Tasks).
is_defaultboolTrue if the SDK uses this model when you leave out model_id.

task is one of: object_detection, face_detection, instance_segmentation, sam3, face_recognition, person_reid, pose_estimation, clip, text_embeddings, slm, vlm, image_generation, image_editing, asr, ocr, layout_detection, document_parsing, 3d_asset_generation. A model with any other task (for example pixel_streaming) has no SDK method.

To find a model for a method, filter by task:

sam3_ids = [m["_id"] for m in neuralhive.list_models() if m["task"] == "sam3"]

Get model details

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

Returns a dict, for example:

{"_id": "668384b260d316759df76666", "name": "Ready-Made Object Detection", "task": "object_detection",
 "project": "", "deploy_status": "", "is_uploaded": False}

Inference Tasks

Each SDK method works with specific model families. Use neuralhive.list_models() to see the models available to your API key. Many methods can use a default model from your allowed models when model_id is omitted.

TaskDescriptionSDK MethodSupported Model Families (task)
DetectionDetect objects, faces, or regions from a local image file.neuralhive.detect()Object Detection (object_detection), Face Detection (face_detection), Instance Segmentation (instance_segmentation), SAM3 / prompt-based segmentation (sam3)
SegmentationSegment image regions from a local image file, optionally with a prompt.neuralhive.segment()Instance Segmentation (instance_segmentation), SAM3 / prompt-based segmentation (sam3)
Detection + SegmentationRun prompt-based SAM3 detection and segmentation together.neuralhive.detect_and_segment()SAM3 / prompt-based segmentation (sam3)
Face RecognitionGenerate face embeddings from a local image file.neuralhive.recognize()Face Recognition (face_recognition)
Re-identificationRun person re-identification on a local image file.neuralhive.reidentify()Person Re-identification (person_reid)
Pose EstimationEstimate human pose from a local image file.neuralhive.estimate_pose()Pose Estimation (pose_estimation)
EmbeddingsCreate embeddings from text or a local image file.neuralhive.embed()Text Embeddings (text_embeddings), CLIP / text-image embeddings (clip)
Text GenerationGenerate text from prompts and optional local media files.neuralhive.generate_text()SLM / text generation (slm), VLM / multimodal generation (vlm)
AnalysisAnalyze text, local image files, or local/public videos.neuralhive.analyze()VLM / multimodal analysis (vlm)
Image GenerationGenerate an image from a prompt, optionally exporting it locally.neuralhive.generate_image()Image Generation (image_generation)
Image EditingEdit a local image file using a text instruction, optionally exporting it locally.neuralhive.edit_image()Image Editing (image_editing)
Audio TranscriptionTranscribe speech from a local audio file.neuralhive.transcribe_audio()Audio Transcription (asr)
OCRRead/extract text from a local image file.neuralhive.read_text()OCR (ocr)
Layout DetectionDetect document layout regions from a local image file.neuralhive.detect_layout()Layout Detection (layout_detection)
Document ParsingTurn a local PDF or image file into a Markdown file.neuralhive.parse_document()Document Parsing (document_parsing)
3D GenerationGenerate a 3D asset from a local image file, optionally exporting it locally.neuralhive.generate_3d()3D Asset Generation (3d_asset_generation)

Limits and formats

The SDK reads local files and sends them for you. These rules apply:

MethodInput rules
All image inputsJPEG or PNG file.
detect(), segment()prompt is required when the model's task is sam3. conf is 0 to 1, and only for object_detection and instance_segmentation models.
detect_and_segment()prompt is required. One prompt can name several objects, separated by , or ; (for example "hard hat, vest, person"). Only the first 10 objects are used. With a list of images: one prompt for all, or exactly one prompt per image.
embed()Exactly one of text or image_path. Text Embeddings models accept text only.
generate_text()enable_thinking is only for VLM models.
generate_text(), analyze() with a VLM modelAll local images together: at most 5 MB. All local videos together: at most 30 MB. Video URLs (http:// or https://) do not count toward the limit.
generate_image()prompt: 1 to 3000 characters. height and width: 512 to 2048, and a multiple of 32 (default 1024).
edit_image()prompt: 1 to 3000 characters. The output size is the input size rounded to a multiple of 32, with the long side at most 1024. An image with a short side under 512 is scaled up to 512 first.
transcribe_audio()WAV, FLAC, or MP3 file.
read_text()One JPEG or PNG image. No PDF (use parse_document()). task is one of ocr, table, formula, chart, spotting, seal.
detect_layout()One JPEG or PNG image, at most 20 MB. No PDF. detection_threshold is 0.05 to 0.95.
parse_document()PDF or image file, at most 2 GB each. parse_mode is page or region. Give a list for many files.
generate_3d()One image of one object, best on a plain background.

Long-running methods

generate_image(), edit_image(), transcribe_audio(), parse_document(), and generate_3d() run as jobs on the server. The method waits until the job is done and then returns. If a job fails, the method raises TaskFailedError.

If a model has not been used for some time, the server starts it first (a "cold start"). The first call can then take a few minutes. The SDK retries for you (see Settings).

List inputs for long-running methods

These methods take one input or a list of inputs:

MethodGive a list in
generate_image()prompt (one image per prompt)
edit_image()image_path (the same prompt is used for every image)
transcribe_audio()audio_path
parse_document()file_path
generate_3d()image_path

detect_and_segment() also takes a list of images. It works a little differently: it sends up to 8 images in one request (see detect_and_segment()).

With a list, the SDK runs the items in parallel, on threads, and returns a list of results in the same order as your inputs. The other parameters (for example export_to) are the same for every item.

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

results = neuralhive.parse_document(
    ["/path/to/a.pdf", "/path/to/b.pdf", "/path/to/c.pdf"],
    export_to="/path/to/parsed",
)

for result in results:
    print(result["page_count"], result["markdown_path"])

How it works:

  • Each item is its own job on the server, and it is billed on its own. Three files are three jobs.
  • At most max_connections items run at the same time (default 20). See Settings.
  • All items are checked before anything is sent. An empty list, an empty item, or a missing file raises InvalidInputError, and nothing is billed.
  • If some items fail, the others still finish. Then the method raises BatchError. Its results list has every finished result in input order (None for a failed item), and errors maps the index of each failed item to its exception:
from neuralhive import BatchError

try:
    results = neuralhive.generate_image(["a red car", "a blue boat", "a green tree"])
except BatchError as error:
    for index, problem in error.errors.items():
        print("item", index, "failed:", problem)
    results = error.results          # finished items are kept; failed ones are None
  • parse_document() with a list never overwrites a file. If a file name is already taken in export_to, _1, _2, ... is added to the new name.
  • The server can queue jobs when it is busy, so a long list may take a while.

Parallel calls

One client is thread-safe. For methods without list input, share the client between your own threads:

from concurrent.futures import ThreadPoolExecutor

from neuralhive import NeuralhiveClient

texts = ["a bus", "a person", "a dog"]

with NeuralhiveClient(max_connections=8) as neuralhive:
    with ThreadPoolExecutor(max_workers=8) as pool:
        vectors = list(pool.map(lambda text: neuralhive.embed(text=text), texts))
  • Each call is a separate request and is billed separately.
  • Set max_connections to at least the number of threads.

Object detection example

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

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

print(result)

Text generation example

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

response = neuralhive.generate_text(
    prompt="Write a short product description.",
)

print(response)

API Reference

NeuralhiveClient(api_key=None, *, timeout=600, max_retries=2, poll_interval=5, job_timeout=5000, max_connections=20)

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()                      # key from env or `neuralhive configure`
neuralhive = NeuralhiveClient("nh_live_...", timeout=120, max_retries=3)

with NeuralhiveClient() as neuralhive:               # closes the connections at the end
    print(neuralhive.list_models())

Settings

All settings except api_key must be given by name.

ParameterTypeDefaultDescription
api_keystrNoneAPI key. If not given, see Which key is used.
timeoutfloat600Seconds to wait for one HTTP request. At least 1.
max_retriesint2How many times to send a call again when the model is still starting (cold start, HTTP 503). The SDK waits 30 seconds before each retry. A 503 is not billed. 0 turns retries off.
poll_intervalfloat5Long-running methods: seconds between result checks. At least 0.5.
job_timeoutfloat5000Long-running methods: the longest time to wait for a job, in seconds (about 83 minutes). After that, the method raises TaskFailedError. The job may still finish on the server.
max_connectionsint20Size of the HTTP connection pool. Set it to at least the number of threads that share this client.

A wrong setting raises InvalidInputError when you create the client.

Network problems are retried for you: a failed connection is tried again up to 3 times. A call that already reached the server is not sent again (except the cold-start 503), so you are never billed twice for one call.

Threads and several API keys

  • A client is thread-safe. Share one client between threads. Calls run in parallel and reuse open connections. See Parallel calls.
  • Each client keeps its own API key. You can create several clients with different keys in the same process, and use them at the same time.
  • Create a client once and reuse it. Do not create a new client for every call.

neuralhive.close()

Closes the client's connections. After close(), every method raises NeuralHiveError. A with NeuralhiveClient() as neuralhive: block calls close() for you.

Shared return values

  • saved_path: the path of the file written to export_to. When the method has an export_to parameter and you leave it out, saved_path is None or not present.
  • Box format: [x_min, y_min, x_max, y_max] in pixels of the original image.
  • download_url: a pre-signed link to the result file. It expires after some time. Use export_to to keep the file.

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

ParameterTypeRequiredDescription
image_pathstrYesLocal image file path.
model_idstrNoTarget model identifier.
promptstrNoOptional prompt, required for sam3 models.
export_tostrNoExport directory path for box-rendered image.
conffloatNoMinimum score, 0 to 1. Only results with score >= conf come back. Server default is 0.5. Only for object_detection and instance_segmentation models.

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

Returns dict. The keys depend on the model's task:

Model taskReturned keys
object_detectionboxes, classes, scores
face_detectionboxes, classes (always 0), scores, masks (always empty)
instance_segmentationboxes, classes, class_names, scores, masks, image_height, image_width
sam3see detect_and_segment()
  • boxes: list[list[float]], one box per object.
  • classes: list[int], the class number per object, starting at 0. For the ready-made models these are COCO class numbers (for example 0 = person, 5 = bus).
  • scores: list[float], confidence from 0 to 1.
  • class_names (instance segmentation): list[str], the class name per object, for example "person". Ready-made model: the 80 COCO names. Your fine-tuned models: your dataset's names (older fine-tuned models: class_0, class_1, ...).
  • masks (instance segmentation): list[list[list[int]]], one outline per object, as [x, y] points in order. Join the points to draw the polygon.
  • image_height, image_width (instance segmentation): int, image size in pixels. Not present when nothing is found.
  • saved_path: str, only when export_to is provided.

All lists have the same length. Index i in each list is the same object.

# object_detection
{"boxes": [[11.86, 229.23, 804.77, 739.51], ...], "classes": [5, 0, ...], "scores": [0.957, 0.91, ...]}

# instance_segmentation
{"boxes": [...], "classes": [0, 0, 0, 5, 0], "class_names": ["person", "person", "person", "bus", "person"],
 "scores": [...], "masks": [[[279, 401], [277, 403], ...], ...], "image_height": 1080, "image_width": 810}

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

ParameterTypeRequiredDescription
image_pathstrYesLocal image file path.
model_idstrNoTarget model identifier.
promptstrNoOptional prompt, required for sam3 models.
export_tostrNoExport directory path for mask-rendered image.
conffloatNoMinimum score, 0 to 1 (server default 0.5). Only for instance_segmentation models.

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

Returns dict. With an instance_segmentation model: boxes, classes, class_names, scores, masks, image_height, image_width (same as detect()). With a sam3 model: same as detect_and_segment(). saved_path is added when export_to is provided.

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

ParameterTypeRequiredDescription
image_pathstr or list[str]YesLocal image file path, or a list of paths.
promptstr or list[str]YesWhat to find, for example "bus" or "hard hat, vest, person" (up to 10 objects, separated by , or ;). With a list of images: one str for all images, or a list with one prompt per image, in the same order.
export_tostrNoExport directory path for mask+box-rendered image(s).

One image

Returns dict:

KeyTypeMeaning
maskslist[list[list[int]]]One item per detection. Each item is a list of polygons (an object can have several parts). Each polygon is a flat list [x1, y1, x2, y2, ...].
boxeslist[list[float]]One box per detection.
scoreslist[float]Confidence per detection, 0 to 1.
labelslist[str]Which object of the prompt each detection is, for example "person".
conceptslist[dict]Every object of the prompt with its count, for example {"concept": "bus", "count": 1}. count is 0 when it was not found.
dropped_conceptslist[str]Objects that were not used, because the prompt had more than 10.
scorestrConfidence of the first detection, as text (for example "0.949"). Empty when nothing is found. Kept for older code; prefer scores.
image_heightstrImage height in pixels, as text.
image_widthstrImage width in pixels, as text.
saved_pathstrOnly when export_to is provided.
result = neuralhive.detect_and_segment("street.jpg", "bus, person")

{"masks": [[[111, 599, 110, 600, ...]], ...], "boxes": [[3.99, 229.1, 805.2, 740.3], ...],
 "scores": [0.949, 0.91, ...], "labels": ["bus", "person", ...],
 "concepts": [{"concept": "bus", "count": 1}, {"concept": "person", "count": 4}], "dropped_concepts": [],
 "score": "0.949", "image_height": "1080", "image_width": "810"}

A list of images

results = neuralhive.detect_and_segment(
    ["site1.jpg", "site2.jpg", "street.jpg"],
    ["hard hat, vest, person", "helmet, gloves", "bus, car"],   # or one str for all images
)

for result in results:
    print(result["labels"], result["scores"])
  • The SDK sends up to 8 images in one request. A longer list is split into groups of 8, and the groups run in parallel.
  • Returns a list with one dict per image, in the same order as image_path.
  • If some groups fail, the method raises BatchError. Every image of a failed group is None in error.results, and error.errors has its index.

Each dict:

KeyTypeMeaning
maskslist[list[list[int]]]One item per detection. Each item is a list of polygons (an object can have several parts). Each polygon is a flat list [x1, y1, x2, y2, ...] in pixels.
boxeslist[list[float]]One box per detection.
scoreslist[float]Confidence per detection, 0 to 1.
labelslist[str]Which object of the prompt each detection is, for example "vest".
conceptslist[dict]Every object of the prompt with its count, for example {"concept": "vest", "count": 2}. count is 0 when the object was not found.
dropped_conceptslist[str]Objects that were not used, because the prompt had more than 10.
image_height, image_widthintImage size in pixels.
saved_pathstrOnly when export_to is provided.

masks[i], boxes[i], scores[i] and labels[i] are the same detection. Detections are grouped by object, in prompt order, and inside a group the highest score comes first.

{"masks": [[[x1, y1, x2, y2, ...]], ...], "boxes": [[12.0, 30.5, 88.1, 140.2], ...],
 "scores": [0.94, 0.86], "labels": ["hard hat", "vest"],
 "concepts": [{"concept": "hard hat", "count": 1}, {"concept": "vest", "count": 1}, {"concept": "person", "count": 0}],
 "dropped_concepts": [], "image_height": 358, "image_width": 538}

The model finds what it can see. A prompt like "no-vest" finds nothing: find person and vest, then compare.

neuralhive.recognize(image_path)

ParameterTypeRequiredDescription
image_pathstrYesLocal image file path.

Returns list[list[float]]: one embedding per detected face. Each embedding has 512 floats.

neuralhive.reidentify(image_path, model_id=None)

ParameterTypeRequiredDescription
image_pathstrYesLocal image file path. Best with an image of one person.
model_idstrNoTarget model identifier.

Returns dict. Each list has one item per input image:

KeyShapeMeaning
embeddings[image][6][512] floats6 feature vectors of 512 floats each.
visibility_scores[image][6] floatsOne visibility score per feature vector.
masks[image][5][96][32] floats5 attention maps of 96×32.

neuralhive.estimate_pose(image_path, export_to=None)

ParameterTypeRequiredDescription
image_pathstrYesLocal image file path.
export_tostrNoExport directory path for pose-rendered image.

Returns dict:

KeyTypeMeaning
keypointslist[list[list[float]]]One item per person. Each person has 133 points as [x, y] in pixels, in COCO-WholeBody order (body, feet, face, hands).
scoreslist[list[float]]One item per person: 133 confidence values from 0 to 1.
saved_pathstr or NoneThe rendered image path, or None when export_to is not provided.

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

ParameterTypeRequiredDescription
textstrNoText input.
image_pathstrNoLocal image file path.
model_idstrNoTarget model identifier.

Provide exactly one input: text or image_path. If model_id is not provided, the SDK uses the default clip model from your allowed models.

Returns list[float], one embedding:

Model taskSizeInputs
clip1024 floatstext or image_path. Text and image embeddings are in the same space, so you can compare them.
text_embeddings384 floatstext only

neuralhive.generate_text(prompt, model_id=None, image_paths=None, video_paths=None, system_prompt=None, enable_thinking=False)

ParameterTypeRequiredDescription
promptstrYesText prompt.
model_idstrNoTarget model identifier.
image_pathsstr or list[str]NoLocal image file path(s). VLM models only.
video_pathsstr or list[str]NoLocal video path(s) or public URL(s). VLM models only.
system_promptstrNoOptional system prompt. Only sent when the selected model is an SLM model.
enable_thinkingboolNoLet a VLM model think before it answers. Slower and uses more tokens. Default False. VLM models only.

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

Returns str: the generated text.

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

ParameterTypeRequiredDescription
textstrNoText input.
image_pathsstr or list[str]NoLocal image file path(s).
video_pathsstr or list[str]NoLocal video path(s) or public URL(s).

Provide at least one input: text, image_paths, or video_paths. Always uses the default vlm model.

Returns str: the model's answer.

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

ParameterTypeRequiredDescription
promptstr or list[str]YesText prompt, 1 to 3000 characters. A list makes one image per prompt, in parallel.
export_tostrNoExport directory path. Filename comes from response URL.
heightintNoImage height in pixels: 512 to 2048, and a multiple of 32. Default is 1024.
widthintNoImage width in pixels: 512 to 2048, and a multiple of 32. Default is 1024.

Long-running method. Raises TaskFailedError if the image cannot be generated.

Returns dict (a list of them for a list input):

{"download_url": "https://...amazonaws.com/outputs/glm-image/<id>.jpg?...", "saved_path": "/path/to/output/<id>.jpg"}  # saved_path is None without export_to

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

ParameterTypeRequiredDescription
image_pathstr or list[str]YesLocal image file path. A list applies the same edit to every image, in parallel.
promptstrYesText instruction for the edit, 1 to 3000 characters. Clear, specific edits work best (for example "change the red jacket to a dark blue jacket").
export_tostrNoExport directory path. Filename comes from response URL.

Long-running method.

Returns dict with download_url (str, a .jpg link) and saved_path (str or None). A list input returns a list of them.

neuralhive.transcribe_audio(audio_path)

ParameterTypeRequiredDescription
audio_pathstr or list[str]YesLocal audio file path (WAV, FLAC, or MP3), or a list of paths.

Long-running method.

Returns str: the transcript. A list input returns list[str], in the same order.

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

ParameterTypeRequiredDescription
file_pathstrYesLocal image file path (JPEG or PNG). For PDF files, use parse_document().
export_tostrNoExport directory path. The text is saved as ocr-result.txt.
taskstrNoWhat to read: ocr (default, plain text), table, formula, chart, spotting, or seal.

Returns str: the text read from the image, with lines separated by \n. When export_to is provided, returns the saved file path instead.

neuralhive.detect_layout(file_path, export_to=None, detection_threshold=None)

ParameterTypeRequiredDescription
file_pathstrYesLocal image file path (JPEG or PNG, at most 20 MB). PDF files are not supported.
export_tostrNoExport directory path. The result is saved as layout-detection-result.json.
detection_thresholdfloatNoMinimum score for a region, 0.05 to 0.95. Server default is 0.3.

Returns dict:

{
    "count": 3,                       # regions found on all pages
    "pages": [
        {
            "page": 1, "width": 810, "height": 1080, "count": 3,
            "detections": [
                {
                    "order": 1,                         # reading order
                    "label": "paragraph_title",         # region type, for example text, image, table
                    "score": 0.8022,                    # confidence, 0 to 1
                    "box": [94.43, 101.09, 534.75, 149.35],
                    "polygon_points": [[94, 101], [534, 101], [534, 149], [94, 149]],
                },
            ],
        },
    ],
    "saved_path": "/path/to/output/layout-detection-result.json",  # only with export_to
}

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

ParameterTypeRequiredDescription
file_pathstr or list[str]YesLocal PDF or image file path (at most 2 GB), or a list of paths. Each file is its own job; a list runs in parallel.
export_tostrYesExport directory path. The results are saved here. It is created if it does not exist. With a list, a file name that is already taken gets _1, _2, ...
parse_modestrNopage (default): each page is read as a whole. region: layout regions are found first, then each region is read.

Long-running method. Raises TaskFailedError if the document cannot be parsed.

Returns dict (a list of them for a list input, in the same order):

KeyTypeMeaning
markdown_pathstrPath of the saved Markdown file. Headings, text, and tables (as Markdown tables), with a <!-- Page N --> line before each page.
page_countintNumber of pages.

neuralhive.generate_3d(image_path, export_to=None)

ParameterTypeRequiredDescription
image_pathstr or list[str]YesLocal image file path. Use a photo of one object on a plain background. A list makes one 3D asset per image, in parallel.
export_tostrNoExport directory path. Filename comes from response URL.

Long-running method.

Returns dict with download_url (str, a .glb 3D model link) and saved_path (str or None). A list input returns a list of them.

Error Handling

Every error the SDK raises is a subclass of NeuralHiveError, which is a subclass of Exception. Import the classes from neuralhive:

from neuralhive import NeuralhiveClient, InvalidInputError, NeuralHiveError, ServiceUnavailableError, TaskFailedError

neuralhive = NeuralhiveClient()

try:
    result = neuralhive.generate_image("a lighthouse at sunset", height=1024, width=768)
except InvalidInputError as error:
    print("Fix the input:", error)            # not sent, not billed
except (ServiceUnavailableError, TaskFailedError) as error:
    print("Try again later:", error)
except NeuralHiveError as error:
    print("Other SDK error:", error)
ProblemLikely CauseFixException
API key not foundNo configured key or environment variable.Run neuralhive configure or set NEURALHIVE_API_KEY.AuthenticationError
Authentication failedThe key is wrong or was revoked.Create a new key and configure it again.AuthenticationError
Access deniedThe key is valid but not allowed to do this request.Check your account and plan.PermissionDeniedError
Invalid model idThe model is unavailable or typed incorrectly, or it does not support this method.Call neuralhive.list_models() and use an allowed model with the right task.ModelNotFoundError
No default model foundmodel_id was omitted, but no default model for that task is available to your API key.Call neuralhive.list_models() or pass a specific model_id when the method supports it.ModelNotFoundError
Invalid file pathThe image_path, file_path, audio_path, image_paths, or video_paths value does not point to an accessible file.Use an absolute or correct relative local path and confirm the file exists.InvalidInputError
Invalid inputA value breaks a rule in Limits and formats, for example height=500 or an unknown parse_mode. Checked before sending, so not billed.Read the error message and fix the value.InvalidInputError
Request rejectedThe service could not use the input, for example no face was found, or the file is too large.Check the input against Limits and formats.RequestError
Service temporarily unavailableThe service cannot be reached, or the model was still starting after the SDK's retries.Wait a minute and call the method again.ServiceUnavailableError
Task did not completeA long-running job failed on the server or did not finish in time.Call the method again.TaskFailedError
Export failedThe export_to directory cannot be created or written to.Choose a writable export path.ExportError
Some list items failedA list call finished, but one or more items failed.Read error.errors (index → exception) and use error.results for the finished items.BatchError

Examples

Generate image

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.generate_image(
    prompt="A clean product photo of a black running shoe",
    export_to="/absolute/path/to/output",
    height=1024,
    width=768,
)

print(result["download_url"])
print(result["saved_path"])

Analyze image

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.analyze(
    image_paths="/absolute/path/to/image.jpg",
)

print(result)

Parse document

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.parse_document(
    file_path="/absolute/path/to/report.pdf",
    export_to="/absolute/path/to/output",
)

print(result["page_count"])
with open(result["markdown_path"], encoding="utf-8") as f:
    print(f.read())

Transcribe many audio files

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

transcripts = neuralhive.transcribe_audio(["/path/to/call1.wav", "/path/to/call2.mp3"])

for transcript in transcripts:
    print(transcript)

Generate 3D asset

from neuralhive import NeuralhiveClient

neuralhive = NeuralhiveClient()

result = neuralhive.generate_3d(
    image_path="/absolute/path/to/image.jpg",
    export_to="/absolute/path/to/output",
)

print(result["download_url"])
print(result["saved_path"])