GithubHelp home page GithubHelp logo

heuer / segno Goto Github PK

View Code? Open in Web Editor NEW
590.0 13.0 49.0 3.29 MB

Python QR Code and Micro QR Code encoder

Home Page: https://pypi.org/project/segno/

License: BSD 3-Clause "New" or "Revised" License

Python 98.24% Roff 1.76%
qrcode barcode micro-qrcode matrix-barcode qr-code segno python qr-generator iso-18004 structured-append

segno's Introduction

QR Code encoder and Micro QR Code encoder

Pure Python QR Code generator with no dependencies.

This package implements ISO/IEC 18004:2015(E) "QR Code bar code symbology specification" and produces QR Codes and Micro QR Codes with nearly no effort. It supports the Structured Append mode which splits a message across several QR codes.

Segno (Italian for "sign" / "symbol") provides several serialization formats like Scalable Vector Graphics (SVG), Encapsulated PostScript (EPS), Portable Network Graphics (PNG), Portable Document Format (PDF), Netpbm (PAM, PBM, PPM), LaTeX (PGF/TikZ), X PixMap (XBM), and X Bitmap (XPM) etc. None of these serializers require an external lib. Further, it provides several high level functions to create QR Codes which encode contact data (vCard, MeCard), EPC QR Codes, or WIFI QR Codes.

The project provides more than 1500 test cases (coverage >= 98%) to verify a standard conform QR Code and Micro QR Code generation acc. to ISO/IEC 18004:2015(E).

Unique features

import segno
qrcode = segno.make('Yellow Submarine')
qrcode.save('yellow-submarine.png')

Installation

Use pip to install segno from PyPI:

$ pip install segno

conda-forge

The library is also available at conda-forge (conda-forge project page):

$ conda install -c conda-forge segno

Debian

$ apt-get install python3-segno

Arch Linux

$ pacman -S python-segno

Usage

Command line

The command line script prints a QR code to the terminal:

$ segno "Comfortably Numb"

To serialize a QR code, use the "output" argument:

$ segno -o=raincoat.svg "Famous Blue Raincoat"
$ segno --scale 10 --dark darkblue --border 0 --output=fire.svg "Who by Fire"
$ segno --scale 10 --light transparent --output=miracle.png "Waiting for the Miracle"

Library

>>> import segno
>>> # Let Segno choose the minimal version and an optimal (maximal) error
>>> # level without changing the minimal version
>>> qrcode = segno.make('Up Jumped the Devil')
>>> qrcode.designator  # Returns the QR code version and the error correction level
'2-Q'
>>> qrcode.save('up-jumped-the-devil.png')  # Save as PNG
>>> qrcode.save('up-jumped-the-devil-2.png', scale=10)  # Scaling factor 10
>>> qrcode.save('up-jumped-the-devil-3.png', light=None)  # Transparent light modules
>>> qrcode.save('up-jumped-the-devil.pdf', scale=10)  # Save as PDF
>>> # SVG drawing the dark modules in "dark blue"
>>> qrcode.save('up-jumped-the-devil.svg', scale=10, dark='darkblue')

If the content to encode is small enough, a Micro QR code is generated:

>>> import segno
>>> qrcode = segno.make('RAIN')
>>> qrcode.is_micro
True
>>> qrcode.designator
'M2-M'

If this behaviour is not desired, the user may set micro to False

>>> import segno
>>> qrcode = segno.make('RAIN', micro=False)
>>> qrcode.is_micro
False
>>> qrcode.designator
'1-H'

Or use the factory functions segno.make_qr() which generates always QR codes (never Micro QR codes) or segno.make_micro() which returns always Micro QR codes (or raises an error if the content is too large for a Micro QR code).

>>> import segno
>>> qrcode_micro = segno.make_micro('THE BEATLES')
>>> qrcode_micro.designator
'M3-M'
>>> qrcode = segno.make_qr('THE BEATLES')  # Same content but enforce a QR Code
>>> qrcode.designator
'1-Q'
>>> # This won't work since the data does not fit into a Micro QR Code M1 - M4
>>> micro_qrcode = segno.make_micro('Nick Cave and the Bad Seeds')
Traceback (most recent call last):
    ...
DataOverflowError: Data too large. No Micro QR Code can handle the provided data

All factory functions use the same parameters to specify the desired error level, version, data mask etc., see Segno's documentation for details.

Documentation

Read the online documentation at <https://segno.readthedocs.io/>

Trademark

"QR Code" and "Micro QR Code" are registered trademarks of DENSO WAVE INCORPORATED.

segno's People

Contributors

alexbeattie42 avatar barbashovtd avatar bitcoinhodler avatar christian-oudard avatar derbiasto avatar eduardomazolini avatar heuer avatar jayaddison avatar missionfloyd avatar neycyanshi avatar stefanoborini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

segno's Issues

print stmt in test_pbm.py

