forked from Niels-Peter/XBRL-AI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxbrl_ai.py
290 lines (273 loc) · 12.7 KB
/
xbrl_ai.py
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 09:40:44 2018
@author: niels-peter
"""
__title__ = 'xbrl_ai'
__version__ = '0.0.4'
__author__ = 'Niels-Peter Rønmos'
from xml.etree.ElementTree import fromstring
from xmljson import badgerfish as bf
import collections
def xbrlinstance_to_dict(xbrlinstance):
"""
Transforming XBRL-instant to python dictionary
"""
# From XBRL to dict
xbrldict = bf.data(fromstring(xbrlinstance))['{http://www.xbrl.org/2003/instance}xbrl']
# Extract unit information
unitlist = {}
unit = xbrldict['{http://www.xbrl.org/2003/instance}unit']
if isinstance(unit, list):
for post in unit:
try:
unitlist[post['@id']] = (post['{http://www.xbrl.org/2003/instance}measure'])['$']
except LookupError:
pass
try:
divide = post['{http://www.xbrl.org/2003/instance}divide']
unitlist[post['@id']] = ((divide['{http://www.xbrl.org/2003/instance}unitNumerator'])['{http://www.xbrl.org/2003/instance}measure'])['$'] + '/'\
+ ((divide['{http://www.xbrl.org/2003/instance}unitDenominator'])['{http://www.xbrl.org/2003/instance}measure'])['$']
except LookupError:
pass
elif isinstance(unit, dict):
try:
unitlist[unit['@id']] = (unit['{http://www.xbrl.org/2003/instance}measure'])['$']
except LookupError:
pass
try:
divide = unit['{http://www.xbrl.org/2003/instance}divide']
unitlist[unit['@id']] = ((divide['{http://www.xbrl.org/2003/instance}unitNumerator'])['{http://www.xbrl.org/2003/instance}measure'])['$'] + '/'\
+ ((divide['{http://www.xbrl.org/2003/instance}unitDenominator'])['{http://www.xbrl.org/2003/instance}measure'])['$']
except LookupError:
pass
# Extract context information
contexts = xbrldict['{http://www.xbrl.org/2003/instance}context']
contextlist = {}
for post in contexts:
identifier = scheme = startdate = enddate\
= instant = explicit = typed = None
entity = post['{http://www.xbrl.org/2003/instance}entity']
for element in entity:
try:
identifier = (entity[element])['$']
scheme = (entity[element])['@scheme']
except LookupError:
pass
try:
explicit = (entity['{http://www.xbrl.org/2003/instance}segment'])\
['{http://xbrl.org/2006/xbrldi}explicitMember']
except LookupError:
pass
try:
typed = (entity['{http://www.xbrl.org/2003/instance}segment'])\
['{http://xbrl.org/2006/xbrldi}typedMember']
except LookupError:
pass
period = post['{http://www.xbrl.org/2003/instance}period']
try:
startdate\
= (period['{http://www.xbrl.org/2003/instance}startDate'])['$']
except LookupError:
startdate = None
try:
enddate\
= (period['{http://www.xbrl.org/2003/instance}endDate'])['$']
except LookupError:
enddate = None
try:
instant\
= (period['{http://www.xbrl.org/2003/instance}instant'])['$']
except LookupError:
instant = None
try:
explicit = (post['{http://www.xbrl.org/2003/instance}scenario'])\
['{http://xbrl.org/2006/xbrldi}explicitMember']
except LookupError:
pass
try:
typed = (post['{http://www.xbrl.org/2003/instance}scenario'])\
['{http://xbrl.org/2006/xbrldi}typedMember']
except LookupError:
pass
contextlist[post['@id']] = [identifier,\
scheme, startdate, enddate, instant, explicit, typed]
for opryd in ('{http://www.xbrl.org/2003/instance}context',
'{http://www.xbrl.org/2003/instance}unit'):
del xbrldict[opryd]
def modificer_xbrl(xbrldict1):
xbrldict2 = {}
modified = False
for concept in xbrldict1:
if isinstance(xbrldict1[concept], list):
for i in range(0, len(xbrldict1[concept])):
for u in xbrldict1[concept][i]:
type_list = type(xbrldict1[concept][i][u]).__name__
break
if type_list not in ('OrderedDict', 'list'):
xbrldict2[concept] = xbrldict1[concept]
elif type_list in ('OrderedDict', 'list'):
for u in xbrldict1[concept][i]:
modified = True
xbrldict2[u] = xbrldict1[concept][i][u]
else:
pass
elif isinstance(xbrldict1[concept], dict):
for i in xbrldict1[concept].keys():
type_in_dict = type(xbrldict1[concept][i]).__name__
break
if type_in_dict not in ('OrderedDict', 'list'):
xbrldict2[concept] = xbrldict1[concept]
elif type_in_dict == 'list':
for u in xbrldict1[concept]:
modified = True
xbrldict2[u] = xbrldict1[concept][u]
elif type_in_dict == 'OrderedDict':
for u in xbrldict1[concept].keys():
modified = True
xbrldict2[u] = xbrldict1[concept][u]
else:
pass
else:
xbrldict2[concept] = xbrldict1[concept]
return xbrldict2, modified
andret = True
while andret == True:
xbrldict, andret = modificer_xbrl(xbrldict)
# Add unit and context infdromation on concepts
for concept in xbrldict:
if isinstance(xbrldict[concept], dict):
try:
(xbrldict[concept])['context']\
= contextlist[(xbrldict[concept])['@contextRef']]
except LookupError:
pass
try:
(xbrldict[concept])['unit']\
= unitlist[(xbrldict[concept])['@unitRef']]
except LookupError:
pass
if isinstance(xbrldict[concept], list):
for i in range(0, len(xbrldict[concept])):
try:
((xbrldict[concept])[i])['context']\
= contextlist[((xbrldict[concept])[i])['@contextRef']]
except LookupError:
pass
try:
((xbrldict[concept])[i])['unit']\
= unitlist[((xbrldict[concept])[i])['@unitRef']]
except LookupError:
pass
return xbrldict
def xbrldict_to_xbrl_54(xbrldict):
def get_xbrlkey(post, char):
return post[post.index(char)+1:]
def explicit_list(explicit):
explicit_liste = {}
dimension_list = []
label_extend = ''
if type(explicit).__name__ == 'OrderedDict':
explicit_liste[get_xbrlkey(explicit['@dimension'], ":")]\
= get_xbrlkey(explicit['$'], ":")
if isinstance(explicit, list):
for element in explicit:
explicit_liste[get_xbrlkey(element['@dimension'], ":")]\
= get_xbrlkey(element['$'], ":")
explicit_liste_od = collections.OrderedDict(sorted(explicit_liste.items()))
for keys in explicit_liste_od:
label_extend = label_extend + '_' + explicit_liste_od[keys]
dimension_list.append(keys)
return label_extend, dimension_list
def typed_list(typed):
typed_liste = {}
dimension_list = []
label_typed = label_typed_id = ''
if type(typed).__name__ == 'OrderedDict':
for poster in typed:
if poster == '@dimension':
dimension = get_xbrlkey(typed['@dimension'], ":")
if poster != '@dimension':
vaerdi = (typed[poster]).get('$', None)
member = get_xbrlkey(poster, "}")
typed_liste[dimension, vaerdi] = member
if type(typed).__name__ == 'list':
for element in typed:
for poster in element:
if poster == '@dimension':
dimension = get_xbrlkey(element['@dimension'], ":")
if poster != '@dimension':
vaerdi = (element[poster]).get('$', None)
member = get_xbrlkey(poster, "}")
typed_liste[dimension, vaerdi] = member
typed_liste_od = collections.OrderedDict(sorted(typed_liste.items()))
for keys in typed_liste_od:
dimension_list.append(keys[0])
label_typed = label_typed + '_' + typed_liste_od[keys]
if label_typed_id == '':
label_typed_id = str(keys[1])
else:
label_typed_id = label_typed_id + '|' + str(keys[1])
return label_typed, label_typed_id, dimension_list
def concept_data(inputdata):
value = inputdata.get('$', None)
unit = inputdata.get('unit', None)
decimals = inputdata.get('@decimals', None)
context = inputdata['context']
lang = inputdata.get('@{http://www.w3.org/XML/1998/namespace}lang', None)
if type(lang).__name__ != 'NoneType':
lang = 'lang:' + lang
startdate = context[2]
enddate = context[3]
instant = context[4]
if type(enddate).__name__ != 'str':
enddate = instant
explicit = context[5]
typed = context[6]
label_extend, dimension_list_extend = explicit_list(explicit)
label_typed, label_typed_id, dimension_list_typed = typed_list(typed)
dimension_list = dimension_list_extend.append(dimension_list_typed)
if label_typed_id == '':
label_typed_id = None
return value, unit, decimals, startdate, enddate, lang,\
label_extend, label_typed, label_typed_id, dimension_list_extend
#schemaRef = (XBRL['{http://www.xbrl.org/2003/linkbase}schemaRef'])\
#['@{http://www.w3.org/1999/xlink}href']
dict54 = {}
for post in xbrldict:
if post not in ('{http://www.xbrl.org/2003/linkbase}s, xbrldict_to_xbrl_54chemaRef',
'@{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'):
ref = post[:post.index('}')]
xbrlref = ref[(ref.rfind('/') - len(ref) + 1):]
if type(xbrldict[post]).__name__ == 'list':
for element in xbrldict[post]:
if element.get('context', 'missing') != 'missing':
value, unit, decimals, startdate, enddate, lang, label_extend,\
label_typed, label_typed_id, dimension_list = concept_data(element)
concept = xbrlref + ':' + get_xbrlkey(post, '}') + label_extend + label_typed
if type(unit).__name__ == 'NoneType':
unit = lang
nogle = (concept, startdate, enddate, label_typed_id, unit)
if nogle in dict54 and dict54[nogle][0] != value:
print('!!!!!!!!!', nogle, value, unit, decimals, dict54[nogle])
if len(str(dimension_list)) < 5:
dimension_list = None
dict54[nogle] = [value, unit, decimals, dimension_list]
if type(xbrldict[post]).__name__ == 'OrderedDict':
if (xbrldict[post]).get('context', 'missing') != 'missing':
value, unit, decimals, startdate, enddate, lang, label_extend, label_typed,\
label_typed_id, dimension_list = concept_data(xbrldict[post])
concept = xbrlref + ':' + get_xbrlkey(post, '}') + label_extend + label_typed
if type(unit).__name__ == 'NoneType':
unit = lang
nogle = (concept, startdate, enddate, label_typed_id, unit)
if nogle in dict54 and dict54[nogle][0] != value:
print('!!!!!!!!!', nogle, value, unit, decimals, dict54[nogle])
if len(str(dimension_list)) < 5:
dimension_list = None
dict54[nogle] = [value, unit, decimals, dimension_list]
if post in ('{http://www.xbrl.org/2003/linkbase}schemaRef',
'@{http://www.w3.org/2001/XMLSchema-instance}schemaLocation'):
dict54[post] = xbrldict[post]
return dict54