Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

preprocess_data.py 5.5 KB

You have to be logged in to leave a comment. Sign In
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
  1. import pandas as pd
  2. import unicodedata
  3. from tqdm.auto import tqdm
  4. from hebrew_utils import strip_nikud, text_contains_nikud, text_contains_abg, ABG
  5. DATA_DIR = './data'
  6. def nikud_slice(text, patience=1):
  7. words = text.split()
  8. out = ''
  9. counter = 0
  10. on = False
  11. for w in words:
  12. if text_contains_nikud(w) or not text_contains_abg(w):
  13. on = True
  14. if len(out) > 0:
  15. out += ' '
  16. out += w
  17. elif on:
  18. counter += 1
  19. if counter <= patience:
  20. out += ' ' + w
  21. else:
  22. on = False
  23. counter = 0
  24. yield out
  25. out = ''
  26. if out != '':
  27. yield out
  28. def count_max_abg_in_row(text):
  29. out = 0
  30. counter = 0
  31. on = False
  32. for char in text:
  33. if char in ABG:
  34. on = True
  35. counter += 1
  36. else:
  37. out = max(out, counter)
  38. counter = 0
  39. return out
  40. def normalize(series):
  41. tqdm.pandas(desc='Normalizing unicode')
  42. return series.str.replace(r'\u05ba', '\u05b9', regex=True # "holam haser for vav" => holam
  43. ).progress_apply(lambda x: unicodedata.normalize('NFC', x)) # splits combining forms (e.g. bet+dagesh)
  44. def preprocess_male_haser():
  45. print('Preprocessing ktiv male data...')
  46. wiktionary_df = pd.read_csv(f'{DATA_DIR}/raw/he_wiktionary-male_haser.csv'
  47. ).drop(columns='haser')
  48. wikisource_df = pd.read_csv(f'{DATA_DIR}/raw/wikisource-haser_male.csv'
  49. ).drop(columns='title'
  50. ).rename(columns={'nikkud': 'nikud', 'plain': 'male'})
  51. wiktionary_df['source'] = 'wiktionary'
  52. wikisource_df['source'] = 'wikisource'
  53. df = pd.concat([wiktionary_df, wikisource_df]).fillna('')
  54. del wiktionary_df, wikisource_df
  55. df.nikud = normalize(df.nikud)
  56. df.male = normalize(df.male)
  57. df.nikud = df.nikud.str.replace(r'\{.*\}', '', regex=True
  58. ).str.replace(r'\(.*\)', '', regex=True
  59. ).str.replace(r'[\[\]]', '', regex=True
  60. ).str.strip()
  61. df.male = df.male.str.replace(r'[\[\]]', '', regex=True).str.strip()
  62. df = df[
  63. df.nikud.notna() &
  64. df.male.notna() &
  65. (df.nikud.str.split().str.len() == df.male.str.split().str.len()) &
  66. (df.male != df.nikud) &
  67. (~df.nikud.str.contains(r'|', regex=False)) &
  68. (~df.male.str.contains(r'|', regex=False))
  69. ]
  70. word_df = df.set_index('source').apply(lambda x: x.str.split().explode()).reset_index()
  71. stripped = word_df.nikud.apply(strip_nikud)
  72. word_df = word_df[
  73. ~(stripped.str.endswith('ו') ^ word_df.male.str.endswith('ו')) &
  74. ~(stripped.str.endswith('י') ^ word_df.male.str.endswith('י')) &
  75. ~(stripped.str.startswith('ו') ^ word_df.male.str.startswith('ו')) &
  76. ~(stripped.str.startswith('י') ^ word_df.male.str.startswith('י')) &
  77. (stripped.str.len() <= word_df.male.str.len())
  78. ]
  79. word_df.to_csv(f'{DATA_DIR}/processed/ktiv_male.csv', index=False)
  80. print('Done (ktiv male)')
  81. def preprocess_nikud_data(nikud_ratio_thresh=0.8, n_words_thresh=3, max_words=50, max_abg_in_row=3):
  82. print('Preprocessing nikud data...')
  83. by_series = pd.read_csv(f'{DATA_DIR}/raw/ben-yehuda.txt', header=None)[0]
  84. wp_series = pd.read_csv(f'{DATA_DIR}/raw/he_wp-nikud.txt', header=None)[0]
  85. df = pd.DataFrame({
  86. 'text': pd.concat([by_series, wp_series]),
  87. 'source': ['BY'] * by_series.shape[0] + ['WP'] * wp_series.shape[0]
  88. })
  89. del by_series
  90. del wp_series
  91. df.text = normalize(df.text)
  92. df = pd.DataFrame([
  93. {
  94. 'text': S,
  95. 'source': row.source
  96. }
  97. for row in tqdm(
  98. df.sample(df.shape[0]).itertuples(),
  99. # ^ random shuffle makes progress bar more accurate
  100. total=df.shape[0], desc='Slicing nikud')
  101. for S in nikud_slice(row.text)
  102. ])
  103. df.text = df.text.str.replace('\u200f', '').str.replace('\xa0', '').str.strip()
  104. tqdm.pandas(desc='Stripping nikud')
  105. stripped = df.text.progress_apply(strip_nikud)
  106. ratios = stripped.str.len() / df.text.str.len()
  107. n_words = df.text.str.split().str.len()
  108. mask = (ratios < nikud_ratio_thresh) & (n_words > n_words_thresh)
  109. def split_text(text):
  110. words = text.split(' ')
  111. out_lists = [[]]
  112. for w in words:
  113. if len(out_lists[-1]) >= max_words:
  114. out_lists.append([])
  115. out_lists[-1].append(w)
  116. return [
  117. ' '.join(L) for L in out_lists
  118. ]
  119. df = pd.DataFrame([
  120. {
  121. 'text': T,
  122. 'source': row.source
  123. }
  124. for row in tqdm(df[mask].itertuples(), total=mask.sum(), desc='Splitting large texts')
  125. for T in split_text(row.text)
  126. ])
  127. tqdm.pandas(desc='Filtering missing nikkud')
  128. n_abg_in_row = df.text.progress_apply(count_max_abg_in_row)
  129. df = df[n_abg_in_row <= max_abg_in_row].copy()
  130. def rm_last_no_nikud(text):
  131. last_word = text.split()[-1]
  132. if last_word != strip_nikud(last_word):
  133. return text
  134. return text[:-len(last_word)].strip()
  135. tqdm.pandas(desc='Removing final words missing nikud')
  136. df.text = df.text.progress_apply(rm_last_no_nikud)
  137. df = df[df.text != ''].copy()
  138. # replace "holam haser for vav" with normal holam
  139. df.text = df.text.str.replace(r'\u05ba', '\u05b9', regex=True)
  140. df.to_csv(f'{DATA_DIR}/processed/nikud.csv', index=False)
  141. print('Done (nikud)')
  142. if __name__ == '__main__':
  143. preprocess_male_haser()
  144. preprocess_nikud_data()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...