Skip to content

Instantly share code, notes, and snippets.

@seignovert
Last active February 28, 2020 01:43
Show Gist options
  • Save seignovert/a8e480c27071f31e58df62d19b7f8098 to your computer and use it in GitHub Desktop.
Save seignovert/a8e480c27071f31e58df62d19b7f8098 to your computer and use it in GitHub Desktop.
[Python] Minimalist DOI QRcode

Minimalist DOI QRcode

Get a short doi from a regular doi

python doi.py 10.22002/d1.1173
https://doi.org/ggmwrc

Save short DOI as a QRcode

https://doi.org/ggmwrc

As SVG (default), titan-vims-iss-map.svg:

python doi.py 10.22002/d1.1173 titan-vims-iss-map

or as PNG, titan-vims-iss-map.png:

python doi.py 10.22002/d1.1173 titan-vims-iss-map.png

Resources

"""Create QR code with short DOI."""
import argparse
import sys
from pathlib import Path
import qrcode
from qrcode.image.svg import SvgPathImage
import requests
def get_short(doi, url=True):
"""Get short DOI from."""
resp = requests.get(
f'http://www.shortdoi.org/{doi}',
params={'format': 'json'},
)
if not resp.ok:
raise resp.raise_for_status()
short = resp.json()['ShortDOI'][3:]
return f'https://doi.org/{short}' if url else short
def get_qrcode(url, svg=False,
fill_color='black',
back_color='white',
optimize=True):
"""Create SVG based on URL."""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(url, optimize=optimize)
if svg:
return qr.make_image(
fill_color=fill_color,
back_color=back_color,
image_factory=SvgPathImage,
)
return qr.make_image(fill_color=fill_color, back_color=back_color)
def save_doi_qrcode(doi, output=None, svg=False, optimize=True, force=False):
"""Get short DOI and save as svg QRcode."""
fout = Path('qrcode' if output is None else output)
fout = fout.parent / f'{fout.stem}.{"svg" if svg else "png"}'
if fout.exists() and not force:
raise FileExistsError(fout)
url = get_short(doi)
img = get_qrcode(url, svg=svg, optimize=optimize)
img.save(str(fout))
def cli(argv=None):
"""Command line interface."""
parser = argparse.ArgumentParser(
description='Convert VIMS QUB cubes into binary array')
parser.add_argument('doi', help='DOI.')
parser.add_argument('name', help='Output QRcode name.', nargs='?')
parser.add_argument('-f', '--force',
help='Enable file overwrite.',
action='store_true')
args, _ = parser.parse_known_args(argv)
if args.name is None:
print(get_short(args.doi))
else:
save_doi_qrcode(
args.doi,
output=args.name,
svg=(not args.name.endswith('png')),
force=args.force,
)
if __name__ == "__main__":
cli(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment