Device Detection services for 51Degrees Pipeline

onpremise/offlineprocessing.py

Provides an example of processing a YAML file containing evidence for device detection.

Provides an example of processing a YAML file containing evidence for device detection.There are 20,000 examples in the supplied file of evidence representing HTTP Headers. For example:

header.user-agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
header.sec-ch-ua: '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"'
header.sec-ch-ua-full-version: '"98.0.4758.87"'
header.sec-ch-ua-mobile: '?0'
header.sec-ch-ua-platform: '"Android"'

We create a device detection pipeline to read the data and find out about the associated device, we write this data to a YAML formatted output stream.

As well as explaining the basic operation of off line processing using the defaults, for advanced operation this example can be used to experiment with tuning device detection for performance and predictive power using Performance Profile, Graph and Difference and Drift settings.

This example is available in full on GitHub.

This example requires a local data file. The free 'Lite' data file can be downloaded with the scripts in the data GitHub repository, which this repository includes at cxx/data. Fetch the submodules by running git submodule update --init --recursive, then run sh cxx/data/get-data-files.sh 51Degrees-LiteV4.1.hash from the repository root, which saves the file as cxx/data/device-detection/51Degrees-LiteV4.1.hash.

The Lite data file is only used for illustration, and has limited accuracy and capabilities. The Enterprise data file has every property. Contact us about a copy.

Required PyPi Dependencies:

# *********************************************************************
# This Original Work is copyright of 51 Degrees Mobile Experts Limited.
# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
#
# This Original Work is licensed under the European Union Public Licence
# (EUPL) v.1.2 and is subject to its terms as set out below.
#
# If a copy of the EUPL was not distributed with this file, You can obtain
# one at https://opensource.org/licenses/EUPL-1.2.
#
# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
# amended by the European Commission) shall be deemed incompatible for
# the purposes of the Work and the provisions of the compatibility
# clause in Article 5 of the EUPL shall not apply.
#
# If using the Work as, or as part of, a network application, by
# including the attribution notice(s) required under Article 5 of the EUPL
# in the end user terms of the application under an appropriate heading,
# such notice(s) shall fulfill the requirements of that article.
# *********************************************************************
from pathlib import Path
import sys
from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
from ruamel.yaml import YAML
# Where to ask for a copy of the Enterprise data file, tagged with this
# example.
CONTACT_US = "/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=enterprise-data-file"
# The properties only the Enterprise data file has, which are recorded as
# needing it when the data file in use does not have them.
ENTERPRISE_PROPERTIES = [
"tac",
"devicetype",
"hardwarevendor",
"hardwarename",
"hardwaremodel",
"nativedevice",
"nativename",
"nativemodel"]
class OfflineProcessing():
def run(self, data_file, evidence_yaml, logger, output):
"""!
Process a YAML representation of evidence - and create a YAML output containing
the processed evidence.
@param data_file: The path to the device detection data file
@param evidence_yaml: File containing the yaml representation of the evidence to process
@param logger: Logger to use within the pipeline
@param output: Output file to write results to
@return: True when the data file lacks properties that only the
Enterprise data file has
"""
# In this example, we use the DeviceDetectionPipelineBuilder
# and configure it in code. For more information about
# pipelines in general see the documentation at
# /documentation/_pipeline_api__concepts__configuration__builders__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=run
pipeline = DeviceDetectionPipelineBuilder(
data_file_path = data_file,
# We use the low memory profile as its performance is
# sufficient for this example. See the documentation for
# more detail on this and other configuration options:
# /documentation/_device_detection__features__performance_options.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=run
# /documentation/_pipeline_api__features__automatic_datafile_updates.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=run
# /documentation/_pipeline_api__features__usage_sharing.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=run
performance_profile = "LowMemory",
# inhibit sharing usage for this test, usually this
# should be set "true"
# In general, off line processing usage should NOT be shared back to 51Degrees.
# This is because it will not contain the full set of information that is
# required by our data processing back-end and will be discarded.
# If you specifically want to share data that is being processed off line
# in order to help us improve detection of new devices/browsers/etc, then
# this additional data will need to be collected and included as evidence
# to the Pipeline. See
# /documentation/_pipeline_api__features__usage_sharing.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=run#Low_Level_Usage_Sharing
# for more details on this.
usage_sharing = False,
# Inhibit auto-update of the data file for this example
auto_update = False,
licence_keys = "").add_logger(logger).build()
# The pipeline is closed at the end of the with block, which
# releases the native data it holds.
with pipeline:
records = 0
yaml = YAML()
# Replace tab characters as they are not valid in unquoted YAML values
# and some evidence files contain them in user-agent strings.
content = evidence_yaml.read().replace('\t', ' ')
yaml_data = yaml.load_all(content)
# The properties only the Enterprise data file has that the data
# file in use lacks, found once rather than for every record.
engine = pipeline.get_element("device")
missing = [name for name in ENTERPRISE_PROPERTIES
if not ExampleUtils.has_property(engine, name)]
try:
# Keep going as long as we have more document records.
for evidence in yaml_data:
# Output progress.
records = records + 1
if (records % 100 == 0):
logger.log("info", f"Processed {records} records")
# write the yaml document separator
print("---", file = output)
# Pass the record to the pipeline as evidence so that it can be analyzed
headers = {}
for key in evidence:
# Convert to string - YAML may parse values like ?1 as booleans
# Keys already have header. prefix in the YAML file
headers[key] = str(evidence[key])
self.analyseEvidence(
headers, pipeline, output, yaml, missing)
except BaseException as err:
# We can't read the evidence values, so cant write them to the output. Will just
# have to skip this entry.
logger.log("error", err)
if missing:
# A comment keeps the output a valid YAML stream.
print("# " + ExampleUtils.get_enterprise_note(CONTACT_US),
file = output)
# write the yaml document end marker
print("...", file = output)
ExampleUtils.check_data_file(pipeline, logger)
return len(missing) > 0
def analyseEvidence(self, evidence, pipeline, output, yaml, missing):
# FlowData is a data structure that is used to convey information required for
# detection and the results of the detection through the pipeline.
# Information required for detection is called "evidence" and usually consists
# of a number of HTTP Header field values, in this case represented by a
# dictionary of header name/value entries.
# Closing the FlowData, which the with statement does at the end of
# the block, releases the results of the detection straight away.
# Without it each record's results would stay in memory until the
# garbage collector next runs.
with pipeline.create_flowdata() as data:
# Add the evidence values to the flow data
data.evidence.add_from_dict(evidence)
# Process the flow data.
data.process()
device = data.device
values = {}
# Add the evidence values to the output
for key in evidence:
values[key] = evidence[key]
# Now add the values that we want to store against the record.
values["device.ismobile"] = device.ismobile.value() if device.ismobile.has_value() else "Unknown"
values["device.platformname"] = ExampleUtils.get_human_readable(device, "platformname")
values["device.platformversion"] = ExampleUtils.get_human_readable(device, "platformversion")
values["device.browsername"] = ExampleUtils.get_human_readable(device, "browsername")
values["device.browserversion"] = ExampleUtils.get_human_readable(device, "browserversion")
# The value of a property the data file does not have is not
# read.
for property in ENTERPRISE_PROPERTIES:
values["device." + property] = (
ExampleUtils.NEEDS_ENTERPRISE if property in missing
else ExampleUtils.get_human_readable(device, property))
# DeviceId is a unique identifier for the combination of hardware, operating
# system, browser and crawler that has been detected.
# Our device detection solution uses machine learning to find the optimal
# way to identify devices based on the real-world evidence values that we
# observe each day.
# As this changes over time, the result of detection can potentially change
# as well. By storing the device id, we can use this as a lookup in future
# rather than performing detection with the original evidence again.
# Do this by passing an evidence entry with:
# key = query.51D_ProfileIds
# value = [the device id]
# This is much faster and avoids the potential for getting a different
# result.
values["device.deviceid"] = ExampleUtils.get_human_readable(device, "deviceid")
yaml.dump(values, output)
def main(argv):
# In this example, by default, the 51degrees "Lite" file needs to be
# somewhere in the project space, or you may specify another file as
# a command line parameter.
#
# Note that the Lite data file is only used for illustration, and has
# a small number of Properties.
# Contact us for a copy of the Enterprise data file:
# /contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_devicedetection_examples-src-fiftyone_devicedetection_examples-onpremise-offlineprocessing.py&utm_term=main
data_file = argv[0] if len(argv) > 0 else ExampleUtils.find_file(LITE_DATAFILE_NAME)
# This file contains the 20,000 most commonly seen combinations of header values
# that are relevant to device detection. For example, User-Agent and UA-CH headers.
evidence_file = argv[1] if len(argv) > 1 else ExampleUtils.find_file(EVIDENCE_FILE_NAME)
# Finally, get the location for the output file. Use the same location as the
# evidence if a path is not supplied on the command line.
output_file = argv[2] if len(argv) > 2 else Path.joinpath(Path(evidence_file).absolute().parent, "offline-processing-output.yml")
# Configure a logger to output to the console.
logger = Logger(min_level="info")
if (data_file != None):
with open(output_file, "w") as output:
with open(evidence_file, "r") as input:
needs_enterprise = OfflineProcessing().run(
data_file, input, logger, output)
print(f"Processing complete. See results in: '{output_file}'")
if needs_enterprise:
print(ExampleUtils.get_enterprise_note(CONTACT_US))
else:
logger.log("error",
"Failed to find a device detection data file. Make sure the " +
"data submodule is there, by running " +
"`git submodule update --init --recursive`, and run this " +
"example again to download the file.")
if __name__ == "__main__":
main(sys.argv[1:])
Definition onpremise/build/__init__.py:1
Definition devicedetection_pipelinebuilder.py:1
Definition example_constants.py:1