-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataTreeGrab.py
More file actions
executable file
·4421 lines (3478 loc) · 171 KB
/
DataTreeGrab.py
File metadata and controls
executable file
·4421 lines (3478 loc) · 171 KB
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
This Package contains a tool for extracting structured data from HTML and JSON
pages.
It reads the page into a Node based tree, from which you, on the bases of a json
data-file, can extract your data into a list of items. It can first extract a
list of keyNodes and extract for each of them the same data-list. During the
extraction several data manipulation functions are available.
Main advantages
- It gives you a highly dependable dataset from a potentially changable source.
- You can easily update on changes in the source without touching your code.
- You can make the data_def available on a central location while distributing
the aplication and so giving your users easy access to (automated) updates.
For the newest version and documentation see:
https://github.com/tvgrabbers/DataTree/
LICENSE
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.'''
from __future__ import unicode_literals
import re, sys, traceback, types, pickle
import time, datetime, pytz
from threading import RLock
from Queue import Queue
try:
from html.parser import HTMLParser, HTMLParseError
except ImportError:
from HTMLParser import HTMLParser, HTMLParseError
try:
from html.entities import name2codepoint
except ImportError:
from htmlentitydefs import name2codepoint
dt_name = u'DataTreeGrab'
dt_major = 1
dt_minor = 4
dt_patch = 0
dt_patchdate = u'20170710'
dt_alfa = False
dt_beta = False
_warnings = None
__version__ = '%s.%s.%s' % (dt_major,'{:0>2}'.format(dt_minor),'{:0>2}'.format(dt_patch))
if dt_alfa:
__version__ = '%s-alfa' % (__version__, )
elif dt_beta:
__version__ = '%s-beta' % (__version__, )
def version():
return (dt_name, dt_major, dt_minor, dt_patch, dt_patchdate, dt_beta, dt_alfa)
# end version()
def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False):
"""
Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dtype
"""
if isinstance(searchpath, (str, unicode, int)):
searchpath = [searchpath]
if not isinstance(searchpath, (list, tuple)):
return False
for d in searchpath:
if isinstance(searchtree, dict):
if not d in searchtree.keys():
return False
elif isinstance(searchtree, (list, tuple)):
if (not isinstance(d, int) or (d >= 0 and d >= len(searchtree)) or (d < 0 and -d > len(searchtree))):
return False
else:
return False
searchtree = searchtree[d]
if dtype == None and not (empty_is_false and searchtree == None):
return True
if empty_is_false and searchtree in (None, "", {}, []):
return False
if isinstance(dtype, tuple):
dtype = list(dtype)
elif not isinstance(dtype, list):
dtype = [dtype]
if float in dtype and not int in dtype:
dtype.append(int)
if str in dtype or unicode in dtype or 'string' in dtype:
for dtp in (str, unicode, 'string'):
while dtp in dtype:
dtype.remove(dtp)
dtype.extend([str, unicode])
if list in dtype or tuple in dtype or 'list' in dtype:
for dtp in (list, tuple, 'list'):
while dtp in dtype:
dtype.remove(dtp)
dtype.extend([list, tuple])
dtype = tuple(dtype)
return bool(isinstance(searchtree, dtype))
# end is_data_value()
def data_value(searchpath, searchtree, dtype = None, default = None):
"""
Follow searchpath through the datatree in searchtree
and return if it exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
If it is not found return default or if dtype is set to
a string, list or dict, an empty one
"""
if is_data_value(searchpath, searchtree, dtype):
if isinstance(searchpath, (str, unicode, int)):
searchpath = [searchpath]
for d in searchpath:
searchtree = searchtree[d]
else:
searchtree = None
if searchtree == None:
if default != None:
return default
elif dtype in (str, unicode, 'string'):
return ""
elif dtype == dict:
return {}
elif dtype in (list, tuple, 'list'):
return []
return searchtree
# end data_value()
def extend_list(base_list, extend_list):
if not isinstance(base_list, list):
base_list = [base_list]
if not isinstance(extend_list, list):
base_list.append(extend_list)
else:
base_list.extend(extend_list)
return base_list
# end extend_list()
class dtWarning(UserWarning):
# The root of all DataTreeGrab warnings.
name = 'General Warning'
class dtDataWarning(dtWarning):
name = 'Data Warning'
class dtdata_defWarning(dtWarning):
name = 'data_def Warning'
class dtConversionWarning(dtdata_defWarning):
name = 'Conversion Warning'
class dtParseWarning(dtdata_defWarning):
name = 'Parse Warning'
class dtCalcWarning(dtdata_defWarning):
name = 'Calc Warning'
class dtUrlWarning(dtWarning):
name = 'URL Warning'
class dtLinkWarning(dtWarning):
name = 'Link Warning'
class _Warnings():
def __init__(self, warnaction = None, warngoal = sys.stderr, caller_id = 0):
self.warn_lock = RLock()
self.onceregistry = {}
self.filters = []
self._ids = []
if not caller_id in self._ids:
self._ids.append(caller_id)
self.warngoal = warngoal
if warnaction == None:
warnaction = "default"
self.set_warnaction(warnaction, caller_id)
def set_warnaction(self, warnaction = "default", caller_id = 0):
with self.warn_lock:
self.resetwarnings(caller_id)
if not caller_id in self._ids:
self._ids.append(caller_id)
if not warnaction in ("error", "ignore", "always", "default", "module", "once"):
warnaction = "default"
self.simplefilter(warnaction, dtWarning, caller_id = caller_id)
self.defaultaction = warnaction
def _show_warning(self, message, category, caller_id, severity, lineno):
with self.warn_lock:
message = "DataTreeGrab,id:%s:%s at line:%s: %s\n" % (caller_id, category.name, lineno, message)
try:
if isinstance(self.warngoal, Queue):
self.warngoal.put((message, caller_id, severity))
else:
self.warngoal.write(message)
except IOError:
pass # the file (probably stderr) is invalid - this warning gets lost.
def warn(self, message, category=None, caller_id=0, severity=1, stacklevel=1):
# 1 = serious
# 2 = invalid data_def
# 4 = invalid data
with self.warn_lock:
# Check if message is already a Warning object
if isinstance(message, Warning):
category = message.__class__
# Check category argument
if category is None:
category = UserWarning
assert issubclass(category, Warning)
# Get context information
try:
caller = sys._getframe(stacklevel)
except ValueError:
globals = sys.__dict__
lineno = 1
else:
globals = caller.f_globals
lineno = caller.f_lineno
if '__name__' in globals:
module = globals['__name__']
else:
module = "<string>"
filename = globals.get('__file__')
if filename:
fnl = filename.lower()
if fnl.endswith((".pyc", ".pyo")):
filename = filename[:-1]
else:
if module == "__main__":
try:
filename = sys.argv[0]
except AttributeError:
# embedded interpreters don't have sys.argv, see bug #839151
filename = '__main__'
if not filename:
filename = module
registry = globals.setdefault("__warningregistry__", {})
self.warn_explicit(message, category, filename, lineno, caller_id, severity, module, registry, globals)
def warn_explicit(self, message, category, filename, lineno, caller_id=0, severity=1, module=None, registry=None, module_globals=None):
with self.warn_lock:
lineno = int(lineno)
if module is None:
module = filename or "<unknown>"
if module[-3:].lower() == ".py":
module = module[:-3] # XXX What about leading pathname?
if registry is None:
registry = {}
if isinstance(message, Warning):
text = str(message)
category = message.__class__
else:
text = message
message = category(message)
key = (text, category, lineno)
# Quick test for common case
if registry.get(key):
return
# Search the filters
for item in self.filters:
action, msg, cat, mod, ln, cid, sev = item
if ((msg is None or msg.match(text)) and
issubclass(category, cat) and
(mod is None or mod.match(module)) and
(ln == 0 or lineno == ln) and
(cid == 0 or caller_id == cid) and
(sev == 0 or severity & sev)):
break
else:
action = self.defaultaction
# Early exit actions
if action == "ignore":
registry[key] = 1
return
if action == "error":
raise message
# Other actions
if action == "once":
registry[key] = 1
oncekey = (text, category)
if self.onceregistry.get(oncekey):
return
self.onceregistry[oncekey] = 1
elif action == "always":
pass
elif action == "module":
registry[key] = 1
altkey = (text, category, 0)
if registry.get(altkey):
return
registry[altkey] = 1
elif action == "default":
registry[key] = 1
else:
# Unrecognized actions are errors
raise RuntimeError(
"Unrecognized action (%r) in warnings.filters:\n %s" %
(action, item))
# Print message and context
self._show_warning(message, category, caller_id, severity, lineno)
def resetwarnings(self, caller_id = 0):
with self.warn_lock:
if caller_id == 0:
self.filters[:] = []
else:
for item in self.filters[:]:
if item[5] == caller_id:
self.filters.remove(item)
def simplefilter(self, action, category=Warning, lineno=0, append=0, caller_id = 0, severity=0):
with self.warn_lock:
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(category, (type, types.ClassType)), \
"category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass"
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
item = (action, None, category, None, lineno, caller_id, severity)
if item in self.filters:
self.filters.remove(item)
if append:
self.filters.append(item)
else:
self.filters.insert(0, item)
def filterwarnings(self, action, message="", category=Warning, module="", lineno=0, append=0, caller_id = 0, severity=0):
with self.warn_lock:
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(message, basestring), "message must be a string"
assert isinstance(category, (type, types.ClassType)), \
"category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass"
assert isinstance(module, basestring), "module must be a string"
assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0"
item = (action, re.compile(message, re.I), category,
re.compile(module), lineno, caller_id, severity)
if item in self.filters:
self.filters.remove(item)
if append:
self.filters.append(item)
else:
self.filters.insert(0, item)
# end _Warnings()
class dtErrorConstants():
# DataTreeShell errorcodes
dtQuiting = -1
dtDataOK = 0
dtDataDefOK = 0
dtURLerror = 1
dtTimeoutError = 2
dtHTTPerror = 3
dtJSONerror = 4
dtEmpty = 5
dtIncompleteRead = 6
dtStartNodeInvalid = 7
dtDataDefInvalid = 8
dtDataInvalid = 10
dtNoData = 14
dtUnknownError = 15
dtFatalError = 15
dtSortFailed = 16
dtUnquoteFailed = 32
dtTextReplaceFailed = 64
dtTimeZoneFailed = 128
dtCurrentDateFailed = 256
dtInvalidValueLink = 512
dtInvalidNodeLink = 1024
dtInvalidPathDef = 2048
dtInvalidLinkDef = 4096
dtErrorTexts = {
dtQuiting: 'The execution was aborted',
dtDataOK: 'Data OK',
dtURLerror: 'There was an error in the URL',
dtTimeoutError: 'Fetching the page took to long',
dtHTTPerror: 'A HTTP error occured',
dtJSONerror: 'A JSON error occured',
dtEmpty: 'Empty Page',
dtIncompleteRead: 'Incomplete Read',
dtStartNodeInvalid: 'Invalid startnode!',
dtDataDefInvalid: 'Invalid data_def',
dtDataInvalid: 'Invalid dataset!',
9: 'Unused Error 9',
dtNoData: 'No Data',
11: 'User Error 11',
12: 'User Error 12',
13: 'User Error 13',
dtUnknownError: 'An unknown error occured',
dtSortFailed: 'Data sorting failed',
dtUnquoteFailed: 'The Unquote filter failed',
dtTextReplaceFailed: 'The Textreplace filter failed',
dtTimeZoneFailed: 'Timezone initialization failed',
dtCurrentDateFailed: 'Setting the current date failed',
dtInvalidValueLink: 'A not jet stored value link was requested',
dtInvalidNodeLink: 'A not jet stored node link was requested',
dtInvalidPathDef: 'Errors in a Path_def were encountered',
dtInvalidLinkDef: 'Errors in a Link_def were encountered'}
def errortext(self, ecode):
if ecode in self.dtErrorTexts.keys():
return self.dtErrorTexts[ecode]
return 'Unknown Error'
# end dtErrorConstants()
dte = dtErrorConstants()
class DataTreeConstants():
# The allowances for a path_def
pathWithValue = 1
pathWithNames = 2
pathMulti = 4
pathInit = 0
pathKey = 5
pathValue = 7
# The node_def type
isGroup = 7
isNone = 0
emptyNodeDef = ((isNone, ), )
isNodeSel = 1
isNodeLink = 2
storeName = 3
isValue = 4
hasCalc = 8
hasDefault = 16
hasType = 32
isMemberOff = 64
storeLinkValue = 128
storePathValue =256
getOnlyOne = 512
getLast = 1024
node_name = {
isNone: "Empty node_def",
isNodeSel: "Node Selection node_def",
isNodeLink: "Node Storing node_def",
storeName: "Name Selection node_def",
isValue: "Value Selection node_def"}
# Node selection and the tuple position for details (node_def type 1 and 2)
selMain = 7
selNone = 0
selPathAll = 1
selPathParent = 2
selPathRoot = 3
selPathLink = 4
selKey = 5
selTag = 6
selKeys = 7
selTags = 7
selIndex = 8
selText = 16
selTail = 32
selChildKeys = 64
selAttrs = 64
selNotChildKeys = 128
selNotAttrs = 128
attr = 0
attrNot = 1
# What data to extract
getGroup = 15
getNone = 0
getIndex = 1
getKey = 2
getTag = 2
getDefault = 3
getValue = 3
getText = 3
getTail = 4
getInclusiveText = 5
getPresence = 6
getLitteral = 7
getAttr = 8
# Is it a value or a linkvalue and what manipulations to do to a retrieved linkvalue
valValue = 0
valLink = 1
valLinkPlus = 2
valLinkMin = 4
valLinkNext = 8
valLinkPrevious = 16
# What data manipulations
calcNone = 0
calcLettering = 1
calcLower = 1
calcUpper = 2
calcCapitalize = 3
calcAsciiReplace = 2
calcLstrip = 3
calcRstrip = 4
calcSub = 5
calcSplit = 6
calcMultiply = 16
calcDivide = 17
calcReplace = 7
calcDefault = 32
calc_name = {
calcNone: "No calculation",
calcLettering: "CaseSetting",
calcAsciiReplace: "AsciiReplace",
calcLstrip: "Left Striping",
calcRstrip: "Right Striping",
calcSub: "Substituting",
calcSplit: "Splitting",
calcMultiply: "Multipling with",
calcDivide: "Dividing by",
calcReplace: "Replacing",
calcDefault: "Default"}
case_name = {
calcLower: "Lower Case",
calcUpper: "Upper Case",
calcCapitalize: "Capitalised"}
# What type to select
typeNone = 0
typeTimeStamp = 1
typeDateTimeString = 2
typeTime = 3
typeTimeDelta = 4
typeDate = 5
typeDateStamp = 6
typeRelativeWeekday = 7
typeString = 8
typeInteger = 9
typeFloat = 10
typeBoolean = 11
typeLowerAscii = 12
typeStringList = 13
typeList = 14
typeLower = 15
typeUpper = 16
typeCapitalize = 17
type_name = {
typeNone: "No Type",
typeTimeStamp: "TimeStamp",
typeDateTimeString: "DateTimeString",
typeTime: "Time",
typeTimeDelta: "TimeDelta",
typeDate: "Date",
typeDateStamp: "DateStamp",
typeRelativeWeekday: "RelativeWeekday",
typeString: "String",
typeInteger: "Integer",
typeFloat: "Float",
typeBoolean: "Boolean",
typeLowerAscii: "LowerAscii",
typeStringList: "StringList",
typeList: "List",
typeLower: "Lower",
typeUpper: "Upper",
typeCapitalize: "Capitalize"}
# About the link_defs
linkNone = 0
linkGroup = 3
linkVarID =1
linkFuncID = 2
linkValue = 3
linkhasDefault = 4
linkhasRegex = 8
linkhasType = 16
linkhasCalc = 32
linkhasMax = 64
linkhasMin = 128
selPosMax = 7
selPos = {
selPathAll: 2,
selPathParent: 2,
selPathRoot: 2,
selPathLink: 2,
selKey: 2,
selTag: 2,
selKeys: 2,
selIndex: 3,
selChildKeys: 4,
selNotChildKeys: 5,
selText: 6,
selTail: 7}
getPosMax = 6
getPos = {
hasCalc: 2,
hasType: 3,
isMemberOff: 4,
storeLinkValue: 5,
hasDefault: 6}
linkPosMax = 7
linkPos = {
linkhasDefault: 2,
linkhasRegex: 3,
linkhasType: 4,
linkhasCalc: 5,
linkhasMax: 6,
linkhasMin: 7}
def const_text(self, ttype, tvalue):
if ttype == 'node_name' and tvalue in self.node_name.keys():
return self.node_name[tvalue]
elif ttype == 'type_name' and tvalue in self.type_name.keys():
return self.type_name[tvalue]
elif ttype == 'calc_name' and tvalue in self.calc_name.keys():
return self.calc_name[tvalue]
elif ttype == 'case_name' and tvalue in self.case_name.keys():
return self.case_name[tvalue]
return ''
# end DataTreeConstants()
class DataDef_Convert():
def __init__(self, data_def = None, warnaction = "default", warngoal = sys.stderr, caller_id = 0):
self.tree_lock = RLock()
with self.tree_lock:
self.dtc = DataTreeConstants()
self.known_urlid = (0, 4, 11, 14)
self.known_linkid = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
self.errorcode = dte.dtDataDefOK
self.caller_id = caller_id
self.cdata_def = {}
self.ddtype = ""
if sys.modules['DataTreeGrab']._warnings == None:
sys.modules['DataTreeGrab']._warnings = _Warnings(warnaction, warngoal, caller_id)
elif caller_id not in sys.modules['DataTreeGrab']._warnings._ids or warnaction != None:
sys.modules['DataTreeGrab']._warnings.set_warnaction(warnaction, caller_id)
if isinstance(data_def, dict):
self.data_def = data_def
self.convert_data_def()
else:
self.data_def = {}
def convert_path_def(self, path_def, ptype = "", path_type = None, link_list = None, init_errors = True):
# check whether it is a link or a value
# return a list (typeint, value/link, plus/min)
def convert_value_link(lvalue, is_index = False):
if is_data_value("link",lvalue, int):
if not lvalue["link"] in self.link_list["values"]:
self.errorcode |= (dte.dtInvalidValueLink + dte.dtDataDefInvalid)
self.warn('LinkID: %s is not jet stored' % ( lvalue["link"], ), dtConversionWarning, 1, 3)
return (self.dtc.valValue,None,0)
val = [self.dtc.valLink, lvalue["link"], 0]
else:
return (self.dtc.valValue,lvalue,0)
if data_value(["calc", 0],lvalue) == "plus":
val[0] += self.dtc.valLinkPlus
val[2] = data_value(["calc", 1],lvalue, int, 0)
elif data_value(["calc", 0],lvalue) == "min":
val[0] += self.dtc.valLinkMin
val[2] = data_value(["calc", 1],lvalue, int, 0)
elif is_index and is_data_value("previous",lvalue):
val[0] += self.dtc.valLinkPrevious
elif is_index and is_data_value("next",lvalue):
val[0] += self.dtc.valLinkNext
return tuple(val)
# ensure it's a list and process the above
# return a list of (value/link)
def convert_value_list(lvalue, is_index = False):
vlist = []
if isinstance(lvalue, (list, tuple)):
for lv in lvalue:
vlist.append(convert_value_link(lv, is_index))
else:
vlist.append(convert_value_link(lvalue, is_index))
return tuple(vlist)
# process an (attrs/childkeys) values dict
# return a list of lists (name, typeint, (value/link))
def convert_attr_dict(ldict):
llist = []
for k, v in ldict.items():
if is_data_value(["not"], v):
dta = self.dtc.attrNot
vl = convert_value_list(v["not"])
else:
vl = convert_value_list(v)
dta = self.dtc.attr
llist.append((k, dta, vl))
return tuple(llist)
# process Data extraction/manipulation
# return (node_type,linkid,data) or (node_type,0,data)
# with data = (sel_type,sel_data),((calc_int,calc_data)),(type_int, type_data), memberoff
def convert_data_extraction(node_def, node_type = self.dtc.isValue):
nlink = 0
if ((node_type & self.dtc.storeLinkValue) or (node_type & self.dtc.storePathValue)) \
and (node_type & self.dtc.isGroup) != self.dtc.isValue:
node_type -= (node_type & self.dtc.isGroup)
node_type += self.dtc.isValue
if (node_type & self.dtc.storeLinkValue):
nlink = node_def["link"]
sel_node = [self.dtc.getDefault, None]
calc_list = []
type_def = []
memberoff = ""
ndefault = None
if isinstance(node_def,dict):
if "value" in node_def.keys():
sel_node = [self.dtc.getLitteral, node_def["value"]]
elif is_data_value("attr", node_def, str) and self.ddtype in ("html", ""):
self.ddtype="html"
#~ sel_node = [self.dtc.getAttr, convert_value_link(node_def["attr"])]
sel_node = [self.dtc.getAttr, node_def["attr"].lower()]
elif is_data_value("select", node_def, str):
if node_def["select"] == "index":
sel_node[0] = self.dtc.getIndex
elif node_def["select"] == "key" and self.ddtype in ("json", ""):
self.ddtype="json"
sel_node[0] = self.dtc.getKey
elif node_def["select"] == "tag" and self.ddtype in ("html", ""):
self.ddtype="html"
sel_node[0] = self.dtc.getTag
elif node_def["select"] == "text" and self.ddtype in ("html", ""):
self.ddtype="html"
sel_node[0] = self.dtc.getText
elif node_def["select"] == "tail" and self.ddtype in ("html", ""):
self.ddtype="html"
sel_node[0] = self.dtc.getTail
elif node_def["select"] == "value" and self.ddtype in ("json", ""):
self.ddtype="json"
sel_node[0] = self.dtc.getValue
elif node_def["select"] == "presence":
sel_node[0] = self.dtc.getPresence
elif node_def["select"] == "inclusive text" and self.ddtype in ("html", ""):
self.ddtype="html"
depth = data_value("depth", node_def, int, 1)
if is_data_value("include", node_def, list):
specs = (depth, 1, node_def["include"])
elif is_data_value("exclude", node_def, list):
specs = (depth, -1, node_def["exclude"])
else:
specs = (depth, 0, [])
sel_node = [self.dtc.getInclusiveText, specs]
# Process any calc statements
calc_type = self.dtc.calcNone
if "lower" in node_def.keys():
calc_list.append((self.dtc.calcLettering, self.dtc.calcLower))
elif "upper" in node_def.keys():
calc_list.append((self.dtc.calcLettering, self.dtc.calcUpper))
elif "capitalize" in node_def.keys():
calc_list.append((self.dtc.calcLettering, self.dtc.calcCapitalize))
if is_data_value('ascii-replace', node_def, list) and len(node_def['ascii-replace']) > 0:
calc_list.append((self.dtc.calcAsciiReplace, tuple(node_def["ascii-replace"])))
if is_data_value('lstrip', node_def, str):
calc_list.append((self.dtc.calcLstrip, node_def["lstrip"]))
if is_data_value('rstrip', node_def, str):
calc_list.append((self.dtc.calcRstrip, node_def["rstrip"]))
if is_data_value('sub', node_def, list) and len(node_def['sub']) > 1:
sl = []
for i in range(int(len(node_def['sub'])/2)):
sl.append((node_def['sub'][i*2], node_def['sub'][i*2+1]))
if len(sl) > 0:
calc_list.append((self.dtc.calcSub, tuple(sl)))
if is_data_value('split', node_def, list) and len(node_def['split']) > 0:
sl = []
if not isinstance(node_def['split'][0],(list, tuple)):
slist = [node_def['split']]
else:
slist = node_def['split']
for s in slist:
if isinstance(s[0], (str,unicode)) and len(s) >1:
sp = [s[0]]
if s[1] == 'list-all':
sp.append(s[1])
else:
for i in range(1, len(s)):
if isinstance(s[i], int):
sp.append(s[i])
if len(sp) >1:
sl.append(tuple(sp))
if len(sl) > 0:
calc_list.append((self.dtc.calcSplit, tuple(sl)))
if is_data_value('multiplier', node_def, int) and \
not data_value('type', node_def, unicode) in ('timestamp', 'datestamp'):
calc_list.append((self.dtc.calcMultiply, node_def["multiplier"]))
if is_data_value('divider', node_def, int) and node_def['divider'] != 0:
calc_list.append((self.dtc.calcDivide, node_def["divider"]))
if is_data_value('replace', node_def, dict):
rl1 = []
rl2 = []
for k, v in node_def["replace"].items():
if isinstance(k, (str, unicode)):
rl1.append(k.lower())
rl2.append(v)
if len(rl1) > 0:
calc_list.append((self.dtc.calcReplace, tuple(rl1), tuple(rl2)))
if len(calc_list) > 0:
node_type += self.dtc.hasCalc
if "default" in node_def.keys():
node_type += self.dtc.hasDefault
ndefault = node_def["default"]
# Process any type statement
if is_data_value('type', node_def, unicode):
if node_def['type'] == 'timestamp':
if is_data_value('multiplier', node_def, int) and node_def['multiplier'] != 0:
type_def = (self.dtc.typeTimeStamp, node_def['multiplier'])
else:
type_def = (self.dtc.typeTimeStamp, 1)
elif node_def['type'] == 'datetimestring':
type_def = (self.dtc.typeDateTimeString, data_value('datetimestring', \
node_def, str, self.cdata_def["datetimestring"]))
elif node_def['type'] == 'time':
tt = self.cdata_def["time-type"]
if is_data_value('time-type', node_def, list) \
and is_data_value(['time-type',0], node_def, int) \
and data_value(['time-type',0], node_def, int) in (12, 24):
tt = [data_value(['time-type', 0], node_def, list),
data_value(['time-type', 1], node_def, str, 'am'),
data_value(['time-type', 2], node_def, str, 'pm')]
type_def = (self.dtc.typeTime, tt,data_value('time-splitter', \
node_def, str, self.cdata_def["time-splitter"]))
elif node_def['type'] == 'timedelta':
type_def = (self.dtc.typeTimeDelta, )
elif node_def['type'] == 'date':
type_def = (self.dtc.typeDate,
data_value('date-sequence', node_def, list, self.cdata_def["date-sequence"]),
data_value('date-splitter', node_def, str, self.cdata_def["date-splitter"]))
elif node_def['type'] == 'datestamp':
if is_data_value('multiplier', node_def, int) and node_def['multiplier'] != 0:
type_def = (self.dtc.typeDateStamp, node_def['multiplier'])
else:
type_def = (self.dtc.typeDateStamp, 1)
elif node_def['type'] == 'relative-weekday':
type_def = (self.dtc.typeRelativeWeekday, )
elif node_def['type'] == 'string':
type_def = (self.dtc.typeString, )
elif node_def['type'] == 'lower':
type_def = (self.dtc.typeLower, )
elif node_def['type'] == 'upper':
type_def = (self.dtc.typeUpper, )
elif node_def['type'] == 'capitalize':
type_def = (self.dtc.typeCapitalize, )
elif node_def['type'] == 'int':
type_def = (self.dtc.typeInteger, )
elif node_def['type'] == 'float':
type_def = (self.dtc.typeFloat, )
elif node_def['type'] == 'boolean':
type_def = (self.dtc.typeBoolean, )
elif node_def['type'] == 'lower-ascii':
type_def = (self.dtc.typeLowerAscii, )
elif node_def['type'] == 'str-list':
type_def = (self.dtc.typeStringList,
data_value('str-list-splitter', node_def, str, self.cdata_def["str-list-splitter"]),
data_value("omit-empty-list-items", node_def, bool, False))
elif node_def['type'] == 'list':
type_def = (self.dtc.typeList, )
if len(type_def) > 0:
node_type += self.dtc.hasType
if not (path_type & self.dtc.pathMulti) or "first" in node_def.keys() or "last" in node_def.keys():
node_type += self.dtc.getOnlyOne
if "last" in node_def.keys():
node_type += self.dtc.getLast
if is_data_value('member-off', node_def, unicode):
memberoff = node_def["member-off"]
node_type += self.dtc.isMemberOff
return (node_type, tuple(sel_node), tuple(calc_list), tuple(type_def), memberoff, nlink, ndefault)
with self.tree_lock:
if path_type == None:
path_type = self.dtc.pathValue
if init_errors:
self.errorcode = dte.dtDataDefOK
self.ddtype = ptype
self.link_list = {"values": [],"nodes": []} if link_list == None else link_list
if not isinstance(self.link_list, dict):
self.link_list = {"values": [],"nodes": []}
if not is_data_value("values", self.link_list, list):
self.link_list["values"] = []
if not is_data_value("nodes", self.link_list, list):
self.link_list["nodes"] = []