Skip to content

rest_api

plantdb.client.rest_api Link

This module regroup the client-side methods of the REST API.

archive_url Link

archive_url(dataset_name, **kwargs)

Generates a formatted URL for accessing the archive of a specific dataset.

Parameters:

Name Type Description Default
dataset_name str

Name of the dataset to access in the archive.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

Fully constructed URL for accessing the specified dataset archive.

Examples:

>>> from plantdb.client.rest_api import archive_url
>>> archive_url('arabidopsis000')
'http://127.0.0.1:5000/archive/arabidopsis000'
>>> archive_url('../arabidopsis000')
'http://127.0.0.1:5000/archive/arabidopsis000'
>>> archive_url('arabidopsis+000')
ValueError: Invalid dataset name: 'arabidopsis+000'. Dataset names must be alphanumeric and can include underscores or dashes.
>>> archive_url('arabidopsis000', prefix='/plantdb')
'http://127.0.0.1/plantdb/archive/arabidopsis000'
Source code in plantdb/client/rest_api.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def archive_url(dataset_name, **kwargs):
    """Generates a formatted URL for accessing the archive of a specific dataset.

    Parameters
    ----------
    dataset_name : str
        Name of the dataset to access in the archive.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        Fully constructed URL for accessing the specified dataset archive.

    Examples
    --------
    >>> from plantdb.client.rest_api import archive_url
    >>> archive_url('arabidopsis000')
    'http://127.0.0.1:5000/archive/arabidopsis000'
    >>> archive_url('../arabidopsis000')
    'http://127.0.0.1:5000/archive/arabidopsis000'
    >>> archive_url('arabidopsis+000')
    ValueError: Invalid dataset name: 'arabidopsis+000'. Dataset names must be alphanumeric and can include underscores or dashes.
    >>> archive_url('arabidopsis000', prefix='/plantdb')
    'http://127.0.0.1/plantdb/archive/arabidopsis000'
    """
    dataset_name = sanitize_name(dataset_name)
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    url = urljoin(url, f"archive/{dataset_name}"
                  )
    return url

base_url Link

base_url(host=REST_API_URL, port=REST_API_PORT, prefix=None, ssl=False)

Generates the URL for the PlantDB REST API using the specified host and port.

This function constructs a URL by combining the provided host, port, prefix, and SSL settings. The default values are used if no arguments are supplied.

Parameters:

Name Type Description Default
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

REST_API_URL
port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

REST_API_PORT
prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. If provided, it will be added to the end of the URL, excluding the port number. Defaults to None.

None
ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

False

Returns:

Type Description
str

A properly formatted URL for the PlantDB REST API.

Notes
  • The function ensures that the prefix is correctly formatted by stripping leading and trailing slashes.
  • The SSL flag determines whether 'http' or 'https' is used in the URL scheme.

Examples:

>>> from plantdb.client.rest_api import base_url
>>> base_url()
'http://127.0.0.1:5000'
>>> base_url(host='api.example.com', port=8443, ssl=True)
'https://api.example.com:8443'
>>> base_url(prefix='/plantdb', ssl=True)
'https://127.0.0.1/plantdb/'
Source code in plantdb/client/rest_api.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def base_url(host: str = REST_API_URL, port: int | str = REST_API_PORT, prefix: str = None, ssl: bool = False) -> str:
    """
    Generates the URL for the PlantDB REST API using the specified host and port.

    This function constructs a URL by combining the provided host, port, prefix, and SSL settings.
    The default values are used if no arguments are supplied.

    Parameters
    ----------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        If provided, it will be added to the end of the URL, excluding the port number.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        A properly formatted URL for the PlantDB REST API.

    Notes
    -----
    - The function ensures that the prefix is correctly formatted by stripping leading and trailing slashes.
    - The SSL flag determines whether 'http' or 'https' is used in the URL scheme.

    Examples
    --------
    >>> from plantdb.client.rest_api import base_url
    >>> base_url()
    'http://127.0.0.1:5000'
    >>> base_url(host='api.example.com', port=8443, ssl=True)
    'https://api.example.com:8443'
    >>> base_url(prefix='/plantdb', ssl=True)
    'https://127.0.0.1/plantdb/'
    """
    # Attempt to split the host to check for an existing scheme (http/https)
    try:
        scheme, host = host.split('://')
    except ValueError:
        pass  # If no scheme is found, proceed with the default
    else:
        # If 's' is in the scheme, it indicates HTTPS
        if 's' in scheme:
            ssl = True

    # Format the prefix by stripping leading and trailing slashes and adding a leading slash
    if prefix:
        prefix = '/' + prefix.lstrip('/').rstrip('/') + '/'

    # Ensure port is converted to string and has no leading colon
    if port:
        if isinstance(port, int):
            port = str(port)
        port = ':' + port.lstrip(':')

    # Construct the final URL using f-string for clarity and formatting
    return f"http{'s' if ssl else ''}://{host}{prefix if prefix else port}"

download_scan_archive Link

download_scan_archive(dataset_name, out_dir=None, **kwargs)

Downloads a scan archive file from a defined dataset based on the specified API parameters.

This function fetches a scan archive in stream mode from a remote API. The archive is expected to be in the form of a binary content stream. The success of the operation is determined by the HTTP response received from the API.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset from which the scan archive file is to be downloaded.

required
out_dir str or Path

A path to the directory where to save the archive.

None

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the download request. Defaults to 10.

Returns:

Type Description
BytesIO or str

A BytesIO object containing the binary content of the downloaded scan archive. A path to the downloaded file, if a directory path is specified.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import download_scan_archive
>>> download_scan_archive("arabidopsis000", out_dir='/tmp')
('/tmp/arabidopsis000.zip', 'Download completed in 0.05 seconds.')
Source code in plantdb/client/rest_api.py
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
def download_scan_archive(dataset_name, out_dir=None, **kwargs):
    """Downloads a scan archive file from a defined dataset based on the specified API parameters.

    This function fetches a scan archive in stream mode from a remote API. The archive
    is expected to be in the form of a binary content stream. The success of the
    operation is determined by the HTTP response received from the API.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset from which the scan archive file is to be downloaded.
    out_dir : str or pathlib.Path, optional
        A path to the directory where to save the archive.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the download request. Defaults to ``10``.

    Returns
    -------
    BytesIO or str
        A `BytesIO` object containing the binary content of the downloaded scan archive.
        A path to the downloaded file, if a directory path is specified.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import download_scan_archive
    >>> download_scan_archive("arabidopsis000", out_dir='/tmp')
    ('/tmp/arabidopsis000.zip', 'Download completed in 0.05 seconds.')
    """
    import time
    url = archive_url(dataset_name, **kwargs)

    start_time = time.time()  # Start timing
    res = requests.get(url, stream=True, timeout=kwargs.get("timeout", 10))
    end_time = time.time()  # End timing
    duration = end_time - start_time
    msg = f"Download completed in {duration:.2f} seconds."

    if res.ok:
        if out_dir is not None:
            out_dir = Path(out_dir) / f"{dataset_name}.zip"
            with open(out_dir, "wb") as archive_file:
                archive_file.write(res.content)
            return f"{out_dir}", msg
        else:
            return BytesIO(res.content), msg
    else:
        res.raise_for_status()  # Raise an error if the request failed

