Inline SVG styles

A designer gave us a set of SVG assets for a project I’m working on. Unfortunately, they each had a <style> tag, and each one used the same conflicting class names (.st0, .st1, .st2, etc). I wrote a quick python script to convert the css rules to attributes so they wouldn’t conflict.

from bs4 import BeautifulSoup
import tinycss
import click
css_parser = tinycss.make_parser('page3')

# Known good list of attributes that can be applied inline.
# Feel free to expand this list if need be. These were just
# the only ones we needed.
    'fill', 'stroke', 'stroke-width', 'stroke-miterlimit',

def apply_styles(elem, declarations):
    for decl in declarations:
        if not in STYLE_ATTRS:
            raise ValueError(
              'unknown svg attribute: {}'.format(
        elem.attrs[] = decl.value.as_css()

@click.option('--infile', default='-', type=click.File('r'))
@click.option('--outfile', default='-', type=click.File('w'))
def inline_styles(infile, outfile):
    soup = BeautifulSoup(, 'html.parser')

    stylesheet = css_parser.parse_stylesheet(
    for rule in stylesheet.rules:
        elems =
        for elem in elems:
            apply_styles(elem, rule.declarations)



if __name__ == '__main__':