from pyquery import PyQuery as pq
import re
import math
import sys
import base64
import os
if len(sys.argv) < 3:
print("python3 svg-transform.py in.svg out.svg")
exit(1)
in_file = sys.argv[1]
out_file = sys.argv[2]
ns = {"svg": "http://www.w3.org/2000/svg"}
if len(sys.argv) > 3 and os.path.exists(sys.argv[3]):
font_src = "url('data:font/woff2;base64,%s') format('woff2')" % base64.b64encode(open(sys.argv[3], "rb").read()).decode("ascii")
else:
font_src = "url('https://petitl.fr/cps2/fonts/newstroke.woff2') format('woff2'), url('https://petitl.fr/cps2/fonts/newstroke.woff') format('woff'), url('https://petitl.fr/cps2/fonts/newstroke.ttf') format('ttf')"
with open(in_file, encoding="utf-8") as f:
svg = pq(f.read(), parser="xml", namespaces=ns)
if svg("svg|defs"):
print("Already transformed, quitting already...")
exit(2)
view_box = [int(i) for i in svg.attr("viewBox").split(" ")]
style = pq(re.sub("\\s+", " ", """
""" % (font_src)), parser="xml", namespaces=ns)
rect = pq("""""" % tuple(view_box), parser="xml", namespaces=ns)
for t in svg.items("svg|text"):
if t.attr("font-size") is None:
continue
t.remove_attr("opacity")
t.remove_attr("lengthAdjust")
text_length = int(t.attr("textLength"))
t.remove_attr("textLength")
t.text(t.text().replace("~", ""))
font_size = int(math.ceil(int(t.attr("font-size")) / 1.33 / 10))*10
t.attr("font-size", str(font_size))
base_x, base_y = int(t.attr("x")), int(t.attr("y"))
if t.attr("transform") is not None:
# we have to transform coordinates even if it globally stays in place
# it is always a matrix(0 -1 1 0 X Y)
transform = [int(m) for m in t.attr("transform")[7:-1].split(" ")]
base_x, base_y = base_y+transform[4], -base_x+transform[5]
# invert x / y coordinates to perform comparisons
base_x, base_y = base_y, base_x
base_y = -base_y
if t.attr("text-anchor") == "middle":
base_x -= text_length / 2
elif t.attr("transform") is None and t.attr("text-anchor") == "end":
base_x -= text_length
elif t.attr("transform") is not None and t.attr("text-anchor") is None:
base_x -= text_length
current_bar = None
all_bars = []
min_x = None
for path in list(t.next_all()):
if not path.tag.endswith("path"):
break
path = pq(path)
p = path.attr("d")
if p is None:
break
_, x, y, __ = re.split("\\D", p, 3)
if not x or not y:
print(p)
break
x, y = int(x), int(y)
if t.attr("transform") is not None:
y, x = x, y
y = -y
if min_x is None or min_x > x:
min_x = x
if (base_y + font_size * 1.1) >= y >= (base_y-font_size*0.4) and (base_x - font_size * 1.1) <= x <= (base_x+text_length+font_size*0.4):
# path is likely to be overlapping current text
# so remove it
path.remove()
pass
elif (base_y + font_size * 1.6) >= y >= (base_y + font_size * 1.1):
# path is just above the current text so it's likely a overline
m = re.search("^m(\\d+) (\\d+)h(\\d+)$", p)
if m:
# confirmed
x, y, h = int(m.group(1)), int(m.group(2)), int(m.group(3))
path.remove()
if current_bar is not None and current_bar[0]+current_bar[2] == x:
# continuation
current_bar[2] += h
else:
current_bar = [x, y, h]
all_bars.append(current_bar)
pass
else:
# it's not the path we want! get out!
break
if min_x is not None:
if min_x >= (base_x + font_size * 0.9):
# we have to shift!
shift = (min_x - base_x) // int(font_size * 0.8)
t.attr("x", str(int(t.attr("x"))+shift*int(font_size * 0.8)))
min_x = 0
pass
# replace all bars
for bar in all_bars:
stroke_width = "stroke-width=\"%d\"" % round(font_size * 1.33 / 10)# if font_size >= 1000 else "")
pq("""""" % (bar[0], bar[1], bar[2], stroke_width), namespaces=ns).insert_after(t)
# we can simplify structures like
if t.siblings().length == 0:
t.attr("fill", t.parent().attr("fill"))
parent = t.parent()
t.remove()
t.insert_after(parent)
parent.remove()
# global clean and insert header
svg("[stroke-width=\"0\"]").remove_attr("stroke").remove_attr("stroke-width")
rect.insert_before(svg.children().eq(0))
style.insert_before(svg.children().eq(0))
with open(out_file, "w", encoding="utf-8") as w:
w.write(str(svg))
print("Finished transforming", in_file, "to", out_file)