Skip to content

Commit fa62a1b

Browse files
h-jooThe TensorFlow Datasets Authors
authored andcommitted
Automated Code Change
PiperOrigin-RevId: 944182406
1 parent fffe727 commit fa62a1b

33 files changed

Lines changed: 212 additions & 211 deletions

tensorflow_datasets/core/as_dataframe.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def _make_columns(
127127
) -> List[ColumnInfo]:
128128
"""Extract the columns info of the `panda.DataFrame`."""
129129
return [
130-
ColumnInfo.from_spec(path, ds_info)
130+
ColumnInfo.from_spec(path, ds_info) # pyrefly: ignore[bad-argument-type]
131131
for path, _ in py_utils.flatten_with_path(specs)
132132
]
133133

@@ -210,7 +210,7 @@ def _repr_html_(self) -> Union[None, str]:
210210

211211
# Flatten the keys names, specs,... while keeping the feature key definition
212212
# order
213-
columns = _make_columns(ds.element_spec, ds_info=ds_info)
213+
columns = _make_columns(ds.element_spec, ds_info=ds_info) # pyrefly: ignore[bad-argument-type]
214214
rows = [_make_row_dict(ex, columns) for ex in dataset_utils.as_numpy(ds)]
215215
df = StyledDataFrame(rows)
216216
df.current_style.format({c.name: c.format_fn for c in columns if c.format_fn})

tensorflow_datasets/core/dataset_builder.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,8 @@ def from_dataset_info(
136136
name=info_proto.config_name,
137137
description=info_proto.config_description,
138138
version=info_proto.version,
139-
release_notes=info_proto.release_notes or {},
140-
tags=info_proto.config_tags or [],
139+
release_notes=info_proto.release_notes or {}, # pyrefly: ignore[bad-argument-type]
140+
tags=info_proto.config_tags or [], # pyrefly: ignore[bad-argument-type]
141141
)
142142

143143

