Skip to content

Commit e0e8265

Browse files
author
Matt Sokoloff
committed
fix mypy
1 parent 6d6462c commit e0e8265

File tree

5 files changed

+51
-50
lines changed

5 files changed

+51
-50
lines changed

labelbox/schema/project.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ def _validate_datetime(string_date: str) -> bool:
327327
try:
328328
datetime.strptime(string_date, "%Y-%m-%d")
329329
except ValueError:
330-
raise ValueError(f"""Incorrect format for: {string_date}.
330+
raise ValueError(f"""Incorrect format for: {string_date}.
331331
Format must be \"YYYY-MM-DD\"""")
332332
return True
333333

labelbox/schema/task.py

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import logging
2+
import json
23
import requests
34
import time
4-
from typing import TYPE_CHECKING, Optional, Dict, Any
5-
from functools import lru_cache
5+
from typing import TYPE_CHECKING, TypeVar, Callable, Optional, Dict, Any, List
66

77
from labelbox.exceptions import ResourceNotFoundError
88
from labelbox.orm.db_object import DbObject
@@ -11,6 +11,11 @@
1111
if TYPE_CHECKING:
1212
from labelbox import User
1313

14+
def lru_cache() -> Callable[..., Callable[..., Dict[str, Any]]]:
15+
pass
16+
else:
17+
from functools import lru_cache
18+
1419
logger = logging.getLogger(__name__)
1520

1621

@@ -73,33 +78,40 @@ def wait_till_done(self, timeout_seconds=300) -> None:
7378
def errors(self) -> Optional[Dict[str, Any]]:
7479
""" Downloads the result file from Task
7580
"""
76-
self.wait_till_done(timeout_seconds=600)
7781
if self.status == "FAILED":
78-
data = self._fetch_remote(self.result_url)
79-
if data:
80-
return data.get('error', None)
81-
elif self.status == "IN_PROGRESS":
82-
raise Exception("Job state IN_PROGRESS. Result not available.")
82+
result = self._fetch_remote_json()
83+
return result['error']
8384
return None
8485

8586
@property
86-
def result(self) -> Dict[str, Any]:
87+
def result(self) -> List[Dict[str, Any]]:
8788
""" Fetch the result for a task
8889
"""
89-
self.wait_till_done(timeout_seconds=600)
90-
if self.status == "COMPLETE":
91-
return self._fetch_remote(self.result_url)
92-
elif self.status == "FAILED":
93-
errors = self.errors
94-
message = errors.get('message') or errors
95-
raise Exception(f"Job failed. Errors : {message}")
90+
if self.status == "FAILED":
91+
raise ValueError(f"Job failed. Errors : {self.errors}")
9692
else:
97-
raise Exception("Job state IN_PROGRESS. Result not available.")
93+
result = self._fetch_remote_json()
94+
return [{
95+
'id': data_row['id'],
96+
'external_id': data_row.get('externalId'),
97+
'row_data': data_row['rowData']
98+
} for data_row in result['createdDataRows']]
9899

99100
@lru_cache()
100-
def _fetch_remote(self, result_url) -> Dict[str, Any]:
101+
def _fetch_remote_json(self) -> Dict[str, Any]:
101102
""" Function for fetching and caching the result data.
102103
"""
103-
response = requests.get(result_url)
104+
if self.name != 'JSON Import':
105+
raise ValueError(
106+
"Task result is only supported for `JSON Import` tasks."
107+
" Download task.result_url manually to access the result for other tasks."
108+
)
109+
self.wait_till_done(timeout_seconds=600)
110+
if self.status == "IN_PROGRESS":
111+
raise ValueError(
112+
"Job status still in `IN_PROGRESS`. The result is not available. Increase timeout or contact support."
113+
)
114+
115+
response = requests.get(self.result_url)
104116
response.raise_for_status()
105117
return response.json()

tests/data/metrics/confusion_matrix/t.py

Lines changed: 0 additions & 23 deletions
This file was deleted.

tests/integration/test_data_rows.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -557,7 +557,5 @@ def test_create_data_rows_result(client, dataset, image_url):
557557
},
558558
])
559559
assert task.errors is None
560-
assert 'createdDataRows' in task.result
561-
results = task.result['createdDataRows']
562-
for result in results:
560+
for result in task.result:
563561
client.get_data_row(result['id'])

tests/integration/test_task.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import pytest
22

3-
from labelbox import DataRow
3+
from labelbox import DataRow, Task
44
from labelbox.schema.data_row_metadata import DataRowMetadataField
55

66
EMBEDDING_SCHEMA_ID = "ckpyije740000yxdk81pbgjdc"
@@ -28,11 +28,10 @@ def test_task_errors(dataset, image_url):
2828
assert 'message' in task.errors
2929
with pytest.raises(Exception) as exc_info:
3030
task.result
31-
assert str(exc_info.value).startswith(
32-
"Job failed. Errors : Failed to validate the metadata")
31+
assert str(exc_info.value).startswith("Job failed. Errors : {")
3332

3433

35-
def test_task_success(dataset, image_url):
34+
def test_task_success_json(dataset, image_url):
3635
client = dataset.client
3736
task = dataset.create_data_rows([
3837
{
@@ -44,3 +43,18 @@ def test_task_success(dataset, image_url):
4443
assert task.status == "COMPLETE"
4544
assert task.errors is None
4645
assert task.result is not None
46+
assert len(task.result)
47+
48+
49+
def test_task_success_label_export(client, configured_project_with_label):
50+
project, _, _, _ = configured_project_with_label
51+
project.export_labels()
52+
user = client.get_user()
53+
task = None
54+
for task in user.created_tasks():
55+
if task.name != 'JSON Import':
56+
break
57+
58+
with pytest.raises(ValueError) as exc_info:
59+
task.result
60+
assert str(exc_info.value).startswith("Task result is only supported for")

0 commit comments

Comments
 (0)