-
Notifications
You must be signed in to change notification settings - Fork 1
/
XMLExtract.py
1491 lines (1390 loc) · 60.4 KB
/
XMLExtract.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import settings
import os
import pickle
import json
import re
import string
import math
import pandas as pd
from collections import OrderedDict
from bs4 import BeautifulSoup as BS
class ExtractFilingData:
def __init__(self, symbol, date, ftype):
self.ticker = symbol
self.date = date
self.ftype = ftype
self.symbol = None
self.data = OrderedDict()
self.ins_sp = None
self.schema_sp = None
self.cal_sp = None
self.def_sp = None
self.lab_sp = None
self.pre_sp = None
self.xl_pd = None
self.xbrl_year = None
self.format_data = {
'quarter': None,
'year': None,
'date': None,
'symbol': None,
'ftype': None,
}
print("Extract contents from: {0}|{1}|{2}".format(self.ticker, self.date, self.ftype))
self.create_data_segments()
self.load_files()
if self.data['error'] == False:
print('dimitry, wooooo no error')
self.get_total_ins_t()
self.build_ins()
self.get_year()
self.get_format_data()
self.symbol = self.format_data['symbol']
self.get_all_labels()
self.extract_all_pre()
self.extract_all_calc()
del self.data['ins_t']
self.format_data['symbol'] = self.ticker
self.format_str = "{0}_{1}_{2}_{3}_{4}".format(self.format_data['symbol'],
self.format_data['date'],
self.format_data['year'],
self.format_data['quarter'],
self.format_data['ftype'])
elif self.data['error'] == True:
pass
def create_data_segments(self):
"""Create the data segment dictionaries."""
self.data['ins_t'] = OrderedDict()
self.data['ins'] = OrderedDict()
self.data['cal'] = OrderedDict()
self.data['lab'] = OrderedDict()
self.data['pre'] = OrderedDict()
self.data['error'] = False
self.data['no_lineage'] = []
def validate_file(self, fname):
"""Returns file category type."""
with open(fname, 'r') as f:
tmp = BS(f)
pre_found = tmp.find(re.compile('presentation[lL]ink'))
def_found = tmp.find(re.compile('definition[lL]ink'))
cal_found = tmp.find(re.compile('calculation[lL]ink'))
lab_found = tmp.find(re.compile('label[lL]ink'))
sch_found = tmp.find(re.compile('roletype'))
ins_found = tmp.find(re.compile('context'))
tmp_found_list = [pre_found, def_found, cal_found, sch_found, ins_found, lab_found]
found_list = []
for fl in tmp_found_list:
if fl:
found_list.append(fl)
if len(found_list) == 1:
tmp_fl = found_list[0]
if tmp_fl == pre_found:
return 'pre'
if tmp_fl == def_found:
return 'def'
if tmp_fl == lab_found:
return 'lab'
if tmp_fl == cal_found:
return 'cal'
if tmp_fl == sch_found:
return 'schema'
if tmp_fl == ins_found:
return 'ins'
else:
return found_list
def load_files(self):
"""Load all data files and store in variables."""
fpath = '{0}/{1}/xml/{2}/{3}'.format(settings.RAW_DATA_PATH,
self.ticker,
self.ftype,
self.date)
print('dimitry, file path: '+str(fpath))
files = os.listdir(fpath)
sym_len = len(self.ticker) + 1
date_len = len(self.date) + 1
tot_len = sym_len + date_len
required = ['pre', 'lab', 'cal', 'ins']
found = []
not_found = []
print('dimitry, here are the files: ')
print(files)
for x in files:
spli_t = os.path.splitext(x)[0]
ext = spli_t[tot_len:]
fname = '{0}/{1}'.format(fpath, x)
ftype = self.validate_file(fname)
if isinstance(ftype, list):
continue
if ftype == 'ins': #Load instance file
with open(fname, 'r') as f:
self.ins_sp = BS(f)
found.append('ins')
if ftype == 'schema':
continue
if ftype == 'cal': #Load calculations file
with open(fname, 'r') as f:
self.cal_sp = BS(f)
found.append('cal')
if ftype == 'def':
continue
if ftype == 'lab': #Load labels file
with open(fname, 'r') as f:
self.lab_sp = BS(f)
found.append('lab')
if ftype == 'pre': #Load presentation file
with open(fname, 'r') as f:
self.pre_sp = BS(f)
found.append('pre')
for i in required:
if i not in found:
not_found.append(i)
if len(not_found) > 0:
self.data['error'] = True
return False
def get_year(self):
try:
yre = '(dei:DocumentFiscalYearFocus$)'
year = self.ins_sp.find(name=re.compile(yre, re.IGNORECASE | re.MULTILINE)).get_text()
except AttributeError:
try:
yre = '(dei:DocumentPeriodEndDate$)'
year = self.ins_sp.find(name=re.compile(yre, re.IGNORECASE | re.MULTILINE)).get_text()
year = year[:4]
except AttributeError:
return False
try:
year = int(year)
sure_years = [2001, 2002, 2003, 2004, 2005,
2006, 2007, 2008, 2009, 2011,
2012, 2013, 2014, 2016]
if year in sure_years:
self.xbrl_year = str(year)
if year == 2010:
self.xbrl_year = '2009'
if year == 2015:
self.xbrl_year = '2014'
return True
except:
return False
def get_format_data(self):
names = ['documentfiscalperiodfocus', 'documentfiscalyearfocus',
'documentperiodenddate', 'tradingsymbol', 'documenttype']
#Get Quarter
try:
val_q = self.data['ins']['facts']['dei'][names[0]]['val_by_date'].keys()[0]
self.format_data['quarter'] = self.data['ins']['facts']['dei'][names[0]]['val_by_date'][val_q][0][0].upper()
except KeyError:
self.format_data['quarter'] = 'NA'
#Get Year
try:
val_y = self.data['ins']['facts']['dei'][names[1]]['val_by_date'].keys()[0]
self.format_data['year'] = self.data['ins']['facts']['dei'][names[1]]['val_by_date'][val_y][0][0]
except KeyError:
self.format_data['year'] = self.xbrl_year
#Get Date
try:
val_d = self.data['ins']['facts']['dei'][names[2]]['val_by_date'].keys()[0]
self.format_data['date'] = self.data['ins']['facts']['dei'][names[2]]['val_by_date'][val_d][0][0]
except KeyError:
self.format_data['date'] = 'NA'
#Get Symbol
try:
val_s = self.data['ins']['facts']['dei'][names[3]]['val_by_date'].keys()[0]
self.format_data['symbol'] = self.data['ins']['facts']['dei'][names[3]]['val_by_date'][val_s][0][0].upper()
except (KeyError, IndexError):
self.format_data['symbol'] = self.ticker
#Get Filing Type
try:
val_f = self.data['ins']['facts']['dei'][names[4]]['val_by_date'].keys()[0]
self.format_data['ftype'] = self.data['ins']['facts']['dei'][names[4]]['val_by_date'][val_f][0][0].replace('/', '-')
self.format_data['ftype'] = self.format_data['ftype'].upper()
except KeyError:
self.format_data['ftype'] = self.ftype
######################
## Generic Portions ##
######################
def find_closest_ins(self, lab):
"""From an entered label, find the closest instance fact."""
if lab[1] == '':
return False
try:
self.data['ins']['facts'][lab[0].lower()][lab[1].lower()]
return lab
except KeyError:
lab0 = lab[0]
lab1 = lab[1][:-1]
lab = (lab0, lab1)
return self.find_closest_ins(lab)
def check_if_in_pre(self, title):
"""Check if title exists in presentation dictionary."""
try:
self.data['pre']['roles'][title]
return True
except KeyError:
return False
def format_to_xbrl(self, try_str):
"""Remove spaces and non-alphanumeric characters
from a string."""
cleaned_str = re.sub('[^0-9a-zA-Z]+', '', try_str)
return cleaned_str
def find_label(self, try_str, get_full=92):
"""Find label from a string as exists in the populated
labels dictionary."""
if try_str == float('nan'):
return False
key_ref = self.data['lab'].keys()
key_lists = []
for kr in key_ref:
kl_cp = self.data['lab'][kr].keys()
key_lists.append(kl_cp)
label_list = []
for key_num in range(len(key_ref)):
for i in key_lists[key_num]:
val_keys = self.data['lab'][key_ref[key_num]][i].keys()
for num in val_keys:
if self.data['lab'][key_ref[key_num]][i][num] == try_str:
if get_full:
label_list.append((key_ref[key_num], i))
else:
label_list.append((key_ref[key_num], i[:get_full]))
label_list = list(set(label_list))
if len(label_list) == 0:
try:
label_list = self.find_label(try_str[:-1])
except RuntimeError:
return label_list
return label_list
def find_label_str(self, label):
"""Find string from a label as exists in the populated
labels dictionary."""
pfx = label[0]
label = label[1]
try:
base_ref = self.data['lab'][pfx][label]
except KeyError:
try:
base_ref = self.data['lab']['us-gaap'][label]
except KeyError:
try:
base_ref = self.data['lab'][self.symbol.lower()][label]
except KeyError:
base_ref = label
return base_ref
def get_pfx_gen(self, html_string, ins):
"""Generic prefix extractor utilizing the instance dictionary."""
ins_keys = self.data[ins]['facts'].keys()
html_string = str(html_string).lower()
pfx = None
for i in ins_keys:
if i in html_string:
pfx = i
if not '_' in html_string and not ':' in html_string and not '-' in html_string:
if pfx == None:
return None
return pfx
def get_name_gen(self, html_string, ins):
"""Generic name extractor utilizing the instance dictionary."""
html_string = str(html_string)
ins_keys = self.data[ins]['facts'].keys()
tmp_str = html_string
while True:
pfx = re.search('([^\W_]|[-])*', tmp_str).group(0)
if len(tmp_str) == 0:
return False
if pfx in ins_keys:
tmp_str = tmp_str[len(pfx)+1:]
break
else:
tmp_str = tmp_str[len(pfx)+1:]
to_use = re.search('[^\W_]*', tmp_str)
return to_use.group(0)
def get_lineage(self, roots, from_to_list, ele, lineage_list=None):
"""Get the lookup location on the tree for a specific element."""
if lineage_list:
lineage = lineage_list
else:
lineage = [ele]
cur_ele = ele
for i in roots:
if cur_ele == i[1]:
return lineage
else:
for i in from_to_list:
if i[1] == cur_ele:
lineage.insert(0, i[0])
cur_ele = i[0]
return self.get_lineage(roots, from_to_list, cur_ele, lineage)
def check_path_exist(self, path):
"""Check if a certain path exists."""
try:
exec(path)
return True
except KeyError:
return False
def gen_dict_path(self, cat, link_eles, role_name, pfx, ctx=None, ref_self='self'):
"""Generate dictionary path and execute code to create or assign
values to dictionary."""
if cat == 'pre' or cat == 'cal':
base_str = '{0}.data["{1}"]["roles"]["{2}"]["tree"]'.format(ref_self, cat, role_name)
elif cat == 'xl':
base_str = '{0}.data["{1}"]["{2}"]["tree"]'.format(ref_self, cat, role_name)
for i in link_eles:
if i == link_eles[0]:
next_ele = "['{0}']".format(i)
base_str += next_ele
if not self.check_path_exist(base_str):
exec(base_str + ' = OrderedDict()')
next_ele = '["sub"]'
base_str += next_ele
if not self.check_path_exist(base_str):
exec(base_str + ' = OrderedDict()')
else:
base_str += '["sub"]'
elif i == link_eles[-1]:
next_ele = '["{0}"]'.format(i)
base_str += next_ele
if not self.check_path_exist(base_str):
exec(base_str + " = OrderedDict()")
pfx_str = base_str + '["pfx"] = "{0}"'.format(pfx)
if not self.check_path_exist(pfx_str):
exec(pfx_str)
if not self.check_path_exist(base_str + "['sub']"):
exec(base_str + '["sub"] = OrderedDict()')
if cat == 'pre' and ctx:
if isinstance(ctx, (unicode, str)):
try:
try:
assign_str = base_str + '["label"] = "{0}"'.format(ctx.encode('utf-8'))
exec(assign_str)
except SyntaxError:
ctx_2 = ctx[2][:79]
ctx_2 = ctx_2.replace('"', "'")
ctx_2 = ctx_2.replace('\n', '')
assign_str = base_str + '["label"] = "{0}"'.format(ctx_2.encode('utf-8'))
exec(assign_str)
except KeyError:
pass
if isinstance(ctx, tuple):
try:
assign_str = base_str + "['order'] = {0}".format(ctx[0])
exec(assign_str)
except KeyError:
pass
try:
assign_str = base_str + "['val'] = {0}".format(ctx[1])
exec(assign_str)
except KeyError:
pass
try:
try:
assign_str = base_str + '["label"] = "{0}"'.format(ctx[2].encode('utf-8'))
exec(assign_str)
except SyntaxError:
ctx_2 = ctx[2][:79]
ctx_2 = ctx_2.replace('"', "'")
ctx_2 = ctx_2.replace('\n', '')
assign_str = base_str + '["label"] = "{0}"'.format(ctx_2.encode('utf-8'))
exec(assign_str)
except KeyError:
pass
elif cat == 'cal' and ctx:
try:
assign_str = base_str + "['order'] = {0}".format(ctx[0])
exec(assign_str)
except KeyError:
pass
try:
assign_str = base_str + "['weight'] = {0}".format(ctx[1])
exec(assign_str)
except KeyError:
pass
try:
assign_str = base_str + "['val'] = {0}".format(ctx[2])
exec(assign_str)
except KeyError:
pass
else:
next_ele = '["{0}"]'.format(i)
base_str += next_ele
if not self.check_path_exist(base_str):
exec(base_str + ' = OrderedDict()')
base_str += "['sub']"
if not self.check_path_exist(base_str):
exec(base_str + ' = OrderedDict()')
else:
base_str += "['sub']"
def traverse_print_tree(self, base, role_keys, tabs=0):
"""Traverse cal tree and print."""
for rk in role_keys:
if rk == 'sub':
continue
tab_str = ' ' * tabs
try:
lab_str = tab_str + str(base[rk]['label'])
except KeyError:
lab_str = rk
try:
base_keys = base[rk]['val'].keys()
if len(base_keys) == 0:
if len(base[rk]['sub']) == 0:
continue
else:
print('\033[1m' + lab_str + '\033[0m')
else:
date_str = ''
val_str = ''
for i in base_keys:
date_str += str(i)
date_str += '\t\t'
for bk in base_keys:
if base[rk]['val'][bk] == None:
continue
if isinstance(base[rk]['val'][bk], float):
val_str += str(base[rk]['val'][bk])
else:
val_str += base[rk]['val'][bk].encode('utf-8')
val_str += '\t\t'
print(lab_str)
print(tab_str + '\t' + date_str)
print(tab_str + '\t' + val_str)
except KeyError:
pass
if len(base[rk]['sub']) > 0:
rk_base = base[rk]['sub']
rk_base_keys = rk_base.keys()
self.traverse_print_tree(rk_base, rk_base_keys, tabs=tabs+1)
def traverse_tree(self, base):
base_tree = base['tree']
role_keys = base_tree.keys()
self.traverse_print_tree(base_tree, role_keys)
def traverse_all_trees(self):
base = self.data['pre']['roles']
base_keys = base.keys()
for bk in base_keys:
self.traverse_tree(base[bk])
def find_fact_in_role(self, cat, fact):
"""Returns list of roles with fact in them."""
all_role_keys = self.data[cat]['roles'].keys()
roles_with_fact = []
for i in all_role_keys:
base = self.data[cat]['roles'][i]['unique']
for b in base:
if fact == b[1]:
roles_with_fact.append(i)
roles_with_fact = list(set(roles_with_fact))
return roles_with_fact
def find_pfx_in_ins(self, fact):
"""Returns pfx of fact in ins given no prefix."""
ins_keys = self.data['ins']['facts'].keys()
for ik in ins_keys:
base = self.data['ins']['facts'][ik].keys()
for b in base:
if b == fact.lower():
return ik
######################
## Instance Section ##
######################
def get_context_id(self, tag):
"""Get context ID."""
return tag.get('id')
def get_period_type(self, tag):
"""Get period type."""
period = tag.find(name=re.compile('period'))
if period.find(name=re.compile('instant')):
return 'instant'
else:
return 'duration'
def get_period(self, tag, p_type):
"""Get period time."""
period = tag.find(name=re.compile('period'))
if p_type == 'instant':
p_content = period.find(name=re.compile('instant')).text
return p_content
else:
p_start = period.find(name=re.compile('start[dD]ate')).text
p_end = period.find(name=re.compile('end[dD]ate')).text
p_content = (p_start, p_end)
return p_content
def build_context_ref_list(self):
"""Build the context reference list. Each context has a period
that is either an instance and duration type, and the
specific period is also stored under 'when'."""
self.data['ins']['contexts'] = OrderedDict()
ctx_raw = self.ins_sp.find_all(name=re.compile('context'))
for ctx in ctx_raw:
ctx_id = self.get_context_id(ctx)
exmem = ctx.find(name=re.compile('explicitmember'))
if exmem:
exmem_txt = exmem.text
else:
exmem_txt = None
period_type = self.get_period_type(ctx)
period = self.get_period(ctx, period_type)
self.data['ins']['contexts'][ctx_id] = OrderedDict()
self.data['ins']['contexts'][ctx_id]['period'] = OrderedDict()
self.data['ins']['contexts'][ctx_id]['period']['type'] = period_type
self.data['ins']['contexts'][ctx_id]['period']['when'] = OrderedDict()
if period_type == 'instant':
self.data['ins']['contexts'][ctx_id]['period']['when'] = period
else:
self.data['ins']['contexts'][ctx_id]['period']['when']['startdate'] = period[0]
self.data['ins']['contexts'][ctx_id]['period']['when']['enddate'] = period[1]
if exmem_txt:
try:
self.data['ins']['contexts'][ctx_id]['exmem'].append(exmem_txt)
except KeyError:
self.data['ins']['contexts'][ctx_id]['exmem'] = []
self.data['ins']['contexts'][ctx_id]['exmem'].append(exmem_txt)
def get_pfx(self, html_string):
"""Extract prefix from HTML string."""
html_string = str(html_string)
pfx = re.search('[A-zA-Z0-9]+[^:_]*', html_string)
try:
return pfx.group(0)
except AttributeError:
return None
def get_name(self, html_string):
"""Extract name from HTML string."""
html_string = str(html_string)
name = re.search('(?<=[:_])[A-zA-Z0-9][^\s_]*', html_string)
try:
return name.group(0)
except AttributeError:
return None
def make_pfx(self, prfx, ins):
"""Make the prefix subcategories."""
if prfx not in self.data[ins]['facts'].keys():
self.data[ins]['facts'][prfx] = OrderedDict()
def pop_ins_t(self, ctx_ref, pfx, name, dates, val, decimals):
"""Populate ins_t with parameters."""
self.data['ins_t']['facts'][pfx][name][ctx_ref]['date'] = dates
self.data['ins_t']['facts'][pfx][name][ctx_ref]['val'] = val
self.data['ins_t']['facts'][pfx][name][ctx_ref]['decimals'] = decimals
def get_facts(self):
"""Get fact names, store them under prefix, and subcategorize
according to context reference."""
self.data['ins_t']['facts'] = OrderedDict()
tmp_tags = self.ins_sp.find_all(name=re.compile('([A-zA-Z]+:[A-zA-Z]+)'))
self.make_pfx(self.ticker.lower(), 'ins_t')
for tmp in tmp_tags:
pfx = self.get_pfx(tmp)
name = self.get_name(tmp)
long_name = None
for i in tmp.attrs.keys():
if tmp[i] == '':
long_name = i
if long_name:
name += long_name
self.make_pfx(pfx, 'ins_t')
try:
self.data['ins_t']['facts'][pfx][name]
except KeyError:
self.data['ins_t']['facts'][pfx][name] = OrderedDict()
if len(tmp.get_text()) < 35 and len(tmp.get_text()) >= 1:
ctx_ref = tmp.get('contextref')
decimals = tmp.get('decimals')
if ctx_ref:
try:
self.data['ins_t']['facts'][pfx][name][ctx_ref]
except KeyError:
self.data['ins_t']['facts'][pfx][name][ctx_ref] = OrderedDict()
dates = self.data['ins']['contexts'][ctx_ref]['period']['when']
try:
exmem = self.data['ins']['contexts'][ctx_ref]['exmem']
self.data['ins_t']['facts'][pfx][name][ctx_ref]['exmem'] = exmem
for em in exmem:
ex_pfx = self.get_pfx(em)
ex_name = self.get_name(em)
ex_name = ex_name.lower()
try:
self.data['ins_t']['facts'][ex_pfx][ex_name]
except KeyError:
self.data['ins_t']['facts'][ex_pfx][ex_name] = OrderedDict()
try:
self.data['ins_t']['facts'][ex_pfx][ex_name][ctx_ref]
except KeyError:
self.data['ins_t']['facts'][ex_pfx][ex_name][ctx_ref] = OrderedDict()
try:
con_fl = float(tmp.text)
self.pop_ins_t(ctx_ref, ex_pfx, ex_name, dates, con_fl, decimals)
except ValueError:
self.pop_ins_t(ctx_ref, ex_pfx, ex_name, dates, tmp.text, decimals)
except KeyError:
pass
try:
con_fl = float(tmp.text)
self.pop_ins_t(ctx_ref, pfx, name, dates, con_fl, decimals)
except ValueError:
self.pop_ins_t(ctx_ref, pfx, name, dates, tmp.text, decimals)
def get_total_ins_t(self):
"""Populate the instance dictionary."""
self.build_context_ref_list()
self.get_facts()
def conv_date_to_int(self, date):
"""Convert date str to int."""
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
return (year, month, day)
def sort_by_date(self, date_list):
"""Sort dates in descending order."""
master = OrderedDict()
s = date_list
s.sort(key=lambda tup: tup[0], reverse=True)
master['val_list'] = []
master['val_by_date'] = OrderedDict()
for i in s:
master['val_list'].append((i[1], i[4]))
try:
master['val_by_date'][i[0]]
except KeyError:
master['val_by_date'][i[0]] = []
master['val_by_date'][i[0]].append((i[1], i[2], i[3], i[4]))
tmp_master = []
tmp_dates = []
for i in master['val_by_date'].keys():
if master['val_by_date'][i] not in tmp_master:
tmp_master.append(master['val_by_date'][i])
tmp_dates.append(i)
master['val_by_date'] = OrderedDict()
for i in range(len(tmp_dates)):
master['val_by_date'][tmp_dates[i]] = tmp_master[i]
master['val_list'] = list(set(master['val_list']))
return master
def val_to_pre_conv(self, val, decimal):
"""Convert value to pre form using decimal attribute."""
if decimal in ['INF', None, 0]:
return val
base_str = '1'
decimal = int(decimal)
if decimal < 0:
base_zero = '0' * (abs(decimal))
base_str += base_zero
conv_num = float(base_str)
val_conv = val / conv_num
return val_conv
elif decimal > 0:
base_zero = '0' * (abs(decimal))
base_str += base_zero
conv_num = float(base_str)
val_conv = val * conv_num
return val_conv
def build_ins(self):
"""Build instance reference with dates in descending order."""
self.data['ins']['facts'] = OrderedDict()
pfx_keys = self.data['ins_t']['facts'].keys()
for pfx in pfx_keys:
self.make_pfx(pfx, 'ins')
name_keys = self.data['ins_t']['facts'][pfx].keys()
for name in name_keys:
self.data['ins']['facts'][pfx][name] = OrderedDict()
ctx_keys = self.data['ins_t']['facts'][pfx][name].keys()
unsorted_ctx = []
ctx_exmem = []
for ctx in ctx_keys:
ctx_val = self.data['ins_t']['facts'][pfx][name][ctx]
ctx_dec = self.data['ins_t']['facts'][pfx][name][ctx]['decimals']
ctx_conv_val = self.val_to_pre_conv(ctx_val['val'], ctx_dec)
ctx_date = ctx_val['date']
if len(ctx_date) == 2:
ctx_date_begin = ctx_date['startdate']
ctx_date_end = ctx_date['enddate']
unsorted_ctx.append(((ctx_date_begin, ctx_date_end), ctx_val['val'], ctx, ctx_dec, ctx_conv_val))
else:
unsorted_ctx.append(((ctx_date), ctx_val['val'], ctx, ctx_dec, ctx_conv_val))
name_val = self.sort_by_date(unsorted_ctx)
self.data['ins']['facts'][pfx][name] = name_val
####################
## Labels Section ##
####################
def get_all_labels(self):
"""Populate the labels dictionary."""
labels = self.lab_sp.find_all(name=re.compile('labellink'))
print('here are some labels: ')
print(labels)
tmp_labels = labels[0].find_all(name=re.compile('link:[lL]abel$'))
if len(tmp_labels) == 0:
labels = labels[0].find_all(name=re.compile('label'))
else:
use_label_nd = False
for tl in tmp_labels:
tmp_str = str(tl)
if '<link:labelarc' in tmp_str or '<link:labelArc' in tmp_str or '<labelarc' in tmp_str:
use_label_nd = True
break
if use_label_nd:
tmp_labels = labels[0].find_all(name=re.compile('label'))
labels = tmp_labels
locs = self.lab_sp.find_all(name=re.compile('x?link:loc'))
locs_pairs = []
for i in locs:
loc_href = i.get('xlink:href')
lnxt_names = []
loc_next = i.find_next()
if loc_next == None:
break
keep_going = True
while loc_next.name not in ['xlink:loc', 'link:loc']:
if loc_next == None:
keep_going = False
elif loc_next.name in ['xlink:labelArc', 'xlink:labelarc']:
loc_next = loc_next.find_next()
continue
elif loc_next.name in ['xlink:label', 'link:label']:
lnxt_name = self.get_name(loc_next.get('xlink:label'))
if lnxt_name not in lnxt_names:
lnxt_names.append(lnxt_name)
loc_next = loc_next.find_next()
if loc_next == None:
break
loc_href = os.path.splitext(loc_href)[1]
if '#' not in loc_href:
continue
pnd_idx = loc_href.index('#')
loc_href = loc_href[pnd_idx+1:]
loc_pfx = self.get_pfx_gen(loc_href, 'ins_t')
loc_name = self.get_name_gen(loc_href, 'ins_t')
if not loc_pfx:
loc_pfx = self.symbol
if loc_pfx and loc_name:
tmp_lp = [loc_pfx, loc_name]
for i in lnxt_names:
if i not in tmp_lp:
tmp_lp.append(i)
tmp_lp = tuple(tmp_lp)
locs_pairs.append(tmp_lp)
for i in labels:
if i.name in ['labelarc', 'labelArc', 'xlink:labelarc', 'xlink:labelArc']:
continue
lab_pfx = self.get_pfx_gen(i.get('xlink:label'), 'ins_t')
lab_name = self.get_name_gen(i.get('xlink:label'), 'ins_t')
if not lab_name:
lab_name = self.get_name(i.get('xlink:label'))
if lab_name and not lab_pfx:
for lp in locs_pairs:
for l in lp[1:]:
if lab_name == l:
lab_name = l
lab_pfx = lp[0]
if not lab_pfx and not lab_name:
lab_name = self.get_name(i.get('xlink:label'))
if lab_name:
lab_pfx = self.find_pfx_in_ins(lab_name)
if lab_name and not lab_pfx:
for lp in locs_pairs:
for l in lp[1:]:
if lab_name == l:
lab_name = l
lab_pfx = lp[0]
if lab_name and not lab_pfx:
for lp in locs_pairs:
for lp in locs_pairs:
for l in lp[1:]:
if lab_name == l:
lab_name = l
lab_pfx = lp[0]
if not lab_pfx and not lab_name:
continue
if lab_pfx and not lab_name:
tmp_lab_store = i.get('xlink:label')
lab_pfx = self.get_pfx_gen(tmp_lab_store, 'ins_t')
try:
reg_xt = '(?<={0}[_])[^\W_]*'.format(lab_pfx)
reg_xt_ex = re.search(reg_xt, tmp_lab_store)
lab_name = reg_xt_ex.group(0)
except AttributeError:
try:
reg_xt = '(?<={0})[^\W_]*'.format(lab_pfx.upper())
reg_xt_ex = re.search(reg_xt, tmp_lab_store)
name_to = reg_xt_ex.group(0)
except AttributeError:
pass
if not lab_name:
pass
try:
self.data['lab'][lab_pfx]
except KeyError:
self.data['lab'][lab_pfx] = OrderedDict()
label_type = i.get('xlink:role')
label_type = os.path.split(label_type)[1]
try:
self.data['lab'][lab_pfx][lab_name][label_type] = i.text
except KeyError:
self.data['lab'][lab_pfx][lab_name] = OrderedDict()
self.data['lab'][lab_pfx][lab_name][label_type] = i.text
for l in locs_pairs:
if len(l[1:]) > 1:
try:
l2 = self.data['lab'][l[0]][l[2]]
self.data['lab'][l[0]][l[1]] = l2
except KeyError:
pass
##########################
## Calculations Section ##
##########################
def make_calc_tree(self, calc_arcs, calc_locs, role_name, title):
"""Generate a calculation tree for a specific role
and create the ordered priority and weight."""
root = []
to_list = []
from_list = []
from_to_pair = [] #(parent, child)
locs_pairs = []
for cl in calc_locs:
tmp_cl_raw = cl.get('xlink:href')
tmp_cl = os.path.splitext(tmp_cl_raw)[1]
if '#' in tmp_cl:
tmp_cl_idx = tmp_cl.index('#')
tmp_cl = tmp_cl[tmp_cl_idx+1:]
pfx_loc = self.get_pfx_gen(tmp_cl, 'ins_t')
name_loc = self.get_name_gen(tmp_cl, 'ins_t')
locs_pairs.append((pfx_loc, name_loc))
for i in calc_arcs:
#Start to list
xlink_to = i.get('xlink:to')
pfx_to = self.get_pfx_gen(xlink_to, 'ins_t')
name_to = self.get_name_gen(xlink_to, 'ins_t')
if not pfx_to and not name_to:
name_to = xlink_to
for lp in locs_pairs:
if name_to == lp[1]:
pfx_to = lp[0]
break
if not pfx_to:
continue
if pfx_to and not name_to:
tmp_to_store = xlink_to
tmp_to = xlink_to.lower()
idx_name_s = tmp_to.index(pfx_to)
xlink_to = xlink_to[idx_name_s:]
try:
reg_xt = '(?<={0})[^\W_]*'.format(pfx_to)
reg_xt_ex = re.search(reg_xt, xlink_to)
name_to = reg_xt_ex.group(0)
except AttributeError:
try:
reg_xt = '(?<={0})[^\W_]*'.format(pfx_to.upper())
reg_xt_ex = re.search(reg_xt, xlink_to)
name_to = reg_xt_ex.group(0)
except AttributeError:
pass
if not name_to:
tmp_pfx = self.get_name_gen(xlink_to, 'ins')
if tmp_pfx:
tmp_nt = xlink_to.lower()
end_pfx = tmp_nt.index(tmp_pfx) + len(tmp_pfx)
name_to = xlink_to[end_pfx:]
if '_' in name_to:
xt_idx = name_to.index('_')
name_to = name_to[:xt_idx]
if not name_to:
if '_' not in xlink_to and ':' not in xlink_to and '-' not in xlink_to:
if isinstance(xlink_to, str):
if tmp_pfx == None:
name_to = xlink_to
if not name_to:
if pfx_to:
if '_' not in xlink_to and ':' not in xlink_to and '-' not in xlink_to:
if isinstance(xlink_to, str):
name_to = xlink_to
if not name_to:
continue
#Get order and weight
order = i.get('order')
order = float(order)
weight = i.get('weight')
weight = float(weight)
if name_to not in to_list:
to_list.append((pfx_to, name_to, order, weight))
#Start From List
xlink_from = i.get('xlink:from')
pfx_from = self.get_pfx_gen(xlink_from, 'ins_t')
name_from = self.get_name_gen(xlink_from, 'ins_t')
if not pfx_from and not name_from:
name_from = xlink_from
for lp in locs_pairs:
if name_from == lp[1]:
pfx_from = lp[0]