@@ -292,7 +292,7 @@ def __init__(
292292
# Extract code version (VERSION or config)
293293
self._version = self._pick_version(version)
294294
# Compute the base directory (for download) and dataset/version directory.
295-
self._data_dir_root, self._data_dir = self._build_data_dir(data_dir)
295+
self._data_dir_root, self._data_dir = self._build_data_dir(data_dir) # pyrefly: ignore[bad-argument-type]
296296
# If the dataset info is available, use it.
297297
dataset_info_path = dataset_info.dataset_info_path(self.data_path)
298298
if retry.retry(dataset_info_path.exists):
@@ -924,14 +924,14 @@ def build_single_data_source(split: str) -> Sequence[Any]:
924924
case file_adapters.FileFormat.ARRAY_RECORD:
925925
return array_record.ArrayRecordDataSource(
926926
info,
927-
split=split,
927+
split=split, # pyrefly: ignore[bad-argument-type]
928928
decoders=decoders,
929929
deserialize_method=deserialize_method,
930930
)
931931
case file_adapters.FileFormat.PARQUET:
932932
return parquet.ParquetDataSource(
933933
info,
934-
split=split,
934+
split=split, # pyrefly: ignore[bad-argument-type]
935935
decoders=decoders,
936936
deserialize_method=deserialize_method,
937937
)
@@ -1298,7 +1298,7 @@ def _make_download_manager(
12981298
# Note: Error will be raised here if user try to record checksums
12991299
# from a `zipapp`
13001300
try:
1301-
register_checksums_path = utils.to_write_path(self._checksums_path)
1301+
register_checksums_path = utils.to_write_path(self._checksums_path) # pyrefly: ignore[bad-argument-type]
13021302
download.validate_checksums_path(register_checksums_path)
13031303
except Exception: # pylint: disable=broad-except
13041304
raise
@@ -1558,7 +1558,7 @@ def _as_dataset(
15581558

15591559
reader = reader_lib.Reader(
15601560
example_specs=example_specs,
1561-
file_format=file_format,
1561+
file_format=file_format, # pyrefly: ignore[bad-argument-type]
15621562
)
15631563
decode_fn = functools.partial(features.decode_example, decoders=decoders)
15641564
return reader.read(
@@ -1849,7 +1849,7 @@ def read_tfrecord_as_dataset(
18491849

18501850
return tf.data.TFRecordDataset(
18511851
filenames=filenames,
1852-
compression_type=compression_type,
1852+
compression_type=compression_type, # pyrefly: ignore[bad-argument-type]
18531853
num_parallel_reads=num_parallel_reads,
18541854
)
18551855

@@ -1939,7 +1939,7 @@ def _download_and_prepare(
19391939
beam_runner=download_config.beam_runner,
19401940
example_writer=self._example_writer(),
19411941
# The following options are ignored by `ShardBasedBuilder`.
1942-
ignore_duplicates=None,
1942+
ignore_duplicates=None, # pyrefly: ignore[bad-argument-type]
19431943
max_examples_per_split=None,
19441944
shard_config=None,
19451945
)
@@ -2000,7 +2000,7 @@ class BeamBasedBuilder(GeneratorBasedBuilder):
20002000
def _generate_examples(
20012001
self, *args: Any, **kwargs: Any
20022002
) -> split_builder_lib.SplitGenerator:
2003-
return self._build_pcollection(*args, **kwargs)
2003+
return self._build_pcollection(*args, **kwargs) # pyrefly: ignore[missing-attribute]
20042004

20052005

20062006
def _check_split_names(split_names: Iterable[str]) -> None:

tensorflow_datasets/core/dataset_collection_builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def from_cls(
107107
return cls(
108108
name=name,
109109
release_notes=release_notes,
110-
description=description,
110+
description=description, # pyrefly: ignore[bad-argument-type]
111111
citation=citation,
112112
homepage=homepage,
113113
)

tensorflow_datasets/core/dataset_info.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def from_proto(
162162
module_name=info_proto.module_name,
163163
config_name=info_proto.config_name,
164164
config_description=info_proto.config_description,
165-
config_tags=info_proto.config_tags or [],
165+
config_tags=info_proto.config_tags or [], # pyrefly: ignore[bad-argument-type]
166166
release_notes={k: v for k, v in info_proto.release_notes.items()},
167167
)
168168

@@ -728,7 +728,7 @@ def read_from_directory(self, dataset_info_dir: epath.PathLike) -> None:
728728
# Update splits
729729
filename_template = naming.ShardedFileTemplate( # pytype: disable=wrong-arg-types # always-use-property-annotation
730730
dataset_name=self.name,
731-
data_dir=self.data_dir,
731+
data_dir=self.data_dir, # pyrefly: ignore[bad-argument-type]
732732
filetype_suffix=parsed_proto.file_format or "tfrecord",
733733
)
734734
split_dict = splits_lib.SplitDict.from_proto(
@@ -743,7 +743,7 @@ def read_from_directory(self, dataset_info_dir: epath.PathLike) -> None:
743743
# For `ReadOnlyBuilder`, reconstruct the features from the config.
744744
elif feature_lib.make_config_path(dataset_info_dir).exists():
745745
self._features = top_level_feature.TopLevelFeature.from_config(
746-
dataset_info_dir
746+
dataset_info_dir # pyrefly: ignore[bad-argument-type]
747747
)
748748

749749
# If the dataset was loaded from file, self.metadata will be `None`, so
@@ -827,7 +827,7 @@ def add_file_data_source_access(
827827
access_timestamp_ms = _now_in_milliseconds()
828828
if isinstance(path, str) or isinstance(path, epath.Path):
829829
path = os.fspath(path).split(",")
830-
for p in path:
830+
for p in path: # pyrefly: ignore[not-iterable]
831831
for file in file_utils.expand_glob(p):
832832
self._info_proto.data_source_accesses.append(
833833
dataset_info_pb2.DataSourceAccess(
@@ -921,7 +921,7 @@ def __repr__(self):
921921
config_description = SKIP
922922

923923
if self._info_proto.config_tags:
924-
config_tags = ", ".join(self.config_tags)
924+
config_tags = ", ".join(self.config_tags) # pyrefly: ignore[no-matching-overload]
925925
else:
926926
config_tags = SKIP
927927

@@ -1007,10 +1007,10 @@ def _nest_to_proto(nest: Nest) -> dataset_info_pb2.SupervisedKeys.Nest:
10071007
for item in nest:
10081008
proto.tuple.items.append(_nest_to_proto(item))
10091009
elif nest_type is dict:
1010-
nest = {key: _nest_to_proto(value) for key, value in nest.items()}
1011-
proto.dict.CopyFrom(dataset_info_pb2.SupervisedKeys.Dict(dict=nest))
1010+
nest = {key: _nest_to_proto(value) for key, value in nest.items()} # pyrefly: ignore[bad-assignment]
1011+
proto.dict.CopyFrom(dataset_info_pb2.SupervisedKeys.Dict(dict=nest)) # pyrefly: ignore[bad-argument-type]
10121012
elif nest_type is str:
1013-
proto.feature_key = nest
1013+
proto.feature_key = nest # pyrefly: ignore[bad-assignment]
10141014
else:
10151015
raise ValueError(
10161016
"The nested structures in `supervised_keys` must only "
@@ -1072,7 +1072,7 @@ def _supervised_keys_from_proto(
10721072
if proto.input and proto.output:
10731073
return (proto.input, proto.output)
10741074
elif proto.tuple:
1075-
return tuple(_nest_from_proto(item) for item in proto.tuple.items)
1075+
return tuple(_nest_from_proto(item) for item in proto.tuple.items) # pyrefly: ignore[bad-return]
10761076
else:
10771077
raise ValueError(
10781078
"A `SupervisedKeys` proto must have either `input` and "
@@ -1376,7 +1376,7 @@ def add_tfds_data_source_access(
13761376
name=dataset_reference.dataset_name,
13771377
config=dataset_reference.config,
13781378
version=str(dataset_reference.version),
1379-
data_dir=os.fspath(dataset_reference.data_dir),
1379+
data_dir=os.fspath(dataset_reference.data_dir), # pyrefly: ignore[no-matching-overload]
13801380
ds_namespace=dataset_reference.namespace,
13811381
),
13821382
url=dataset_info_pb2.Url(url=url),

tensorflow_datasets/core/dataset_metadata.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ def load(pkg_path: epath.Path) -> DatasetMetadata:
8888
raw_metadata = _read_files(pkg_path)
8989
tags = _get_tags(raw_metadata.get(TAGS_FILENAME, ""))
9090
return DatasetMetadata(
91-
description=raw_metadata.get(DESCRIPTIONS_FILENAME, None),
92-
citation=raw_metadata.get(CITATIONS_FILENAME, None),
91+
description=raw_metadata.get(DESCRIPTIONS_FILENAME, None), # pyrefly: ignore[bad-argument-type]
92+
citation=raw_metadata.get(CITATIONS_FILENAME, None), # pyrefly: ignore[bad-argument-type]
9393
tags=tags,
9494
)
9595

@@ -108,4 +108,4 @@ def _read_files(path: epath.Path) -> dict[str, str]:
108108
for inode in path.iterdir():
109109
if inode.name in _METADATA_FILES:
110110
name2path[inode.name] = path.joinpath(inode.name)
111-
return etree.parallel_map(lambda f: f.read_text(encoding="utf-8"), name2path)
111+
return etree.parallel_map(lambda f: f.read_text(encoding="utf-8"), name2path) # pyrefly: ignore[bad-return]

tensorflow_datasets/core/example_parser.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,8 @@ def __post_init__(self):
130130
def parse_example(
131131
self, serialized_example: bytes | memoryview
132132
) -> Mapping[str, Union[np.ndarray, list[Any]]]:
133-
example = tf_example_pb2.Example.FromString(serialized_example)
134-
np_example = _features_to_numpy(example.features, self._flat_example_specs)
133+
example = tf_example_pb2.Example.FromString(serialized_example) # pyrefly: ignore[bad-argument-type]
134+
np_example = _features_to_numpy(example.features, self._flat_example_specs) # pyrefly: ignore[bad-argument-type]
135135
return utils.pack_as_nest_dict(np_example, self.example_specs)
136136

137137

@@ -220,7 +220,7 @@ def _feature_to_numpy(
220220
return value_array.item()
221221
feature_name = _key_to_feature_name(key)
222222
row_lengths = _extract_row_lengths(features, feature_name)
223-
return reshape_ragged_tensor(value_array, row_lengths, shape)
223+
return reshape_ragged_tensor(value_array, row_lengths, shape) # pyrefly: ignore[bad-argument-type]
224224

225225

226226
def _extract_row_lengths(
@@ -269,7 +269,7 @@ def reshape_ragged_tensor(
269269
value = values[i : i + length]
270270
array.append(value)
271271
i += length
272-
values = array
272+
values = array # pyrefly: ignore[bad-assignment]
273273
return values
274274

275275

@@ -346,7 +346,7 @@ def _deserialize_single_field(
346346

347347
def _dict_to_ragged(example_data, tensor_info):
348348
"""Reconstruct the ragged tensor from the row ids."""
349-
return tf.RaggedTensor.from_nested_row_lengths(
349+
return tf.RaggedTensor.from_nested_row_lengths( # pyrefly: ignore[missing-attribute]
350350
flat_values=example_data["ragged_flat_values"],
351351
nested_row_lengths=[
352352
example_data["ragged_row_lengths_{}".format(k)]
@@ -363,13 +363,13 @@ def _to_tf_example_spec(tensor_info: feature_lib.TensorInfo):
363363
# This create limitation like float64 downsampled to float32, bool converted
364364
# to int64 which is space ineficient, no support for complexes or quantized
365365
# It seems quite space inefficient to convert bool to int64
366-
if dtype_utils.is_integer(tensor_info.tf_dtype) or dtype_utils.is_bool(
367-
tensor_info.tf_dtype
366+
if dtype_utils.is_integer(tensor_info.tf_dtype) or dtype_utils.is_bool( # pyrefly: ignore[bad-argument-type]
367+
tensor_info.tf_dtype # pyrefly: ignore[bad-argument-type]
368368
):
369369
dtype = tf.int64
370-
elif dtype_utils.is_floating(tensor_info.tf_dtype):
370+
elif dtype_utils.is_floating(tensor_info.tf_dtype): # pyrefly: ignore[bad-argument-type]
371371
dtype = tf.float32
372-
elif dtype_utils.is_string(tensor_info.tf_dtype):
372+
elif dtype_utils.is_string(tensor_info.tf_dtype): # pyrefly: ignore[bad-argument-type]
373373
dtype = tf.string
374374
else:
375375
# TFRecord only support 3 types

tensorflow_datasets/core/example_serializer.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def get_tf_example(self, example: TreeDict[Any]) -> tf.train.Example:
8181
Returns:
8282
The `tf.train.Example` proto
8383
"""
84-
return _dict_to_tf_example(
84+
return _dict_to_tf_example( # pyrefly: ignore[bad-return]
8585
utils.flatten_nest_dict(example), self._flat_example_specs
8686
)
8787

@@ -166,7 +166,7 @@ def _is_string(item) -> bool:
166166
def _item_to_np_array(item, dtype: np.dtype, shape: Shape) -> np.ndarray:
167167
"""Single item to a np.array."""
168168
result = np.asanyarray(item, dtype=dtype)
169-
utils.assert_shape_match(result.shape, shape)
169+
utils.assert_shape_match(result.shape, shape) # pyrefly: ignore[bad-argument-type]
170170
if dtype_utils.is_string(dtype) and not _is_string(item):
171171
raise ValueError(
172172
f"Unsupported value: {result}\nCould not convert to bytes list."
@@ -192,16 +192,16 @@ def _item_to_tf_feature(
192192
v = v.view(np.int64)
193193
vals = v.flat # Convert v into a 1-d array (without extra copy)
194194
if dtype_utils.is_integer(v.dtype):
195-
return tf_feature_pb2.Feature(
196-
int64_list=tf_feature_pb2.Int64List(value=vals)
195+
return tf_feature_pb2.Feature( # pyrefly: ignore[bad-return]
196+
int64_list=tf_feature_pb2.Int64List(value=vals) # pyrefly: ignore[bad-argument-type]
197197
)
198198
elif dtype_utils.is_floating(v.dtype):
199-
return tf_feature_pb2.Feature(
200-
float_list=tf_feature_pb2.FloatList(value=vals)
199+
return tf_feature_pb2.Feature( # pyrefly: ignore[bad-return]
200+
float_list=tf_feature_pb2.FloatList(value=vals) # pyrefly: ignore[bad-argument-type]
201201
)
202202
elif dtype_utils.is_string(tensor_info.np_dtype):
203-
vals = [_as_bytes(x) for x in vals]
204-
return tf_feature_pb2.Feature(
203+
vals = [_as_bytes(x) for x in vals] # pyrefly: ignore[bad-argument-type]
204+
return tf_feature_pb2.Feature( # pyrefly: ignore[bad-return]
205205
bytes_list=tf_feature_pb2.BytesList(value=vals)
206206
)
207207
else:
@@ -229,7 +229,7 @@ def _as_bytes(bytes_or_text: bytearray | bytes | str) -> bytes:
229229
"""
230230
# Validate encoding, a LookupError will be raised if invalid.
231231
if isinstance(bytes_or_text, (bytearray, bytes)):
232-
return bytes_or_text
232+
return bytes_or_text # pyrefly: ignore[bad-return]
233233
elif isinstance(bytes_or_text, str):
234234
return bytes_or_text.encode(encoding="utf-8")
235235
else:
@@ -300,11 +300,11 @@ def _add_ragged_fields(example_data, tensor_info: feature_lib.TensorInfo):
300300
tensor_info_length = feature_lib.TensorInfo(shape=(None,), dtype=np.int64)
301301
ragged_attr_dict = {
302302
"ragged_row_lengths_{}".format(i): (length, tensor_info_length)
303-
for i, length in enumerate(nested_row_lengths)
303+
for i, length in enumerate(nested_row_lengths) # pyrefly: ignore[unbound-name]
304304
}
305305
tensor_info_flat = feature_lib.TensorInfo(
306-
shape=(None,) + tensor_info.shape[tensor_info.sequence_rank :],
307-
dtype=tensor_info.dtype,
306+
shape=(None,) + tensor_info.shape[tensor_info.sequence_rank :], # pyrefly: ignore[unsupported-operation]
307+
dtype=tensor_info.dtype, # pyrefly: ignore[bad-argument-type]
308308
)
309309
ragged_attr_dict["ragged_flat_values"] = (example_data, tensor_info_flat)
310310
return ragged_attr_dict
@@ -342,8 +342,8 @@ def _extract_ragged_attributes(
342342
)
343343
)
344344
if not flat_values: # The full sequence is empty
345-
flat_values = np.empty(
346-
shape=(0,) + tensor_info.shape[tensor_info.sequence_rank :],
345+
flat_values = np.empty( # pyrefly: ignore[no-matching-overload]
346+
shape=(0,) + tensor_info.shape[tensor_info.sequence_rank :], # pyrefly: ignore[unsupported-operation]
347347
dtype=tensor_info.np_dtype,
348348
)
349349
else: # Otherwise, merge all flat values together, some might be empty

tensorflow_datasets/core/features/audio_feature.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -179,11 +179,11 @@ def decode_audio(self, audio_tensor: tf.Tensor) -> tf.Tensor:
179179
decoded_audio_tensor = tf.squeeze(decoded_audio_tensor)
180180
else:
181181
if self._file_format:
182-
file_format_tensor = tf.experimental.Optional.from_value(
182+
file_format_tensor = tf.experimental.Optional.from_value( # pyrefly: ignore[missing-attribute]
183183
self._file_format
184184
)
185185
else:
186-
file_format_tensor = tf.experimental.Optional.empty(
186+
file_format_tensor = tf.experimental.Optional.empty( # pyrefly: ignore[missing-attribute]
187187
tf.TensorSpec(shape=(), dtype=tf.string)
188188
)
189189

@@ -206,7 +206,7 @@ class _EagerDecoder(_AudioDecoder):
206206
def encode_audio(
207207
self, fobj: BinaryIO, file_format: Optional[str]
208208
) -> np.ndarray:
209-
audio = _pydub_load_audio(fobj, file_format, self._channels)
209+
audio = _pydub_load_audio(fobj, file_format, self._channels) # pyrefly: ignore[bad-argument-type]
210210
return audio.astype(self._np_dtype)
211211

212212
def decode_audio(self, audio_tensor: tf.Tensor) -> tf.Tensor:
@@ -336,17 +336,17 @@ def repr_html(self, ex: np.ndarray) -> str:
336336
)
337337

338338
@classmethod
339-
def from_json_content(
339+
def from_json_content( # pyrefly: ignore[bad-override]
340340
cls, value: Union[Json, feature_pb2.AudioFeature]
341341
) -> 'Audio':
342342
if isinstance(value, dict):
343343
# For backwards compatibility
344344
return cls(
345-
file_format=value['file_format'],
346-
shape=tuple(value['shape']),
347-
dtype=feature_lib.dtype_from_str(value['dtype']),
348-
sample_rate=value['sample_rate'],
349-
lazy_decode=value.get('lazy_decode', False),
345+
file_format=value['file_format'], # pyrefly: ignore[bad-argument-type]
346+
shape=tuple(value['shape']), # pyrefly: ignore[bad-argument-type]
347+
dtype=feature_lib.dtype_from_str(value['dtype']), # pyrefly: ignore[bad-argument-type]
348+
sample_rate=value['sample_rate'], # pyrefly: ignore[bad-argument-type]
349+
lazy_decode=value.get('lazy_decode', False), # pyrefly: ignore[bad-argument-type]
350350
)
351351
return cls(
352352
shape=feature_lib.from_shape_proto(value.shape),
@@ -360,7 +360,7 @@ def from_json_content(
360360
def to_json_content(self) -> feature_pb2.AudioFeature: # pytype: disable=signature-mismatch # overriding-return-type-checks
361361
return feature_pb2.AudioFeature(
362362
shape=feature_lib.to_shape_proto(self.shape),
363-
dtype=feature_lib.dtype_to_str(self.dtype),
363+
dtype=feature_lib.dtype_to_str(self.dtype), # pyrefly: ignore[bad-argument-type]
364364
file_format=self._file_format,
365365
sample_rate=self._sample_rate,
366366
encoding=self._encoding.name,

0 commit comments

Comments
 (0)