Dataset Viewer
Auto-converted to Parquet
repo
stringlengths
8
46
pull_number
int64
1
11.6k
instance_id
stringlengths
13
51
issue_numbers
stringlengths
5
42
base_commit
stringlengths
40
40
patch
stringlengths
145
88.1M
test_patch
stringlengths
99
70.7M
problem_statement
stringlengths
12
44k
hints_text
stringlengths
0
77.5k
created_at
timestamp[us]date
2012-10-22 17:43:45
2025-04-11 08:25:56
version
stringclasses
1 value
aio-libs/aiobotocore
795
aio-libs__aiobotocore-795
['794']
017cb59e276a24b64005beb6bd41d3ebc4135904
diff --git a/CHANGES.rst b/CHANGES.rst index 771b5033..d9b776d9 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,10 @@ Changes ------- + +1.0.3 (2020-04-09) +^^^^^^^^^^^^^^^^^^ +* Fixes typo when using credential process + 1.0.2 (2020-04-05) ^^^^^^^^^^^^^^^^^^ * Disable Client.__getattr__ emit for now #789 diff --git a/aiobotocore/__init__.py b/aiobotocore/__init__.py index 4345f0e2..4680261f 100644 --- a/aiobotocore/__init__.py +++ b/aiobotocore/__init__.py @@ -1,4 +1,4 @@ from .session import get_session, AioSession __all__ = ['get_session', 'AioSession'] -__version__ = '1.0.2' +__version__ = '1.0.3' diff --git a/aiobotocore/credentials.py b/aiobotocore/credentials.py index a5b15898..a1c530d6 100644 --- a/aiobotocore/credentials.py +++ b/aiobotocore/credentials.py @@ -425,7 +425,7 @@ async def _retrieve_credentials_using(self, credential_process): # We're not using shell=True, so we need to pass the # command and all arguments as a list. process_list = compat_shell_split(credential_process) - p = await self._popen(process_list, + p = await self._popen(*process_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = await p.communicate()
diff --git a/tests/botocore/test_credentials.py b/tests/botocore/test_credentials.py index ecbe17e8..d41c773a 100644 --- a/tests/botocore/test_credentials.py +++ b/tests/botocore/test_credentials.py @@ -931,7 +931,7 @@ def _f(profile_name='default', loaded_config=None, invoked_process=None): @pytest.mark.moto @pytest.mark.asyncio async def test_processprovider_retrieve_refereshable_creds(process_provider): - config = {'profiles': {'default': {'credential_process': 'my-process'}}} + config = {'profiles': {'default': {'credential_process': 'my-process /somefile'}}} invoked_process = mock.AsyncMock() stdout = json.dumps({ 'Version': 1, @@ -955,7 +955,7 @@ async def test_processprovider_retrieve_refereshable_creds(process_provider): assert creds.access_key == 'foo' assert creds.secret_key == 'bar' assert creds.token == 'baz' - popen_mock.assert_called_with(['my-process'], + popen_mock.assert_called_with('my-process', '/somefile', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Issue with handling credentials with credentials.process **Describe the bug** Credential loading fails when using [credential_process](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html) with the following exception. I am not sure if this is a bug asyncio? ``` File "/usr/local/lib/python3.7/contextlib.py", line 570, in enter_async_context result = await _cm_type.__aenter__(cm) File "/app/.venv/lib/python3.7/site-packages/aioboto3/session.py", line 195, in __aenter__ client = await self.client.__aenter__() File "/app/.venv/lib/python3.7/site-packages/aiobotocore/session.py", line 19, in __aenter__ self._client = await self._coro File "/app/.venv/lib/python3.7/site-packages/aiobotocore/session.py", line 92, in _create_client credentials = await self.get_credentials() File "/app/.venv/lib/python3.7/site-packages/aiobotocore/session.py", line 117, in get_credentials 'credential_provider').load_credentials()) File "/app/.venv/lib/python3.7/site-packages/aiobotocore/credentials.py", line 787, in load_credentials creds = await provider.load() File "/app/.venv/lib/python3.7/site-packages/aiobotocore/credentials.py", line 409, in load creds_dict = await self._retrieve_credentials_using(credential_process) File "/app/.venv/lib/python3.7/site-packages/aiobotocore/credentials.py", line 430, in _retrieve_credentials_using stderr=subprocess.PIPE) File "/usr/local/lib/python3.7/asyncio/subprocess.py", line 217, in create_subprocess_exec stderr=stderr, **kwds) File "/usr/local/lib/python3.7/asyncio/base_events.py", line 1529, in subprocess_exec f"program arguments must be a bytes or text string, " TypeError: program arguments must be a bytes or text string, not list ``` The exception occurs when a dynamodb client is being created, and credentials are loaded. I have the following two files ``` $ ll test total 16 -rw-r--r-- 1 mvalkonen xxx 573B Apr 8 18:40 credentials.json -rw-r--r-- 1 mvalkonen xxx 66B Apr 8 18:29 credentials.process ``` The `credentials.process`-file contains just the following ``` $ cat test/credentials.process [default] credential_process = cat /meta/aws-iam/credentials.json ``` The contents of `credentials.json` are valid, they work in my production environment with aiobotocore 0.11.1 I am using `aioboto3` and `aiohttp`. Running in a container environment, with a base ubuntu image and python 3.7.6. Will try to provide an isolated example of the issue. UPDATE: Seems like unpacking `args` to `self._popen` in https://github.com/aio-libs/aiobotocore/blob/master/aiobotocore/credentials.py#L428 will fix this. ```python p = await self._popen(*process_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` Not sure if this change should be done? **Checklist** - [x] I have reproduced in environment where `pip check` passes without errors - [ ] I have provided `pip freeze` results - [ ] I have provided sample code or detailed way to reproduce - [x] I have tried the same code in botocore to ensure this is an aiobotocore specific issue - [x] I have tried similar code in aiohttp to ensure this is is an aiobotocore specific issue - [x] I have checked the latest and older versions of aiobotocore/aiohttp/python to see if this is a regression / injection
ping @terrycain as this affects `aioboto3`. @mvalkon yeah, this one is my fault when porting said credentials class. I'll look into it.
2020-04-09T17:05:36
-1.0
karolzak/ipyplot
41
karolzak__ipyplot-41
['36']
3d32f3f90727671a64ac258b0b1241fa8fc9edcb
diff --git a/README.md b/README.md index 10a99ab..ee78adf 100644 --- a/README.md +++ b/README.md @@ -75,14 +75,45 @@ and use any of the available plotting functions shown below (notice execution ti #### Display a collection of images +```python +images = [ + "docs/example1-tabs.jpg", + "docs/example2-images.jpg", + "docs/example3-classes.jpg", +] +ipyplot.plot_images(images, max_images=30, img_width=150) +``` + ![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example2-images.jpg) #### Display class representations (first image for each unique label) +```python +images = [ + "docs/example1-tabs.jpg", + "docs/example2-images.jpg", + "docs/example3-classes.jpg", +] +labels = ['label1', 'label2', 'label3'] +ipyplot.plot_class_representations(images, labels, img_width=150) + +``` + ![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example3-classes.jpg) #### Display images in separate, interactive tabs for each unique class +```python +images = [ + "docs/example1-tabs.jpg", + "docs/example2-images.jpg", + "docs/example3-classes.jpg", +] +labels = ['class1', 'class2', 'class3'] +ipyplot.plot_class_tabs(images, labels, max_images_per_tab=10, img_width=150) + +``` + ![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example1-tabs.gif) To learn more about what you can do with IPyPlot go to [gear-images-examples.ipynb](https://github.com/karolzak/ipyplot/blob/master/notebooks/gear-images-examples.ipynb) notebook for more complex examples. \ No newline at end of file diff --git a/ipyplot/_html_helpers.py b/ipyplot/_html_helpers.py index 6841134..b5cee2e 100644 --- a/ipyplot/_html_helpers.py +++ b/ipyplot/_html_helpers.py @@ -5,6 +5,7 @@ from typing import Sequence +import os import numpy as np import shortuuid from numpy import str_ @@ -26,7 +27,8 @@ def _create_tabs( zoom_scale: float = 2.5, show_url: bool = True, force_b64: bool = False, - tabs_order: Sequence[str or int] = None): + tabs_order: Sequence[str or int] = None, + resize_image: bool = False): """ Generates HTML code required to display images in interactive tabs grouped by labels. For tabs ordering and filtering check out `tabs_order` param. @@ -66,6 +68,10 @@ def _create_tabs( By default, tabs will be sorted alphabetically based on provided labels. This param can be also used as a filtering mechanism - only labels provided in `tabs_order` param will be displayed as tabs. Defaults to None. + resize_image : bool, optional + If `True` it will resize image based on `width` parameter. + Useful when working with big images and notebooks getting too big in terms of file size. + Defaults to `False`. """ # NOQA E501 tab_layout_id = shortuuid.uuid() @@ -240,7 +246,8 @@ def _create_img( grid_style_uuid: str, custom_text: str = None, show_url: bool = True, - force_b64: bool = False): + force_b64: bool = False, + resize_image: bool = False): """Helper function to generate HTML code for displaying images along with corresponding texts. Parameters @@ -263,12 +270,18 @@ def _create_img( Do mind that using b64 conversion vs reading directly from filepath will be slower. You might need to set this to `True` in environments like Google colab. Defaults to False. + resize_image : bool, optional + If `True` it will resize image based on `width` parameter. + Useful when working with big images and notebooks getting too big in terms of file size. + Defaults to `False`. Returns ------- str Output HTML code. """ # NOQA E501 + if width is None: + raise ValueError("`img_width` can't be `None`!") img_uuid = shortuuid.uuid() @@ -277,8 +290,12 @@ def _create_img( img_html += '<h4 style="font-size: 12px; word-wrap: break-word;">%s</h4>' % str(custom_text) # NOQA E501 use_b64 = True - # if image is a string (URL) display its URL + if type(image) is str or type(image) is str_: + # if image url is local path convert to relative path + matches = ['http:', 'https:', 'ftp:', 'www.', 'data:', 'file:'] + if not any(image.lower().startswith(x) for x in matches): + image = os.path.relpath(image) if show_url: img_html += '<h4 style="font-size: 9px; padding-left: 10px; padding-right: 10px; width: 95%%; word-wrap: break-word; white-space: normal;">%s</h4>' % (image) # NOQA E501 if not force_b64: @@ -291,7 +308,9 @@ def _create_img( # if image is not a string it means its either PIL.Image or np.ndarray # that's why it's necessary to use conversion to b64 if use_b64: - img_html += '<img src="data:image/png;base64,%s"/>' % _img_to_base64(image, width) # NOQA E501 + img_html += '<img src="data:image/png;base64,%s"/>' % _img_to_base64( + image, + width if resize_image else None) html = """ <div class="ipyplot-placeholder-div-%(0)s"> @@ -318,7 +337,8 @@ def _create_imgs_grid( img_width: int = 150, zoom_scale: float = 2.5, show_url: bool = True, - force_b64: bool = False): + force_b64: bool = False, + resize_image: bool = False): """ Creates HTML code for displaying images provided in `images` param in grid-like layout. Check optional params for max number of images to plot, labels and custom texts to add to each image, image width and other options. @@ -353,6 +373,10 @@ def _create_imgs_grid( Do mind that using b64 conversion vs reading directly from filepath will be slower. You might need to set this to `True` in environments like Google colab. Defaults to False. + resize_image : bool, optional + If `True` it will resize image based on `width` parameter. + Useful when working with big images and notebooks getting too big in terms of file size. + Defaults to `False`. Returns ------- @@ -372,7 +396,8 @@ def _create_imgs_grid( x, width=img_width, label=y, grid_style_uuid=grid_style_uuid, custom_text=text, show_url=show_url, - force_b64=force_b64 + force_b64=force_b64, + resize_image=resize_image ) for x, y, text in zip( images[:max_images], labels[:max_images], diff --git a/ipyplot/_img_helpers.py b/ipyplot/_img_helpers.py index c8c642b..9fc2f4d 100644 --- a/ipyplot/_img_helpers.py +++ b/ipyplot/_img_helpers.py @@ -65,7 +65,7 @@ def _img_to_base64( image : str or numpy.str_ or numpy.ndarray or PIL.Image Input image can be either PIL.Image, numpy.ndarray or simply a string URL to local or external image file. target_width : int, optional - Target width (in pixels) to rescale to. + Target width (in pixels) to rescale to. If None image will not be rescaled. Defaults to None. Returns @@ -74,7 +74,7 @@ def _img_to_base64( Image as base64 string. """ # NOQA E501 # if statements to convert image to PIL.Image object - if type(image) is np.ndarray: + if isinstance(image, np.ndarray): if image.dtype in [np.float, np.float32, np.float64]: # if dtype is float and values range is from 0.0 to 1.0 # we need to normalize it to 0-255 range
diff --git a/tests/test_plotting.py b/tests/test_plotting.py index b64754b..236bf00 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -1,6 +1,7 @@ import sys from typing import Sequence +import os import numpy as np import pandas as pd import pytest @@ -49,6 +50,8 @@ (LOCAL_URLS_AS_PIL, LABELS[1], LABELS[1]), (LOCAL_URLS_AS_PIL, LABELS[2], LABELS[2]), (LOCAL_URLS_AS_PIL, LABELS[3], LABELS[3]), + # test case for abs to rel path convertion + ([os.path.abspath(pth) for pth in BASE_LOCAL_URLS], LABELS[1], LABELS[0]), ]
[Bug] Image resolution vs image width - blurry images when zoomed in nice little program, but what I don't understand is whether it is intentional that the images become blurry/compressed when selecting small `img_width`. for instance, see here (all the way to the bottom): https://www.phenopype.org/gallery/example_1/ I would want the thumbnails to be small enough to display in a grid inside the cell, but when people click on them I'd expect the original resolution, not the specified display width of 300. am I misunderstanding something here?
Hi @mluerig Thanks for your feedback. You're right, the way it is done right now, images are being resized under the hood (for compression purposes when converting to base64) according to `img_width` and it was ok at first but when I introduced zoom feature I didn't change this behavior. I think this can be fixed quite easily.
2022-03-14T14:32:58
-1.0
labgrid-project/labgrid
1,591
labgrid-project__labgrid-1591
['1570']
c609d2d7a88016f4610f396a22cd29a676180045
diff --git a/labgrid/remote/client.py b/labgrid/remote/client.py index 5ab4f0683..430509a1c 100755 --- a/labgrid/remote/client.py +++ b/labgrid/remote/client.py @@ -1425,7 +1425,7 @@ async def create_reservation(self): raise UserError(f"'{pair}' is not a valid filter (must contain a '=')") if not TAG_KEY.match(k): raise UserError(f"Key '{k}' in filter '{pair}' is invalid") - if not TAG_KEY.match(v): + if not TAG_VAL.match(v): raise UserError(f"Value '{v}' in filter '{pair}' is invalid") fltr[k] = v
diff --git a/tests/test_client.py b/tests/test_client.py index 5a1fc1a74..34297e7eb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -15,7 +15,7 @@ def place(coordinator): spawn.close() assert spawn.exitstatus == 0, spawn.before.strip() - with pexpect.spawn('python -m labgrid.remote.client -p test set-tags board=bar') as spawn: + with pexpect.spawn('python -m labgrid.remote.client -p test set-tags board=123board') as spawn: spawn.expect(pexpect.EOF) spawn.close() assert spawn.exitstatus == 0, spawn.before.strip() @@ -271,7 +271,7 @@ def test_remoteplace_target(place_acquire, tmpdir): t.await_resources(t.resources) remote_place = t.get_resource("RemotePlace") - assert remote_place.tags == {"board": "bar"} + assert remote_place.tags == {"board": "123board"} def test_remoteplace_target_without_env(request, place_acquire): from labgrid import Target @@ -279,7 +279,7 @@ def test_remoteplace_target_without_env(request, place_acquire): t = Target(request.node.name) remote_place = RemotePlace(t, name="test") - assert remote_place.tags == {"board": "bar"} + assert remote_place.tags == {"board": "123board"} def test_resource_conflict(place_acquire, tmpdir): with pexpect.spawn('python -m labgrid.remote.client -p test2 create') as spawn: @@ -303,7 +303,7 @@ def test_resource_conflict(place_acquire, tmpdir): assert spawn.exitstatus == 0, spawn.before.strip() def test_reservation(place_acquire, tmpdir): - with pexpect.spawn('python -m labgrid.remote.client reserve --shell board=bar name=test') as spawn: + with pexpect.spawn('python -m labgrid.remote.client reserve --shell board=123board name=test') as spawn: spawn.expect(pexpect.EOF) spawn.close() assert spawn.exitstatus == 0, spawn.before.strip() @@ -510,7 +510,7 @@ def test_reservation_custom_config(place, exporter, tmpdir): name: test """ ) - with pexpect.spawn(f'python -m labgrid.remote.client -c {p} reserve --wait --shell board=bar name=test') as spawn: + with pexpect.spawn(f'python -m labgrid.remote.client -c {p} reserve --wait --shell board=123board name=test') as spawn: spawn.expect(pexpect.EOF) spawn.close() assert spawn.exitstatus == 0, spawn.before.strip()
create a reservation - value is invalid When I tried to create a reservation: labgrid-client -p idan create labgrid-client -p idan set-tags my_tag=15 labgrid-client reserve my_tag=15 I got the following exception: labgrid-client: error: Value '15' in filter 'my_tag=15' is invalid I think in order to fix it we just need to replace TAG_KEY.match(v) with TAG_VAL.match(v) in the create_reservation function: /labgrid/remote/client.py ` TAG_KEY = re.compile(r"[a-z][a-z0-9_]+") TAG_VAL = re.compile(r"[a-z0-9_]?") .... .... async def create_reservation(self): prio = self.args.prio fltr = {} for pair in self.args.filters: try: k, v = pair.split("=") except ValueError: raise UserError(f"'{pair}' is not a valid filter (must contain a '=')") if not TAG_KEY.match(k): raise UserError(f"Key '{k}' in filter '{pair}' is invalid") if not TAG_KEY.match(v): raise UserError(f"Value '{v}' in filter '{pair}' is invalid") fltr[k] = v `
2025-02-02T08:53:46
-1.0
aio-libs/aiobotocore
683
aio-libs__aiobotocore-683
['682']
3725599ca470ddc4cfdbf6127968593ebd56b7d7
diff --git a/CHANGES.txt b/CHANGES.txt index 30400b29..fed48ccd 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,8 +1,9 @@ Changes ------- -0.10.2 (2018-XX-XX) +0.10.2 (2018-02-11) ^^^^^^^^^^^^^^^^^^^ +* Fix response-received emitted event #682 0.10.1 (2019-02-08) ^^^^^^^^^^^^^^^^^^^ diff --git a/aiobotocore/__init__.py b/aiobotocore/__init__.py index 1888841a..61a1da3a 100644 --- a/aiobotocore/__init__.py +++ b/aiobotocore/__init__.py @@ -1,4 +1,4 @@ from .session import get_session, AioSession __all__ = ['get_session', 'AioSession'] -__version__ = '0.10.2.a0' +__version__ = '0.10.2' diff --git a/aiobotocore/endpoint.py b/aiobotocore/endpoint.py index 23cab648..77a0c0a5 100644 --- a/aiobotocore/endpoint.py +++ b/aiobotocore/endpoint.py @@ -290,7 +290,7 @@ async def _get_response(self, request, operation_model, context): if success_response is not None: http_response, parsed_response = success_response kwargs_to_emit['parsed_response'] = parsed_response - kwargs_to_emit['response_dict'] = convert_to_response_dict( + kwargs_to_emit['response_dict'] = await convert_to_response_dict( http_response, operation_model) service_id = operation_model.service_model.service_id.hyphenize() self._event_emitter.emit(
diff --git a/tests/test_monitor.py b/tests/test_monitor.py new file mode 100644 index 00000000..eb05dc4a --- /dev/null +++ b/tests/test_monitor.py @@ -0,0 +1,23 @@ +import pytest + +from aiobotocore.session import AioSession + + [email protected] [email protected] +async def test_monitor_response_received(session: AioSession, s3_client): + # Basic smoke test to ensure we can talk to s3. + handler_kwargs = {} + + def handler(**kwargs): + nonlocal handler_kwargs + handler_kwargs = kwargs + + s3_client.meta.events.register('response-received.s3.ListBuckets', handler) + result = await s3_client.list_buckets() + # Can't really assume anything about whether or not they have buckets, + # but we can assume something about the structure of the response. + actual_keys = sorted(list(result.keys())) + assert actual_keys == ['Buckets', 'Owner', 'ResponseMetadata'] + + assert handler_kwargs['response_dict']['status_code'] == 200
'convert_to_response_dict' was never awaited in aiobotocore/endpoint.py:293 **Describe the bug** 'convert_to_response_dict' was never awaited in aiobotocore/endpoint.py:293 I get this warning: RuntimeWarning: coroutine 'convert_to_response_dict' was never awaited **Additional context** Assuming it is just a typo. Warning goes away when I added await. aiobotocore/endpoint.py:293 ```py kwargs_to_emit['response_dict'] = await convert_to_response_dict(http_response, operation_model) ```
mind a testcase so we can ensure this doesn't happen again? figured it out
2019-02-12T03:42:14
-1.0
karolzak/ipyplot
51
karolzak__ipyplot-51
['50', '50']
5518b7fd53a45ef0f5bfd0f581d6c52a0e29b8df
diff --git a/ipyplot/_img_helpers.py b/ipyplot/_img_helpers.py index 9fc2f4d..6f69ccb 100644 --- a/ipyplot/_img_helpers.py +++ b/ipyplot/_img_helpers.py @@ -75,7 +75,7 @@ def _img_to_base64( """ # NOQA E501 # if statements to convert image to PIL.Image object if isinstance(image, np.ndarray): - if image.dtype in [np.float, np.float32, np.float64]: + if image.dtype in [np.float32, np.float64]: # if dtype is float and values range is from 0.0 to 1.0 # we need to normalize it to 0-255 range image = image * 255 if image.max() <= 1.0 else image
diff --git a/tests/test_plotting.py b/tests/test_plotting.py index 236bf00..554ec4e 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -45,7 +45,7 @@ (np.asarray(BASE_NP_IMGS), LABELS[1], LABELS[0]), (np.asarray(BASE_INTERNET_URLS), LABELS[1], LABELS[0]), (np.asarray(BASE_LOCAL_URLS), LABELS[1], LABELS[0]), - (np.asarray(BASE_NP_IMGS, dtype=np.float) / 255, LABELS[1], LABELS[0]), + (np.asarray(BASE_NP_IMGS, dtype=np.float32) / 255, LABELS[1], LABELS[0]), (LOCAL_URLS_AS_PIL, LABELS[0], LABELS[0]), (LOCAL_URLS_AS_PIL, LABELS[1], LABELS[1]), (LOCAL_URLS_AS_PIL, LABELS[2], LABELS[2]),
numpy 1.20+ does't have `np.float` When trying basic: `ipyplot.plot_images([np.array([1,2])])` I get: `AttributeError: module 'numpy' has no attribute 'float'` This is due to [this](https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations) depreciation. numpy 1.20+ does't have `np.float` When trying basic: `ipyplot.plot_images([np.array([1,2])])` I get: `AttributeError: module 'numpy' has no attribute 'float'` This is due to [this](https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations) depreciation.
2023-01-12T02:37:57
-1.0
karolzak/ipyplot
4
karolzak__ipyplot-4
['8']
485c54bcdeb1e9bfc27a3de18a1d9eeb369a68b1
diff --git a/.bumpversion.cfg b/.bumpversion.cfg new file mode 100644 index 0000000..ab32af2 --- /dev/null +++ b/.bumpversion.cfg @@ -0,0 +1,8 @@ +[bumpversion] +current_version = 1.1.0 +commit = True +tag = True + +[bumpversion:file:setup.py] + +[bumpversion:file:ipyplot/__init__.py] diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..648f6f6 --- /dev/null +++ b/.github/workflows/python-package.yml @@ -0,0 +1,39 @@ +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: CI Build + +on: + push: + branches: [ master ] + pull_request: + +jobs: + build: + + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python-version: [3.5, 3.6, 3.7, 3.8] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + pip install -r requirements.txt + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test with pytest + run: | + pytest diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..0978e49 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,31 @@ +# This workflows will upload a Python Package using Twine when a release is created +# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries + +name: Upload Python Package + +on: + release: + types: [created] + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build and publish + env: + TWINE_USERNAME: ${{ secrets.PYPIUSERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPIPW }} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.gitignore b/.gitignore index 5ac8001..b4542da 100644 --- a/.gitignore +++ b/.gitignore @@ -129,4 +129,9 @@ dmypy.json .pyre/ .vscode -datasets/* \ No newline at end of file +datasets/* +notebooks/*.jpg +notebooks/*.jpeg +notebooks/*.tif +notebooks/*.tiff +notebooks/*.png \ No newline at end of file diff --git a/README.md b/README.md index 818c309..10a99ab 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Build](https://github.com/karolzak/ipyplot/workflows/Python%20package/badge.svg)](https://github.com/karolzak/ipyplot/actions?query=workflow%3A%22Python+package%22) +[![Build](https://github.com/karolzak/ipyplot/workflows/CI%20Build/badge.svg)](https://github.com/karolzak/ipyplot/actions?query=workflow%3A%22CI+Build%22) [![PyPI - version](https://img.shields.io/pypi/v/ipyplot.svg "PyPI version")](https://pypi.org/project/ipyplot/) [![Downloads](https://pepy.tech/badge/ipyplot)](https://pepy.tech/project/ipyplot) [![Downloads/Month](https://pepy.tech/badge/ipyplot/month)](https://pepy.tech/project/ipyplot/month) @@ -8,49 +8,57 @@ [![Twitter URL](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2karolzak%2Fipyplot)](http://twitter.com/share?text=IPyPlot%20-%20fast%20and%20effortless%20way%20to%20display%20huge%20numbers%20of%20images%20in%20Python%20notebooks&url=https://github.com/karolzak/ipyplot/&hashtags=python,computervision,imageclassification,deeplearning,ML,AI) [![LinkedIn URL](https://raw.githubusercontent.com/karolzak/boxdetect/master/images/linkedin_share4.png)](http://www.linkedin.com/shareArticle?mini=true&url=https://github.com/karolzak/ipyplot&title=IPyPlot%20python%20package) -**IPyPlot** is a small python package offering fast and efficient plotting of images inside Jupyter Notebooks cells. It's using IPython with HTML for faster, richer and more interactive way of displaying big number of images. +**IPyPlot** is a small python package offering fast and efficient plotting of images inside Python Notebooks cells. It's using IPython with HTML for faster, richer and more interactive way of displaying big numbers of images. -Displaying huge numbers of images with Python in Notebooks always was a big pain for me as I always used `matplotlib` for that task and never have I even considered if it can be done faster, easier or more efficiently. +![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example1-tabs.gif) + +Displaying big numbers of images with Python in Notebooks always was a big pain for me as I always used `matplotlib` for that task and never have I even considered if it can be done faster, easier or more efficiently. Especially in one of my recent projects I had to work with a vast number of document images in a very interactive way which led me to forever rerunning notebook cells and waiting for countless seconds for `matplotlib` to do it's thing.. -My frustration grew up to a point were I couldn't stand it anymore and started to look for other options.. -Best solution I found involved using `IPython.display` function in connection with simple HTML. Using that approach I built a simple python package called **IPyPlot** which finally helped me cure my frustration and saved a lot of my time +My frustration grew up to the point were I couldn't stand it anymore and started to look for other options.. +Best solution I found involved using `IPython` package in connection with simple HTML. Using that approach I built this simple python package called **IPyPlot** which finally helped me cure my frustration and saved a lot of my time. ### Features: - [x] Easy, fast and efficient plotting of images in python within notebooks -- [x] Plotting functions (see [examples section](#Usage-examples) to learn more: - - [x] `plot_images` - simply plots all the images in a grid-like manner - - [x] `plot_class_representations` - similar to `plot_images` but displays only a single image per class (based on provided labels collection) - - [x] `plot_class_tabs` - plots images in a grid-like manner in a separate tab for each class based on provided label +- [x] Plotting functions (see [examples section](#Usage-examples) to learn more): + - [x] `plot_images` - simply plots all the images in a grid-like layout + - [x] `plot_class_representations` - similar to `plot_images` but displays only the first image for each label/class (based on provided labels collection) + - [x] `plot_class_tabs` - plots images in a grid-like manner in a separate tab for each label/class based on provided labels +- [x] Supported image formats: + - [x] Sequence of local storage URLs, e.g. `[your/dir/img1.jpg]` + - [x] Sequence of remote URLs, e.g. `[http://yourimages.com/img1.jpg]` + - [x] Sequence of `PIL.Image` objects + - [x] Sequence of images as `numpy.ndarray` objects + - [x] Supported sequence types: `list`, `numpy.ndarray`, `pandas.Series` +- [x] Misc features: + - [x] `custom_texts` param to display additional texts like confidence score or some other information for each image + - [x] `force_b64` flag to force conversion of images from URLs to base64 format + - [x] click on image to enlarge + - [x] control number of displayed images and their width through `max_images` and `img_width` params + - [x] "show html" button which reveals the HTML code used to generate plots + - [x] option to set specific order of labels/tabs, filter them or ignore some of the labels - [x] Supported notebook platforms: - [x] Jupyter - [x] Google Colab - [x] Azure Notebooks - [x] Kaggle Notebooks -- [x] Supported image formats: - - [x] Array of local storage URLs, e.g. `[your/dir/img1.jpg]` - - [x] Array of remote URLs, e.g. `[http://yourimages.com/img1.jpg]` - - [x] Array of `PIL.Image` objects - - [x] Array of images as `numpy.ndarray` objects -- [x] Misc: - - [x] `force_b64` flag to force conversion of images from URLs to base64 format ## Getting Started -Checkout the [examples below](#Usage-examples) and -[gear-images-examples.ipynb](https://github.com/karolzak/ipyplot/blob/master/notebooks/gear-images-examples.ipynb) notebook which holds end to end examples for using **IPyPlot**. +To start using IPyPlot, see [examples below](#Usage-examples) or go to +[gear-images-examples.ipynb](https://github.com/karolzak/ipyplot/blob/master/notebooks/gear-images-examples.ipynb) notebook which takes you through most of the scenarios and options possible with **IPyPlot**. ## Installation -**IPyPlot** can be installed directly from this repo using `pip`: +**IPyPlot** can be installed through [PyPI](https://pypi.org/project/ipyplot/): ``` -pip install git+https://github.com/karolzak/ipyplot +pip install ipyplot ``` -or through [PyPI](https://pypi.org/project/ipyplot/) +or directly from this repo using `pip`: ``` -pip install ipyplot +pip install git+https://github.com/karolzak/ipyplot ``` ## Usage examples @@ -62,17 +70,19 @@ To start working with `IPyPlot` you need to simply import it like this: import ipyplot ``` and use any of the available plotting functions shown below (notice execution times). -`images` - should be a numpy array of either `string` (image file paths), `PIL.Image` objects or `numpy.array` objects representing images -`labels` - should be a numpy array of `string` - -#### Display images in separate, interactive tabs for each class - -![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example1-tabs.gif) +- **images** - should be a sequence of either `string` (local or remote image file URLs), `PIL.Image` objects or `numpy.ndarray` objects representing images +- **labels** - should be a sequence of `string` or `int` #### Display a collection of images ![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example2-images.jpg) -#### Display class representations (first image for each class) +#### Display class representations (first image for each unique label) ![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example3-classes.jpg) + +#### Display images in separate, interactive tabs for each unique class + +![](https://raw.githubusercontent.com/karolzak/ipyplot/master/docs/example1-tabs.gif) + +To learn more about what you can do with IPyPlot go to [gear-images-examples.ipynb](https://github.com/karolzak/ipyplot/blob/master/notebooks/gear-images-examples.ipynb) notebook for more complex examples. \ No newline at end of file diff --git a/docs/example1-tabs.gif b/docs/example1-tabs.gif index 3ab3c5b..cf8132b 100644 Binary files a/docs/example1-tabs.gif and b/docs/example1-tabs.gif differ diff --git a/ipyplot/__init__.py b/ipyplot/__init__.py index 19cd8c4..786eefb 100644 --- a/ipyplot/__init__.py +++ b/ipyplot/__init__.py @@ -1,15 +1,28 @@ -import sys +""" +IPyPlot package gives you a fast and easy way of displaying images in python notebooks environment. +It leverages HTML and IPython package under the hood which makes it very fast and efficient in displaying images. +It works best for images as string URLs to local/external files but it can also be used with numpy.ndarray or PIL.Image image formats as well. +To use it, you just need to add `import ipyplot` to your code and use one of the public functions available from top level module. +Example: +``` +import ipyplot -if 'google.colab' in sys.modules: - print(""" - WARNING! Google Colab Environment detected! - You might encounter issues while running in Google Colab environment. - If images are not displaying properly please try setting `base_64` param to `True`. - """) +ipyplot.plot_images(images=images, labels=labels, ..) +``` +""" # NOQA E501 -from .plotting import ( - plot_class_representations, plot_class_tabs, - plot_images -) +import sys as _sys -import ipyplot.img_helpers +from ._plotting import plot_images, plot_class_tabs, plot_class_representations + +__name__ = "IPyPlot" +__version__ = "1.1.0" + +if 'google.colab' in _sys.modules: # pragma: no cover + print( + """ + WARNING! Google Colab Environment detected! + You might encounter issues while running in Google Colab environment. + If images are not displaying properly please try setting `base_64` param to `True`. + """ # NOQA E501 + ) diff --git a/ipyplot/_html_helpers.py b/ipyplot/_html_helpers.py new file mode 100644 index 0000000..adc8803 --- /dev/null +++ b/ipyplot/_html_helpers.py @@ -0,0 +1,461 @@ +""" +This module contains helper functions for generating HTML code +required for displaying images, grid/tab layout and general styling. +""" + +from typing import Sequence + +import numpy as np +import shortuuid +from numpy import str_ + +from ._img_helpers import _img_to_base64 + +try: + from IPython.display import display, HTML +except Exception: # pragma: no cover + raise Exception('IPython not detected. Plotting without IPython is not possible') # NOQA E501 + + +def _create_tabs( + images: Sequence[object], + labels: Sequence[str or int], + custom_texts: Sequence[str] = None, + max_imgs_per_tab: int = 30, + img_width: int = 150, + zoom_scale: float = 2.5, + force_b64: bool = False, + tabs_order: Sequence[str or int] = None): + """ + Generates HTML code required to display images in interactive tabs grouped by labels. + For tabs ordering and filtering check out `tabs_order` param. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int] + List of classes/labels for images to be grouped by. + Must be same length as `images`. + custom_texts : Sequence[str], optional + List of custom strings to be drawn above each image. + Must be same length as `images`, by default `None`. + max_imgs_per_tab : int, optional + How many samples from each label/class to display in a tab + Defaults to 30. + img_width : int, optional + Image width in px, by default 150 + zoom_scale : float, optional + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + Defaults to 2.5. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + tabs_order : Sequence[str or int], optional + Order of tabs based on provided list of classes/labels. + By default, tabs will be sorted alphabetically based on provided labels. + This param can be also used as a filtering mechanism - only labels provided in `tabs_order` param will be displayed as tabs. + Defaults to None. + """ # NOQA E501 + + tab_layout_id = shortuuid.uuid() + + # if `tabs_order` is None use sorted unique values from `labels` + if tabs_order is None: + tabs_order = np.unique(labels) + + # assure same length for images, labels and custom_texts sequences + assert(len(labels) == len(images)) + if custom_texts is not None: + assert(len(custom_texts) == len(images)) + + html = '<div>' + tab_ids = [shortuuid.uuid() for label in tabs_order] + style_html = """ + <style> + input.ipyplot-tab-%(0)s { + display: none; + } + input.ipyplot-tab-%(0)s + label.ipyplot-tab-label-%(0)s { + border: 1px solid #999; + background: #EEE; + padding: 4px 12px; + border-radius: 4px 4px 0 0; + position: relative; + top: 1px; + } + input.ipyplot-tab-%(0)s:checked + label.ipyplot-tab-label-%(0)s { + background: #FFF; + border-bottom: 1px solid transparent; + } + input.ipyplot-tab-%(0)s ~ .tab { + border-top: 1px solid #999; + padding: 12px; + } + + input.ipyplot-tab-%(0)s ~ .tab { + display: none + } + """ % {'0': tab_layout_id} + + for i in tab_ids: + style_html += '#tab%s:checked ~ .tab.content%s,' % (i, i) + style_html = style_html[:-1] + '{ display: block; }</style>' + + html += style_html + + # sets the first tab to active/selected state + active_tab = True + for i, label in zip(tab_ids, tabs_order): + # define radio type tab buttons for each label + html += '<input class="ipyplot-tab-%s" type="radio" name="tabs-%s" id="tab%s"%s/>' % (tab_layout_id, tab_layout_id, i, ' checked ' if active_tab else '') # NOQA E501 + html += '<label class="ipyplot-tab-label-%s" for="tab%s">%s</label>' % (tab_layout_id, i, label) # NOQA E501 + active_tab = False + + # sets the first tab to active/selected state + active_tab = True + for i, label in zip(tab_ids, tabs_order): + # define content for each tab + html += '<div class="tab content%s">' % i # NOQA E501 + active_tab = False + + tab_imgs_mask = labels == label + html += _create_imgs_grid( + images=images[tab_imgs_mask], + labels=list(range(0, max_imgs_per_tab)), + max_images=max_imgs_per_tab, + img_width=img_width, + zoom_scale=zoom_scale, + custom_texts=custom_texts[tab_imgs_mask] if custom_texts is not None else None, # NOQA E501 + force_b64=force_b64) + + html += '</div>' + + html += '</div>' + + return html + + +def _create_html_viewer( + html: str): + """Creates HTML code for HTML previewer. + + Parameters + ---------- + html : str + HTML content to be displayed in HTML viewer. + + Returns + ------- + str + HTML code for HTML previewer control. + """ + + html_viewer_id = shortuuid.uuid() + html_viewer = """ + <style> + #ipyplot-html-viewer-toggle-%(1)s { + position: absolute; + top: -9999px; + left: -9999px; + visibility: hidden; + } + + #ipyplot-html-viewer-label-%(1)s { + position: relative; + display: inline-block; + cursor: pointer; + color: blue; + text-decoration: underline; + } + + #ipyplot-html-viewer-textarea-%(1)s { + background: lightgrey; + width: 100%%; + height: 0px; + display: none; + } + + #ipyplot-html-viewer-toggle-%(1)s:checked ~ #ipyplot-html-viewer-textarea-%(1)s { + height: 200px; + display: block; + } + + #ipyplot-html-viewer-toggle-%(1)s:checked + #ipyplot-html-viewer-label-%(1)s:after { + content: "hide html"; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: white; + cursor: pointer; + color: blue; + text-decoration: underline; + } + </style> + <div> + <input type="checkbox" id="ipyplot-html-viewer-toggle-%(1)s"> + <label id="ipyplot-html-viewer-label-%(1)s" for="ipyplot-html-viewer-toggle-%(1)s">show html</label> + <textarea id="ipyplot-html-viewer-textarea-%(1)s" readonly> + %(0)s + </textarea> + </div> + """ % {'0': html, '1': html_viewer_id} # NOQA E501 + return html_viewer + + +def _display_html(html: str): + """Simply displays provided HTML string using IPython.display function. + + Parameters + ---------- + html : str + HTML code to be displayed. + + Returns + ------- + handle: DisplayHandle + Returns a handle on updatable displays + """ + display(HTML(_create_html_viewer(html))) + return display(HTML(html)) + + +def _create_img( + image: str or object, + label: str or int, + width: int, + grid_style_uuid: str, + custom_text: str = None, + force_b64: bool = False): + """Helper function to generate HTML code for displaying images along with corresponding texts. + + Parameters + ---------- + image : str or object + Image object or string URL to local/external image file. + label : str or int + Label/class string to be displayed above the image. + width : int + Image width value in pixels. + grid_style_uuid : str + Unique identifier used to connect image style with specific style definition. + custom_text : str, optional + Additional text to be displayed above the image but below the label name. + Defaults to None. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + + Returns + ------- + str + Output HTML code. + """ # NOQA E501 + + img_uuid = shortuuid.uuid() + + img_html = "" + if custom_text is not None: + img_html += '<h4 style="font-size: 12px; word-wrap: break-word;">%s</h4>' % str(custom_text) # NOQA E501 + + use_b64 = True + # if image is a string (URL) display its URL + if type(image) is str or type(image) is str_: + img_html += '<h4 style="font-size: 9px; padding-left: 10px; padding-right: 10px; width: 95%%; word-wrap: break-word; white-space: normal;">%s</h4>' % (image) # NOQA E501 + if not force_b64: + use_b64 = False + img_html += '<img src="%s"/>' % image + elif "http" in image: + print("WARNING: Current implementation doesn't allow to use 'force_b64=True' with images as remote URLs. Ignoring 'force_b64' flag") # NOQA E501 + use_b64 = False + + # if image is not a string it means its either PIL.Image or np.ndarray + # that's why it's necessary to use conversion to b64 + if use_b64: + img_html += '<img src="data:image/png;base64,%s"/>' % _img_to_base64(image, width) # NOQA E501 + + html = """ + <div class="ipyplot-placeholder-div-%(0)s"> + <div id="ipyplot-content-div-%(0)s-%(1)s" class="ipyplot-content-div-%(0)s"> + <h4 style="font-size: 12px; word-wrap: break-word;">%(2)s</h4> + %(3)s + <a href="#!"> + <span class="ipyplot-img-close"/> + </a> + <a href="#ipyplot-content-div-%(0)s-%(1)s"> + <span class="ipyplot-img-expand"/> + </a> + </div> + </div> + """ % {'0': grid_style_uuid, '1': img_uuid, '2': label, '3': img_html} # NOQA E501 + return html + + +def _create_imgs_grid( + images: Sequence[object], + labels: Sequence[str or int], + custom_texts: Sequence[str] = None, + max_images: int = 30, + img_width: int = 150, + zoom_scale: float = 2.5, + force_b64: bool = False): + """ + Creates HTML code for displaying images provided in `images` param in grid-like layout. + Check optional params for max number of images to plot, labels and custom texts to add to each image, image width and other options. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int] + List of classes/labels for images to be grouped by. + Must be same length as `images`. + custom_texts : Sequence[str], optional + List of custom strings to be drawn above each image. + Must be same length as `images`, by default `None`. + max_images : int, optional + How many images to display (takes first N images). + Defaults to 30. + img_width : int, optional + Image width in px, by default 150 + zoom_scale : float, optional + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + Defaults to 2.5. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + + Returns + ------- + str + Output HTML code. + """ # NOQA E501 + + if custom_texts is None: + custom_texts = [None for _ in range(len(images))] + + # create code with style definitions + html, grid_style_uuid = _get_default_style(img_width, zoom_scale) + + html += '<div id="ipyplot-imgs-container-div-%s">' % grid_style_uuid + html += ''.join([ + _create_img( + x, width=img_width, label=y, + grid_style_uuid=grid_style_uuid, + custom_text=text, force_b64=force_b64 + ) + for x, y, text in zip( + images[:max_images], labels[:max_images], + custom_texts[:max_images]) + ]) + html += '</div>' + return html + + +def _get_default_style(img_width: int, zoom_scale: float): + """Creates HTML code with default style definitions required for elements to be properly displayed + + Parameters + ---------- + img_width : int + Image width in pixels. + zoom_scale : float + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + + Returns + ------- + str + Output HTML code. + """ # NOQA E501 + style_uuid = shortuuid.uuid() + html = """ + <style> + #ipyplot-imgs-container-div-%(0)s { + width: 100%%; + height: 100%%; + margin: 0%%; + overflow: auto; + position: relative; + overflow-y: scroll; + } + + div.ipyplot-placeholder-div-%(0)s { + width: %(1)spx; + display: inline-block; + margin: 3px; + position: relative; + } + + div.ipyplot-content-div-%(0)s { + width: %(1)spx; + background: white; + display: inline-block; + vertical-align: top; + text-align: center; + position: relative; + border: 2px solid #ddd; + top: 0; + left: 0; + } + + div.ipyplot-content-div-%(0)s span.ipyplot-img-close { + display: none; + } + + div.ipyplot-content-div-%(0)s span { + width: 100%%; + height: 100%%; + position: absolute; + top: 0; + left: 0; + } + + div.ipyplot-content-div-%(0)s img { + width: %(1)spx; + } + + div.ipyplot-content-div-%(0)s span.ipyplot-img-close:hover { + cursor: zoom-out; + } + div.ipyplot-content-div-%(0)s span.ipyplot-img-expand:hover { + cursor: zoom-in; + } + + div[id^=ipyplot-content-div-%(0)s]:target { + transform: scale(%(2)s); + transform-origin: left top; + z-index: 5000; + top: 0; + left: 0; + position: absolute; + } + + div[id^=ipyplot-content-div-%(0)s]:target span.ipyplot-img-close { + display: block; + } + + div[id^=ipyplot-content-div-%(0)s]:target span.ipyplot-img-expand { + display: none; + } + </style> + """ % {'0': style_uuid, '1': img_width, '2': zoom_scale} + return html, style_uuid diff --git a/ipyplot/_img_helpers.py b/ipyplot/_img_helpers.py new file mode 100644 index 0000000..c8c642b --- /dev/null +++ b/ipyplot/_img_helpers.py @@ -0,0 +1,96 @@ +""" +Helper methods for working with images. +""" + +import base64 +import io + +import numpy as np +from numpy import str_ +import PIL +from PIL import Image + + +def _rescale_to_width( + img: Image, + target_width: int): + """Helper function to rescale image to `target_width`. + + Parameters + ---------- + img : PIL.Image + Input image object to be rescaled. + target_width : int + Target width (in pixels) for rescaling. + + Returns + ------- + PIL.Image + Rescaled image object + """ + w, h = img.size + rescaled_img = img.resize(_scale_wh_by_target_width(w, h, target_width)) + return rescaled_img + + +def _scale_wh_by_target_width(w: int, h: int, target_width: int): + """Helper functions for scaling width and height based on target width. + + Parameters + ---------- + w : int + Width in pixels. + h : int + Heights in pixels. + target_width : int + Target width (in pixels) for rescaling. + + Returns + ------- + (int, int) + Returns rescaled width and height as a tuple (w, h). + """ + scale = target_width / w + return int(w * scale), int(h * scale) + + +def _img_to_base64( + image: str or str_ or np.ndarray or PIL.Image, + target_width: int = None): + """Converts image to base64 string. + Use `target_width` param to rescale the image to specific width - keeps original size by default. + + Parameters + ---------- + image : str or numpy.str_ or numpy.ndarray or PIL.Image + Input image can be either PIL.Image, numpy.ndarray or simply a string URL to local or external image file. + target_width : int, optional + Target width (in pixels) to rescale to. + Defaults to None. + + Returns + ------- + str + Image as base64 string. + """ # NOQA E501 + # if statements to convert image to PIL.Image object + if type(image) is np.ndarray: + if image.dtype in [np.float, np.float32, np.float64]: + # if dtype is float and values range is from 0.0 to 1.0 + # we need to normalize it to 0-255 range + image = image * 255 if image.max() <= 1.0 else image + image = PIL.Image.fromarray(image.astype(np.uint8)) + else: + image = PIL.Image.fromarray(image) + elif type(image) is str or type(image) is str_: + image = PIL.Image.open(image) + + # rescale image based on target_width + if target_width: + image = _rescale_to_width(image, target_width) + # save image object to bytes stream + output = io.BytesIO() + image.save(output, format='PNG') + # encode bytes as base64 string + b64 = str(base64.b64encode(output.getvalue()).decode('utf-8')) + return b64 diff --git a/ipyplot/_plotting.py b/ipyplot/_plotting.py new file mode 100644 index 0000000..e060c1f --- /dev/null +++ b/ipyplot/_plotting.py @@ -0,0 +1,211 @@ +""" +This is the main module of IPyPlot package. +It contains all the user-facing functions for displaying images in Python Notebooks. +""" # NOQA E501 + +import numpy as _np +from typing import Sequence + +from ._html_helpers import ( + _display_html, _create_tabs, _create_imgs_grid) +from ._utils import _get_class_representations, _seq2arr + + +def plot_class_tabs( + images: Sequence[object], + labels: Sequence[str or int], + custom_texts: Sequence[str] = None, + max_imgs_per_tab: int = 30, + img_width: int = 150, + zoom_scale: float = 2.5, + force_b64: bool = False, + tabs_order: Sequence[str or int] = None): + """ + Efficient and convenient way of displaying images in interactive tabs grouped by labels. + For tabs ordering and filtering check out `tabs_order` param. + This function (same as the whole IPyPlot package) is using IPython and HTML under the hood. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int] + List of classes/labels for images to be grouped by. + Must be same length as `images`. + custom_texts : Sequence[str], optional + List of custom strings to be drawn above each image. + Must be same length as `images`, by default `None`. + max_imgs_per_tab : int, optional + How many samples from each label/class to display in a tab + Defaults to 30. + img_width : int, optional + Image width in px, by default 150 + zoom_scale : float, optional + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + Defaults to 2.5. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + tabs_order : Sequence[str or int], optional + Order of tabs based on provided list of classes/labels. + By default, tabs will be sorted alphabetically based on provided labels. + This param can be also used as a filtering mechanism - only labels provided in `tabs_order` param will be displayed as tabs. + Defaults to None. + """ # NOQA E501 + assert(len(images) == len(labels)) + + # convert to numpy.ndarray for further processing + images = _seq2arr(images) + labels = _np.asarray(labels) + tabs_order = _np.asarray(tabs_order) if tabs_order is not None else tabs_order # NOQA E501 + custom_texts = _np.asarray(custom_texts) if custom_texts is not None else custom_texts # NOQA E501 + + # run html helper function to generate html content + html = _create_tabs( + images=images, + labels=labels, + custom_texts=custom_texts, + max_imgs_per_tab=max_imgs_per_tab, + img_width=img_width, + zoom_scale=zoom_scale, + force_b64=force_b64, + tabs_order=tabs_order) + + _display_html(html) + + +def plot_images( + images: Sequence[object], + labels: Sequence[str or int] = None, + custom_texts: Sequence[str] = None, + max_images: int = 30, + img_width: int = 150, + zoom_scale: float = 2.5, + force_b64: bool = False): + """ + Simply displays images provided in `images` param in grid-like layout. + Check optional params for max number of images to plot, labels and custom texts to add to each image, image width and other options. + This function (same as the whole IPyPlot package) is using IPython and HTML under the hood. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int], optional + List of classes/labels for images to be grouped by. + Must be same length as `images`. + Defaults to None. + custom_texts : Sequence[str], optional + List of custom strings to be drawn above each image. + Must be same length as `images`, by default `None`. + max_images : int, optional + How many images to display (takes first N images). + Defaults to 30. + img_width : int, optional + Image width in px, by default 150 + zoom_scale : float, optional + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + Defaults to 2.5. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + """ # NOQA E501 + + images = _seq2arr(images) + + if labels is None: + labels = list(range(0, len(images))) + else: + labels = _np.asarray(labels) + + custom_texts = _np.asarray(custom_texts) if custom_texts is not None else custom_texts # NOQA E501 + + html = _create_imgs_grid( + images=images, + labels=labels, + custom_texts=custom_texts, + max_images=max_images, + img_width=img_width, + zoom_scale=zoom_scale, + force_b64=force_b64) + + _display_html(html) + + +def plot_class_representations( + images: Sequence[object], + labels: Sequence[str or int], + img_width: int = 150, + zoom_scale: float = 2.5, + force_b64: bool = False, + ignore_labels: Sequence[str or int] = None, + labels_order: Sequence[str or int] = None): + """ + Displays single image (first occurence for each class) for each label/class in grid-like layout. + Check optional params for labels filtering, ignoring and ordering, image width and other options. + This function (same as the whole IPyPlot package) is using IPython and HTML under the hood. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int] + List of classes/labels for images to be grouped by. + Must be same length as `images`. + img_width : int, optional + Image width in px, by default 150 + zoom_scale : float, optional + Scale for zoom-in-on-click feature. + Best to keep between 1.0~5.0. + Defaults to 2.5. + force_b64 : bool, optional + You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. + Do mind that using b64 conversion vs reading directly from filepath will be slower. + You might need to set this to `True` in environments like Google colab. + Defaults to False. + ignore_labels : Sequence[str or int], optional + List of labels to ignore. + Defaults to None. + labels_order : Sequence[str or int], optional + Defines order of labels based on provided list of classes/labels. + By default, images will be sorted alphabetically based on provided label. + This param can be also used as a filtering mechanism - only images for labels provided in `labels_order` param will be displayed. + Defaults to None. + """ # NOQA E501 + + assert(len(images) == len(labels)) + + images = _seq2arr(images) + + labels = _np.asarray(labels) + ignore_labels = _np.asarray(ignore_labels) if ignore_labels is not None else ignore_labels # NOQA E501 + labels_order = _np.asarray(labels_order) if labels_order is not None else labels_order # NOQA E501 + + images, labels = _get_class_representations( + images, labels, ignore_labels, labels_order) + + plot_images( + images=images, + labels=labels, + max_images=len(images), + img_width=img_width, + zoom_scale=zoom_scale, + force_b64=force_b64) diff --git a/ipyplot/_utils.py b/ipyplot/_utils.py new file mode 100644 index 0000000..56760c8 --- /dev/null +++ b/ipyplot/_utils.py @@ -0,0 +1,97 @@ +""" +Misc utils for IPyPlot package. +""" + +from typing import Sequence + +import numpy as np +from PIL import Image + + +def _get_class_representations( + images: Sequence[object], + labels: Sequence[str or int], + ignore_labels: Sequence[str or int] = None, + labels_order: Sequence[str or int] = None): + """Returns a list of images (and labels) representing first occurance of each label/class type. + Check optional params for labels ignoring and ordering. + For labels filtering refer to `labels_order` param. + + Parameters + ---------- + images : Sequence[object] + List of images to be displayed in tabs layout. + Currently supports images in the following formats: + - str (local/remote URL) + - PIL.Image + - numpy.ndarray + labels : Sequence[str or int] + List of classes/labels for images to be grouped by. + Must be same length as `images`. + ignore_labels : Sequence[str or int], optional + List of labels to ignore. + Defaults to None. + labels_order : Sequence[str or int], optional + Defines order of labels based on provided list of classes/labels. + By default, images will be sorted alphabetically based on provided label. + This param can be also used as a filtering mechanism - only images for labels provided in `labels_order` param will be displayed. + Defaults to None. + + Returns + ------- + (numpy.ndarray, numpy.ndarray) + Returns a tuple containing an array of images along with associated labels (out_images, out_labels). + """ # NOQA E501 + + # convert everything to numpy.ndarray + # required for further filtering and ordering operations + images = np.asarray(images) + labels = np.asarray(labels) + ignore_labels = np.asarray(ignore_labels) if ignore_labels is not None else ignore_labels # NOQA E501 + labels_order = np.asarray(labels_order) if labels_order is not None else labels_order # NOQA E501 + + # ignore labels based on provided list + if ignore_labels is not None: + not_labeled_mask = np.isin(labels, ignore_labels) + labels = labels[~not_labeled_mask] + images = images[~not_labeled_mask] + + if labels_order is not None: + # create idices mask based on ordered labels provided + labels_order_mask = [ + np.where(labels == label)[0][0] + for label in labels_order + if len(np.where(labels == label)[0]) > 0 + ] + # note that this will not only order labels and images + # but it will filter them as well + out_images = images[labels_order_mask] + out_labels = labels[labels_order_mask] + else: + # if no filtering/ordering was provided + # use uniques from labels list as indices mask + uniques = np.unique(labels, return_index=True) + out_labels = uniques[0] + out_images = images[uniques[1]] + + return out_images, out_labels + + +def _seq2arr(seq: Sequence[str or int or object]): + """Convert sequence to numpy.ndarray. + + Parameters + ---------- + seq : Sequence[str or int or object] + Input sequence of elements + + Returns + ------- + numpy.ndarray + Array of elements + """ + # this is a hack to make the code work with PIL images + if issubclass(type(seq[0]), Image.Image): + return np.asarray(seq, dtype=type(seq[0])) + else: + return np.asarray(seq) diff --git a/ipyplot/img_helpers.py b/ipyplot/img_helpers.py deleted file mode 100644 index 6377f79..0000000 --- a/ipyplot/img_helpers.py +++ /dev/null @@ -1,20 +0,0 @@ -def resize_with_aspect_ratio(img, max_size=1000): - """Helper function to resize image against the longer edge - - Args: - img (PIL.Image): - Image object to be resized - max_size (int, optional): - Max size of the longer edge in pixels. - Defaults to 2800. - - Returns: - PIL.Image: - Resized image object - """ - w, h = img.size - aspect_ratio = min(max_size/w, max_size/h) - resized_img = img.resize( - (int(w * aspect_ratio), int(h * aspect_ratio)) - ) - return resized_img diff --git a/ipyplot/plotting.py b/ipyplot/plotting.py deleted file mode 100644 index e48b3a9..0000000 --- a/ipyplot/plotting.py +++ /dev/null @@ -1,242 +0,0 @@ -import base64 -import io -import uuid - -import numpy as np -from numpy import str_ -from PIL import Image - -from .img_helpers import resize_with_aspect_ratio - -try: - from IPython.display import display, HTML -except Exception as e: - raise Exception('IPython not detected. Plotting without IPython is not possible') # NOQA E501 - - -def plot_class_tabs( - images, - labels, - max_imgs_per_tab=10, - img_width=220, - force_b64=False): - """ - Efficient and convenient way of displaying images in interactive tabs - grouped by labels/clusters. - It's using IPython.display function and HTML under the hood - - Args: - images (numpy.ndarray): - Numpy array of image file paths or PIL.Image objects - labels (numpy.ndarray): - Numpy array of corresponding classes - max_imgs_per_tab (int, optional): - How many samples from each cluster/class to display. - Defaults to 50. - img_width (int, optional): - Image width. - Adjust to change the number of images per row. - Defaults to 220. - force_b64 (boolean, optional): - You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. # NOQA E501 - Do mind that using b64 conversion vs reading directly from filepath will be slower. # NOQA E501 - You might need to set this to `True` in environments like Google colab. - Defaults to False. - """ - assert(len(images) == len(labels)) - assert(type(images) is np.ndarray) - assert(type(labels) is np.ndarray) - assert(type(max_imgs_per_tab) is int) - assert(type(img_width) is int) - - html = _create_tabs_html( - images, labels, max_imgs_per_tab, img_width, force_b64=force_b64) - - _display(html) - - -def plot_images( - images, - labels=None, - max_images=30, - img_width=300, - force_b64=False): - """ - Displays images based on the provided paths - - Args: - images (array): - Array of coresponding file paths. - labels (array, optional): - Array of labels/cluster names. - If None it will just assign numbers going from 0 - Defaults to None. - max_images (int, optional): - Max number of images to display. - Defaults to 100. - img_width (int, optional): - Width of the displayed image. - Defaults to 300. - force_b64 (boolean, optional): - You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. # NOQA E501 - Do mind that using b64 conversion vs reading directly from filepath will be slower. # NOQA E501 - You might need to set this to `True` in environments like Google colab. - Defaults to False. - """ - assert(type(max_images) is int) - assert(type(img_width) is int) - - if labels is None: - labels = list(range(0, len(images))) - html = _create_imgs_list_html( - images, labels, max_images, img_width, force_b64=force_b64) - - _display(html) - - -def plot_class_representations( - images, labels, - ignore_list=['-1', 'unknown'], - img_width=150, - force_b64=False): - """ - Function used to display first image from each cluster/class - - Args: - images (array): - Array of image file paths or PIL.Image objects. - labels (array): - Array of labels/classes names. - ignore_list (list, optional): - List of classes to ignore when plotting. - Defaults to ['-1', 'unknown']. - img_width (int, optional): - Width of the displayed image. - Defaults to 150. - force_b64 (boolean, optional): - You can force conversion of images to base64 instead of reading them directly from filepaths with HTML. # NOQA E501 - Do mind that using b64 conversion vs reading directly from filepath will be slower. # NOQA E501 - You might need to set this to `True` in environments like Google colab. - Defaults to False. - """ - assert(len(images) == len(labels)) - assert(type(ignore_list) is list or ignore_list is None) - assert(type(img_width) is int) - - uniques = np.unique(labels, return_index=True) - labels = uniques[0] - not_labeled_mask = np.isin(labels, ignore_list) - labels = labels[~not_labeled_mask] - idices = uniques[1][~not_labeled_mask] - - group = [] - for img_path in images[idices]: - group.append(img_path) - - plot_images( - group, - labels=labels, - max_images=len(group), - img_width=img_width, - force_b64=force_b64) - -def _create_tabs_html(images, labels, max_imgs_per_tab, img_width, force_b64=False): - # html = '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>' # NOQA E501 - html = '<div>' - - unique_labels = np.unique(labels) - tab_ids = [uuid.uuid4() for label in unique_labels] - style_html = """ - <style> - input { display: none; } - input + label { display: inline-block } - - input + label { - border: 1px solid #999; - background: #EEE; - padding: 4px 12px; - border-radius: 4px 4px 0 0; - position: relative; - top: 1px; - } - input:checked + label { - background: #FFF; - border-bottom: 1px solid transparent; - } - input ~ .tab { - border-top: 1px solid #999; - padding: 12px; - } - - input ~ .tab { display: none } - """ - - for i in tab_ids: - style_html += '#tab%s:checked ~ .tab.content%s,' % (i, i) - style_html = style_html[:-1] + '{ display: block; }</style>' - - html += style_html - - active_tab = True - for i, label in zip(tab_ids, unique_labels): - html += '<input type="radio" name="tabs" id="tab%s"%s/>' % (i, ' checked ' if active_tab else '') # NOQA E501 - html += '<label for="tab%s">%s</label>' % (i, label) - active_tab = False - - active_tab = True - for i, label in zip(tab_ids, unique_labels): - html += '<div class="tab content%s">' % i # NOQA E501 - active_tab = False - - html += ''.join([ - _create_img_html(x, img_width, label=y, force_b64=force_b64) - for y, x in enumerate(images[labels == label][:max_imgs_per_tab]) - ]) - html += '</div>' - - html += '</div>' - - return html - - -def _display(html): - return display(HTML(html)) - - -def _img_to_base64(image, max_size): - if type(image) is np.ndarray: - image = Image.fromarray(image) - elif type(image) is str or type(image) is str_: - image = Image.open(image) - output = io.BytesIO() - image = resize_with_aspect_ratio(image, max_size) - image.save(output, format='PNG') - b64 = str(base64.b64encode(output.getvalue()).decode('utf-8')) - return b64 - - -def _create_img_html(image, width, label, force_b64=False): - html = ( - '<div style="display: inline-block; width: %spx; vertical-align: top; text-align: center;">' % (width + 20) + - '<h4 style="font-size: 12px">%s</h4>' % label - ) - use_b64 = True - if type(image) is str or type(image) is str_: - html += '<h4 style="font-size: 9px; padding-left: 10px; padding-right: 10px; width: 90%%; word-wrap: break-word; white-space: normal;">%s</h4>' % (image) # NOQA E501 - if not force_b64: - use_b64 = False - html += '<img src="%s" style="margin: 1px; width: %spx; border: 2px solid #ddd;"/>' % (image, width) # NOQA E501 - - if use_b64: - html += '<img src="data:image/png;base64,%s" style="margin: 1px; width: %spx; border: 2px solid #ddd;"/>' % ( - _img_to_base64(image, width*2), width) # NOQA E501 - - return html + '</div>' - - -def _create_imgs_list_html(images, labels, max_images, img_width, force_b64=False): - html = ''.join([ - _create_img_html(x, img_width, label=y, force_b64=force_b64) - for x, y in zip(images[:max_images], labels[:max_images]) - ]) - return html diff --git a/notebooks/gear-images-examples.ipynb b/notebooks/gear-images-examples.ipynb index 3be4e44..75b8006 100644 --- a/notebooks/gear-images-examples.ipynb +++ b/notebooks/gear-images-examples.ipynb @@ -7,19 +7,35 @@ "### Table of content:\n", "1. [Imports](#1.-Imports) \n", "2. [Load the dataset](#2.-Load-the-dataset) \n", - "3. [Plotting images](#3.-Plotting-images) \n", - " 3.1. [Plotting using image paths](#3.1-Plotting-using-image-paths) \n", - " 3.2. [Plotting using PIL.Image objects](#3.2-Plotting-images-using-PIL.Image-objects) \n", - " 3.3. [Plotting using numpy.ndarray objects](#3.3-Plotting-using-numpy.ndarray-objects) " + "3. [Basic usage](#3.-Basic-usage) \n", + " 3.1. [Display images list](#3.1-Display-images-list) \n", + " 3.2. [Display class representations](#3.2-Display-class-representations) \n", + " 3.3. [Display images in class tabs layout](#3.3-Display-images-in-class-tabs-layout) \n", + "4. [Different sequence and data types](#4.-Different-sequence-and-data-types) \n", + " 4.1. [Sequence types](#4.1-Sequence-types) \n", + " 4.2. [Image types](#4.2-Image-types) \n", + "5. [Order, filter, ignore labels](#5.-Order,-filter,-ignore-labels) \n", + " 5.1. [Ordering](#5.1-Ordering) \n", + " 5.2. [Filtering](#5.2-Filtering) \n", + " 5.3. [Ignoring labels](#5.3-Ignoring-labels) \n", + "6. [Force convert images to base64 strings](#6.-Force-convert-images-to-base64-strings) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 1. Imports\n", + "[[back to the top](#Table-of-content:)]" ] }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:56:38.851008Z", - "start_time": "2020-04-29T12:56:38.804222Z" + "end_time": "2020-10-20T19:37:54.551532Z", + "start_time": "2020-10-20T19:37:54.475232Z" } }, "outputs": [], @@ -30,65 +46,37 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:57:41.027309Z", - "start_time": "2020-04-29T12:57:33.114314Z" + "end_time": "2020-10-20T19:37:54.878197Z", + "start_time": "2020-10-20T19:37:54.554841Z" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Collecting git+https://github.com/karolzak/ipyplot\n", - " Cloning https://github.com/karolzak/ipyplot to c:\\users\\karol\\appdata\\local\\temp\\pip-req-build-st50f8r7\n", - "Building wheels for collected packages: ipyplot\n", - " Building wheel for ipyplot (setup.py): started\n", - " Building wheel for ipyplot (setup.py): finished with status 'done'\n", - " Created wheel for ipyplot: filename=ipyplot-0.0.1-cp36-none-any.whl size=4690 sha256=5689ca05cc6ffabbdf1c5904050cfbc6bd4451f41b37487df9837f73972bfc14\n", - " Stored in directory: C:\\Users\\karol\\AppData\\Local\\Temp\\pip-ephem-wheel-cache-xqnjxgp7\\wheels\\1e\\7c\\d8\\88b9fa77fd2c5ed1fc1599eced6e121d76891a3c008e91df25\n", - "Successfully built ipyplot\n", - "Installing collected packages: ipyplot\n", - "Successfully installed ipyplot-0.0.1\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " Running command git clone -q https://github.com/karolzak/ipyplot 'C:\\Users\\karol\\AppData\\Local\\Temp\\pip-req-build-st50f8r7'\n" - ] - } - ], + "outputs": [], "source": [ + "import sys\n", "try:\n", + " sys.path.append('../')\n", " import ipyplot\n", "except:\n", - " import sys\n", - "# sys.path.append('../')\n", - " ! {sys.executable} -m pip install git+https://github.com/karolzak/ipyplot\n", + " ! {sys.executable} -m pip install ipyplot\n", " import ipyplot" ] }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:57:48.627031Z", - "start_time": "2020-04-29T12:57:48.080305Z" + "end_time": "2020-10-20T19:37:54.990587Z", + "start_time": "2020-10-20T19:37:54.881599Z" } }, "outputs": [], "source": [ "import glob\n", "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "from numpy import random\n", - "from PIL import Image\n", "import urllib.request\n", "import zipfile" ] @@ -97,33 +85,36 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## 2. Load the dataset\n", + "# 2. Load the dataset\n", "[[back to the top](#Table-of-content:)]" ] }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:58:14.357662Z", - "start_time": "2020-04-29T12:57:59.510207Z" + "end_time": "2020-10-20T19:37:55.191374Z", + "start_time": "2020-10-20T19:37:55.002104Z" } }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Downloading the data into `datasets` folder..\n", - "Done!\n" - ] - } - ], + "outputs": [], "source": [ "datasets_dir = '../datasets/'\n", - "zip_filename = 'gear_images.zip'\n", - "\n", + "zip_filename = 'gear_images.zip'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T19:38:09.162618Z", + "start_time": "2020-10-20T19:37:55.200372Z" + } + }, + "outputs": [], + "source": [ "print('Downloading the data into `datasets` folder..')\n", "url = 'https://privdatastorage.blob.core.windows.net/github/ipyplot/gear_images.zip'\n", "urllib.request.urlretrieve(url, datasets_dir + zip_filename)\n", @@ -132,11 +123,11 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:58:16.023769Z", - "start_time": "2020-04-29T12:58:14.359625Z" + "end_time": "2020-10-20T19:38:10.866286Z", + "start_time": "2020-10-20T19:38:09.170566Z" } }, "outputs": [], @@ -148,49 +139,69 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:58:24.050687Z", - "start_time": "2020-04-29T12:58:23.976609Z" + "end_time": "2020-10-20T19:38:11.069937Z", + "start_time": "2020-10-20T19:38:10.871004Z" } }, "outputs": [], "source": [ "images = glob.glob(datasets_dir + 'gear_images' + '/**/*.*')\n", - "images = [image.replace('\\\\', '/') for image in images]\n", - "images = np.asarray(images, dtype=str) # conversion to nummpy is pretty important here" + "images = [image.replace('\\\\', '/') for image in images]" ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:58:24.928270Z", - "start_time": "2020-04-29T12:58:24.870390Z" + "end_time": "2020-10-20T19:38:11.163494Z", + "start_time": "2020-10-20T19:38:11.075409Z" } }, "outputs": [], "source": [ - "labels = [image.split('/')[-2] for image in images]\n", - "labels = np.asarray(labels, dtype=str) # conversion to nummpy is pretty important here" + "labels = [image.split('/')[-2] for image in images]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## 3. Plotting images\n", - "### 3.1 Plotting using image paths\n", - "[[back to the top](#Table-of-content:)]" + "# 3. Basic usage\n", + "[[back to the top](#Table-of-content:)]\n", + "## 3.1 Display images list\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Displays images based on provided list. \n", + "max_images param limits the number of displayed images (takes top n images only)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T19:38:11.226414Z", + "start_time": "2020-10-20T19:38:11.165605Z" + }, + "scrolled": false + }, + "outputs": [], + "source": [ + "ipyplot.plot_images(images, max_images=10, img_width=150)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display class representations (first image from each class)" + "## 3.2 Display class representations\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Displays first image for each class/label" ] }, { @@ -198,8 +209,8 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:02.748325Z", - "start_time": "2020-04-29T12:59:02.678885Z" + "end_time": "2020-10-20T19:38:11.318696Z", + "start_time": "2020-10-20T19:38:11.228450Z" }, "scrolled": false }, @@ -212,9 +223,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display a collection of images \n", - "Displays images based on provided list. \n", - "max_images param limits the number of displayed images (takes top n images only)" + "## 3.3 Display images in class tabs layout\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Displays top N images (max_imgs_per_tab) in separate tab for each label/class (based on provided labels list)" ] }, { @@ -222,20 +234,34 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:04.669312Z", - "start_time": "2020-04-29T12:59:04.594009Z" + "end_time": "2020-10-20T19:38:11.428142Z", + "start_time": "2020-10-20T19:38:11.324448Z" } }, "outputs": [], "source": [ - "ipyplot.plot_images(images[labels == 'tents'], max_images=30, img_width=150)" + "ipyplot.plot_class_tabs(images, labels, max_imgs_per_tab=5, img_width=150)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display top N images (max_imgs_per_tab) in separate tab for each class (based on provided labels)" + "# 4. Different sequence and data types \n", + "[[back to the top](#Table-of-content:)]\n", + "## 4.1 Sequence types \n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "\n", + "IPyPlot currently support most common sequence types in python including:\n", + "- list\n", + "- numpy.ndarray\n", + "- pandas.Series\n", + "\n", + "In previous examples we were using `images` object to store our images which was of simple python type `list`.\n", + "Now let's try using different sequence types.\n", + "\n", + "### Using numpy.ndarray as images sequence" ] }, { @@ -243,22 +269,25 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:13.091954Z", - "start_time": "2020-04-29T12:59:13.021359Z" + "end_time": "2020-10-20T19:38:11.506705Z", + "start_time": "2020-10-20T19:38:11.430737Z" }, "scrolled": false }, "outputs": [], "source": [ - "ipyplot.plot_class_tabs(images, labels, max_imgs_per_tab=15, img_width=150)" + "import numpy as np\n", + "\n", + "images_np = np.asarray(images)\n", + "\n", + "ipyplot.plot_images(images_np, max_images=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### 3.2 Plotting images using PIL.Image objects\n", - "[[back to the top](#Table-of-content:)]" + "### Using pandas.Series as images sequence" ] }, { @@ -266,21 +295,44 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:21.930580Z", - "start_time": "2020-04-29T12:59:14.754318Z" - } + "end_time": "2020-10-20T19:38:13.350900Z", + "start_time": "2020-10-20T19:38:11.509631Z" + }, + "scrolled": false }, "outputs": [], "source": [ - "images = [Image.open(image) for image in images]\n", - "images = np.asarray(images, dtype=np.object)" + "import pandas as pd\n", + "\n", + "images_df = pd.DataFrame()\n", + "images_df['images'] = images\n", + "images_df['labels'] = labels\n", + "\n", + "ipyplot.plot_images(images_df['images'], max_images=5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4.2 Image types \n", + "\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "IPyPlot supports passing in images using one of the following types:\n", + "- local image file URL\n", + "- external/remote image file URL\n", + "- PIL.Image objects\n", + "- numpy.ndarray objects\n", + "\n", + "In previous examples we used local image files URLs so now we will focus more on other options." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display class representations (first image from each class)" + "### Displaying images using images as PIL.Image objects" ] }, { @@ -288,23 +340,24 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:22.197274Z", - "start_time": "2020-04-29T12:59:21.932221Z" - }, - "scrolled": true + "end_time": "2020-10-20T19:38:31.876537Z", + "start_time": "2020-10-20T19:38:13.353901Z" + } }, "outputs": [], "source": [ - "ipyplot.plot_class_representations(images, labels, img_width=150)" + "from PIL import Image\n", + "\n", + "images_pil = [Image.open(image) for image in images]\n", + "\n", + "ipyplot.plot_images(images_pil, max_images=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display a collection of images \n", - "Displays images based on provided list. \n", - "max_images param limits the number of displayed images (takes top n images only)" + "### Displaying images using images as numpy.ndarray objects" ] }, { @@ -312,20 +365,33 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:22.533432Z", - "start_time": "2020-04-29T12:59:22.200264Z" + "end_time": "2020-10-20T19:38:35.710371Z", + "start_time": "2020-10-20T19:38:31.880538Z" } }, "outputs": [], "source": [ - "ipyplot.plot_images(images[labels == 'tents'], max_images=20, img_width=150)" + "import numpy as np\n", + "\n", + "images_np = [np.asarray(image) for image in images_pil]\n", + "\n", + "ipyplot.plot_images(images_np, max_images=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Display top N images (max_imgs_per_tab) in separate tab for each class (based on provided labels)" + "# 5. Order, filter, ignore labels\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "By default labels or tabs are sorted alphabetically. Some of the plotting functions allow you to perform custom ordering, filtering or ignoring (not displaying) labels.\n", + "\n", + "## 5.1 Ordering\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Ordering can be performed:\n", + "- **using `tabs_order` param for `plot_class_tabs` function**" ] }, { @@ -333,22 +399,37 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:25.596312Z", - "start_time": "2020-04-29T12:59:22.537429Z" + "end_time": "2020-10-20T19:38:35.788586Z", + "start_time": "2020-10-20T19:38:35.712376Z" + } + }, + "outputs": [], + "source": [ + "labels_list_ordered = [\"helmets\", \"boots\", \"insulated_jackets\", \"hardshell_jackets\", \"axes\", \"tents\"]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T19:38:35.978605Z", + "start_time": "2020-10-20T19:38:35.794069Z" }, "scrolled": false }, "outputs": [], "source": [ - "ipyplot.plot_class_tabs(images, labels, max_imgs_per_tab=15, img_width=150)" + "ipyplot.plot_class_tabs(\n", + " images, labels, max_imgs_per_tab=5, tabs_order=labels_list_ordered\n", + ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### 3.3 Plotting using numpy.ndarray objects \n", - "[[back to the top](#Table-of-content:)]" + "- **using `labels_order` param for `plot_class_represenations` function**" ] }, { @@ -356,22 +437,31 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:28.326062Z", - "start_time": "2020-04-29T12:59:25.600311Z" + "end_time": "2020-10-20T19:38:36.181026Z", + "start_time": "2020-10-20T19:38:35.986558Z" } }, "outputs": [], "source": [ - "images = [np.asarray(image) for image in images]\n", - "images = np.asarray(images)\n", - "images[0].shape" + "ipyplot.plot_class_representations(\n", + " images, labels, labels_order=labels_list_ordered\n", + ")" ] }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T13:07:07.491970Z", + "start_time": "2020-10-20T13:07:07.222723Z" + } + }, "source": [ - "#### Display class representations (first image from each class)" + "## 5.2 Filtering \n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Filtering tabs/labels can be achieved the same way as with [ordering](#5.1-Ordering). \n", + "Just create a list of labels/tabs that you want to display and pass it into `tabs_order` or `labels_order` params." ] }, { @@ -379,23 +469,29 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:28.616915Z", - "start_time": "2020-04-29T12:59:28.329030Z" - }, - "scrolled": false + "end_time": "2020-10-20T19:38:36.414300Z", + "start_time": "2020-10-20T19:38:36.191859Z" + } }, "outputs": [], "source": [ - "ipyplot.plot_class_representations(images, labels, img_width=150)" + "labels_list_filtered = [\"insulated_jackets\", \"hardshell_jackets\"]" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T19:38:36.632884Z", + "start_time": "2020-10-20T19:38:36.422002Z" + } + }, + "outputs": [], "source": [ - "#### Display a collection of images \n", - "Displays images based on provided list. \n", - "max_images param limits the number of displayed images (takes top n images only)" + "ipyplot.plot_class_tabs(\n", + " images, labels, max_imgs_per_tab=5, tabs_order=labels_list_filtered\n", + ")" ] }, { @@ -403,20 +499,30 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:28.950211Z", - "start_time": "2020-04-29T12:59:28.618878Z" + "end_time": "2020-10-20T19:38:36.790950Z", + "start_time": "2020-10-20T19:38:36.637573Z" } }, "outputs": [], "source": [ - "ipyplot.plot_images(images[labels == 'tents'], max_images=20, img_width=150)" + "ipyplot.plot_class_representations(\n", + " images, labels, labels_order=labels_list_filtered\n", + ")" ] }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T13:07:07.495900Z", + "start_time": "2020-10-20T13:07:07.324Z" + } + }, "source": [ - "#### Display top N images (max_imgs_per_tab) in separate tab for each class (based on provided labels)" + "## 5.3 Ignoring labels\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "If you want to prevent displaying images for specific labels just use `ignore_labels` param as show below" ] }, { @@ -424,29 +530,45 @@ "execution_count": null, "metadata": { "ExecuteTime": { - "end_time": "2020-04-29T12:59:32.022266Z", - "start_time": "2020-04-29T12:59:28.953205Z" + "end_time": "2020-10-20T19:38:37.022119Z", + "start_time": "2020-10-20T19:38:36.798582Z" }, - "scrolled": false + "scrolled": true }, "outputs": [], "source": [ - "ipyplot.plot_class_tabs(images, labels, max_imgs_per_tab=15, img_width=150)" + "ignore_list = [\"boots\", \"axes\", \"helmets\", \"insulated_jackets\", \"hardshell_jackets\", \"tents\"]\n", + "\n", + "ipyplot.plot_class_representations(\n", + " images, labels, img_width=100, ignore_labels=ignore_list\n", + ")" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], - "source": [] + "source": [ + "# 6. Force convert images to base64 strings\n", + "[[back to the top](#Table-of-content:)]\n", + "\n", + "Since IPyPlot is using HTML under the hood, by design all the images provided as URL strings are just injected into HTML `img` elements as they are. For all the other image types (numpy.ndarray, PIL.Image) IPyPlot is performing a conversion to base64 strings which are then injected into HTML `img` elements. \n", + "If for any reason you would like to force that behavior for URL strings as well you need to set `force_b64` flag to `True`. \n", + "This param is available for all the plotting functions." + ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "ExecuteTime": { + "end_time": "2020-10-20T19:38:37.274612Z", + "start_time": "2020-10-20T19:38:37.030968Z" + } + }, "outputs": [], - "source": [] + "source": [ + "ipyplot.plot_images(images, max_images=5, force_b64=True)" + ] } ], "metadata": { @@ -470,4 +592,4 @@ }, "nbformat": 4, "nbformat_minor": 2 -} \ No newline at end of file +} diff --git a/requirements.txt b/requirements.txt index b274cc5..472e51f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,8 @@ IPython Numpy -pillow \ No newline at end of file +pillow +bump2version +pytest +pytest-cov +shortuuid +pandas \ No newline at end of file diff --git a/setup.py b/setup.py index c45552e..c7da86d 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ setup( name="ipyplot", - version="1.0.5", + version="1.1.0", description="Simple package that leverages IPython and HTML for more efficient, reach and interactive plotting of images in Jupyter Notebooks", long_description=long_description, long_description_content_type="text/markdown", # This is important! @@ -14,11 +14,25 @@ author="Karol Zak", author_email="[email protected]", license="MIT", + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Intended Audience :: Education', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Software Development :: Libraries', + 'Topic :: Software Development :: Libraries :: Python Modules' + ], packages=find_packages(), zip_safe=False, install_requires=[ "IPython", "numpy", - "pillow" + "pillow", + "shortuuid" ], )
diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..a6cf16c --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +junit_family=xunit1 +addopts = --cov ipyplot --cov-report html \ No newline at end of file diff --git a/tests/test_plotting.py b/tests/test_plotting.py new file mode 100644 index 0000000..b64754b --- /dev/null +++ b/tests/test_plotting.py @@ -0,0 +1,111 @@ +import sys +from typing import Sequence + +import numpy as np +import pandas as pd +import pytest +from IPython.display import HTML +from PIL import Image + +sys.path.append(".") +sys.path.append("../.") +import ipyplot + + +BASE_NP_IMGS = list(np.asarray( + np.random.randint(0, 255, (3, 128, 128, 3)), dtype=np.uint8)) + +BASE_INTERNET_URLS = [ + "https://raw.githubusercontent.com/karolzak/boxdetect/master/images/checkbox-example.jpg", # NOQA E501 + "https://raw.githubusercontent.com/karolzak/boxdetect/master/images/checkboxes-details.jpg", # NOQA E501 + "https://raw.githubusercontent.com/karolzak/boxdetect/master/images/example1.png", # NOQA E501 +] + +BASE_LOCAL_URLS = [ + "docs/example1-tabs.jpg", + "docs/example2-images.jpg", + "docs/example3-classes.jpg", +] + +LOCAL_URLS_AS_PIL = list([Image.open(url) for url in BASE_LOCAL_URLS]) + +LABELS = [ + None, + ['a', 'b', 'a'], + np.asarray(['a', 'b', 'a']), + pd.Series(['a', 'b', 'a']) +] + +TEST_DATA = [ + # (imgs, labels, custom_texts) + (LOCAL_URLS_AS_PIL, LABELS[1], LABELS[0]), + (BASE_NP_IMGS, LABELS[1], LABELS[0]), + (pd.Series(BASE_NP_IMGS), LABELS[1], LABELS[0]), + (np.asarray(BASE_NP_IMGS), LABELS[1], LABELS[0]), + (np.asarray(BASE_INTERNET_URLS), LABELS[1], LABELS[0]), + (np.asarray(BASE_LOCAL_URLS), LABELS[1], LABELS[0]), + (np.asarray(BASE_NP_IMGS, dtype=np.float) / 255, LABELS[1], LABELS[0]), + (LOCAL_URLS_AS_PIL, LABELS[0], LABELS[0]), + (LOCAL_URLS_AS_PIL, LABELS[1], LABELS[1]), + (LOCAL_URLS_AS_PIL, LABELS[2], LABELS[2]), + (LOCAL_URLS_AS_PIL, LABELS[3], LABELS[3]), +] + + [email protected](params=[True, False]) +def test_true_false(request): + return request.param + + [email protected]( + "imgs, labels, custom_texts", + TEST_DATA) +def test_plot_images( + capsys, test_true_false, imgs, labels, custom_texts): + ipyplot.plot_images( + imgs, + labels=labels, + custom_texts=custom_texts, + max_images=30, + img_width=300, + force_b64=test_true_false) + captured = capsys.readouterr() + if test_true_false and type(imgs[0]) is np.str_ and "http" in imgs[0]: + assert("Ignoring 'force_b64' flag" in captured.out) + + assert(str(HTML).split("'")[1] in captured.out) + + [email protected]( + "imgs, labels, custom_texts", + TEST_DATA) +def test_plot_class_tabs( + capsys, test_true_false, imgs, labels, custom_texts): + ipyplot.plot_class_tabs( + imgs, + labels=labels if labels is not None else LABELS[1], + custom_texts=custom_texts, + img_width=300, + force_b64=test_true_false) + captured = capsys.readouterr() + if test_true_false and type(imgs[0]) is np.str_ and "http" in imgs[0]: + assert("Ignoring 'force_b64' flag" in captured.out) + + assert(str(HTML).split("'")[1] in captured.out) + + [email protected]( + "imgs, labels, custom_texts", + TEST_DATA) +def test_plot_class_representations( + capsys, test_true_false, imgs, labels, custom_texts): + ipyplot.plot_class_representations( + imgs, + labels=labels if labels is not None else LABELS[1], + img_width=300, + force_b64=test_true_false) + captured = capsys.readouterr() + if test_true_false and type(imgs[0]) is np.str_ and "http" in imgs[0]: + assert("Ignoring 'force_b64' flag" in captured.out) + + assert(str(HTML).split("'")[1] in captured.out) diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..03674d1 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,106 @@ +import sys + +import numpy as np +import pytest +import pandas as pd + +sys.path.append(".") +sys.path.append("../.") +from ipyplot._utils import _get_class_representations + + +TEST_OUT_IMAGES = ['a', 'b', 'c'] +TEST_DATA = [ + # images, labels, + # ignore_list, labels_order, + # out_images, out_labels + + # data type tests + ( + ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'], + None, None, + TEST_OUT_IMAGES, ['1', '2', '3'] + ), + ( + np.array(['c', 'b', 'a', 'd']), np.array(['3', '2', '1', '3']), + None, None, + TEST_OUT_IMAGES, np.array(['1', '2', '3']) + ), + ( + pd.Series(['c', 'b', 'a', 'd']), pd.Series(['3', '2', '1', '3']), + None, None, + TEST_OUT_IMAGES, pd.Series(['1', '2', '3']) + ), + ( + ['c', 'b', 'a', 'd'], [3, 2, 1, 3], + None, None, + TEST_OUT_IMAGES, [1, 2, 3] + ), + # ignore_list tests + ( + ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'], + ['4'], None, + TEST_OUT_IMAGES, ['1', '2', '3'] + ), + ( + ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3], + [4], None, + TEST_OUT_IMAGES, [1, 2, 3] + ), + # labels_order tests + ( + ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'], + None, ['2', '1', '3'], + ['b', 'a', 'c'], ['2', '1', '3'] + ), + ( + ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'], + None, ['2', '1', '4', '3'], + ['b', 'a', 'c'], ['2', '1', '3'] + ), + ( + ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3], + None, [2, 1, 3], + ['b', 'a', 'c'], [2, 1, 3] + ), + ( + ['c', 'b', 'a', 'd'], [3, 2, 1, 3], + None, [2, 1, 4, 3], + ['b', 'a', 'c'], [2, 1, 3] + ), + # labels_order + ignore_list tests + ( + ['e', 'c', 'b', 'a', 'd'], ['4', '3', '2', '1', '3'], + ['1'], ['2', '1', '3'], + ['b', 'c'], ['2', '3'] + ), + ( + ['c', 'b', 'a', 'd'], ['3', '2', '1', '3'], + ['1'], ['2', '1', '4', '3'], + ['b', 'c'], ['2', '3'] + ), + ( + ['e', 'c', 'b', 'a', 'd'], [4, 3, 2, 1, 3], + [1], [2, 1, 3], + ['b', 'c'], [2, 3] + ), + ( + ['c', 'b', 'a', 'd'], [3, 2, 1, 3], + [1], [2, 1, 4, 3], + ['b', 'c'], [2, 3] + ), +] + + [email protected]( + "images, labels, ignore_labels, labels_order, out_images, out_labels", + TEST_DATA) +def test_get_class_representations( + images, labels, ignore_labels, labels_order, out_images, out_labels): + images, labels = _get_class_representations( + images, + labels=labels, + ignore_labels=ignore_labels, + labels_order=labels_order) + assert all(images == out_images) + assert all(labels == out_labels)
[Bug] ipyplot breaks input() functionality in Jupyter Lab Hey! First off I just wanted to thank you for building this tool, I've found it really useful for some exploratory work I've been doing. That said, I just spent a few hours trying to solve an issue that ended up being due to something in the ipyplot implementation. # My Environment Python 3.7.5 Jupyter Lab 2.2.4 Ubuntu 16.04 inside WSL 2 on Windows 10 # The Issue When running `input()` in a Jupyter cell, the text-entry box would fail to render, leaving the interpreter frozen waiting for a response and no place to enter it. # The Unexpected Solution It seems this was tied in some way to how ipyplot modifies the HTML, as I found that simply deleting the cells in my notebook that had previously run `ipyplot.plot_class_tabs()` made the text entry box for `input()` suddenly appear. The impact of this was surprisingly expansive, as it would actually cause entirely separate notebooks to exhibit this issue. I figured it out when I saw that closing a notebook containing ipyplot code caused a separate, new notebook to all of a sudden work correctly. Just wanted to post this here in case you know of a fix, and in case anybody else encounters this issue.
2020-06-08T11:50:56
-1.0
DisnakeDev/disnake
655
DisnakeDev__disnake-655
['259']
593bc49b936f90aa45a06c30622c88de16ab042b
diff --git a/changelog/655.breaking.rst b/changelog/655.breaking.rst new file mode 100644 index 0000000000..bd7ddfe476 --- /dev/null +++ b/changelog/655.breaking.rst @@ -0,0 +1,1 @@ +|tasks| Change :class:`.ext.tasks.Loop` to use keyword-only parameters. diff --git a/changelog/655.feature.rst b/changelog/655.feature.rst new file mode 100644 index 0000000000..18654d6715 --- /dev/null +++ b/changelog/655.feature.rst @@ -0,0 +1,1 @@ +|tasks| Add support for subclassing :class:`.ext.tasks.Loop` and using subclasses in :func:`.ext.tasks.loop` decorator. diff --git a/disnake/ext/tasks/__init__.py b/disnake/ext/tasks/__init__.py index 014ade6f02..bcf833aee2 100644 --- a/disnake/ext/tasks/__init__.py +++ b/disnake/ext/tasks/__init__.py @@ -8,7 +8,22 @@ import sys import traceback from collections.abc import Sequence -from typing import Any, Callable, Coroutine, Generic, List, Optional, Type, TypeVar, Union +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Coroutine, + Generic, + List, + Optional, + Protocol, + Type, + TypeVar, + Union, + cast, + get_origin, + overload, +) import aiohttp @@ -16,6 +31,14 @@ from disnake.backoff import ExponentialBackoff from disnake.utils import MISSING, utcnow +if TYPE_CHECKING: + from typing_extensions import Concatenate, ParamSpec, Self + + P = ParamSpec("P") + +else: + P = TypeVar("P") + __all__ = ("loop",) T = TypeVar("T") @@ -30,16 +53,16 @@ class SleepHandle: def __init__(self, dt: datetime.datetime, *, loop: asyncio.AbstractEventLoop) -> None: self.loop = loop - self.future = future = loop.create_future() + self.future: asyncio.Future[bool] = loop.create_future() relative_delta = disnake.utils.compute_timedelta(dt) - self.handle = loop.call_later(relative_delta, future.set_result, True) + self.handle = loop.call_later(relative_delta, self.future.set_result, True) def recalculate(self, dt: datetime.datetime) -> None: self.handle.cancel() relative_delta = disnake.utils.compute_timedelta(dt) self.handle = self.loop.call_later(relative_delta, self.future.set_result, True) - def wait(self) -> asyncio.Future[Any]: + def wait(self) -> asyncio.Future[bool]: return self.future def done(self) -> bool: @@ -59,14 +82,19 @@ class Loop(Generic[LF]): def __init__( self, coro: LF, - seconds: float, - hours: float, - minutes: float, - time: Union[datetime.time, Sequence[datetime.time]], - count: Optional[int], - reconnect: bool, - loop: asyncio.AbstractEventLoop, + *, + seconds: float = 0, + minutes: float = 0, + hours: float = 0, + time: Union[datetime.time, Sequence[datetime.time]] = MISSING, + count: Optional[int] = None, + reconnect: bool = True, + loop: asyncio.AbstractEventLoop = MISSING, ) -> None: + """ + .. note: + If you overwrite ``__init__`` arguments, make sure to redefine .clone too. + """ self.coro: LF = coro self.reconnect: bool = reconnect self.loop: asyncio.AbstractEventLoop = loop @@ -74,7 +102,7 @@ def __init__( self._current_loop = 0 self._handle: SleepHandle = MISSING self._task: asyncio.Task[None] = MISSING - self._injected = None + self._injected: Any = None self._valid_exception = ( OSError, disnake.GatewayNotFound, @@ -169,11 +197,16 @@ async def _loop(self, *args: Any, **kwargs: Any) -> None: self._stop_next_iteration = False self._has_failed = False - def __get__(self, obj: T, objtype: Type[T]) -> Loop[LF]: + def __get__(self, obj: T, objtype: Type[T]) -> Self: if obj is None: return self + clone = self.clone() + clone._injected = obj + setattr(obj, self.coro.__name__, clone) + return clone - copy: Loop[LF] = Loop( + def clone(self) -> Self: + instance = type(self)( self.coro, seconds=self._seconds, hours=self._hours, @@ -183,12 +216,11 @@ def __get__(self, obj: T, objtype: Type[T]) -> Loop[LF]: reconnect=self.reconnect, loop=self.loop, ) - copy._injected = obj - copy._before_loop = self._before_loop - copy._after_loop = self._after_loop - copy._error = self._error - setattr(obj, self.coro.__name__, copy) - return copy + instance._before_loop = self._before_loop + instance._after_loop = self._after_loop + instance._error = self._error + instance._injected = self._injected + return instance @property def seconds(self) -> Optional[float]: @@ -672,21 +704,55 @@ def change_interval( self._handle.recalculate(self._next_iteration) +T_co = TypeVar("T_co", covariant=True) +L_co = TypeVar("L_co", bound=Loop, covariant=True) + + +class Object(Protocol[T_co, P]): + def __new__(cls) -> T_co: + ... + + def __init__(*args: P.args, **kwargs: P.kwargs) -> None: + ... + + +@overload def loop( *, - seconds: float = MISSING, - minutes: float = MISSING, - hours: float = MISSING, - time: Union[datetime.time, Sequence[datetime.time]] = MISSING, + seconds: float = ..., + minutes: float = ..., + hours: float = ..., + time: Union[datetime.time, Sequence[datetime.time]] = ..., count: Optional[int] = None, reconnect: bool = True, - loop: asyncio.AbstractEventLoop = MISSING, + loop: asyncio.AbstractEventLoop = ..., ) -> Callable[[LF], Loop[LF]]: + ... + + +@overload +def loop( + cls: Type[Object[L_co, Concatenate[LF, P]]], *_: P.args, **kwargs: P.kwargs +) -> Callable[[LF], L_co]: + ... + + +def loop( + cls: Type[Object[L_co, Concatenate[LF, P]]] = Loop[LF], + **kwargs: Any, +) -> Callable[[LF], L_co]: """A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a :class:`Loop`. Parameters ---------- + cls: Type[:class:`Loop`] + The loop subclass to create an instance of. If provided, the following parameters + described below do not apply. Instead, this decorator will accept the same keywords + as the passed cls does. + + .. versionadded:: 2.6 + seconds: :class:`float` The number of seconds between every iteration. minutes: :class:`float` @@ -722,20 +788,21 @@ def loop( ValueError An invalid value was given. TypeError - The function was not a coroutine, an invalid value for the ``time`` parameter was passed, + The function was not a coroutine, the ``cls`` parameter was not a subclass of ``Loop``, + an invalid value for the ``time`` parameter was passed, or ``time`` parameter was passed in conjunction with relative time parameters. """ - def decorator(func: LF) -> Loop[LF]: - return Loop[LF]( - func, - seconds=seconds, - minutes=minutes, - hours=hours, - count=count, - time=time, - reconnect=reconnect, - loop=loop, - ) + if (origin := get_origin(cls)) is not None: + cls = origin + + if not isinstance(cls, type) or not issubclass(cls, Loop): + raise TypeError(f"cls argument must be a subclass of Loop, got {cls!r}") + + def decorator(func: LF) -> L_co: + if not asyncio.iscoroutinefunction(func): + raise TypeError("decorated function must be a coroutine") + + return cast("Type[L_co]", cls)(func, **kwargs) return decorator
diff --git a/tests/ext/tasks/test_loops.py b/tests/ext/tasks/test_loops.py new file mode 100644 index 0000000000..9ffe589121 --- /dev/null +++ b/tests/ext/tasks/test_loops.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: MIT + +import datetime +from typing import Any, Tuple + +import pytest + +from disnake.ext import commands +from disnake.ext.tasks import LF, Loop, loop + + +class TestLoops: + def test_decorator(self): + class Cog(commands.Cog): + @loop(seconds=30, minutes=0, hours=0) + async def task(self) -> None: + ... + + for c in (Cog, Cog()): + assert c.task.seconds == 30 + + with pytest.raises(TypeError, match="must be a coroutine"): + + @loop() # type: ignore + def task() -> None: + ... + + def test_mixing_time(self): + async def callback(): + pass + + with pytest.raises(TypeError): + Loop(callback, seconds=30, time=datetime.time()) + + with pytest.raises(TypeError): + + @loop(seconds=30, time=datetime.time()) + async def task() -> None: + ... + + def test_inheritance(self): + class HyperLoop(Loop[LF]): + def __init__(self, coro: LF, time_tup: Tuple[float, float, float]) -> None: + s, m, h = time_tup + super().__init__(coro, seconds=s, minutes=m, hours=h) + + def clone(self): + instance = type(self)(self.coro, (self._seconds, self._minutes, self._hours)) + instance._time = self._time + instance.count = self.count + instance.reconnect = self.reconnect + instance.loop = self.loop + instance._before_loop = self._before_loop + instance._after_loop = self._after_loop + instance._error = self._error + instance._injected = self._injected + return instance + + class WhileTrueLoop: + def __init__(self, coro: Any) -> None: + ... + + async def callback(): + pass + + HyperLoop(callback, (1, 2, 3)) + + class Cog(commands.Cog): + @loop(cls=HyperLoop[Any], time_tup=(1, 2, 3)) + async def task(self) -> None: + ... + + for c in (Cog, Cog()): + assert (c.task.seconds, c.task.minutes, c.task.hours) == (1, 2, 3) + + with pytest.raises(TypeError, match="subclass of Loop"): + + @loop(cls=WhileTrueLoop) # type: ignore + async def task() -> None: + ...
ext.tasks.Loop descriptor inheritance support ## Summary <!-- What is this pull request for? Does it fix any issues? --> Descriptor of `disnake.ext.tasks.Loop` returns new `Loop` instance instead of current class instance. Thats inheritance issue. ## Checklist <!-- Put an x inside [ ] to check it, like so: [x] --> - [x] If code changes were made, then they have been tested - [ ] I have updated the documentation to reflect the changes - [x] I have formatted the code properly by running `pre-commit run --all-files` - [x] This PR fixes an issue - [ ] This PR adds something new (e.g. new method or parameters) - [ ] This PR is a breaking change (e.g. methods or parameters removed/renamed) - [ ] This PR is **not** a code change (e.g. documentation, README, ...)
2022-07-25T16:54:51
-1.0
DisnakeDev/disnake
603
DisnakeDev__disnake-603
['573']
988e8c2b88428c5c205fecba16c96638e68dcfa0
diff --git a/disnake/mentions.py b/disnake/mentions.py index 07c811f320..6f3f02218a 100644 --- a/disnake/mentions.py +++ b/disnake/mentions.py @@ -27,10 +27,13 @@ from typing import TYPE_CHECKING, Any, List, Type, TypeVar, Union +from .enums import MessageType + __all__ = ("AllowedMentions",) if TYPE_CHECKING: from .abc import Snowflake + from .message import Message from .types.message import AllowedMentions as AllowedMentionsPayload @@ -111,6 +114,30 @@ def none(cls: Type[A]) -> A: """ return cls(everyone=False, users=False, roles=False, replied_user=False) + @classmethod + def from_message(cls: Type[A], message: Message) -> A: + """A factory method that returns a :class:`AllowedMentions` dervived from the current :class:`.Message` state. + + Note that this is not what AllowedMentions the message was sent with, but what the message actually mentioned. + For example, a message that successfully mentioned everyone will have :attr:`~AllowedMentions.everyone` set to ``True``. + + .. versionadded:: 2.6 + """ + # circular import + from .message import Message + + return cls( + everyone=message.mention_everyone, + users=message.mentions.copy(), # type: ignore # mentions is a list of Snowflakes + roles=message.role_mentions.copy(), # type: ignore # mentions is a list of Snowflakes + replied_user=bool( + message.type is MessageType.reply + and message.reference + and isinstance(message.reference.resolved, Message) + and message.reference.resolved.author in message.mentions + ), + ) + def to_dict(self) -> AllowedMentionsPayload: parse = [] data = {}
diff --git a/tests/test_mentions.py b/tests/test_mentions.py new file mode 100644 index 0000000000..492c445d12 --- /dev/null +++ b/tests/test_mentions.py @@ -0,0 +1,117 @@ +from typing import Dict, Union +from unittest import mock + +import pytest + +from disnake import AllowedMentions, Message, MessageType, Object + + +def test_classmethod_none() -> None: + none = AllowedMentions.none() + assert none.everyone is False + assert none.roles is False + assert none.users is False + assert none.replied_user is False + + +def test_classmethod_all() -> None: + all_mentions = AllowedMentions.all() + assert all_mentions.everyone is True + assert all_mentions.roles is True + assert all_mentions.users is True + assert all_mentions.replied_user is True + + [email protected]( + ("am", "expected"), + [ + (AllowedMentions(), {"parse": ["everyone", "users", "roles"], "replied_user": True}), + (AllowedMentions.all(), {"parse": ["everyone", "users", "roles"], "replied_user": True}), + (AllowedMentions(everyone=False), {"parse": ["users", "roles"], "replied_user": True}), + ( + AllowedMentions(users=[Object(x) for x in [123, 456, 789]]), + {"parse": ["everyone", "roles"], "replied_user": True, "users": [123, 456, 789]}, + ), + ( + AllowedMentions( + users=[Object(x) for x in [123, 456, 789]], + roles=[Object(x) for x in [123, 456, 789]], + ), + { + "parse": ["everyone"], + "replied_user": True, + "users": [123, 456, 789], + "roles": [123, 456, 789], + }, + ), + (AllowedMentions.none(), {"parse": []}), + ], +) +def test_to_dict(am: AllowedMentions, expected: Dict[str, Union[bool, list]]) -> None: + assert expected == am.to_dict() + + [email protected]( + ("og", "to_merge", "expected"), + [ + (AllowedMentions.none(), AllowedMentions.none(), AllowedMentions.none()), + (AllowedMentions.none(), AllowedMentions(), AllowedMentions.none()), + (AllowedMentions.all(), AllowedMentions(), AllowedMentions.all()), + (AllowedMentions(), AllowedMentions(), AllowedMentions()), + (AllowedMentions.all(), AllowedMentions.none(), AllowedMentions.none()), + ( + AllowedMentions(everyone=False), + AllowedMentions(users=True), + AllowedMentions(everyone=False, users=True), + ), + ( + AllowedMentions(users=[Object(x) for x in [123, 456, 789]]), + AllowedMentions(users=False), + AllowedMentions(users=False), + ), + ], +) +def test_merge(og: AllowedMentions, to_merge: AllowedMentions, expected: AllowedMentions) -> None: + merged = og.merge(to_merge) + + assert expected.everyone is merged.everyone + assert expected.users is merged.users + assert expected.roles is merged.roles + assert expected.replied_user is merged.replied_user + + +def test_from_message() -> None: + # as we don't have a message mock yet we are faking a message here with the necessary components + msg = mock.NonCallableMock() + msg.mention_everyone = True + users = [Object(x) for x in [123, 456, 789]] + msg.mentions = users + roles = [Object(x) for x in [123, 456, 789]] + msg.role_mentions = roles + msg.reference = None + + am = AllowedMentions.from_message(msg) + + assert am.everyone is True + # check that while the list matches, it isn't the same list + assert am.users == users + assert am.users is not users + + assert am.roles == roles + assert am.roles is not roles + + assert am.replied_user is False + + +def test_from_message_replied_user() -> None: + message = mock.Mock(Message) + author = Object(123) + message.mentions = [author] + assert AllowedMentions.from_message(message).replied_user is False + + message.type = MessageType.reply + assert AllowedMentions.from_message(message).replied_user is False + + resolved = mock.Mock(Message, author=author) + message.reference = mock.Mock(resolved=resolved) + assert AllowedMentions.from_message(message).replied_user is True
MessageInteraction.edit_original_message does not preserve allowed_mentions state if kwarg not passed ### Summary MessageInteraction.edit_original_message does not preserve allowed_mentions state if kwarg not passed ### Reproduction Steps 1. Set Client.allowed_mentions to AllowedMentions.none() 2. Send a message that mentions a user containing a button, explicitly defining allowed_mentions 3. Click the button, and have the button handler update the content of the message using `inter.edit_original_message(content=...)` 4. Observe that the allowed_mentions is not preserved ### Minimal Reproducible Code _No response_ ### Expected Results The edited message remains highlighted, mentioning the user ### Actual Results The edited message no longer appears highlighted Attaching a debugger reveals that https://github.com/DisnakeDev/disnake/blob/master/disnake/interactions/base.py#L449 became an AllowedMentions.none() instead of the actual previous allowed mentions ### Intents discord.Intents( guilds=True, members=True, messages=True, reactions=True, bans=False, emojis=False, integrations=False, webhooks=False, invites=False, voice_states=False, presences=False, typing=False, ) ### System Information ```markdown - Python v3.10.2-final - disnake v2.4.0-final - disnake pkg_resources: v2.4.0 - aiohttp v3.8.1 - system info: Darwin 18.7.0 Darwin Kernel Version 18.7.0: Tue Jun 22 19:37:08 PDT 2021; root:xnu-4903.278.70~1/RELEASE_X86_64 Note: this is not the most recent Disnake version but I have confirmed that the applicable code has not been updated since. ``` ### Checklist - [X] I have searched the open issues for duplicates. - [X] I have shown the entire traceback, if possible. - [X] I have removed my token from display, if visible. ### Additional Context - This might only occur if Client.allowed_mentions is set, overwriting the allowed_mentions with Client.allowed_mentions
This appears to be working as intended, as Discord unfortunately doesn't return the `allowed_mentions` value in the payload - there's no way of knowing the previous `allowed_mentions` value solely based on the interaction, and sending it again on edit. Editing messages works similarly for the same reason, which is why the only feasible default action is to fall back to the client's `allowed_mentions`.
2022-07-05T17:24:19
-1.0
DisnakeDev/disnake
584
DisnakeDev__disnake-584
['577']
1c9ddd8cc369bfaa8c6259b736ca8af772a9011d
diff --git a/disnake/ext/commands/params.py b/disnake/ext/commands/params.py index 46284b85dd..775b7d2863 100644 --- a/disnake/ext/commands/params.py +++ b/disnake/ext/commands/params.py @@ -36,6 +36,8 @@ Callable, ClassVar, Dict, + Final, + FrozenSet, List, Literal, Optional, @@ -43,7 +45,6 @@ Type, TypeVar, Union, - cast, get_args, get_origin, get_type_hints, @@ -114,8 +115,6 @@ def issubclass_(obj: Any, tp: Union[TypeT, Tuple[TypeT, ...]]) -> TypeGuard[Type def remove_optionals(annotation: Any) -> Any: """remove unwanted optionals from an annotation""" if get_origin(annotation) in (Union, UnionType): - annotation = cast(Any, annotation) - args = tuple(i for i in annotation.__args__ if i not in (None, type(None))) if len(args) == 1: annotation = args[0] @@ -280,6 +279,10 @@ class LargeInt(int): """Type for large integers in slash commands.""" +# option types that require additional handling in verify_type +_VERIFY_TYPES: Final[FrozenSet[OptionType]] = frozenset((OptionType.user, OptionType.mentionable)) + + class ParamInfo: """A class that basically connects function params with slash command options. The instances of this class are not created manually, but via the functional interface instead. @@ -443,14 +446,21 @@ async def get_default(self, inter: ApplicationCommandInteraction) -> Any: return default async def verify_type(self, inter: ApplicationCommandInteraction, argument: Any) -> Any: - """Check if a type of an argument is correct and possibly fix it""" - if issubclass_(self.type, disnake.Member): - if isinstance(argument, disnake.Member): - return argument + """Check if the type of an argument is correct and possibly raise if it's not.""" + if self.discord_type not in _VERIFY_TYPES: + return argument + # The API may return a `User` for options annotated with `Member`, + # including `Member` (user option), `Union[User, Member]` (user option) and + # `Union[Member, Role]` (mentionable option). + # If we received a `User` but didn't expect one, raise. + if ( + isinstance(argument, disnake.User) + and issubclass_(self.type, disnake.Member) + and not issubclass_(self.type, disnake.User) + ): raise errors.MemberNotFound(str(argument.id)) - # unexpected types may just be ignored return argument async def convert_argument(self, inter: ApplicationCommandInteraction, argument: Any) -> Any:
diff --git a/tests/ext/commands/test_params.py b/tests/ext/commands/test_params.py new file mode 100644 index 0000000000..b63ab9b851 --- /dev/null +++ b/tests/ext/commands/test_params.py @@ -0,0 +1,61 @@ +from typing import Union +from unittest import mock + +import pytest + +import disnake +from disnake import Member, Role, User +from disnake.ext import commands + +OptionType = disnake.OptionType + + +class TestParamInfo: + @pytest.mark.parametrize( + ("annotation", "expected_type", "arg_types"), + [ + # should accept user or member + (disnake.abc.User, OptionType.user, [User, Member]), + (User, OptionType.user, [User, Member]), + (Union[User, Member], OptionType.user, [User, Member]), + # only accepts member, not user + (Member, OptionType.user, [Member]), + # only accepts role + (Role, OptionType.role, [Role]), + # should accept member or role + (Union[Member, Role], OptionType.mentionable, [Member, Role]), + # should accept everything + (disnake.abc.Snowflake, OptionType.mentionable, [User, Member, Role]), + ], + ) + @pytest.mark.asyncio + async def test_verify_type(self, annotation, expected_type, arg_types) -> None: + # tests that the Discord option type is determined correctly, + # and that valid argument types are accepted + info = commands.ParamInfo() + info.parse_annotation(annotation) + + # type should be valid + assert info.discord_type is expected_type + + for arg_type in arg_types: + arg_mock = mock.Mock(arg_type) + assert await info.verify_type(mock.Mock(), arg_mock) is arg_mock + + @pytest.mark.parametrize( + ("annotation", "arg_types"), + [ + (Member, [User]), + (Union[Member, Role], [User]), + ], + ) + @pytest.mark.asyncio + async def test_verify_type__invalid_member(self, annotation, arg_types) -> None: + # tests that invalid argument types result in `verify_type` raising an exception + info = commands.ParamInfo() + info.parse_annotation(annotation) + + for arg_type in arg_types: + arg_mock = mock.Mock(arg_type) + with pytest.raises(commands.errors.MemberNotFound): + await info.verify_type(mock.Mock(), arg_mock)
Traceback when "Union[Member, User]" is used as type hint in slash command parameters ### Summary When "Union[Member, User]" is used as a type hint in a slash command parameter, a traceback from disnake is shown when the slash command is invoked targeting a user who should resolve to a User object, not a Member object.. ### Reproduction Steps Reference the below Minimal Reproducible Code and invoke the relevant slash command against a user who is not currently in the server. This issue does *not* occur when the target of the slash command is in the server (and resolves to a Member object). ### Minimal Reproducible Code ```python @discord_bot.slash_command() async def whois( inter: ApplicationCommandInteraction, user: Union[Member, User] = commands.Param( description="The member to display information about" ), ) -> None: pass ``` ### Expected Results The slash command should be invoked successfully without a traceback when targeting a user who is not in the server. This used to work in v2.4.0 of disnake - not positive if it is broken in v2.5.0 as well. ### Actual Results The following traceback is observed when this slash command is invoked: ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1264, in process_application_commands await app_command.invoke(interaction) File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/slash_core.py", line 680, in invoke await call_param_func(self.callback, inter, self.cog, **kwargs) File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/params.py", line 811, in call_param_func kwargs[param.param_name] = await param.convert_argument( File "/usr/local/lib/python3.8/site-packages/disnake/ext/commands/params.py", line 464, in convert_argument return await self.verify_type(inter, argument) disnake.ext.commands.errors.MemberNotFound: Member "redacted_valid_snowflake_here" not found. ``` ### Intents default, members, message_content ### System Information ```markdown $ python -m disnake -v - Python v3.8.10-final - disnake v2.5.1-final - disnake pkg_resources: v2.5.1 - aiohttp v3.7.4.post0 - system info: Linux 5.4.0-120-generic #136-Ubuntu SMP Fri Jun 10 13:40:48 UTC 2022 ``` ``` ### Checklist - [X] I have searched the open issues for duplicates. - [X] I have shown the entire traceback, if possible. - [X] I have removed my token from display, if visible. ### Additional Context Talked with Mari about this over Discord, she said she'd open up an issue for this. I opened this up to save her some time 😅
2022-06-26T18:52:54
-1.0
openwisp/django-x509
127
openwisp__django-x509-127
['119', '119']
46620baf9e7519c256c92c23ac0fd510f1db5ec4
diff --git a/django_x509/base/models.py b/django_x509/base/models.py index 780ac63..b9dc05f 100644 --- a/django_x509/base/models.py +++ b/django_x509/base/models.py @@ -20,7 +20,6 @@ utc_time = '%y%m%d%H%M%SZ' KEY_LENGTH_CHOICES = ( - ('', ''), ('512', '512'), ('1024', '1024'), ('2048', '2048'), @@ -28,7 +27,6 @@ ) DIGEST_CHOICES = ( - ('', ''), ('sha1', 'SHA1'), ('sha224', 'SHA224'), ('sha256', 'SHA256'), @@ -114,7 +112,6 @@ class BaseX509(models.Model): key_length = models.CharField( _('key length'), help_text=_('bits'), - blank=True, choices=KEY_LENGTH_CHOICES, default=default_key_length, max_length=6, @@ -122,7 +119,6 @@ class BaseX509(models.Model): digest = models.CharField( _('digest algorithm'), help_text=_('bits'), - blank=True, choices=DIGEST_CHOICES, default=default_digest_algorithm, max_length=8, diff --git a/django_x509/migrations/0009_alter_ca_digest_alter_ca_key_length_and_more.py b/django_x509/migrations/0009_alter_ca_digest_alter_ca_key_length_and_more.py new file mode 100644 index 0000000..9e48788 --- /dev/null +++ b/django_x509/migrations/0009_alter_ca_digest_alter_ca_key_length_and_more.py @@ -0,0 +1,80 @@ +# Generated by Django 4.0.2 on 2022-02-16 14:01 + +from django.db import migrations, models +import django_x509.base.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('django_x509', '0008_common_name_max_length'), + ] + + operations = [ + migrations.AlterField( + model_name='ca', + name='digest', + field=models.CharField( + choices=[ + ('sha1', 'SHA1'), + ('sha224', 'SHA224'), + ('sha256', 'SHA256'), + ('sha384', 'SHA384'), + ('sha512', 'SHA512'), + ], + default=django_x509.base.models.default_digest_algorithm, + help_text='bits', + max_length=8, + verbose_name='digest algorithm', + ), + ), + migrations.AlterField( + model_name='ca', + name='key_length', + field=models.CharField( + choices=[ + ('512', '512'), + ('1024', '1024'), + ('2048', '2048'), + ('4096', '4096'), + ], + default=django_x509.base.models.default_key_length, + help_text='bits', + max_length=6, + verbose_name='key length', + ), + ), + migrations.AlterField( + model_name='cert', + name='digest', + field=models.CharField( + choices=[ + ('sha1', 'SHA1'), + ('sha224', 'SHA224'), + ('sha256', 'SHA256'), + ('sha384', 'SHA384'), + ('sha512', 'SHA512'), + ], + default=django_x509.base.models.default_digest_algorithm, + help_text='bits', + max_length=8, + verbose_name='digest algorithm', + ), + ), + migrations.AlterField( + model_name='cert', + name='key_length', + field=models.CharField( + choices=[ + ('512', '512'), + ('1024', '1024'), + ('2048', '2048'), + ('4096', '4096'), + ], + default=django_x509.base.models.default_key_length, + help_text='bits', + max_length=6, + verbose_name='key length', + ), + ), + ]
diff --git a/django_x509/tests/test_ca.py b/django_x509/tests/test_ca.py index 74f76ce..b6ca756 100644 --- a/django_x509/tests/test_ca.py +++ b/django_x509/tests/test_ca.py @@ -681,3 +681,14 @@ def test_ca_common_name_length(self): message_dict = context_manager.exception.message_dict self.assertIn('common_name', message_dict) self.assertEqual(message_dict['common_name'][0], msg) + + def test_ca_without_key_length_and_digest_algo(self): + try: + self._create_ca(key_length='', digest='') + except ValidationError as e: + self.assertIn('key_length', e.error_dict) + self.assertIn('digest', e.error_dict) + except Exception as e: + self.fail(f'Got exception: {e}') + else: + self.fail('ValidationError not raised as expected') diff --git a/tests/openwisp2/sample_x509/migrations/0001_initial.py b/tests/openwisp2/sample_x509/migrations/0001_initial.py index c06ad77..cfa051e 100644 --- a/tests/openwisp2/sample_x509/migrations/0001_initial.py +++ b/tests/openwisp2/sample_x509/migrations/0001_initial.py @@ -33,9 +33,7 @@ class Migration(migrations.Migration): ( 'key_length', models.CharField( - blank=True, choices=[ - ('', ''), ('512', '512'), ('1024', '1024'), ('2048', '2048'), @@ -50,9 +48,7 @@ class Migration(migrations.Migration): ( 'digest', models.CharField( - blank=True, choices=[ - ('', ''), ('sha1', 'SHA1'), ('sha224', 'SHA224'), ('sha256', 'SHA256'), @@ -191,9 +187,7 @@ class Migration(migrations.Migration): ( 'key_length', models.CharField( - blank=True, choices=[ - ('', ''), ('512', '512'), ('1024', '1024'), ('2048', '2048'), @@ -208,9 +202,7 @@ class Migration(migrations.Migration): ( 'digest', models.CharField( - blank=True, choices=[ - ('', ''), ('sha1', 'SHA1'), ('sha224', 'SHA224'), ('sha256', 'SHA256'), @@ -380,9 +372,7 @@ class Migration(migrations.Migration): ( 'key_length', models.CharField( - blank=True, choices=[ - ('', ''), ('512', '512'), ('1024', '1024'), ('2048', '2048'), @@ -397,9 +387,7 @@ class Migration(migrations.Migration): ( 'digest', models.CharField( - blank=True, choices=[ - ('', ''), ('sha1', 'SHA1'), ('sha224', 'SHA224'), ('sha256', 'SHA256'),
[pki] CA can't be created when `Key length` set to `None` or `Digest algorithm` set to `None` ### Steps to reproduce :- **First Error** 1. Start creating a new CA. 2. Set the name. 3. Set the `Key length` choice to `None`. 4. Hit the save button. Error[Screenshot]:- ![image](https://user-images.githubusercontent.com/45564404/116928944-57dd2e00-ac7b-11eb-8faf-29452079a560.png) **Second Error** 3. Set the `Digest algorithm` to `None` 4. Hit the save button. Error[Screenshot]:- ![image](https://user-images.githubusercontent.com/45564404/116929389-fb2e4300-ac7b-11eb-9c6a-894b43f754f2.png) [pki] CA can't be created when `Key length` set to `None` or `Digest algorithm` set to `None` ### Steps to reproduce :- **First Error** 1. Start creating a new CA. 2. Set the name. 3. Set the `Key length` choice to `None`. 4. Hit the save button. Error[Screenshot]:- ![image](https://user-images.githubusercontent.com/45564404/116928944-57dd2e00-ac7b-11eb-8faf-29452079a560.png) **Second Error** 3. Set the `Digest algorithm` to `None` 4. Hit the save button. Error[Screenshot]:- ![image](https://user-images.githubusercontent.com/45564404/116929389-fb2e4300-ac7b-11eb-9c6a-894b43f754f2.png)
I was able to replicate this in django-x509. I believe we can move this issue to that repository @pandafy @ManishShah120 @atb00ker issue moved to django-x509. I was able to replicate this in django-x509. I believe we can move this issue to that repository @pandafy @ManishShah120 @atb00ker issue moved to django-x509.
2022-02-14T13:55:48
-1.0
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
10