Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rules improvements #295

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions generated/docs/ActionsApi.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,13 +296,23 @@ with groundlight_openapi_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = actions_api.ActionsApi(api_client)
detector_id = "detector_id_example" # str |
page = 1 # int | A page number within the paginated result set. (optional)
page_size = 1 # int | Number of results to return per page. (optional)

# example passing only required values which don't have defaults set
try:
api_response = api_instance.list_detector_rules(detector_id)
pprint(api_response)
except groundlight_openapi_client.ApiException as e:
print("Exception when calling ActionsApi->list_detector_rules: %s\n" % e)

# example passing only required values which don't have defaults set
# and optional values
try:
api_response = api_instance.list_detector_rules(detector_id, page=page, page_size=page_size)
pprint(api_response)
except groundlight_openapi_client.ApiException as e:
print("Exception when calling ActionsApi->list_detector_rules: %s\n" % e)
```


Expand All @@ -311,6 +321,8 @@ with groundlight_openapi_client.ApiClient(configuration) as api_client:
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**detector_id** | **str**| |
**page** | **int**| A page number within the paginated result set. | [optional]
**page_size** | **int**| Number of results to return per page. | [optional]

### Return type

Expand Down
6 changes: 3 additions & 3 deletions generated/docs/ImageQueriesApi.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,14 @@ configuration.api_key['ApiToken'] = 'YOUR_API_KEY'
with groundlight_openapi_client.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = image_queries_api.ImageQueriesApi(api_client)
detector_id = "detector_id_example" # str | Optionally filter image queries by detector ID. (optional)
page = 1 # int | A page number within the paginated result set. (optional)
page_size = 1 # int | Number of items to return per page. (optional)
predictor_id = "predictor_id_example" # str | Optionally filter image queries by detector ID. (optional)

# example passing only required values which don't have defaults set
# and optional values
try:
api_response = api_instance.list_image_queries(page=page, page_size=page_size, predictor_id=predictor_id)
api_response = api_instance.list_image_queries(detector_id=detector_id, page=page, page_size=page_size)
pprint(api_response)
except groundlight_openapi_client.ApiException as e:
print("Exception when calling ImageQueriesApi->list_image_queries: %s\n" % e)
Expand All @@ -219,9 +219,9 @@ with groundlight_openapi_client.ApiClient(configuration) as api_client:

Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**detector_id** | **str**| Optionally filter image queries by detector ID. | [optional]
**page** | **int**| A page number within the paginated result set. | [optional]
**page_size** | **int**| Number of items to return per page. | [optional]
**predictor_id** | **str**| Optionally filter image queries by detector ID. | [optional]

### Return type

Expand Down
10 changes: 10 additions & 0 deletions generated/groundlight_openapi_client/api/actions_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ def __init__(self, api_client=None):
params_map={
"all": [
"detector_id",
"page",
"page_size",
],
"required": [
"detector_id",
Expand All @@ -186,12 +188,18 @@ def __init__(self, api_client=None):
"allowed_values": {},
"openapi_types": {
"detector_id": (str,),
"page": (int,),
"page_size": (int,),
},
"attribute_map": {
"detector_id": "detector_id",
"page": "page",
"page_size": "page_size",
},
"location_map": {
"detector_id": "path",
"page": "query",
"page_size": "query",
},
"collection_format_map": {},
},
Expand Down Expand Up @@ -434,6 +442,8 @@ def list_detector_rules(self, detector_id, **kwargs):
detector_id (str):

Keyword Args:
page (int): A page number within the paginated result set.. [optional]
page_size (int): Number of results to return per page.. [optional]
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
Expand Down
10 changes: 5 additions & 5 deletions generated/groundlight_openapi_client/api/image_queries_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ def __init__(self, api_client=None):
},
params_map={
"all": [
"detector_id",
"page",
"page_size",
"predictor_id",
],
"required": [],
"nullable": [],
Expand All @@ -140,19 +140,19 @@ def __init__(self, api_client=None):
"validations": {},
"allowed_values": {},
"openapi_types": {
"detector_id": (str,),
"page": (int,),
"page_size": (int,),
"predictor_id": (str,),
},
"attribute_map": {
"detector_id": "detector_id",
"page": "page",
"page_size": "page_size",
"predictor_id": "predictor_id",
},
"location_map": {
"detector_id": "query",
"page": "query",
"page_size": "query",
"predictor_id": "query",
},
"collection_format_map": {},
},
Expand Down Expand Up @@ -377,9 +377,9 @@ def list_image_queries(self, **kwargs):


Keyword Args:
detector_id (str): Optionally filter image queries by detector ID.. [optional]
page (int): A page number within the paginated result set.. [optional]
page_size (int): Number of items to return per page.. [optional]
predictor_id (str): Optionally filter image queries by detector ID.. [optional]
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
Expand Down
2 changes: 1 addition & 1 deletion generated/model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# generated by datamodel-codegen:
# filename: public-api.yaml
# timestamp: 2024-12-10T01:13:13+00:00
# timestamp: 2024-12-12T23:38:24+00:00

from __future__ import annotations

Expand Down
19 changes: 18 additions & 1 deletion spec/public-api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ paths:
schema:
type: string
required: true
- name: page
required: false
in: query
description: A page number within the paginated result set.
schema:
type: integer
- name: page_size
required: false
in: query
description: Number of results to return per page.
schema:
type: integer
tags:
- actions
security:
Expand Down Expand Up @@ -313,6 +325,11 @@ paths:
operationId: List image queries
description: Retrieve a list of image-queries.
parameters:
- in: query
name: detector_id
schema:
type: string
description: Optionally filter image queries by detector ID.
- in: query
name: page
schema:
Expand Down Expand Up @@ -1457,4 +1474,4 @@ servers:
- url: https://device.positronix.ai/device-api
description: Device Prod
- url: https://device.integ.positronix.ai/device-api
description: Device Integ
description: Device Integ
45 changes: 32 additions & 13 deletions src/groundlight/experimental_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,33 @@ def get_rule(self, action_id: int) -> Rule:
"""
return Rule.model_validate(self.actions_api.get_rule(action_id).to_dict())

def list_detector_rules(self, detector: Union[str, Detector], page=1, page_size=10) -> PaginatedRuleList:
"""
Gets a paginated list of rules associated with the given detector.

**Example usage**::

gl = ExperimentalApi()

# Get all rules for a specific detector
rules = gl.list_detector_rules(det_mydetectorid)
for rule in rules.results:
print(f"Rule {rule.id}: {rule.name}")

# Get next page
next_page = gl.list_detector_rules(det_mydetectorid, page=2)

:param detector: the detector or detector_id to get the rules for
:param page: the page number to retrieve (default: 1)
:param page_size: the number of rules per page (default: 10)
:return: a list of Rule objects associated with the given detector
"""
if isinstance(detector, Detector):
detector = detector.id
return PaginatedRuleList.parse_obj(
self.actions_api.list_detector_rules(detector, page=page, page_size=page_size).to_dict()
)

def delete_rule(self, action_id: int) -> None:
"""
Deletes the rule with the given id.
Expand Down Expand Up @@ -255,13 +282,11 @@ def list_rules(self, page=1, page_size=10) -> PaginatedRuleList:
obj = self.actions_api.list_rules(page=page, page_size=page_size)
return PaginatedRuleList.parse_obj(obj.to_dict())

def delete_all_rules(self, detector: Union[None, str, Detector] = None) -> int:
def delete_all_rules(self, detector: Union[str, Detector]) -> int:
"""
Deletes all rules associated with the given detector. If no detector is specified,
deletes all rules in the account.
Deletes all rules associated with the given detector.

WARNING: If no detector is specified, this will delete ALL rules in your account.
This action cannot be undone. Use with caution.
WARNING: This action cannot be undone. Use with caution.

**Example usage**::

Expand All @@ -272,11 +297,7 @@ def delete_all_rules(self, detector: Union[None, str, Detector] = None) -> int:
num_deleted = gl.delete_all_rules(detector)
print(f"Deleted {num_deleted} rules")

# Delete all rules in the account
num_deleted = gl.delete_all_rules()
print(f"Deleted {num_deleted} rules")

:param detector: the detector to delete the rules from. If None, deletes all rules.
:param detector: the detector to delete the rules from.

:return: the number of rules deleted
"""
Expand All @@ -286,9 +307,7 @@ def delete_all_rules(self, detector: Union[None, str, Detector] = None) -> int:
num_rules = self.list_rules().count
for page in range(1, (num_rules // self.ITEMS_PER_PAGE) + 2):
for rule in self.list_rules(page=page, page_size=self.ITEMS_PER_PAGE).results:
if det_id is None:
ids_to_delete.append(rule.id)
elif rule.detector_id == det_id:
if rule.detector_id == det_id:
ids_to_delete.append(rule.id)
for rule_id in ids_to_delete:
self.delete_rule(rule_id)
Expand Down
22 changes: 14 additions & 8 deletions test/unit/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,37 @@


def test_create_action(gl_experimental: ExperimentalApi):
# We first clear out any rules in case the account has any left over from a previous test
gl_experimental.delete_all_rules()
name = f"Test {datetime.utcnow()}"
det = gl_experimental.get_or_create_detector(name, "test_query")
rule = gl_experimental.create_rule(det, f"test_rule_{name}", "EMAIL", "[email protected]")
rule2 = gl_experimental.get_rule(rule.id)
assert rule == rule2


@pytest.mark.skip(reason="actions are global on account, the test matrix collides with itself") # type: ignore
def test_get_all_actions(gl_experimental: ExperimentalApi):
name = f"Test {datetime.utcnow()}"
num_test_rules = 13 # needs to be larger than the default page size
gl_experimental.ITEMS_PER_PAGE = 10
assert gl_experimental.ITEMS_PER_PAGE < num_test_rules
det = gl_experimental.get_or_create_detector(name, "test_query")
gl_experimental.delete_all_rules()
for i in range(num_test_rules):
_ = gl_experimental.create_rule(det, f"test_rule_{i}", "EMAIL", "[email protected]")
rules = gl_experimental.list_rules(page_size=gl_experimental.ITEMS_PER_PAGE)
assert rules.count == num_test_rules
# The exact number of actions is not guaranteed if another client is making calls at the same time
assert rules.count > num_test_rules
assert len(rules.results) == gl_experimental.ITEMS_PER_PAGE
num_deleted = gl_experimental.delete_all_rules()
assert num_deleted == num_test_rules
rules = gl_experimental.list_rules()


def test_delete_actions(gl_experimental: ExperimentalApi):
name = f"Test {datetime.utcnow()}"
num_test_rules = 13 # needs to be larger than the default page size
det = gl_experimental.get_or_create_detector(name, "test_query")
for i in range(num_test_rules):
_ = gl_experimental.create_rule(det, f"test_rule_{i}", "EMAIL", "[email protected]")
rules = gl_experimental.list_detector_rules(det.id)
assert rules.count == num_test_rules
gl_experimental.delete_all_rules(det.id)
rules = gl_experimental.list_detector_rules(det.id)
assert rules.count == 0


Expand Down
Loading