test_pbm.py / line 54 ...

        if l.startswith(b'P') or l.startswith(b'#'):
            print('Skip line', l)
            continue

boost_error=True creates invalid QR Codes

>>> import segno
>>> qr = segno.make('http://www.example.org/bla/bla/')
>>> qr.show()  # Does not scan
>>> qr.designator
'3-H'
>>> qr = segno.make('http://www.example.org/bla/bla/', boost_error=False)
>>> qr.show()  # Works!
>>> qr.designator
'3-M'
>>> # Setting the error level to 'H' works, too
>>> qr = segno.make('http://www.example.org/bla/bla/', error='h')
>>> qr.show()  # Works!
>>> qr.designator
'4-H'
>>> # boost_error should choose error level "Q" which does not change the QR Code version
>>> qr = segno.make('http://www.example.org/bla/bla/', boost_error=False, error='q')
>>> qr.show()  # Works!
>>> qr.designator
'3-Q'

Remove PDF support?

Segno supports EPS and SVG. Is the PDF output useful at all? Maybe it should become a plugin.

Console script (Windows): Error for struct.unpack

Error:

default_color = struct.unpack("hhhhHhhhhhh", csbi.raw)[4]
TypeError: Struct() argument 1 must be string, not unicode

Solution:
writers.py / line 770

    default_color = struct.unpack(b'hhhhHhhhhhh', csbi.raw)[4]

Provide helpers.make_XXX in segno.__init__?

The helpers module provides several factory functions to create QR Codes for e-mail addresses, contacts, ...

Might be nice if at least the make_XXX (and not make_XXX_data) functions would be available with a simple import segno import:

Currently:

>>> from segno import helpers
>>> qr = helpers.make_email('[email protected]')

If segno.__init__ imports the factory functions:

>>> import segno
>>> qr = segno.make_email('[email protected]')

The factory functions of helpers differ from the usual factory functions, though. They don't allow to set the minimum error level / version ...

Make helpers factory functions available in command line script?

The factory functions of helpers.py aren't accessible through the command line script; might be useful to find a way to expose them.

segno wifi network=x password=y

Probably it might be more useful to utilize the make_XXX_data factories since the command line script could set the error level and QR Code version

Accept unquoted space delimited content as last item of cmd line

Does not work:

segno --scale 10 --output good-times.png Good Times
usage: segno [-h] [--version VERSION] [--error {L,M,Q,H,-}]
             [--mode {numeric,alphanumeric,byte,kanji}] [--pattern PATTERN]
             [--scale SCALE] [--border BORDER] [--micro] [--no-micro]
             [--color COLOR] [--background BACKGROUND] [--output OUTPUT]
             [--no-error-boost] [--no-classes] [--no-xmldecl] [--no-namespace]
             [--no-newline] [--title TITLE] [--desc DESC] [--svgid SVGID]
             [--svgclass SVGCLASS] [--lineclass LINECLASS] [--no-size]
             [--unit UNIT] [--svgversion SVGVERSION] [--encoding ENCODING]
             [--dpi DPI] [--no-ad] [--ver]
             content
segno: error: unrecognized arguments: Times

Works:

segno --scale 10 --output good-times.png "Good Times"

Error level: Minimum level vs. explicit level

Would be nice if a minimum error level could be provided. If the data is small enough, the algorithm could increase the error level automatically (version must be the same).

>>> import segno
>>> qr_m = segno.make_qr('ABCDE', error='m')
>>> qr_m.designator
'1-M'
>>> qr_h = segno.make_qr('ABCDE', error='h')
>>> q_h.designator
'1-H'
>>> qr_h.symbol_size()  == qr_m_symbol_size()
True

The above should be done automatically, if the user wants it

>>> import segno
>>> qr = segno.make_qr('ABCDEF', please_increase_error_level_if_possible=True)
>>> qr.designator
'1-H'
>>> # With an explicit error level
>>> qr = segno.make_qr('ABCDEF', error='l', please_increase_error_level_if_possible=True)
>>> qr.designator
'1-H'

find_version should operate with bits and not with modes

encoder.find_version takes the character count (len(data)) and the individual modes into account. This may lead to suboptimal versions. find_version should take the number of bits into account. Further, it should take the overhead (mode indicator, length of char indicator) into account, see TODO.

Inkscape plugin?

Would be nice if Segno could be used as Inkscape extension.
Maybe a subproject?

Structured Append

This allows files of data to be represented logically and continuously in up to 16 QR Code symbols. These may be scanned in any sequence to enable the original data to be correctly reconstructed. (c.f. chapter 8)

Minor priority since the usual QR Code readers do not support this mode; might be a "nice to have"

vcard field

Thank's for your work.

Is it possible to know all the different vcard fields we can introduce with segno? on segno.readthedocs.io, I only see the following parameters :
qr = helpers.make_vcard(name='Doe;John', displayname='John Doe', email='[email protected]', phone='+1234567')

but there are many others parameters :
https://en.wikipedia.org/wiki/VCard#Properties

