\r\n

51Degrees Device Detection Python  4.3Newer Version 4.4

Device Detection services for 51Degrees Pipeline

onpremise/gettingstarted_console.py

This example shows how to use 51Degrees on-premise device detection to determine details about a device based on its User-Agent and User-Agent Client Hint HTTP header values.

You will learn:

  1. How to create a Pipeline that uses 51Degrees on-premise device detection
  2. How to pass input data (evidence) to the Pipeline
  3. How to retrieve the results

This example is available in full on GitHub.

This example requires a local data file. The free 'Lite' data file can be acquired by pulling the git submodules under this repository (run `git submodule update --recursive`) or from the device-detection-data GitHub repository.

The Lite data file is only used for illustration, and has limited accuracy and capabilities. Find out about the more capable data files that are available on our pricing page

Required PyPi Dependencies:

  • fiftyone_devicedetection
1 # *********************************************************************
2 # This Original Work is copyright of 51 Degrees Mobile Experts Limited.
3 # Copyright 2019 51 Degrees Mobile Experts Limited, 5 Charlotte Close,
4 # Caversham, Reading, Berkshire, United Kingdom RG4 7BY.
5 #
6 # This Original Work is licensed under the European Union Public Licence (EUPL)
7 # v.1.2 and is subject to its terms as set out below.
8 #
9 # If a copy of the EUPL was not distributed with this file, You can obtain
10 # one at https://opensource.org/licenses/EUPL-1.2.
11 #
12 # The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
13 # amended by the European Commission) shall be deemed incompatible for
14 # the purposes of the Work and the provisions of the compatibility
15 # clause in Article 5 of the EUPL shall not apply.
16 #
17 # If using the Work as, or as part of, a network application, by
18 # including the attribution notice(s) required under Article 5 of the EUPL
19 # in the end user terms of the application under an appropriate heading,
20 # such notice(s) shall fulfill the requirements of that article.
21 # ********************************************************************
22 
23 
34 
35 # todo rework pipeline.logging to match logging.
36 import logging
37 import sys
38 from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
39 from fiftyone_devicedetection_examples.example_utils import ExampleUtils
40 
41 # In this example, by default, the 51degrees "Lite" file needs to be
42 # somewhere in the project space, or you may specify another file as
43 # a command line parameter.
44 #
45 # Note that the Lite data file is only used for illustration, and has
46 # limited accuracy and capabilities.
47 # Find out about the Enterprise data file on our pricing page:
48 # https://51degrees.com/pricing
49 LITE_V_4_1_HASH = "51Degrees-LiteV4.1.hash";
50 
51 class GettingStartedConsole():
52  def run(self, data_file, logger):
53 
54  # In this example, we use the DeviceDetectionPipelineBuilder
55  # and configure it in code. For more information about
56  # pipelines in general see the documentation at
57  # http://51degrees.com/documentation/4.3/_concepts__configuration__builders__index.html
58  pipeline = DeviceDetectionPipelineBuilder(
59  data_file_path = data_file,
60  # We use the low memory profile as its performance is
61  # sufficient for this example. See the documentation for
62  # more detail on this and other configuration options:
63  # http://51degrees.com/documentation/4.3/_device_detection__features__performance_options.html
64  # http://51degrees.com/documentation/4.3/_features__automatic_datafile_updates.html
65  # http://51degrees.com/documentation/4.3/_features__usage_sharing.html
66  performance_profile = "LowMemory",
67  # inhibit sharing usage for this test, usually this
68  # should be set "true"
69  auto_update = False,
70  licence_keys = "").build()
71 
72  ExampleUtils.check_data_file(pipeline, logger);
73 
74  # carry out some sample detections
75  for values in self.EvidenceValues:
76  self.analyseEvidence(values, pipeline, logger)
77 
78  def analyseEvidence(self, evidence, pipeline, logger):
79 
80  # FlowData is a data structure that is used to convey
81  # information required for detection and the results of the
82  # detection through the pipeline.
83  # Information required for detection is called "evidence"
84  # and usually consists of a number of HTTP Header field
85  # values, in this case represented by a dictionary of header
86  # name/value entries.
87  data = pipeline.create_flowdata()
88 
89  message = []
90 
91  # List the evidence
92  message.append("Input values:\n")
93  for key in evidence:
94  message.append(f"\t{key}: {evidence[key]}\n")
95 
96  logger.info("".join(message))
97 
98  # Add the evidence values to the flow data
99  data.evidence.add_from_dict(evidence)
100 
101  # Process the flow data.
102  data.process()
103 
104  message = []
105  message.append("Results:\n")
106 
107  # Now that it's been processed, the flow data will have
108  # been populated with the result. In this case, we want
109  # information about the device, which we can get by
110  # asking for a result matching named "device"
111  device = data.device
112 
113  # Display the results of the detection, which are called
114  # device properties. See the property dictionary at
115  # https://51degrees.com/developers/property-dictionary
116  # for details of all available properties.
117  self.outputValue("Mobile Device", device.ismobile, message);
118  self.outputValue("Platform Name", device.platformname, message);
119  self.outputValue("Platform Version", device.platformversion, message);
120  self.outputValue("Browser Name", device.browsername, message);
121  self.outputValue("Browser Version", device.browserversion, message);
122  logger.info("".join(message));
123 
124  def outputValue(self, name, value, message):
125  # Individual result values have a wrapper called
126  # `AspectPropertyValue`. This functions similarly to
127  # a null-able type.
128  # If the value has not been set then trying to access the
129  # `value` method will throw an exception.
130  # `AspectPropertyValue` also includes the `no_value_message`
131  # method, which describes why the value has not been set.
132  message.append(
133  f"\t{name}: {value.value()}\n" if value.has_value()
134  else f"\t{name}: {value.no_value_message()}\n")
135 
136 
137  # This collection contains the various input values that will
138  # be passed to the device detection algorithm.
139  EvidenceValues = [
140  # A User-Agent from a mobile device.
141  { "header.user-agent":
142  "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G960U) "
143  "AppleWebKit/537.36 (KHTML, like Gecko) "
144  "SamsungBrowser/10.1 Chrome/71.0.3578.99 Mobile Safari/537.36" },
145  # A User-Agent from a desktop device.
146  { "header.user-agent":
147  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
148  "AppleWebKit/537.36 (KHTML, like Gecko) "
149  "Chrome/78.0.3904.108 Safari/537.36" },
150  # Evidence values from a windows 11 device using a browser
151  # that supports User-Agent Client Hints.
152  { "header.user-agent":
153  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
154  "AppleWebKit/537.36 (KHTML, like Gecko) "
155  "Chrome/98.0.4758.102 Safari/537.36",
156  "header.sec-ch-ua-mobile": "?0",
157  "header.sec-ch-ua":
158  "\" Not A; Brand\";v=\"99\", \"Chromium\";v=\"98\", "
159  "\"Google Chrome\";v=\"98\"",
160  "header.sec-ch-ua-platform": "\"Windows\"",
161  "header.sec-ch-ua-platform-version": "\"14.0.0\"" }
162  ]
163 
164 def main(argv):
165  # Use the supplied path for the data file or find the lite
166  # file that is included in the repository.
167  data_file = argv[0] if len(argv) > 0 else ExampleUtils.find_file(LITE_V_4_1_HASH)
168 
169  # Configure a logger to output to the console.
170  logger = logging.getLogger("Getting Started")
171  logger.setLevel(logging.INFO)
172 
173  if (data_file != None):
174  GettingStartedConsole().run(data_file, logger)
175  else:
176  logger.error("Failed to find a device detection " +
177  "data file. Make sure the device-detection-data " +
178  "submodule has been updated by running " +
179  "`git submodule update --recursive`.")
180 
181 if __name__ == "__main__":
182  main(sys.argv[1:])