Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Allow specifying alt text for IPython.display.Image. #12864

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions IPython/core/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@


from binascii import b2a_base64, hexlify
import html
import json
import mimetypes
import os
Expand Down Expand Up @@ -800,9 +801,20 @@ class Image(DisplayObject):
_FMT_GIF: 'image/gif',
}

def __init__(self, data=None, url=None, filename=None, format=None,
embed=None, width=None, height=None, retina=False,
unconfined=False, metadata=None):
def __init__(
self,
data=None,
url=None,
filename=None,
format=None,
embed=None,
width=None,
height=None,
retina=False,
unconfined=False,
metadata=None,
alt=None,
):
"""Create a PNG/JPEG/GIF image object given raw data.

When this object is returned by an input cell or passed to the
Expand Down Expand Up @@ -847,6 +859,8 @@ def __init__(self, data=None, url=None, filename=None, format=None,
Set unconfined=True to disable max-width confinement of the image.
metadata : dict
Specify extra metadata to attach to the image.
alt : unicode
Alternative text for the image, for use by screen readers.

Examples
--------
Expand Down Expand Up @@ -924,6 +938,7 @@ def __init__(self, data=None, url=None, filename=None, format=None,
self.height = height
self.retina = retina
self.unconfined = unconfined
self.alt = alt
super(Image, self).__init__(data=data, url=url, filename=filename,
metadata=metadata)

Expand All @@ -933,6 +948,9 @@ def __init__(self, data=None, url=None, filename=None, format=None,
if self.height is None and self.metadata.get('height', {}):
self.height = metadata['height']

if self.alt is None and self.metadata.get("alt", {}):
self.alt = metadata["alt"]

if retina:
self._retina_shape()

Expand Down Expand Up @@ -962,18 +980,21 @@ def reload(self):

def _repr_html_(self):
if not self.embed:
width = height = klass = ''
width = height = klass = alt = ""
if self.width:
width = ' width="%d"' % self.width
if self.height:
height = ' height="%d"' % self.height
if self.unconfined:
klass = ' class="unconfined"'
return u'<img src="{url}"{width}{height}{klass}/>'.format(
if self.alt:
alt = ' alt="%s"' % html.escape(self.alt)
return '<img src="{url}"{width}{height}{klass}{alt}/>'.format(
url=self.url,
width=width,
height=height,
klass=klass,
alt=alt,
)

def _repr_mimebundle_(self, include=None, exclude=None):
Expand Down Expand Up @@ -1006,6 +1027,8 @@ def _data_and_metadata(self, always_both=False):
md['height'] = self.height
if self.unconfined:
md['unconfined'] = self.unconfined
if self.alt:
md["alt"] = self.alt
if md or always_both:
return b64_data, md
else:
Expand Down
37 changes: 31 additions & 6 deletions IPython/core/tests/test_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ def test_embed_svg_url():
from io import BytesIO
svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>'
url = 'http://test.com/circle.svg'

gzip_svg = BytesIO()
with gzip.open(gzip_svg, 'wb') as fp:
fp.write(svg_data)
gzip_svg = gzip_svg.getvalue()

def mocked_urlopen(*args, **kwargs):
class MockResponse:
def __init__(self, svg):
Expand All @@ -94,9 +94,9 @@ def read(self):

if args[0] == url:
return MockResponse(svg_data)
elif args[0] == url + 'z':
ret= MockResponse(gzip_svg)
ret.headers['content-encoding']= 'gzip'
elif args[0] == url + "z":
ret = MockResponse(gzip_svg)
ret.headers["content-encoding"] = "gzip"
return ret
return MockResponse(None)

Expand All @@ -105,7 +105,7 @@ def read(self):
nt.assert_true(svg._repr_svg_().startswith('<svg'))
svg = display.SVG(url=url + 'z')
nt.assert_true(svg._repr_svg_().startswith('<svg'))

def test_retina_jpeg():
here = os.path.dirname(__file__)
img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
Expand Down Expand Up @@ -458,6 +458,31 @@ def test_display_handle():
})


def test_image_alt_tag():
"""Simple test for display.Image(args, alt=x,)"""
thisurl = "http://example.com/image.png"
img = display.Image(url=thisurl, alt="an image")
nt.assert_equal(u'<img src="%s" alt="an image"/>' % (thisurl), img._repr_html_())
img = display.Image(url=thisurl, unconfined=True, alt="an image")
nt.assert_equal(
u'<img src="%s" class="unconfined" alt="an image"/>' % (thisurl),
img._repr_html_(),
)
img = display.Image(url=thisurl, alt='>"& <')
nt.assert_equal(
u'<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl), img._repr_html_()
)

img = display.Image(url=thisurl, metadata={"alt": "an image"})
nt.assert_equal(img.alt, "an image")

here = os.path.dirname(__file__)
img = display.Image(os.path.join(here, "2x2.png"), alt="an image")
nt.assert_equal(img.alt, "an image")
_, md = img._repr_png_()
nt.assert_equal(md["alt"], "an image")


@nt.raises(FileNotFoundError)
def test_image_bad_filename_raises_proper_exception():
display.Image("/this/file/does/not/exist/")._repr_png_()