Choose error level more lenient

If the user specifies the version but not the error level, a DataOverflowException may be raised

>>> import segno
>>> qr = segno.make('Wikipedia', version='M3')
Traceback (most recent call last):
[...]
DataOverflowError: The provided data does not fit into version "M3". Proposal: version M4

If Segno would not insist on error level M (default), the symbol can be generated:

>>> import segno
>>> qr = segno.make('Wikipedia', version='M3', error='l')
>>> qr.designator
'M3-L'

CLI should not raise exceptions but return an error code

Would be nice if CLI would not show the traceback but simply return an error code and show the message from the exception

$ segno --micro This does not fit into a micro code
Traceback (most recent call last):
[...]
segno.encoder.DataOverflowError: Data too large. No Micro QR Code can handle the provided data

segno always append '0a' to the content

I use onlinebarcodereader to decode the qrcode that generate by segno and I find it always auto append '0a' to the content in hex values. How to remove it?

Validity check for user provided mask index is wrong

    if is_micro:
        if not 0 <= mask <= 4:
            raise MaskError('Invalid data mask "{0}" for Micro QR Code'.format(mask))
    else:
        if not 0 <= mask <= 8:
            raise MaskError('Invalid data mask "{0}"'.format(mask))

Correct: 0 <= mask < 4 and 0 <= mask < 8

from segno import * fails

>>> from segno import *

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from segno import *
TypeError: Item in ``from list'' must be str, not unicode

Thanks!

This library is very well done:

  • Has all features I could want.
  • Nice API.
  • Helpful CLI tool.
  • Great docs & changelogs.
  • No dependencies.
  • Fast.
  • Has tests.
  • Permissive license.
  • Can even render to the terminal!

It should be the default choice for QR handling in Python. Just wanted to say thanks for the hard work :)

Accept percentual values for error correction level?

Segno could accept something like

>>> import segno
>>> segno.make('Avalanche', error=.07)
>>> segno.make('Tupelo', error=.25)

where the error value refers to the corresponding error levels "L", "M", "Q", "H".

PyQRCode, for example, accepts values like "7%" etc.

I don't think that PyQRCode's behaviour adds any value, maybe

>>> segno.make('Mermaids', error=7) 
>>> segno.make('Deanna', error=25) 

would make more sense.

If it makes sense at all...

Problem with micro QR code generation

Hi,

I was trying to generate some micro QR codes that should be read by someone else, but they reported that they could not read them.
After some investigation, it seems that the code for generating format information for micro QR codes is wrong, except for M1 and M2-L code.

The patch below seems to fix that problem, although the people who read my codes still report they can’t read the M3 codes I generated (M2 and M4 seemed to be fine)…

Cheers,

--
Nicolas Boullis

diff --git a/segno/encoder.py b/segno/encoder.py
--- a/segno/encoder.py
+++ b/segno/encoder.py
@@ -786,12 +786,15 @@ def add_format_info(matrix, version, err
     is_micro = version < 1
     offset = int(is_micro)
     fmt = mask_pattern
-    if error == consts.ERROR_LEVEL_L:
-        fmt += (0x08 if not is_micro else 0x4)
-    elif error == consts.ERROR_LEVEL_H:
-        fmt += (0x10 if not is_micro else 0xe)
-    elif error == consts.ERROR_LEVEL_Q:
-        fmt += (0x18 if not is_micro else 0x14)
+    if is_micro:
+        fmt += consts.ERROR_LEVEL_TO_MICRO_MAPPING[version][error] << 2
+    else:
+        if error == consts.ERROR_LEVEL_L:
+            fmt += 0x08
+        elif error == consts.ERROR_LEVEL_H:
+            fmt += 0x10
+        elif error == consts.ERROR_LEVEL_Q:
+            fmt += 0x18
     format_info = consts.FORMAT_INFO[fmt] if not is_micro else consts.FORMAT_INFO_MICRO[fmt]
     for i in range(8):
         bit = (format_info >> i) & 0x01

Command line: Support plugins

Would be nice if plugins and their specific keywords could be supported:

$ segno 'Cocaine' --plugin=glow deviation=.4 filter-id=boah -o=cocaine.svg

Add contact 'photo' field to vcards

I would be nice to add the photo field to the vcard

https://tools.ietf.org/html/rfc6350#section-6.2.4

Examples:

   PHOTO:http://www.example.com/pub/photos/jqpublic.gif

   PHOTO:data:image/jpeg;base64,MIICajCCAdOgAwIBAgICBEUwDQYJKoZIhv
    AQEEBQAwdzELMAkGA1UEBhMCVVMxLDAqBgNVBAoTI05ldHNjYXBlIENvbW11bm
    ljYXRpb25zIENvcnBvcmF0aW9uMRwwGgYDVQQLExNJbmZvcm1hdGlvbiBTeXN0
    <...remainder of base64-encoded data...>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.