Skip to content

Commit

Permalink
Update the behavior of opening image files in Jupyter type.
Browse files Browse the repository at this point in the history
  • Loading branch information
MeF0504 committed Sep 20, 2024
1 parent bbaa145 commit 70bed13
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 18 deletions.
26 changes: 20 additions & 6 deletions aftviewer/core/image_viewer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def __set_image_viewer(args: Args) -> None:
logger.debug(f'image viewer: {__ImgViewer} (None?:{__ImgViewer is None})')


def show_image_file(img_file: str, args: Args) -> None | bool:
def show_image_file(img_file: str, args: Args,
wait: bool = True) -> None | bool:
"""
show an image file with the image viewer.
Expand All @@ -141,6 +142,10 @@ def show_image_file(img_file: str, args: Args) -> None | bool:
image file.
args: Args
The arguments given by the command line.
wait: bool
If true, wait to press any key after opening the image file
by the command.
Default: True.
Returns
-------
Expand Down Expand Up @@ -175,8 +180,10 @@ def show_image_file(img_file: str, args: Args) -> None | bool:
if chk_cmd(__ImgViewer, logger=logger):
cmds = __get_exec_cmds(__ImgViewer, img_file)
out = subprocess.run(cmds)
# wait to open file. this is for, e.g., open command on Mac OS.
input('Press Enter to continue')
if wait:
# wait to open file. this supports stable behavior
# for, e.g., open command on Mac OS.
input('Press Enter to continue')
if out.returncode == 0:
ret = True
else:
Expand All @@ -187,7 +194,8 @@ def show_image_file(img_file: str, args: Args) -> None | bool:
return ret


def show_image_ndarray(data: Any, name: str, args: Args) -> None | bool:
def show_image_ndarray(data: Any, name: str, args: Args,
wait: bool = True) -> None | bool:
"""
show a given ndArray as an image with the image viewer.
Expand All @@ -200,6 +208,10 @@ def show_image_ndarray(data: Any, name: str, args: Args) -> None | bool:
The name of the image.
args: Args
The arguments given by the command line.
wait: bool
If true, wait to press any key after opening the image file
by the command.
Default: True
Returns
-------
Expand Down Expand Up @@ -233,8 +245,10 @@ def show_image_ndarray(data: Any, name: str, args: Args) -> None | bool:
make_bitmap(tmp.name, data, verbose=False, logger=logger)
cmds = __get_exec_cmds(__ImgViewer, tmp.name)
out = subprocess.run(cmds)
# wait to open file. this is for, e.g., open command on Mac OS.
input('Press Enter to continue')
if wait:
# wait to open file. this supports stable behavior
# for, e.g., open command on Mac OS.
input('Press Enter to continue')
if out.returncode == 0:
ret = True
else:
Expand Down
49 changes: 37 additions & 12 deletions aftviewer/viewers/jupyter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
import tempfile
from pathlib import Path
from logging import getLogger
from typing import Any

from .. import (GLOBAL_CONF, args_chk, cprint, show_image_file, print_error,
get_config, help_template,
from .. import (GLOBAL_CONF, Args, args_chk, cprint,
show_image_file, print_error, get_config, help_template,
add_args_imageviewer, add_args_output, add_args_verbose)
logger = getLogger(GLOBAL_CONF.logname)


def show_output(output, args, out_obj):
def show_output(output: dict[str, Any], args: Args, cnt: str,
out_obj, tmpdir: None | tempfile.TemporaryDirectory):
if out_obj == sys.stdout:
header = ''
else:
Expand All @@ -30,14 +32,29 @@ def show_output(output, args, out_obj):
elif out_type == 'image/png':
img_code = out_data['image/png']
img_bin = base64.b64decode(img_code.encode())
with tempfile.NamedTemporaryFile(suffix='.png') as tmp:
tmp.write(img_bin)
ret = show_image_file(tmp.name, args)
if out_obj == sys.stdout:
if ret is None:
print_error('image viewer is not found.')
elif not ret:
print_error('failed to open an image.')
if out_obj != sys.stdout:
# --output case
continue
elif tmpdir is None:
# normal case
with tempfile.NamedTemporaryFile(suffix='.png') as tmp:
tmp.write(img_bin)
ret = show_image_file(tmp.name, args, wait=True)
else:
# --verbose case
tmpfile = f'{tmpdir.name}/out-{cnt}.png'
add_idx = 0
while Path(tmpfile).is_file():
tmpfile = f'{tmpdir.name}/out-{cnt}_{add_idx}.png'
add_idx += 1
with open(tmpfile, 'wb') as tmp:
tmp.write(img_bin)
ret = show_image_file(tmpfile, args, wait=False)
pass
if ret is None:
print_error('image viewer is not found.')
elif not ret:
print_error('failed to open an image.')


def add_args(parser):
Expand Down Expand Up @@ -79,9 +96,12 @@ def main(fpath, args):
fgo, bgo = get_config('jupyter', 'output_color')
fgt, bgt = get_config('jupyter', 'type_color')

tmpdir = None
meta = data['metadata']
logger.debug(f'meta data: {meta}')
if args_chk(args, 'verbose'):
tmpdir = tempfile.TemporaryDirectory()
logger.info(f'tmpdir: {tmpdir.name}')
print(f'{header}kernel : {meta["kernelspec"]["display_name"]}',
file=outf)
if 'language_info' in meta:
Expand Down Expand Up @@ -119,7 +139,7 @@ def main(fpath, args):
cprint(f'{header}Out [{cnt}]{num}',
fg=fgo, bg=bgo, file=outf)
for output in cell['outputs']:
show_output(output, args, outf)
show_output(output, args, cnt, outf, tmpdir)
elif cell['cell_type'] == 'markdown':
cprint(f'{header}markdown{num}',
fg=fgt, bg=bgt, file=outf)
Expand All @@ -141,4 +161,9 @@ def main(fpath, args):
if key == 'quit':
break

if args_chk(args, 'verbose'):
input('Press ENTER to close file.')
outf.close()
if tmpdir is not None:
tmpdir.cleanup()
logger.info('cleanup tmpdir.')

0 comments on commit 70bed13

Please sign in to comment.