get_angles_and_internodes_data Link

get_angles_and_internodes_data(dataset_name, **kwargs)

Return a dictionary with 'angles' and 'internodes' data for selected dataset, if it exists.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

A dictionary with 'angles' and 'internodes' data.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_angles_and_internodes_data
>>> data = get_angles_and_internodes_data('real_plant_analyzed')
>>> print(list(data.keys()))
['angles', 'internodes']
>>> print(len(data['angles']))
33
Source code in plantdb/client/rest_api.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def get_angles_and_internodes_data(dataset_name, **kwargs):
    """Return a dictionary with 'angles' and 'internodes' data for selected dataset, if it exists.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        A dictionary with 'angles' and 'internodes' data.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_angles_and_internodes_data
    >>> data = get_angles_and_internodes_data('real_plant_analyzed')
    >>> print(list(data.keys()))
    ['angles', 'internodes']
    >>> print(len(data['angles']))
    33
    """
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    res = requests.get(urljoin(url, f"sequence/{dataset_name}"))
    if res.ok:
        data = json.loads(res.content.decode('utf-8'))
        return {seq: data[seq] for seq in ['angles', 'internodes']}
    else:
        return None

get_file_uri Link

get_file_uri(scan, fileset, file)

Return the URI for the corresponding scan/fileset/file tree.

Parameters:

Name Type Description Default
scan Scan or str

A Scan instance or the name of the scan dataset.

required
fileset Fileset or str

A Fileset instance or the name of the fileset.

required
file File or str

A File instance or the name of the file.

required

Returns:

Type Description
str

The URI for the corresponding scan/fileset/file tree.

Examples:

>>> from plantdb.client.rest_api import get_file_uri
>>> get_file_uri('real_plant', 'images', '00000_rgb')
'files/real_plant/images/00000_rgb'
Source code in plantdb/client/rest_api.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def get_file_uri(scan, fileset, file):
    """Return the URI for the corresponding `scan/fileset/file` tree.

    Parameters
    ----------
    scan : plantdb.commons.fsdb.Scan or str
        A ``Scan`` instance or the name of the scan dataset.
    fileset : plantdb.commons.fsdb.Fileset or str
        A ``Fileset`` instance or the name of the fileset.
    file : plantdb.commons.fsdb.File or str
        A ``File`` instance or the name of the file.

    Returns
    -------
    str
        The URI for the corresponding `scan/fileset/file` tree.

    Examples
    --------
    >>> from plantdb.client.rest_api import get_file_uri
    >>> get_file_uri('real_plant', 'images', '00000_rgb')
    'files/real_plant/images/00000_rgb'
    """
    from plantdb.commons.fsdb import Scan
    from plantdb.commons.fsdb import Fileset
    from plantdb.commons.fsdb import File
    scan_id = scan.id if isinstance(scan, Scan) else scan
    fileset_id = fileset.id if isinstance(fileset, Fileset) else fileset
    file_id = file.path().name if isinstance(file, File) else file
    return f"files/{scan_id}/{fileset_id}/{file_id}"

get_images_from_task Link

get_images_from_task(dataset_name, task_name='images', size='orig', **kwargs)

Get the list of images data for a given dataset and task name.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset to retrieve the images for.

required
task_name str

The name of the task to retrieve the images from. Defaults to 'images'.

