Skip to content

Commit 41b52b1

Browse files
Move custom query strings inline.
1 parent 95512d4 commit 41b52b1

File tree

7 files changed

+117
-219
lines changed

7 files changed

+117
-219
lines changed

labelbox/schema/benchmark.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,8 @@ class Benchmark(DbObject):
1919
reference_label = Relationship.ToOne("Label", False, "reference_label")
2020

2121
def delete(self):
22-
query_str, params = _delete_benchmark(self.reference_label())
23-
self.client.execute(query_str, params)
24-
25-
26-
def _delete_benchmark(label):
27-
label_id_param = "labelId"
28-
query_str = """mutation DeleteBenchmarkPyApi($%s: ID!) {
29-
deleteBenchmark(where: {labelId: $%s}) {id}} """ % (
30-
label_id_param, label_id_param)
31-
return query_str, {label_id_param: label.uid}
22+
label_param = "labelId"
23+
query_str = """mutation DeleteBenchmarkPyApi($%s: ID!) {
24+
deleteBenchmark(where: {labelId: $%s}) {id}} """ % (
25+
label_param, label_param)
26+
self.client.execute(query_str, {label_param: self.reference_label().uid})

labelbox/schema/data_row.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from labelbox.orm import query
2-
from labelbox.orm.db_object import (DbObject, Updateable, Deletable,
3-
BulkDeletable)
2+
from labelbox.orm.db_object import DbObject, Updateable, BulkDeletable
43
from labelbox.orm.model import Entity, Field, Relationship
54
from labelbox.pagination import PaginatedCollection
65

@@ -43,23 +42,19 @@ def create_metadata(self, meta_type, meta_value):
4342
Return:
4443
AssetMetadata DB object.
4544
"""
46-
query_str, params = _create_metadata(meta_type, meta_value, self.uid)
47-
res = self.client.execute(query_str, params)
45+
meta_type_param = "meta_type"
46+
meta_value_param = "meta_value"
47+
data_row_id_param = "data_row_id"
48+
query_str = """mutation CreateAssetMetadataPyApi(
49+
$%s: MetadataType!, $%s: String!, $%s: ID!) {
50+
createAssetMetadata(data: {
51+
metaType: $%s metaValue: $%s dataRowId: $%s}) {%s}} """ % (
52+
meta_type_param, meta_value_param, data_row_id_param,
53+
meta_type_param, meta_value_param, data_row_id_param,
54+
query.results_query_part(Entity.named("AssetMetadata")))
55+
56+
res = self.client.execute(
57+
query_str, {meta_type_param: meta_type, meta_value_param: meta_value,
58+
data_row_id_param: self.uid})
4859
return Entity.named("AssetMetadata")(
4960
self.client, res["data"]["createAssetMetadata"])
50-
51-
52-
def _create_metadata(meta_type, meta_value, data_row_id):
53-
meta_type_param = "meta_type"
54-
meta_value_param = "meta_value"
55-
data_row_id_param = "data_row_id"
56-
query_str = """mutation CreateAssetMetadataPyApi(
57-
$%s: MetadataType!, $%s: String!, $%s: ID!) {
58-
createAssetMetadata(data: {
59-
metaType: $%s metaValue: $%s dataRowId: $%s}) {%s}} """ % (
60-
meta_type_param, meta_value_param, data_row_id_param,
61-
meta_type_param, meta_value_param, data_row_id_param,
62-
query.results_query_part(Entity.named("AssetMetadata")))
63-
return query_str, {meta_type_param: meta_type,
64-
meta_value_param: meta_value,
65-
data_row_id_param: data_row_id}

labelbox/schema/dataset.py

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import os
44

55
from labelbox.exceptions import InvalidQueryError, ResourceNotFoundError
6-
from labelbox.orm import query
76
from labelbox.orm.db_object import DbObject, Updateable, Deletable
87
from labelbox.orm.model import Entity, Field, Relationship
98

@@ -121,9 +120,15 @@ def convert_item(item):
121120
descriptor_url = self.client.upload_data(data)
122121

123122
# Create data source
124-
res = self.client.execute(*_create_data_rows(self.uid, descriptor_url))
123+
dataset_param = "dataSetId"
124+
url_param = "jsonURL"
125+
query_str = """mutation AppendRowsToDatasetPyApi($%s: ID!, $%s: String!){
126+
appendRowsToDataset(data:{datasetId: $%s, jsonFileUrl: $%s}
127+
){ taskId accepted } } """ % (
128+
dataset_param, url_param, dataset_param, url_param)
129+
res = self.client.execute(
130+
query_str, {dataset_param: self.uid, url_param: descriptor_url})
125131
res = res["data"]["appendRowsToDataset"]
126-
127132
if not res["accepted"]:
128133
raise MalformedRequestError(
129134
"Server did not accept DataRow creation request", data)
@@ -167,25 +172,3 @@ def data_row_for_external_id(self, external_id):
167172
raise ResourceNotFoundError(DataRow, where)
168173

169174
return data_rows[0]
170-
171-
172-
def _create_data_rows(dataset_id, json_file_url):
173-
""" Generates the query and parameters dictionary for creating multiple
174-
DataRows for a Dataset.
175-
176-
Args:
177-
dataset_id (str): ID of the Dataset object to create DataRows for.
178-
json_file_url (str): URL of the file containing row data.
179-
Return:
180-
(query_string, parameters_dict)
181-
"""
182-
dataset_param = "dataSetId"
183-
url_param = "jsonURL"
184-
query_str = """mutation AppendRowsToDatasetPyApi(
185-
$%s: ID!, $%s: String!){
186-
appendRowsToDataset(data:{datasetId: $%s, jsonFileUrl: $%s}
187-
){ taskId accepted } } """ % (dataset_param, url_param, dataset_param,
188-
url_param)
189-
190-
return query_str, {dataset_param: dataset_id, url_param: json_file_url}
191-

labelbox/schema/label.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,11 @@ def create_benchmark(self):
4848
Return:
4949
The newly created Benchmark.
5050
"""
51-
query_str, params = _create_benchmark(self)
52-
res = self.client.execute(query_str, params)
51+
label_id_param = "labelId"
52+
query_str = """mutation CreateBenchmarkPyApi($%s: ID!) {
53+
createBenchmark(data: {labelId: $%s}) {%s}} """ % (
54+
label_id_param, label_id_param,
55+
query.results_query_part(Entity.named("Benchmark")))
56+
res = self.client.execute(query_str, {label_id_param: self.uid})
5357
res = res["data"]["createBenchmark"]
5458
return Entity.named("Benchmark")(self.client, res)
55-
56-
57-
def _create_benchmark(label):
58-
label_id_param = "labelId"
59-
query_str = """mutation CreateBenchmarkPyApi($%s: ID!) {
60-
createBenchmark(data: {labelId: $%s}) {%s}} """ % (
61-
label_id_param, label_id_param,
62-
query.results_query_part(Entity.named("Benchmark")))
63-
return query_str, {label_id_param: label.uid}

