summaryrefslogtreecommitdiffstats
path: root/data/wikidata/devices.py
blob: 61483d06e1c503b8efe77dcb1836b72b7c5ca930 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/bin/env python
# Copyright (C) 2020 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import os

from optparse import OptionParser
from tabulate import tabulate

# We don't need a configuration as we only need read-only access to the data
os.environ['PYWIKIBOT_NO_USER_CONFIG'] = '1'
import pywikibot
import pywikibot.config2

from cache import *

# Workaround the following bug:
# https://phabricator.wikimedia.org/T242081
pywikibot.config2.maxlag = 60


def get_id(data):
    # constructs the id from data ['datavalue']['value']['numeric-id']
    value = data.get('datavalue', {}).get('value', {})
    numeric_id = value.get('numeric-id', None)
    if numeric_id:
        return 'Q' + str(numeric_id)
    else:
        return None


def get_label(data, lang='en'):
    return data.get('labels', {}).get(lang, None)


def is_a_smartphone_or_tablet_model(page):
    smartphone_model_id = 'Q19723451'
    tablet_model_id = 'Q155972'

    instances_of = page.get('claims', {}).get('P31', [])
    for instance_of in instances_of:
        instance_of_target_id = instance_of.getTarget().getID()
        if instance_of_target_id == smartphone_model_id:
            return True
        if instance_of_target_id == tablet_model_id:
            return True
    return False


def get_variant_device_specifications(repo, variant_page):
    results = {}
    parts = variant_page.get('claims', {}).get('P527', [])
    for part in parts:
        part_type_id = get_id(part.toJSON().get('mainsnak', {}))
        part_model_id = None

        qualifiers = part.toJSON().get('qualifiers', {}).get('P527', [])
        assert (len(qualifiers) <= 1), 'Multiple qualifiers'

        for qualifier in qualifiers:
            qualifier_id = get_id(qualifier)
            if qualifier_id != None:
                part_model_id = qualifier_id
                part_model_page = pywikibot.ItemPage(repo, part_model_id).get()
                part_model_name = get_label(part_model_page)

                if part_type_id == 'Q610398': # System on a chip
                    results['soc'] = part_model_name;
                elif part_type_id == 'Q5607': # Modem
                    results['modem'] = part_model_name;
                elif part_type_id == 'Q5295': # RAM
                    pass

    return results


def get_variant_device_name(variant_page):
    variant_superclasses = variant_page.get('claims', {}).get('P279', [])

    for variant_superclass in variant_superclasses:
        variant_superclass_page = variant_superclass.getTarget().get()
        if is_a_smartphone_or_tablet_model(variant_superclass_page):
            model_name = get_label(variant_superclass_page)
            return model_name

    return None


def get_all_compatible_devices(repo, replicant_page, caching=True):
    # Example: {'6.0 0004': { 'GT-I9300': { 'device_name' : 'Galaxy SIII'}}}
    results = {}
    cache = None

    if caching:
        cache = Cache()
        #if cache.read():
        results = cache.load()
        return results

    replicant_releases_data = replicant_page.get('claims', {}).get('P348', [])
    for release_data in replicant_releases_data:
        replicant_version = release_data.getTarget()
        assert (replicant_version != None), 'replicant_version == None'

        if replicant_version not in results:
            results[replicant_version] = {}

        release_qualifiers = release_data.toJSON().get('qualifiers', {})
        compatible_variants = release_qualifiers.get('P400', [])
        for compatible_variant in compatible_variants:
            variant_id = get_id(compatible_variant)
            variant_page = pywikibot.ItemPage(repo, variant_id).get()
            variant_name = get_label(variant_page)
            model_name = get_variant_device_name(variant_page)
            assert (variant_name != None), 'variant_name == None'

            if  variant_name not in results[replicant_version]:
                results[replicant_version][variant_name] = {}

            variant_results = results[replicant_version][variant_name]

            # Enable model_name to be None as it's not essential
            if model_name not in results[replicant_version][variant_name]:
                variant_results['device_name'] = model_name

            specifications = get_variant_device_specifications(repo, variant_page)
            variant_results.update(specifications)
    if cache:
        cache.store(results)
        cache.close()

    return results


