-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.py
2791 lines (2235 loc) · 125 KB
/
utils.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 json
import sys
import ijson
import re
import heapq
from typing import Any, Dict, List, Union, Optional
from io import StringIO
from tqdm import tqdm
from datetime import datetime
from dateutil import tz
import csv
import os
import tempfile
import shutil
import humanize
import jsonlines
from functools import partial
from decimal import Decimal
import warnings
import numpy as np
import pandas as pd
from pandas.api.types import CategoricalDtype
import ast
from jaccard_index.jaccard import jaccard_index
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return super(CustomJSONEncoder, self).default(obj)
def replace_index_with_brackets(new_path):
path_parts = new_path.split('.')
for i, part in enumerate(path_parts):
if part.isdigit():
path_parts[i] = '[]'
return '.'.join(path_parts)
def combine_matching_pairs(dict1, dict2):
combined_dict = {}
for key in set(dict1.keys()) | set(dict2.keys()):
if key in dict1 and key in dict2:
combined_dict[key] = [dict1[key], dict2[key]]
elif key in dict1:
combined_dict[key] = dict1[key]
elif key in dict2:
combined_dict[key] = dict2[key]
return combined_dict
class CustomJSONTqdm(tqdm):
@staticmethod
def format_meter(n, total, elapsed, rate_fmt=None, postfix=None, ncols=None, **extra_kwargs):
rate = n / elapsed if elapsed else 0
remaining_time = (total - n) / rate if rate and total is not None else 0
formatted_rate = f"{rate:.2f}"
humanized_rate = humanize.intcomma(formatted_rate)
if total is not None:
return f"Counting objects: {humanize.intcomma(n)}/{humanize.intcomma(total)} objects " \
f"[{tqdm.format_interval(elapsed)}<{tqdm.format_interval(remaining_time)}, " \
f"{humanized_rate} objects/s]"
else:
return f"Counting objects: {humanize.intcomma(n)} objects " \
f"[{tqdm.format_interval(elapsed)}, {humanized_rate} objects/s]"
class CustomCSVTqdm(tqdm):
@staticmethod
def format_meter(n, total, elapsed, rate_fmt=None, postfix=None, ncols=None, **extra_kwargs):
rate = n / elapsed if elapsed else 0
remaining_time = (total - n) / rate if rate and total is not None else 0
formatted_rate = f"{rate:.2f}"
humanized_rate = humanize.intcomma(formatted_rate)
if total is not None:
return f"Counting rows: {humanize.intcomma(n)}/{humanize.intcomma(total)} rows " \
f"[{tqdm.format_interval(elapsed)}<{tqdm.format_interval(remaining_time)}, " \
f"{humanized_rate} row/s]"
else:
return f"Counting objects: {humanize.intcomma(n)} rows " \
f"[{tqdm.format_interval(elapsed)}, {humanized_rate} rows/s]"
class CustomChunkedCSVTqdm(tqdm):
def __init__(self, iterable, chunksize, *args, **kwargs):
self.chunksize = chunksize
super().__init__(iterable, *args, **kwargs)
def update_to(self, b=1, bsize=None, tsize=None):
bsize = bsize or self.chunksize
self.update(b * bsize - self.n)
def format_meter(self, n, total, elapsed, rate_fmt=None, postfix=None, ncols=None, **extra_kwargs):
rate = n / elapsed if elapsed else 0
rate *= self.chunksize
remaining_time = (total - n) / rate if rate and total is not None else 0
formatted_rate = f"{rate:.2f}"
humanized_rate = humanize.intcomma(formatted_rate)
if total is not None:
return f"Counting rows in chunks: {humanize.intcomma(n * self.chunksize)}/{humanize.intcomma(total)} rows " \
f"[{tqdm.format_interval(elapsed)}<{tqdm.format_interval(remaining_time)}, " \
f"{humanized_rate} rows/s]"
else:
return f"Counting rows in chunks: {humanize.intcomma(n * self.chunksize)} rows " \
f"[{tqdm.format_interval(elapsed)}, {humanized_rate} rows/s]"
class CustomComparisonTqdm2(tqdm):
@staticmethod
def format_meter(n, total, elapsed, rate_fmt=None, postfix=None, ncols=None, **extra_kwargs):
rate = n / elapsed if elapsed else 0
remaining_time = (total - n) / rate if rate and total is not None else 0
formatted_rate = f"{rate:.2f}"
humanized_rate = humanize.intcomma(formatted_rate)
if total is not None:
return f"Processing comparisons: {humanize.intcomma(n)}/{humanize.intcomma(total)} comparisons " \
f"[{tqdm.format_interval(elapsed)}<{tqdm.format_interval(remaining_time)}, " \
f"{humanized_rate} comparisons/s]"
else:
return f"Processing comparisons: {humanize.intcomma(n)} comparisons " \
f"[{tqdm.format_interval(elapsed)}, {humanized_rate} comparisons/s]"
class CustomComparisonTqdm(tqdm):
@staticmethod
def format_meter(n, total, elapsed, rate_fmt=None, postfix=None, ncols=None, **extra_kwargs):
percentage = n / total * 100 if total is not None else 0
formatted_percentage = f"{percentage:.1f}"
if total is not None:
return f"Processing comparisons: {humanize.intcomma(n)}/{humanize.intcomma(total)} comparisons " \
f"({formatted_percentage}%) [{tqdm.format_interval(elapsed)}]"
else:
return f"Processing comparisons: {humanize.intcomma(n)} comparisons " \
f"[{tqdm.format_interval(elapsed)}]"
def count_items_old(json_input, root_key=None, row_limit=None):
with open(json_input, 'r', encoding='utf-8') as f:
if root_key:
items = ijson.items(f, f"{root_key}.item")
else:
items = ijson.items(f, 'item')
count = 0
for _ in CustomJSONTqdm(items, unit=' objects', ncols=None):
count += 1
if row_limit is not None and count >= row_limit:
break
return count
def count_items(json_input, root_key=None, is_array=False, row_limit=None):
with open(json_input, 'r', encoding='utf-8') as f:
if root_key:
items = ijson.items(f, f"{root_key}.item")
elif is_array:
items = ijson.items(f, 'item')
else:
return 1
count = 0
for _ in CustomJSONTqdm(items, unit=' objects', ncols=None):
count += 1
if row_limit is not None and count >= row_limit:
break
return count
def reformat_json(input_json: str = None):
# Set up the input and output file paths
output_path = "reformatted__" + os.path.basename(input_json)
# Count the total number of top-level objects in the input JSON file
total_objects = count_items(input_json)
# Process the input JSON file and reformat it
with open(input_json, 'r', encoding='utf-8') as input_file, \
open(output_path, 'w', encoding='utf-8') as output_file:
output_file.write("[\n")
parser = ijson.items(input_file, 'item')
for index, obj in tqdm(enumerate(parser), total=total_objects, desc="Processing objects", unit=" objects",
ncols=100):
formatted_obj = json.dumps(obj, ensure_ascii=False, indent=2, cls=CustomJSONEncoder)
output_file.write(formatted_obj)
if index < total_objects - 1:
output_file.write(",\n")
output_file.write("\n]")
return output_path
def truncate_json_inefficient_memory(input_json: str = None, root_key: str = None, depth: int = 1):
def truncate(obj, current_depth):
if current_depth > depth:
return '{}' if isinstance(obj, dict) else '[]' if isinstance(obj, list) else str(obj)
if isinstance(obj, dict):
return {k: truncate(v, current_depth + 1) for k, v in obj.items()}
elif isinstance(obj, list):
return [truncate(v, current_depth + 1) for v in obj]
else:
return obj
total_items = count_items(input_json, root_key)
truncated_data = []
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.items(f, f"{root_key}.item" if root_key else 'item')
input_json_basename = os.path.basename(input_json)
filename_without_ext = os.path.splitext(input_json_basename)[0]
json_output_filename = f'truncated__{filename_without_ext}.json'
for obj in tqdm(parser, total=total_items, desc='Processing objects', unit=' objects', ncols=100):
truncated_obj = truncate(obj, 1)
truncated_data.append(truncated_obj)
with open(json_output_filename, 'w+', newline='', encoding='utf-8') as json_output:
json.dump(truncated_data, json_output, ensure_ascii=False, indent=2, cls=CustomJSONEncoder)
return json_output_filename
def truncate_jsonl(input_json: str = None, root_key: str = None, depth: int = 1):
def truncate(obj, current_depth):
if current_depth > depth:
return '{}' if isinstance(obj, dict) else '[]' if isinstance(obj, list) else str(obj)
if isinstance(obj, dict):
return {k: truncate(v, current_depth + 1) for k, v in obj.items()}
elif isinstance(obj, list):
return [truncate(v, current_depth + 1) for v in obj]
else:
return obj
total_items = count_items(input_json, root_key)
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.items(f, f"{root_key}.item" if root_key else 'item')
input_json_basename = os.path.basename(input_json)
filename_without_ext = os.path.splitext(input_json_basename)[0]
json_output_filename = f'truncated__{filename_without_ext}.jsonl'
with jsonlines.open(json_output_filename, mode='w') as json_output:
for obj in tqdm(parser, total=total_items, desc='Processing objects', unit=' objects', ncols=100):
truncated_obj = truncate(obj, 1)
json_output.write(truncated_obj)
return json_output_filename
def truncate_json(input_json: str = None, root_key: str = None, depth: int = 1):
def truncate(obj, current_depth):
if current_depth > depth:
return '{}' if isinstance(obj, dict) else '[]' if isinstance(obj, list) else str(obj)
if isinstance(obj, dict):
return {k: truncate(v, current_depth + 1) for k, v in obj.items()}
elif isinstance(obj, list):
return [truncate(v, current_depth + 1) for v in obj]
else:
return obj
total_items = count_items(input_json, root_key)
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.items(f, f"{root_key}.item" if root_key else 'item')
input_json_basename = os.path.basename(input_json)
filename_without_ext = os.path.splitext(input_json_basename)[0]
json_output_filename = f'truncated__{filename_without_ext}.json'
with open(json_output_filename, 'w', newline='', encoding='utf-8') as json_output:
json_output.write('[')
first_item = True
for obj in tqdm(parser, total=total_items, desc='Processing objects', unit=' objects', ncols=100):
truncated_obj = truncate(obj, 1)
if first_item:
first_item = False
else:
json_output.write(',')
json.dump(truncated_obj, json_output, ensure_ascii=False, indent=2, cls=CustomJSONEncoder)
json_output.write(']')
return json_output_filename
def collapse_json(input_json: str = None, root_key: str = None, depth: int = 1):
def truncate_stats(obj, current_depth):
if current_depth == depth:
if isinstance(obj, dict):
return f'{{{len(obj)} props}}'
elif isinstance(obj, list):
return f'[{len(obj)} props]'
if isinstance(obj, dict):
return {k: truncate_stats(v, current_depth + 1) for k, v in obj.items()}
elif isinstance(obj, list):
return [truncate_stats(v, current_depth + 1) for v in obj]
else:
return obj
input_json_basename = os.path.basename(input_json)
filename_without_ext = os.path.splitext(input_json_basename)[0]
json_output_filename = f'collapse__{filename_without_ext}.json'
with open(input_json, 'r', encoding='utf-8') as f:
first_token = next(ijson.parse(f))
is_single_object = first_token[0] == "start_map"
f.seek(0)
if is_single_object:
parser = ijson.items(f, 'item')
total_items = count_items(input_json, root_key) if root_key else count_items(input_json)
else:
parser = ijson.items(f, f"{root_key}.item" if root_key else 'item')
total_items = count_items(input_json, root_key) if root_key else count_items(input_json)
with open(json_output_filename, 'w', newline='', encoding='utf-8') as json_output:
if depth == 0:
if is_single_object:
progress_bar = tqdm(total=1, desc='Processing objects', unit=' objects', ncols=100)
progress_bar.update()
truncated_obj = f'{{\"{total_items} props\"}}'
else:
progress_bar = tqdm(total=1, desc='Processing objects', unit=' objects', ncols=100)
progress_bar.update()
truncated_obj = f'["{total_items} props"]'
json_output.write(truncated_obj)
return json_output_filename
json_output.write('[')
first_item = True
for obj in tqdm(parser, total=total_items, desc='Processing objects', unit=' objects', ncols=100):
truncated_obj = truncate_stats(obj, 1)
if first_item:
first_item = False
else:
json_output.write(',')
json.dump(truncated_obj, json_output, ensure_ascii=False, indent=2, cls=CustomJSONEncoder)
json_output.write(']')
return json_output_filename
def dot_notation_match(search_key, path):
if search_key == path:
return True
search_key_parts = search_key.split('.')
path_parts = path.split('.')
if len(search_key_parts) != len(path_parts):
return False
for search_part, path_part in zip(search_key_parts, path_parts):
if search_part == '[]':
if not path_part.isdigit():
return False
elif '[' in search_part and ']' in search_part:
field, indices = search_part.split('[')
start, end = indices[:-1].split('-')
if not (start.isdigit() and end.isdigit()):
return False
start, end = int(start), int(end)
if not (path_part.startswith(field + '[') and path_part.endswith(']')):
return False
index_str = path_part[len(field) + 1:-1]
if not index_str.isdigit():
return False
index = int(index_str)
if not (start <= index <= end):
return False
elif search_part != path_part:
return False
return True
def process_item(item, options, prefix='', row=None):
if row is None:
row = {}
if isinstance(item, dict):
for k, v in item.items():
new_key = f"{prefix}.{k}" if prefix else k
process_item(v, options=options, prefix=new_key, row=row)
elif isinstance(item, list):
array_handling = options.get('arrayHandling', 'stringify')
if array_handling == 'stringify':
row[prefix] = str(item)
elif array_handling == 'explode':
# TODO: handle explode
pass
else:
row[prefix] = item
return row
def get_datetime():
# Get the current date and time (naive)
current_datetime_naive = datetime.now()
# Get the system's timezone
system_timezone = tz.tzlocal()
# Make the current datetime timezone-aware
current_datetime_local = current_datetime_naive.replace(tzinfo=system_timezone)
# Format the current date and time with the system's timezone for use in a filename
formatted_datetime = current_datetime_local.strftime('%Y-%m-%d_%H-%M-%S_%z')
return formatted_datetime
def find_root_key_old(input_json: str):
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.parse(f)
for prefix, event, value in parser:
if event == 'map_key' and (prefix == '' or prefix.endswith('.item')):
return value
else:
break
return None
def find_root_key(input_json: str, root_key=None):
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.parse(f)
is_array = False
for prefix, event, value in parser:
if event == 'start_array' and (prefix == '' or prefix.endswith('.item')):
is_array = True
break
elif event == 'map_key' and (prefix == '' or prefix.endswith('.item')):
if root_key is None or root_key == value:
return (is_array, value)
else:
break
return (is_array, None)
# TODO fix this
def create_temp_array_wrapped_json(input_json: str, return_basename: bool = False) -> str:
"""
Creates a temporary JSON file containing the input JSON wrapped in an array.
Args:
input_json (str): Path to the input JSON file.
return_basename (bool, optional): If True, return only the filename without the path. Defaults to False.
Returns:
str: Path to the temporary JSON file with the input JSON wrapped in an array (or just the filename, if return_basename is True).
"""
# Create a temporary folder in the current directory
temp_folder = "temp"
if not os.path.exists(temp_folder):
os.makedirs(temp_folder)
with open(input_json, 'r', encoding='utf-8') as original_file:
# Use the temporary folder for the NamedTemporaryFile
with tempfile.NamedTemporaryFile(mode='w+', suffix='.json', delete=False, dir=temp_folder) as temp_file:
temp_file.write('[')
shutil.copyfileobj(original_file, temp_file)
temp_file.write(']')
temp_file.flush()
temp_file_path = temp_file.name
if return_basename:
return os.path.basename(temp_file_path)
else:
return temp_file_path
class DynamicDictWriter: # TODO finish smart functions
def __init__(self, csvfile, fieldnames, delimiter=None, dialect='excel', quoting=csv.QUOTE_NONE, escapechar='\\',
smart_header_padding_amount=100000):
self.headers_written = False
self.fieldnames = list(fieldnames) # Ensure fieldnames is a list
self.csvfile = csvfile
self.delimiter = delimiter
self.smart_header_padding_amount = smart_header_padding_amount
self.smart_header_present = False
self.smart_written_num = 0
self.padding_length = 0
self.previous_header_length = 0
self.remaining_padding = 0
# Create a temporary folder in the current directory
self.temp_folder = "temp"
if not os.path.exists(self.temp_folder):
os.makedirs(self.temp_folder)
if delimiter:
# Register a new dialect with the specified delimiter
csv.register_dialect('custom_dialect', delimiter=delimiter,
quoting=quoting, escapechar=escapechar)
self.dialect = 'custom_dialect'
else:
self.dialect = dialect
self.writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=self.dialect)
self.headers_written = True
def writeheader(self):
if not self.headers_written:
self.writer.writeheader()
self.headers_written = True
def writerow(self, row):
new_fields = set(row.keys()) - set(self.fieldnames)
new_fields_sorted = sorted(new_fields)
if new_fields:
self.fieldnames += new_fields_sorted
self.update_header()
self.update_writer()
self.writer.writerow(row)
def update_header(self):
# Read the current header row from the file up to the newline character
self.csvfile.seek(0)
current_header = self.csvfile.readline()
# Calculate the length of the current header row (including newline character)
current_header_length = len(current_header)
# Calculate the length of the new header row (including newline character)
new_header = ','.join(self.fieldnames) + '\n'
new_header_length = len(new_header)
# If the new header is longer than the current header, rewrite the entire file
if new_header_length > current_header_length:
self.csvfile.seek(0)
# Use the temporary folder for the NamedTemporaryFile
with tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=self.temp_folder, newline='',
encoding='utf-8') as temp_file:
# Write the new header to the temporary file
temp_file.write(new_header)
# Move the file pointer to the position right after the current header
self.csvfile.seek(current_header_length) # +1 gets rid of trailing newline character
# Copy the rest of the contents from the original file to the temporary file
shutil.copyfileobj(self.csvfile, temp_file)
temp_file.flush()
# Replace the original file with the temporary file
shutil.move(temp_file.name, self.csvfile.name)
# Re-open the original file
self.csvfile.close()
self.csvfile = open(self.csvfile.name, 'r+', newline='', encoding='utf-8')
self.csvfile.seek(0, os.SEEK_END)
# If the new header is shorter than or equal to the current header, just update the header
else:
# Write the new header row to the beginning of the file
self.csvfile.seek(0)
self.csvfile.write(new_header)
# Move the file pointer to the end of the file
self.csvfile.seek(0, os.SEEK_END)
self.update_writer()
def smart_writerow(self, row):
new_fields = set(row.keys()) - set(self.fieldnames)
new_fields_sorted = sorted(new_fields)
if new_fields:
self.fieldnames += new_fields_sorted
self.smart_update_header()
self.update_writer()
self.writer.writerow(row)
self.smart_written_num += 1
def smart_update_header(self):
current_header_length = self.get_current_header_length()
new_header = ','.join(self.fieldnames) + '\n'
new_header_length = len(new_header)
if not self.smart_header_present:
self.add_padding()
self.smart_header_present = True
if new_header_length > (current_header_length - self.padding_length):
self.remove_padding()
self.update_padding()
self.add_padding()
self.remaining_padding = self.padding_length - (new_header_length - self.previous_header_length)
self.csvfile.seek(0)
self.csvfile.write(new_header + ' ' * self.remaining_padding)
self.previous_header_length = current_header_length
def add_padding(self):
current_header_length = self.get_current_header_length()
new_header = ','.join(self.fieldnames) + '\n'
new_header_length = len(new_header)
padding = ' ' * self.smart_header_padding_amount
with tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=self.temp_folder, newline='', encoding='utf-8') \
as temp_file:
self.csvfile.seek(0)
shutil.copyfileobj(self.csvfile, temp_file, current_header_length)
temp_file.write(padding)
temp_file.flush()
shutil.move(temp_file.name, self.csvfile.name)
self.csvfile.close()
self.csvfile = open(self.csvfile.name, 'r+', newline='', encoding='utf-8')
self.csvfile.seek(0, os.SEEK_END)
self.padding_length = self.smart_header_padding_amount
self.remaining_padding = self.smart_header_padding_amount
def get_current_header_length(self):
self.csvfile.seek(0)
current_header = self.csvfile.readline()
current_header_length = len(current_header)
return current_header_length
def update_padding(self):
new_padding_amount = int((self.smart_written_num / self.smart_header_padding_amount) * self.padding_length)
self.smart_header_padding_amount = max(self.smart_header_padding_amount, new_padding_amount)
def remove_padding(self):
if not self.smart_header_present:
return
self.csvfile.seek(0)
current_header = self.csvfile.readline()
current_header_length = len(current_header)
self.csvfile.seek(0)
new_header = ','.join(self.fieldnames) + '\n'
new_header_length = len(new_header)
padding_to_remove = current_header_length - new_header_length
if padding_to_remove > 0:
self.csvfile.seek(0)
temp_folder = "temp"
if not os.path.exists(temp_folder):
os.makedirs(temp_folder)
with tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=temp_folder, newline='',
encoding='utf-8') as temp_file:
temp_file.write(new_header)
self.csvfile.seek(current_header_length - padding_to_remove)
shutil.copyfileobj(self.csvfile, temp_file)
temp_file.flush()
shutil.move(temp_file.name, self.csvfile.name)
self.csvfile.close()
self.csvfile = open(self.csvfile.name, 'r+', newline='', encoding='utf-8')
self.csvfile.seek(0, os.SEEK_END)
self.padding_length = 0
self.smart_header_present = False
def update_writer(self):
self.writer = csv.DictWriter(self.csvfile, self.fieldnames, dialect=self.dialect)
if not self.headers_written:
self.writer.writeheader()
class DynamicHeaderWriter(csv.DictWriter):
def __init__(self, csvfile, fieldnames, delimiter=None, dialect='excel'):
self.headers_written = False
self.fieldnames = list(fieldnames) # Ensure fieldnames is a list
self.csvfile = csvfile
self.delimiter = delimiter
if delimiter:
# Register a new dialect with the specified delimiter
csv.register_dialect('custom_dialect', delimiter=delimiter)
self.dialect = 'custom_dialect'
else:
self.dialect = dialect
self.writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=self.dialect)
self.headers_written = True
def process_row(self, row):
new_fields = set(row.keys()) - set(self.fieldnames)
new_fields_sorted = sorted(new_fields)
if new_fields:
self.fieldnames += new_fields_sorted
self.update_header()
def update_header(self):
# Read the current header row from the file up to the newline character
self.csvfile.seek(0)
current_header = self.csvfile.readline()
# Calculate the length of the current header row (including newline character)
current_header_length = len(current_header)
# Calculate the length of the new header row (including newline character)
new_header = ','.join(self.fieldnames) + '\n'
new_header_length = len(new_header)
# Move the file pointer to the beginning of the file
self.csvfile.seek(0)
# Write the new header row
self.csvfile.write(new_header)
# If the new header is shorter than the current header, fill the remaining space with spaces
if new_header_length < current_header_length:
padding = ' ' * (current_header_length - new_header_length)
self.csvfile.write(padding)
# Move the file pointer to the end of the file
self.csvfile.seek(0, os.SEEK_END)
def update_writer(self):
self.writer = csv.DictWriter(self.csvfile, self.fieldnames, dialect=self.dialect)
def trim_json(input_json: Union[str, Dict], root_key: Optional[str] = None, range_str: Optional[str] = None):
if range_str:
start, end = map(int, range_str.split('-'))
total_items = count_items(input_json, root_key, end)
else:
total_items = count_items(input_json, root_key)
start, end = 0, total_items
with open(input_json, 'r', encoding='utf-8') as f:
parser = ijson.items(f, f"{root_key}.item" if root_key else 'item')
datetime = str(get_datetime())
json_output_filename = 'trimmed_json__' + root_key + '_' + datetime + ".json"
with open(json_output_filename, 'w+', newline='', encoding='utf-8') as json_output:
json_output.write("[\n")
for idx, obj in enumerate(
tqdm(parser, total=total_items, desc='Processing objects', unit=' objects', ncols=100)):
if start <= idx < end:
json.dump(obj, json_output, ensure_ascii=False, indent=2, cls=CustomJSONEncoder)
if idx < end - 1:
json_output.write(",\n")
elif idx >= end:
break
json_output.write("\n]")
def bulk_rename_csv_headers(input_csv: str, rename_obj: dict, threshold: float = None):
with open(input_csv, 'w+', newline='', encoding='utf-8') as csvfile:
# Read the current header row from the file up to the newline character
csvfile.seek(0)
current_header = csvfile.readline()
# Split the current header into columns and create a new header list
current_columns = current_header.strip().split(',')
new_columns = []
for col in current_columns:
if col in rename_obj:
new_columns.append(rename_obj[col])
else:
max_similarity = -1
best_match = col
if threshold is not None:
for old_name in rename_obj:
similarity = jaccard_index(col, old_name)
if similarity > max_similarity and similarity >= threshold:
max_similarity = similarity
best_match = rename_obj[old_name]
new_columns.append(best_match)
new_header = ','.join(new_columns) + '\n'
# Calculate the length of the current header row (including newline character)
current_header_length = len(current_header)
# Calculate the length of the new header row (including newline character)
new_header_length = len(new_header)
# If the new header is longer than the current header, rewrite the entire file
if new_header_length > current_header_length:
csvfile.seek(0)
# Create a temporary folder in the current directory
temp_folder = "temp"
if not os.path.exists(temp_folder):
os.makedirs(temp_folder)
# Use the temporary folder for the NamedTemporaryFile
with tempfile.NamedTemporaryFile(mode='w+', delete=False, dir=temp_folder, newline='',
encoding='utf-8') as temp_file:
# Write the new header to the temporary file
temp_file.write(new_header)
# Move the file pointer to the position right after the current header
csvfile.seek(current_header_length)
# Copy the rest of the contents from the original file to the temporary file
shutil.copyfileobj(csvfile, temp_file)
temp_file.flush()
# Replace the original file with the temporary file
shutil.move(temp_file.name, csvfile.name)
# If the new header is shorter than or equal to the current header, just update the header
else:
# Write the new header row to the beginning of the file
csvfile.seek(0)
csvfile.write(new_header)
# Move the file pointer to the end of the file
csvfile.seek(0, os.SEEK_END)
return input_csv
def gen_bulk_rename_csv_headers(input_csv: str, rename_obj: dict, threshold: float = None):
with open(input_csv, 'r', newline='', encoding='utf-8') as csvfile:
# Read the current header row from the file up to the newline character
csvfile.seek(0)
current_header = csvfile.readline()
# Split the current header into columns and create a new header list
current_columns = current_header.strip().split(',')
new_columns = []
for col in current_columns:
if col in rename_obj:
new_columns.append(rename_obj[col])
else:
max_similarity = -1
best_match = col
if threshold is not None:
for old_name in rename_obj:
similarity = jaccard_index(col, old_name)
if similarity > max_similarity and similarity >= threshold:
max_similarity = similarity
best_match = rename_obj[old_name]
new_columns.append(best_match)
new_header = ','.join(new_columns) + '\n'
# Generate the new CSV file name with "_renamed" added to the original file name
input_csv_name, input_csv_ext = os.path.splitext(input_csv)
output_csv = f"{input_csv_name}_renamed{input_csv_ext}"
# Create a new CSV file with the new header
with open(output_csv, 'w', newline='', encoding='utf-8') as output_file:
output_file.write(new_header)
# Move the file pointer to the position right after the current header
csvfile.seek(len(current_header))
# Copy the rest of the contents from the original file to the new file
shutil.copyfileobj(csvfile, output_file)
def escape_csv_string(s, line_break_handling='escape', quote_handling='double', quote_values=False):
# try:
if line_break_handling == 'escape':
s = s.replace('\r\n', '\\r\\n').replace('\n', '\\n').replace('\r', '\\r')
elif line_break_handling == 'remove':
s = s.replace('\r\n', '').replace('\n', '').replace('\r', '')
'''
except Exception as e:
print(f'String: {s}')
print(f"An error occurred: {e}")
'''
if quote_handling == 'double':
s = s.replace('"', '""')
elif quote_handling == 'escape':
s = s.replace('"', '\\"')
if quote_values:
s = f'"{s}"'
return s
def sanitize_key_name(key_name, line_break_handling='escape', quote_handling='double'):
return escape_csv_string(key_name, line_break_handling, quote_handling)
def sanitize_top_level_keys(data, line_break_handling='escape', quote_handling='double'):
if isinstance(data, dict):
return {sanitize_key_name(k, line_break_handling, quote_handling): v for k, v in data.items()}
elif isinstance(data, list):
return [sanitize_top_level_keys(item, line_break_handling, quote_handling) for item in data]
else:
return data
def count_rows(file_path):
with CustomCSVTqdm(pd.read_csv(file_path, iterator=True, chunksize=10000), ncols=100,
desc='Counting rows') as reader:
return sum(chunk.shape[0] for chunk in reader)
def count_rows_in_chunks(file_path, chunksize):
reader = read_csv_in_chunks(file_path, chunksize)
with CustomChunkedCSVTqdm(reader, ncols=100, desc='Counting rows', chunksize=chunksize) as reader_tqdm:
return sum(chunk.shape[0] for chunk in reader_tqdm)
def read_csv_in_chunks(file_path, chunksize):
reader = pd.read_csv(file_path, iterator=True, chunksize=chunksize, low_memory=False)
for chunk in reader:
yield chunk
def filter_rows_by_priority_old(row_limit, input_csv, output_csv=None, filter_config=None, chunksize=10000,
drop_score=True, score_breakdown=False):
def calculate_score(row):
score = 0
breakdown = []
for col, config in filter_config.items():
value = row[col]
if isinstance(config['range'], list):
if isinstance(config['range'][0], (int, float)):
min_val = config['range'][0]
max_val = config['range'][-1]
step = (max_val - min_val) / (len(config['range']) - 1)
normalized_value = (value - min_val) / step
elif isinstance(config['range'][0], str):
index = config['range'].index(value)
normalized_value = index / (len(config['range']) - 1)
else:
raise ValueError("Invalid value in the range list.")
elif isinstance(config['range'], tuple) and len(config['range']) == 2:
min_val, max_val = config['range']
normalized_value = (value - min_val) / (max_val - min_val)
else:
raise ValueError("Invalid range configuration.")
if config['order'] == 'desc':
normalized_value = 1 - normalized_value
score_component = normalized_value * config.get('priority', 1)
score += score_component
breakdown.append(f"({col}: {score_component:.2f})")
if score_breakdown:
return score, ' + '.join(breakdown)
return score
total_rows = count_rows(input_csv)
# First pass to calculate value ranges if not provided
for col, config in filter_config.items():
if not config.get('range'):
min_val = None
max_val = None
with tqdm(total=total_rows, desc='Calculating value ranges', unit=' rows', ncols=100) as pbar:
for chunk in pd.read_csv(input_csv, chunksize=chunksize, usecols=[col]):
chunk_min, chunk_max = chunk[col].min(), chunk[col].max()
if min_val is None or chunk_min < min_val:
min_val = chunk_min
if max_val is None or chunk_max > max_val:
max_val = chunk_max
pbar.update(chunk.shape[0])
config['range'] = (min_val, max_val)
# Second pass to calculate scores and filter rows
temp_file = tempfile.NamedTemporaryFile(mode='w+', delete=False, newline='', encoding='utf-8')
header_written = False
rows_written = 0
with tqdm(total=total_rows, desc='Filtering rows', unit=' rows', ncols=100) as pbar:
for chunk in pd.read_csv(input_csv, chunksize=chunksize):
if score_breakdown:
chunk['score'], chunk['breakdown'] = zip(*chunk.apply(calculate_score, axis=1))
else:
chunk['score'] = chunk.apply(calculate_score, axis=1)
sorted_chunk = chunk.nlargest(row_limit - rows_written, 'score')
if not header_written:
sorted_chunk.to_csv(temp_file, index=False)
header_written = True
else:
sorted_chunk.to_csv(temp_file, index=False, header=False)
rows_written += len(sorted_chunk)
if rows_written >= row_limit:
break