biip.gs1
Support for barcode data with GS1 element strings.
The biip.gs1
module contains Biip’s support for parsing data
consisting of GS1 Element Strings. Each Element String is identified by a GS1
Application Identifier (AI) prefix.
Data of this format is found in the following types of barcodes:
GS1-128
GS1 DataBar
GS1 DataMatrix
GS1 QR Code
If you only want to parse GS1 Messages, you can import the GS1 Message parser
directly instead of using biip.parse()
.
>>> from biip.gs1 import GS1Message
If the parsing succeeds, it returns a GS1Message
object.
>>> msg = GS1Message.parse("010703206980498815210526100329")
The GS1Message
has a raw value as well as an HRI, short for “human readable
interpretation”. The HRI is the text usually printed below or next to the
barcode.
>>> msg.value
'010703206980498815210526100329'
>>> msg.as_hri()
'(01)07032069804988(15)210526(10)0329'
HRI can also be parsed.
>>> GS1Message.parse_hri("(01)07032069804988(15)210526(10)0329")
A message can contain multiple element strings.
>>> len(msg.element_strings)
3
In this example, the first element string is a GTIN.
>>> msg.element_strings[0]
GS1ElementString(ai=GS1ApplicationIdentifier(ai='01', description='Global
Trade Item Number (GTIN)', data_title='GTIN', fnc1_required=False,
format='N2+N14'), value='07032069804988', pattern_groups=['07032069804988'],
gln=None, gln_error=None, gtin=Gtin(value='07032069804988',
format=GtinFormat.GTIN_13, prefix=GS1Prefix(value='703', usage='GS1
Norway'), company_prefix=GS1CompanyPrefix(value='703206'),
payload='703206980498', check_digit=8, packaging_level=None),
gtin_error=None, sscc=None, sscc_error=None, date=None, datetime=None,
decimal=None, money=None)
The message object has get()
and filter()
methods to lookup element strings either by the Application Identifier’s
“data title” or its AI number.
>>> msg.get(data_title='BEST BY')
GS1ElementString(ai=GS1ApplicationIdentifier(ai='15', description='Best
before date (YYMMDD)', data_title='BEST BEFORE or BEST BY',
fnc1_required=False, format='N2+N6'), value='210526',
pattern_groups=['210526'], gln=None, gln_error=None, gtin=None,
gtin_error=None, sscc=None, sscc_error=None, date=datetime.date(2021, 5,
26), datetime=None, decimal=None, money=None)
>>> msg.get(ai="10")
GS1ElementString(ai=GS1ApplicationIdentifier(ai='10', description='Batch
or lot number', data_title='BATCH/LOT', fnc1_required=True,
format='N2+X..20'), value='0329', pattern_groups=['0329'], gln=None,
gln_error=None, gtin=None, gtin_error=None, sscc=None, sscc_error=None,
date=None, datetime=None, decimal=None, money=None)
- class biip.gs1.GS1CompanyPrefix(value)
Company prefix assigned by GS1.
The prefix assigned to a single company.
Example
>>> from biip.gs1 import GS1CompanyPrefix >>> GS1CompanyPrefix.extract("7044610873466") GS1CompanyPrefix(value='704461')
-
value:
str
The company prefix itself.
- classmethod extract(value)
Extract the GS1 Company Prefix from the given value.
- Parameters:
value (
str
) – The string to extract a GS1 Company Prefix from. The value is typically a GLN, GTIN, or an SSCC.- Return type:
Optional
[GS1CompanyPrefix
]- Returns:
Metadata about the extracted prefix, or None if the prefix is unknown.
- Raises:
ParseError – If the parsing fails.
-
value:
- class biip.gs1.GS1Message(value, element_strings)
A GS1 message is the result of a single barcode scan.
It may contain one or more GS1 Element Strings.
Example
See
biip.gs1
for a usage example.-
value:
str
Raw unprocessed value.
-
element_strings:
list
[GS1ElementString
] List of Element Strings found in the message.
- classmethod parse(value, *, rcn_region=None, rcn_verify_variable_measure=True, separator_chars=('\\x1d',))
Parse a string from a barcode scan as a GS1 message with AIs.
- Parameters:
value (
str
) – The string to parse.rcn_region (
Optional
[RcnRegion
]) – The geographical region whose rules should be used to interpret Restricted Circulation Numbers (RCN). Needed to extract e.g. variable weight/price from GTIN.rcn_verify_variable_measure (
bool
) – Whether to verify that the variable measure in a RCN matches its check digit, if present. Some companies use the variable measure check digit for other purposes, requiring this check to be disabled.separator_chars (
Iterable
[str
]) – Characters used in place of the FNC1 symbol. Defaults to <GS> (ASCII value 29). If variable-length fields in the middle of the message are not terminated with a separator character, the parser might greedily consume the rest of the message.
- Return type:
- Returns:
A message object with one or more element strings.
- Raises:
ValueError – If the
separator_char
isn’t exactly 1 character long.ParseError – If the parsing fails.
- classmethod parse_hri(value, *, rcn_region=None, rcn_verify_variable_measure=True)
Parse the GS1 string given in HRI (human readable interpretation) format.
- Parameters:
value (
str
) – The HRI string to parse.rcn_region (
Optional
[RcnRegion
]) – The geographical region whose rules should be used to interpret Restricted Circulation Numbers (RCN). Needed to extract e.g. variable weight/price from GTIN.rcn_verify_variable_measure (
bool
) – Whether to verify that the variable measure in a RCN matches its check digit, if present. Some companies use the variable measure check digit for other purposes, requiring this check to be disabled.
- Return type:
- Returns:
A message object with one or more element strings.
- Raises:
ParseError – If parsing of the data fails.
- as_hri()
Render as a human readable interpretation (HRI).
The HRI is often printed directly below barcodes.
- Return type:
str
- Returns:
A human-readable string where the AIs are wrapped in parenthesis.
- filter(*, ai=None, data_title=None)
Filter Element Strings by AI or data title.
- Parameters:
ai (
Union
[str
,GS1ApplicationIdentifier
,None
]) – AI instance or string to match against the start of the Element String’s AI.data_title (
Optional
[str
]) – String to find anywhere in the Element String’s AI data title.
- Return type:
list
[GS1ElementString
]- Returns:
All matching Element Strings in the message.
- get(*, ai=None, data_title=None)
Get Element String by AI or data title.
- Parameters:
ai (
Union
[str
,GS1ApplicationIdentifier
,None
]) – AI instance or string to match against the start of the Element String’s AI.data_title (
Optional
[str
]) – String to find anywhere in the Element String’s AI data title.
- Return type:
Optional
[GS1ElementString
]- Returns:
The first matching Element String in the message.
-
value:
- class biip.gs1.GS1ElementString(ai, value, pattern_groups, gln=None, gln_error=None, gtin=None, gtin_error=None, sscc=None, sscc_error=None, date=None, datetime=None, decimal=None, money=None)
GS1 Element String.
An Element String consists of a GS1 Application Identifier (AI) and its data field.
A single barcode can contain multiple Element Strings. Together these are called a “message.”
Example
>>> from biip.gs1 import GS1ElementString >>> element_string = GS1ElementString.extract("0107032069804988") >>> element_string GS1ElementString(ai=GS1ApplicationIdentifier(ai='01', description='Global Trade Item Number (GTIN)', data_title='GTIN', fnc1_required=False, format='N2+N14'), value='07032069804988', pattern_groups=['07032069804988'], gln=None, gln_error=None, gtin=Gtin(value='07032069804988', format=GtinFormat.GTIN_13, prefix=GS1Prefix(value='703', usage='GS1 Norway'), company_prefix=GS1CompanyPrefix(value='703206'), payload='703206980498', check_digit=8, packaging_level=None), gtin_error=None, sscc=None, sscc_error=None, date=None, datetime=None, decimal=None, money=None) >>> element_string.as_hri() '(01)07032069804988'
-
ai:
GS1ApplicationIdentifier
The element’s Application Identifier (AI).
-
value:
str
Raw data field of the Element String. Does not include the AI.
-
pattern_groups:
list
[str
] List of pattern groups extracted from the Element String.
-
gln_error:
Optional
[str
] = None The GLN parse error, if parsing as a GLN was attempted and failed.
-
gtin_error:
Optional
[str
] = None The GTIN parse error, if parsing as a GTIN was attempted and failed.
-
sscc_error:
Optional
[str
] = None The SSCC parse error, if parsing as an SSCC was attempted and failed.
-
date:
Optional
[date
] = None A date created from the element string, if the AI represents a date.
-
datetime:
Optional
[datetime
] = None A datetime created from the element string, if the AI represents a datetime.
-
decimal:
Optional
[Decimal
] = None A decimal value created from the element string, if the AI represents a number.
-
money:
Optional
[Money
] = None A Money value created from the element string, if the AI represents a currency and an amount. Only set if py-moneyed is installed.
- classmethod extract(value, *, rcn_region=None, rcn_verify_variable_measure=True, separator_chars=('\\x1d',))
Extract the first GS1 Element String from the given value.
If the element string contains a primitive data type, like a date, decimal number, or currency, it will be parsed and stored in the
date
,decimal
, ormoney
field respectively. If parsing of a primitive data type fails, aParseError
will be raised.If the element string contains another supported format, like a GLN, GTIN, or SSCC, it will parsed and validated, and the result stored in the fields
gln
,gtin
, orsscc
respectively. If parsing or validation of an inner format fails, thegln_error
,gtin_error
, orsscc_error
field will be set. NoParseError
will be raised.- Parameters:
value (
str
) – The string to extract an Element String from. May contain more than one Element String.rcn_region (
Optional
[RcnRegion
]) – The geographical region whose rules should be used to interpret Restricted Circulation Numbers (RCN). Needed to extract e.g. variable weight/price from GTIN.rcn_verify_variable_measure (
bool
) – Whether to verify that the variable measure in a RCN matches its check digit, if present. Some companies use the variable measure check digit for other purposes, requiring this check to be disabled.separator_chars (
Iterable
[str
]) – Characters used in place of the FNC1 symbol. Defaults to <GS> (ASCII value 29). If variable-length fields are not terminated with a separator character, the parser might greedily consume later fields.
- Return type:
- Returns:
A data class with the Element String’s parts and data extracted from it.
- Raises:
ValueError – If the
separator_char
isn’t exactly 1 character long.ParseError – If the parsing fails.
- as_hri()
Render as a human readable interpretation (HRI).
The HRI is often printed directly below the barcode.
- Return type:
str
- Returns:
A human-readable string where the AI is wrapped in parenthesis.
-
ai:
- class biip.gs1.GS1ApplicationIdentifier(ai, description, data_title, fnc1_required, format, pattern)
GS1 Application Identifier (AI).
AIs are data field prefixes used in several types of barcodes, including GS1-128. The AI defines what semantical meaning and format of the following data field.
AIs standardize how to include e.g. product weight, expiration dates, and lot numbers in barcodes.
References
https://www.gs1.org/standards/barcodes/application-identifiers
Example
>>> from biip.gs1 import GS1ApplicationIdentifier >>> ai = GS1ApplicationIdentifier.extract("01") >>> ai GS1ApplicationIdentifier(ai='01', description='Global Trade Item Number (GTIN)', data_title='GTIN', fnc1_required=False, format='N2+N14') >>> ai.pattern '^01(\\d{14})$'
-
ai:
str
The Application Identifier (AI) itself.
-
description:
str
Description of the AIs use.
-
data_title:
str
Commonly used label/abbreviation for the AI.
-
fnc1_required:
bool
Whether a FNC1 character is required after element strings of this type. This is the case for all AIs that have a variable length.
-
format:
str
Human readable format of the AIs element string.
-
pattern:
str
Regular expression for parsing the AIs element string.
- classmethod extract(value)
Extract the GS1 Application Identifier (AI) from the given value.
- Parameters:
value (
str
) – The string to extract an AI from.- Return type:
- Returns:
Metadata about the extracted AI.
- Raises:
ParseError – If the parsing fails.
Example
>>> from biip.gs1 import GS1ApplicationIdentifier >>> GS1ApplicationIdentifier.extract("010703206980498815210526100329") GS1ApplicationIdentifier(ai='01', description='Global Trade Item Number (GTIN)', data_title='GTIN', fnc1_required=False, format='N2+N14')
-
ai:
- class biip.gs1.GS1Prefix(value, usage)
Prefix assigned by GS1.
Used to split the allocation space of various number schemes, e.g. GTIN, among GS1 organizations worldwide.
The GS1 Prefix does not identify the origin of a product, only where the number was assigned to a GS1 member organization.
References
https://www.gs1.org/standards/id-keys/company-prefix
Example
>>> from biip.gs1 import GS1Prefix >>> GS1Prefix.extract("978-1-492-05374-3") GS1Prefix(value='978', usage='Bookland (ISBN)')
-
value:
str
The prefix itself.
-
usage:
str
Description of who is using the prefix.
- classmethod extract(value)
Extract the GS1 Prefix from the given value.
- Parameters:
value (
str
) – The string to extract a GS1 Prefix from.- Return type:
Optional
[GS1Prefix
]- Returns:
Metadata about the extracted prefix, or None if the prefix is unknown.
- Raises:
ParseError – If the parsing fails.
-
value:
- class biip.gs1.GS1Symbology(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Enum of Symbology Identifiers used in the GS1 system.
References
GS1 General Specifications, figure 5.1.2-2. ISO/IEC 15424:2008.
- EAN_13 = 'E0'
EAN-13, UPC-A, or UPC-E.
- EAN_TWO_DIGIT_ADD_ON = 'E1'
Two-digit add-on symbol for EAN-13.
- EAN_FIVE_DIGIT_ADD_ON = 'E2'
Five-digit add-on symbol for EAN-13.
- EAN_13_WITH_ADD_ON = 'E3'
EAN-13, UPC-A, or UPC-E with add-on symbol.
- EAN_8 = 'E4'
EAN-8
- ITF_14 = 'I1'
ITF-14
- GS1_128 = 'C1'
GS1-128
- GS1_DATABAR = 'e0'
GS1 DataBar
- GS1_COMPOSITE_WITH_SEPARATOR_CHAR = 'e1'
GS1 Composite. Data packet follows an encoded symbol separator character.
- GS1_COMPOSITE_WITH_ESCAPE_CHAR = 'e2'
GS1 Composite. Data packet follows an escape mechanism character.
- GS1_DATAMATRIX = 'd2'
GS1 DataMatrix
- GS1_QR_CODE = 'Q3'
GS1 QR Code
- GS1_DOTCODE = 'J1'
GS1 DotCode
- classmethod with_ai_element_strings()
Symbologies that may contain AI Element Strings.
- Return type:
set
[GS1Symbology
]
- classmethod with_gtin()
Symbologies that may contain GTINs.
- Return type:
set
[GS1Symbology
]
- biip.gs1.DEFAULT_SEPARATOR_CHARS: tuple[str] = ('\x1d',)
The default separator character is <GS>, ASCII value 29.
References
GS1 General Specifications, section 7.8.3.