def get_variant_infos(variant_data, variant):
    device_name = variant_data.get('device_name', None)
    modem = variant_data.get('modem', None)
    soc = variant_data.get('soc', None)

    string = ''
    args = []

    if device_name:
        string += '- {} ({})'
        args += [device_name, variant]
    else:
        string += '- {}'
        args.append(variant_name)

    if soc:
        string += ': {}'
        args.append(soc)

    if modem:
        args.append(modem)
        if soc:
            string += ', {}'
        else:
            string += ': {}'

    return string.format(*args)

def print_variant_infos_2(variant_data, variant):
    device_name = variant_data.get('device_name', None)
    modem = variant_data.get('modem', None)
    soc = variant_data.get('soc', None)

    headers = []
    table = []
    table.append([])

    if device_name:
        headers.append("Device")
        table[0].append(device_name)

        headers.append("Variant")
        table[0].append(variant)
    else:
        headers.append("Variant")
        table[0].append(variant_name)

    if soc:
        headers.append("SOC")
        table[0].append(soc)

    if modem:
        headers.append("Modem")
        table[0].append(modem)

    print(tabulate(table, headers, tablefmt="psql"))

def print_compatible_devices(data):
    # Example: {'6.0 0004': { 'GT-I9300': { 'device_name' : 'Galaxy SIII'}}}
    for replicant_version in data.keys():
        print('Replicant {}:'.format(replicant_version))
        for variant in data[replicant_version].keys():
            variant_data = data[replicant_version][variant]
            print(get_variant_infos(variant_data, variant))

def print_compatible_variant(data, requested_variant):
    # Example: { 'GT-I9300': { 'device_name' : 'Galaxy SIII'}}
    for replicant_version in data.keys():
        for variant in data[replicant_version].keys():
            if variant == requested_variant:
                variant_data = data[replicant_version][variant]
                print_variant_infos_2(variant_data, variant)
                return

def print_device_infos(variant, cache=False):
    replicant_releases_data = None
    if not cache:
        wikidata = pywikibot.Site('wikidata', 'wikidata')
        repo = wikidata.data_repository()
        replicant_id = 'Q7314062'
        replicant_page = pywikibot.ItemPage(repo, replicant_id).get()
        replicant_releases_data = get_all_compatible_devices(repo, replicant_page)
    else:
        replicant_releases_data = get_all_compatible_devices(None, None)

    print_compatible_variant(replicant_releases_data, variant)

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-c', '--cache', dest='cache',
                      action="store_true",
                      help='Use the local cache only (offline mode)',
                      metavar='NAME=value')
    parser.add_option('-t', '--match-token', dest='match_token',
                      action='append',
                      help='Search for information with tokens named NAME that have the value value,',
                      metavar='NAME=value')

    (options, args) = parser.parse_args()


    parser_options = options.__dict__

    cache = parser_options.get('cache', False)
    if parser_options.get('match_token', None):
        # TODO: handle multiple constraints
        for match_token in options.match_token:
            # TODO: check format
            (key, value) = match_token.split('=')
            if key == 'device':
                # TODO: sanity check on value?
                print_device_infos(value, cache)
                pass
            else:
                #TODO
                pass
    else:
        replicant_releases_data = None
        if not cache:
            wikidata = pywikibot.Site('wikidata', 'wikidata')
            repo = wikidata.data_repository()
            replicant_id = 'Q7314062'
            replicant_page = pywikibot.ItemPage(repo, replicant_id).get()
            replicant_releases_data = get_all_compatible_devices(repo, replicant_page)
        else:
            replicant_releases_data = get_all_compatible_devices(None, None)
            
        print_compatible_devices(replicant_releases_data)