ipython-icat 0.3.1__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipython-icat
3
- Version: 0.3.1
3
+ Version: 0.4.1
4
4
  Summary: IPython magic command for displaying images in kitty terminal
5
5
  Author-email: Tony Kabilan Okeke <tonykabilanokeke@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/Kabilan108/ipython-icat
@@ -45,20 +45,26 @@ In your IPython session, load the extension:
45
45
 
46
46
  ### Displaying Matplotlib Plots
47
47
 
48
- To use the kitty backend for matplotlib:
48
+ To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
49
49
 
50
50
  ```python
51
- %plt_icat
51
+ %icat
52
52
  ```
53
53
 
54
- After running this command, any matplotlib plots you create will be displayed directly in your kitty terminal.
54
+ After running this command:
55
+ - Matplotlib plots will be displayed directly in your kitty-compatible terminal.
56
+ - Evaluating a `PIL.Image.Image` value (e.g. typing `img` at the prompt) will automatically render it.
57
+
58
+ You can also run:
59
+ - `%icat status` to see whether integration is enabled
60
+ - `%icat off` to disable auto-rendering and restore the previous matplotlib backend (best-effort)
55
61
 
56
62
  ### Use as a Default Backend
57
63
 
58
64
  To set the kitty backend for matplotlib as the default, add the following lines to your IPython configuration file:
59
65
 
60
66
  1. `c.InteractiveShellApp.extensions = ['icat']`
61
- 2. `c.InteractiveShellApp.exec_lines = ['%plt_icat']`
67
+ 2. `c.InteractiveShellApp.exec_lines = ['%icat on']`
62
68
 
63
69
  #### Automatic Setup
64
70
 
@@ -84,7 +90,7 @@ python -m icat setup --profile myprofile
84
90
 
85
91
  ### Displaying Images
86
92
 
87
- To display an image file or a PIL Image object:
93
+ To display an image file, a PIL Image object, or a Python expression that evaluates to a PIL Image:
88
94
 
89
95
  ```python
90
96
  %icat path/to/your/image.jpg
@@ -98,10 +104,16 @@ img = Image.open('path/to/your/image.jpg')
98
104
  %icat img
99
105
  ```
100
106
 
107
+ Expressions work too:
108
+
109
+ ```python
110
+ %icat ds[0].image
111
+ ```
112
+
101
113
  You can also resize the image when displaying:
102
114
 
103
115
  ```python
104
- %icat path/to/your/image.jpg -w 300 -h 200
116
+ %icat path/to/your/image.jpg -W 300 -H 200
105
117
  ```
106
118
 
107
119
  ### Using Ghostty
@@ -30,20 +30,26 @@ In your IPython session, load the extension:
30
30
 
31
31
  ### Displaying Matplotlib Plots
32
32
 
33
- To use the kitty backend for matplotlib:
33
+ To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
34
34
 
35
35
  ```python
36
- %plt_icat
36
+ %icat
37
37
  ```
38
38
 
39
- After running this command, any matplotlib plots you create will be displayed directly in your kitty terminal.
39
+ After running this command:
40
+ - Matplotlib plots will be displayed directly in your kitty-compatible terminal.
41
+ - Evaluating a `PIL.Image.Image` value (e.g. typing `img` at the prompt) will automatically render it.
42
+
43
+ You can also run:
44
+ - `%icat status` to see whether integration is enabled
45
+ - `%icat off` to disable auto-rendering and restore the previous matplotlib backend (best-effort)
40
46
 
41
47
  ### Use as a Default Backend
42
48
 
43
49
  To set the kitty backend for matplotlib as the default, add the following lines to your IPython configuration file:
44
50
 
45
51
  1. `c.InteractiveShellApp.extensions = ['icat']`
46
- 2. `c.InteractiveShellApp.exec_lines = ['%plt_icat']`
52
+ 2. `c.InteractiveShellApp.exec_lines = ['%icat on']`
47
53
 
48
54
  #### Automatic Setup
49
55
 
@@ -69,7 +75,7 @@ python -m icat setup --profile myprofile
69
75
 
70
76
  ### Displaying Images
71
77
 
72
- To display an image file or a PIL Image object:
78
+ To display an image file, a PIL Image object, or a Python expression that evaluates to a PIL Image:
73
79
 
74
80
  ```python
75
81
  %icat path/to/your/image.jpg
@@ -83,10 +89,16 @@ img = Image.open('path/to/your/image.jpg')
83
89
  %icat img
84
90
  ```
85
91
 
92
+ Expressions work too:
93
+
94
+ ```python
95
+ %icat ds[0].image
96
+ ```
97
+
86
98
  You can also resize the image when displaying:
87
99
 
88
100
  ```python
89
- %icat path/to/your/image.jpg -w 300 -h 200
101
+ %icat path/to/your/image.jpg -W 300 -H 200
90
102
  ```
91
103
 
92
104
  ### Using Ghostty
@@ -0,0 +1,255 @@
1
+ import sys
2
+ from io import BytesIO
3
+ from os import getenv
4
+ from pathlib import Path
5
+ from subprocess import run
6
+ from typing import Optional
7
+
8
+ import matplotlib
9
+ from IPython.core.getipython import get_ipython
10
+ from IPython.core.magic import Magics, line_magic, magics_class
11
+ from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
12
+ from matplotlib import interactive, is_interactive
13
+ from matplotlib._pylab_helpers import Gcf
14
+ from matplotlib.backend_bases import FigureManagerBase, _Backend
15
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
16
+ from PIL import Image
17
+
18
+ if hasattr(sys, "ps1") or sys.flags.interactive:
19
+ interactive(True)
20
+
21
+
22
+ def _run(*cmd):
23
+ def f(*args, output=True, **kwargs):
24
+ if output:
25
+ kwargs["capture_output"] = True
26
+ kwargs["text"] = True
27
+ r = run(cmd + args, **kwargs)
28
+ if output:
29
+ return r.stdout.rstrip()
30
+
31
+ return f
32
+
33
+
34
+ _icat = _run("kitten", "icat", "--align", "left")
35
+
36
+
37
+ class FigureManagerICat(FigureManagerBase):
38
+ def show(self):
39
+ with BytesIO() as buf:
40
+ self.canvas.figure.savefig(buf, format="png")
41
+ _icat(output=False, input=buf.getbuffer())
42
+
43
+
44
+ class FigureCanvasICat(FigureCanvasAgg):
45
+ manager_class = FigureManagerICat
46
+
47
+
48
+ @_Backend.export
49
+ class _BackendICatAgg(_Backend):
50
+ FigureCanvas = FigureCanvasICat
51
+ FigureManager = FigureManagerICat
52
+ mainloop = lambda: None
53
+
54
+ @classmethod
55
+ def draw_if_interactive(cls):
56
+ manager = Gcf.get_active()
57
+ if is_interactive() and manager.canvas.figure.get_axes():
58
+ cls.show()
59
+
60
+ @classmethod
61
+ def show(cls, *args, **kwargs):
62
+ _Backend.show(*args, **kwargs)
63
+ Gcf.destroy_all()
64
+
65
+
66
+ @magics_class
67
+ class ICatMagics(Magics):
68
+ @magic_arguments()
69
+ @argument(
70
+ "target",
71
+ nargs="?",
72
+ help="Toggle on/off/status, a Python expression that evaluates to a PIL Image, or a path to an image file",
73
+ )
74
+ @argument("-W", "--width", type=int, help="Width to resize the image")
75
+ @argument("-H", "--height", type=int, help="Height to resize the image")
76
+ @line_magic
77
+ def icat(self, line):
78
+ args = parse_argstring(self.icat, line)
79
+ target = (args.target or "").strip()
80
+
81
+ if target in {"", "on"}:
82
+ _enable_session(self.shell)
83
+ return
84
+ if target == "off":
85
+ _disable_session(self.shell)
86
+ return
87
+ if target == "status":
88
+ _print_status(self.shell)
89
+ return
90
+
91
+ obj = _resolve_target(self.shell, target)
92
+ if obj is None:
93
+ print(
94
+ f"Error: could not resolve '{target}' as an image expression or file path."
95
+ )
96
+ return
97
+
98
+ img = _coerce_to_image(obj)
99
+ if img is None:
100
+ print(
101
+ f"Error: '{target}' did not evaluate to a PIL Image or readable image path."
102
+ )
103
+ return
104
+
105
+ # resize the image if width or height is specified
106
+ if args.width or args.height:
107
+ img.thumbnail((args.width or img.width, args.height or img.height))
108
+
109
+ # display image
110
+ with BytesIO() as buf:
111
+ img.save(buf, format="PNG")
112
+ _icat(output=False, input=buf.getbuffer())
113
+
114
+
115
+ def icat(img: Image.Image, width: Optional[int] = None, height: Optional[int] = None):
116
+ img_ = img.copy()
117
+ with BytesIO() as buf:
118
+ if width or height:
119
+ img_.thumbnail((width or img.width, height or img.height))
120
+ img_.save(buf, format="PNG")
121
+ _icat(output=False, input=buf.getbuffer())
122
+
123
+
124
+ def load_ipython_extension(ipython):
125
+ ipython.register_magics(ICatMagics)
126
+
127
+ auto = getenv("IPYTHON_ICAT_AUTO", "").strip().lower()
128
+ if auto in {"1", "true", "yes", "on"}:
129
+ _enable_session(ipython)
130
+
131
+
132
+ def _session_state(shell) -> dict:
133
+ return shell.user_ns.setdefault("_icat_state", {})
134
+
135
+
136
+ def _enable_session(shell) -> None:
137
+ state = _session_state(shell)
138
+ if state.get("enabled"):
139
+ return
140
+
141
+ try:
142
+ state["prev_mpl_backend"] = matplotlib.get_backend()
143
+ except Exception:
144
+ state["prev_mpl_backend"] = None
145
+
146
+ try:
147
+ matplotlib.use("module://icat")
148
+ print("icat: enabled matplotlib backend + PIL auto-render")
149
+ except Exception as e:
150
+ print(f"icat: failed to enable matplotlib backend: {e}")
151
+
152
+ try:
153
+ _enable_pil_autorender(shell)
154
+ except Exception as e:
155
+ print(f"icat: failed to enable PIL auto-render: {e}")
156
+
157
+ state["enabled"] = True
158
+
159
+
160
+ def _disable_session(shell) -> None:
161
+ state = _session_state(shell)
162
+ if not state.get("enabled"):
163
+ return
164
+
165
+ try:
166
+ _disable_pil_autorender(shell)
167
+ except Exception as e:
168
+ print(f"icat: failed to disable PIL auto-render: {e}")
169
+
170
+ prev_backend = state.get("prev_mpl_backend")
171
+ if prev_backend:
172
+ try:
173
+ matplotlib.use(prev_backend)
174
+ print(f"icat: restored matplotlib backend to {prev_backend!r}")
175
+ except Exception as e:
176
+ print(f"icat: failed to restore matplotlib backend {prev_backend!r}: {e}")
177
+
178
+ state.clear()
179
+
180
+
181
+ def _print_status(shell) -> None:
182
+ state = _session_state(shell)
183
+ enabled = bool(state.get("enabled"))
184
+ prev = state.get("prev_mpl_backend")
185
+ current = None
186
+ try:
187
+ current = matplotlib.get_backend()
188
+ except Exception:
189
+ pass
190
+ print(
191
+ f"icat: enabled={enabled}, matplotlib_backend={current!r}, prev_backend={prev!r}"
192
+ )
193
+
194
+
195
+ def _resolve_target(shell, target: str):
196
+ try:
197
+ return shell.ev(target)
198
+ except Exception:
199
+ pass
200
+
201
+ try:
202
+ path = Path(target).expanduser()
203
+ if path.is_file():
204
+ return path
205
+ except Exception:
206
+ pass
207
+
208
+ return None
209
+
210
+
211
+ def _coerce_to_image(obj):
212
+ if isinstance(obj, Image.Image):
213
+ return obj.copy()
214
+
215
+ if isinstance(obj, (str, Path)):
216
+ path = Path(obj).expanduser()
217
+ if path.is_file():
218
+ return Image.open(path)
219
+
220
+ return None
221
+
222
+
223
+ def _enable_pil_autorender(shell) -> None:
224
+ ip = get_ipython()
225
+ if ip is None:
226
+ ip = shell
227
+
228
+ state = _session_state(shell)
229
+ fmt = ip.display_formatter.formatters["text/plain"]
230
+
231
+ if "_prev_pil_printer_present" not in state:
232
+ state["_prev_pil_printer_present"] = Image.Image in fmt.type_printers
233
+ state["_prev_pil_printer"] = fmt.type_printers.get(Image.Image)
234
+
235
+ def _pil_printer(img, _pprinter, _cycle):
236
+ icat(img)
237
+ return f"<PIL.Image.Image size={img.size} mode={img.mode} (rendered by icat)>"
238
+
239
+ fmt.for_type(Image.Image, _pil_printer)
240
+
241
+
242
+ def _disable_pil_autorender(shell) -> None:
243
+ ip = get_ipython()
244
+ if ip is None:
245
+ ip = shell
246
+
247
+ state = _session_state(shell)
248
+ fmt = ip.display_formatter.formatters["text/plain"]
249
+
250
+ prev_present = bool(state.get("_prev_pil_printer_present"))
251
+ if not prev_present:
252
+ fmt.type_printers.pop(Image.Image, None)
253
+ return
254
+
255
+ fmt.for_type(Image.Image, state.get("_prev_pil_printer"))
@@ -1,7 +1,7 @@
1
1
  import re
2
2
  import subprocess
3
3
  from pathlib import Path
4
- from typing import List, Optional, Tuple
4
+ from typing import List, Optional, Tuple, Union
5
5
 
6
6
  from traitlets.config import Config
7
7
  from traitlets.config.loader import PyFileConfigLoader
@@ -54,8 +54,6 @@ def setup_ipython_profile(
54
54
  f.writelines(lines)
55
55
  except IOError as e:
56
56
  raise RuntimeError(f"Failed to write to config file {profile_path}: {e}")
57
- except PermissionError:
58
- raise RuntimeError(f"Permission denied when writing to {profile_path}")
59
57
 
60
58
  print(f"Successfully updated IPython config at {profile_path}")
61
59
  return True
@@ -71,7 +69,9 @@ def sanitize_profile_name(profile_name: str) -> str:
71
69
  return profile_name
72
70
 
73
71
 
74
- def get_profile_path(profile_name: str, ipython_path: Optional[str] = None) -> Path:
72
+ def get_profile_path(
73
+ profile_name: str, ipython_path: Optional[Union[str, Path]] = None
74
+ ) -> Path:
75
75
  """Silently create a default profile if it doesn't exist"""
76
76
  profile_name = sanitize_profile_name(profile_name)
77
77
 
@@ -87,7 +87,7 @@ def get_profile_path(profile_name: str, ipython_path: Optional[str] = None) -> P
87
87
  profile_dir = ipython_path / f"profile_{profile_name}"
88
88
  if not profile_dir.exists():
89
89
  try:
90
- subprocess.run(
90
+ _ = subprocess.run(
91
91
  ["ipython", "profile", "create", profile_name], check=True
92
92
  )
93
93
  except subprocess.CalledProcessError as e:
@@ -120,8 +120,8 @@ def dynamic_update_config(profile_path: Path) -> Tuple[str, str]:
120
120
  if "icat" not in extensions:
121
121
  extensions.append("icat")
122
122
 
123
- if "%plt_icat" not in exec_lines:
124
- exec_lines.append("%plt_icat")
123
+ if "%icat on" not in exec_lines and "%icat" not in exec_lines:
124
+ exec_lines.append("%icat on")
125
125
 
126
126
  extensions_line = f"c.InteractiveShellApp.extensions = {extensions}\n"
127
127
  exec_lines_line = f"c.InteractiveShellApp.exec_lines = {exec_lines}\n"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipython-icat
3
- Version: 0.3.1
3
+ Version: 0.4.1
4
4
  Summary: IPython magic command for displaying images in kitty terminal
5
5
  Author-email: Tony Kabilan Okeke <tonykabilanokeke@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/Kabilan108/ipython-icat
@@ -45,20 +45,26 @@ In your IPython session, load the extension:
45
45
 
46
46
  ### Displaying Matplotlib Plots
47
47
 
48
- To use the kitty backend for matplotlib:
48
+ To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
49
49
 
50
50
  ```python
51
- %plt_icat
51
+ %icat
52
52
  ```
53
53
 
54
- After running this command, any matplotlib plots you create will be displayed directly in your kitty terminal.
54
+ After running this command:
55
+ - Matplotlib plots will be displayed directly in your kitty-compatible terminal.
56
+ - Evaluating a `PIL.Image.Image` value (e.g. typing `img` at the prompt) will automatically render it.
57
+
58
+ You can also run:
59
+ - `%icat status` to see whether integration is enabled
60
+ - `%icat off` to disable auto-rendering and restore the previous matplotlib backend (best-effort)
55
61
 
56
62
  ### Use as a Default Backend
57
63
 
58
64
  To set the kitty backend for matplotlib as the default, add the following lines to your IPython configuration file:
59
65
 
60
66
  1. `c.InteractiveShellApp.extensions = ['icat']`
61
- 2. `c.InteractiveShellApp.exec_lines = ['%plt_icat']`
67
+ 2. `c.InteractiveShellApp.exec_lines = ['%icat on']`
62
68
 
63
69
  #### Automatic Setup
64
70
 
@@ -84,7 +90,7 @@ python -m icat setup --profile myprofile
84
90
 
85
91
  ### Displaying Images
86
92
 
87
- To display an image file or a PIL Image object:
93
+ To display an image file, a PIL Image object, or a Python expression that evaluates to a PIL Image:
88
94
 
89
95
  ```python
90
96
  %icat path/to/your/image.jpg
@@ -98,10 +104,16 @@ img = Image.open('path/to/your/image.jpg')
98
104
  %icat img
99
105
  ```
100
106
 
107
+ Expressions work too:
108
+
109
+ ```python
110
+ %icat ds[0].image
111
+ ```
112
+
101
113
  You can also resize the image when displaying:
102
114
 
103
115
  ```python
104
- %icat path/to/your/image.jpg -w 300 -h 200
116
+ %icat path/to/your/image.jpg -W 300 -H 200
105
117
  ```
106
118
 
107
119
  ### Using Ghostty
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ipython-icat"
3
- version = "0.3.1"
3
+ version = "0.4.1"
4
4
  description = "IPython magic command for displaying images in kitty terminal"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
@@ -1,114 +0,0 @@
1
- # modified from https://github.com/jktr/matplotlib-backend-kitty
2
-
3
- import sys
4
- from io import BytesIO
5
- from pathlib import Path
6
- from subprocess import run
7
-
8
- import matplotlib
9
- from IPython.core.magic import Magics, line_magic, magics_class
10
- from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
11
- from matplotlib import interactive, is_interactive
12
- from matplotlib._pylab_helpers import Gcf
13
- from matplotlib.backend_bases import FigureManagerBase, _Backend
14
- from matplotlib.backends.backend_agg import FigureCanvasAgg
15
- from PIL import Image
16
-
17
-
18
- if hasattr(sys, "ps1") or sys.flags.interactive:
19
- interactive(True)
20
-
21
-
22
- def _run(*cmd):
23
- def f(*args, output=True, **kwargs):
24
- if output:
25
- kwargs["capture_output"] = True
26
- kwargs["text"] = True
27
- r = run(cmd + args, **kwargs)
28
- if output:
29
- return r.stdout.rstrip()
30
-
31
- return f
32
-
33
-
34
- _icat = _run("kitten", "icat", "--align", "left")
35
-
36
-
37
- class FigureManagerICat(FigureManagerBase):
38
- def show(self):
39
- with BytesIO() as buf:
40
- self.canvas.figure.savefig(buf, format="png")
41
- _icat(output=False, input=buf.getbuffer())
42
-
43
-
44
- class FigureCanvasICat(FigureCanvasAgg):
45
- manager_class = FigureManagerICat
46
-
47
-
48
- @_Backend.export
49
- class _BackendICatAgg(_Backend):
50
- FigureCanvas = FigureCanvasICat
51
- FigureManager = FigureManagerICat
52
- mainloop = lambda: None
53
-
54
- @classmethod
55
- def draw_if_interactive(cls):
56
- manager = Gcf.get_active()
57
- if is_interactive() and manager.canvas.figure.get_axes():
58
- cls.show()
59
-
60
- @classmethod
61
- def show(cls, *args, **kwargs):
62
- _Backend.show(*args, **kwargs)
63
- Gcf.destroy_all()
64
-
65
-
66
- @magics_class
67
- class ICatMagics(Magics):
68
- @line_magic
69
- def plt_icat(self, line):
70
- matplotlib.use("module://icat")
71
- print("loaded icat backend for mpl")
72
-
73
- @magic_arguments()
74
- @argument("image", help="PIL Image object or path to image file")
75
- @argument("-w", "--width", type=int, help="Width to resize the image")
76
- @argument("-h", "--height", type=int, help="Height to resize the image")
77
- @line_magic
78
- def icat(self, line):
79
- args = parse_argstring(self.icat, line)
80
- image_arg = args.image.strip()
81
-
82
- # check if the input is a variable in the user's ns
83
- user_ns = self.shell.user_ns
84
- if image_arg in user_ns and isinstance(user_ns[image_arg], Image.Image):
85
- img = user_ns[image_arg]
86
- elif Path(image_arg).is_file():
87
- img = Image.open(image_arg)
88
- else:
89
- print(
90
- f"Error: '{image_arg}' is neither a valid PIL Image nor a path to an image file."
91
- )
92
- return
93
-
94
- # resize the image if width or height is specified
95
- if args.width or args.height:
96
- img.thumbnail((args.width or img.width, args.height or img.height))
97
-
98
- # display image
99
- with BytesIO() as buf:
100
- img.save(buf, format="PNG")
101
- _icat(output=False, input=buf.getbuffer())
102
-
103
-
104
- def icat(img: Image.Image, width: int = None, height: int = None):
105
- img_ = img.copy()
106
- with BytesIO() as buf:
107
- if width or height:
108
- img_.thumbnail((width or img.width, height or img.height))
109
- img_.save(buf, format="PNG")
110
- _icat(output=False, input=buf.getbuffer())
111
-
112
-
113
- def load_ipython_extension(ipython):
114
- ipython.register_magics(ICatMagics)
File without changes
File without changes