Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update _read_bytes function in images.py support for URL #548

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions oml/datasets/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,17 @@ def __init__(

@staticmethod
def _read_bytes(path: Union[Path, str]) -> bytes:
with open(str(path), "rb") as fin:
return fin.read()
if isinstance(path, str) and path.startswith(('http://', 'https://')):
# If the path is a URL, use requests to fetch the content
response = requests.get(path)
Copy link
Collaborator

Choose a reason for hiding this comment

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

From a performance point of view, it would be more efficient to create a session instance self.session = self.session or requests.Session() and make requests using self.session.get(...). Otherwise, for each call of __getitem__, you will need to establish a new connection with the remote server (DNS resolution, certificate exchange, etc). Establishing a connection can take a huge amount of time.

I'm not sure about an exact implementation but doing requests.get is not a good idea for dataset scenario, because we can reuse a session.

if response.status_code == 200:
return response.content
else:
raise ValueError(f"Failed to fetch image from URL: {path}")
else:
# Otherwise, assume it's a local file path
with open(str(path), "rb") as fin:
return fin.read()

def __getitem__(self, item: int) -> Dict[str, Union[FloatTensor, int]]:
img_bytes = self.read_bytes(self._paths[item])
Expand Down