Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GS1 QR mode support #140

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions segno/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@


def make(content, error=None, version=None, mode=None, mask=None, encoding=None,
eci=False, micro=None, boost_error=True):
eci=False, micro=None, boost_error=True, gs1=None):
"""\
Creates a (Micro) QR Code.

Expand Down Expand Up @@ -136,11 +136,11 @@ def make(content, error=None, version=None, mode=None, mask=None, encoding=None,
:rtype: QRCode
"""
return QRCode(encoder.encode(content, error, version, mode, mask, encoding,
eci, micro, boost_error=boost_error))
eci, micro, boost_error=boost_error,gs1=gs1))


def make_qr(content, error=None, version=None, mode=None, mask=None,
encoding=None, eci=False, boost_error=True):
encoding=None, eci=False, boost_error=True, gs1=None):
"""\
Creates a QR code (never a Micro QR code).

Expand All @@ -149,7 +149,7 @@ def make_qr(content, error=None, version=None, mode=None, mask=None,
:rtype: QRCode
"""
return make(content, error=error, version=version, mode=mode, mask=mask,
encoding=encoding, eci=eci, micro=False, boost_error=boost_error)
encoding=encoding, eci=eci, micro=False, boost_error=boost_error,gs1=gs1)


def make_micro(content, error=None, version=None, mode=None, mask=None,
Expand Down
16 changes: 16 additions & 0 deletions segno/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,22 @@
'H': ERROR_LEVEL_H,
}

# ISO/IEC 18004:2015(E) -- 7.4.8.2

FNC1_FIRST = 0x5
FNC1_SECOND = 0x9

GS_BYTES = 0x1D
# % character
GS_ALPHANUMERIC = 0x25


FNC1_MAPPING = {
'first': FNC1_FIRST,
'second': FNC1_SECOND,
# 'uri': None
}

#
# ISO/IEC 18004:2015(E) -- 7.3.2 Extended Channel Interpretation (ECI) mode (page 20)
#
Expand Down
49 changes: 43 additions & 6 deletions segno/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class DataOverflowError(ValueError):


def encode(content, error=None, version=None, mode=None, mask=None,
encoding=None, eci=False, micro=None, boost_error=True):
encoding=None, eci=False, micro=None, boost_error=True,gs1=None):
"""\
Creates a (Micro) QR code.

Expand All @@ -58,6 +58,9 @@ def encode(content, error=None, version=None, mode=None, mask=None,

:rtype: namedtuple
"""
if micro and gs1:
raise ValueError(f'GS1 does not support Micro QR, parameter "gs1" is not None')

