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:
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 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.
from pathlib import Path
import sys
from ruamel.yaml import YAML
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"
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
"""
pipeline = DeviceDetectionPipelineBuilder(
data_file_path = data_file,
performance_profile = "LowMemory",
usage_sharing = False,
auto_update = False,
licence_keys =
"").add_logger(logger).
build()
with pipeline:
records = 0
yaml = YAML()
content = evidence_yaml.read().replace('\t', ' ')
yaml_data = yaml.load_all(content)
engine = pipeline.get_element("device")
missing = [name for name in ENTERPRISE_PROPERTIES
if not ExampleUtils.has_property(engine, name)]
try:
for evidence in yaml_data:
records = records + 1
if (records % 100 == 0):
logger.log("info", f"Processed {records} records")
print("---", file = output)
headers = {}
for key in evidence:
headers[key] = str(evidence[key])
self.analyseEvidence(
headers, pipeline, output, yaml, missing)
except BaseException as err:
logger.log("error", err)
if missing:
print("# " + ExampleUtils.get_enterprise_note(CONTACT_US),
file = output)
print("...", file = output)
ExampleUtils.check_data_file(pipeline, logger)
return len(missing) > 0
def analyseEvidence(self, evidence, pipeline, output, yaml, missing):
with pipeline.create_flowdata() as data:
data.evidence.add_from_dict(evidence)
data.process()
device = data.device
values = {}
for key in evidence:
values[key] = evidence[key]
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")
for property in ENTERPRISE_PROPERTIES:
values["device." + property] = (
ExampleUtils.NEEDS_ENTERPRISE if property in missing
else ExampleUtils.get_human_readable(device, property))
values["device.deviceid"] = ExampleUtils.get_human_readable(device, "deviceid")
yaml.dump(values, output)
def main(argv):
data_file = argv[0] if len(argv) > 0 else ExampleUtils.find_file(LITE_DATAFILE_NAME)
evidence_file = argv[1] if len(argv) > 1 else ExampleUtils.find_file(EVIDENCE_FILE_NAME)
output_file = argv[2] if len(argv) > 2 else Path.joinpath(Path(evidence_file).absolute().parent, "offline-processing-output.yml")
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_utils.py:1
Definition example_constants.py:1