\r\n

51Degrees Device Detection Python  4.4

Device Detection services for 51Degrees Pipeline

cloud/gettingstarted_console.py

This example shows how to use the 51Degrees Cloud service 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 the 51Degrees cloud service
  2. How to pass input data (evidence) to the Pipeline
  3. How to retrieve the results

This example is available in full on GitHub.

To run this example, you will need to create a resource key. The resource key is used as shorthand to store the particular set of properties you are interested in as well as any associated license keys that entitle you to increased request limits and/or paid-for properties.

You can create a resource key using the 51Degrees Configurator.

Required PyPi Dependencies:

1 # *********************************************************************
2 # This Original Work is copyright of 51 Degrees Mobile Experts Limited.
3 # Copyright 2025 51 Degrees Mobile Experts Limited, Davidson House,
4 # Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
5 #
6 # This Original Work is licensed under the European Union Public Licence
7 # (EUPL) 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 
24 
35 
36 import json5
37 from pathlib import Path
38 import sys
39 from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder
40 from fiftyone_pipeline_core.logger import Logger
41 from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder
42 # pylint: disable=E0402
43 from ..example_utils import ExampleUtils
44 
45 class GettingStartedConsole():
46  def run(self, config, logger, output):
47 
48  # In this example, we use the PipelineBuilder and configure it from a file.
49  # For more information about builders in general see the documentation at
50  # https://51degrees.com/documentation/_concepts__configuration__builders__index.html
51 
52  # Create the pipeline using the service provider and the configured options.
53  pipeline = PipelineBuilder().add_logger(logger).build_from_configuration(config)
54 
55  # carry out some sample detections
56  for values in self.EvidenceValues:
57  self.analyseEvidence(values, pipeline, output)
58 
59  def analyseEvidence(self, evidence, pipeline, output):
60 
61  # FlowData is a data structure that is used to convey
62  # information required for detection and the results of the
63  # detection through the pipeline.
64  # Information required for detection is called "evidence"
65  # and usually consists of a number of HTTP Header field
66  # values, in this case represented by a dictionary of header
67  # name/value entries.
68  data = pipeline.create_flowdata()
69 
70  message = []
71 
72  # List the evidence
73  message.append("Input values:\n")
74  for key in evidence:
75  message.append(f"\t{key}: {evidence[key]}\n")
76 
77  output("".join(message))
78 
79  # Add the evidence values to the flow data
80  data.evidence.add_from_dict(evidence)
81 
82  # Process the flow data.
83  data.process()
84 
85  message = []
86  message.append("Results:\n")
87 
88  # Now that it's been processed, the flow data will have
89  # been populated with the result. In this case, we want
90  # information about the device, which we can get by
91  # asking for a result matching named "device"
92  device = data.device
93 
94  # Display the results of the detection, which are called
95  # device properties. See the property dictionary at
96  # https://51degrees.com/developers/property-dictionary
97  # for details of all available properties.
98  self.outputValue("Mobile Device", device.ismobile, message)
99  self.outputValue("Platform Name", device.platformname, message)
100  self.outputValue("Platform Version", device.platformversion, message)
101  self.outputValue("Browser Name", device.browsername, message)
102  self.outputValue("Browser Version", device.browserversion, message)
103  output("".join(message))
104 
105  def outputValue(self, name, value, message):
106  # Individual result values have a wrapper called
107  # `AspectPropertyValue`. This functions similarly to
108  # a null-able type.
109  # If the value has not been set then trying to access the
110  # `value` method will throw an exception.
111  # `AspectPropertyValue` also includes the `no_value_message`
112  # method, which describes why the value has not been set.
113  message.append(
114  f"\t{name}: {value.value()}\n" if value.has_value()
115  else f"\t{name}: {value.no_value_message()}\n")
116 
117 
118  # This collection contains the various input values that will
119  # be passed to the device detection algorithm.
120  EvidenceValues = [
121  # A User-Agent from a mobile device.
122  { "header.user-agent":
123  "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G960U) "
124  "AppleWebKit/537.36 (KHTML, like Gecko) "
125  "SamsungBrowser/10.1 Chrome/71.0.3578.99 Mobile Safari/537.36" },
126  # A User-Agent from a desktop device.
127  { "header.user-agent":
128  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
129  "AppleWebKit/537.36 (KHTML, like Gecko) "
130  "Chrome/78.0.3904.108 Safari/537.36" },
131  # Evidence values from a windows 11 device using a browser
132  # that supports User-Agent Client Hints.
133  { "header.user-agent":
134  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
135  "AppleWebKit/537.36 (KHTML, like Gecko) "
136  "Chrome/98.0.4758.102 Safari/537.36",
137  "header.sec-ch-ua-mobile": "?0",
138  "header.sec-ch-ua":
139  "\" Not A; Brand\";v=\"99\", \"Chromium\";v=\"98\", "
140  "\"Google Chrome\";v=\"98\"",
141  "header.sec-ch-ua-platform": "\"Windows\"",
142  "header.sec-ch-ua-platform-version": "\"14.0.0\"" }
143  ]
144 
145 def main(argv):
146  # Use the command line args to get the resource key if present.
147  # Otherwise, get it from the environment variable.
148  resource_key = argv[0] if len(argv) > 0 else ExampleUtils.get_resource_key()
149 
150  # Configure a logger to output to the console.
151  logger = Logger(min_level="info")
152 
153  # Load the configuration file
154  configFile = Path(__file__).resolve().parent.joinpath("gettingstarted_console.json").read_text()
155  config = json5.loads(configFile)
156 
157  # Get the resource key setting from the config file.
158  resourceKeyFromConfig = ExampleUtils.get_resource_key_from_config(config)
159  configHasKey = resourceKeyFromConfig and resourceKeyFromConfig.startswith("!!") == False
160 
161  # If no resource key is specified in the config file then override it with the key
162  # from the environment variable / command line.
163  if configHasKey == False:
164  ExampleUtils.set_resource_key_in_config(config, resource_key)
165 
166  # If we don't have a resource key then log an error.
167  if not ExampleUtils.get_resource_key_from_config(config):
168  logger.log("error",
169  "No resource key specified in the configuration file " +
170  "'gettingstarted_console.json' or the environment variable " +
171  f"'{ExampleUtils.RESOURCE_KEY_ENV_VAR}'. The 51Degrees cloud " +
172  "service is accessed using a 'ResourceKey'. For more information " +
173  "see " +
174  "https://51degrees.com/documentation/_info__resource_keys.html. " +
175  "A resource key with the properties required by this example can be " +
176  "created for free at https://configure.51degrees.com/1QWJwHxl. " +
177  "Once complete, populate the config file or environment variable " +
178  "mentioned at the start of this message with the key.")
179  else:
180  GettingStartedConsole().run(config, logger, print)
181 
182 if __name__ == "__main__":
183  main(sys.argv[1:])