vietsvg 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.
- vietsvg/__init__.py +6 -0
- vietsvg/cli.py +104 -0
- vietsvg/core.py +288 -0
- vietsvg/grok_proofread.py +60 -0
- vietsvg-0.1.0.dist-info/METADATA +91 -0
- vietsvg-0.1.0.dist-info/RECORD +10 -0
- vietsvg-0.1.0.dist-info/WHEEL +5 -0
- vietsvg-0.1.0.dist-info/entry_points.txt +2 -0
- vietsvg-0.1.0.dist-info/licenses/LICENSE +21 -0
- vietsvg-0.1.0.dist-info/top_level.txt +1 -0
vietsvg/__init__.py
ADDED
vietsvg/cli.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""VietSVG command-line interface.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
vietsvg check <file.svg>
|
|
5
|
+
vietsvg finish <file.svg> [--fix fixes.json] [--render] [--grok-proofread]
|
|
6
|
+
|
|
7
|
+
`check` prints the diacritic risk report without modifying anything.
|
|
8
|
+
`finish` writes <stem>-finished.svg next to the input: tightly cropped,
|
|
9
|
+
with confirmed fixes applied. --grok-proofread additionally asks Grok
|
|
10
|
+
(BYOK via XAI_API_KEY) for fix suggestions and writes them to
|
|
11
|
+
<stem>-fixes.suggested.json for human confirmation; suggestions are
|
|
12
|
+
never applied automatically.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from .core import analyze_svg_text, finish_svg_text
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _print_report(report: dict) -> None:
|
|
25
|
+
if not report["valid"]:
|
|
26
|
+
print(f"XML: INVALID - {report['error']}")
|
|
27
|
+
return
|
|
28
|
+
print("XML: valid")
|
|
29
|
+
print(f"viewBox: {report['viewBox_before']} -> suggested {report['viewBox_suggested']}")
|
|
30
|
+
print(f"Text nodes ({len(report['texts'])}):")
|
|
31
|
+
for item in report["texts"]:
|
|
32
|
+
print(f" - {item['text']!r}")
|
|
33
|
+
for flag in item["flags"]:
|
|
34
|
+
print(f" ! {flag}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cmd_check(args) -> int:
|
|
38
|
+
raw = Path(args.file).read_text(encoding="utf-8")
|
|
39
|
+
report = analyze_svg_text(raw)
|
|
40
|
+
_print_report(report)
|
|
41
|
+
return 0 if report["valid"] else 1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def cmd_finish(args) -> int:
|
|
45
|
+
src = Path(args.file)
|
|
46
|
+
raw = src.read_text(encoding="utf-8")
|
|
47
|
+
fixes = {}
|
|
48
|
+
if args.fix:
|
|
49
|
+
fixes = json.loads(Path(args.fix).read_text(encoding="utf-8"))
|
|
50
|
+
out_raw, report = finish_svg_text(raw, fixes)
|
|
51
|
+
_print_report(report)
|
|
52
|
+
if not report["valid"]:
|
|
53
|
+
return 1
|
|
54
|
+
for wrong, right in report.get("fixes_applied", {}).items():
|
|
55
|
+
print(f"fix: {wrong!r} -> {right!r}")
|
|
56
|
+
out = src.with_name(src.stem + "-finished.svg")
|
|
57
|
+
out.write_text(out_raw, encoding="utf-8")
|
|
58
|
+
print(f"Wrote: {out} ({len(out_raw.encode('utf-8')):,} bytes)")
|
|
59
|
+
|
|
60
|
+
if args.grok_proofread:
|
|
61
|
+
from .grok_proofread import suggest_fixes
|
|
62
|
+
texts = [t["text"] for t in report["texts"]]
|
|
63
|
+
try:
|
|
64
|
+
suggestions = suggest_fixes(texts)
|
|
65
|
+
except Exception as e: # noqa: BLE001 - surface any proofreader failure plainly
|
|
66
|
+
print(f"Grok proofread failed: {e}", file=sys.stderr)
|
|
67
|
+
return 1
|
|
68
|
+
sug = src.with_name(src.stem + "-fixes.suggested.json")
|
|
69
|
+
sug.write_text(json.dumps(suggestions, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
70
|
+
print(f"Grok suggestions ({len(suggestions)}): {sug}")
|
|
71
|
+
print("Review them, then re-run with --fix on the confirmed subset.")
|
|
72
|
+
|
|
73
|
+
if args.render:
|
|
74
|
+
try:
|
|
75
|
+
import cairosvg
|
|
76
|
+
except ImportError:
|
|
77
|
+
print("Render needs cairosvg: pip install 'vietsvg[render]'", file=sys.stderr)
|
|
78
|
+
return 1
|
|
79
|
+
png = src.with_name(src.stem + "-finished.png")
|
|
80
|
+
cairosvg.svg2png(bytestring=out_raw.encode("utf-8"), write_to=str(png),
|
|
81
|
+
output_width=1024, background_color="white")
|
|
82
|
+
print(f"Rendered: {png}")
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main(argv=None) -> int:
|
|
87
|
+
parser = argparse.ArgumentParser(prog="vietsvg", description=__doc__)
|
|
88
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
89
|
+
p_check = sub.add_parser("check", help="report diacritic risks, change nothing")
|
|
90
|
+
p_check.add_argument("file")
|
|
91
|
+
p_check.set_defaults(func=cmd_check)
|
|
92
|
+
p_finish = sub.add_parser("finish", help="crop tightly and apply confirmed fixes")
|
|
93
|
+
p_finish.add_argument("file")
|
|
94
|
+
p_finish.add_argument("--fix", help="JSON mapping of confirmed {wrong: right} fixes")
|
|
95
|
+
p_finish.add_argument("--render", action="store_true", help="also render a PNG proof")
|
|
96
|
+
p_finish.add_argument("--grok-proofread", action="store_true",
|
|
97
|
+
help="ask Grok (XAI_API_KEY) for fix suggestions to confirm")
|
|
98
|
+
p_finish.set_defaults(func=cmd_finish)
|
|
99
|
+
args = parser.parse_args(argv)
|
|
100
|
+
return args.func(args)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
sys.exit(main())
|
vietsvg/core.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Core SVG finishing logic for VietSVG.
|
|
2
|
+
|
|
3
|
+
Born from a real workflow (December 2026): image-to-SVG models such as
|
|
4
|
+
Baidu's Unlimited-SVG produce editable SVG with real <text> nodes, but
|
|
5
|
+
they shrink content into the middle of a large canvas and mangle
|
|
6
|
+
Vietnamese stacked diacritics (vowel mark + tone, e.g. the ằ ầ ề ồ ờ ừ
|
|
7
|
+
families). In our full-diacritics test nearly every stacked instance
|
|
8
|
+
broke, ê-family tones drifted, and the caron ǎ appeared even though it
|
|
9
|
+
never occurs in Vietnamese.
|
|
10
|
+
|
|
11
|
+
This module therefore:
|
|
12
|
+
1. validates the XML,
|
|
13
|
+
2. computes the content bounding box (ignoring a full-canvas
|
|
14
|
+
background),
|
|
15
|
+
3. rewrites the root viewBox to crop tightly around the content,
|
|
16
|
+
4. lists every <text> node and flags suspicious Vietnamese
|
|
17
|
+
diacritics by risk tier,
|
|
18
|
+
5. applies only human-confirmed text fixes (never guessed).
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from xml.etree import ElementTree
|
|
24
|
+
|
|
25
|
+
PAD = 12.0
|
|
26
|
+
NUM = re.compile(r"-?\d*\.?\d+(?:[eE][-+]?\d+)?")
|
|
27
|
+
|
|
28
|
+
# Diacritic risk tiers from the 2026-12-05 full-diacritics test:
|
|
29
|
+
# caron/ë never occur in Vietnamese; stacked diacritics (vowel mark +
|
|
30
|
+
# tone) broke in nearly every instance; single tones and đ mostly held.
|
|
31
|
+
DEFINITE_BAD = set("ǎǐǒǔǍǏǑǓëË")
|
|
32
|
+
STACKED = set(
|
|
33
|
+
"ằắẳẵặầấẩẫậềếểễệồốổỗộờớởỡợừứửữự"
|
|
34
|
+
"ẰẮẲẴẶẦẤẨẪẬỀẾỂỄỆỒỐỔỖỘỜỚỞỠỢỪỨỬỮỰ"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def fnum(v, default=0.0):
|
|
39
|
+
try:
|
|
40
|
+
return float(str(v).strip().rstrip("px"))
|
|
41
|
+
except Exception:
|
|
42
|
+
return default
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _tag(el) -> str:
|
|
46
|
+
return el.tag.rsplit("}", 1)[-1]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def parse_transform(t):
|
|
50
|
+
"""Return (tx, ty, sx, sy) for translate/scale/matrix transforms."""
|
|
51
|
+
tx = ty = 0.0
|
|
52
|
+
sx = sy = 1.0
|
|
53
|
+
if not t:
|
|
54
|
+
return tx, ty, sx, sy
|
|
55
|
+
m = re.search(r"translate\(\s*([^)]+)\)", t)
|
|
56
|
+
if m:
|
|
57
|
+
parts = [fnum(x) for x in NUM.findall(m.group(1))]
|
|
58
|
+
tx = parts[0] if parts else 0.0
|
|
59
|
+
ty = parts[1] if len(parts) > 1 else 0.0
|
|
60
|
+
m = re.search(r"scale\(\s*([^)]+)\)", t)
|
|
61
|
+
if m:
|
|
62
|
+
parts = [fnum(x) for x in NUM.findall(m.group(1))]
|
|
63
|
+
sx = parts[0] if parts else 1.0
|
|
64
|
+
sy = parts[1] if len(parts) > 1 else sx
|
|
65
|
+
m = re.search(r"matrix\(\s*([^)]+)\)", t)
|
|
66
|
+
if m:
|
|
67
|
+
p = [fnum(x) for x in NUM.findall(m.group(1))]
|
|
68
|
+
if len(p) == 6:
|
|
69
|
+
sx, sy, tx, ty = p[0], p[3], p[4], p[5]
|
|
70
|
+
return tx, ty, sx, sy
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def path_points(d):
|
|
74
|
+
"""Collect coordinate points from path data, honouring commands.
|
|
75
|
+
|
|
76
|
+
Endpoints and control points are collected; arcs also add a point
|
|
77
|
+
expanded by their radii around the chord midpoint (a safe
|
|
78
|
+
overestimate).
|
|
79
|
+
"""
|
|
80
|
+
tokens = re.findall(r"[MmLlHhVvCcSsQqTtAaZz]|-?\d*\.?\d+(?:[eE][-+]?\d+)?", d)
|
|
81
|
+
pts = []
|
|
82
|
+
i = 0
|
|
83
|
+
cx = cy = 0.0
|
|
84
|
+
sx = sy = 0.0
|
|
85
|
+
cmd = None
|
|
86
|
+
arity = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "T": 2, "A": 7}
|
|
87
|
+
|
|
88
|
+
def take(n):
|
|
89
|
+
nonlocal i
|
|
90
|
+
vals = [fnum(x) for x in tokens[i:i + n]]
|
|
91
|
+
i += n
|
|
92
|
+
return vals
|
|
93
|
+
|
|
94
|
+
while i < len(tokens):
|
|
95
|
+
tok = tokens[i]
|
|
96
|
+
if re.fullmatch(r"[A-Za-z]", tok):
|
|
97
|
+
cmd = tok
|
|
98
|
+
i += 1
|
|
99
|
+
if cmd in "Zz":
|
|
100
|
+
cx, cy = sx, sy
|
|
101
|
+
pts.append((cx, cy))
|
|
102
|
+
cmd = None
|
|
103
|
+
continue
|
|
104
|
+
if cmd is None:
|
|
105
|
+
i += 1
|
|
106
|
+
continue
|
|
107
|
+
rel = cmd.islower()
|
|
108
|
+
up = cmd.upper()
|
|
109
|
+
if up == "H":
|
|
110
|
+
(v,) = take(1)
|
|
111
|
+
cx = cx + v if rel else v
|
|
112
|
+
pts.append((cx, cy))
|
|
113
|
+
elif up == "V":
|
|
114
|
+
(v,) = take(1)
|
|
115
|
+
cy = cy + v if rel else v
|
|
116
|
+
pts.append((cx, cy))
|
|
117
|
+
elif up == "A":
|
|
118
|
+
rx, ry, _rot, _la, _sw, x, y = take(7)
|
|
119
|
+
nx, ny = (cx + x, cy + y) if rel else (x, y)
|
|
120
|
+
mx, my = (cx + nx) / 2, (cy + ny) / 2
|
|
121
|
+
pts += [(cx, cy), (nx, ny), (mx - rx, my - ry), (mx + rx, my + ry)]
|
|
122
|
+
cx, cy = nx, ny
|
|
123
|
+
else:
|
|
124
|
+
vals = take(arity[up])
|
|
125
|
+
for j in range(0, len(vals) - 1, 2):
|
|
126
|
+
x, y = vals[j], vals[j + 1]
|
|
127
|
+
pts.append((cx + x, cy + y) if rel else (x, y))
|
|
128
|
+
x, y = vals[-2], vals[-1]
|
|
129
|
+
cx, cy = (cx + x, cy + y) if rel else (x, y)
|
|
130
|
+
if up == "M":
|
|
131
|
+
sx, sy = cx, cy
|
|
132
|
+
cmd = "l" if rel else "L"
|
|
133
|
+
return pts
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def bbox_of(el):
|
|
137
|
+
"""Bounding box of one element in local coords, or None."""
|
|
138
|
+
tag = _tag(el)
|
|
139
|
+
a = el.attrib
|
|
140
|
+
if tag in ("rect", "image"):
|
|
141
|
+
x, y = fnum(a.get("x")), fnum(a.get("y"))
|
|
142
|
+
w, h = fnum(a.get("width")), fnum(a.get("height"))
|
|
143
|
+
return (x, y, x + w, y + h) if w > 0 and h > 0 else None
|
|
144
|
+
if tag == "circle":
|
|
145
|
+
cx, cy, r = fnum(a.get("cx")), fnum(a.get("cy")), fnum(a.get("r"))
|
|
146
|
+
return (cx - r, cy - r, cx + r, cy + r)
|
|
147
|
+
if tag == "ellipse":
|
|
148
|
+
cx, cy = fnum(a.get("cx")), fnum(a.get("cy"))
|
|
149
|
+
rx, ry = fnum(a.get("rx")), fnum(a.get("ry"))
|
|
150
|
+
return (cx - rx, cy - ry, cx + rx, cy + ry)
|
|
151
|
+
if tag == "line":
|
|
152
|
+
xs = [fnum(a.get("x1")), fnum(a.get("x2"))]
|
|
153
|
+
ys = [fnum(a.get("y1")), fnum(a.get("y2"))]
|
|
154
|
+
return (min(xs), min(ys), max(xs), max(ys))
|
|
155
|
+
if tag in ("polyline", "polygon"):
|
|
156
|
+
nums = [fnum(x) for x in NUM.findall(a.get("points", ""))]
|
|
157
|
+
if len(nums) < 4:
|
|
158
|
+
return None
|
|
159
|
+
xs, ys = nums[0::2], nums[1::2]
|
|
160
|
+
return (min(xs), min(ys), max(xs), max(ys))
|
|
161
|
+
if tag == "path":
|
|
162
|
+
pts = path_points(a.get("d", ""))
|
|
163
|
+
if len(pts) < 2:
|
|
164
|
+
return None
|
|
165
|
+
xs = [p[0] for p in pts]
|
|
166
|
+
ys = [p[1] for p in pts]
|
|
167
|
+
return (min(xs), min(ys), max(xs), max(ys))
|
|
168
|
+
if tag == "text":
|
|
169
|
+
x, y = fnum(a.get("x")), fnum(a.get("y"))
|
|
170
|
+
fs = fnum(a.get("font-size"), 16.0)
|
|
171
|
+
txt = "".join(el.itertext()).strip()
|
|
172
|
+
w = max(len(txt), 1) * 0.62 * fs
|
|
173
|
+
anchor = a.get("text-anchor", "start")
|
|
174
|
+
x0 = x - w / 2 if anchor == "middle" else (x - w if anchor == "end" else x)
|
|
175
|
+
return (x0, y - fs, x0 + w, y + 0.25 * fs)
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
WHITE = {"#fff", "#ffffff", "white", "none", ""}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _walk(el, ctx, boxes, canvas):
|
|
183
|
+
if _tag(el) in ("defs", "clipPath", "mask", "pattern", "symbol"):
|
|
184
|
+
return
|
|
185
|
+
tx, ty, sx, sy = parse_transform(el.attrib.get("transform"))
|
|
186
|
+
ctx = (ctx[0] + tx * ctx[2], ctx[1] + ty * ctx[3], ctx[2] * sx, ctx[3] * sy)
|
|
187
|
+
b = bbox_of(el)
|
|
188
|
+
if b:
|
|
189
|
+
x0 = ctx[0] + b[0] * ctx[2]
|
|
190
|
+
y0 = ctx[1] + b[1] * ctx[3]
|
|
191
|
+
x1 = ctx[0] + b[2] * ctx[2]
|
|
192
|
+
y1 = ctx[1] + b[3] * ctx[3]
|
|
193
|
+
cw, ch = canvas[2] - canvas[0], canvas[3] - canvas[1]
|
|
194
|
+
fill = el.attrib.get("fill", "").strip().lower()
|
|
195
|
+
is_bg = ((x1 - x0) > 0.92 * cw and (y1 - y0) > 0.92 * ch) or (
|
|
196
|
+
(x1 - x0) > 0.95 * cw and fill in WHITE)
|
|
197
|
+
if not is_bg:
|
|
198
|
+
boxes.append((x0, y0, x1, y1))
|
|
199
|
+
for child in el:
|
|
200
|
+
_walk(child, ctx, boxes, canvas)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def compute_viewbox(root, pad=PAD):
|
|
204
|
+
"""Return a tight viewBox string around the content, or None."""
|
|
205
|
+
vb = [fnum(x) for x in NUM.findall(root.attrib.get("viewBox", "0 0 1024 1024"))]
|
|
206
|
+
canvas = (vb[0], vb[1], vb[0] + vb[2], vb[1] + vb[3]) if len(vb) == 4 else (0, 0, 1024, 1024)
|
|
207
|
+
boxes = []
|
|
208
|
+
_walk(root, (0.0, 0.0, 1.0, 1.0), boxes, canvas)
|
|
209
|
+
if not boxes:
|
|
210
|
+
return None
|
|
211
|
+
x0 = max(canvas[0], min(b[0] for b in boxes) - pad)
|
|
212
|
+
y0 = max(canvas[1], min(b[1] for b in boxes) - pad)
|
|
213
|
+
x1 = min(canvas[2], max(b[2] for b in boxes) + pad)
|
|
214
|
+
y1 = min(canvas[3], max(b[3] for b in boxes) + pad)
|
|
215
|
+
return f"{x0:.0f} {y0:.0f} {x1 - x0:.0f} {y1 - y0:.0f}"
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def scan_texts(root):
|
|
219
|
+
"""Scan <text> nodes for Vietnamese diacritic risks.
|
|
220
|
+
|
|
221
|
+
Returns a list of {"text": str, "flags": [str, ...]} where each flag
|
|
222
|
+
is prefixed with a tier: "definite" (character never occurs in
|
|
223
|
+
Vietnamese), "stacked" (vowel mark + tone — check every word),
|
|
224
|
+
"ocr" (data-ocr disagrees), "digits" (verify against source), or
|
|
225
|
+
"review" (has Vietnamese diacritics — proofread by eye).
|
|
226
|
+
"""
|
|
227
|
+
results = []
|
|
228
|
+
for el in root.iter():
|
|
229
|
+
if _tag(el) != "text":
|
|
230
|
+
continue
|
|
231
|
+
t = "".join(el.itertext()).strip()
|
|
232
|
+
if not t:
|
|
233
|
+
continue
|
|
234
|
+
flags = []
|
|
235
|
+
bad = sorted({c for c in t if c in DEFINITE_BAD})
|
|
236
|
+
risky = sorted({c for c in t if c in STACKED})
|
|
237
|
+
if bad:
|
|
238
|
+
flags.append(f"definite: {''.join(bad)} never occurs in Vietnamese")
|
|
239
|
+
if risky:
|
|
240
|
+
flags.append(f"stacked: {''.join(risky)} — vowel mark + tone, check every word")
|
|
241
|
+
ocr = (el.attrib.get("data-ocr") or "").strip()
|
|
242
|
+
if ocr and ocr != t:
|
|
243
|
+
flags.append(f"ocr: data-ocr reads {ocr!r}")
|
|
244
|
+
if any(c.isdigit() for c in t):
|
|
245
|
+
flags.append("digits: verify numbers against the source image")
|
|
246
|
+
if not bad and not risky and any(ord(c) > 127 for c in t):
|
|
247
|
+
flags.append("review: has Vietnamese diacritics — proofread by eye")
|
|
248
|
+
results.append({"text": t, "flags": flags})
|
|
249
|
+
return results
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def analyze_svg_text(raw: str) -> dict:
|
|
253
|
+
"""Validate and analyze SVG source text. Returns a report dict."""
|
|
254
|
+
try:
|
|
255
|
+
root = ElementTree.fromstring(raw)
|
|
256
|
+
except ElementTree.ParseError as e:
|
|
257
|
+
return {"valid": False, "error": str(e)}
|
|
258
|
+
return {
|
|
259
|
+
"valid": True,
|
|
260
|
+
"viewBox_before": root.attrib.get("viewBox"),
|
|
261
|
+
"viewBox_suggested": compute_viewbox(root),
|
|
262
|
+
"texts": scan_texts(root),
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def finish_svg_text(raw: str, fixes: dict | None = None) -> tuple[str, dict]:
|
|
267
|
+
"""Crop tightly and apply confirmed fixes. Returns (svg, report).
|
|
268
|
+
|
|
269
|
+
Fixes are a {wrong: right} mapping confirmed by a human (or by a
|
|
270
|
+
proofreader suggestion the human accepted). They are never guessed.
|
|
271
|
+
"""
|
|
272
|
+
report = analyze_svg_text(raw)
|
|
273
|
+
if not report["valid"]:
|
|
274
|
+
return raw, report
|
|
275
|
+
out = raw
|
|
276
|
+
applied = {}
|
|
277
|
+
for wrong, right in (fixes or {}).items():
|
|
278
|
+
if wrong in out:
|
|
279
|
+
out = out.replace(wrong, right)
|
|
280
|
+
applied[wrong] = right
|
|
281
|
+
report["fixes_applied"] = applied
|
|
282
|
+
new_vb = report["viewBox_suggested"]
|
|
283
|
+
if new_vb:
|
|
284
|
+
out, n = re.subn(r'viewBox="[^"]*"', f'viewBox="{new_vb}"', out, count=1)
|
|
285
|
+
report["viewBox_after"] = new_vb if n == 1 else report["viewBox_before"]
|
|
286
|
+
else:
|
|
287
|
+
report["viewBox_after"] = report["viewBox_before"]
|
|
288
|
+
return out, report
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Optional Grok-powered Vietnamese proofreader for SVG text nodes.
|
|
2
|
+
|
|
3
|
+
Bring your own key: set XAI_API_KEY (and optionally XAI_MODEL).
|
|
4
|
+
Suggestions are returned as a {wrong: right} mapping for a human to
|
|
5
|
+
confirm — VietSVG never applies them automatically. Only strings the
|
|
6
|
+
model is confident are wrong (e.g. caron/ë substitutions, broken
|
|
7
|
+
stacked diacritics) should come back; when unsure it must return {}.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import urllib.request
|
|
14
|
+
|
|
15
|
+
API_URL = "https://api.x.ai/v1/chat/completions"
|
|
16
|
+
DEFAULT_MODEL = "grok-4.7"
|
|
17
|
+
|
|
18
|
+
PROMPT = """You are a Vietnamese proofreader for text extracted from an AI-generated SVG.
|
|
19
|
+
Image-to-SVG models often break Vietnamese stacked diacritics (vowel mark + tone:
|
|
20
|
+
ằ ầ ề ồ ờ ừ families) and substitute characters that never occur in Vietnamese
|
|
21
|
+
(caron ǎ, ë). Given the list of text strings below, return ONLY a JSON object
|
|
22
|
+
mapping each definitely-wrong string to its corrected full string.
|
|
23
|
+
Rules: only include strings you are confident are wrong; never guess names;
|
|
24
|
+
if nothing is definitely wrong, return {}.
|
|
25
|
+
Strings: {texts}"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def suggest_fixes(texts: list[str], api_key: str | None = None,
|
|
29
|
+
model: str | None = None, timeout: int = 60) -> dict:
|
|
30
|
+
"""Ask Grok for confirmed-style fix suggestions for the given strings."""
|
|
31
|
+
key = api_key or os.environ.get("XAI_API_KEY")
|
|
32
|
+
if not key:
|
|
33
|
+
raise RuntimeError(
|
|
34
|
+
"XAI_API_KEY is not set. Create a key at console.x.ai and "
|
|
35
|
+
"export XAI_API_KEY=... to enable --grok-proofread."
|
|
36
|
+
)
|
|
37
|
+
if not texts:
|
|
38
|
+
return {}
|
|
39
|
+
payload = {
|
|
40
|
+
"model": model or os.environ.get("XAI_MODEL", DEFAULT_MODEL),
|
|
41
|
+
"messages": [{"role": "user", "content": PROMPT.format(texts=json.dumps(texts, ensure_ascii=False))}],
|
|
42
|
+
"temperature": 0,
|
|
43
|
+
}
|
|
44
|
+
req = urllib.request.Request(
|
|
45
|
+
API_URL,
|
|
46
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
47
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},
|
|
48
|
+
method="POST",
|
|
49
|
+
)
|
|
50
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
51
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
52
|
+
content = data["choices"][0]["message"]["content"].strip()
|
|
53
|
+
if content.startswith("```"):
|
|
54
|
+
content = content.strip("`")
|
|
55
|
+
content = content[content.find("{"):]
|
|
56
|
+
suggestions = json.loads(content)
|
|
57
|
+
if not isinstance(suggestions, dict):
|
|
58
|
+
raise RuntimeError(f"Unexpected proofreader output: {content!r}")
|
|
59
|
+
# Keep only mappings whose key is one of the input strings.
|
|
60
|
+
return {k: v for k, v in suggestions.items() if k in texts and isinstance(v, str)}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vietsvg
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Vietnamese-safe finishing toolkit for AI-generated SVGs: tight auto-crop, diacritic risk scan, confirmed text fixes, render proofs.
|
|
5
|
+
Author: Chiêu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Konoha95/vietsvg
|
|
8
|
+
Project-URL: Issues, https://github.com/Konoha95/vietsvg/issues
|
|
9
|
+
Keywords: svg,vietnamese,diacritics,ai,image-to-svg,grok
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Provides-Extra: render
|
|
16
|
+
Requires-Dist: cairosvg>=2.7; extra == "render"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# VietSVG
|
|
20
|
+
|
|
21
|
+
**Vietnamese-safe finishing toolkit for AI-generated SVGs.**
|
|
22
|
+
|
|
23
|
+
Image-to-SVG models (such as Baidu's [Unlimited-SVG](https://github.com/baidu/Unlimited-SVG)) can turn a logo, diagram, or infographic into an editable SVG with real `<text>` nodes. Two things reliably go wrong for Vietnamese content:
|
|
24
|
+
|
|
25
|
+
1. **The canvas is mostly empty.** Some demos shrink the artwork into the middle of a 1024×1024 canvas, so the SVG looks tiny everywhere you use it.
|
|
26
|
+
2. **Vietnamese diacritics break.** Stacked diacritics (vowel mark + tone: the `ằ ầ ề ồ ờ ừ` families) are mangled, `ê`-family tones drift, and characters that never occur in Vietnamese (caron `ǎ`, `ë`) show up — we have seen `Chiuë` and `Chéu` where the source said `Chiêu`.
|
|
27
|
+
|
|
28
|
+
VietSVG finishes those files for real use:
|
|
29
|
+
|
|
30
|
+
- **Tight auto-crop** — computes the true content bounding box (paths, shapes, text, transforms; full-canvas backgrounds ignored) and rewrites the root `viewBox`. In our verification runs the auto-crop matched a hand crop within 1 unit on a logo (`244 244 536 536` vs `244 244 535 535`).
|
|
31
|
+
- **Diacritic risk scan** — lists every `<text>` node and flags risks by tier: `definite` (character never occurs in Vietnamese), `stacked` (vowel mark + tone — check every word), `ocr` (`data-ocr` disagrees), `digits` (verify numbers), `review` (has Vietnamese diacritics — proofread by eye).
|
|
32
|
+
- **Confirmed fixes only** — applies a `{wrong: right}` JSON mapping a human confirmed. VietSVG never guesses text.
|
|
33
|
+
- **Optional Grok proofreader** — with your own `XAI_API_KEY`, asks Grok to suggest fixes for flagged strings. Suggestions land in a JSON file for you to confirm; nothing is auto-applied.
|
|
34
|
+
- **Render proof** — optional PNG render so you can eyeball the finished file against the source image.
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install vietsvg # PyPI release coming with v0.1.0
|
|
40
|
+
# or from source:
|
|
41
|
+
git clone https://github.com/Konoha95/vietsvg && cd vietsvg && pip install -e .
|
|
42
|
+
|
|
43
|
+
vietsvg check examples/broken-vietnamese.svg
|
|
44
|
+
vietsvg finish examples/broken-vietnamese.svg --render
|
|
45
|
+
vietsvg finish logo.svg --fix fixes.json --render
|
|
46
|
+
XAI_API_KEY=... vietsvg finish logo.svg --grok-proofread
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`fixes.json` is a plain mapping of confirmed corrections:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{"Chiuë": "Chiêu"}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Why this exists
|
|
56
|
+
|
|
57
|
+
VietSVG was born from a real workflow in December 2026: converting Vietnamese logos and diagrams with Unlimited-SVG demos, then discovering that every conversion needed the same manual finishing — crop the canvas, hunt broken diacritics word by word, fix, re-render, compare. The first version of this tool caught `Xin chao Chiuë` automatically and, with one confirmed mapping, produced a clean, correctly cropped `Xin chao Chiêu`. The full-diacritics test behind the risk tiers is documented in the code: stacked diacritics broke in nearly every instance, single tones and `đ` mostly held.
|
|
58
|
+
|
|
59
|
+
Vietnamese is spoken by ~90 million people, and AI design tools keep shipping text that is *almost* right. Almost-right text in a logo is wrong text. VietSVG is the small, honest finishing step between "the model made an SVG" and "you can ship it".
|
|
60
|
+
|
|
61
|
+
## Built with Grok
|
|
62
|
+
|
|
63
|
+
This project is developed with [Grok Build](https://grok.com/product/build) and uses the Grok API (bring your own key) for its optional proofreader. The proofreader prompt encodes the same diacritic risk tiers as the scanner, so model suggestions stay conservative: confident errors only, names never guessed.
|
|
64
|
+
|
|
65
|
+
## Web demo
|
|
66
|
+
|
|
67
|
+
Drop an SVG into the browser demo and see the tight crop plus the diacritic
|
|
68
|
+
risk report — everything runs locally in your browser, nothing is uploaded:
|
|
69
|
+
**https://konoha95.github.io/vietsvg/** · **https://vietsvg.netlify.app/**
|
|
70
|
+
(source in [`docs/`](docs/); the Netlify deployment is powered by
|
|
71
|
+
[Netlify](https://www.netlify.com)).
|
|
72
|
+
|
|
73
|
+
## Roadmap
|
|
74
|
+
|
|
75
|
+
- [x] Web demo: drop an SVG, see the crop + risk report in the browser
|
|
76
|
+
- [ ] Side-by-side compare view (source image vs finished SVG render)
|
|
77
|
+
- [ ] MCP server + Agent Skill so coding agents can finish SVGs themselves
|
|
78
|
+
- [ ] More scripts with stacked diacritics (Thai, Devanagari) via pluggable risk tiers
|
|
79
|
+
- [ ] Batch mode for folders of generated assets
|
|
80
|
+
|
|
81
|
+
## Tiếng Việt
|
|
82
|
+
|
|
83
|
+
VietSVG là công cụ hoàn thiện file SVG do AI tạo ra, chuyên cho nội dung tiếng Việt: tự cắt khung `viewBox` ôm sát nội dung, quét mọi chữ `<text>` và cảnh báo chỗ nghi sai dấu (dấu chồng như `ằ ầ ề` là nhóm rủi ro cao nhất; ký tự `ǎ`, `ë` là chắc chắn sai), áp dụng bảng sửa chữ đã được người soát xác nhận — công cụ không tự đoán chữ. Có thể bật thêm bộ soát lỗi bằng Grok (dùng API key của bạn) để nhận gợi ý sửa, vẫn phải xác nhận tay trước khi áp dụng.
|
|
84
|
+
|
|
85
|
+
## Contributing
|
|
86
|
+
|
|
87
|
+
Bug reports with a minimal SVG that crops or flags wrong are gold. See [CONTRIBUTING.md](CONTRIBUTING.md). Please follow the [Code of Conduct](CODE_OF_CONDUCT.md).
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
vietsvg/__init__.py,sha256=ftLNRYUNzcbny_c5jKqIvUMJOHNvdLeb8yeiaJJTAW4,234
|
|
2
|
+
vietsvg/cli.py,sha256=nlm8OL7QkgsBvCjOKQ_DUuysyKegyMRwx3DU80TOHUQ,3974
|
|
3
|
+
vietsvg/core.py,sha256=dHidrXhQ4cOCo12d4ncEr9Rel9sg5ZuahYDuEf6HjTM,10462
|
|
4
|
+
vietsvg/grok_proofread.py,sha256=jBBWKVrrcT24B8ZEPxB3R3YYNbopBpsIREme2X7ba_c,2662
|
|
5
|
+
vietsvg-0.1.0.dist-info/licenses/LICENSE,sha256=iF-saRQ_210BYH9y0eNywLDJMLoVy4G2DaHXmhok2NU,1063
|
|
6
|
+
vietsvg-0.1.0.dist-info/METADATA,sha256=knwM5dyjR1XWayJACWD7pGXaqMKHNH4j4EqbnQXj6Vw,5739
|
|
7
|
+
vietsvg-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
vietsvg-0.1.0.dist-info/entry_points.txt,sha256=mMo9MuOb_kra0cofYJR5dGG2A_hcqJBcHiIAhAtzDLo,45
|
|
9
|
+
vietsvg-0.1.0.dist-info/top_level.txt,sha256=KIkCyRGGgDi_K5hQ6sX3rHsIJx7-PDO_nGlu99RR5KU,8
|
|
10
|
+
vietsvg-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chiêu
|
|
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
|
+
vietsvg
|