matlab-prodserver-client 24.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- google/__init__.py +7 -0
- google/protobuf_ml/__init__.py +33 -0
- google/protobuf_ml/descriptor.py +1230 -0
- google/protobuf_ml/descriptor_database.py +177 -0
- google/protobuf_ml/descriptor_pb2.py +1925 -0
- google/protobuf_ml/descriptor_pool.py +1295 -0
- google/protobuf_ml/internal/__init__.py +0 -0
- google/protobuf_ml/internal/_parameterized.py +443 -0
- google/protobuf_ml/internal/api_implementation.py +168 -0
- google/protobuf_ml/internal/builder.py +130 -0
- google/protobuf_ml/internal/containers.py +708 -0
- google/protobuf_ml/internal/decoder.py +1068 -0
- google/protobuf_ml/internal/descriptor_database_test.py +127 -0
- google/protobuf_ml/internal/descriptor_pool_test.py +1149 -0
- google/protobuf_ml/internal/descriptor_test.py +1076 -0
- google/protobuf_ml/internal/encoder.py +829 -0
- google/protobuf_ml/internal/enum_type_wrapper.py +124 -0
- google/protobuf_ml/internal/extension_dict.py +213 -0
- google/protobuf_ml/internal/generator_test.py +354 -0
- google/protobuf_ml/internal/import_test.py +49 -0
- google/protobuf_ml/internal/json_format_test.py +1285 -0
- google/protobuf_ml/internal/keywords_test.py +103 -0
- google/protobuf_ml/internal/message_factory_test.py +299 -0
- google/protobuf_ml/internal/message_listener.py +78 -0
- google/protobuf_ml/internal/message_test.py +2573 -0
- google/protobuf_ml/internal/proto_builder_test.py +106 -0
- google/protobuf_ml/internal/python_message.py +1539 -0
- google/protobuf_ml/internal/reflection_test.py +3381 -0
- google/protobuf_ml/internal/service_reflection_test.py +139 -0
- google/protobuf_ml/internal/symbol_database_test.py +133 -0
- google/protobuf_ml/internal/test_util.py +878 -0
- google/protobuf_ml/internal/testing_refleaks.py +142 -0
- google/protobuf_ml/internal/text_encoding_test.py +67 -0
- google/protobuf_ml/internal/text_format_test.py +2447 -0
- google/protobuf_ml/internal/type_checkers.py +435 -0
- google/protobuf_ml/internal/unknown_fields_test.py +461 -0
- google/protobuf_ml/internal/well_known_types.py +887 -0
- google/protobuf_ml/internal/well_known_types_test.py +1013 -0
- google/protobuf_ml/internal/wire_format.py +268 -0
- google/protobuf_ml/internal/wire_format_test.py +252 -0
- google/protobuf_ml/json_format.py +912 -0
- google/protobuf_ml/message.py +424 -0
- google/protobuf_ml/message_factory.py +189 -0
- google/protobuf_ml/proto_builder.py +134 -0
- google/protobuf_ml/reflection.py +95 -0
- google/protobuf_ml/service.py +228 -0
- google/protobuf_ml/service_reflection.py +295 -0
- google/protobuf_ml/symbol_database.py +194 -0
- google/protobuf_ml/text_encoding.py +110 -0
- google/protobuf_ml/text_format.py +1842 -0
- google/protobuf_ml/unknown_fields.py +120 -0
- matlab/__init__.py +43 -0
- matlab/bin/win64/libmwfoundation_matlabdata.dll +0 -0
- matlab/bin/win64/libmwfoundation_matlabdata_standalone.dll +0 -0
- matlab/extern/bin/win64/libMatlabDataArray.dll +0 -0
- matlab/extern/bin/win64/matlabmultidimarrayforpython.cp310-win_amd64.pyd +0 -0
- matlab/extern/bin/win64/matlabmultidimarrayforpython.cp39-win_amd64.pyd +0 -0
- matlab/extern/bin/win64/matlabmultidimarrayforpython.pyd +0 -0
- matlab/production_server/__init__.py +2 -0
- matlab/production_server/_internal_mps/__init__.py +2 -0
- matlab/production_server/_internal_mps/feval_handler.py +76 -0
- matlab/production_server/_internal_mps/invocation_handler_utils.py +52 -0
- matlab/production_server/_internal_mps/matlab_array_builder.py +201 -0
- matlab/production_server/_internal_mps/matlab_response_builder.py +134 -0
- matlab/production_server/_proto_generated/MATLABArray_pb2.py +129 -0
- matlab/production_server/_proto_generated/MATLABError_pb2.py +27 -0
- matlab/production_server/_proto_generated/MATLABParams_pb2.py +26 -0
- matlab/production_server/_proto_generated/MATLABResult_pb2.py +27 -0
- matlab/production_server/_proto_generated/__init__.py +0 -0
- matlab/production_server/client.py +140 -0
- matlab/production_server/mpsexceptions.py +56 -0
- matlab_prodserver_client-24.2.dist-info/LICENSE.txt +27 -0
- matlab_prodserver_client-24.2.dist-info/METADATA +94 -0
- matlab_prodserver_client-24.2.dist-info/RECORD +77 -0
- matlab_prodserver_client-24.2.dist-info/WHEEL +5 -0
- matlab_prodserver_client-24.2.dist-info/top_level.txt +3 -0
- six.py +953 -0
|
@@ -0,0 +1,887 @@
|
|
|
1
|
+
# Protocol Buffers - Google's data interchange format
|
|
2
|
+
# Copyright 2008 Google Inc. All rights reserved.
|
|
3
|
+
# https://developers.google.com/protocol-buffers/
|
|
4
|
+
#
|
|
5
|
+
# Redistribution and use in source and binary forms, with or without
|
|
6
|
+
# modification, are permitted provided that the following conditions are
|
|
7
|
+
# met:
|
|
8
|
+
#
|
|
9
|
+
# * Redistributions of source code must retain the above copyright
|
|
10
|
+
# notice, this list of conditions and the following disclaimer.
|
|
11
|
+
# * Redistributions in binary form must reproduce the above
|
|
12
|
+
# copyright notice, this list of conditions and the following disclaimer
|
|
13
|
+
# in the documentation and/or other materials provided with the
|
|
14
|
+
# distribution.
|
|
15
|
+
# * Neither the name of Google Inc. nor the names of its
|
|
16
|
+
# contributors may be used to endorse or promote products derived from
|
|
17
|
+
# this software without specific prior written permission.
|
|
18
|
+
#
|
|
19
|
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
20
|
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
21
|
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
22
|
+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
23
|
+
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
24
|
+
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
25
|
+
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
26
|
+
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
27
|
+
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
28
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
30
|
+
|
|
31
|
+
"""Contains well known classes.
|
|
32
|
+
|
|
33
|
+
This files defines well known classes which need extra maintenance including:
|
|
34
|
+
- Any
|
|
35
|
+
- Duration
|
|
36
|
+
- FieldMask
|
|
37
|
+
- Struct
|
|
38
|
+
- Timestamp
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
__author__ = 'jieluo@google.com (Jie Luo)'
|
|
42
|
+
|
|
43
|
+
#start: MathWorks update 12/14/21
|
|
44
|
+
import collections
|
|
45
|
+
try:
|
|
46
|
+
collections_abc = collections.abc #2.7
|
|
47
|
+
except AttributeError:
|
|
48
|
+
collections_abc = collections #3.8
|
|
49
|
+
#end: MathWorks update 12/14/21
|
|
50
|
+
|
|
51
|
+
import calendar
|
|
52
|
+
import datetime
|
|
53
|
+
|
|
54
|
+
from google.protobuf_ml.descriptor import FieldDescriptor
|
|
55
|
+
|
|
56
|
+
_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
|
|
57
|
+
_NANOS_PER_SECOND = 1000000000
|
|
58
|
+
_NANOS_PER_MILLISECOND = 1000000
|
|
59
|
+
_NANOS_PER_MICROSECOND = 1000
|
|
60
|
+
_MILLIS_PER_SECOND = 1000
|
|
61
|
+
_MICROS_PER_SECOND = 1000000
|
|
62
|
+
_SECONDS_PER_DAY = 24 * 3600
|
|
63
|
+
_DURATION_SECONDS_MAX = 315576000000
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Any(object):
|
|
67
|
+
"""Class for Any Message type."""
|
|
68
|
+
|
|
69
|
+
__slots__ = ()
|
|
70
|
+
|
|
71
|
+
def Pack(self, msg, type_url_prefix='type.googleapis.com/',
|
|
72
|
+
deterministic=None):
|
|
73
|
+
"""Packs the specified message into current Any message."""
|
|
74
|
+
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
|
|
75
|
+
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
|
|
76
|
+
else:
|
|
77
|
+
self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
|
|
78
|
+
self.value = msg.SerializeToString(deterministic=deterministic)
|
|
79
|
+
|
|
80
|
+
def Unpack(self, msg):
|
|
81
|
+
"""Unpacks the current Any message into specified message."""
|
|
82
|
+
descriptor = msg.DESCRIPTOR
|
|
83
|
+
if not self.Is(descriptor):
|
|
84
|
+
return False
|
|
85
|
+
msg.ParseFromString(self.value)
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
def TypeName(self):
|
|
89
|
+
"""Returns the protobuf type name of the inner message."""
|
|
90
|
+
# Only last part is to be used: b/25630112
|
|
91
|
+
return self.type_url.split('/')[-1]
|
|
92
|
+
|
|
93
|
+
def Is(self, descriptor):
|
|
94
|
+
"""Checks if this Any represents the given protobuf type."""
|
|
95
|
+
return '/' in self.type_url and self.TypeName() == descriptor.full_name
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_EPOCH_DATETIME_NAIVE = datetime.datetime.utcfromtimestamp(0)
|
|
99
|
+
_EPOCH_DATETIME_AWARE = datetime.datetime.fromtimestamp(
|
|
100
|
+
0, tz=datetime.timezone.utc)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Timestamp(object):
|
|
104
|
+
"""Class for Timestamp message type."""
|
|
105
|
+
|
|
106
|
+
__slots__ = ()
|
|
107
|
+
|
|
108
|
+
def ToJsonString(self):
|
|
109
|
+
"""Converts Timestamp to RFC 3339 date string format.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
A string converted from timestamp. The string is always Z-normalized
|
|
113
|
+
and uses 3, 6 or 9 fractional digits as required to represent the
|
|
114
|
+
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
|
|
115
|
+
"""
|
|
116
|
+
nanos = self.nanos % _NANOS_PER_SECOND
|
|
117
|
+
total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND
|
|
118
|
+
seconds = total_sec % _SECONDS_PER_DAY
|
|
119
|
+
days = (total_sec - seconds) // _SECONDS_PER_DAY
|
|
120
|
+
dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(days, seconds)
|
|
121
|
+
|
|
122
|
+
result = dt.isoformat()
|
|
123
|
+
if (nanos % 1e9) == 0:
|
|
124
|
+
# If there are 0 fractional digits, the fractional
|
|
125
|
+
# point '.' should be omitted when serializing.
|
|
126
|
+
return result + 'Z'
|
|
127
|
+
if (nanos % 1e6) == 0:
|
|
128
|
+
# Serialize 3 fractional digits.
|
|
129
|
+
return result + '.%03dZ' % (nanos / 1e6)
|
|
130
|
+
if (nanos % 1e3) == 0:
|
|
131
|
+
# Serialize 6 fractional digits.
|
|
132
|
+
return result + '.%06dZ' % (nanos / 1e3)
|
|
133
|
+
# Serialize 9 fractional digits.
|
|
134
|
+
return result + '.%09dZ' % nanos
|
|
135
|
+
|
|
136
|
+
def FromJsonString(self, value):
|
|
137
|
+
"""Parse a RFC 3339 date string format to Timestamp.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
value: A date string. Any fractional digits (or none) and any offset are
|
|
141
|
+
accepted as long as they fit into nano-seconds precision.
|
|
142
|
+
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
ValueError: On parsing problems.
|
|
146
|
+
"""
|
|
147
|
+
if not isinstance(value, str):
|
|
148
|
+
raise ValueError('Timestamp JSON value not a string: {!r}'.format(value))
|
|
149
|
+
timezone_offset = value.find('Z')
|
|
150
|
+
if timezone_offset == -1:
|
|
151
|
+
timezone_offset = value.find('+')
|
|
152
|
+
if timezone_offset == -1:
|
|
153
|
+
timezone_offset = value.rfind('-')
|
|
154
|
+
if timezone_offset == -1:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
'Failed to parse timestamp: missing valid timezone offset.')
|
|
157
|
+
time_value = value[0:timezone_offset]
|
|
158
|
+
# Parse datetime and nanos.
|
|
159
|
+
point_position = time_value.find('.')
|
|
160
|
+
if point_position == -1:
|
|
161
|
+
second_value = time_value
|
|
162
|
+
nano_value = ''
|
|
163
|
+
else:
|
|
164
|
+
second_value = time_value[:point_position]
|
|
165
|
+
nano_value = time_value[point_position + 1:]
|
|
166
|
+
if 't' in second_value:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
'time data \'{0}\' does not match format \'%Y-%m-%dT%H:%M:%S\', '
|
|
169
|
+
'lowercase \'t\' is not accepted'.format(second_value))
|
|
170
|
+
date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFOMAT)
|
|
171
|
+
td = date_object - datetime.datetime(1970, 1, 1)
|
|
172
|
+
seconds = td.seconds + td.days * _SECONDS_PER_DAY
|
|
173
|
+
if len(nano_value) > 9:
|
|
174
|
+
raise ValueError(
|
|
175
|
+
'Failed to parse Timestamp: nanos {0} more than '
|
|
176
|
+
'9 fractional digits.'.format(nano_value))
|
|
177
|
+
if nano_value:
|
|
178
|
+
nanos = round(float('0.' + nano_value) * 1e9)
|
|
179
|
+
else:
|
|
180
|
+
nanos = 0
|
|
181
|
+
# Parse timezone offsets.
|
|
182
|
+
if value[timezone_offset] == 'Z':
|
|
183
|
+
if len(value) != timezone_offset + 1:
|
|
184
|
+
raise ValueError('Failed to parse timestamp: invalid trailing'
|
|
185
|
+
' data {0}.'.format(value))
|
|
186
|
+
else:
|
|
187
|
+
timezone = value[timezone_offset:]
|
|
188
|
+
pos = timezone.find(':')
|
|
189
|
+
if pos == -1:
|
|
190
|
+
raise ValueError(
|
|
191
|
+
'Invalid timezone offset value: {0}.'.format(timezone))
|
|
192
|
+
if timezone[0] == '+':
|
|
193
|
+
seconds -= (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
|
|
194
|
+
else:
|
|
195
|
+
seconds += (int(timezone[1:pos])*60+int(timezone[pos+1:]))*60
|
|
196
|
+
# Set seconds and nanos
|
|
197
|
+
self.seconds = int(seconds)
|
|
198
|
+
self.nanos = int(nanos)
|
|
199
|
+
|
|
200
|
+
def GetCurrentTime(self):
|
|
201
|
+
"""Get the current UTC into Timestamp."""
|
|
202
|
+
self.FromDatetime(datetime.datetime.utcnow())
|
|
203
|
+
|
|
204
|
+
def ToNanoseconds(self):
|
|
205
|
+
"""Converts Timestamp to nanoseconds since epoch."""
|
|
206
|
+
return self.seconds * _NANOS_PER_SECOND + self.nanos
|
|
207
|
+
|
|
208
|
+
def ToMicroseconds(self):
|
|
209
|
+
"""Converts Timestamp to microseconds since epoch."""
|
|
210
|
+
return (self.seconds * _MICROS_PER_SECOND +
|
|
211
|
+
self.nanos // _NANOS_PER_MICROSECOND)
|
|
212
|
+
|
|
213
|
+
def ToMilliseconds(self):
|
|
214
|
+
"""Converts Timestamp to milliseconds since epoch."""
|
|
215
|
+
return (self.seconds * _MILLIS_PER_SECOND +
|
|
216
|
+
self.nanos // _NANOS_PER_MILLISECOND)
|
|
217
|
+
|
|
218
|
+
def ToSeconds(self):
|
|
219
|
+
"""Converts Timestamp to seconds since epoch."""
|
|
220
|
+
return self.seconds
|
|
221
|
+
|
|
222
|
+
def FromNanoseconds(self, nanos):
|
|
223
|
+
"""Converts nanoseconds since epoch to Timestamp."""
|
|
224
|
+
self.seconds = nanos // _NANOS_PER_SECOND
|
|
225
|
+
self.nanos = nanos % _NANOS_PER_SECOND
|
|
226
|
+
|
|
227
|
+
def FromMicroseconds(self, micros):
|
|
228
|
+
"""Converts microseconds since epoch to Timestamp."""
|
|
229
|
+
self.seconds = micros // _MICROS_PER_SECOND
|
|
230
|
+
self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND
|
|
231
|
+
|
|
232
|
+
def FromMilliseconds(self, millis):
|
|
233
|
+
"""Converts milliseconds since epoch to Timestamp."""
|
|
234
|
+
self.seconds = millis // _MILLIS_PER_SECOND
|
|
235
|
+
self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND
|
|
236
|
+
|
|
237
|
+
def FromSeconds(self, seconds):
|
|
238
|
+
"""Converts seconds since epoch to Timestamp."""
|
|
239
|
+
self.seconds = seconds
|
|
240
|
+
self.nanos = 0
|
|
241
|
+
|
|
242
|
+
def ToDatetime(self, tzinfo=None):
|
|
243
|
+
"""Converts Timestamp to a datetime.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
tzinfo: A datetime.tzinfo subclass; defaults to None.
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone
|
|
250
|
+
information, i.e. not aware that it's UTC).
|
|
251
|
+
|
|
252
|
+
Otherwise, returns a timezone-aware datetime in the input timezone.
|
|
253
|
+
"""
|
|
254
|
+
delta = datetime.timedelta(
|
|
255
|
+
seconds=self.seconds,
|
|
256
|
+
microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND))
|
|
257
|
+
if tzinfo is None:
|
|
258
|
+
return _EPOCH_DATETIME_NAIVE + delta
|
|
259
|
+
else:
|
|
260
|
+
return _EPOCH_DATETIME_AWARE.astimezone(tzinfo) + delta
|
|
261
|
+
|
|
262
|
+
def FromDatetime(self, dt):
|
|
263
|
+
"""Converts datetime to Timestamp.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
dt: A datetime. If it's timezone-naive, it's assumed to be in UTC.
|
|
267
|
+
"""
|
|
268
|
+
# Using this guide: http://wiki.python.org/moin/WorkingWithTime
|
|
269
|
+
# And this conversion guide: http://docs.python.org/library/time.html
|
|
270
|
+
|
|
271
|
+
# Turn the date parameter into a tuple (struct_time) that can then be
|
|
272
|
+
# manipulated into a long value of seconds. During the conversion from
|
|
273
|
+
# struct_time to long, the source date in UTC, and so it follows that the
|
|
274
|
+
# correct transformation is calendar.timegm()
|
|
275
|
+
self.seconds = calendar.timegm(dt.utctimetuple())
|
|
276
|
+
self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class Duration(object):
|
|
280
|
+
"""Class for Duration message type."""
|
|
281
|
+
|
|
282
|
+
__slots__ = ()
|
|
283
|
+
|
|
284
|
+
def ToJsonString(self):
|
|
285
|
+
"""Converts Duration to string format.
|
|
286
|
+
|
|
287
|
+
Returns:
|
|
288
|
+
A string converted from self. The string format will contains
|
|
289
|
+
3, 6, or 9 fractional digits depending on the precision required to
|
|
290
|
+
represent the exact Duration value. For example: "1s", "1.010s",
|
|
291
|
+
"1.000000100s", "-3.100s"
|
|
292
|
+
"""
|
|
293
|
+
_CheckDurationValid(self.seconds, self.nanos)
|
|
294
|
+
if self.seconds < 0 or self.nanos < 0:
|
|
295
|
+
result = '-'
|
|
296
|
+
seconds = - self.seconds + int((0 - self.nanos) // 1e9)
|
|
297
|
+
nanos = (0 - self.nanos) % 1e9
|
|
298
|
+
else:
|
|
299
|
+
result = ''
|
|
300
|
+
seconds = self.seconds + int(self.nanos // 1e9)
|
|
301
|
+
nanos = self.nanos % 1e9
|
|
302
|
+
result += '%d' % seconds
|
|
303
|
+
if (nanos % 1e9) == 0:
|
|
304
|
+
# If there are 0 fractional digits, the fractional
|
|
305
|
+
# point '.' should be omitted when serializing.
|
|
306
|
+
return result + 's'
|
|
307
|
+
if (nanos % 1e6) == 0:
|
|
308
|
+
# Serialize 3 fractional digits.
|
|
309
|
+
return result + '.%03ds' % (nanos / 1e6)
|
|
310
|
+
if (nanos % 1e3) == 0:
|
|
311
|
+
# Serialize 6 fractional digits.
|
|
312
|
+
return result + '.%06ds' % (nanos / 1e3)
|
|
313
|
+
# Serialize 9 fractional digits.
|
|
314
|
+
return result + '.%09ds' % nanos
|
|
315
|
+
|
|
316
|
+
def FromJsonString(self, value):
|
|
317
|
+
"""Converts a string to Duration.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
value: A string to be converted. The string must end with 's'. Any
|
|
321
|
+
fractional digits (or none) are accepted as long as they fit into
|
|
322
|
+
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
|
|
323
|
+
|
|
324
|
+
Raises:
|
|
325
|
+
ValueError: On parsing problems.
|
|
326
|
+
"""
|
|
327
|
+
if not isinstance(value, str):
|
|
328
|
+
raise ValueError('Duration JSON value not a string: {!r}'.format(value))
|
|
329
|
+
if len(value) < 1 or value[-1] != 's':
|
|
330
|
+
raise ValueError(
|
|
331
|
+
'Duration must end with letter "s": {0}.'.format(value))
|
|
332
|
+
try:
|
|
333
|
+
pos = value.find('.')
|
|
334
|
+
if pos == -1:
|
|
335
|
+
seconds = int(value[:-1])
|
|
336
|
+
nanos = 0
|
|
337
|
+
else:
|
|
338
|
+
seconds = int(value[:pos])
|
|
339
|
+
if value[0] == '-':
|
|
340
|
+
nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))
|
|
341
|
+
else:
|
|
342
|
+
nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))
|
|
343
|
+
_CheckDurationValid(seconds, nanos)
|
|
344
|
+
self.seconds = seconds
|
|
345
|
+
self.nanos = nanos
|
|
346
|
+
except ValueError as e:
|
|
347
|
+
raise ValueError(
|
|
348
|
+
'Couldn\'t parse duration: {0} : {1}.'.format(value, e))
|
|
349
|
+
|
|
350
|
+
def ToNanoseconds(self):
|
|
351
|
+
"""Converts a Duration to nanoseconds."""
|
|
352
|
+
return self.seconds * _NANOS_PER_SECOND + self.nanos
|
|
353
|
+
|
|
354
|
+
def ToMicroseconds(self):
|
|
355
|
+
"""Converts a Duration to microseconds."""
|
|
356
|
+
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
|
|
357
|
+
return self.seconds * _MICROS_PER_SECOND + micros
|
|
358
|
+
|
|
359
|
+
def ToMilliseconds(self):
|
|
360
|
+
"""Converts a Duration to milliseconds."""
|
|
361
|
+
millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND)
|
|
362
|
+
return self.seconds * _MILLIS_PER_SECOND + millis
|
|
363
|
+
|
|
364
|
+
def ToSeconds(self):
|
|
365
|
+
"""Converts a Duration to seconds."""
|
|
366
|
+
return self.seconds
|
|
367
|
+
|
|
368
|
+
def FromNanoseconds(self, nanos):
|
|
369
|
+
"""Converts nanoseconds to Duration."""
|
|
370
|
+
self._NormalizeDuration(nanos // _NANOS_PER_SECOND,
|
|
371
|
+
nanos % _NANOS_PER_SECOND)
|
|
372
|
+
|
|
373
|
+
def FromMicroseconds(self, micros):
|
|
374
|
+
"""Converts microseconds to Duration."""
|
|
375
|
+
self._NormalizeDuration(
|
|
376
|
+
micros // _MICROS_PER_SECOND,
|
|
377
|
+
(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)
|
|
378
|
+
|
|
379
|
+
def FromMilliseconds(self, millis):
|
|
380
|
+
"""Converts milliseconds to Duration."""
|
|
381
|
+
self._NormalizeDuration(
|
|
382
|
+
millis // _MILLIS_PER_SECOND,
|
|
383
|
+
(millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND)
|
|
384
|
+
|
|
385
|
+
def FromSeconds(self, seconds):
|
|
386
|
+
"""Converts seconds to Duration."""
|
|
387
|
+
self.seconds = seconds
|
|
388
|
+
self.nanos = 0
|
|
389
|
+
|
|
390
|
+
def ToTimedelta(self):
|
|
391
|
+
"""Converts Duration to timedelta."""
|
|
392
|
+
return datetime.timedelta(
|
|
393
|
+
seconds=self.seconds, microseconds=_RoundTowardZero(
|
|
394
|
+
self.nanos, _NANOS_PER_MICROSECOND))
|
|
395
|
+
|
|
396
|
+
def FromTimedelta(self, td):
|
|
397
|
+
"""Converts timedelta to Duration."""
|
|
398
|
+
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
|
|
399
|
+
td.microseconds * _NANOS_PER_MICROSECOND)
|
|
400
|
+
|
|
401
|
+
def _NormalizeDuration(self, seconds, nanos):
|
|
402
|
+
"""Set Duration by seconds and nanos."""
|
|
403
|
+
# Force nanos to be negative if the duration is negative.
|
|
404
|
+
if seconds < 0 and nanos > 0:
|
|
405
|
+
seconds += 1
|
|
406
|
+
nanos -= _NANOS_PER_SECOND
|
|
407
|
+
self.seconds = seconds
|
|
408
|
+
self.nanos = nanos
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _CheckDurationValid(seconds, nanos):
|
|
412
|
+
if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX:
|
|
413
|
+
raise ValueError(
|
|
414
|
+
'Duration is not valid: Seconds {0} must be in range '
|
|
415
|
+
'[-315576000000, 315576000000].'.format(seconds))
|
|
416
|
+
if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND:
|
|
417
|
+
raise ValueError(
|
|
418
|
+
'Duration is not valid: Nanos {0} must be in range '
|
|
419
|
+
'[-999999999, 999999999].'.format(nanos))
|
|
420
|
+
if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0):
|
|
421
|
+
raise ValueError(
|
|
422
|
+
'Duration is not valid: Sign mismatch.')
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _RoundTowardZero(value, divider):
|
|
426
|
+
"""Truncates the remainder part after division."""
|
|
427
|
+
# For some languages, the sign of the remainder is implementation
|
|
428
|
+
# dependent if any of the operands is negative. Here we enforce
|
|
429
|
+
# "rounded toward zero" semantics. For example, for (-5) / 2 an
|
|
430
|
+
# implementation may give -3 as the result with the remainder being
|
|
431
|
+
# 1. This function ensures we always return -2 (closer to zero).
|
|
432
|
+
result = value // divider
|
|
433
|
+
remainder = value % divider
|
|
434
|
+
if result < 0 and remainder > 0:
|
|
435
|
+
return result + 1
|
|
436
|
+
else:
|
|
437
|
+
return result
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
class FieldMask(object):
|
|
441
|
+
"""Class for FieldMask message type."""
|
|
442
|
+
|
|
443
|
+
__slots__ = ()
|
|
444
|
+
|
|
445
|
+
def ToJsonString(self):
|
|
446
|
+
"""Converts FieldMask to string according to proto3 JSON spec."""
|
|
447
|
+
camelcase_paths = []
|
|
448
|
+
for path in self.paths:
|
|
449
|
+
camelcase_paths.append(_SnakeCaseToCamelCase(path))
|
|
450
|
+
return ','.join(camelcase_paths)
|
|
451
|
+
|
|
452
|
+
def FromJsonString(self, value):
|
|
453
|
+
"""Converts string to FieldMask according to proto3 JSON spec."""
|
|
454
|
+
if not isinstance(value, str):
|
|
455
|
+
raise ValueError('FieldMask JSON value not a string: {!r}'.format(value))
|
|
456
|
+
self.Clear()
|
|
457
|
+
if value:
|
|
458
|
+
for path in value.split(','):
|
|
459
|
+
self.paths.append(_CamelCaseToSnakeCase(path))
|
|
460
|
+
|
|
461
|
+
def IsValidForDescriptor(self, message_descriptor):
|
|
462
|
+
"""Checks whether the FieldMask is valid for Message Descriptor."""
|
|
463
|
+
for path in self.paths:
|
|
464
|
+
if not _IsValidPath(message_descriptor, path):
|
|
465
|
+
return False
|
|
466
|
+
return True
|
|
467
|
+
|
|
468
|
+
def AllFieldsFromDescriptor(self, message_descriptor):
|
|
469
|
+
"""Gets all direct fields of Message Descriptor to FieldMask."""
|
|
470
|
+
self.Clear()
|
|
471
|
+
for field in message_descriptor.fields:
|
|
472
|
+
self.paths.append(field.name)
|
|
473
|
+
|
|
474
|
+
def CanonicalFormFromMask(self, mask):
|
|
475
|
+
"""Converts a FieldMask to the canonical form.
|
|
476
|
+
|
|
477
|
+
Removes paths that are covered by another path. For example,
|
|
478
|
+
"foo.bar" is covered by "foo" and will be removed if "foo"
|
|
479
|
+
is also in the FieldMask. Then sorts all paths in alphabetical order.
|
|
480
|
+
|
|
481
|
+
Args:
|
|
482
|
+
mask: The original FieldMask to be converted.
|
|
483
|
+
"""
|
|
484
|
+
tree = _FieldMaskTree(mask)
|
|
485
|
+
tree.ToFieldMask(self)
|
|
486
|
+
|
|
487
|
+
def Union(self, mask1, mask2):
|
|
488
|
+
"""Merges mask1 and mask2 into this FieldMask."""
|
|
489
|
+
_CheckFieldMaskMessage(mask1)
|
|
490
|
+
_CheckFieldMaskMessage(mask2)
|
|
491
|
+
tree = _FieldMaskTree(mask1)
|
|
492
|
+
tree.MergeFromFieldMask(mask2)
|
|
493
|
+
tree.ToFieldMask(self)
|
|
494
|
+
|
|
495
|
+
def Intersect(self, mask1, mask2):
|
|
496
|
+
"""Intersects mask1 and mask2 into this FieldMask."""
|
|
497
|
+
_CheckFieldMaskMessage(mask1)
|
|
498
|
+
_CheckFieldMaskMessage(mask2)
|
|
499
|
+
tree = _FieldMaskTree(mask1)
|
|
500
|
+
intersection = _FieldMaskTree()
|
|
501
|
+
for path in mask2.paths:
|
|
502
|
+
tree.IntersectPath(path, intersection)
|
|
503
|
+
intersection.ToFieldMask(self)
|
|
504
|
+
|
|
505
|
+
def MergeMessage(
|
|
506
|
+
self, source, destination,
|
|
507
|
+
replace_message_field=False, replace_repeated_field=False):
|
|
508
|
+
"""Merges fields specified in FieldMask from source to destination.
|
|
509
|
+
|
|
510
|
+
Args:
|
|
511
|
+
source: Source message.
|
|
512
|
+
destination: The destination message to be merged into.
|
|
513
|
+
replace_message_field: Replace message field if True. Merge message
|
|
514
|
+
field if False.
|
|
515
|
+
replace_repeated_field: Replace repeated field if True. Append
|
|
516
|
+
elements of repeated field if False.
|
|
517
|
+
"""
|
|
518
|
+
tree = _FieldMaskTree(self)
|
|
519
|
+
tree.MergeMessage(
|
|
520
|
+
source, destination, replace_message_field, replace_repeated_field)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _IsValidPath(message_descriptor, path):
|
|
524
|
+
"""Checks whether the path is valid for Message Descriptor."""
|
|
525
|
+
parts = path.split('.')
|
|
526
|
+
last = parts.pop()
|
|
527
|
+
for name in parts:
|
|
528
|
+
field = message_descriptor.fields_by_name.get(name)
|
|
529
|
+
if (field is None or
|
|
530
|
+
field.label == FieldDescriptor.LABEL_REPEATED or
|
|
531
|
+
field.type != FieldDescriptor.TYPE_MESSAGE):
|
|
532
|
+
return False
|
|
533
|
+
message_descriptor = field.message_type
|
|
534
|
+
return last in message_descriptor.fields_by_name
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _CheckFieldMaskMessage(message):
|
|
538
|
+
"""Raises ValueError if message is not a FieldMask."""
|
|
539
|
+
message_descriptor = message.DESCRIPTOR
|
|
540
|
+
if (message_descriptor.name != 'FieldMask' or
|
|
541
|
+
message_descriptor.file.name != 'google/protobuf_ml/field_mask.proto'):
|
|
542
|
+
raise ValueError('Message {0} is not a FieldMask.'.format(
|
|
543
|
+
message_descriptor.full_name))
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _SnakeCaseToCamelCase(path_name):
|
|
547
|
+
"""Converts a path name from snake_case to camelCase."""
|
|
548
|
+
result = []
|
|
549
|
+
after_underscore = False
|
|
550
|
+
for c in path_name:
|
|
551
|
+
if c.isupper():
|
|
552
|
+
raise ValueError(
|
|
553
|
+
'Fail to print FieldMask to Json string: Path name '
|
|
554
|
+
'{0} must not contain uppercase letters.'.format(path_name))
|
|
555
|
+
if after_underscore:
|
|
556
|
+
if c.islower():
|
|
557
|
+
result.append(c.upper())
|
|
558
|
+
after_underscore = False
|
|
559
|
+
else:
|
|
560
|
+
raise ValueError(
|
|
561
|
+
'Fail to print FieldMask to Json string: The '
|
|
562
|
+
'character after a "_" must be a lowercase letter '
|
|
563
|
+
'in path name {0}.'.format(path_name))
|
|
564
|
+
elif c == '_':
|
|
565
|
+
after_underscore = True
|
|
566
|
+
else:
|
|
567
|
+
result += c
|
|
568
|
+
|
|
569
|
+
if after_underscore:
|
|
570
|
+
raise ValueError('Fail to print FieldMask to Json string: Trailing "_" '
|
|
571
|
+
'in path name {0}.'.format(path_name))
|
|
572
|
+
return ''.join(result)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _CamelCaseToSnakeCase(path_name):
|
|
576
|
+
"""Converts a field name from camelCase to snake_case."""
|
|
577
|
+
result = []
|
|
578
|
+
for c in path_name:
|
|
579
|
+
if c == '_':
|
|
580
|
+
raise ValueError('Fail to parse FieldMask: Path name '
|
|
581
|
+
'{0} must not contain "_"s.'.format(path_name))
|
|
582
|
+
if c.isupper():
|
|
583
|
+
result += '_'
|
|
584
|
+
result += c.lower()
|
|
585
|
+
else:
|
|
586
|
+
result += c
|
|
587
|
+
return ''.join(result)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
class _FieldMaskTree(object):
|
|
591
|
+
"""Represents a FieldMask in a tree structure.
|
|
592
|
+
|
|
593
|
+
For example, given a FieldMask "foo.bar,foo.baz,bar.baz",
|
|
594
|
+
the FieldMaskTree will be:
|
|
595
|
+
[_root] -+- foo -+- bar
|
|
596
|
+
| |
|
|
597
|
+
| +- baz
|
|
598
|
+
|
|
|
599
|
+
+- bar --- baz
|
|
600
|
+
In the tree, each leaf node represents a field path.
|
|
601
|
+
"""
|
|
602
|
+
|
|
603
|
+
__slots__ = ('_root',)
|
|
604
|
+
|
|
605
|
+
def __init__(self, field_mask=None):
|
|
606
|
+
"""Initializes the tree by FieldMask."""
|
|
607
|
+
self._root = {}
|
|
608
|
+
if field_mask:
|
|
609
|
+
self.MergeFromFieldMask(field_mask)
|
|
610
|
+
|
|
611
|
+
def MergeFromFieldMask(self, field_mask):
|
|
612
|
+
"""Merges a FieldMask to the tree."""
|
|
613
|
+
for path in field_mask.paths:
|
|
614
|
+
self.AddPath(path)
|
|
615
|
+
|
|
616
|
+
def AddPath(self, path):
|
|
617
|
+
"""Adds a field path into the tree.
|
|
618
|
+
|
|
619
|
+
If the field path to add is a sub-path of an existing field path
|
|
620
|
+
in the tree (i.e., a leaf node), it means the tree already matches
|
|
621
|
+
the given path so nothing will be added to the tree. If the path
|
|
622
|
+
matches an existing non-leaf node in the tree, that non-leaf node
|
|
623
|
+
will be turned into a leaf node with all its children removed because
|
|
624
|
+
the path matches all the node's children. Otherwise, a new path will
|
|
625
|
+
be added.
|
|
626
|
+
|
|
627
|
+
Args:
|
|
628
|
+
path: The field path to add.
|
|
629
|
+
"""
|
|
630
|
+
node = self._root
|
|
631
|
+
for name in path.split('.'):
|
|
632
|
+
if name not in node:
|
|
633
|
+
node[name] = {}
|
|
634
|
+
elif not node[name]:
|
|
635
|
+
# Pre-existing empty node implies we already have this entire tree.
|
|
636
|
+
return
|
|
637
|
+
node = node[name]
|
|
638
|
+
# Remove any sub-trees we might have had.
|
|
639
|
+
node.clear()
|
|
640
|
+
|
|
641
|
+
def ToFieldMask(self, field_mask):
|
|
642
|
+
"""Converts the tree to a FieldMask."""
|
|
643
|
+
field_mask.Clear()
|
|
644
|
+
_AddFieldPaths(self._root, '', field_mask)
|
|
645
|
+
|
|
646
|
+
def IntersectPath(self, path, intersection):
|
|
647
|
+
"""Calculates the intersection part of a field path with this tree.
|
|
648
|
+
|
|
649
|
+
Args:
|
|
650
|
+
path: The field path to calculates.
|
|
651
|
+
intersection: The out tree to record the intersection part.
|
|
652
|
+
"""
|
|
653
|
+
node = self._root
|
|
654
|
+
for name in path.split('.'):
|
|
655
|
+
if name not in node:
|
|
656
|
+
return
|
|
657
|
+
elif not node[name]:
|
|
658
|
+
intersection.AddPath(path)
|
|
659
|
+
return
|
|
660
|
+
node = node[name]
|
|
661
|
+
intersection.AddLeafNodes(path, node)
|
|
662
|
+
|
|
663
|
+
def AddLeafNodes(self, prefix, node):
|
|
664
|
+
"""Adds leaf nodes begin with prefix to this tree."""
|
|
665
|
+
if not node:
|
|
666
|
+
self.AddPath(prefix)
|
|
667
|
+
for name in node:
|
|
668
|
+
child_path = prefix + '.' + name
|
|
669
|
+
self.AddLeafNodes(child_path, node[name])
|
|
670
|
+
|
|
671
|
+
def MergeMessage(
|
|
672
|
+
self, source, destination,
|
|
673
|
+
replace_message, replace_repeated):
|
|
674
|
+
"""Merge all fields specified by this tree from source to destination."""
|
|
675
|
+
_MergeMessage(
|
|
676
|
+
self._root, source, destination, replace_message, replace_repeated)
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _StrConvert(value):
|
|
680
|
+
"""Converts value to str if it is not."""
|
|
681
|
+
# This file is imported by c extension and some methods like ClearField
|
|
682
|
+
# requires string for the field name. py2/py3 has different text
|
|
683
|
+
# type and may use unicode.
|
|
684
|
+
if not isinstance(value, str):
|
|
685
|
+
return value.encode('utf-8')
|
|
686
|
+
return value
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _MergeMessage(
|
|
690
|
+
node, source, destination, replace_message, replace_repeated):
|
|
691
|
+
"""Merge all fields specified by a sub-tree from source to destination."""
|
|
692
|
+
source_descriptor = source.DESCRIPTOR
|
|
693
|
+
for name in node:
|
|
694
|
+
child = node[name]
|
|
695
|
+
field = source_descriptor.fields_by_name[name]
|
|
696
|
+
if field is None:
|
|
697
|
+
raise ValueError('Error: Can\'t find field {0} in message {1}.'.format(
|
|
698
|
+
name, source_descriptor.full_name))
|
|
699
|
+
if child:
|
|
700
|
+
# Sub-paths are only allowed for singular message fields.
|
|
701
|
+
if (field.label == FieldDescriptor.LABEL_REPEATED or
|
|
702
|
+
field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE):
|
|
703
|
+
raise ValueError('Error: Field {0} in message {1} is not a singular '
|
|
704
|
+
'message field and cannot have sub-fields.'.format(
|
|
705
|
+
name, source_descriptor.full_name))
|
|
706
|
+
if source.HasField(name):
|
|
707
|
+
_MergeMessage(
|
|
708
|
+
child, getattr(source, name), getattr(destination, name),
|
|
709
|
+
replace_message, replace_repeated)
|
|
710
|
+
continue
|
|
711
|
+
if field.label == FieldDescriptor.LABEL_REPEATED:
|
|
712
|
+
if replace_repeated:
|
|
713
|
+
destination.ClearField(_StrConvert(name))
|
|
714
|
+
repeated_source = getattr(source, name)
|
|
715
|
+
repeated_destination = getattr(destination, name)
|
|
716
|
+
repeated_destination.MergeFrom(repeated_source)
|
|
717
|
+
else:
|
|
718
|
+
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE:
|
|
719
|
+
if replace_message:
|
|
720
|
+
destination.ClearField(_StrConvert(name))
|
|
721
|
+
if source.HasField(name):
|
|
722
|
+
getattr(destination, name).MergeFrom(getattr(source, name))
|
|
723
|
+
else:
|
|
724
|
+
setattr(destination, name, getattr(source, name))
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _AddFieldPaths(node, prefix, field_mask):
|
|
728
|
+
"""Adds the field paths descended from node to field_mask."""
|
|
729
|
+
if not node and prefix:
|
|
730
|
+
field_mask.paths.append(prefix)
|
|
731
|
+
return
|
|
732
|
+
for name in sorted(node):
|
|
733
|
+
if prefix:
|
|
734
|
+
child_path = prefix + '.' + name
|
|
735
|
+
else:
|
|
736
|
+
child_path = name
|
|
737
|
+
_AddFieldPaths(node[name], child_path, field_mask)
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _SetStructValue(struct_value, value):
|
|
741
|
+
if value is None:
|
|
742
|
+
struct_value.null_value = 0
|
|
743
|
+
elif isinstance(value, bool):
|
|
744
|
+
# Note: this check must come before the number check because in Python
|
|
745
|
+
# True and False are also considered numbers.
|
|
746
|
+
struct_value.bool_value = value
|
|
747
|
+
elif isinstance(value, str):
|
|
748
|
+
struct_value.string_value = value
|
|
749
|
+
elif isinstance(value, (int, float)):
|
|
750
|
+
struct_value.number_value = value
|
|
751
|
+
elif isinstance(value, (dict, Struct)):
|
|
752
|
+
struct_value.struct_value.Clear()
|
|
753
|
+
struct_value.struct_value.update(value)
|
|
754
|
+
elif isinstance(value, (list, ListValue)):
|
|
755
|
+
struct_value.list_value.Clear()
|
|
756
|
+
struct_value.list_value.extend(value)
|
|
757
|
+
else:
|
|
758
|
+
raise ValueError('Unexpected type')
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _GetStructValue(struct_value):
|
|
762
|
+
which = struct_value.WhichOneof('kind')
|
|
763
|
+
if which == 'struct_value':
|
|
764
|
+
return struct_value.struct_value
|
|
765
|
+
elif which == 'null_value':
|
|
766
|
+
return None
|
|
767
|
+
elif which == 'number_value':
|
|
768
|
+
return struct_value.number_value
|
|
769
|
+
elif which == 'string_value':
|
|
770
|
+
return struct_value.string_value
|
|
771
|
+
elif which == 'bool_value':
|
|
772
|
+
return struct_value.bool_value
|
|
773
|
+
elif which == 'list_value':
|
|
774
|
+
return struct_value.list_value
|
|
775
|
+
elif which is None:
|
|
776
|
+
raise ValueError('Value not set')
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
class Struct(object):
|
|
780
|
+
"""Class for Struct message type."""
|
|
781
|
+
|
|
782
|
+
__slots__ = ()
|
|
783
|
+
|
|
784
|
+
def __getitem__(self, key):
|
|
785
|
+
return _GetStructValue(self.fields[key])
|
|
786
|
+
|
|
787
|
+
def __contains__(self, item):
|
|
788
|
+
return item in self.fields
|
|
789
|
+
|
|
790
|
+
def __setitem__(self, key, value):
|
|
791
|
+
_SetStructValue(self.fields[key], value)
|
|
792
|
+
|
|
793
|
+
def __delitem__(self, key):
|
|
794
|
+
del self.fields[key]
|
|
795
|
+
|
|
796
|
+
def __len__(self):
|
|
797
|
+
return len(self.fields)
|
|
798
|
+
|
|
799
|
+
def __iter__(self):
|
|
800
|
+
return iter(self.fields)
|
|
801
|
+
|
|
802
|
+
def keys(self): # pylint: disable=invalid-name
|
|
803
|
+
return self.fields.keys()
|
|
804
|
+
|
|
805
|
+
def values(self): # pylint: disable=invalid-name
|
|
806
|
+
return [self[key] for key in self]
|
|
807
|
+
|
|
808
|
+
def items(self): # pylint: disable=invalid-name
|
|
809
|
+
return [(key, self[key]) for key in self]
|
|
810
|
+
|
|
811
|
+
def get_or_create_list(self, key):
|
|
812
|
+
"""Returns a list for this key, creating if it didn't exist already."""
|
|
813
|
+
if not self.fields[key].HasField('list_value'):
|
|
814
|
+
# Clear will mark list_value modified which will indeed create a list.
|
|
815
|
+
self.fields[key].list_value.Clear()
|
|
816
|
+
return self.fields[key].list_value
|
|
817
|
+
|
|
818
|
+
def get_or_create_struct(self, key):
|
|
819
|
+
"""Returns a struct for this key, creating if it didn't exist already."""
|
|
820
|
+
if not self.fields[key].HasField('struct_value'):
|
|
821
|
+
# Clear will mark struct_value modified which will indeed create a struct.
|
|
822
|
+
self.fields[key].struct_value.Clear()
|
|
823
|
+
return self.fields[key].struct_value
|
|
824
|
+
|
|
825
|
+
def update(self, dictionary): # pylint: disable=invalid-name
|
|
826
|
+
for key, value in dictionary.items():
|
|
827
|
+
_SetStructValue(self.fields[key], value)
|
|
828
|
+
|
|
829
|
+
collections_abc.MutableMapping.register(Struct)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
class ListValue(object):
|
|
833
|
+
"""Class for ListValue message type."""
|
|
834
|
+
|
|
835
|
+
__slots__ = ()
|
|
836
|
+
|
|
837
|
+
def __len__(self):
|
|
838
|
+
return len(self.values)
|
|
839
|
+
|
|
840
|
+
def append(self, value):
|
|
841
|
+
_SetStructValue(self.values.add(), value)
|
|
842
|
+
|
|
843
|
+
def extend(self, elem_seq):
|
|
844
|
+
for value in elem_seq:
|
|
845
|
+
self.append(value)
|
|
846
|
+
|
|
847
|
+
def __getitem__(self, index):
|
|
848
|
+
"""Retrieves item by the specified index."""
|
|
849
|
+
return _GetStructValue(self.values.__getitem__(index))
|
|
850
|
+
|
|
851
|
+
def __setitem__(self, index, value):
|
|
852
|
+
_SetStructValue(self.values.__getitem__(index), value)
|
|
853
|
+
|
|
854
|
+
def __delitem__(self, key):
|
|
855
|
+
del self.values[key]
|
|
856
|
+
|
|
857
|
+
def items(self):
|
|
858
|
+
for i in range(len(self)):
|
|
859
|
+
yield self[i]
|
|
860
|
+
|
|
861
|
+
def add_struct(self):
|
|
862
|
+
"""Appends and returns a struct value as the next value in the list."""
|
|
863
|
+
struct_value = self.values.add().struct_value
|
|
864
|
+
# Clear will mark struct_value modified which will indeed create a struct.
|
|
865
|
+
struct_value.Clear()
|
|
866
|
+
return struct_value
|
|
867
|
+
|
|
868
|
+
def add_list(self):
|
|
869
|
+
"""Appends and returns a list value as the next value in the list."""
|
|
870
|
+
list_value = self.values.add().list_value
|
|
871
|
+
# Clear will mark list_value modified which will indeed create a list.
|
|
872
|
+
list_value.Clear()
|
|
873
|
+
return list_value
|
|
874
|
+
|
|
875
|
+
collections_abc.MutableSequence.register(ListValue)
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
# LINT.IfChange(wktbases)
|
|
879
|
+
WKTBASES = {
|
|
880
|
+
'google.protobuf_ml.Any': Any,
|
|
881
|
+
'google.protobuf_ml.Duration': Duration,
|
|
882
|
+
'google.protobuf_ml.FieldMask': FieldMask,
|
|
883
|
+
'google.protobuf_ml.ListValue': ListValue,
|
|
884
|
+
'google.protobuf_ml.Struct': Struct,
|
|
885
|
+
'google.protobuf_ml.Timestamp': Timestamp,
|
|
886
|
+
}
|
|
887
|
+
# LINT.ThenChange(//depot/google.protobuf_ml/compiler/python/pyi_generator.cc:wktbases)
|