-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprovenance_harvester.py
2143 lines (1835 loc) · 85.6 KB
/
provenance_harvester.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 tarfile
import os
import zipfile
import os
from tqdm import tqdm
import json
import numpy as np
import csv
import sqlite3
import networkx as nx
class RowId():
def __init__(self,row_id):
self.row_id = row_id
def __str__(self):
return self.row_id
class ColId():
def __init__(self,col_id):
self.col_id = col_id
def __str__(self):
return self.col_id
def init_column(n_col):
list_col = []
for x in range(n_col):
list_col.append(ColId(x))
def init_row(n_row):
list_row = []
for x in range(n_row):
list_row.append(RowId(x))
def extract_project(file_name,temp_folder="temp"):
fname = ".".join(file_name.split(".")[:-2])
tar = tarfile.open(file_name,"r:gz")
locex = "{}/{}".format(temp_folder,fname)
try:
os.mkdir(locex)
except BaseException as ex:
print(ex)
tar.extractall(path=locex)
tar.close()
return locex,fname
def read_dataset(project_file):
locex = "{}/{}/".format(project_file,"data")
zipdoc = zipfile.ZipFile(project_file+"/data.zip")
try:
os.mkdir(locex)
except BaseException as ex:
print(ex)
zipdoc.extractall(path=locex)
zipdoc.close()
datafile = open(locex+"/data.txt","r",encoding="ascii", errors="ignore")
# read column model
column_model_dict = {}
line = next(datafile).replace("\n","")
while line:
if line=="/e/":
break
else:
head = line.split("=")[0]
val = line.split("=")[-1]
column_model_dict[head] = val
cols = []
#print(head)
if head == "columnCount":
for x in range(int(val)):
line = next(datafile).replace("\n","")
col = json.loads(line)
cols.append(col)
column_model_dict["cols"] = cols
try:
line=next(datafile).replace("\n","")
except:
break
#print(column_model_dict)
# read history
history_dict = {}
line = next(datafile).replace("\n","")
while line:
if line=="/e/":
break
else:
head = line.split("=")[0]
val = line.split("=")[-1]
history_dict[head] = val
hists = []
#print(head)
if head == "pastEntryCount":
for x in range(int(val)):
line = next(datafile).replace("\n","")
hist = json.loads(line)
hists.append(hist)
history_dict["hists"] = hists
try:
line=next(datafile).replace("\n","")
except:
break
#print(history_dict)
# read data row
data_row_dict = {}
line = next(datafile).replace("\n","")
while line:
if line=="/e/":
break
else:
head = line.split("=")[0]
val = line.split("=")[-1]
data_row_dict[head] = val
rows = []
#print(head)
if head == "rowCount":
for x in range(int(val)):
line = next(datafile).replace("\n","")
row = json.loads(line)
rows.append(row)
data_row_dict["rows"] = rows
try:
line=next(datafile).replace("\n","")
except:
break
#print(data_row_dict)
return column_model_dict,history_dict,data_row_dict
def open_change(hist_dir,file_name,target_folder):
fname = ".".join(file_name.split(".")[:-1])
zipdoc = zipfile.ZipFile(hist_dir+file_name)
locex = target_folder+fname
try:
os.mkdir(locex)
except BaseException as ex:
print(ex)
zipdoc.extractall(locex)
zipdoc.close()
return locex,fname
def read_change(changefile):
changefile = open(changefile,"r",encoding="ascii", errors="ignore")
# read version
version = next(changefile).replace("\n","")
# read command_name
command_name = next(changefile).replace("\n","")
print(version,command_name)
header_dict = {}
data_row = []
if command_name == "com.google.refine.model.changes.MassCellChange":
header = ["commonColumnName","updateRowContextDependencies","cellChangeCount"]
for head in header:
header_dict[head] = next(changefile).replace("\n","").split("=")[-1]
print(header_dict)
data_header = ["row","cell","old","new"]
data_row = []
data_dict = {}
line = next(changefile).replace("\n","")
while line:
if line=="/ec/":
data_row.append(data_dict)
data_dict = {}
#break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
data_dict[head] = val
try:
line=next(changefile).replace("\n","")
except:
break
#print(data_row)
elif command_name == "com.google.refine.model.changes.ColumnAdditionChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
rows = {}
#print(head)
if head == "newCellCount":
for x in range(int(val)):
line = next(changefile).replace("\n","").split(";")
val = None
try:
val = json.loads(line[1])
except:
pass
row = int(line[0])
rows[row] = val
header_dict["val"] = rows
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.ColumnRemovalChange" :
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
rows = {}
#print(head)
if head == "oldCellCount":
for x in range(int(val)):
line = next(changefile).replace("\n","").split(";")
val = None
try:
val = json.loads(line[1])
except:
pass
row = int(line[0])
rows[row] = val
header_dict["val"] = rows
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.ColumnSplitChange" :
line = next(changefile).replace("\n","")
#print(line)
new_columns = []
new_cells = {}
new_rows = {}
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
#print(head)
# read new column name
if head == "columnNameCount":
for x in range(int(val)):
line = next(changefile).replace("\n","")
new_columns.append(line)
header_dict["new_columns"] = new_columns
# read new cells
if head == "rowIndexCount":
for x in range(int(val)):
line = next(changefile).replace("\n","")
index = int(line)
new_cells[x] = [None for i in range(int(header_dict["columnNameCount"]))]
new_rows[x] = None
if head == "tupleCount":
r_idx = list(new_cells.keys())
for i,x in enumerate(range(int(val))):
line = next(changefile).replace("\n","")
for y in range(int(line)):
line = next(changefile).replace("\n","")
new_cells[r_idx[i]][y] = line
header_dict["new_cells"] = new_cells
# read new rows values
if head == "newRowCount":
for x in new_rows.keys():
line = next(changefile).replace("\n","")
new_rows[x] = json.loads(line)
header_dict["new_rows"] = new_rows
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.ColumnRenameChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.CellChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.ColumnMoveChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.RowReorderChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
if head == "rowIndexCount":
row_order = []
for i,x in enumerate(range(int(val))):
line = next(changefile).replace("\n","")
row_order.append(int(line))
header_dict["row_order"] = row_order
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.RowRemovalChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
if head == "rowIndexCount":
row_idx_remove = []
for i,x in enumerate(range(int(val))):
line = next(changefile).replace("\n","")
row_idx_remove.append(int(line))
header_dict["row_idx_remove"] = row_idx_remove
if head == "rowCount":
old_values = []
for i,x in enumerate(range(int(val))):
line = next(changefile).replace("\n","")
old_values.append(json.loads(line))
header_dict["old_values"] = old_values
try:
line=next(changefile).replace("\n","")
except:
break
elif command_name == "com.google.refine.model.changes.RowStarChange":
line = next(changefile).replace("\n","")
#print(line)
while line:
if line=="/ec/":
break
else:
head = line.split("=")[0]
val = None
try:
val = "=".join(line.split("=")[1:])
except:
pass
header_dict[head] = val
try:
line=next(changefile).replace("\n","")
except:
break
return version,command_name,header_dict,data_row
def search_cell_column(col_mds,cell_index):
for i,col in enumerate(col_mds):
if col["cellIndex"] == cell_index:
return i,col
return -1, None
def search_cell_column_byname(col_mds,name):
for i,col in enumerate(col_mds):
if col["originalName"] == name:
return i,col
if col["name"] == name:
return i,col
return -1, None
at = 0
if __name__ == "__main__":
import sys
args = sys.argv
if len(args)!=2:
print("usage: {} <openrefine_projectfile>".format(args[0]))
exit()
file_name = args[1]
print("Process file: {}".format(file_name))
# extract project
#file_name = "airbnb_dirty-csv.openrefine.tar.gz"
#file_name = "03_poster_demo.openrefine.tar.gz"
#prepare database
extract_folder = ".".join(file_name.split(".")[:-2])+".extract"
try:
os.mkdir(extract_folder)
except:
pass
print("create extraction folder:",extract_folder)
db_name = '{}.db'.format(".".join(file_name.split(".")[:-2]))
if os.path.exists(db_name):
os.remove(db_name)
print("create database",db_name)
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
# Create table source
cursor.execute('''CREATE TABLE IF NOT EXISTS source
(source_id integer, source_url text, source_format text)''')
cursor.execute('''CREATE UNIQUE INDEX source_id
ON source(source_id)''');
source_id = 0
# Create table dataset
cursor.execute('''CREATE TABLE IF NOT EXISTS dataset
(dataset_id integer, source_id integer)''')
cursor.execute('''CREATE UNIQUE INDEX dataset_id
ON dataset(dataset_id)''');
dataset_id = 0
# Create table array
cursor.execute('''CREATE TABLE IF NOT EXISTS array
(array_id integer, dataset_id integer)''')
cursor.execute('''CREATE UNIQUE INDEX array_id
ON array(array_id)''');
array_id = 0
# Create table column
cursor.execute('''CREATE TABLE IF NOT EXISTS column
(col_id integer, array_id integer)''')
cursor.execute('''CREATE UNIQUE INDEX col_id
ON column(col_id)''');
col_id = 0
# row
cursor.execute('''CREATE TABLE IF NOT EXISTS row
(row_id integer, array_id integer)''')
cursor.execute('''CREATE UNIQUE INDEX row_id
ON row(row_id)''')
row_id = 0
# cell
cursor.execute('''CREATE TABLE IF NOT EXISTS cell
(cell_id integer, col_id integer, row_id integer)''')
cursor.execute('''CREATE UNIQUE INDEX cell_id
ON cell(cell_id)''')
cursor.execute('''CREATE UNIQUE INDEX cell_col_row
ON cell(col_id,row_id)''')
cell_id = 0
# state
"""
cursor.execute('''CREATE TABLE IF NOT EXISTS state
(state_id integer, array_id integer, prev_state_id integer, state_label text, command text)''')
"""
cursor.execute('''CREATE TABLE IF NOT EXISTS state
(state_id integer, array_id integer, prev_state_id integer)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS state_detail
(state_id integer, array_id integer, detail text)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS state_command
(state_id integer, state_label text, command text)''')
state_id = 0
cursor.execute('''CREATE TABLE IF NOT EXISTS col_dependency
(state_id integer, output_column integer, input_column integer)''')
# create network for dependency
col_dependency_graph = nx.DiGraph()
# content
cursor.execute('''CREATE TABLE IF NOT EXISTS content
(content_id integer, cell_id integer, state_id integer, value_id integer, prev_content_id integer)''')
content_id = 0
cursor.execute('''CREATE UNIQUE INDEX content_id
ON content(content_id)''')
cursor.execute('''CREATE INDEX content_cell
ON content(cell_id)''')
cursor.execute('''CREATE INDEX content_value_id_idx
ON content(value_id)''')
# value
cursor.execute('''CREATE TABLE IF NOT EXISTS value
(value_id integer, value_text text)''')
cursor.execute('''CREATE INDEX value_value_id_idx
ON value(value_id)''')
value_id = 0
# column_schema
cursor.execute('''CREATE TABLE IF NOT EXISTS column_schema
(col_schema_id integer, col_id integer, state_id integer, col_type string, col_name string, prev_col_id integer, prev_col_schema_id integer)''')
col_schema_id = 0
# row_position
cursor.execute('''CREATE TABLE IF NOT EXISTS row_position
(row_pos_id integer, row_id integer, state_id integer, prev_row_id integer, prev_row_pos_id integer)''')
cursor.execute('''CREATE INDEX row_pos_id_row_pos
ON row_position(row_pos_id)''')
cursor.execute('''CREATE INDEX row_id_row_pos_idx
ON row_position(row_id)''')
cursor.execute('''CREATE INDEX state_id_row_pos_idx
ON row_position(state_id)''')
cursor.execute('''CREATE INDEX prev_row_id_row_pos_idx
ON row_position(prev_row_id)''')
cursor.execute('''CREATE INDEX prev_row_posexit_id_row_pos_idx
ON row_position(prev_row_pos_id)''')
row_pos_id = 0
# create additional index
# create content and state relation
cursor.execute('''CREATE INDEX content_state_id_idx
ON content(state_id)''')
# create content and prev_content_id relation
cursor.execute('''CREATE INDEX content_prev_content_id_idx
ON content(prev_content_id)''');
# create view
# column schema and position at each state
cursor.execute('''
create view col_each_state as
select (b.state_id-(select max(state_id) from state s))*-1 as state
,b.state_id,a.col_schema_id,a.col_id,a.col_name,a.prev_col_id,a.prev_col_schema_id
from column_schema a, (
WITH RECURSIVE
state_cnt(state_id) AS (
SELECT -1 UNION ALL
SELECT state_id+1 FROM state_cnt
LIMIT (select max(state_id)+2 from state)
)
SELECT state_id FROM state_cnt
) b
where a.state_id<=b.state_id
and a.col_schema_id not in
(
select a.prev_col_schema_id from column_schema a
where a.state_id<=b.state_id
)
and prev_col_id>=-1
''');
# row position
cursor.execute(
'''create view row_at_state as
select (b.state_id-(select max(state_id) from state s))*-1 as state
,b.state_id,a.row_pos_id,a.row_id,a.prev_row_id,a.prev_row_pos_id
from row_position a, (
WITH RECURSIVE
state_cnt(state_id) AS (
SELECT -1 UNION ALL
SELECT state_id+1 FROM state_cnt
LIMIT (select max(state_id)+2 from state)
) SELECT state_id FROM state_cnt
) b
where a.state_id<=b.state_id
and a.row_pos_id not in
(
select a.prev_row_pos_id from row_position a
where a.state_id<=b.state_id
)
''')
# column dependency at state
cursor.execute('''create view col_dep_state as
WITH RECURSIVE
col_dep_order(state_id,prev_state_id,prev_input_column,input_column,output_column,level) AS (
select state_id,state_id,input_column,input_column,output_column,0 from col_dependency cd
UNION ALL
SELECT a.state_id,b.state_id,b.prev_input_column,a.input_column,b.input_column,b.level+1
FROM col_dependency a, col_dep_order b
WHERE a.output_column=b.input_column
and a.state_id>b.state_id)
SELECT distinct * from col_dep_order
''')
# value at state
cursor.execute('''
create view value_at_state as
select (b.state_id-(select max(state_id) from state s))*-1 as state
,b.state_id,a.content_id,a.prev_content_id,c.value_text,d.row_id,d.col_id
from content a, (
WITH RECURSIVE
state_cnt(state_id) AS (
SELECT -1 UNION ALL
SELECT state_id+1 FROM state_cnt
LIMIT (select max(state_id)+2 from state)
) SELECT state_id FROM state_cnt
) b
NATURAL JOIN value c
NATURAL JOIN cell d
where a.state_id<=b.state_id
and a.content_id not in
(
select a.prev_content_id from content a
where a.state_id<=b.state_id
)
''')
cursor.execute("INSERT INTO source VALUES (?,?,?)",(source_id,file_name,"OpenRefine Project File"))
locex,_ = extract_project(file_name)
# extract data
dataset = read_dataset(locex)
cursor.execute("INSERT INTO dataset VALUES (?,?)",(dataset_id,source_id))
cursor.execute("INSERT INTO array VALUES (?,?)",(array_id,dataset_id))
#columns = dataset[0]["cols"].copy()
#print(columns)
#exit()
recipes = {}
for x in dataset[1]["hists"]:
recipes[x["id"]] = x
#exit()
#print(recipes)
#exit()
#print([str(x["id"])+".change.zip" for x in dataset[1]["hists"][::-1]])
#exit()
# prepare cell changes log
"""
cell_changes = open("cell_changes.log","w",newline="",encoding="ascii", errors="ignore")
cell_writer = csv.writer(cell_changes,delimiter=",",quotechar='"',quoting=csv.QUOTE_ALL,escapechar="\\",doublequote=False)
meta_changes = open("meta_changes.log","w",encoding="ascii", errors="ignore")
recipe_changes = open("recipe_changes.log","w",encoding="ascii", errors="ignore")
recipe_writer = csv.writer(recipe_changes,delimiter=",",quotechar='"',quoting=csv.QUOTE_ALL,escapechar="\\",doublequote=False)
col_changes = open("col_changes.log","w",encoding="ascii", errors="ignore")
col_writer = csv.writer(col_changes,delimiter=",",quotechar='"',quoting=csv.QUOTE_ALL,escapechar="\\",doublequote=False)
row_changes = open("row_changes.log","w",encoding="ascii", errors="ignore")
row_writer = csv.writer(row_changes,delimiter=",",quotechar='"',quoting=csv.QUOTE_ALL,escapechar="\\",doublequote=False)
col_dependency = open("col_dependency.log","w",encoding="ascii", errors="ignore")
col_dep_writer = csv.writer(col_dependency,delimiter=",",quotechar='"',quoting=csv.QUOTE_ALL,escapechar="\\",doublequote=False)
"""
# read history file
hist_dir = locex+"/history/"
list_dir = os.listdir(hist_dir)
#for change in sorted(list_dir)[::-1]:
#order = 0
"""
cursor.execute('''CREATE TABLE IF NOT EXISTS cell
(cell_id number, col_id number, row_id number)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS value
(value_id number, value_text text)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS content
(content_id number, cell_id number, state_id number, value_id number, prev_content_id)''')
"""
#print(dataset[0]["cols"],len(dataset[0]["cols"]))
#print(sorted([x["cellIndex"] for x in dataset[0]["cols"]]))
#exit()
# insert column maximum index
for xx in range(int(dataset[0]["maxCellIndex"])+1):
cursor.execute("INSERT INTO column VALUES (?,?)",(xx,array_id))
col_dependency_graph.add_node(xx)
for ix, xx in enumerate(dataset[0]["cols"]):
#cursor.execute("INSERT INTO column VALUES (?,?)",(col_id,array_id))
tcid = xx["cellIndex"]
if ix==0:
prev_col_id = -1
cursor.execute('''INSERT INTO column_schema VALUES
(?,?,?,?,?,?,?)''',(col_schema_id,tcid,state_id-1,"",xx["name"],prev_col_id,-1))
prev_col_id=tcid
col_id+=1
col_schema_id+=1
cc_ids = list(cursor.execute("SELECT distinct state_id from column_schema order by state_id desc limit 1"))[0][0]
ccexs = list(cursor.execute("SELECT col_id,col_schema_id from column_schema where state_id=? order by col_schema_id asc",(str(cc_ids),)))
ccexs = [(x[0],x[1]) for x in ccexs]
#print(ccexs,len(ccexs))
for temp_row_id,x in enumerate(dataset[2]["rows"]):
#print(x["cells"])
for temp_col_id,y in enumerate(x["cells"]):
#print(temp_col_id)
try:
cursor.execute("INSERT INTO cell VALUES (?,?,?)",(cell_id,temp_col_id,temp_row_id))
except BaseException as ex:
print(x["cells"])
raise ex
try:
val = y["v"]
except:
val = None
if type(val)==str:
val = val.replace("\\","\\\\")
cursor.execute("INSERT INTO value VALUES (?,?)",(value_id,val))
cursor.execute("INSERT INTO content VALUES (?,?,?,?,?)",(content_id,cell_id,-1,value_id,-1))
cell_id+=1
value_id+=1
content_id+=1
"""
if temp_row_id==0:
cursor.execute("INSERT INTO column VALUES (?,?)",(col_id,array_id))
if temp_col_id==0:
prev_col_id = None
cursor.execute('''INSERT INTO column_schema VALUES
(?,?,?,?,?,?,?)''',(col_schema_id,col_id,state_id,"","",prev_col_id,None))
prev_col_id=col_id
col_id+=1
col_schema_id+=1
"""
cursor.execute("INSERT INTO row VALUES (?,?)",(row_id,array_id))
if temp_row_id==0:
prev_row_id = -1
#cursor.execute('''INSERT INTO row_position VALUES
# (?,?,?,?)''',(row_pos_id,row_id,state_id,prev_row_id))
cursor.execute('''INSERT INTO row_position VALUES
(?,?,?,?,?)''',(row_pos_id,row_id,-1,prev_row_id,-1))
prev_row_id=row_id
row_id+=1
row_pos_id+=1
#print(row_pos_id)
#exit()
#print(temp_row_id,temp_col_id,dataset[0],dataset[1])
conn.commit()
#exit()
#backward
ccexs_all = list(cursor.execute("SELECT * from column_schema where state_id=? order by col_schema_id asc",(str(cc_ids),)))
rcexs_all = list(cursor.execute("SELECT * from row_position where state_id=? order by row_pos_id asc",(str(cc_ids),)))
rcexs = list(cursor.execute("SELECT row_id,row_pos_id from row_position where state_id=? order by row_pos_id asc",(str(cc_ids),)))
rcexs = [(x[0],x[1]) for x in rcexs]
print([(x["id"],str(x["id"])+".change.zip") for x in dataset[1]["hists"][::-1]])
"""
for order,(change_id, change) in enumerate([(x["id"],str(x["id"])+".change.zip") for x in dataset[1]["hists"][::-1]]):
#print(change)
if change.endswith(".zip"):
print(change)
locexzip,_ = open_change(hist_dir,change,target_folder=hist_dir)
changes = read_change(locexzip+"/change.txt")
print(changes[1])
"""
#exit()
for order,(change_id, change) in enumerate([(x["id"],str(x["id"])+".change.zip") for x in dataset[1]["hists"][::-1]]):
print(change)
if change.endswith(".zip"):
print(change)
locexzip,_ = open_change(hist_dir,change,target_folder=hist_dir)
# read change
changes = read_change(locexzip+"/change.txt")
#recipe_writer.writerow([order,change_id,changes[1],dataset[0]["cols"],recipes[change_id]["description"]])
# insert state
#prev_state_id = state_id
#state_id+=1
#(state_id number, array_id number, prev_state_id number, state_label text, command text)
#print(state_id,array_id,prev_state_id,change_id,changes[1])
#cursor.execute("INSERT INTO state VALUES (?,?,?,?,?)",(state_id,array_id,prev_state_id,change_id,changes[1]))
if order == 0:
prev_state_id = -1
cursor.execute("INSERT INTO state VALUES (?,?,?)",(state_id,array_id,prev_state_id))
# extract operation history data
cursor.execute("INSERT INTO state_detail VALUES (?,?,?)",(state_id,array_id,json.dumps(recipes[change_id])))
#cursor.execute("INSERT INTO state VALUES (?,?,?)",(state_id,array_id,state_id))
cursor.execute("INSERT INTO state_command VALUES (?,?,?)",(state_id,change_id,changes[1]))
conn.commit()
# get rows and cols indexes for the state
# latest state_id of change
rc_ids = list(cursor.execute("SELECT distinct state_id from row_position order by state_id desc limit 1"))[0][0]
#rcexs = list(cursor.execute("SELECT row_id from row_position where state_id=? order by row_pos_id asc",(str(rc_ids),)))
#rcexs = [x[0] for x in rcexs]
#print(rcexs)
cc_ids = list(cursor.execute("SELECT distinct state_id from column_schema order by state_id desc limit 1"))[0][0]
ccexs = list(cursor.execute("SELECT col_id,col_schema_id from column_schema where state_id=? order by col_schema_id asc",(str(cc_ids),)))
ccexs = [(x[0],x[1]) for x in ccexs]
#ccexs_all = [(x[0],x[1]) for x in ccexs]
#print(ccexs_all)
#exit()
#exit()
#op-1
if changes[1] == "com.google.refine.model.changes.MassCellChange":
#print(changes[3])
#print(changes)
is_change = False
#print(dataset[0]["cols"])
columns = dataset[0]["cols"].copy()
cc = search_cell_column_byname(columns,changes[2]["commonColumnName"])
#print(cc)
cursor.execute("INSERT INTO col_dependency VALUES (?,?,?)",(state_id,int(cc[1]["cellIndex"]),int(cc[1]["cellIndex"])))
for ch in changes[3]:
try:
r = int(ch["row"])
is_change = True
except BaseException as ex:
print(ex)
continue
c = int(ch["cell"])
nv = json.loads(ch["new"])
if ch["old"] == "":
ov = {"v": None}
else:
try:
ov = json.loads(ch["old"])
except Exception as ex:
print(ch["old"])
raise ex
#print(ch)
#print(ch)
#print(dataset[2]["rows"][r])
#print(dataset[2]["rows"][r]["cells"][c],ch)
#print(dataset[2]["rows"][r]["cells"][c],nv)
if dataset[2]["rows"][r]["cells"][c] == nv:
# log file recorded here
# 0, start, cell_no, row_no, null, 1
# <change_id>,<operation_name,<cell_no>,<row_no>,<old_val>,<new_val>,<row_depend>,<cell_depend>
dataset[2]["rows"][r]["cells"][c] = ov
#print(rcexs[:100])
#print(r,c,rcexs[r],rcexs.index(r))
val = ov["v"]
#cell_changes.write("{},{},{},{},{},{},{},{},{}\n".format(order,change_id,changes[1],r,c,ov,nv,r,c))
#cell_writer.writerow([order,change_id,changes[1],r,c,ov,nv,r,c])
# write cell_changes
# get previous value_id
#print(rcexs.index(r))
try:
cex = cursor.execute("SELECT content_id,cell_id FROM (SELECT a.content_id,a.cell_id,a.state_id FROM content a,cell b where a.cell_id=b.cell_id and b.col_id=? and b.row_id=?) order by state_id desc limit 1",(c,rcexs[r][0]))
#cex = cursor.execute("SELECT content_id,cell_id FROM (SELECT a.content_id,a.cell_id,a.state_id FROM content a,cell b where a.cell_id=b.cell_id and b.col_id=? and b.row_id=?) order by state_id desc limit 1",(c,rcexs[r]))
#cex = cursor.execute("SELECT content_id,cell_id FROM (SELECT a.content_id,a.cell_id,a.state_id FROM content a,cell b where a.cell_id=b.cell_id and b.col_id=? and b.row_id=?) order by state_id desc limit 1",(c,r))
except BaseException as ex:
print(dataset[2]["rows"][r]["cells"])
print(ccexs,c,len(ccexs),len(dataset[2]["rows"][r]["cells"]))
raise ex
#print(dataset[2]["rows"][r]["cells"])
#print(ccexs,c,len(ccexs),len(dataset[2]["rows"][r]["cells"]))
#exit()
#print(len(dataset[2]["rows"][r]["cells"]))
try:
cex = list(cex)[0]
except BaseException as ex:
print((r,c),list(cex))
raise ex
if type(val)==str:
val = val.replace("\\","\\\\")
cursor.execute("INSERT INTO value VALUES (?,?)",(value_id,val))
cursor.execute("INSERT INTO content VALUES (?,?,?,?,?)",(content_id,cex[1],state_id,value_id,cex[0]))
#print(value_id,content_id)
#if state_id==42:
# conn.commit()
# exit()
value_id+=1
content_id+=1
#conn.commit()
#exit()
#print(dataset[2]["rows"][r]["cells"][c],ch)
#print(dataset[2]["rows"][0]["cells"])
conn.commit()
columns = dataset[0]["cols"].copy()
col_names = [x["name"] for x in columns]
# add dependency column
##col_dep_writer.writerow([order,change_id,c_idx,new])
#print("recipe:",recipes[change_id])
#print(len(changes[3]))
if is_change: