Skip to content

Instantly share code, notes, and snippets.

@tav
Created December 8, 2013 18:34
Show Gist options
  • Save tav/7861743 to your computer and use it in GitHub Desktop.
Save tav/7861743 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import os
import requests
import sys
from BeautifulSoup import BeautifulSoup
from commands import getoutput
from hashlib import sha1
from os.path import expanduser, isfile, join
url = getoutput('pbpaste')
if not url.startswith('http://'):
print "!! ERROR: Invalid URL: %r" % url
sys.exit(1)
tmp_path = expanduser("~/.local/nounproject/index.html")
svg_path = join(expanduser("~/.local/nounproject"), sha1(url).hexdigest() + ".svg")
if isfile(svg_path):
print ">> Loading saved %s (%s)" % (url, svg_path)
f = open(svg_path, 'rb')
svg = f.read()
f.close()
else:
print ">> Fetching data from %s" % url
html = BeautifulSoup(requests.get(url).text)
ok = False
for tag in html.findAll('img'):
src = None
for attr, val in tag.attrs:
if attr == 'src':
src = val
if attr == 'class' and val == 'icon':
ok = True
if ok:
break
else:
print "!! ERROR: No <img class='icon'> tag found !!"
sys.exit(1)
print ">> Fetching svg from %s" % src
svg = requests.get(src).text
print ">> Saving file to %s" % svg_path
f = open(svg_path, 'wb')
f.write(svg)
f.close()
TEMPLATE = """<!doctype html>
<html>
<head>
<script src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script id="svg">%s</script>
<body>
<script>
scr = document.getElementById('svg');
svg = scr.innerText;
svg = svg.replace(/^[\s\S]*<svg/, '<svg');
size = parseInt(prompt("What size?","1024"));
if (!size || isNaN(size)) size = 1024;
svg = svg.replace(/(width|height)="\d+px"/g, '$1="'+size+'px"');
color = prompt("What color? (CSS hexa plz)", "000");
if (!color || !color.length) color = '#000';
if (color[0] !== '#') color = '#' + color;
if (!/#([0-9a-f]{3}){1,2}/i.test(color)) color = '#000';
svg = svg.replace(/stroke="[^"]+"/g, 'stroke="'+color+'"');
svg = svg.replace(/fill="[^"]+"/g, '');
svg = svg.replace('<svg', '<svg fill="'+color+'" ');
canvas = document.createElement('canvas');
canvas.width = canvas.height = size+'px';
context = canvas.getContext('2d');
context.fillStyle = 'red';
context.strokeStyle = 'blue';
canvg(canvas, svg);
png = canvas.toDataURL();
window.location = png;
</script>
"""
print ">> Writing to %s" % tmp_path
f = open(tmp_path, 'wb')
f.write(TEMPLATE % svg)
f.close()
os.system("open %s" % tmp_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment