cools commited on
Commit
e9dfae8
·
1 Parent(s): b201bc0

Removed para-identifier

Browse files
Files changed (1) hide show
  1. ImageProcessor.py +24 -80
ImageProcessor.py CHANGED
@@ -5,6 +5,7 @@ import os
5
  import pandas as pd
6
  import pytesseract
7
  import warnings
 
8
 
9
  def pdf2png(folderpath):
10
  doc = fitz.open(folderpath + '/opinion.pdf')
@@ -16,23 +17,27 @@ def pdf2png(folderpath):
16
 
17
  def is_leftmost(image, x, y_top, y_bot):
18
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
19
- blur = cv2.GaussianBlur(gray, (7,7), 0)
20
  thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
21
  left_portion = thresh[int((y_top+y_bot)/2), :x]
22
  return np.sum(left_portion) == 0
23
 
24
- def get_indents(filename, body_bbox, page):
25
- indented_lines = []
26
  image = cv2.imread(filename)
27
  body_rect = fitz.Rect(body_bbox)
28
  pg_dict = page.get_text('dict', clip=body_rect)
29
  all_lines = [(int(line['bbox'][0]), int(line['bbox'][1]), int(line['bbox'][2]), int(line['bbox'][3]), line)for block in pg_dict['blocks'] for line in block['lines']]
30
- body_text = page.get_text("text", clip=body_rect).strip()
31
- baseline = min([l[0] for l in all_lines])
32
- indented_inds = [i for (i,l) in enumerate(all_lines) if (l[0]-baseline > 9 and is_leftmost(image, l[0]-12, l[1], l[3]))]# and l[0]-baseline < 30
33
- for i in indented_inds:
34
- indented_lines.append((i, all_lines[i][0], all_lines[i][1], all_lines[i][2], all_lines[i][3]))
35
- return indented_lines
 
 
 
 
36
 
37
  def get_footnote_bbox(filename):
38
  footnotes_bbox = (None, None, None, None)
@@ -125,7 +130,7 @@ def get_page_elements(filename, page):
125
  body_bbox = (page_bbox[0], header_bbox[3], page_bbox[2], fn_bbox[1])
126
  else:
127
  body_bbox = (page_bbox[0], header_bbox[3], page_bbox[2], page_bbox[3])
128
- indent_lines = get_indents(filename, body_bbox, page)
129
 
130
  image = cv2.imread(filename)
131
  cv2.rectangle(image, (page_bbox[0], page_bbox[1]), (page_bbox[2], page_bbox[3]), (0, 0, 0), 4)
@@ -134,76 +139,17 @@ def get_page_elements(filename, page):
134
  if fn_bbox[0] is not None:
135
  cv2.rectangle(image, (fn_bbox[0], fn_bbox[1]), (fn_bbox[2], fn_bbox[3]), (0, 0, 255), 2)
136
  if case_separator_bbox[0] is not None:
137
- cv2.rectangle(image, (case_separator_bbox[0], case_separator_bbox[1]),
138
- (case_separator_bbox[2], case_separator_bbox[3]), (255, 0, 255), 2)
139
- for (i, il) in enumerate(indent_lines):
140
- cv2.circle(image, (il[1]-15, int(0.5*(il[2] + il[4]))), radius=1, color=(240, 32, 160), thickness=2)
141
 
142
- return page_bbox, header_bbox, fn_bbox, body_bbox, case_separator_bbox, indent_lines, image
143
-
144
- def paragraphs(folderpath):
145
- doc = fitz.open(folderpath + '/opinion.pdf')
146
- df = pd.read_csv(folderpath + '/data.csv')
147
- df = df.replace({np.nan: None})
148
- nl_inds = df['Indent Lines'].tolist()
149
- nl_inds = [eval(nli) for nli in nl_inds]
150
- nl_indents = [nli[1] for page_nli in nl_inds for nli in page_nli]
151
- nl_inds = [(i, nli[0]) for (i, page_nli) in zip(df['Pg Ind'].tolist(), nl_inds) for nli in page_nli]
152
- paras = [([], 0, 0, 0)] # Text, indent amount, start pg ind, end pg ind
153
- para_lines = []
154
- for (i, page) in enumerate(doc):
155
- ind = df.index[df['Pg Ind'] == i].tolist()[0]
156
- body_bbox = [df.iloc[ind]['Body X1'], df.iloc[ind]['Body Y1'], df.iloc[ind]['Body X2'], df.iloc[ind]['Body Y2']]
157
- case_separator = df.iloc[ind]['Case Separator Y']
158
- if case_separator is not None:
159
- body_bbox[-1] = case_separator
160
- body_rect = fitz.Rect(body_bbox)
161
- pg_dict = page.get_text('dict', clip=body_rect)
162
- all_lines = [get_line_text(line) for block in pg_dict['blocks'] for line in block['lines']]
163
- for (j, line) in enumerate(all_lines):
164
- if line == "":
165
- continue
166
- if (i, j) in nl_inds:
167
- indent_amt = nl_indents[nl_inds.index((i, j))] # This is for the starting one
168
- paras.append(([], indent_amt, i, i))
169
- paras[-1] = list(paras[-1])
170
- paras[-1][0].append(line.strip())
171
- paras[-1][-1] = i # Update the page ind
172
- paras[-1] = tuple(paras[-1])
173
- paras = block_quotes(paras)
174
- paras_df = pd.DataFrame(data=paras, index=None, columns=['Text', 'Indent Amount', 'Start Pg Ind', 'End Pg Ind'])
175
- return paras_df
176
 
177
  def get_line_text(line):
178
  words = []
179
- for s in line['spans']:
180
- text = s['text'].strip()
181
- if text != "":
182
- words.append(text)
183
- words = " ".join(words)
184
  return words
185
 
186
- def block_quotes(paras):
187
- modified_paras = []
188
- start_para, end_para, end_quote_passed = None, None, None
189
- for (i, (para, ind_amt, start_pg_ind, end_pg_ind)) in enumerate(paras):
190
- if i == len(paras) - 1:
191
- modified_paras.append((para, ind_amt, start_pg_ind, end_pg_ind))
192
- break
193
- if len(para) == 1 and "“" == para[0][0] and start_para is None:
194
- start_para = i
195
- if len(para) == 1 and "”" == para[0][-1] and start_para is not None:
196
- end_quote_passed = True
197
- if len(para) == 1 and (
198
- paras[i + 1][1] - ind_amt) < -5 and end_para is None and start_para is not None and end_quote_passed:
199
- end_para = i
200
- if start_para is not None and end_para is not None:
201
- para = [p[0][0] for p in paras[start_para:end_para + 1]]
202
- start_para, end_para, end_quote_passed = None, None, False
203
- if start_para is None and end_para is None:
204
- modified_paras.append((para, ind_amt, start_pg_ind, end_pg_ind))
205
- return modified_paras
206
-
207
  def process_file(folderpath):
208
  pdf2png(folderpath)
209
  doc = fitz.open(folderpath + '/opinion.pdf')
@@ -214,25 +160,23 @@ def process_file(folderpath):
214
  'Footer X1':[], 'Footer Y1': [], 'Footer X2': [], 'Footer Y2':[],
215
  'Page X1':[], 'Page Y1': [], 'Page X2': [], 'Page Y2':[],
216
  'Case Separator Y': [],
217
- 'Indent Lines': [],
218
  }
219
  data_df = pd.DataFrame(data)
220
  for (i,f) in enumerate(files):
221
  ind = int(f.split('.png')[0])
222
  page = doc[ind]
223
- page_bbox, header_bbox, fn_bbox, body_bbox, case_separator_bbox, indent_lines, image = get_page_elements(folderpath +'/' + f, page)
224
  row = {'Pg Ind':[ind],
225
  'Header X1':[header_bbox[0]], 'Header Y1': [header_bbox[1]], 'Header X2': [header_bbox[2]], 'Header Y2':[header_bbox[3]],
226
  'Body X1':[body_bbox[0]], 'Body Y1': [body_bbox[1]], 'Body X2': [body_bbox[2]], 'Body Y2':[body_bbox[3]],
227
  'Footer X1':[fn_bbox[0]], 'Footer Y1': [fn_bbox[1]], 'Footer X2': [fn_bbox[2]], 'Footer Y2':[fn_bbox[3]],
228
  'Page X1':[page_bbox[0]], 'Page Y1': [page_bbox[1]], 'Page X2': [page_bbox[2]], 'Page Y2':[page_bbox[3]],
229
  'Case Separator Y': [case_separator_bbox[1]],
230
- 'Indent Lines': [indent_lines]
231
  }
232
  row_df = pd.DataFrame(row)
233
  data_df = pd.concat([data_df, row_df], ignore_index=True)
234
  cv2.imwrite(folderpath + '/' + str(ind) + '-processed.png', image)
235
  data_df['Pg Ind'] = data_df['Pg Ind'].astype('int')
236
- data_df.to_csv(folderpath +'/data.csv', index=False)
237
- paras_df = paragraphs(folderpath)
238
- paras_df.to_csv(folderpath + '/paragraphs.csv', index=False)
 
5
  import pandas as pd
6
  import pytesseract
7
  import warnings
8
+ import re
9
 
10
  def pdf2png(folderpath):
11
  doc = fitz.open(folderpath + '/opinion.pdf')
 
17
 
18
  def is_leftmost(image, x, y_top, y_bot):
19
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
20
+ blur = cv2.GaussianBlur(gray, (9,9), 0)
21
  thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
22
  left_portion = thresh[int((y_top+y_bot)/2), :x]
23
  return np.sum(left_portion) == 0
24
 
25
+
26
+ def get_line_data(filename, body_bbox, page):
27
  image = cv2.imread(filename)
28
  body_rect = fitz.Rect(body_bbox)
29
  pg_dict = page.get_text('dict', clip=body_rect)
30
  all_lines = [(int(line['bbox'][0]), int(line['bbox'][1]), int(line['bbox'][2]), int(line['bbox'][3]), line)for block in pg_dict['blocks'] for line in block['lines']]
31
+ line_data = []
32
+ for (i,l) in enumerate(all_lines):
33
+ if not is_leftmost(image, l[0]-11, l[1], l[3]) and i > 0: # Add it
34
+ line_data[-1] = list(line_data[-1])
35
+ line_data[-1][-1] += " " + get_line_text(l[-1])
36
+ line_data[-1] = tuple(line_data[-1])
37
+ else:
38
+ line_data.append((l[0], l[1], l[2], l[3], get_line_text(l[-1])))
39
+ return line_data
40
+
41
 
42
  def get_footnote_bbox(filename):
43
  footnotes_bbox = (None, None, None, None)
 
130
  body_bbox = (page_bbox[0], header_bbox[3], page_bbox[2], fn_bbox[1])
131
  else:
132
  body_bbox = (page_bbox[0], header_bbox[3], page_bbox[2], page_bbox[3])
133
+ line_data = get_line_data(filename, body_bbox, page)
134
 
135
  image = cv2.imread(filename)
136
  cv2.rectangle(image, (page_bbox[0], page_bbox[1]), (page_bbox[2], page_bbox[3]), (0, 0, 0), 4)
 
139
  if fn_bbox[0] is not None:
140
  cv2.rectangle(image, (fn_bbox[0], fn_bbox[1]), (fn_bbox[2], fn_bbox[3]), (0, 0, 255), 2)
141
  if case_separator_bbox[0] is not None:
142
+ cv2.rectangle(image, (case_separator_bbox[0], case_separator_bbox[1]), (case_separator_bbox[2], case_separator_bbox[3]), (255, 0, 255), 2)
143
+ # for (i, il) in enumerate(indent_lines):
144
+ # cv2.circle(image, (il[1]-15, int(0.5*(il[2] + il[4]))), radius=1, color=(240, 32, 160), thickness=2)
 
145
 
146
+ return page_bbox, header_bbox, fn_bbox, body_bbox, case_separator_bbox, line_data, image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  def get_line_text(line):
149
  words = []
150
+ words = "".join(s['text'] for s in line['spans'] if s['text'].strip() != "")
 
 
 
 
151
  return words
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  def process_file(folderpath):
154
  pdf2png(folderpath)
155
  doc = fitz.open(folderpath + '/opinion.pdf')
 
160
  'Footer X1':[], 'Footer Y1': [], 'Footer X2': [], 'Footer Y2':[],
161
  'Page X1':[], 'Page Y1': [], 'Page X2': [], 'Page Y2':[],
162
  'Case Separator Y': [],
163
+ 'Lines': [],
164
  }
165
  data_df = pd.DataFrame(data)
166
  for (i,f) in enumerate(files):
167
  ind = int(f.split('.png')[0])
168
  page = doc[ind]
169
+ page_bbox, header_bbox, fn_bbox, body_bbox, case_separator_bbox, line_data, image = get_page_elements(folderpath +'/' + f, page)
170
  row = {'Pg Ind':[ind],
171
  'Header X1':[header_bbox[0]], 'Header Y1': [header_bbox[1]], 'Header X2': [header_bbox[2]], 'Header Y2':[header_bbox[3]],
172
  'Body X1':[body_bbox[0]], 'Body Y1': [body_bbox[1]], 'Body X2': [body_bbox[2]], 'Body Y2':[body_bbox[3]],
173
  'Footer X1':[fn_bbox[0]], 'Footer Y1': [fn_bbox[1]], 'Footer X2': [fn_bbox[2]], 'Footer Y2':[fn_bbox[3]],
174
  'Page X1':[page_bbox[0]], 'Page Y1': [page_bbox[1]], 'Page X2': [page_bbox[2]], 'Page Y2':[page_bbox[3]],
175
  'Case Separator Y': [case_separator_bbox[1]],
176
+ 'Lines': [line_data]
177
  }
178
  row_df = pd.DataFrame(row)
179
  data_df = pd.concat([data_df, row_df], ignore_index=True)
180
  cv2.imwrite(folderpath + '/' + str(ind) + '-processed.png', image)
181
  data_df['Pg Ind'] = data_df['Pg Ind'].astype('int')
182
+ data_df.to_csv(folderpath +'/data.csv', index=False)