|
19 | 19 | import datetime |
20 | 20 | from enum import Enum, EnumMeta |
21 | 21 | import inspect |
22 | | -import io |
23 | 22 | import json |
24 | 23 | import logging |
25 | 24 | import sys |
@@ -824,20 +823,18 @@ class Blob(_common.BaseModel): |
824 | 823 | description="""Required. The IANA standard MIME type of the source data.""", |
825 | 824 | ) |
826 | 825 |
|
827 | | - def as_image(self) -> Optional['PIL_Image']: |
828 | | - """Returns the Blob as a PIL Image, or None if the Blob is not an image.""" |
| 826 | + def as_image(self) -> Optional['Image']: |
| 827 | + """Returns the Blob as a Image, or None if the Blob is not an image.""" |
829 | 828 | if ( |
830 | 829 | not self.data |
831 | 830 | or not self.mime_type |
832 | 831 | or not self.mime_type.startswith('image/') |
833 | 832 | ): |
834 | 833 | return None |
835 | | - if not _is_pillow_image_imported: |
836 | | - raise ImportError( |
837 | | - 'The PIL module is not available. Please install the Pillow' |
838 | | - ' package. `pip install pillow`' |
839 | | - ) |
840 | | - return PIL.Image.open(io.BytesIO(self.data)) |
| 834 | + return Image( |
| 835 | + image_bytes=self.data, |
| 836 | + mime_type=self.mime_type, |
| 837 | + ) |
841 | 838 |
|
842 | 839 |
|
843 | 840 | class BlobDict(TypedDict, total=False): |
@@ -1098,7 +1095,7 @@ class Part(_common.BaseModel): |
1098 | 1095 | default=None, description="""Optional. Text part (can be code).""" |
1099 | 1096 | ) |
1100 | 1097 |
|
1101 | | - def as_image(self) -> Optional['PIL_Image']: |
| 1098 | + def as_image(self) -> Optional['Image']: |
1102 | 1099 | """Returns the part as a PIL Image, or None if the part is not an image.""" |
1103 | 1100 | if not self.inline_data: |
1104 | 1101 | return None |
@@ -6222,13 +6219,19 @@ def show(self) -> None: |
6222 | 6219 |
|
6223 | 6220 | This method only works in a notebook environment. |
6224 | 6221 | """ |
6225 | | - try: |
6226 | | - from IPython import display as IPython_display |
6227 | | - except ImportError: |
6228 | | - IPython_display = None |
| 6222 | + in_notebook = 'ipykernel' in sys.modules |
| 6223 | + if in_notebook: |
| 6224 | + try: |
| 6225 | + from IPython import display as IPython_display |
| 6226 | + except ImportError: |
| 6227 | + IPython_display = None |
6229 | 6228 |
|
6230 | | - if IPython_display: |
6231 | | - IPython_display.display(self._pil_image) |
| 6229 | + if IPython_display: |
| 6230 | + IPython_display.display(self._pil_image) |
| 6231 | + else: |
| 6232 | + img = self._pil_image |
| 6233 | + if img is not None: |
| 6234 | + img.show() |
6232 | 6235 |
|
6233 | 6236 | @property |
6234 | 6237 | def _pil_image(self) -> Optional['PIL_Image']: |
|
0 commit comments