'images'
size (orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'orig', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no chache;

'orig'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
list of PIL.Image

The list of PIL.Image from the PlantDB REST API.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_images_from_task
>>> images = get_images_from_task('real_plant')
>>> print(len(images))
60
>>> img1 = images[0]
>>> print(img1.size)
(1440, 1080)
Source code in plantdb/client/rest_api.py
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
def get_images_from_task(dataset_name, task_name='images', size='orig', **kwargs):
    """Get the list of images data for a given dataset and task name.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset to retrieve the images for.
    task_name : str, optional
        The name of the task to retrieve the images from. Defaults to 'images'.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to `'orig'`, and it works as follows:
           * `'thumb'`: image max width and height to `150`.
           * `'large'`: image max width and height to `1500`;
           * `'orig'`: original image, no chache;

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    list of PIL.Image
        The list of PIL.Image from the PlantDB REST API.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_images_from_task
    >>> images = get_images_from_task('real_plant')
    >>> print(len(images))
    60
    >>> img1 = images[0]
    >>> print(img1.size)
    (1440, 1080)
    """
    images = []
    for img_uri in list_task_images_uri(dataset_name, task_name, size, **kwargs):
        images.append(Image.open(BytesIO(requests.get(img_uri).content)))
    return images

get_reconstruction_config Link

get_reconstruction_config(dataset_name, cfg_fname='pipeline.toml', **kwargs)

Return the reconstruction configuration for selected dataset, if it exists.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
cfg_fname str

The name of the configuration file.

'pipeline.toml'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_reconstruction_config
>>> cfg = get_reconstruction_config('real_plant_analyzed')
>>> cfg['PointCloud']['upstream_task']
'Voxels'
Source code in plantdb/client/rest_api.py
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
def get_reconstruction_config(dataset_name, cfg_fname='pipeline.toml', **kwargs):
    """Return the reconstruction configuration for selected dataset, if it exists.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the configuration file.
    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_reconstruction_config
    >>> cfg = get_reconstruction_config('real_plant_analyzed')
    >>> cfg['PointCloud']['upstream_task']
    'Voxels'

    """
    return get_toml_file(dataset_name, cfg_fname, **kwargs)

get_scan_config Link

get_scan_config(dataset_name, cfg_fname='scan.toml', **kwargs)

Return the scan configuration for selected dataset, if it exists.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
cfg_fname str

The name of the configuration file.

'scan.toml'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_scan_config
>>> cfg = get_scan_config('real_plant')
>>> cfg['ScanPath']['class_name']
'Circle'
Source code in plantdb/client/rest_api.py
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
def get_scan_config(dataset_name, cfg_fname='scan.toml', **kwargs):
    """Return the scan configuration for selected dataset, if it exists.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the configuration file.
    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_scan_config
    >>> cfg = get_scan_config('real_plant')
    >>> cfg['ScanPath']['class_name']
    'Circle'

    """
    return get_toml_file(dataset_name, cfg_fname, **kwargs)

get_scan_data Link

get_scan_data(scan_id, **kwargs)

Retrieve the data dictionary for a given scan dataset from the PlantDB REST API.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to be retrieved.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The data dictionary for the given scan dataset.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_scan_data
>>> scan_data = get_scan_data('real_plant')
>>> print(scan_data['id'])
real_plant
>>> print(scan_data['hasColmap'])
False
Source code in plantdb/client/rest_api.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
def get_scan_data(scan_id, **kwargs):
    """Retrieve the data dictionary for a given scan dataset from the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to be retrieved.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The data dictionary for the given scan dataset.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_scan_data
    >>> scan_data = get_scan_data('real_plant')
    >>> print(scan_data['id'])
    real_plant
    >>> print(scan_data['hasColmap'])
    False
    """
    scan_id = sanitize_name(scan_id)
    scan_names = list_scan_names(**kwargs)
    if scan_id in scan_names:
        return requests.get(url=scan_url(scan_id, **kwargs)).json()
    else:
        return {}

get_scan_image Link

get_scan_image(scan_id, fileset_id, file_id, size='orig', **kwargs)

Get the image for a scan dataset and task fileset served by the PlantDB REST API.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to be retrieved.

required
fileset_id str

The name of the fileset containing the image to be retrieved.

required
file_id str

The name of the image file to be retrieved.

required
size (orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'orig', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no cache;

'orig'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
Response

The URL to an image of a scan dataset and task fileset.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_scan_image
>>> response = get_scan_image('real_plant', 'images', '00000_rgb')  # download the image
>>> print(response.status_code)
200
>>> # Display the image
>>> from PIL import Image
>>> from io import BytesIO
>>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
>>> image.show()  # Display the image
Source code in plantdb/client/rest_api.py
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
def get_scan_image(scan_id, fileset_id, file_id, size='orig', **kwargs):
    """Get the image for a scan dataset and task fileset served by the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to be retrieved.
    fileset_id : str
        The name of the fileset containing the image to be retrieved.
    file_id : str
        The name of the image file to be retrieved.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to ``'orig'``, and it works as follows:
           * ``'thumb'``: image max width and height to `150`.
           * ``'large'``: image max width and height to `1500`;
           * ``'orig'``: original image, no cache;

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    requests.Response
        The URL to an image of a scan dataset and task fileset.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_scan_image
    >>> response = get_scan_image('real_plant', 'images', '00000_rgb')  # download the image
    >>> print(response.status_code)
    200
    >>> # Display the image
    >>> from PIL import Image
    >>> from io import BytesIO
    >>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
    >>> image.show()  # Display the image
    """
    return requests.get(url=scan_image_url(scan_id, fileset_id, file_id, size, **kwargs))

get_scans_info Link

get_scans_info(**kwargs)

Retrieve the information dictionary for all scans from the PlantDB REST API.

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The scans information dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_scans_info
>>> get_scans_info()
Source code in plantdb/client/rest_api.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def get_scans_info(**kwargs):
    """Retrieve the information dictionary for all scans from the PlantDB REST API.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The scans information dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_scans_info
    >>> get_scans_info()
    """
    scan_list = list_scan_names(**kwargs)
    return [requests.get(url=scan_url(scan, **kwargs)).json() for scan in scan_list]

get_task_data Link

get_task_data(dataset_name, task, filename=None, api_data=None, **kwargs)

Get the data corresponding to a dataset/task/filename.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
task str

The name of the task.

required
filename str

The name of the file to load. If not specified defaults to the main file returned by the task as defined in filesUri_task_mapping.

None
api_data dict

The dictionary of information for the dataset as returned by the REST API. If not specified, fetch it from the REST API.

None

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
any

The parsed data.

See Also

plantdb.server.rest_api.filesUri_task_mapping plantdb.client.rest_api.parse_task_requests_data

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> import numpy as np
>>> from plantdb.client.rest_api import get_task_data
>>> pcd = get_task_data('real_plant_analyzed', 'PointCloud')
>>> np.array(pcd).shape
(3, 57890)
Source code in plantdb/client/rest_api.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def get_task_data(dataset_name, task, filename=None, api_data=None, **kwargs):
    """Get the data corresponding to a `dataset/task/filename`.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    task : str
        The name of the task.
    filename : str, optional
        The name of the file to load.
        If not specified defaults to the main file returned by the task as defined in `filesUri_task_mapping`.
    api_data : dict, optional
        The dictionary of information for the dataset as returned by the REST API.
        If not specified, fetch it from the REST API.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    any
        The parsed data.

    See Also
    --------
    plantdb.server.rest_api.filesUri_task_mapping
    plantdb.client.rest_api.parse_task_requests_data

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> import numpy as np
    >>> from plantdb.client.rest_api import get_task_data
    >>> pcd = get_task_data('real_plant_analyzed', 'PointCloud')
    >>> np.array(pcd).shape
    (3, 57890)
    """
    if api_data is None:
        api_data = get_scan_data(dataset_name, **kwargs)
    # Get data from `File` resource of REST API:
    ext = None
    if filename is None:
        file_uri = api_data["filesUri"][task_filesUri_mapping[task]]
    else:
        _, ext = Path(filename).suffix.split('.')
        file_uri = get_file_uri(dataset_name, api_data["tasks_fileset"][task], filename)

    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    data = requests.get(url + file_uri).content
    return parse_task_requests_data(task, data, ext)

get_tasks_fileset_from_api Link

get_tasks_fileset_from_api(dataset_name, **kwargs)

Get the task name to fileset name mapping dictionary from the REST API.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset to retrieve the mapping for.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The mapping of the task name to fileset name.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_tasks_fileset_from_api
>>> get_tasks_fileset_from_api('real_plant')
{'images': 'images'}
Source code in plantdb/client/rest_api.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
def get_tasks_fileset_from_api(dataset_name, **kwargs):
    """Get the task name to fileset name mapping dictionary from the REST API.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset to retrieve the mapping for.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The mapping of the task name to fileset name.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_tasks_fileset_from_api
    >>> get_tasks_fileset_from_api('real_plant')
    {'images': 'images'}
    """
    return get_scan_data(dataset_name, **kwargs).get('tasks_fileset', dict())

get_toml_file Link

get_toml_file(dataset_name, file_path, **kwargs)

Return a loaded TOML file for selected dataset, if it exists.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
file_path str

The path to the TOML file.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The configuration dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import get_toml_file
>>> cfg = get_toml_file('real_plant_analyzed', 'pipeline.toml')
>>> cfg['PointCloud']
{'upstream_task': 'Voxels', 'level_set_value': 1.0}
Source code in plantdb/client/rest_api.py
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
def get_toml_file(dataset_name, file_path, **kwargs):
    """Return a loaded TOML file for selected dataset, if it exists.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    file_path : str
        The path to the TOML file.
    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The configuration dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import get_toml_file
    >>> cfg = get_toml_file('real_plant_analyzed', 'pipeline.toml')
    >>> cfg['PointCloud']
    {'upstream_task': 'Voxels', 'level_set_value': 1.0}
    """
    url = scan_file_url(dataset_name, file_path, **kwargs)
    return _load_toml_from_url(url)

list_scan_names Link

list_scan_names(**kwargs)

List the names of the scan datasets served by the PlantDB REST API.

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
list

The list of scan dataset names served by the PlantDB REST API.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import list_scan_names
>>> print(list_scan_names())
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
Source code in plantdb/client/rest_api.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def list_scan_names(**kwargs):
    """List the names of the scan datasets served by the PlantDB REST API.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    list
        The list of scan dataset names served by the PlantDB REST API.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import list_scan_names
    >>> print(list_scan_names())
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    """
    try:
        response = requests.get(url=scans_url(**kwargs))
    except Exception as e:
        return []
    return sorted(response.json())

list_task_images_uri Link

list_task_images_uri(dataset_name, task_name='images', size='orig', **kwargs)

Get the list of images URI for a given dataset and task name.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset to retrieve the images for.

required
task_name str

The name of the task to retrieve the images from. Defaults to 'images'.

'images'
size (orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'orig', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no cache;

'orig'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
list of str

The list of image URI strings for the PlantDB REST API.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import list_task_images_uri
>>> print(list_task_images_uri('real_plant')[2])
http://127.0.0.1:5000/image/real_plant/images/00002_rgb?size=orig
>>> print(list_task_images_uri('real_plant', size=100)[2])
http://127.0.0.1:5000/image/real_plant/images/00002_rgb?size=100
Source code in plantdb/client/rest_api.py
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
def list_task_images_uri(dataset_name, task_name='images', size='orig', **kwargs):
    """Get the list of images URI for a given dataset and task name.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset to retrieve the images for.
    task_name : str, optional
        The name of the task to retrieve the images from. Defaults to 'images'.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to `'orig'`, and it works as follows:
           * `'thumb'`: image max width and height to `150`.
           * `'large'`: image max width and height to `1500`;
           * `'orig'`: original image, no cache;

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    list of str
        The list of image URI strings for the PlantDB REST API.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import list_task_images_uri
    >>> print(list_task_images_uri('real_plant')[2])
    http://127.0.0.1:5000/image/real_plant/images/00002_rgb?size=orig
    >>> print(list_task_images_uri('real_plant', size=100)[2])
    http://127.0.0.1:5000/image/real_plant/images/00002_rgb?size=100
    """
    dataset_name = sanitize_name(dataset_name)
    task_name = sanitize_name(task_name)
    scan_info = get_scan_data(dataset_name, **kwargs)
    tasks_fileset = scan_info["tasks_fileset"]
    images = scan_info["images"]
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    return [urljoin(url, f"image/{dataset_name}/{tasks_fileset[task_name]}/{Path(img).stem}?size={size}") for img in
            images]

parse_requests_json Link

parse_requests_json(data)

Parse a requests content, should be from a AnglesAndInternodes task source.

Parameters:

Name Type Description Default
data buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The full angles and internodes dictionary with 'angles', 'internodes', '' & '' entries.

Source code in plantdb/client/rest_api.py
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def parse_requests_json(data):
    """Parse a requests content, should be from a AnglesAndInternodes task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The full angles and internodes dictionary with 'angles', 'internodes', '' & '' entries.
    """
    return json.loads(data)

parse_requests_mesh Link

parse_requests_mesh(data)

Parse a requests content, should be from a TriangleMesh task source.

Parameters:

Name Type Description Default
data buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The parsed triangular mesh with two entries: 'vertices' for vertex coordinates and 'triangles' for triangle coordinates.

Source code in plantdb/client/rest_api.py
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
def parse_requests_mesh(data):
    """Parse a requests content, should be from a TriangleMesh task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The parsed triangular mesh with two entries: 'vertices' for vertex coordinates and 'triangles' for triangle coordinates.
    """
    ## Read the PLY as a `PlyData`:
    mesh_data = PlyData.read(BytesIO(data))
    ## Convert the `PlyData`:
    return {"vertices": _ply_vertex_to_array(mesh_data),
            "triangles": _ply_face_to_array(mesh_data)}

parse_requests_pcd Link

parse_requests_pcd(data)

Parse a requests content, should be from a PointCloud task source.

Parameters:

Name Type Description Default
data buffer

The data source from a requests content.

required

Returns:

Type Description
ndarray

The parsed pointcloud with vertex coordinates sorted as XYZ.

Source code in plantdb/client/rest_api.py
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def parse_requests_pcd(data):
    """Parse a requests content, should be from a PointCloud task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    numpy.ndarray
        The parsed pointcloud with vertex coordinates sorted as XYZ.
    """
    ## Read the pointcloud PLY as a `PlyData`:
    ply_pcd = PlyData.read(BytesIO(data))
    ## Convert the `PlyData`:
    return _ply_vertex_to_array(ply_pcd)

parse_requests_skeleton Link

parse_requests_skeleton(data)

Parse a requests content, should be from a CurveSkeleton task source.

Parameters:

Name Type Description Default
data buffer

The data source from a requests content.

required

Returns:

Type Description
dict

The parsed skeleton with two entries: 'points' for points coordinates and 'lines' joining them.

Source code in plantdb/client/rest_api.py
920
921
922
923
924
925
926
927
928
929
930
931
932
933
def parse_requests_skeleton(data):
    """Parse a requests content, should be from a CurveSkeleton task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    dict
        The parsed skeleton with two entries: 'points' for points coordinates and 'lines' joining them.
    """
    return json.loads(data)

parse_requests_tree Link

parse_requests_tree(data)

Parse a requests content, should be from a TreeGraph task source.

Parameters:

Name Type Description Default
data buffer

The data source from a requests content.

required

Returns:

Type Description
Graph

The loaded (tree) graph object.

Source code in plantdb/client/rest_api.py
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def parse_requests_tree(data):
    """Parse a requests content, should be from a TreeGraph task source.

    Parameters
    ----------
    data : buffer
        The data source from a requests content.

    Returns
    -------
    networkx.Graph
        The loaded (tree) graph object.
    """
    import pickle
    tree = pickle.load(BytesIO(data))
    # FIXME: it would be better to return something that is JSON serializable...
    #  but the tree is not directed, so the `json_graph.tree_data` fails!
    # from networkx.readwrite import json_graph
    # data = json_graph.tree_data(tree, root=0)
    # return json.dumps(data)
    return tree

parse_scans_info Link

parse_scans_info(**kwargs)

Parse the information dictionary for all scans served by the PlantDB REST API.

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

The scan-id (dataset name) indexed information dictionary.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import parse_scans_info
>>> scan_dict = parse_scans_info()
>>> print(sorted(scan_dict.keys()))
['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
Source code in plantdb/client/rest_api.py
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def parse_scans_info(**kwargs):
    """Parse the information dictionary for all scans served by the PlantDB REST API.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        The scan-id (dataset name) indexed information dictionary.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import parse_scans_info
    >>> scan_dict = parse_scans_info()
    >>> print(sorted(scan_dict.keys()))
    ['arabidopsis000', 'real_plant', 'real_plant_analyzed', 'virtual_plant', 'virtual_plant_analyzed']
    """
    scan_json = get_scans_info(**kwargs)
    scan_dict = {}
    for scan in scan_json:
        name = scan.pop('id')
        scan_dict[name] = scan
    return scan_dict

parse_task_requests_data Link

parse_task_requests_data(task, data, extension=None)

The task data parser, behave according to the source and default to JSON parser.

Source code in plantdb/client/rest_api.py
988
989
990
991
992
993
994
def parse_task_requests_data(task, data, extension=None):
    """The task data parser, behave according to the source and default to JSON parser."""
    if extension is not None:
        data_parser = EXT_PARSER_DICT[extension]
    else:
        data_parser = PARSER_DICT.get(task, parse_requests_json)
    return data_parser(data)

refresh Link

refresh(dataset_name=None, **kwargs)

Refreshes the database, potentialy only for a specified dataset.

Parameters:

Name Type Description Default
dataset_name str or None

The name of the dataset to trigger a refresh. If None, the entire database is refreshed.

None

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the refresh request. Defaults to 5.

Returns:

Type Description
dict

Parsed JSON response from the refresh API if the request is successful.

Raises:

Type Description
HTTPError

If the request fails or the response status is not successful.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import refresh
>>> refresh("arabidopsis000")
{'message': "Successfully reloaded scan 'arabidopsis000'."}
Source code in plantdb/client/rest_api.py
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
def refresh(dataset_name=None, **kwargs):
    """Refreshes the database, potentialy only for a specified dataset.

    Parameters
    ----------
    dataset_name : str or None
        The name of the dataset to trigger a refresh.
        If ``None``, the entire database is refreshed.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the refresh request. Defaults to ``5``.

    Returns
    -------
    dict
        Parsed JSON response from the refresh API if the request is successful.

    Raises
    ------
    HTTPError
        If the request fails or the response status is not successful.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import refresh
    >>> refresh("arabidopsis000")
    {'message': "Successfully reloaded scan 'arabidopsis000'."}
    """
    res = requests.get(refresh_url(dataset_name, **kwargs), timeout=kwargs.get("timeout", 5))
    if res.ok:
        return res.json()
    else:
        res.raise_for_status()  # Raise an error if the request failed

refresh_url Link

refresh_url(dataset_name=None, **kwargs)

Generates a formatted URL for refreshing a specific dataset or the entire database.

Parameters:

Name Type Description Default
dataset_name str or None

The name of the dataset for which the refresh URL needs to be generated. If not provided, the refresh URL for the entire server is returned instead. Defaults to None.

None

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

A correctly formatted URL for refreshing the specified dataset or the entire PlantDB REST API server.

Examples:

>>> from plantdb.client.rest_api import refresh_url
>>> refresh_url("real_plant")
'http://127.0.0.1:5000/refresh?scan_id=real_plant'
>>> refresh_url("real_plant", prefix='/plantdb')
'http://127.0.0.1/plantdb/refresh?scan_id=real_plant'
Source code in plantdb/client/rest_api.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def refresh_url(dataset_name=None, **kwargs):
    """Generates a formatted URL for refreshing a specific dataset or the entire database.

    Parameters
    ----------
    dataset_name : str or None, optional
        The name of the dataset for which the refresh URL needs to be generated.
        If not provided, the refresh URL for the entire server is returned instead.
        Defaults to ``None``.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        A correctly formatted URL for refreshing the specified dataset or the entire PlantDB REST API server.

    Examples
    --------
    >>> from plantdb.client.rest_api import refresh_url
    >>> refresh_url("real_plant")
    'http://127.0.0.1:5000/refresh?scan_id=real_plant'
    >>> refresh_url("real_plant", prefix='/plantdb')
    'http://127.0.0.1/plantdb/refresh?scan_id=real_plant'
    """
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    url = urljoin(url, "refresh")
    if dataset_name is None:
        return url
    else:
        dataset_name = sanitize_name(dataset_name)
        return f"{url}?scan_id={dataset_name}"

sanitize_name Link

sanitize_name(name)

Sanitizes and validates the provided name.

The function ensures that the input string adheres to predefined naming rules by:

  • stripping leading/trailing spaces,
  • isolating the last segment after splitting by slashes,
  • validating the name against an alphanumeric pattern with optional underscores (_), dashes (-), or periods (.).

Parameters:

Name Type Description Default
name str

The name to sanitize and validate.

required

Returns:

Type Description
str

Sanitized name that conforms to the rules.

Raises:

Type Description
ValueError

If the provided name contains invalid characters or does not meet the naming rules.

Source code in plantdb/client/rest_api.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def sanitize_name(name):
    """Sanitizes and validates the provided name.

    The function ensures that the input string adheres to predefined naming rules by:

    - stripping leading/trailing spaces,
    - isolating the last segment after splitting by slashes,
    - validating the name against an alphanumeric pattern
      with optional underscores (`_`), dashes (`-`), or periods (`.`).

    Parameters
    ----------
    name : str
        The name to sanitize and validate.

    Returns
    -------
    str
        Sanitized name that conforms to the rules.

    Raises
    ------
    ValueError
        If the provided name contains invalid characters or does not meet the naming rules.
    """
    import re
    sanitized_name = name.strip()  # Remove leading/trailing spaces
    sanitized_name = sanitized_name.split('/')[-1]  # isolate the last segment after splitting by slashes
    # Validate against an alphanumeric pattern with optional underscores, dashes, or periods
    if not re.match(r"^[a-zA-Z0-9_.-]+$", sanitized_name):
        raise ValueError(
            f"Invalid name: '{name}'. Names must be alphanumeric and can include underscores, dashes, or periods.")
    return sanitized_name

scan_config_url Link

scan_config_url(dataset_name, cfg_fname='scan.toml', **kwargs)

Return the scan URL to access the scanning configuration file.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
cfg_fname str

The name of the TOML scan file, defaults to 'scan.toml'.

'scan.toml'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

The URL to the scanning configuration file.

Examples:

>>> from plantdb.client.rest_api import scan_config_url
>>> scan_config_url('real_plant')
'http://127.0.0.1:5000/files/real_plant/scan.toml'
>>> scan_config_url('real_plant', prefix='/plantdb')
'http://127.0.0.1/plantdb/files/real_plant/scan.toml'
Source code in plantdb/client/rest_api.py
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
def scan_config_url(dataset_name, cfg_fname='scan.toml', **kwargs):
    """Return the scan URL to access the scanning configuration file.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the TOML scan file, defaults to ``'scan.toml'``.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        The URL to the scanning configuration file.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_config_url
    >>> scan_config_url('real_plant')
    'http://127.0.0.1:5000/files/real_plant/scan.toml'
    >>> scan_config_url('real_plant', prefix='/plantdb')
    'http://127.0.0.1/plantdb/files/real_plant/scan.toml'
    """
    return scan_file_url(dataset_name, cfg_fname, **kwargs)

scan_file_url Link

scan_file_url(dataset_name, file_path, **kwargs)

Build the URL for accessing a dataset file.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
file_path str

The path to the file.

required
**kwargs

Keyword arguments passed to base_url().

{}

Returns:

Type Description
str

The complete URL for the dataset file.

Source code in plantdb/client/rest_api.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
def scan_file_url(dataset_name, file_path, **kwargs):
    """Build the URL for accessing a dataset file.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    file_path : str
        The path to the file.
    **kwargs
        Keyword arguments passed to base_url().

    Returns
    -------
    str
        The complete URL for the dataset file.
    """
    url = base_url(
        host=kwargs.get("host", REST_API_URL),
        port=kwargs.get("port", REST_API_PORT),
        prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
        ssl=kwargs.get("ssl", False)
    )
    return urljoin(url, f"files/{dataset_name}/{file_path}")

scan_image_url Link

scan_image_url(scan_id, fileset_id, file_id, size='orig', **kwargs)

Get the URL to the image for a scan dataset and task fileset served by the PlantDB REST API.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to be retrieved.

required
fileset_id str

The name of the fileset containing the image to be retrieved.

required
file_id str

The name of the image file to be retrieved.

required
size (orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'orig', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no cache;

'orig'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

The URL to an image of a scan dataset and task fileset.

Examples:

>>> from plantdb.client.rest_api import scan_image_url
>>> scan_image_url("real_plant", "images", "00000_rgb")
'http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=orig'
>>> scan_image_url("real_plant", "images", "00000_rgb", prefix='/plantdb')
'http://127.0.0.1/plantdb/image/real_plant/images/00000_rgb?size=orig'
Source code in plantdb/client/rest_api.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def scan_image_url(scan_id, fileset_id, file_id, size='orig', **kwargs):
    """Get the URL to the image for a scan dataset and task fileset served by the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to be retrieved.
    fileset_id : str
        The name of the fileset containing the image to be retrieved.
    file_id : str
        The name of the image file to be retrieved.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to ``'orig'``, and it works as follows:
           * ``'thumb'``: image max width and height to `150`.
           * ``'large'``: image max width and height to `1500`;
           * ``'orig'``: original image, no cache;

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        The URL to an image of a scan dataset and task fileset.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_image_url
    >>> scan_image_url("real_plant", "images", "00000_rgb")
    'http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=orig'
    >>> scan_image_url("real_plant", "images", "00000_rgb", prefix='/plantdb')
    'http://127.0.0.1/plantdb/image/real_plant/images/00000_rgb?size=orig'
    """
    scan_id = sanitize_name(scan_id)
    fileset_id = sanitize_name(fileset_id)
    file_id = sanitize_name(file_id)
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    return urljoin(url, f"image/{scan_id}/{fileset_id}/{file_id}?size={size}")

scan_preview_image_url Link

scan_preview_image_url(scan_id, size='thumb', **kwargs)

Get the URL to the preview image for a scan dataset served by the PlantDB REST API.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to be retrieved.

required
size (orig, large, thumb)

If an integer, use it as the size of the cached image to create and return. Else, should be a string, defaulting to 'thumb', and it works as follows: * 'thumb': image max width and height to 150. * 'large': image max width and height to 1500; * 'orig': original image, no cache;

'orig'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

The URL to the preview image for a scan dataset.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import scan_preview_image_url
>>> img_url = scan_preview_image_url('real_plant')
>>> print(img_url)
http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=thumb
>>> img_url = scan_preview_image_url('real_plant', size=100)
>>> print(img_url)
http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=100
>>> # Download and display the image
>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> response = requests.get(img_url)  # Send a GET request to the URL
>>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
>>> image.show()  # Display the image
Source code in plantdb/client/rest_api.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def scan_preview_image_url(scan_id, size="thumb", **kwargs):
    """Get the URL to the preview image for a scan dataset served by the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to be retrieved.
    size : {'orig', 'large', 'thumb'} or int, optional
        If an integer, use  it as the size of the cached image to create and return.
        Else, should be a string, defaulting to ``'thumb'``, and it works as follows:
           * ``'thumb'``: image max width and height to `150`.
           * ``'large'``: image max width and height to `1500`;
           * ``'orig'``: original image, no cache;

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        The URL to the preview image for a scan dataset.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import scan_preview_image_url
    >>> img_url = scan_preview_image_url('real_plant')
    >>> print(img_url)
    http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=thumb
    >>> img_url = scan_preview_image_url('real_plant', size=100)
    >>> print(img_url)
    http://127.0.0.1:5000/image/real_plant/images/00000_rgb?size=100
    >>> # Download and display the image
    >>> import requests
    >>> from PIL import Image
    >>> from io import BytesIO
    >>> response = requests.get(img_url)  # Send a GET request to the URL
    >>> image = Image.open(BytesIO(response.content))  # Open the image from the bytes data
    >>> image.show()  # Display the image
    """
    scan_id = sanitize_name(scan_id)
    scan_names = list_scan_names(**kwargs)
    if scan_id not in scan_names:
        return None

    thumb_uri = get_scan_data(scan_id)["thumbnailUri"]
    if size != "thumb":
        thumb_uri = thumb_uri.replace("size=thumb", f"size={size}")
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    return urljoin(url, thumb_uri.lstrip("/"))

scan_reconstruction_url Link

scan_reconstruction_url(dataset_name, cfg_fname='pipeline.toml', **kwargs)

Return the scan URL to access the reconstruction configuration file.

Parameters:

Name Type Description Default
dataset_name str

The name of the dataset.

required
cfg_fname str

The name of the TOML scan file, defaults to 'pipeline.toml'.

'pipeline.toml'

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

The URL to the reconstruction configuration file.

Examples:

>>> from plantdb.client.rest_api import scan_reconstruction_url
>>> scan_reconstruction_url('real_plant')
'http://127.0.0.1:5000/files/real_plant/pipeline.toml'
>>> scan_reconstruction_url('real_plant', prefix='/plantdb')
'http://127.0.0.1/plantdb/files/real_plant/pipeline.toml'
Source code in plantdb/client/rest_api.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
def scan_reconstruction_url(dataset_name, cfg_fname='pipeline.toml', **kwargs):
    """Return the scan URL to access the reconstruction configuration file.

    Parameters
    ----------
    dataset_name : str
        The name of the dataset.
    cfg_fname : str, optional
        The name of the TOML scan file, defaults to ``'pipeline.toml'``.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        The URL to the reconstruction configuration file.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_reconstruction_url
    >>> scan_reconstruction_url('real_plant')
    'http://127.0.0.1:5000/files/real_plant/pipeline.toml'
    >>> scan_reconstruction_url('real_plant', prefix='/plantdb')
    'http://127.0.0.1/plantdb/files/real_plant/pipeline.toml'
    """
    return scan_file_url(dataset_name, cfg_fname, **kwargs)

scan_url Link

scan_url(scan_id, **kwargs)

Generates the URL pointing to the scan JSON from the PlantDB REST API.

Parameters:

Name Type Description Default
scan_id str

The name of the scan dataset to retrieve the JSON from.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

A properly formatted URL of the PlantDB REST API pointing to the scans list.

Examples:

>>> from plantdb.client.rest_api import scan_url
>>> scan_url("real_plant")
'http://127.0.0.1:5000/scans/real_plant'
>>> scan_url("real_plant", prefix='/plantdb')
'http://127.0.0.1/plantdb/scans/real_plant'
Source code in plantdb/client/rest_api.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def scan_url(scan_id, **kwargs):
    """Generates the URL pointing to the scan JSON from the PlantDB REST API.

    Parameters
    ----------
    scan_id : str
        The name of the scan dataset to retrieve the JSON from.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        A properly formatted URL of the PlantDB REST API pointing to the scans list.

    Examples
    --------
    >>> from plantdb.client.rest_api import scan_url
    >>> scan_url("real_plant")
    'http://127.0.0.1:5000/scans/real_plant'
    >>> scan_url("real_plant", prefix='/plantdb')
    'http://127.0.0.1/plantdb/scans/real_plant'
    """
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    return urljoin(url, f"scans/{sanitize_name(scan_id)}")

scans_url Link

scans_url(**kwargs)

Generates the URL listing the scans from the PlantDB REST API.

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
str

A properly formatted URL of the PlantDB REST API pointing to the scans list.

Examples:

>>> from plantdb.client.rest_api import scans_url
>>> scans_url()
'http://127.0.0.1:5000/scans'
>>> scans_url(prefix='/plantdb')
'http://127.0.0.1/plantdb/scans'
Source code in plantdb/client/rest_api.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def scans_url(**kwargs):
    """Generates the URL listing the scans from the PlantDB REST API.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    str
        A properly formatted URL of the PlantDB REST API pointing to the scans list.

    Examples
    --------
    >>> from plantdb.client.rest_api import scans_url
    >>> scans_url()
    'http://127.0.0.1:5000/scans'
    >>> scans_url(prefix='/plantdb')
    'http://127.0.0.1/plantdb/scans'
    """
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    return urljoin(url, "scans")

test_availability Link

test_availability(url)

Verifies the connectivity to a given host and port from a URL-like string.

This function parses a URL string into host and port components, attempts to establish a socket connection to check its availability, and raises appropriate exceptions on failure.

Parameters:

Name Type Description Default
url str

A string specifying the host and port in the format 'host:port'.

required

Raises:

Type Description
ValueError

If the input URL is not in the correct format 'host:port'.

ConnectionError

If the specified host and port cannot be connected, indicating that the port might be closed or unavailable.

RuntimeError

If an unexpected error occurs during the verification process.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import test_availability
>>> test_availability('http://127.0.0.1:5000')
>>> test_availability('http://127.0.0.1:5000/plantdb/')
Source code in plantdb/client/rest_api.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def test_availability(url):
    """Verifies the connectivity to a given host and port from a URL-like string.

    This function parses a URL string into host and port components, attempts to establish a
    socket connection to check its availability, and raises appropriate exceptions on failure.

    Parameters
    ----------
    url : str
        A string specifying the host and port in the format 'host:port'.

    Raises
    ------
    ValueError
        If the input URL is not in the correct format 'host:port'.
    ConnectionError
        If the specified host and port cannot be connected, indicating that the port might
        be closed or unavailable.
    RuntimeError
        If an unexpected error occurs during the verification process.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import test_availability
    >>> test_availability('http://127.0.0.1:5000')
    >>> test_availability('http://127.0.0.1:5000/plantdb/')
    """
    import socket
    try:
        parsed_url = urlparse(url)
        host, port = parsed_url.hostname, parsed_url.port
        socket.setdefaulttimeout(2)  # Set a timeout for the connection check
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            if s.connect_ex((host, port)) != 0:
                raise ConnectionError(f"Cannot connect to {host}:{port}. Port might be closed or unavailable.")
    except ValueError:
        raise ValueError(f"Database URL should be 'host:port', got '{url}' instead.")
    except ConnectionError as e:
        raise e

upload_dataset_file Link

upload_dataset_file(scan_id, file_path, chunk_size=0, **kwargs)

Uploads a file to the server using the DatasetFile POST endpoint.

Parameters:

Name Type Description Default
server_url str

The base URL of the server hosting the REST API.

required
scan_id str

The unique identifier of the scan associated with the file upload.

required
file_path str

The path to the file to be uploaded.

required
chunk_size int

The size of chunks (in bytes) to read and send, by default 0 (no chunking).

0

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

Returns:

Type Description
dict

A dictionary containing the server's response.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import upload_dataset_file
>>> upload_dataset_file('arabidopsis000', '/path/to/local/file.txt')
Source code in plantdb/client/rest_api.py
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
def upload_dataset_file(scan_id, file_path, chunk_size=0, **kwargs):
    """Uploads a file to the server using the DatasetFile POST endpoint.

    Parameters
    ----------
    server_url : str
        The base URL of the server hosting the REST API.
    scan_id : str
        The unique identifier of the scan associated with the file upload.
    file_path : str
        The path to the file to be uploaded.
    chunk_size : int, optional
        The size of chunks (in bytes) to read and send, by default 0 (no chunking).

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.

    Returns
    -------
    dict
        A dictionary containing the server's response.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import upload_dataset_file
    >>> upload_dataset_file('arabidopsis000', '/path/to/local/file.txt')
    """
    from os.path import basename
    from os.path import getsize
    # Prepare the URL and headers
    scan_id = sanitize_name(scan_id)
    url = base_url(host=kwargs.get("host", REST_API_URL),
                   port=kwargs.get("port", REST_API_PORT),
                   prefix=kwargs.get('prefix', os.environ.get('PLANTDB_API_PREFIX', None)),
                   ssl=kwargs.get("ssl", False))
    url = urljoin(url, f"files/{scan_id}")

    filename = basename(file_path)
    file_size = getsize(file_path)
    # Create the request header
    headers = {
        "Content-Disposition": f"attachment; filename={filename}",
        "Content-Length": str(file_size),
        "X-File-Path": filename,
    }

    try:
        # Open the file for reading
        with open(file_path, 'rb') as f:
            if chunk_size > 0:
                # Upload in chunks
                headers["X-Chunk-Size"] = str(chunk_size)
                bytes_sent = 0
                while bytes_sent < file_size:
                    chunk = f.read(chunk_size)
                    response = requests.post(
                        url,
                        headers=headers,
                        data=chunk,
                    )
                    bytes_sent += len(chunk)
                    # Check if the request was successful
                    if response.status_code not in (200, 201):
                        return {"error": "File upload failed", "status_code": response.status_code,
                                "response": response.json()}
            else:
                # Upload the entire file
                response = requests.post(url, headers=headers, data=f)

        # Return the server's response
        if response.status_code in (200, 201):
            return response.json()
        else:
            return {"error": "File upload failed", "status_code": response.status_code, "response": response.json()}
    except Exception as e:
        return {"error": str(e)}

upload_scan_archive Link

upload_scan_archive(dataset_name, path, **kwargs)

Upload a scan archive file to a specified dataset on a server.

This function sends a POST request to upload a scan archive file to a particular dataset, utilizing the archive URL and optionally specified additional API-related request parameters. Ensures proper handling of file opening/closing procedures and response status checks.

Parameters:

Name Type Description Default
dataset_name str

The name of the target dataset for the archive upload.

required
path str

The local file system path to the archive to be uploaded.

required

Other Parameters:

Name Type Description
host str

The hostname or IP address of the PlantDB REST API server. Defaults to REST_API_URL.

port int or str

The port number of the PlantDB REST API server. Defaults to REST_API_PORT.

prefix str

The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes. Defaults to None.

ssl bool

Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to False.

timeout int

A timeout, in seconds, to succeed the upload request. Defaults to 120.

Returns:

Type Description
str

The time it took to upload the archive.

Raises:

Type Description
RequestException

If the HTTP request fails for any reason.

HTTPError

If the request returns an unsuccessful HTTP status code.

Examples:

>>> # Start a test PlantDB REST API server first, in a terminal:
>>> # $ fsdb_rest_api --test
>>> from plantdb.client.rest_api import upload_scan_archive
>>> upload_scan_archive("arabidopsis000", path='/tmp/arabidopsis000.zip')
'Upload completed in 0.10 seconds.'
Source code in plantdb/client/rest_api.py
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
def upload_scan_archive(dataset_name, path, **kwargs):
    """Upload a scan archive file to a specified dataset on a server.

    This function sends a POST request to upload a scan archive file to a
    particular dataset, utilizing the archive URL and optionally specified
    additional API-related request parameters. Ensures proper handling of
    file opening/closing procedures and response status checks.

    Parameters
    ----------
    dataset_name : str
        The name of the target dataset for the archive upload.
    path : str
        The local file system path to the archive to be uploaded.

    Other Parameters
    ----------------
    host : str, optional
        The hostname or IP address of the PlantDB REST API server. Defaults to ``REST_API_URL``.
    port : int or str, optional
        The port number of the PlantDB REST API server. Defaults to ``REST_API_PORT``.
    prefix : str, optional
        The prefix to be prepended to the URL. If provided, it will be stripped of leading and trailing slashes.
        Defaults to ``None``.
    ssl : bool, optional
        Flag indicating whether to use HTTPS (True) or HTTP (False). Defaults to ``False``.
    timeout : int, optional
        A timeout, in seconds, to succeed the upload request. Defaults to ``120``.

    Returns
    -------
    str
        The time it took to upload the archive.

    Raises
    ------
    requests.exceptions.RequestException
        If the HTTP request fails for any reason.
    requests.exceptions.HTTPError
        If the request returns an unsuccessful HTTP status code.

    Examples
    --------
    >>> # Start a test PlantDB REST API server first, in a terminal:
    >>> # $ fsdb_rest_api --test
    >>> from plantdb.client.rest_api import upload_scan_archive
    >>> upload_scan_archive("arabidopsis000", path='/tmp/arabidopsis000.zip')
    'Upload completed in 0.10 seconds.'
    """
    import time
    from zipfile import ZipFile

    path = Path(path)
    # Verify path existence
    if not path.is_file():
        raise FileNotFoundError(f"The file at path '{path}' does not exist!")
    # Verify the integrity of the ZIP file
    try:
        with ZipFile(path, 'r') as zip_file:
            zip_file.testzip()
    except Exception as e:
        print(e)
        raise IOError(f"Invalid ZIP file '{path}!'")

    # Construct the URL for the archive upload:
    url = archive_url(dataset_name, **kwargs)

    start_time = time.time()  # Start timing
    with open(path, "rb") as f:
        timeout = kwargs.get("timeout", 120)
        try:
            res = requests.post(url, files={"zip_file": (path.name, f, "application/zip")}, stream=True,
                                timeout=timeout)
        except requests.exceptions.Timeout:
            raise RuntimeError(f"The upload request timed out after {timeout} seconds.")
        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"An error occurred during the upload: {e}")
    end_time = time.time()  # End timing

    if res.ok:
        duration = end_time - start_time
        return f"Upload completed in {duration:.2f} seconds."
    else:
        res.raise_for_status()  # Raise an error if the request failed