labelbox/schema/project.py

Lines changed: 62 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,29 @@ def create_label(self, **kwargs):
6969
return Label(self.client, res)
7070

7171
def labels(self, datasets=None, order_by=None):
72-
query_string, params = _project_labels(self, datasets, order_by)
73-
return PaginatedCollection(self.client, query_string, params,
74-
["project", "labels"], Entity.named("Label"))
72+
Label = Entity.named("Label")
73+
74+
if datasets is not None:
75+
where = " where:{dataRow: {dataset: {id_in: [%s]}}}" % ", ".join(
76+
'"%s"' % dataset.uid for dataset in datasets)
77+
else:
78+
where = ""
79+
80+
if order_by is not None:
81+
query.check_order_by_clause(Label, order_by)
82+
order_by_str = "orderBy: %s_%s" % (
83+
order_by[0].graphql_name, order_by[1].name.upper())
84+
else:
85+
order_by_str = ""
86+
87+
query_str = """query GetProjectLabelsPyApi($project_id: ID!)
88+
{project (where: {id: $project_id})
89+
{labels (skip: %%d first: %%d%s%s) {%s}}}""" % (
90+
where, order_by_str, query.results_query_part(Label))
91+
92+
return PaginatedCollection(
93+
self.client, query_str, {"project_id": self.uid},
94+
["project", "labels"], Label)
7595

