\r\n

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