codewidget 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.
- codewidget/__init__.py +6 -0
- codewidget/cli.py +28 -0
- codewidget/renderer.py +102 -0
- codewidget/themes.py +30 -0
- codewidget/widget.py +80 -0
- codewidget-0.1.0.dist-info/METADATA +101 -0
- codewidget-0.1.0.dist-info/RECORD +10 -0
- codewidget-0.1.0.dist-info/WHEEL +4 -0
- codewidget-0.1.0.dist-info/entry_points.txt +2 -0
- codewidget-0.1.0.dist-info/licenses/LICENSE +21 -0
codewidget/__init__.py
ADDED
codewidget/cli.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .widget import CodeWidget
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main() -> None:
|
|
10
|
+
parser = argparse.ArgumentParser(description="Render source code as an SVG or HTML widget.")
|
|
11
|
+
parser.add_argument("input", type=Path, help="Source code file")
|
|
12
|
+
parser.add_argument("output", type=Path, help="Destination ending in .svg or .html")
|
|
13
|
+
parser.add_argument("--language", "-l", default="python", help="Pygments language alias")
|
|
14
|
+
parser.add_argument("--theme", default="dark", choices=("dark", "midnight", "light"))
|
|
15
|
+
parser.add_argument("--title", help="Window title shown above the code")
|
|
16
|
+
parser.add_argument("--no-line-numbers", action="store_true")
|
|
17
|
+
parser.add_argument("--font-size", type=int, default=18)
|
|
18
|
+
args = parser.parse_args()
|
|
19
|
+
|
|
20
|
+
widget = CodeWidget(
|
|
21
|
+
args.input.read_text(encoding="utf-8"),
|
|
22
|
+
language=args.language,
|
|
23
|
+
theme=args.theme,
|
|
24
|
+
title=args.title or args.input.name,
|
|
25
|
+
show_line_numbers=not args.no_line_numbers,
|
|
26
|
+
font_size=args.font_size,
|
|
27
|
+
)
|
|
28
|
+
widget.render(args.output)
|
codewidget/renderer.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""SVG rendering helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from html import escape
|
|
6
|
+
from pygments import lex
|
|
7
|
+
from pygments.lexers import get_lexer_by_name
|
|
8
|
+
from pygments.styles import get_style_by_name
|
|
9
|
+
from pygments.token import Token
|
|
10
|
+
|
|
11
|
+
from .themes import Theme
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _token_style(style, token):
|
|
15
|
+
token_style = style.style_for_token(token)
|
|
16
|
+
color = f"#{token_style['color']}" if token_style.get("color") else None
|
|
17
|
+
return color, token_style.get("bold", False), token_style.get("italic", False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _lines_with_spans(code: str, language: str, pygments_style: str):
|
|
21
|
+
lexer = get_lexer_by_name(language, stripnl=False, ensurenl=False)
|
|
22
|
+
style = get_style_by_name(pygments_style)
|
|
23
|
+
lines: list[list[tuple[str, str | None, bool, bool]]] = [[]]
|
|
24
|
+
for token, value in lex(code, lexer):
|
|
25
|
+
color, bold, italic = _token_style(style, token)
|
|
26
|
+
pieces = value.expandtabs(4).split("\n")
|
|
27
|
+
for index, piece in enumerate(pieces):
|
|
28
|
+
if piece:
|
|
29
|
+
lines[-1].append((piece, color, bold, italic))
|
|
30
|
+
if index < len(pieces) - 1:
|
|
31
|
+
lines.append([])
|
|
32
|
+
if code.endswith("\n") and len(lines) > 1 and not lines[-1]:
|
|
33
|
+
lines.pop()
|
|
34
|
+
return lines
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def render_svg(
|
|
38
|
+
code: str,
|
|
39
|
+
language: str,
|
|
40
|
+
theme: Theme,
|
|
41
|
+
*,
|
|
42
|
+
title: str,
|
|
43
|
+
show_line_numbers: bool,
|
|
44
|
+
font_size: int,
|
|
45
|
+
padding: int,
|
|
46
|
+
line_height: int,
|
|
47
|
+
radius: int,
|
|
48
|
+
) -> str:
|
|
49
|
+
lines = _lines_with_spans(code, language, theme.pygments_style)
|
|
50
|
+
columns = max((sum(len(part[0]) for part in line) for line in lines), default=0)
|
|
51
|
+
char_width = font_size * 0.62
|
|
52
|
+
number_width = (len(str(len(lines))) + 1) * char_width if show_line_numbers else 0
|
|
53
|
+
gutter = 16 if show_line_numbers else 0
|
|
54
|
+
header_height = max(48, font_size * 2.7)
|
|
55
|
+
code_width = max(columns, 1) * char_width
|
|
56
|
+
title_width = 68 + len(title or language) * font_size * 0.45
|
|
57
|
+
width = int(padding * 2 + number_width + gutter + max(code_width, title_width))
|
|
58
|
+
height = int(header_height + padding * 2 + max(len(lines), 1) * line_height)
|
|
59
|
+
code_x = padding + number_width + gutter
|
|
60
|
+
header_title = escape(title or language, quote=True)
|
|
61
|
+
chunks = [
|
|
62
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-label="{header_title} code widget">',
|
|
63
|
+
'<style>text{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace}</style>',
|
|
64
|
+
f'<rect width="{width}" height="{height}" rx="{radius}" fill="{theme.background}"/>',
|
|
65
|
+
f'<path d="M0 {header_height}H{width}" stroke="{theme.surface}" stroke-width="1"/>',
|
|
66
|
+
]
|
|
67
|
+
for index, color in enumerate(theme.dots):
|
|
68
|
+
chunks.append(f'<circle cx="{padding + index * 19 + 6}" cy="{header_height / 2}" r="5" fill="{color}"/>')
|
|
69
|
+
chunks.append(f'<text x="{padding + 68}" y="{header_height / 2 + font_size * 0.35}" font-size="{font_size * 0.78}" fill="{theme.muted}">{header_title}</text>')
|
|
70
|
+
|
|
71
|
+
for line_index, spans in enumerate(lines):
|
|
72
|
+
baseline = header_height + padding + font_size + line_index * line_height
|
|
73
|
+
if show_line_numbers:
|
|
74
|
+
chunks.append(f'<text x="{padding + number_width - char_width}" y="{baseline}" text-anchor="end" font-size="{font_size}" fill="{theme.muted}">{line_index + 1}</text>')
|
|
75
|
+
chunks.append(f'<text x="{code_x}" y="{baseline}" font-size="{font_size}" xml:space="preserve">')
|
|
76
|
+
offset = 0
|
|
77
|
+
for value, color, bold, italic in spans:
|
|
78
|
+
attrs = [f'x="{code_x + offset * char_width:.2f}"', f'fill="{color or theme.foreground}"']
|
|
79
|
+
if bold:
|
|
80
|
+
attrs.append('font-weight="700"')
|
|
81
|
+
if italic:
|
|
82
|
+
attrs.append('font-style="italic"')
|
|
83
|
+
chunks.append(f'<tspan {" ".join(attrs)}>{escape(value)}</tspan>')
|
|
84
|
+
offset += len(value)
|
|
85
|
+
chunks.append('</text>')
|
|
86
|
+
chunks.append('</svg>')
|
|
87
|
+
return "\n".join(chunks)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def render_html(svg: str, title: str) -> str:
|
|
91
|
+
safe_title = escape(title or "Code widget", quote=True)
|
|
92
|
+
return f'''<!doctype html>
|
|
93
|
+
<html lang="en">
|
|
94
|
+
<head>
|
|
95
|
+
<meta charset="utf-8">
|
|
96
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
97
|
+
<title>{safe_title}</title>
|
|
98
|
+
<style>html,body{{margin:0;min-height:100%;background:#09090b}}body{{display:grid;place-items:center;padding:4vw}}svg{{max-width:100%;height:auto;box-shadow:0 24px 80px #0008}}</style>
|
|
99
|
+
</head>
|
|
100
|
+
<body>{svg}</body>
|
|
101
|
+
</html>
|
|
102
|
+
'''
|
codewidget/themes.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Built-in visual palettes for code widgets."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Theme:
|
|
8
|
+
background: str
|
|
9
|
+
surface: str
|
|
10
|
+
foreground: str
|
|
11
|
+
muted: str
|
|
12
|
+
accent: str
|
|
13
|
+
dots: tuple[str, str, str]
|
|
14
|
+
pygments_style: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
THEMES = {
|
|
18
|
+
"dark": Theme("#0b1020", "#111a2e", "#dbe7ff", "#71809e", "#7c9cff", ("#ff5f57", "#febc2e", "#28c840"), "monokai"),
|
|
19
|
+
"midnight": Theme("#09090b", "#18181b", "#e4e4e7", "#71717a", "#a78bfa", ("#fb7185", "#fbbf24", "#34d399"), "dracula"),
|
|
20
|
+
"light": Theme("#f4f6fb", "#ffffff", "#202738", "#8790a0", "#5269d8", ("#ff5f57", "#febc2e", "#28c840"), "default"),
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_theme(name: str) -> Theme:
|
|
25
|
+
"""Return a named palette, with a useful error for unknown names."""
|
|
26
|
+
try:
|
|
27
|
+
return THEMES[name.lower()]
|
|
28
|
+
except (KeyError, AttributeError) as exc:
|
|
29
|
+
choices = ", ".join(sorted(THEMES))
|
|
30
|
+
raise ValueError(f"Unknown theme {name!r}. Choose one of: {choices}.") from exc
|
codewidget/widget.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Public CodeWidget API."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from .renderer import render_html, render_svg
|
|
6
|
+
from .themes import get_theme
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CodeWidget:
|
|
10
|
+
"""Turn source code into a styled, resolution-independent visual.
|
|
11
|
+
|
|
12
|
+
Example::
|
|
13
|
+
|
|
14
|
+
widget = CodeWidget(code="print('hello')", language="python")
|
|
15
|
+
widget.render("hello.svg")
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
code: str = "",
|
|
21
|
+
*,
|
|
22
|
+
language: str = "python",
|
|
23
|
+
theme: str = "dark",
|
|
24
|
+
title: str | None = None,
|
|
25
|
+
show_line_numbers: bool = True,
|
|
26
|
+
font_size: int = 18,
|
|
27
|
+
padding: int = 28,
|
|
28
|
+
line_height: int | None = None,
|
|
29
|
+
radius: int = 14,
|
|
30
|
+
) -> None:
|
|
31
|
+
if font_size < 8:
|
|
32
|
+
raise ValueError("font_size must be at least 8 pixels")
|
|
33
|
+
if padding < 0 or radius < 0:
|
|
34
|
+
raise ValueError("padding and radius cannot be negative")
|
|
35
|
+
self.code = code
|
|
36
|
+
self.language = language
|
|
37
|
+
self.theme = theme
|
|
38
|
+
self.title = title or language
|
|
39
|
+
self.show_line_numbers = show_line_numbers
|
|
40
|
+
self.font_size = font_size
|
|
41
|
+
self.padding = padding
|
|
42
|
+
self.line_height = line_height or int(font_size * 1.65)
|
|
43
|
+
self.radius = radius
|
|
44
|
+
|
|
45
|
+
def set_code(self, code: str) -> "CodeWidget":
|
|
46
|
+
"""Replace the source and return this widget for convenient chaining."""
|
|
47
|
+
self.code = code
|
|
48
|
+
return self
|
|
49
|
+
|
|
50
|
+
def to_svg(self) -> str:
|
|
51
|
+
"""Return the widget as an SVG document string."""
|
|
52
|
+
return render_svg(
|
|
53
|
+
self.code,
|
|
54
|
+
self.language,
|
|
55
|
+
get_theme(self.theme),
|
|
56
|
+
title=self.title,
|
|
57
|
+
show_line_numbers=self.show_line_numbers,
|
|
58
|
+
font_size=self.font_size,
|
|
59
|
+
padding=self.padding,
|
|
60
|
+
line_height=self.line_height,
|
|
61
|
+
radius=self.radius,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def to_html(self) -> str:
|
|
65
|
+
"""Return a standalone HTML page containing the SVG widget."""
|
|
66
|
+
return render_html(self.to_svg(), self.title)
|
|
67
|
+
|
|
68
|
+
def render(self, path: str | Path) -> Path:
|
|
69
|
+
"""Write an SVG or HTML file and return its path."""
|
|
70
|
+
destination = Path(path)
|
|
71
|
+
suffix = destination.suffix.lower()
|
|
72
|
+
if suffix == ".svg":
|
|
73
|
+
content = self.to_svg()
|
|
74
|
+
elif suffix in {".html", ".htm"}:
|
|
75
|
+
content = self.to_html()
|
|
76
|
+
else:
|
|
77
|
+
raise ValueError("Output must use the .svg, .html, or .htm extension")
|
|
78
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
destination.write_text(content, encoding="utf-8")
|
|
80
|
+
return destination
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: codewidget
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Create polished, resolution-independent code widgets for video and design.
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 CodeWidget contributors
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Keywords: code,graphics,svg,syntax-highlighting,video
|
|
28
|
+
Classifier: Development Status :: 3 - Alpha
|
|
29
|
+
Classifier: Intended Audience :: Developers
|
|
30
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
31
|
+
Classifier: Programming Language :: Python :: 3
|
|
32
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
33
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
34
|
+
Requires-Python: >=3.11
|
|
35
|
+
Requires-Dist: pygments<3,>=2.17
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# CodeWidget
|
|
39
|
+
|
|
40
|
+
**Create polished, resolution-independent code visuals for video and design.** CodeWidget turns source files into SVG widgets with syntax highlighting, line numbers, and a ready-made editor frame. SVG stays sharp when resized in editors such as Premiere, DaVinci Resolve, CapCut, OBS, or a video-generation workflow.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install codewidget
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
For development from this repository:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
python -m pip install -e .
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Python API
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from codewidget import CodeWidget
|
|
58
|
+
|
|
59
|
+
widget = CodeWidget(
|
|
60
|
+
language="cpp",
|
|
61
|
+
theme="midnight",
|
|
62
|
+
title="main.cpp",
|
|
63
|
+
font_size=20,
|
|
64
|
+
)
|
|
65
|
+
widget.set_code('''#include <iostream>
|
|
66
|
+
int main() {
|
|
67
|
+
std::cout << "Hello, video!";
|
|
68
|
+
}''')
|
|
69
|
+
widget.render("output/code.svg")
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
You can also initialize with code and get the SVG string directly:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
widget = CodeWidget("print('Hello, video!')", language="python")
|
|
76
|
+
svg = widget.to_svg()
|
|
77
|
+
html = widget.to_html()
|
|
78
|
+
widget.render("code.html")
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Themes included: `dark`, `midnight`, and `light`. Language names are Pygments lexer aliases, such as `python`, `javascript`, `typescript`, `cpp`, `rust`, `html`, and `bash`.
|
|
82
|
+
|
|
83
|
+
## Command line
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
codewidget example.py output/code.svg --language python --theme dark
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The output directory is created when needed. The current release writes SVG and standalone HTML; raster and video export can be added as optional integrations later.
|
|
90
|
+
|
|
91
|
+
## Development
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
python -m pip install -e .
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
CodeWidget requires Python 3.11 or newer and uses Pygments for syntax highlighting. SVG rendering has no browser, Node.js, or video-library requirement.
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
codewidget/__init__.py,sha256=fn7LN-NTMwZaZA0s3BBrG5eRz8v6oHsdS1xK0jlfrZU,128
|
|
2
|
+
codewidget/cli.py,sha256=7lFdyZc7JhclwzySutrX-WCbgd-g6cfwt0WsNyfhH10,1102
|
|
3
|
+
codewidget/renderer.py,sha256=xcOjokuBzynr2bM9oBrASAOmZl5Zpo9d8PAQehcXrcM,4464
|
|
4
|
+
codewidget/themes.py,sha256=a0vHJTFQIMAqdmAttOcfCEwENa3G8khzMVF4dY4XOl4,979
|
|
5
|
+
codewidget/widget.py,sha256=j7pAle7np6WzK4qpx4QVoZK1Ipy4LVkPgyWvFyGZOfw,2579
|
|
6
|
+
codewidget-0.1.0.dist-info/METADATA,sha256=qa7Sqsyd6I_x2uG40piezvoKQZ851didkQ8kUu4S0WI,3515
|
|
7
|
+
codewidget-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
codewidget-0.1.0.dist-info/entry_points.txt,sha256=WYhxqhnJ5T-UjtZA-6Aq_SGfaafMiHmdRCUpZ8L5h94,51
|
|
9
|
+
codewidget-0.1.0.dist-info/licenses/LICENSE,sha256=ySE9luTCvSW2OqMqIDSFS8oAhDedffHctqqD7yrUeXw,1080
|
|
10
|
+
codewidget-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CodeWidget contributors
|
|
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.
|