Welcome to T2D2 SDK’s documentation!¶
T2D2 SDK¶
A Python SDK for seamless integration with the T2D2 platform.
Easily manage projects, assets, and AI-powered inspections for structural health monitoring.
Description¶
T2D2 SDK is a Python wrapper for the T2D2 API, enabling seamless integration with T2D2 projects and related assets for structural inspection data management.
Manage projects, images, annotations, drawings, videos, reports, and more
Upload, download, and organize assets
Run AI inference and summarize inspection data
Integrate with T2D2’s web platform
Documentation¶
Full documentation is available at: https://t2d2-ai.github.io/t2d2-sdk/
Table of Contents¶
Features¶
Authentication: API key or email/password
Project Management: Set, get, and summarize projects
Asset Management: Upload/download images, drawings, videos, 3D models, and reports
Annotations: Add, retrieve, and manage annotation classes and annotations
Regions & Tags: Organize assets by regions and tags
AI Integration: Run AI inference on images using project models
Summarization: Summarize images and annotation conditions
Notifications: Send notifications to users or Slack
Installation¶
Install the latest version from PyPI:
pip install --upgrade t2d2-sdk
Quickstart¶
Sign up for a T2D2 account: Register here
Get your API key from the T2D2 web app
Initialize the client:
from t2d2_sdk import T2D2
credentials = {'api_key': '<YOUR_API_KEY>'}
t2d2 = T2D2(credentials)
Usage¶
Set Project¶
t2d2.set_project('<PROJECT_ID>')
project_info = t2d2.get_project_info()
print(project_info)
Upload Images¶
image_paths = ['./images/img1.jpg', './images/img2.jpg']
response = t2d2.upload_images(image_paths)
print(response)
Get Images¶
images = t2d2.get_images()
for img in images:
print(img['filename'], img['id'])
Add Annotation Class¶
result = t2d2.add_annotation_class('Crack', color='#FF0000', materials=['Concrete'])
print(result)
Add Annotations to an Image¶
annotations = [
{
'annotation_class_id': 'class_id',
'coordinates': [[100, 100], [200, 100], [200, 200], [100, 200]],
'attributes': {'severity': 'high'}
}
]
result = t2d2.add_annotations('image_id', annotations)
print(result)
Run AI Inference¶
result = t2d2.run_ai_inferencer(
image_ids=['image_id1', 'image_id2'],
model_id='model_id',
confidence_threshold=0.6
)
print(result)
For more advanced usage, see the full documentation.
Contributing¶
Contributions are welcome! Please contact bhiriyur@t2d2.ai for more information.
License¶
See the LICENSE file for details.
Support¶
Documentation: https://t2d2-ai.github.io/t2d2-sdk/
Email: bhiriyur@t2d2.ai
T2D2 Web: https://t2d2.ai
T2D2 SDK Client Library¶
- class t2d2_sdk.RequestType(value)¶
Request types
- class t2d2_sdk.T2D2(credentials, base_url='https://api-v3.t2d2.ai/api/')¶
A class to interact with the T2D2 API for structural inspection data management.
This class provides a comprehensive interface to the T2D2 API, enabling authentication, project management, and manipulation of various data types including images, annotations, drawings, videos, reports, and more.
- Variables:
base_url (str) – The base URL for the T2D2 API endpoints
headers (dict) – Headers sent with each API request (includes content type and authorization)
s3_base_url (str) – The base URL for S3 storage where data is stored or retrieved
aws_region (str) – The AWS region for S3 interactions
bucket (str) – The name of the S3 bucket used for storing data
access_token (str) – The token used for authenticating API requests
api_key (str) – The API key used for authenticating with the T2D2 API
project (dict) – A dictionary representing the current project’s data
debug (bool) – A flag to enable or disable debug mode
- add_annotation_class(name, color=None, materials=None)¶
Add a new annotation class to the current project.
This method creates a new annotation class with the specified name, color, and associated materials.
- Parameters:
name (str) – The name of the annotation class to create
color (str, optional) – The color for the annotation class, defaults to a random color
materials (list of str, optional) – A list of materials associated with this class, defaults to an empty list
- Returns:
Response from the API containing information about the created class
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Create a basic annotation class >>> result = client.add_annotation_class('Pedestrian') >>> print(result) >>> >>> # Create an annotation class with specific color and materials >>> result = client.add_annotation_class('Crack', '#FF0000', ['Concrete', 'Asphalt']) >>> print(result)
- add_annotations(image_id, annotations)¶
Add new annotations to an image in the current project.
This method creates new annotations for a specific image. Each annotation is defined by its properties such as class, geometry, and attributes.
- Parameters:
image_id (str) – The ID of the image to which annotations will be added
annotations (list of dict) – A list of annotation definitions to be added
- Returns:
Response from the API containing information about the created annotations
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> image_id = 'image123' >>> annotations_to_add = [ ... { ... 'annotation_class_id': 'class1', ... 'coordinates': [[100, 100], [200, 100], [200, 200], [100, 200]], ... 'attributes': {'severity': 'high'} ... }, ... { ... 'annotation_class_id': 'class2', ... 'coordinates': [[300, 300], [400, 400]], ... } ... ] >>> result = client.add_annotations(image_id, annotations_to_add) >>> print(result)
- add_assets(payload)¶
Add assets to the current project.
This generic method adds assets of various types to the project using a structured payload that defines the assets’ properties.
- Parameters:
payload (dict) – A dictionary containing the assets to add
- Returns:
A dictionary containing the API response with status and created asset data
- Return type:
dict
- Raises:
ValueError – If no project has been set or the API request fails
- Example:
>>> asset_data = { ... "project_id": client.project["id"], ... "asset_type": 1, ... "assets": [ ... { ... "name": "Bridge Side View", ... "filename": "bridge_side.jpg", ... "url": "path/to/file.jpg", ... "size": {"filesize": 1024000} ... } ... ] ... } >>> response = client.add_assets(asset_data) >>> print(response["success"]) True
- Note:
This is a lower-level method. Consider using specialized methods like upload_images() or upload_reports() for specific asset types.
- add_geotags(drawing_id, geotags)¶
Add new geotags to a drawing in the current project.
This method creates new geotags associated with the specified drawing. Each geotag is defined by its coordinates and can include additional metadata.
- Parameters:
drawing_id (str) – The ID of the drawing to which the geotags will be added
geotags (list of dict) – A list of geotag definitions to be added
- Returns:
Response from the API containing information about the created geotags
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> drawing_id = 'drawing123' >>> geotags_to_add = [ ... {'latitude': 40.7128, 'longitude': -74.0060, 'tags': ['tag1', 'tag2']}, ... {'latitude': 34.0522, 'longitude': -118.2437} ... ] >>> result = client.add_geotags(drawing_id, geotags_to_add) >>> print(result)
- add_region(region_name: str)¶
Add a new region to the current project.
Regions in T2D2 represent geographical or logical divisions within a project, allowing for better organization of assets and data.
- Parameters:
region_name (str) – The name of the region to add
- Returns:
A dictionary containing the API response with status and region data
- Return type:
dict
- Raises:
ValueError – If no project has been set using set_project()
- Example:
>>> response = client.add_region("North Tower") >>> print(response["success"]) True >>> print(response["data"]["name"]) 'North Tower'
- add_tags(tags)¶
Add new tags to the current project.
This method creates new tags within the project. Each tag is defined by a name. If a tag already exists, a warning is printed and the operation for that tag is skipped.
- Parameters:
tags (str or list of str) – Either a single tag name (string) or a list of tag names
- Returns:
List of API responses for each successfully created tag
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Add a single tag >>> result = client.add_tags('New Tag') >>> print(result) >>> >>> # Add multiple tags >>> result = client.add_tags(['Tag 1', 'Tag 2', 'Tag 3']) >>> print(result)
- delete_annotation_classes(annotation_class_ids)¶
Delete annotation classes from the current project.
This method removes annotation classes identified by their IDs from the project. This operation is irreversible.
- Parameters:
annotation_class_ids (list of str or int) – One or more annotation class IDs to delete
- Returns:
Response from the API indicating the status of the deletion operation
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Delete a single annotation class >>> result = client.delete_annotation_classes('class1_id') >>> print(result) >>> >>> # Delete multiple annotation classes >>> result = client.delete_annotation_classes(['class1_id', 'class2_id']) >>> print(result)
- delete_annotations(image_id, annotation_ids=None)¶
Delete annotations from an image in the current project.
This method removes annotations from a specific image. If annotation_ids is provided, it deletes those specific annotations. If annotation_ids is None, it deletes all annotations in the image.
- Parameters:
image_id (str) – The ID of the image from which to delete annotations
annotation_ids (list of str, optional) – A list of annotation IDs to delete, defaults to None (all annotations)
- Returns:
Response from the API indicating the status of the deletion operation
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Delete specific annotations from an image >>> image_id = 'image123' >>> annotation_ids = ['ann1', 'ann2'] >>> result = client.delete_annotations(image_id, annotation_ids) >>> print(result) >>> >>> # Delete all annotations from an image >>> image_id = 'image123' >>> result = client.delete_annotations(image_id) >>> print(result)
- delete_drawings(drawing_ids)¶
Delete drawings from the current project.
This method removes drawings from the project based on their IDs. This operation is irreversible and will also delete all associated data.
- Parameters:
drawing_ids (list) – A list of drawing IDs to delete
- Returns:
A dictionary containing the API response with status and result information
- Return type:
dict
- Raises:
ValueError – If no project has been set or the delete operation fails
- Example:
>>> drawing_ids = ["dwg_123", "dwg_456"] >>> response = client.delete_drawings(drawing_ids) >>> print(response["success"]) True >>> print(f"Deleted {len(response['data']['deleted_ids'])} drawings")
- Warning:
This operation cannot be undone. All drawing data and associated information will be permanently removed from the project.
- delete_geotags(drawing_id, geotag_ids)¶
Delete specified geotags from a drawing in the current project.
This method removes geotags identified by their IDs from a specified drawing. This operation is irreversible.
- Parameters:
drawing_id (str) – The ID of the drawing from which the geotags will be deleted
geotag_ids (list of str) – A list of geotag IDs to delete
- Returns:
Response from the API indicating the status of the deletion operation
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> drawing_id = 'drawing123' >>> geotag_ids = ['geotag1', 'geotag2'] >>> result = client.delete_geotags(drawing_id, geotag_ids) >>> print(result)
- delete_images(image_ids)¶
Delete images from the current project.
This method removes images from the project based on their IDs. This operation is irreversible and will also delete all associated annotations and data.
- Parameters:
image_ids (list) – A list of image IDs to delete
- Returns:
A dictionary containing the API response with status and result information
- Return type:
dict
- Raises:
ValueError – If no project has been set or the delete operation fails
- Example:
>>> image_ids = ["img_123", "img_456"] >>> response = client.delete_images(image_ids) >>> print(response["success"]) True >>> print(f"Deleted {len(response['data']['deleted_ids'])} images")
- Warning:
This operation cannot be undone. All image data and associated annotations will be permanently removed from the project.
- delete_reports(report_ids)¶
Delete reports from the current project.
This method removes reports identified by their IDs from the current project. This operation is irreversible.
- Parameters:
report_ids (list of str) – A list of report IDs to delete from the project
- Returns:
Response from the API indicating which reports were successfully deleted
- Return type:
dict
- Raises:
ValueError – If no project is currently set or if report_ids is empty or not a list
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> report_ids = ['report1_id', 'report2_id'] >>> response = client.delete_reports(report_ids) >>> print(response)
- delete_threed(model_ids)¶
Delete 3D models from the current project.
This method removes 3D models identified by their IDs from the current project. This operation is irreversible.
- Parameters:
model_ids (list of str) – A list of 3D model IDs to delete from the project
- Returns:
Response from the API indicating which models were successfully deleted
- Return type:
dict
- Raises:
ValueError – If no project is currently set or if model_ids is empty or not a list
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> model_ids = ['model1_id', 'model2_id'] >>> response = client.delete_threed(model_ids) >>> print(response)
- delete_videos(video_ids)¶
Delete videos from the current project.
This method removes videos identified by their IDs from the current project. This operation is irreversible.
- Parameters:
video_ids (list of str) – A list of video IDs to delete from the project
- Returns:
Response from the API indicating which videos were successfully deleted
- Return type:
dict
- Raises:
ValueError – If no project is currently set or if video_ids is empty or not a list
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> video_ids = ['abc123', 'def456'] >>> response = client.delete_videos(video_ids) >>> print(response)
- download_assets(asset_ids, asset_type=1, download_dir='./', original_filename=False)¶
Download assets from the project to the local filesystem.
This method retrieves assets by their IDs, downloads them from storage, and saves them to the specified directory.
- Parameters:
asset_ids (list) – A list of asset IDs to download
asset_type (int) – The numeric type of assets to download
download_dir (str) – The local directory path where assets will be saved
original_filename (bool) – Whether to use the original filename (True) or generate a name based on the asset ID (False)
- Default asset_type:
1
- Default download_dir:
“./” (current directory)
- Default original_filename:
False
- Returns:
A dictionary mapping asset IDs to their local file paths
- Return type:
dict
- Raises:
ValueError – If no project has been set, if some assets are not found, or if downloading fails
- Example:
>>> image_ids = ["img_123", "img_456"] >>> file_paths = client.download_assets( ... asset_ids=image_ids, ... asset_type=1, ... download_dir="./images", ... original_filename=True ... ) >>> for asset_id, path in file_paths.items(): ... print(f"Asset {asset_id} downloaded to {path}")
- get_ai_model_by_id(model_id)¶
Retrieve details of a specific AI model by its ID.
This method fetches detailed information about a specific AI model from the T2D2 API. It returns a dictionary containing all the information available for the specified AI model.
- Parameters:
model_id (str) – The ID of the AI model to retrieve
- Returns:
A dictionary containing AI model details
- Return type:
dict
- get_ai_models()¶
Retrieve all AI models available in the current project.
This method fetches all AI models associated with the current project from the T2D2 API. It returns a list of dictionaries containing details about each AI model.
- Returns:
A list of dictionaries, each containing AI model details
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> models = client.get_ai_models() >>> print(models)
- get_annotation_classes(params=None)¶
Retrieve annotation classes from the current project.
This method queries the project’s database for annotation classes defined within the project. It returns information about each class including ID, name, and attributes.
- Parameters:
params (dict, optional) – Additional query parameters to filter classes, defaults to None
- Returns:
Information about annotation classes in the project
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> annotation_classes = client.get_annotation_classes() >>> print(annotation_classes) {'label_list': [{'id': 'class1', 'name': 'Vehicle', 'attributes': ['color', 'make']}, ...]}
- get_annotations(image_id=None, params=None)¶
Retrieve annotations from the current project.
This method queries the project for annotations. If image_id is provided, it retrieves annotations for that specific image. If image_id is None, it retrieves annotations for all images matching the provided params.
- Parameters:
image_id (str, optional) – The ID of the image for which to retrieve annotations, defaults to None
params (dict, optional) – Additional query parameters to filter images, defaults to None
- Returns:
A list of dictionaries, each containing details of an annotation
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Get annotations for a specific image >>> image_id = 'image123' >>> annotations = client.get_annotations(image_id) >>> print(annotations) >>> >>> # Get annotations for images matching certain criteria >>> params = {'region_id': 'region1', 'date_from': '2023-01-01'} >>> all_annotations = client.get_annotations(params=params) >>> print(all_annotations)
- get_assets(asset_type=1, asset_ids=None)¶
Retrieve a list of assets based on specified IDs and asset type.
This method fetches detailed information about specific assets in the project.
- Parameters:
asset_type (int) – The numeric type of assets to retrieve
asset_ids (list) – A list of asset IDs to retrieve
- Default asset_type:
1
- Default asset_ids:
None
- Returns:
A list of dictionaries, each containing detailed information about an asset
- Return type:
list
- Raises:
ValueError – If no project has been set or the API request fails
- Example:
>>> image_ids = ["img_123", "img_456"] >>> images = client.get_assets(asset_type=1, asset_ids=image_ids) >>> for img in images: ... print(f"Image: {img['filename']}, URL: {img['url']}")
- Note:
If asset_ids is None, an empty list is returned
- get_classes()¶
Retrieve annotation classes with associated conditions.
This method retrieves all annotation classes from the current project and maps them to their corresponding conditions. It returns a list of condition objects enriched with the name of the annotation class they belong to.
- Returns:
A list of dictionaries, each containing condition details with associated class name
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> classes = client.get_classes() >>> print(classes) [{'id': 'cond1', 'name': 'Crack', 'annotation_class_id': 'class1', ...}, ...]
- get_drawings(drawing_ids=None, params=None)¶
Retrieve drawings from the current project.
This method fetches drawing data either for specific drawing IDs or for all drawings in the project if no IDs are specified.
- Parameters:
drawing_ids (list or None) – A list of specific drawing IDs to retrieve, or None to get all drawings
params (dict or None) – Additional parameters to filter the drawing results, which may include: - region_id: Filter drawings by region - tag_ids: Filter drawings by associated tags - date_range: Filter drawings by upload date - limit/offset: Pagination parameters
- Default drawing_ids:
None
- Default params:
None
- Returns:
A list of dictionaries, each containing detailed information about a drawing
- Return type:
list
- Raises:
ValueError – If no project has been set or the request fails
- Example:
>>> # Get all drawings in a project >>> all_drawings = client.get_drawings() >>> print(f"Total drawings: {len(all_drawings)}")
>>> # Get specific drawings by ID >>> specific_drawings = client.get_drawings(["dwg_123", "dwg_456"]) >>> for dwg in specific_drawings: ... print(f"Drawing: {dwg['filename']}, Region: {dwg['region']['name']}")
>>> # Get drawings with filtering >>> filtered_drawings = client.get_drawings(params={"region_id": "region123"}) >>> print(f"Drawings in region: {len(filtered_drawings)}")
- get_geotags(drawing_id, params=None)¶
Retrieve geotags associated with a drawing in the current project.
This method queries the project’s database for geotags associated with the specified drawing. Additional filter parameters can be provided through the params argument.
- Parameters:
drawing_id (str) – The ID of the drawing for which to retrieve geotags
params (dict, optional) – Additional query parameters to filter geotags, defaults to None
- Returns:
A list of dictionaries, each containing details of a geotag
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> drawing_id = 'drawing123' >>> geotags = client.get_geotags(drawing_id) >>> print(geotags) [{'id': 'geotag1', 'latitude': 40.7138, 'longitude': -74.0065, 'tags': ['tag1']}, ...]
- get_images(image_ids=None, params=None)¶
Retrieve images from the current project.
This method fetches image data either for specific image IDs or for all images in the project if no IDs are specified.
- Parameters:
image_ids (list or None) – A list of specific image IDs to retrieve, or None to get all images
params (dict or None) – Additional parameters to filter the image results, which may include: - region_id: Filter images by region - tag_ids: Filter images by associated tags - date_range: Filter images by capture date - limit/offset: Pagination parameters - search: Search term for filtering images - sortBy: Sort order (e.g. “id:-1” for descending) - page: Page number for pagination - regions: List of region IDs to filter by - image_types: List of image type IDs to filter by
- Default image_ids:
None
- Default params:
None
- Returns:
A list of dictionaries, each containing detailed information about an image
- Return type:
list
- Raises:
ValueError – If no project has been set or the request fails
- Example:
>>> # Get all images in a project >>> all_images = client.get_images() >>> print(f"Total images: {len(all_images)}")
>>> # Get specific images by ID >>> specific_images = client.get_images(["img_123", "img_456"]) >>> for img in specific_images: ... print(f"Image: {img['filename']}, Region: {img['region']['name']}")
>>> # Get images with filtering >>> filtered_images = client.get_images(params={ ... "search": "", ... "sortBy": "id:-1", ... "page": 1, ... "limit": 10, ... "regions": ["6841697bf8ab7deb15ededc8"], ... "image_types": [1, 2, 4] ... }) >>> print(f"Images in region: {len(filtered_images)}")
- get_materials()¶
Retrieve materials from the current project.
This method queries the project’s database for a list of all materials that have been defined within the project.
- Returns:
Information about materials in the project
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> materials = client.get_materials() >>> print(materials) {'material_list': ['Concrete', 'Steel', 'Wood']}
- get_project(project_id=None)¶
Retrieve a project by ID or get a list of all projects.
If project_id is provided, returns data for the specific project. If project_id is None, returns a list of all available projects.
- Parameters:
project_id (str or None) – The ID of the specific project to retrieve
- Default project_id:
None
- Returns:
Project data dictionary for a specific project, or a list of projects
- Return type:
dict
- Raises:
ValueError – If the API request fails or the project_id is invalid
- Example:
>>> # Get a specific project >>> project = client.get_project("project_123abc") >>> print(project["profile"]["name"]) 'Bridge Inspection'
>>> # Get all projects >>> all_projects = client.get_project() >>> print(len(all_projects["project_list"])) 5
- get_project_info()¶
Retrieve a summary of the current active project’s information.
This method returns a dictionary containing the essential information about the currently selected project, including its ID, name, address, description, creation details, and statistics.
- Returns:
A dictionary containing the project information with the following keys: - id: The project’s unique identifier - name: The project’s display name - address: The physical address/location of the project - description: A text description of the project - created_by: Username of the project creator - created_at: Formatted creation date and time - statistics: Dictionary containing project statistics
- Return type:
dict
- Raises:
ValueError – If no project has been set using set_project()
- Example:
>>> client.set_project("project_123abc") >>> info = client.get_project_info() >>> print(info["name"]) 'Bridge Inspection' >>> print(info["created_at"]) '2023-04-15 14:30:22'
- get_regions()¶
Retrieve all regions from the current project.
This method returns a list of all regions defined in the project.
- Returns:
A list of dictionaries, each containing region details
- Return type:
list
- Raises:
ValueError – If no project has been set using set_project()
- Example:
>>> regions = client.get_regions() >>> for region in regions: ... print(f"Region: {region['name']}, ID: {region['_id']}") Region: North Tower, ID: reg_123abc Region: South Tower, ID: reg_456def
- get_reports(report_ids=None, params=None)¶
Retrieve reports from the current project.
This method queries the project for details on reports identified by their unique IDs. It returns information about each report, including metadata.
- Parameters:
report_ids (list of str, optional) – A list of report IDs for which details are to be retrieved, defaults to None
params (dict, optional) – Additional query parameters to pass to the API, defaults to None
- Returns:
A list of dictionaries, each containing details of a report
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> report_ids = ['report1_id', 'report2_id'] >>> report_details = client.get_reports(report_ids) >>> print(report_details) [{'id': 'report1_id', 'title': 'Report One', 'creation_date': '2023-01-01'}, ...]
- get_tags(params=None)¶
Retrieve tags from the current project.
This method queries the project for all tags or specific tags based on the provided parameters. It returns information about each tag, including its name and associated metadata.
- Parameters:
params (dict, optional) – Additional query parameters to filter tags, defaults to None
- Returns:
Tag data from the API response
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Get all tags >>> all_tags = client.get_tags() >>> print(all_tags) >>> >>> # Get tags with specific filter >>> filtered_tags = client.get_tags(params={'name': 'example'}) >>> print(filtered_tags)
- get_task_by_id(task_id)¶
Get the details of a specific task by its ID.
This method fetches detailed information about a specific task from the T2D2 API. It returns a dictionary containing all the information available for the specified task.
- Parameters:
task_id (str) – The ID of the task to retrieve
- Returns:
A dictionary containing task details
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> task = client.get_task_by_id("9d9f28a5-df16-4f69-bbc9-4dc718ea204c") >>> print(task)
- get_task_list()¶
Get the list of tasks for the current project.
This method fetches the list of tasks associated with the current project from the T2D2 API. It returns a list of dictionaries containing details about each task.
- Returns:
A list of dictionaries, each containing task details
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> tasks = client.get_task_list() >>> print(tasks)
- get_threed(model_ids=None, params=None)¶
Retrieve 3D models from the current project.
This method queries the project for details on 3D models. If model_ids is provided, it returns details for those specific models. If model_ids is None, all 3D models in the project are returned.
- Parameters:
model_ids (list of str, optional) – A list of 3D model IDs to retrieve, defaults to None
params (dict, optional) – Additional query parameters to pass to the API, defaults to None
- Returns:
A list of dictionaries, each containing details of a 3D model
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Get all 3D models in project >>> all_models = client.get_threed() >>> >>> # Get specific models by IDs >>> model_ids = ['model1_id', 'model2_id'] >>> specific_models = client.get_threed(model_ids) >>> print(specific_models) [{'id': 'model1_id', 'name': 'model1.obj', 'size': '2MB'}, {'id': 'model2_id', ...}]
- get_videos(video_ids=None, params=None)¶
Retrieve videos from the current project.
This method queries the T2D2 API to fetch details for videos in the current project. If video_ids is provided, it returns details for those specific videos. If video_ids is None, all videos in the project are returned.
- Parameters:
video_ids (list of str, optional) – A list of video IDs for which details are to be retrieved, defaults to None
params (dict, optional) – Additional query parameters to pass to the API, defaults to None
- Returns:
A list of dictionaries, each containing details of a video
- Return type:
list of dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> # Get all videos in project >>> all_videos = client.get_videos() >>> >>> # Get specific videos by IDs >>> video_ids = ['abc123', 'def456'] >>> specific_videos = client.get_videos(video_ids) >>> print(specific_videos) [{'id': 'abc123', 'title': 'Video One', ...}, {'id': 'def456', ...}]
- login(credentials)¶
Authenticate with the T2D2 API using provided credentials.
This method supports three authentication methods: 1. Direct access token authentication 2. Username/password login 3. API key authentication
Upon successful authentication, the appropriate authorization header is set for future requests.
- Parameters:
credentials (dict) – Authentication credentials dictionary which must include one of: - ‘access_token’: Direct token for authentication - ‘username’ and ‘password’: For login-based authentication - ‘api_key’: API key for authentication
- Returns:
None
- Raises:
ValueError – If the provided credentials are invalid, missing required fields, or if the authentication request fails
- Example:
>>> client.login({'access_token': 'your-access-token'}) >>> client.login({'username': 'user@example.com', 'password': 'password123'}) >>> client.login({'api_key': 'your-api-key'})
- notify_user(title, message)¶
Send a notification to the user
- Parameters:
title (str) – The title of the notification.
message (str) – The message content of the notification.
- Returns:
A dictionary containing the response from the API.
- Return type:
dict
- Raises:
ValueError – If the notification could not be sent.
- request(url_suffix: str, req_type: RequestType = RequestType.GET, params=None, headers=None, data=None) dict ¶
Send a request and handle response
- run_ai_inferencer(image_ids, model_id, confidence_threshold=0.5, replace_annotations=False, sliding_window=False, whole_image=True, batch_size=1)¶
Run AI inference on specified images using a selected model.
This method initiates an AI inference process on a set of images using the specified model. It constructs the payload with model details and user parameters, then sends the request to start the inference process.
- Parameters:
image_ids (list of int) – List of image IDs to run inference on
model_id (int) – ID of the AI model to use for inference
confidence_threshold (float) – Minimum confidence score for detections (0.0 to 1.0)
replace_annotations (bool) – Whether to replace existing annotations
sliding_window (bool) – Whether to use sliding window approach for inference
whole_image (bool) – Whether to process the whole image at once
batch_size (int) – Number of images to process in each batch
- Default confidence_threshold:
0.5
- Default replace_annotations:
False
- Default sliding_window:
False
- Default whole_image:
True
- Default batch_size:
1
- Returns:
Response from the API containing the inference job details
- Return type:
dict
- Raises:
ValueError – If no project is set or if required parameters are invalid
- Example:
>>> image_ids = [000000, 000000, 000000] >>> result = client.run_ai_inferencer( ... image_ids=image_ids, ... model_id=1, ... confidence_threshold=0.6 ... ) >>> print(result)
- set_project(project_id)¶
Set the current active project for the T2D2 client.
This method retrieves the project data by ID, sets it as the active project, and configures related S3 storage settings for the client instance.
- Parameters:
project_id (str) – The ID of the project to set as active
- Returns:
None
- Raises:
ValueError – If the project_id is invalid or the project cannot be accessed
- Example:
>>> client.set_project("project_123abc") >>> print(client.project["profile"]["name"]) 'Bridge Inspection'
- Note:
After setting a project, S3 storage information is automatically configured for use with other methods that require file uploads or downloads.
- slack_notification(payload)¶
Send a notification to Slack.
This method sends a notification to a Slack channel using the T2D2 API. The notification content and destination are specified in the payload.
- Parameters:
payload (dict) – Dictionary containing the notification details
- Returns:
Response from the API indicating whether the notification was sent successfully
- Return type:
dict
- Raises:
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> payload = { ... "channel": "#project-updates", ... "message": "New 3D model uploaded", ... "attachments": [{"title": "Model Details", "text": "Model ID: abc123"}] ... } >>> response = client.slack_notification(payload) >>> print(response)
- summarize_conditions(params=None)¶
Summarize annotations and their conditions by region, label, and rating.
This method analyzes all annotations in the project, grouped by region, and summarizes them based on annotation class label and condition rating. For each combination, it calculates total count, cumulative length, total area, and collects annotation IDs.
- Parameters:
params (dict, optional) – Additional query parameters to filter images, defaults to None
- Returns:
A nested dictionary with regions as top-level keys, each containing summaries for label-rating combinations with count, length, area, and annotation_ids
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> summary = client.summarize_conditions() >>> print(summary) { 'Region A': { ('Crack', 'Severe'): { 'count': 5, 'length': 120.5, 'area': 45.2, 'annotation_ids': ['ann1', 'ann2', ...] }, ... }, 'Region B': {...} }
- summarize_images(params=None)¶
Summarize images in the current project by region, date, and tags.
This method analyzes all images in the project and groups them by region, capture date, and assigned tags. It returns counts for each group category.
- Parameters:
params (dict, optional) – Additional query parameters to filter images, defaults to None
- Returns:
A dictionary with three subdictionaries: ‘region_group’, ‘date_group’, and ‘tag_group’ Each containing counts of images per category
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> summary = client.summarize_images() >>> print(summary) { 'region_group': {'Region A': 10, 'Region B': 5}, 'date_group': {'2023-01-15': 7, '2023-01-16': 8}, 'tag_group': {'Priority': 3, 'Review': 12} }
- update_drawings(drawing_ids, payload)¶
Update properties of existing drawings in the current project.
This method allows you to modify drawing metadata such as region, tags, and name.
- Parameters:
drawing_ids (list) – A list of drawing IDs to update
payload (dict) – A dictionary containing the updates to apply, which may include: - region_id: ID of the region to associate with the drawings - name: Updated name for the drawings - tag_ids: List of tag IDs to associate with the drawings - region: Dict with region_id and name (e.g., {“region_id”: “6281d46733c74ef808a4812e”, “name”: “default”})
- Returns:
A dictionary containing the API response with status and updated drawing data
- Return type:
dict
- Raises:
ValueError – If no project has been set or the update fails
- Example:
>>> drawing_ids = ["dwg_123", "dwg_456"] >>> updates = { ... "name": "Updated Drawing Name", ... "tag_ids": [123, 456], ... "region": {"region_id": "6281d46733c74ef808a4812e", "name": "default"} ... } >>> response = client.update_drawings(drawing_ids, updates) >>> print(response["success"]) True
- update_images(image_ids, payload)¶
Update properties of existing images in the current project.
This method allows you to modify image metadata such as region, tags, and notes.
- Parameters:
image_ids (list) – A list of image IDs to update
payload (dict) – A dictionary containing the updates to apply, which may include: - region_id: ID of the region to associate with the images - name: Updated name for the images - tag_ids: List of tag IDs to associate with the images - notes: Updated text notes for the images - scale: Updated image scale information
- Returns:
A dictionary containing the API response with status and updated image data
- Return type:
dict
- Raises:
ValueError – If no project has been set or the update fails
- Example:
>>> image_ids = ["img_123", "img_456"] >>> updates = { ... "region_id": "region789", ... "name": "Updated Image Name", ... "notes": "These images show deterioration in the north section", ... "tag_ids": [123, 4567] ... } >>> response = client.update_images(image_ids, updates) >>> print(response["success"]) True
- update_region(region_name: str, new_region: dict)¶
Update an existing region in the current project.
This method finds a region by name and updates its properties with the provided values.
- Parameters:
region_name (str) – The name of the region to update
new_region (dict) – Dictionary containing the updated region properties
- Returns:
A dictionary containing the API response with status and updated region data
- Return type:
dict
- Raises:
ValueError – If no project has been set or if the specified region cannot be found
- Example:
>>> updated_data = {"name": "North Tower A", "description": "Northern section of the tower"} >>> response = client.update_region("North Tower", updated_data) >>> print(response["data"]["name"]) 'North Tower A'
- update_reports(report_ids, payload)¶
Update reports in the current project.
This method updates the details of reports identified by their IDs in the current project. The updates are specified in the payload dictionary and are applied to each report.
- Parameters:
report_ids (list of str) – A list of report IDs to update
payload (dict) – Dictionary containing the fields to update and their new values
- Returns:
Response from the API containing information about the updated reports
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> report_ids = ['report1_id', 'report2_id'] >>> payload = {'title': 'Updated Report Title', 'status': 'Completed'} >>> response = client.update_reports(report_ids, payload) >>> print(response)
- update_threed(model_ids, payload)¶
Update 3D models in the current project.
This method updates the details of 3D models identified by their IDs in the current project. The updates are specified in the payload dictionary and are applied to each model.
- Parameters:
model_ids (list of str) – A list of 3D model IDs to update
payload (dict) – Dictionary containing the fields to update and their new values
- Returns:
Response from the API containing information about the updated models
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> model_ids = ['model1_id', 'model2_id'] >>> payload = {'name': 'New Model Name', 'description': 'Updated description'} >>> response = client.update_threed(model_ids, payload) >>> print(response)
- update_videos(video_ids, payload)¶
Update multiple videos in the current project.
This method updates the details of videos identified by their IDs in the current project. The updates are specified in the payload dictionary and are applied to each video.
- Parameters:
video_ids (list of str) – A list of video IDs to update
payload (dict) – Dictionary containing the fields to update and their new values
- Returns:
Response from the API containing information about the updated videos
- Return type:
dict
- Raises:
ValueError – If no project is currently set
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> video_ids = ['abc123', 'def456'] >>> payload = {'title': 'New Title', 'description': 'Updated description'} >>> response = client.update_videos(video_ids, payload) >>> print(response)
- upload_downloads(file_paths)¶
Upload files to the downloads section of the current project.
This method uploads files to the downloads section of the current project. Each file is uploaded to a pre-specified storage location and is associated with the project.
- Parameters:
file_paths (list of str) – A list of file paths to be uploaded
- Returns:
Dictionary indicating success or failure of the upload operation
- Return type:
dict
- Raises:
ValueError – If no project is currently set or if upload fails
FileNotFoundError – If any path in file_paths does not point to an existing file
ConnectionError – If there is a problem connecting to the storage service
- Example:
>>> file_paths = ['/path/to/report.pdf', '/path/to/data.zip'] >>> result = client.upload_downloads(file_paths) >>> print(result) {'success': True, 'message': 'Files uploaded'}
- upload_drawings(drawing_paths, params=None)¶
Upload drawings to the current project.
This method uploads drawing files from local paths to the project’s S3 storage and registers them with the T2D2 API.
- Parameters:
drawing_paths (list) – A list of local file paths for the drawings to upload
params (dict or None) – Additional parameters to include in the upload, which may include: - name: Name for the drawings - tag_ids: List of tag IDs to associate with the drawings - region: Dict with region_id and name (e.g., {“region_id”: “6281d46733c74ef808a4812e”, “name”: “default”})
- Default params:
None
- Returns:
A dictionary containing the API response with status and created drawing data
- Return type:
dict
- Raises:
ValueError – If no project has been set or the upload fails
- Example:
>>> drawing_paths = ["./drawings/floor_plan.pdf", "./drawings/elevation.dwg"] >>> params = { ... "name": "Building Plans", ... "tag_ids": [123, 456], ... "region": {"region_id": "6281d46733c74ef808a4812e", "name": "default"} ... } >>> response = client.upload_drawings(drawing_paths, params=params) >>> print(response["success"]) True
- upload_images(image_paths, image_type=1, params=None)¶
Upload images to the current project.
This method uploads images from local paths to the project’s S3 storage and registers them with the T2D2 API.
- Parameters:
image_paths (list) – A list of local file paths for the images to upload
image_type (int) – The type of image to upload (1=regular images, 3=orthomosaics)
params (dict or None) – Additional parameters to include in the upload, which may include: - region: Dict with region_id and name (e.g., {“region_id”: “id123”, “name”: “default”}) - notes: Text notes for the images - tag_ids: List of tag IDs to associate with the images - scale: Image scale information
- Default image_type:
1
- Default params:
None
- Returns:
A dictionary containing the API response with status and created image data
- Return type:
dict
- Raises:
ValueError – If no project has been set or the upload fails
- Example:
>>> image_paths = ["./images/bridge1.jpg", "./images/bridge2.jpg"] >>> params = { ... "region": {"region_id": "region123", "name": "North Section"}, ... "notes": "Initial inspection images", ... "tag_ids": [1234, 4567] ... } >>> response = client.upload_images(image_paths, params=params) >>> print(response["success"]) True
- upload_reports(report_paths)¶
Upload report files to the current project.
This method takes a list of file paths pointing to report files (PDF or docx) and uploads them to the T2D2 project. Each file is uploaded to a storage location and then registered within the project.
- Parameters:
report_paths (list of str) – A list of file paths to report files (PDF or docx)
- Returns:
Response from the API containing information about the uploaded reports
- Return type:
dict
- Raises:
ValueError – If report_paths is empty, not a list, or if no project is set
FileNotFoundError – If any path does not point to an existing file
ConnectionError – If there is a problem connecting to the T2D2 API
- Example:
>>> report_path = "./reports/report_123.pdf" >>> response = client.upload_reports([report_path]) >>> print(response)
- upload_threed(threed_paths)¶
Upload 3D model files to the current project.
This method takes a list of file paths pointing to 3D model files and uploads them to the T2D2 project. Each file is uploaded to a storage location and then registered within the project with a unique identifier.
- Parameters:
threed_paths (list of str) – A list of file paths to 3D model files
- Returns:
Response from the API containing information about the uploaded models
- Return type:
dict
- Raises:
FileNotFoundError – If any path in threed_paths does not point to an existing file
ConnectionError – If there is a problem connecting to the API or storage location
ValueError – If threed_paths is empty, not a list, or if no project is set
- Example:
>>> threed_paths = ['/path/to/model1.obj', '/path/to/model2.stl'] >>> response = client.upload_threed(threed_paths) >>> print(response)
- upload_videos(video_paths)¶
Upload videos to the current project.
This method uploads a list of videos to the current project. Each video is first uploaded to S3 storage and then registered as an asset in the project.
- Parameters:
video_paths (list of str) – A list of file paths to the videos to be uploaded
- Returns:
Response from the API containing information about the uploaded videos
- Return type:
dict
- Raises:
ValueError – If no project is currently set
- Example:
>>> video_paths = ['/path/to/video1.mp4', '/path/to/video2.mp4'] >>> response = client.upload_videos(video_paths) >>> print(response)
- t2d2_sdk.download_file(url: str, file_path: str)¶
Download a file from an S3 URL to a local path.
This function parses the S3 URL to extract bucket and key information, then downloads the file to the specified local path.
- Parameters:
url (str) – S3 URL of the file to download
file_path (str) – Local path where the file should be saved
- Returns:
Dictionary containing success status and message
- Return type:
dict
- Raises:
Exception – If there is an error during download
- Example:
>>> download_file('s3://my-bucket/path/to/file.jpg', '/local/path/file.jpg') {'success': True, 'message': 'File downloaded'}
- t2d2_sdk.random_color() str ¶
Generate a random hexadecimal color code.
- Returns:
A random color in hexadecimal format (e.g., ‘#FF5733’)
- Return type:
str
- Example:
>>> random_color() '#A2B9C7'
- t2d2_sdk.random_string(length: int = 6) str ¶
Generate a random string of fixed length.
- Parameters:
length (int) – The length of the random string to generate
- Default length:
6
- Returns:
A random string consisting of lowercase ASCII letters
- Return type:
str
- Example:
>>> random_string() 'abcdef' >>> random_string(10) 'abcdefghij'
- t2d2_sdk.ts2date(ts)¶
Convert a Unix timestamp to a human-readable date string.
- Parameters:
ts (int or float) – Unix timestamp to convert
- Returns:
Formatted date string in ‘YYYY-MM-DD HH:MM:SS’ format
- Return type:
str
- Example:
>>> ts2date(1609459200) '2021-01-01 00:00:00'
- t2d2_sdk.upload_file(file_path: str, url: str)¶
Upload a file from a local path to an S3 URL.
This function parses the S3 URL to extract bucket and key information, then uploads the file from the specified local path with public-read ACL.
- Parameters:
file_path (str) – Local path of the file to upload
url (str) – S3 URL where the file should be uploaded
- Returns:
Dictionary containing success status and message
- Return type:
dict
- Raises:
Exception – If there is an error during upload
- Example:
>>> upload_file('/local/path/file.jpg', 's3://my-bucket/path/to/file.jpg') {'success': True, 'message': 'File uploaded'}