Skip to content

Sourcery refactored main branch - #1

Open
sourcery-ai[bot] wants to merge 1 commit into
mainfrom
sourcery/main
Open

Sourcery refactored main branch#1
sourcery-ai[bot] wants to merge 1 commit into
mainfrom
sourcery/main

Conversation

@sourcery-ai

@sourcery-ai sourcery-ai Bot commented Dec 12, 2021

Copy link
Copy Markdown

Branch main refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch origin sourcery/main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai
sourcery-ai Bot requested a review from wjptak December 12, 2021 20:32

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

Comment thread hub/compression.py
Bytes : lz4

"""

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 81-83 refactored with the following changes:

Comment thread hub/constants.py
ENCODED_CHUNK_NAMES_FOLDER = "chunks_index"
# unsharded naming will help with backwards compatibility
ENCODED_CHUNK_NAMES_FILENAME = f"unsharded"
ENCODED_CHUNK_NAMES_FILENAME = 'unsharded'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 56-56 refactored with the following changes:

Comment thread hub/api/dataset.py
Comment on lines +263 to -269
elif isinstance(e, (DatasetHandlerError, PathNotEmptyException)):
raise DatasetHandlerError(
"A Hub dataset wasn't found at the specified path. "
"This may be due to a corrupt dataset or a wrong path. "
"If you want to delete the data at the path regardless, use force=True"
)
else:
if isinstance(e, (DatasetHandlerError, PathNotEmptyException)):
raise DatasetHandlerError(
"A Hub dataset wasn't found at the specified path. "
"This may be due to a corrupt dataset or a wrong path. "
"If you want to delete the data at the path regardless, use force=True"
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function dataset.delete refactored with the following changes:

Comment thread hub/api/dataset.py
Comment on lines -478 to +483
if os.path.isdir(src) and os.path.isdir(dest):
if os.path.samefile(src, dest):
raise SamePathException(src)
if (
os.path.isdir(src)
and os.path.isdir(dest)
and os.path.samefile(src, dest)
):
raise SamePathException(src)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function dataset.ingest_kaggle refactored with the following changes:

Comment thread hub/api/dataset.py
Comment on lines -519 to +520
datasets = client.get_datasets(workspace=workspace)
return datasets
return client.get_datasets(workspace=workspace)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function dataset.list refactored with the following changes:

Comment thread hub/client/client.py
self.token = self.get_token()
else:
self.token = token
self.token = self.get_token() if token is None else token

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function HubBackendClient.__init__ refactored with the following changes:

Comment thread hub/client/client.py
Comment on lines -229 to -245
response = self.request(
return self.request(
"GET",
suffix_user,
endpoint=self.endpoint(),
params={"organization": workspace},
).json()
else:
print(
f'You are not a member of organization "{workspace}". List of accessible datasets from "{workspace}": ',
)
response = self.request(
print(
f'You are not a member of organization "{workspace}". List of accessible datasets from "{workspace}": ',
)
return self.request(
"GET",
suffix_public,
endpoint=self.endpoint(),
params={"organization": workspace},
).json()
return response

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function HubBackendClient.get_workspace_datasets refactored with the following changes:

Comment thread hub/core/chunk_engine.py
Comment on lines -496 to +497
if not aslist and last_shape is not None:
if shape != last_shape:
raise DynamicTensorNumpyError(self.key, index, "shape")
if not aslist and last_shape is not None and shape != last_shape:
raise DynamicTensorNumpyError(self.key, index, "shape")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ChunkEngine.numpy refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -197 to +203
if compression == "lz4":
if (
buffer[:4] == b'\x04"M\x18'
): # python-lz4 magic number (backward compatiblity)
return lz4.frame.decompress(buffer)
return numcodecs.lz4.decompress(buffer)
else:
if compression != "lz4":
raise SampleDecompressionError()
if (
buffer[:4] == b'\x04"M\x18'
): # python-lz4 magic number (backward compatiblity)
return lz4.frame.decompress(buffer)
return numcodecs.lz4.decompress(buffer)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function decompress_bytes refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -419 to +418
elif compression in ("mp4", "mkv", "avi"):
elif compression in {"mp4", "mkv", "avi"}:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function verify_compressed_file refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -555 to +554
if img.mode == 1:
args = ("L",)
else:
args = (img.mode,)
args = ("L", ) if img.mode == 1 else (img.mode, )

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _fast_decompress refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -723 to +719
if bits == 8:
nlayers = 2
else:
nlayers = 4
nlayers = 2 if bits == 8 else 4

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _read_png_shape_and_dtype refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -848 to +841
if "duration" in ret:
ret["duration"] = float(ret["duration"])
else:
ret["duration"] = duration
ret["duration"] = float(ret["duration"]) if "duration" in ret else duration

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_video_info refactored with the following changes:

Comment thread hub/core/compression.py
Comment on lines -860 to +850
return sum([60 ** i * float(j) for (i, j) in enumerate(time.split(":")[::-1])])
return sum(60 ** i * float(j) for (i, j) in enumerate(time.split(":")[::-1]))

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function to_seconds refactored with the following changes:

Comment on lines -23 to +26
for i in range(m, n):
for _ in range(m, n):
arr2.append(0)
elif m > n:
for i in range(n, m):
for _ in range(n, m):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function version_compare refactored with the following changes:

Comment thread hub/core/index/index.py
return IndexEntry(new_value)
elif isinstance(self.value, tuple):
if isinstance(item, int) or isinstance(item, slice):
if isinstance(item, (int, slice)):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function IndexEntry.__getitem__ refactored with the following changes:

Comment thread hub/core/index/index.py
Comment on lines -192 to +193
and self.value.stop == None
and ((self.value.step or 1) == 1)
and self.value.stop is None
and (self.value.step or 1) == 1

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function IndexEntry.is_trivial refactored with the following changes:

Comment thread hub/core/index/index.py
Comment on lines -237 to +242
if isinstance(self.value, int):
if self.value >= parent_length or self.value < -parent_length:
raise ValueError(
f"Index {self.value} is out of range for tensors with length {parent_length}"
)
if isinstance(self.value, int) and (
self.value >= parent_length or self.value < -parent_length
):
raise ValueError(
f"Index {self.value} is out of range for tensors with length {parent_length}"
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function IndexEntry.validate refactored with the following changes:

Comment thread hub/core/index/index.py
Comment on lines -301 to +303
else:
new_values = self.values[:i] + [self.values[i][item]] + self.values[i + 1 :]
return Index(new_values)
new_values = self.values[:i] + [self.values[i][item]] + self.values[i + 1 :]
return Index(new_values)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Index.compose_at refactored with the following changes:

Comment thread hub/core/index/index.py
or compatible with NumPy's advanced integer indexing.
"""
if isinstance(item, int) or isinstance(item, slice):
if isinstance(item, (int, slice)):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Index.__getitem__ refactored with the following changes:

Comment thread hub/core/index/index.py
"""
index_values = tuple(item.value for item in self.values[1:])
samples = list(arr[index_values] for arr in samples)
samples = [arr[index_values] for arr in samples]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Index.apply refactored with the following changes:

Comment on lines -136 to -144
required_meta = {
return {
"htype": htype,
"min_shape": [],
"max_shape": [],
"length": 0,
**defaults,
}

return required_meta

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _required_meta_from_htype refactored with the following changes:

Comment on lines -156 to +158
if value == UNSPECIFIED:
if defaults[key] == REQUIRE_USER_SPECIFICATION:
raise TensorMetaMissingRequiredValue(htype, key)
if (
value == UNSPECIFIED
and defaults[key] == REQUIRE_USER_SPECIFICATION
):
raise TensorMetaMissingRequiredValue(htype, key)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _validate_htype_overwrites refactored with the following changes:

Comment on lines -216 to +218
if htype in ("json", "list", "text") and not htype_overwrite["dtype"]:
if htype in {"json", "list", "text"} and not htype_overwrite["dtype"]:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _replace_unspecified_values refactored with the following changes:

Comment on lines -239 to +241
if htype in ("json", "list"):
if htype in {"json", "list"}:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _validate_required_htype_overwrites refactored with the following changes:

Comment on lines -138 to +143
dsv = local_ds[0:3]
dsv = local_ds[:3]
dsv.abc[0] = 5
h = local_ds.commit("it is 5")
i = local_ds.checkout(e)
local_ds.abc[0] = 6
tsv = local_ds.abc[0:5]
tsv = local_ds.abc[:5]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_auto_checkout_bug refactored with the following changes:

Comment on lines +36 to +39
if ensure_order:
return MultiThreadedNaiveScheduler(num_workers)
else:
if ensure_order:
return MultiThreadedNaiveScheduler(num_workers)
else:
return SequentialMultithreadScheduler(num_workers)
return SequentialMultithreadScheduler(num_workers)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function use_scheduler refactored with the following changes:

Comment on lines -293 to +317
if not self.shutdown:
self.workers_done.set()
if self.shutdown:
return

try:
for wid in range(self.num_workers):
self.request_queues[wid].put(None)
self.workers[wid].join(timeout=5)

for queue in self.request_queues:
queue.cancel_join_thread()
queue.close()

self.data_queue.cancel_join_thread()
self.data_queue.close()
finally:
if self._worker_pids_set:
_remove_worker_pids(id(self))
self._worker_pids_set = False

for worker in self.workers:
if worker.is_alive():
worker.terminate()

self.shutdown = True
self.workers_done.set()

try:
for wid in range(self.num_workers):
self.request_queues[wid].put(None)
self.workers[wid].join(timeout=5)

for queue in self.request_queues:
queue.cancel_join_thread()
queue.close()

self.data_queue.cancel_join_thread()
self.data_queue.close()
finally:
if self._worker_pids_set:
_remove_worker_pids(id(self))
self._worker_pids_set = False

for worker in self.workers:
if worker.is_alive():
worker.terminate()

self.shutdown = True

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PrefetchConcurrentIterator._shutdown_all refactored with the following changes:

Comment on lines -79 to +83
warning_message += f"Windows OS detected. Pytorch iteration speeds are up to 500% faster using linux/macOS along with Python version >= 3.8. "
warning_message += 'Windows OS detected. Pytorch iteration speeds are up to 500% faster using linux/macOS along with Python version >= 3.8. '

else:
warning_message += f"Python version < 3.8 detected. Pytorch iteration speeds are up to 500% faster on Python version >= 3.8.\n"
warning_message += 'Python version < 3.8 detected. Pytorch iteration speeds are up to 500% faster on Python version >= 3.8.\n'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function TorchDataset.__init__ refactored with the following changes:

buffer_len = len(self.buffer)

if not sample is None:
if sample is not None:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ShuffleBuffer.exchange refactored with the following changes:

@sourcery-ai

sourcery-ai Bot commented Dec 12, 2021

Copy link
Copy Markdown
Author

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.21%.

Quality metrics Before After Change
Complexity 4.63 ⭐ 4.46 ⭐ -0.17 👍
Method Length 54.31 ⭐ 54.02 ⭐ -0.29 👍
Working memory 7.55 🙂 7.51 🙂 -0.04 👍
Quality 70.95% 🙂 71.16% 🙂 0.21% 👍
Other metrics Before After Change
Lines 11470 11386 -84
Changed files Quality Before Quality After Quality Change
hub/compression.py 58.91% 🙂 60.28% 🙂 1.37% 👍
hub/constants.py 65.35% 🙂 65.42% 🙂 0.07% 👍
hub/api/dataset.py 63.11% 🙂 63.62% 🙂 0.51% 👍
hub/api/read.py 96.34% ⭐ 99.50% ⭐ 3.16% 👍
hub/api/tests/test_api.py 73.46% 🙂 73.47% 🙂 0.01% 👍
hub/api/tests/test_meta.py 78.38% ⭐ 78.38% ⭐ 0.00%
hub/api/tests/test_update_samples.py 65.93% 🙂 66.15% 🙂 0.22% 👍
hub/auto/unstructured/image_classification.py 58.51% 🙂 56.37% 🙂 -2.14% 👎
hub/auto/unstructured/kaggle.py 65.85% 🙂 65.95% 🙂 0.10% 👍
hub/client/client.py 78.09% ⭐ 78.32% ⭐ 0.23% 👍
hub/core/chunk_engine.py 76.37% ⭐ 76.54% ⭐ 0.17% 👍
hub/core/compression.py 59.67% 🙂 59.94% 🙂 0.27% 👍
hub/core/fast_forwarding.py 78.66% ⭐ 78.65% ⭐ -0.01% 👎
hub/core/io.py 73.72% 🙂 73.79% 🙂 0.07% 👍
hub/core/sample.py 59.51% 🙂 59.57% 🙂 0.06% 👍
hub/core/serialize.py 68.60% 🙂 68.45% 🙂 -0.15% 👎
hub/core/tensor.py 88.94% ⭐ 89.05% ⭐ 0.11% 👍
hub/core/dataset/dataset.py 74.85% 🙂 74.93% 🙂 0.08% 👍
hub/core/index/index.py 75.07% ⭐ 75.45% ⭐ 0.38% 👍
hub/core/meta/tensor_meta.py 71.03% 🙂 72.12% 🙂 1.09% 👍
hub/core/meta/encode/base_encoder.py 81.32% ⭐ 81.92% ⭐ 0.60% 👍
hub/core/meta/encode/byte_positions.py 82.64% ⭐ 82.59% ⭐ -0.05% 👎
hub/core/storage/gcs.py 87.09% ⭐ 87.15% ⭐ 0.06% 👍
hub/core/storage/lru_cache.py 82.86% ⭐ 83.06% ⭐ 0.20% 👍
hub/core/storage/tests/test_storage_provider.py 73.17% 🙂 73.40% 🙂 0.23% 👍
hub/core/tests/test_io.py 89.14% ⭐ 89.16% ⭐ 0.02% 👍
hub/core/transform/test_transform.py 62.99% 🙂 63.29% 🙂 0.30% 👍
hub/core/version_control/test_version_control.py 57.82% 🙂 57.83% 🙂 0.01% 👍
hub/integrations/pytorch/dataset.py 57.40% 🙂 58.15% 🙂 0.75% 👍
hub/integrations/pytorch/pytorch_old.py 66.46% 🙂 66.55% 🙂 0.09% 👍
hub/integrations/pytorch/shuffle_buffer.py 71.39% 🙂 73.51% 🙂 2.12% 👍
hub/integrations/tests/test_pytorch.py 54.98% 🙂 55.34% 🙂 0.36% 👍
hub/integrations/tests/test_pytorch_dataloader.py 85.30% ⭐ 85.05% ⭐ -0.25% 👎
hub/integrations/tests/test_shuffle_buffer.py 92.76% ⭐ 92.76% ⭐ 0.00%
hub/integrations/tests/test_tensorflow.py 73.59% 🙂 73.59% 🙂 0.00%
hub/tests/cache_fixtures.py 75.90% ⭐ 76.18% ⭐ 0.28% 👍
hub/tests/client_fixtures.py 86.42% ⭐ 86.82% ⭐ 0.40% 👍
hub/tests/common.py 79.75% ⭐ 79.73% ⭐ -0.02% 👎
hub/tests/path_fixtures.py 78.62% ⭐ 80.28% ⭐ 1.66% 👍
hub/util/auto.py 57.34% 🙂 59.02% 🙂 1.68% 👍
hub/util/casting.py 76.28% ⭐ 76.39% ⭐ 0.11% 👍
hub/util/exceptions.py 95.21% ⭐ 95.43% ⭐ 0.22% 👍
hub/util/iterable_ordered_dict.py 98.67% ⭐ 100.00% ⭐ 1.33% 👍
hub/util/json.py 70.76% 🙂 70.22% 🙂 -0.54% 👎
hub/util/shape_interval.py 85.08% ⭐ 84.95% ⭐ -0.13% 👎
hub/util/storage.py 65.97% 🙂 67.08% 🙂 1.11% 👍

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
hub/integrations/pytorch/dataset.py _worker_loop 25 😞 208 ⛔ 16 ⛔ 27.65% 😞 Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
hub/core/compression.py read_meta_from_compressed_file 25 😞 221 ⛔ 14 😞 29.16% 😞 Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
hub/auto/unstructured/image_classification.py ImageClassification.structure 13 🙂 263 ⛔ 15 😞 34.40% 😞 Try splitting into smaller methods. Extract out complex expressions
hub/core/sample.py Sample.uncompressed_bytes 27 😞 154 😞 13 😞 34.98% 😞 Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
hub/core/dataset/dataset.py Dataset.create_tensor 15 🙂 237 ⛔ 14 😞 35.30% 😞 Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant