snipc 0.1.0__py3-none-any.whl

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.
snipc/__init__.py ADDED
File without changes
snipc/cli.py ADDED
@@ -0,0 +1,236 @@
1
+ import io
2
+ import platform
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import typer
10
+ from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont
11
+ from pygments import highlight
12
+ from pygments.formatters import ImageFormatter
13
+ from pygments.lexers import TextLexer, get_lexer_for_filename
14
+ from pygments.styles import get_all_styles
15
+ from pygments.util import ClassNotFound
16
+
17
+ app = typer.Typer(
18
+ help="Generate aesthetic code snippet cards straight from your terminal.",
19
+ no_args_is_help=True,
20
+ )
21
+
22
+ GRADIENTS: dict[str, tuple[str, str]] = {
23
+ "ocean": ("#2193b0", "#6dd5ed"),
24
+ "sunset": ("#ee0979", "#ff6a00"),
25
+ "emerald": ("#11998e", "#38ef7d"),
26
+ "cyberpunk": ("#8e2de2", "#4a00e0"),
27
+ "peach": ("#ff9a9e", "#fecfef"),
28
+ "midnight": ("#232526", "#414345"),
29
+ }
30
+
31
+
32
+ def create_background(width: int, height: int, bg: str) -> Image.Image:
33
+ """Create a solid color or vertical linear gradient background."""
34
+ if bg.lower() in GRADIENTS:
35
+ c1, c2 = GRADIENTS[bg.lower()]
36
+ r1, g1, b1 = ImageColor.getrgb(c1)
37
+ r2, g2, b2 = ImageColor.getrgb(c2)
38
+
39
+ base = Image.new("RGBA", (width, height))
40
+ draw = ImageDraw.Draw(base)
41
+ for y in range(height):
42
+ ratio = y / max(height - 1, 1)
43
+ r = int(r1 + (r2 - r1) * ratio)
44
+ g = int(g1 + (g2 - g1) * ratio)
45
+ b = int(b1 + (b2 - b1) * ratio)
46
+ draw.line([(0, y), (width, y)], fill=(r, g, b, 255))
47
+ return base
48
+
49
+ try:
50
+ return Image.new("RGBA", (width, height), bg)
51
+ except ValueError:
52
+ typer.secho(f"Unknown color or gradient: {bg}", fg=typer.colors.RED)
53
+ raise typer.Exit(code=1)
54
+
55
+
56
+ def extract_lines(code: str, lines_range: Optional[str]) -> str:
57
+ """Slice code by line range (e.g., '10:25')."""
58
+ if not lines_range:
59
+ return code
60
+ try:
61
+ start_str, end_str = lines_range.split(":")
62
+ lines = code.splitlines()
63
+ start = int(start_str) - 1 if start_str else 0
64
+ end = int(end_str) if end_str else len(lines)
65
+ return "\n".join(lines[start:end])
66
+ except ValueError:
67
+ typer.secho("Invalid --lines format. Use START:END (e.g., 10:25)", fg=typer.colors.RED)
68
+ raise typer.Exit(code=1)
69
+
70
+
71
+ def copy_image_to_clipboard(image_path: Path) -> bool:
72
+ """Copy PNG image to system clipboard (Linux Wayland/X11, macOS, Windows)."""
73
+ system = platform.system()
74
+ abs_path = str(image_path.resolve())
75
+
76
+ try:
77
+ if system == "Linux":
78
+ if shutil.which("wl-copy"):
79
+ with open(abs_path, "rb") as f:
80
+ subprocess.run(["wl-copy", "--type", "image/png"], stdin=f, check=True)
81
+ return True
82
+ if shutil.which("xclip"):
83
+ subprocess.run(
84
+ ["xclip", "-selection", "clipboard", "-t", "image/png", "-i", abs_path],
85
+ check=True,
86
+ )
87
+ return True
88
+ elif system == "Darwin":
89
+ script = f'set the clipboard to (read (POSIX file "{abs_path}") as «class PNGf»)'
90
+ subprocess.run(["osascript", "-e", script], check=True)
91
+ return True
92
+ elif system == "Windows":
93
+ ps_cmd = (
94
+ f"Add-Type -AssemblyName System.Windows.Forms; "
95
+ f"[System.Windows.Forms.Clipboard]::SetImage([System.Drawing.Image]::FromFile('{abs_path}'))"
96
+ )
97
+ subprocess.run(["powershell", "-Command", ps_cmd], check=True)
98
+ return True
99
+ except subprocess.CalledProcessError:
100
+ return False
101
+
102
+ return False
103
+
104
+
105
+ def add_window_frame(
106
+ code_img: Image.Image,
107
+ bg: str = "cyberpunk",
108
+ title: Optional[str] = None,
109
+ ) -> Image.Image:
110
+ padding = 55
111
+ header_height = 42
112
+ radius = 14
113
+
114
+ window_bg = code_img.getpixel((0, 0))
115
+ win_w = max(code_img.width + 40, 260)
116
+ win_h = code_img.height + header_height + 20
117
+
118
+ total_w = win_w + padding * 2
119
+ total_h = win_h + padding * 2
120
+
121
+ canvas = create_background(total_w, total_h, bg)
122
+
123
+
124
+ shadow = Image.new("RGBA", (total_w, total_h), (0, 0, 0, 0))
125
+ shadow_draw = ImageDraw.Draw(shadow)
126
+ shadow_box = [padding, padding + 14, padding + win_w, padding + win_h + 14]
127
+ shadow_draw.rounded_rectangle(shadow_box, radius=radius, fill=(0, 0, 0, 120))
128
+ shadow = shadow.filter(ImageFilter.GaussianBlur(radius=20))
129
+ canvas = Image.alpha_composite(canvas, shadow)
130
+
131
+
132
+ draw = ImageDraw.Draw(canvas)
133
+ win_box = [padding, padding, padding + win_w, padding + win_h]
134
+ draw.rounded_rectangle(win_box, radius=radius, fill=window_bg)
135
+
136
+
137
+ colors = ["#ff5f56", "#ffbd2e", "#27c93f"]
138
+ for i, color in enumerate(colors):
139
+ cx = padding + 22 + i * 22
140
+ cy = padding + 21
141
+ draw.ellipse([cx - 6, cy - 6, cx + 6, cy + 6], fill=color)
142
+
143
+
144
+ if title:
145
+ brightness = sum(window_bg[:3]) / 3
146
+ text_color = (180, 180, 180, 220) if brightness < 128 else (90, 90, 90, 220)
147
+ font = ImageFont.load_default()
148
+ bbox = draw.textbbox((0, 0), title, font=font)
149
+ text_w = bbox[2] - bbox[0]
150
+ text_x = padding + (win_w - text_w) // 2
151
+ text_y = padding + 15
152
+ draw.text((text_x, text_y), title, fill=text_color, font=font)
153
+
154
+ canvas.paste(code_img, (padding + 20, padding + header_height))
155
+ return canvas
156
+
157
+
158
+ def list_themes_callback(value: bool):
159
+ if value:
160
+ themes = ", ".join(sorted(get_all_styles()))
161
+ typer.echo(f"Available themes:\n{themes}\n")
162
+ typer.echo(f"Available gradients:\n{', '.join(GRADIENTS.keys())}")
163
+ raise typer.Exit()
164
+
165
+
166
+ @app.command()
167
+ def render(
168
+ file_path: Path = typer.Argument(..., exists=True, help="Path to the source code file"),
169
+ output: Optional[Path] = typer.Option(None, "--out", "-o", help="Output PNG file path (defaults to snippet.png)"),
170
+ theme: str = typer.Option("dracula", "--theme", "-t", help="Syntax highlighting theme"),
171
+ bg: str = typer.Option("cyberpunk", "--bg", help="HEX color or gradient (ocean, sunset, emerald, cyberpunk, peach, midnight)"),
172
+ lines: Optional[str] = typer.Option(None, "--lines", "-l", help="Line range to capture (e.g., 1:25)"),
173
+ line_numbers: bool = typer.Option(False, "--numbers", "-n", help="Show line numbers"),
174
+ no_title: bool = typer.Option(False, "--no-title", help="Hide filename in the window header"),
175
+ copy: bool = typer.Option(False, "--copy", "-c", help="Copy image directly to clipboard"),
176
+ font: Optional[str] = typer.Option(None, "--font", "-f", help="System font family name (e.g., 'JetBrains Mono')"),
177
+ list_themes: Optional[bool] = typer.Option(
178
+ None, "--list-themes", callback=list_themes_callback, is_eager=True, help="List all available themes and gradients"
179
+ ),
180
+ ):
181
+ """Render a code file into an aesthetic PNG image."""
182
+ raw_code = file_path.read_text(encoding="utf-8")
183
+ code = extract_lines(raw_code, lines)
184
+
185
+ try:
186
+ lexer = get_lexer_for_filename(file_path.name)
187
+ except ClassNotFound:
188
+ lexer = TextLexer()
189
+
190
+ formatter_kwargs = {
191
+ "style": theme,
192
+ "line_numbers": line_numbers,
193
+ "font_size": 20,
194
+ "image_pad": 10,
195
+ }
196
+ if font:
197
+ formatter_kwargs["font_name"] = font
198
+
199
+ try:
200
+ formatter = ImageFormatter(**formatter_kwargs)
201
+ except ClassNotFound:
202
+ typer.secho(f"Theme '{theme}' not found. Run --list-themes to see available options.", fg=typer.colors.RED)
203
+ raise typer.Exit(code=1)
204
+
205
+ img_bytes = highlight(code, lexer, formatter)
206
+ code_img = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
207
+
208
+ title = None if no_title else file_path.name
209
+ final_img = add_window_frame(code_img, bg=bg, title=title)
210
+
211
+
212
+ if copy and output is None:
213
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
214
+ tmp_path = Path(tmp.name)
215
+ final_img.save(tmp_path)
216
+ if copy_image_to_clipboard(tmp_path):
217
+ typer.secho("Copied snippet image to clipboard!", fg=typer.colors.CYAN)
218
+ else:
219
+ typer.secho("Clipboard copy failed (install wl-clipboard or xclip on Linux).", fg=typer.colors.YELLOW)
220
+ tmp_path.unlink(missing_ok=True)
221
+ return
222
+
223
+ target_path = output or Path("snippet.png")
224
+ final_img.save(target_path)
225
+ typer.secho(f"Saved snippet to {target_path}", fg=typer.colors.GREEN)
226
+
227
+ if copy:
228
+ if copy_image_to_clipboard(target_path):
229
+ typer.secho("Copied snippet image to clipboard!", fg=typer.colors.CYAN)
230
+ else:
231
+ typer.secho("Clipboard copy failed (install wl-clipboard or xclip on Linux).", fg=typer.colors.YELLOW)
232
+
233
+
234
+ if __name__ == "__main__":
235
+ app()
236
+
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: snipc
3
+ Version: 0.1.0
4
+ Summary: Generate aesthetic code snippet cards straight from your terminal
5
+ Author: GraffGit
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/GraffGit/snipc
8
+ Project-URL: Repository, https://github.com/GraffGit/snipc
9
+ Project-URL: Issues, https://github.com/GraffGit/snipc/issues
10
+ Keywords: cli,code,screenshot,snippet,syntax-highlighting
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Multimedia :: Graphics
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: typer>=0.12.0
21
+ Requires-Dist: pygments>=2.17.0
22
+ Requires-Dist: pillow>=10.0.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
25
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
26
+ Requires-Dist: build>=1.2.0; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # snipc
30
+
31
+ ![CI](https://github.com/GraffGit/snipc/actions/workflows/ci.yml/badge.svg)
32
+ ![Python](https://shields.io/badge/python-3.10%2B-blue)
33
+ ![License](https://shields.io/badge/license-MIT-green)
34
+
35
+ A fast, zero-browser CLI tool to turn your code snippets into aesthetic images straight from your terminal.
36
+
37
+ ![Demo Snippet](assets/demo.png)
38
+
39
+ ## Features
40
+ - **500+ Languages** — automatic syntax highlighting powered by Pygments.
41
+ - **Built-in Gradients & Custom Colors** — choose from `ocean`, `sunset`, `emerald`, `cyberpunk`, `peach`, `midnight`, or pass any HEX color.
42
+ - **Line Slicing** — capture only the relevant lines of a file (`--lines 10:25`).
43
+ - **Clipboard Support** — copy generated images directly to your clipboard (`--copy`) on Linux (Wayland/X11), macOS, and Windows.
44
+ - **macOS-style Window Frame** — soft drop shadows and auto-detected file title in the header.
45
+
46
+ ## Installation
47
+
48
+ Recommended via `pipx` or `uv`:
49
+
50
+ ```bash
51
+ pipx install git+https://github.com/GraffGit/snipc.git
52
+ ```
53
+
54
+ Or using standard `pip`:
55
+
56
+ ```bash
57
+ pip install git+https://github.com/GraffGit/snipc.git
58
+ ```
59
+
60
+ > **Note for Linux users:** To use the `--copy` flag, make sure you have `wl-clipboard` (Wayland) or `xclip` (X11) installed.
61
+
62
+ ## Usage
63
+
64
+ Generate a snippet card with default settings (`snippet.png`):
65
+ ```bash
66
+ snipc main.py
67
+ ```
68
+
69
+ Customize theme, gradient background, line range, and copy directly to clipboard without saving a file:
70
+ ```bash
71
+ snipc src/app.py --theme monokai --bg sunset --lines 15:40 --copy
72
+ ```
73
+
74
+ Save to a specific path with line numbers and a custom system font:
75
+ ```bash
76
+ snipc main.cpp -o card.png -n -f "JetBrains Mono"
77
+ ```
78
+
79
+ List all available syntax themes and gradients:
80
+ ```bash
81
+ snipc --list-themes
82
+ ```
83
+
84
+ ## Options
85
+
86
+ | Option | Short | Description | Default |
87
+ | :--- | :---: | :--- | :--- |
88
+ | `--out` | `-o` | Output PNG file path | `snippet.png` |
89
+ | `--theme` | `-t` | Syntax highlighting theme | `dracula` |
90
+ | `--bg` | | HEX color or built-in gradient name | `cyberpunk` |
91
+ | `--lines` | `-l` | Line range to capture (e.g., `1:25`) | All lines |
92
+ | `--numbers` | `-n` | Show line numbers | `False` |
93
+ | `--no-title` | | Hide filename in the window header | `False` |
94
+ | `--copy` | `-c` | Copy image directly to clipboard | `False` |
95
+ | `--font` | `-f` | Custom system font family name | System default |
96
+ | `--list-themes` | | Show all available themes and gradients | |
97
+
98
+ ## License
99
+
100
+ MIT
@@ -0,0 +1,8 @@
1
+ snipc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ snipc/cli.py,sha256=F7gk6g-UZ5LbbpzbKLJ8OoHpX6eWn1Y5wXiOGaI_3c0,8703
3
+ snipc-0.1.0.dist-info/licenses/LICENSE,sha256=YBIFLZc0Lp-y2n6HNsx0aLpkE0Bfen4RSaMMga4N0n8,1065
4
+ snipc-0.1.0.dist-info/METADATA,sha256=-SsX0fA1nfevMLFGgqGZeuEruSZr54c8NEJzCiQgdH4,3393
5
+ snipc-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ snipc-0.1.0.dist-info/entry_points.txt,sha256=PlieYGbN9WSzGZaWmzJehEUYECL8zjp89ALiod9Rti4,40
7
+ snipc-0.1.0.dist-info/top_level.txt,sha256=gUWdTG7JLFoIdpY0Rwt2PwDFcDvnORAPBU5VjN1GJjw,6
8
+ snipc-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ snipc = snipc.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GraffGit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ snipc