-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataTag_helper.py
1406 lines (1178 loc) · 53 KB
/
DataTag_helper.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
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: /lib/AIClerk_helper.py
# Project: suidice-text-detection
# Created Date: Monday, May 4th 2020, 3:06:41 pm
# Author: Allenyl([email protected]>)
# -----
# Last Modified: Friday, September 15th 2023, 2:57:01 pm
# Modified By: Allenyl([email protected])
# -----
# Copyright 2018 - 2020 Allenyl Copyright, Allenyl Company
# -----
# license:
# All shall be well and all shall be well and all manner of things shall be well.
# We're doomed!
# ------------------------------------
# HISTORY:
# Date By Comments
# ---------- --- ---------------------------------------------------------
###
## Non-ASCII output hangs execution in PyInstaller packaged app · Issue #520 · chriskiehl/Gooey
## https://github.com/chriskiehl/Gooey/issues/520
import codecs
import copy
import hashlib
import json
import os
import platform
import re
import sys
from collections import Counter, OrderedDict, defaultdict
from functools import reduce
from pathlib import Path
# from sklearn.utils import shuffle
import emoji
import numpy as np
import pandas as pd
import pdfplumber
from chardet.universaldetector import UniversalDetector
# from lib.AIClerk_helper import to_AI_clerk_batch_upload_json
from docx import Document
# import argparse
from gooey import Gooey, GooeyParser
from natsort import natsorted
from openpyxl.styles import Font
from sklearn.model_selection import StratifiedShuffleSplit
if sys.stdout.encoding != "UTF-8":
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict")
if sys.stderr.encoding != "UTF-8":
sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, "strict")
# use sqlite db to share data between gui and cli
# because gui will excute this file with cli args to finish its work,
# it needs a way to know what data is change in gui screen.
from sqlitedict import SqliteDict
MY_DB_FILE = "./my_db.sqlite"
# mydict = SqliteDict(MY_DB_FILE, autocommit=True)
# try:
# mydict["global_choies"]
# except KeyError:
# mydict["global_choies"] = []
# share args across different event callbacks
global_args = defaultdict(list)
def patch_gooey_gui_component(mydict):
"""Monkey patch gooey's gui components, like:
Dropdown, FileChooser, GooeyApplication,...etc.
To avoid `ImportError: libXxf86vm.so.1` while import,
we enclose patch code into a function,
and call it when we are going into GUI mode.
Returns:
[type]: [description]
"""
import wx
# from gooey.gui.lang.i18n import _
######
## [Feature request: Allow general callbacks for validation · Issue #293 · chriskiehl/Gooey]
## (https://github.com/chriskiehl/Gooey/issues/293)
# from gooey.gui.components.widgets.bases import TextContainer
# oldGetValue = TextContainer.getValue
#
# def newGetValue(self):
# result = oldGetValue(self)
# userValidator = self._options['validator']['callback']
# message = self._options['validator']['message']
# value = self.getWidgetValue()
# validates = userValidator(value)
# result['test'] = False
# result['error'] = 'test'
# return result
#
# TextContainer.getValue = newGetValue
######
# [Gooey/dropdown.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/dropdown.py)
from gooey.gui.components.widgets.dropdown import Dropdown
Dropdown_oldGetWidget = Dropdown.getWidget
# from gooey.gui import formatters
# def newFormatOutput(self, metadata, value):
# print("debug2")
# print("metadata", metadata)
# print("value", value)
# return formatters.dropdown(metadata, value)
# def newSetValue(self, value):
# ## +1 to offset the default placeholder value
# index = self._meta['choices'].index(value) + 1
# print("debug", self._meta['choices'])
# self.widget.SetSelection(index)
# def newGetWidgetValue(self):
# value = self.widget.GetValue()
# # filter out the extra default option that's
# # appended during creation
# print(value)
# if value == _('select_option'):
# return None
# return value
def Dropdown_newGetWidget(self, parent, *args, **options):
widget = Dropdown_oldGetWidget(self, parent, *args, **options)
# [wxPython ComboBox & Choice类 - WxPython教程™]
# (https://www.yiibai.com/wxpython/wx_combobox_choice_class.html)
# [wx.ComboBox — wxPython Phoenix 4.1.1a1 documentation]
# (https://wxpython.org/Phoenix/docs/html/wx.ComboBox.html)
widget.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.OnCombo)
return widget
def Dropdown_newOnCombo(self, event):
def get_choices(input_file):
try:
# specify engine use 'openpyxl' to avoid not found xlrd error
new_choices = list(
pd.read_excel(
input_file,
sheet_name="document_label",
index_col=0,
nrows=0,
engine="openpyxl",
)
)
message = ""
self.setErrorString(message)
self.showErrorString(False)
# force refresh parent screen
# python - Update/Refresh Dynamically–Created WxPython Widgets - Stack Overflow
# https://stackoverflow.com/questions/10368948/update-refresh-dynamically-created-wxpython-widgets
self.GetParent().Layout()
except Exception as e:
# message = "No sheet named 'document_label'"
# show actual exception message for easier debug
message = repr(e)
# print(message)
self.setErrorString(message)
self.showErrorString(True)
# force refresh parent screen
# python - Update/Refresh Dynamically–Created WxPython Widgets - Stack Overflow
# https://stackoverflow.com/questions/10368948/update-refresh-dynamically-created-wxpython-widgets
self.GetParent().Layout()
new_choices = []
return new_choices
current_input_file = global_args["input_file"]
try:
self.previous_input_file
except Exception:
self.previous_input_file = ""
if self.previous_input_file != current_input_file:
self.new_choices = get_choices(current_input_file)
self.previous_input_file = current_input_file
# save self.new_choices into sqlite db for later access
mydict["global_choies"] = self.new_choices
# [python - Dynamically change the choices in a wx.ComboBox() - Stack Overflow]
# (https://stackoverflow.com/questions/682923/dynamically-change-the-choices-in-a-wx-combobox)
self.setOptions(self.new_choices)
Dropdown.getWidget = Dropdown_newGetWidget
Dropdown.OnCombo = Dropdown_newOnCombo
# Dropdown.setValue = newSetValue
# Dropdown.getWidgetValue = newGetWidgetValue
# Dropdown.formatOutput = newFormatOutput
# [Gooey/choosers.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/choosers.py)
# [Gooey/chooser.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/core/chooser.py#L65)
# [Gooey/chooser.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/core/chooser.py#L13)
# [Gooey/text_input.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/core/text_input.py#L7)
# [Gooey/bases.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/components/widgets/bases.py#L170)
from gooey.gui.components.widgets.core.chooser import FileChooser
FileChooser_old_init = FileChooser.__init__
## monkey patch __init__
def FileChooser_new_init(self, parent, *args, **kwargs):
FileChooser_old_init(self, parent, *args, **kwargs)
# bind event wx.EVT_TEXT to trigger self.OnFileChooser when text change
# [wx.TextCtrl — wxPython Phoenix 4.1.1a1 documentation]
# (https://wxpython.org/Phoenix/docs/html/wx.TextCtrl.html)
# [wxPython - TextCtrl Class - Tutorialspoint]
# (https://www.tutorialspoint.com/wxpython/wx_textctrl_class.htm)
self.widget.Bind(wx.EVT_TEXT, self.OnFileChooser)
## monkey patch OnFileChooser
def FileChooser_newOnFileChooser(self, event):
# read text area value to global_args
global_args["input_file"] = self.widget.getValue()
# print(global_args)
FileChooser.__init__ = FileChooser_new_init
FileChooser.OnFileChooser = FileChooser_newOnFileChooser
# [Gooey/application.py at 8c88980e12a968430df5cfd0779fab37db287680 · chriskiehl/Gooey]
# (https://github.com/chriskiehl/Gooey/blob/8c88980e12a968430df5cfd0779fab37db287680/gooey/gui/containers/application.py#L29)
from gooey.gui.containers.application import GooeyApplication
## monkey patch onClose
def newOnClose(self, *args, **kwargs):
"""Cleanup the top level WxFrame and shutdown the process"""
self.Destroy()
# print("onClose")
# remove db file when close
# [sqlite - Python PermissionError: [WinError 32] The process cannot access the file..... but my file is closed - Stack Overflow]
# (https://stackoverflow.com/questions/59482990/python-permissionerror-winerror-32-the-process-cannot-access-the-file-bu)
mydict.close()
os.remove(MY_DB_FILE)
sys.exit()
GooeyApplication.onClose = newOnClose
# navigation option must be upper cased 'TABBED', instead of 'Tabbed'
@Gooey(
program_name="DataTag Helper (標註轉檔小幫手) v0.9.0",
navigation="TABBED",
tabbed_groups=False,
default_size=(525, 670),
)
def parse_args(mydict, args=None):
if args is None:
args = sys.argv[1:]
# parser = argparse.ArgumentParser()
parser = GooeyParser()
subs = parser.add_subparsers(help="commands", dest="command")
### for original file
sub_parser1 = subs.add_parser("original", prog="未標註原始檔案", help="未標註原始檔案")
sub_parser1_1 = sub_parser1.add_argument_group(
"input file(s)",
"choose unlabeled file(s)",
gooey_options={"show_border": True, "show_underline": True, "columns": 1},
)
# add default selection option
# https://github.com/chriskiehl/Gooey/issues/590#issue-650474511
mutex_sub_parser1 = sub_parser1_1.add_mutually_exclusive_group(
required=True,
gooey_options={
"show_border": True,
"show_underline": True,
"columns": 1,
"initial_selection": 0,
},
)
#### input txt files
mutex_sub_parser1.add_argument(
"-d",
"--input-dir",
help="dir that contains input files(.txt)",
dest="input_dir",
default=None,
widget="DirChooser",
)
#### input excel files
mutex_sub_parser1.add_argument(
"-i",
"--input_file",
help="input filename (excel)",
dest="input_file",
default=None,
widget="FileChooser",
)
sub_parser1_2 = sub_parser1.add_argument_group(
"options",
"only works for input excel file",
gooey_options={"show_border": True, "show_underline": True, "columns": 2},
)
sub_parser1_2.add_argument(
"--emojilize",
help="turn text to emoji (uncheck to reverse)",
dest="emojilize",
action="store_true",
)
sub_parser1_2.set_defaults(emojilize=False)
sub_parser1_2.add_argument(
"--to-excel",
help="output excel file (uncheck to output json)",
dest="to_excel",
action="store_true",
)
sub_parser1_2.set_defaults(to_excel=False)
### for labeled file
sub_parser2 = subs.add_parser("labeled", prog="已標註檔案", help="已標註檔案")
sub_parser2 = sub_parser2.add_argument_group(
"labeled file to excel",
"choose the labeled file which want to be convert to Excel file(s)",
gooey_options={"show_border": True, "show_underline": True, "columns": 1},
)
sub_parser2.add_argument(
"-i",
"--input_file",
help="input filename (json)",
dest="input_file",
default=None,
widget="FileChooser",
)
### for labeled file want to second upload
sub_parser2_1 = subs.add_parser("second_upload", prog="標註二次上傳", help="已標註檔案二次上傳")
sub_parser2_1 = sub_parser2_1.add_argument_group(
"second upload",
"choose the labeled file which want to be second upload (for double check purpose)",
gooey_options={"show_border": True, "show_underline": True, "columns": 1},
)
sub_parser2_1.add_argument(
"-i",
"--input_file",
help="input filename (json)",
dest="input_file",
default=None,
widget="FileChooser",
)
### for second labeled file convert
sub_parser2_2 = subs.add_parser("second_labeled", prog="二次標註轉換", help="二次標註轉換")
sub_parser2_2 = sub_parser2_2.add_argument_group(
"second labeled convertion",
"choose the first and second labeled files which wants to be converted to final json",
gooey_options={"show_border": True, "show_underline": True, "columns": 1},
)
sub_parser2_2.add_argument(
"-i1",
"--input_file_1",
nargs="*",
help="choose multiple files (first labeled json)",
dest="input_file_1",
default=None,
widget="MultiFileChooser",
)
sub_parser2_2.add_argument(
"-i2",
"--input_file_2",
help="input filename (second labeled json)",
dest="input_file_2",
default=None,
widget="FileChooser",
)
### concat files
sub_parser3 = subs.add_parser("concat", prog="合併檔案", help="合併檔案")
sub_parser3 = sub_parser3.add_argument_group("")
sub_parser3.add_argument(
"-i",
"--input_file",
help="input filenames (excel)",
dest="input_files",
default=None,
widget="MultiFileChooser",
)
### for random tran/test split
sub_parser4 = subs.add_parser("split", prog="分割檔案", help="分割檔案")
sub_parser4 = sub_parser4.add_argument_group("")
sub_parser4.add_argument(
"-i",
"--input_file",
help="input filename (excel)",
dest="input_file",
default=None,
widget="FileChooser",
)
sub_parser4.add_argument(
"-y",
"--y_column",
help="y column",
dest="y_col",
default=None,
widget="Dropdown",
choices=mydict["global_choies"],
)
# parser.add_argument('--type', '-t', choices=getLob())
# args, unknown = parser.parse_known_args()
args = parser.parse_args(args)
return args
def to_AI_clerk_batch_upload_json(dataframe, save_path):
def to_article_dict(x):
return {
"Title": x.Title.tolist()[0],
"Content": x.Content.tolist()[0],
"Author": x.Author.tolist()[0],
"Time": x.Time.tolist()[0],
}
print("number of entries: {}".format(len(dataframe)))
dup_id = dataframe.duplicated(["TextID"], keep=False)
print("duplicated entries: {}".format(len(dataframe[dup_id])))
print(dataframe[dup_id])
samples_dict = dataframe.groupby(["TextID"]).apply(to_article_dict).to_dict()
print("keep first, drop duplicated!")
content_length_lower_threshold = 100
long_id = dataframe["Content"].apply(
lambda x: True if len(x) < content_length_lower_threshold else False
)
print(
"number of entries which Content shorter then {} words: {}".format(
content_length_lower_threshold, len(dataframe[long_id])
)
)
print("no drop, just show information.")
sample_articles = defaultdict(defaultdict)
sample_articles["Articles"].update(samples_dict)
print("number of remaining entries: {}".format(len(sample_articles["Articles"])))
# output articles.json
with open(save_path, "w", encoding="utf-8") as outfile:
json.dump(sample_articles, outfile, ensure_ascii=False, indent=4)
# read ouputed samples to test
# with open('./suicide_text_sample.json', 'r') as outfile:
# temp_dict = json.load(outfile)
# try:
# display(temp_dict)
# except:
# pass
def get_TextID(df):
title_hsah = hashlib.md5(df["Title"].encode("utf-8")).hexdigest()[:10]
content_hash = hashlib.md5(df["Content"].encode("utf-8")).hexdigest()[:10]
return title_hsah + "-" + content_hash
# ### 清理資料格式
def clean_data(df):
empty_entries = df["Content"].isnull()
print("number of empty content entries: {}".format(len(df[empty_entries])))
df_cleaned = df[~empty_entries].copy()
if len(df[empty_entries]):
print("drop empty!")
drop_columns = df_cleaned.columns.str.contains("Unnamed")
# print(any(df_cleaned.columns.str.contains("^ID$")))
# if not any(df_cleaned.columns.str.contains("^TextID$")):
leave_columns = df_cleaned.columns[~drop_columns].tolist()
# df_cleaned['ID'] = df_cleaned[["Content"]].apply(lambda x: hashlib.md5(x[0].encode('utf-8')).hexdigest()[:10],axis=1)
df_cleaned = df_cleaned[leave_columns]
# print(df_cleaned.head())
df_cleaned = df_cleaned.sort_values("TextID").reset_index(drop=True)
try:
df_cleaned["Author"] = df_cleaned.apply(
lambda x: x.Poster + "/" + x.Gender, axis=1
)
except:
try:
df_cleaned["Author"] = df_cleaned["Poster"]
except:
df_cleaned["Author"] = None
try:
df_cleaned["Date"] = df_cleaned["Date"].apply(lambda x: x.strftime("%Y-%m-%d"))
df_cleaned["Time"] = df_cleaned["Time"].apply(lambda x: x.strftime("%H:%M:%S"))
except:
pass
try:
df_cleaned["Time"] = df_cleaned.apply(
lambda x: str(x.Date) + "/" + str(x.Time), axis=1
)
except:
try:
df_cleaned["Time"] = df_cleaned.apply(lambda x: str(x.Date), axis=1)
except:
df_cleaned["Time"] = None
return df_cleaned
def emoji_to_text(df):
df_deemojilized = df.copy()
## 轉換 emoji 格式成 :emoji:
## python - How to replace emoji to word in a text? - Stack Overflow
## https://stackoverflow.com/questions/57580288/how-to-replace-emoji-to-word-in-a-text
df_deemojilized["Content"] = df[["Content"]].apply(
lambda x: emoji.demojize(x[0]), axis=1
)
df_deemojilized["Title"] = df[["Title"]].apply(
lambda x: emoji.demojize(x[0]), axis=1
)
return df_deemojilized
def text_to_emoji(df):
df_emojilized = df.copy()
## 將:emoji: 換回 unicode character
df_emojilized["Content"] = df[["Content"]].apply(
lambda x: emoji.emojize(x[0]), axis=1
)
df_emojilized["Title"] = df[["Title"]].apply(lambda x: emoji.emojize(x[0]), axis=1)
return df_emojilized
def reorder_column(columns_list, selected_column_name, insert_before_column_name=None):
"""
columns_list: the list of columns to be reordered
selected_column_name: the column name which wants to be inserted to the point before column `insert_before_column_name`
insert_before_column_name: the column name which act as fix point relative to the `selected_column_name`
"""
columns_list = copy.copy(columns_list)
selected_index = columns_list.index(selected_column_name)
selected_item = columns_list.pop(selected_index)
# drop selected column when insert_before_column_name is infinity
if insert_before_column_name is np.inf:
return columns_list
# print(insert_before_column_name is float('inf'))
# insert to the end of column list when insert_before_column_name is None
if insert_before_column_name is None:
insert_point_index = len(columns_list)
else:
insert_point_index = columns_list.index(insert_before_column_name)
columns_list.insert(insert_point_index, selected_item)
return columns_list
def extract_dict(df, id_column_list, dict_column):
df_tmp = df[id_column_list + [dict_column]].set_index(id_column_list)
df_tmp = pd.DataFrame(
df_tmp.apply(lambda x: {"empty": "nan"} if len(x[0]) == 0 else x[0], axis=1)
)
df_tmp = df_tmp.apply(
lambda x: pd.DataFrame.from_dict(x[0], orient="index").stack(), axis=1
)
df_tmp = df_tmp.reset_index(level=id_column_list)
return df_tmp
# these illegal characters is represented by octal escape
# [Regular Expressions Reference: Special and Non-Printable Characters]
# (https://www.regular-expressions.info/refcharacters.html)
# [(1条消息)openpyxl.utils.exceptions.IllegalCharacterError 错误原因分析及解决办法_村中少年的专栏-CSDN博客]
# (https://blog.csdn.net/javajiawei/article/details/97147219)
ILLEGAL_CHARACTERS_RE = re.compile(r"[\000-\010]|[\013-\014]|[\016-\037]")
# [openpyxl.utils.escape — openpyxl 3.0.5 documentation]
# (https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/utils/escape.html)
ESCAPED_REGEX = re.compile("_x([0-9A-Fa-f]{4})_")
def unescape_OOXML(string):
def remove_character(char):
print("removed illegal char!")
return r""
def _sub(match):
"""
Callback to unescape chars
"""
char = chr(int(match.group(1), 16))
# [Convert regular Python string to raw string - Stack Overflow]
# (https://stackoverflow.com/questions/4415259/convert-regular-python-string-to-raw-string)
# [python - Pythonic way to do base conversion - Stack Overflow]
# (https://stackoverflow.com/questions/28824874/pythonic-way-to-do-base-conversion)
print(
"found char {}, which int in octal number is: {}".format(
char.encode("unicode_escape"), oct(ord(char))
)
)
# remove carriage return
if char == "\r":
print("removed!")
char = ""
else:
# remove illegal characters
char = ILLEGAL_CHARACTERS_RE.sub(remove_character, char)
return char
string = ESCAPED_REGEX.sub(_sub, string)
return string
## [pandas - How to remove illegal characters so a dataframe can write to Excel - Stack Overflow]
## (https://stackoverflow.com/questions/42306755/how-to-remove-illegal-characters-so-a-dataframe-can-write-to-excel)
def remove_illegal_characters(dataframe):
# dataframe = dataframe.applymap(lambda x: x.encode('unicode_escape').decode('utf-8') if isinstance(x, str) else x)
dataframe = dataframe.applymap(
lambda x: ILLEGAL_CHARACTERS_RE.sub(r"", x) if isinstance(x, str) else x
)
return dataframe
def to_excel_AI_clerk_labeled_data(dataframe, save_path):
## unescape OOXML string
dataframe = dataframe.applymap(
lambda x: unescape_OOXML(x) if isinstance(x, str) else x
)
## remove illegal characters
dataframe = remove_illegal_characters(dataframe)
df1 = (
dataframe.T.sort_values(["TextID", "Annotator"])
.rename_axis("SerialID")
.reset_index()
)
df1 = df1[sorted(df1.columns)]
columns_list = list(df1.columns)
print(columns_list)
columns_list = reorder_column(columns_list, "TextID", "Annotator")
columns_list = reorder_column(columns_list, "SerialID", "TextID")
columns_list = reorder_column(columns_list, "Title", "Content")
columns_list = reorder_column(columns_list, "Author", "Title")
columns_list = reorder_column(columns_list, "TextTime", "Comment")
print(columns_list)
df2 = df1[columns_list]
def extract_dict_of_list(dataframe, column_name):
df_dict_of_list = extract_dict(dataframe, ["TextID", "Annotator"], column_name)
## reduce multi-selection option into string
def multi_selection_to_string(option_columns):
# print(option_columns)
option_columns_list = list(filter(lambda y: pd.notnull(y), option_columns))
# check if option_columns_list is empty or ['']
if len(option_columns_list) == 0:
result = np.nan
elif len(option_columns_list) == 1 and option_columns_list[0] == "":
result = np.nan
else:
result = reduce(lambda a, b: a + ", " + b, option_columns_list)
if result == "":
# print(list(option_columns))
# print(len(option_columns_list))
result = np.nan
return result
### use ordered set to keep columns order
od = OrderedDict(df_dict_of_list.columns.to_flat_index())
option_columns_list = list(od.keys())
df_dict_of_list_tmp = pd.DataFrame(columns=option_columns_list)
df_dict_of_list_tmp["TextID"] = df_dict_of_list["TextID"]
df_dict_of_list_tmp["Annotator"] = df_dict_of_list["Annotator"]
option_columns_list.remove("TextID")
option_columns_list.remove("Annotator")
### flatten all option columns
for option_column in option_columns_list:
df_dict_of_list_tmp[option_column] = df_dict_of_list[option_column].apply(
lambda x: multi_selection_to_string(x), axis=1
)
df_dict_of_list = pd.merge(
dataframe[["TextID", "Annotator"]],
df_dict_of_list_tmp,
how="left",
on=["TextID", "Annotator"],
)
return df_dict_of_list, option_columns_list
########### extract document label #############
df_document_label, document_label_option_columns_list = extract_dict_of_list(
df2, "Summary"
)
########### extract ArticleTag #############
df_article_tag = None
try:
df_article_tag, _ = extract_dict_of_list(df2, "ArticleTag")
# print(df_article_tag)
except Exception as e:
print(str(e))
pass
########## create doc label compare view ##########
df_doc_label_cmp = pd.pivot_table(
df_document_label,
values=document_label_option_columns_list,
index=["TextID"],
columns=["Annotator"],
aggfunc=lambda x: x.iloc[0],
)
df_doc_label_cmp = df_doc_label_cmp.reset_index()
########## extract sentence label ############
df_sentence_label_tmp = extract_dict(df2, ["TextID", "Annotator"], "TermTab")
sentence_label_index_dict = OrderedDict(
df_sentence_label_tmp.columns.to_flat_index()
)
sent_label_column_list = list(sentence_label_index_dict.keys())
# print(sent_label_column_list)
sent_label_column_list.remove("TextID")
sent_label_column_list.remove("Annotator")
## drop unused level of multi index to avoid KeyError
df_sentence_label_tmp = df_sentence_label_tmp.droplevel(1, axis=1)
df_sentence_label_tmp = df_sentence_label_tmp.melt(
id_vars=["TextID", "Annotator"],
value_vars=sent_label_column_list,
var_name="Sent_Label",
value_name="Sentence",
)
df_sentence_label_tmp = df_sentence_label_tmp.dropna()
df_sentence_label_tmp["Sent_Label"] = df_sentence_label_tmp["Sent_Label"].apply(
lambda x: x.split("_")[0]
)
df_sentence_label_tmp.reset_index(drop=True, inplace=True)
df_sentence_label = pd.merge(
df_document_label, df_sentence_label_tmp, how="left", on=["TextID", "Annotator"]
)
df_sentence_label = df_sentence_label.sort_values(
["TextID", "Annotator", "Sent_Label"]
)
######### create sent label cmp long view ########
# this will group sentence by 'TextID', 'Annotator' and 'Sent_Label'
df_sentence_sector = df_sentence_label_tmp.groupby(
["TextID", "Annotator", "Sent_Label"]
)
# because there may be many sentences belong to one Sent_Label,
# when arragate, save these sentence into a list
df_sent_label_cmp_long_tmp = df_sentence_sector.agg(lambda x: [y for y in x])
# this will separate each sentence into columns,
# so if there are 21 sentence, column's name will be a list of 0-20
df_sent_label_cmp_long_tmp = df_sent_label_cmp_long_tmp["Sentence"].apply(
lambda x: pd.Series(x)
)
# add new column level: Sentence
column_level_list = [["Sentence"], df_sent_label_cmp_long_tmp.columns]
df_sent_label_cmp_long_tmp.columns = pd.MultiIndex.from_product(
column_level_list, names=["", "Sent_num"]
)
# stack 'Sent_num' column as row index
df_sent_label_cmp_long_tmp = df_sent_label_cmp_long_tmp.stack()
# reset_index will turn all row index into columns
df_sent_label_cmp_long_tmp = df_sent_label_cmp_long_tmp.reset_index()
# set multilevel index with this order: 'TextID', 'Annotator', 'Sent_Label', 'Sent_num'
df_sent_label_cmp_long_tmp = df_sent_label_cmp_long_tmp.set_index(
["TextID", "Annotator", "Sent_Label", "Sent_num"]
)
def merge(x, y):
if isinstance(x, list):
new_x = x + y
else:
new_x = "error"
return new_x
# use 'TextID', 'Sent_Label', 'Sent_num' as index,
# and turn 'Annotator''s value into columns, eg.
# if there were four possible values of Annotator: A,B,C,D
# then use A,B,C,B as new column names, pivot under value column 'Sentence'
# in case there are multiple items with same index, aggfunc will be used.
# it will pass a pd.Series object into aggfunc,
# we cae use reduce to return sum over the series,
# if each item in series is a list object,
# we can define a merge function to sum these list up into one list.
df_sent_label_cmp_long = pd.pivot_table(
df_sent_label_cmp_long_tmp,
values=["Sentence"],
index=["TextID", "Sent_Label", "Sent_num"],
columns=["Annotator"],
aggfunc=lambda x: reduce(merge, x),
)
# add additional level in the multiindex: 'Sent'
# for sent_doc_cmp use
col_index_names = list(df_sent_label_cmp_long.columns.names)
df_sent_label_cmp_long.columns = pd.MultiIndex.from_tuples(
map(lambda x: (x[0], "Sent", x[1]), df_sent_label_cmp_long.columns),
names=[col_index_names[0], "", col_index_names[1]],
)
######### create sentence label wide view ##########
df_sentence_label_wide = df_sent_label_cmp_long.unstack().unstack()
df_sentence_label_wide.columns = df_sentence_label_wide.columns.swaplevel(3, 4)
df_sentence_label_wide.sort_index(axis=1, level=3, inplace=True)
df_sentence_label_wide.columns = pd.MultiIndex.from_tuples(
map(
lambda x: (x[2], str(x[3]) + "_" + "{:0>2d}".format(x[4])),
df_sentence_label_wide.columns,
)
)
df_sentence_label_wide = df_sentence_label_wide.stack(level=0)
df_sentence_label_wide.index = df_sentence_label_wide.index.rename(
["TextID", "Annotator"]
)
df_sentence_label_wide = df_sentence_label_wide.reset_index()
df_sentence_label_wide = pd.merge(
df_document_label,
df_sentence_label_wide,
how="left",
on=["TextID", "Annotator"],
)
empty_cols_exclude_first = df_sentence_label_wide.columns[
df_sentence_label_wide.columns.str.contains("empty_(?:[0][1-9]|[1-9][0-9])")
]
df_sentence_label_wide = df_sentence_label_wide.drop(
empty_cols_exclude_first, axis=1
)
######### create sent label cmp wide views ##########
df_sent_label_cmp_wide = df_sent_label_cmp_long.unstack()
df_sent_label_cmp_wide.columns = df_sent_label_cmp_wide.columns.swaplevel(2, 3)
df_sent_label_cmp_wide.sort_index(axis=1, level=2, inplace=True)
######## create sent_doc_cmp views #########
df_doc_tmp = df_doc_label_cmp.set_index("TextID")
df_doc_tmp = pd.concat({"Doc_Label": df_doc_tmp}, names=["label_kind"], axis=1)
df_sent_tmp = df_sent_label_cmp_long.reset_index()
# to prevent warning: PerformanceWarning: dropping on a non-lexsorted multi-index without a level parameter may impact performance.
# need to sort multi-index
# see: [python - What exactly is the lexsort_depth of a multi-index Dataframe? - Stack Overflow](https://stackoverflow.com/questions/27116739/what-exactly-is-the-lexsort-depth-of-a-multi-index-dataframe)
df_sent_tmp.sort_index(axis=1, level=0, inplace=True)
df_sent_doc_cmp_tmp = pd.merge(df_doc_tmp, df_sent_tmp, how="left", on=["TextID"])
df_sent_doc_cmp_tmp.columns = df_sent_doc_cmp_tmp.columns.swaplevel(1, 2)
df_sent_doc_cmp_tmp.columns = df_sent_doc_cmp_tmp.columns.swaplevel(0, 1)
df_sent_doc_cmp_tmp.sort_index(axis=1, level=0, inplace=True)
sent_doc_cols = list(df_sent_doc_cmp_tmp.columns)
new_sent_doc_cols = reorder_column(
sent_doc_cols, ("", "TextID", ""), ("", "Sent_Label", "")
)
df_sent_doc_cmp = df_sent_doc_cmp_tmp[new_sent_doc_cols]
df_sent_doc_cmp = df_sent_doc_cmp.set_index(
[("", "TextID", ""), ("", "Sent_Label", ""), ("", "Sent_num", "")]
)
df_sent_doc_cmp.index = df_sent_doc_cmp.index.rename(
["TextID", "Sent_Label", "Sent_num"]
)
########## extract content ##########
drop_columns_list = reorder_column(columns_list, "Summary", np.inf)
drop_columns_list = reorder_column(drop_columns_list, "TermTab", np.inf)
if df_article_tag is not None:
drop_columns_list = reorder_column(drop_columns_list, "ArticleTag", np.inf)
print(drop_columns_list)
## explicit copy to avoid SettingWithCopyWarning warning
df_content = df2[drop_columns_list].copy()
## remove tags in content
df_content["Content(remove_tag)"] = df_content["Content"].apply(
lambda x: re.sub(r"(<(/)?*(.+?)_\d{1,2}*>)", "", x)
)
# write to excel
with pd.ExcelWriter(
save_path, options={"strings_to_urls": False}, engine="openpyxl"
) as writer:
df_sent_doc_cmp.to_excel(writer, sheet_name="sent_doc_cmp", index=True)
df_doc_label_cmp.to_excel(writer, sheet_name="doc_label_cmp", index=True)
df_sent_label_cmp_long.to_excel(
writer, sheet_name="sent_label_cmp(long)", index=True
)
df_sent_label_cmp_wide.to_excel(
writer, sheet_name="sent_label_cmp(wide)", index=True
)
df_sentence_label_wide.to_excel(
writer, sheet_name="sentence_label(wide)", index=False
)
df_content.to_excel(writer, sheet_name="contents", index=False)
df_document_label.to_excel(writer, sheet_name="document_label", index=False)
df_sentence_label.to_excel(writer, sheet_name="sentence_label", index=False)
if df_article_tag is not None:
df_article_tag.to_excel(writer, sheet_name="article_tag", index=False)
for ws in writer.sheets.values():
"""
fix column headers and row headers no font name issue
need to use engine='openpyxl'
"""
# row_level = df_sent_doc_cmp.index.nlevels
# print(row_level)
for row in ws.iter_rows(min_row=1, max_row=1):
"""
walk through each cell of first row to assign font name
"""
for cell in row:
# print(cell)
font_params = cell.font.__dict__
if font_params["name"] is None:
font_params["name"] = "Calibri"
cell.font = Font(**font_params)
return (
df_content,
df_document_label,
df_sentence_label,
df_sentence_label_wide,
df_doc_label_cmp,
df_sent_label_cmp_long,
df_sent_label_cmp_wide,
df_sent_doc_cmp,
df_article_tag,
)
def split_train_test_to_target(X, y, target):
sss = StratifiedShuffleSplit(n_splits=5, test_size=0.2, random_state=1234)
for index, (train_index, test_index) in enumerate(sss.split(X, y)):
# print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
print("split {}".format(index))
print("train:", Counter(y_train))
print("test:", Counter(y_test))
df_train = pd.DataFrame({"TextID": X_train}).reset_index(drop=True)
df_test = pd.DataFrame({"TextID": X_test}).reset_index(drop=True)
df_target_train = pd.merge(df_train, target, how="left", on=["TextID"])
df_target_test = pd.merge(df_test, target, how="left", on=["TextID"])