7696
def export_labels(self, timeout_seconds=60):
7797
""" Calls the server-side Label exporting that generates a JSON
@@ -84,7 +104,11 @@ def export_labels(self, timeout_seconds=60):
84104
is returned.
85105
"""
86106
sleep_time = 2
87-
query_str, id_param = _export_labels()
107+
id_param = "projectId"
108+
query_str = """mutation GetLabelExportUrlPyApi($%s: ID!)
109+
{exportLabels(data:{projectId: $%s }) {downloadUrl createdAt shouldPoll} }
110+
""" % (id_param, id_param)
111+
88112
while True:
89113
res = self.client.execute(query_str, {id_param: self.uid})[
90114
"data"]["exportLabels"]
@@ -104,7 +128,14 @@ def labeler_performance(self):
104128
Returns:
105129
A PaginatedCollection of LabelerPerformance objects.
106130
"""
107-
query_str, params = _labeler_performance(self)
131+
project_id_param = "projectId"
132+
query_str = """query LabelerPerformancePyApi($%s: ID!) {
133+
project(where: {id: $%s}) {
134+
labelerPerformance(skip: %%d first: %%d) {
135+
count user {%s} secondsPerLabel totalTimeLabeling consensus
136+
averageBenchmarkAgreement lastActivityTime}
137+
}}""" % (project_id_param, project_id_param,
138+
query.results_query_part(Entity.named("User")))
108139

109140
def create_labeler_performance(client, result):
110141
result["user"] = Entity.named("User")(client, result["user"])
@@ -113,9 +144,9 @@ def create_labeler_performance(client, result):
113144
return LabelerPerformance(**{utils.snake_case(key): value
114145
for key, value in result.items()})
115146

116-
return PaginatedCollection(self.client, query_str, params,
117-
["project", "labelerPerformance"],
118-
create_labeler_performance)
147+
return PaginatedCollection(
148+
self.client, query_str, {project_id_param: self.uid},
149+
["project", "labelerPerformance"], create_labeler_performance)
119150

120151
def review_metrics(self, net_score):
121152
""" Returns this Project's review metrics.
@@ -127,8 +158,13 @@ def review_metrics(self, net_score):
127158
if net_score not in (None,) + tuple(Entity.named("Review").NetScore):
128159
raise InvalidQueryError("Review metrics net score must be either None "
129160
"or one of Review.NetScore values")
130-
query_str, params = _project_review_metrics(self, net_score)
131-
res = self.client.execute(query_str, params)
161+
project_id_param = "project_id"
162+
net_score_literal = "None" if net_score is None else net_score.name
163+
query_str = """query ProjectReviewMetricsPyApi($%s: ID!){
164+
project(where: {id:$%s})
165+
{reviewMetrics {labelAggregate(netScore: %s) {count}}}
166+
}""" % (project_id_param, project_id_param, net_score_literal)
167+
res = self.client.execute(query_str, {project_id_param: self.uid})
132168
return res["data"]["project"]["reviewMetrics"]["labelAggregate"]["count"]
133169

134170
def setup(self, labeling_frontend, labeling_frontend_options):
@@ -162,8 +198,15 @@ def set_labeling_parameter_overrides(self, data):
162198
Return:
163199
bool indicating if the operation was a success.
164200
"""
165-
query_str, params = _set_labeling_parameter_overrides(self, data)
166-
res = self.client.execute(query_str, params)
201+
data_str = ",\n".join(
202+
"{dataRow: {id: \"%s\"}, priority: %d, numLabels: %d }" % (
203+
data_row.uid, priority, num_labels)
204+
for data_row, priority, num_labels in data)
205+
project_param = "projectId"
206+
query_str = """mutation setLabelingParameterOverridesPyApi($%s: ID!){
207+
project(where: { id: $%s }) {setLabelingParameterOverrides
208+
(data: [%s]) {success}}} """ % (project_param, project_param, data_str)
209+
res = self.client.execute(query_str, {project_param: self.uid})
167210
return res["data"]["project"]["setLabelingParameterOverrides"]["success"]
168211

169212
def unset_labeling_parameter_overrides(self, data_rows):
@@ -173,8 +216,13 @@ def unset_labeling_parameter_overrides(self, data_rows):
173216
Return:
174217
bool indicating if the operation was a success.
175218
"""
176-
query_str, params = _unset_labeling_parameter_overrides(self, data_rows)
177-
res = self.client.execute(query_str, params)
219+
project_param = "projectId"
220+
query_str = """mutation unsetLabelingParameterOverridesPyApi($%s: ID!){
221+
project(where: { id: $%s}) {
222+
unsetLabelingParameterOverrides(data: [%s]) { success }}}""" % (
223+
project_param, project_param,
224+
",\n".join("{dataRowId: \"%s\"}" % row.uid for row in data_rows))
225+
res = self.client.execute(query_str, {project_param: self.uid})
178226
return res["data"]["project"]["unsetLabelingParameterOverrides"]["success"]
179227

180228

@@ -188,112 +236,3 @@ class LabelingParameterOverride(DbObject):
188236
"consensus average_benchmark_agreement last_activity_time")
189237
LabelerPerformance.__doc__ = "Named tuple containing info about a labeler's " \
190238
"performance."
191-
192-
193-
def _project_labels(project, datasets, order_by):
194-
""" Returns the query and params for getting a Project's labels
195-
relationship. A non-standard relationship query is used to support
196-
filtering on Datasets.
197-
Args:
198-
datasets (list or None): The datasets filter. If None it's
199-
ignored.
200-
Return:
201-
(query_string, params)
202-
"""
203-
Label = Entity.named("Label")
204-
205-
if datasets is not None:
206-
where = " where:{dataRow: {dataset: {id_in: [%s]}}}" % ", ".join(
207-
'"%s"' % dataset.uid for dataset in datasets)
208-
else:
209-
where = ""
210-
211-
if order_by is not None:
212-
query.check_order_by_clause(Label, order_by)
213-
order_by_str = "orderBy: %s_%s" % (
214-
order_by[0].graphql_name, order_by[1].name.upper())
215-
else:
216-
order_by_str = ""
217-
218-
query_str = """query GetProjectLabelsPyApi($project_id: ID!)
219-
{project (where: {id: $project_id})
220-
{labels (skip: %%d first: %%d%s%s) {%s}}}""" % (
221-
where, order_by_str, query.results_query_part(Label))
222-
return query_str, {"project_id": project.uid}
223-
224-
225-
def _export_labels():
226-
""" Returns the query and ID param for exporting a Project's
227-
labels.
228-
Return:
229-
(query_string, id_param_name)
230-
"""
231-
id_param = "projectId"
232-
query_str = """mutation GetLabelExportUrlPyApi($%s: ID!) {exportLabels(data:{
233-
projectId: $%s } ) {
234-
downloadUrl createdAt shouldPoll } }
235-
""" % (id_param, id_param)
236-
return (query_str, id_param)
237-
238-
239-
def _labeler_performance(project):
240-
project_id_param = "projectId"
241-
query_str = """query LabelerPerformancePyApi($%s: ID!) {
242-
project(where: {id: $%s}) {
243-
labelerPerformance(skip: %%d first: %%d) {
244-
count user {%s} secondsPerLabel totalTimeLabeling consensus
245-
averageBenchmarkAgreement lastActivityTime}
246-
}
247-
}""" % (project_id_param, project_id_param,
248-
query.results_query_part(Entity.named("User")))
249-
250-
return query_str, {project_id_param: project.uid}
251-
252-
253-
def _project_review_metrics(project, net_score):
254-
project_id_param = "project_id"
255-
net_score_literal = "None" if net_score is None else net_score.name
256-
query_str = """query ProjectReviewMetricsPyApi($%s: ID!){
257-
project(where: {id:$%s})
258-
{reviewMetrics {labelAggregate(netScore: %s) {count}}}
259-
}""" % (project_id_param, project_id_param, net_score_literal)
260-
261-
return query_str, {project_id_param: project.uid}
262-
263-
264-
def _set_labeling_parameter_overrides(project, data):
265-
""" Constructs a query for setting labeling parameter overrides.
266-
Args:
267-
project (Project): The project to set param overrides for.
268-
data (iterable): An iterable of tuples. Each tuple must contain
269-
(DataRow, priority, numberOfLabels) for the new override.
270-
Return:
271-
(query_string, query_parameters)
272-
"""
273-
data_str = ",\n".join(
274-
"{dataRow: {id: \"%s\"}, priority: %d, numLabels: %d }" % (
275-
data_row.uid, priority, num_labels)
276-
for data_row, priority, num_labels in data)
277-
query_str = """mutation setLabelingParameterOverridesPyApi {
278-
project(where: { id: "%s" }) {
279-
setLabelingParameterOverrides(data: [%s]) { success } } } """ % (
280-
project.uid, data_str)
281-
return query_str, {}
282-
283-
284-
def _unset_labeling_parameter_overrides(project, data_rows):
285-
""" Constructs a query for unsetting labeling parameter overrides.
286-
Args:
287-
project (Project): The project to set param overrides for.
288-
data_rows (iterable): An iterable of DataRow objects
289-
for which the to set as parameter overrides.
290-
Return:
291-
(query_string, query_parameters)
292-
"""
293-
data_str = ",\n".join("{dataRowId: \"%s\"}" % data_row.uid
294-
for data_row in data_rows)
295-
query_str = """mutation unsetLabelingParameterOverridesPyApi {
296-
project(where: { id: "%s" }) {
297-
unsetLabelingParameterOverrides(data: [%s]) { success } } } """ % (
298-
project.uid, data_str)
299-
return query_str, {}

0 commit comments

Comments
 (0)