version = normalize_version(version)
if not micro and micro is not None and version in consts.MICRO_VERSIONS:
raise ValueError(f'A Micro QR Code version ("{get_version_name(version)}") '
Expand All @@ -66,6 +69,7 @@ def encode(content, error=None, version=None, mode=None, mask=None,
raise ValueError(f'Illegal Micro QR Code version "{get_version_name(version)}"')
error = normalize_errorlevel(error, accept_none=True)
mode = normalize_mode(mode)
gs1 = normalize_gs1(gs1)
if mode is not None and version is not None \
and not is_mode_supported(mode, version):
raise ValueError(f'Mode "{get_mode_name(mode)}" is not available in version "{get_version_name(version)}"')
Expand All @@ -84,7 +88,7 @@ def encode(content, error=None, version=None, mode=None, mask=None,
error = consts.ERROR_LEVEL_L
is_micro = version < 1
mask = normalize_mask(mask, is_micro)
return _encode(segments, error, version, mask, eci, boost_error)
return _encode(segments, error, version, mask, eci, boost_error, gs1=gs1)


def encode_sequence(content, error=None, version=None, mode=None, mask=None,
Expand Down Expand Up @@ -199,7 +203,7 @@ def number_of_symbols_by_version(content, version, error, mode):
sa_info=sa_info(i)) for i, chunk in enumerate(chunks)]


def _encode(segments, error, version, mask, eci, boost_error, sa_info=None):
def _encode(segments, error, version, mask, eci, boost_error, sa_info=None, gs1=None):
"""\
Creates a (Micro) QR code.

Expand All @@ -222,8 +226,9 @@ def _encode(segments, error, version, mask, eci, boost_error, sa_info=None):
buff.append_bits(i, 4)
buff.append_bits(sa_info.parity, 8)
# ISO/IEC 18004:2015(E) -- 7.4 Data encoding (page 22)
for segment in segments:
write_segment(buff, segment, ver, ver_range, eci)
for e,segment in enumerate(segments):
gs_seperator = e+1<len(segments)
write_segment(buff, segment, ver, ver_range, eci, gs1, gs_seperator=gs_seperator)
capacity = consts.SYMBOL_CAPACITY[version][error]
# ISO/IEC 18004:2015(E) -- 7.4.9 Terminator (page 32)
write_terminator(buff, capacity, ver, len(buff))
Expand Down Expand Up @@ -282,7 +287,7 @@ def boost_error_level(version, error, segments, eci, is_sa=False):
return error


def write_segment(buff, segment, ver, ver_range, eci=False):
def write_segment(buff, segment, ver, ver_range, eci=False, gs1=None,gs_seperator=None):
"""\
Writes a segment.

Expand All @@ -301,6 +306,8 @@ def write_segment(buff, segment, ver, ver_range, eci=False):
append_bits(consts.MODE_ECI, 4)
append_bits(get_eci_assignment_number(segment.encoding), 8)
if ver is None: # QR Code
if gs1:
append_bits(gs1, 4)
append_bits(mode, 4)
if mode == consts.MODE_HANZI:
subset = 1 # Indicator for GB2312 subset
Expand All @@ -311,6 +318,12 @@ def write_segment(buff, segment, ver, ver_range, eci=False):
append_bits(segment.char_count,
consts.CHAR_COUNT_INDICATOR_LENGTH[mode][ver_range])
buff.extend(segment.bits)
# skip if last segment?
if gs_seperator:
if gs1 and mode is consts.MODE_ALPHANUMERIC:
append_bits(consts.GS_ALPHANUMERIC,8)
elif gs1 and mode is consts.MODE_BYTE:
append_bits(consts.GS_BYTES,8)


def write_terminator(buff, capacity, ver, length):
Expand Down Expand Up @@ -1205,6 +1218,30 @@ def normalize_mode(mode):
except (KeyError, AttributeError):
raise ValueError(f'Illegal mode "{mode}". '
f'Supported values: {", ".join(sorted(consts.MODE_MAPPING.keys()))}')



def normalize_gs1(position):
"""\
Returns a Functiona 1 character position constant which is equivalent to the
provided `position`.

In case the provided `mode` is ``None``, this function returns ``None``.
Otherwise a mode constant is returned unless the provided parameter cannot
be mapped to a valid mode. In the latter case, a :py:exc:`ValueError` is raised.

:param mode: An integer or string or ``None``.
:raises: :py:exc:`ValueError` In case the provided `mode` does not represent a valid
QR Code mode.
:rtype: int or None
"""
if position is None or position in consts.FNC1_MAPPING.values():
return position
try:
return consts.FNC1_MAPPING[position.lower()]
except (KeyError, AttributeError):
raise ValueError(f'Illegal mode "{position}". '
f'Supported values: {", ".join(sorted(consts.FNC1_MAPPING.keys()))}')


def normalize_mask(mask, is_micro):
Expand Down
55 changes: 55 additions & 0 deletions tests/test_gs1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# import sys
# sys.path.append(r"C:\Users\Willis\Desktop\segno\segno")


import segno

qr=segno.make("2100",version=1,gs1="first")
qr.show()

# https://www.gs1jp.org/assets/img/pdf/GS1_General_Specifications.pdf

# https://ref.gs1.org/ai/j
# AI_DATA_MAPPING = {
# 21: "N2+x..20"
# }

# GS1_CHARACTER_SET_82 = [

# ]

# # page 155
# # n implied decimal point position
# # N numeric digit
# # X any character in figure 7.11-1 character set 82
# # N3 3 numeric digits, predefined length
# # X3 3 characters, fixed length
# # N..3 up to 3 numeric digits
# # X..3 up to 3 characters in figure 7.11-1
# # DD must be filled

# AI_MAPPING = {
# 21: "N2+X..20"
# }


# def generate_gs1(string):
# left_b_split=string.split("[",)
# if left_b_split[0]:
# raise ValueError(f'"string" must start with an AI in brackets "[]"')
# ai_b_data=left_b_split[1:]
# elements=[]
# for i in range(len(ai_b_data)):
# try:
# ai,data=ai_b_data[i].split("]")
# except:
# raise ValueError(f'"string" contains open AI bracket')
# if not ai.isdecimal():
# raise ValueError("AI must be a whole number")
# if not data.isalnum():
# raise ValueError("Data must only contain characters 0-9, A-Z, and (#-/)")
# print(ai, data)
# elements.append((ai,data))
# print(elements)

# generate_gs1("[21]00[21]00")