shrudhit commited on
Commit
e878bbc
·
verified ·
1 Parent(s): 54a903f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -34
app.py CHANGED
@@ -4,27 +4,39 @@ import cv2
4
  import pandas as pd
5
  import gradio as gr
6
  import pytesseract
 
 
7
  from PIL import Image
8
 
9
 
 
 
 
 
 
 
 
 
 
10
  # =========================================================
11
  # OCR CORRECTION
12
  # =========================================================
13
 
14
  def correct_ocr_mistakes(text):
 
15
  if not text:
16
  return ""
17
 
18
  text = text.upper()
19
 
20
  replacements = {
21
- 'O': '0',
22
- 'I': '1',
23
- 'L': '1',
24
- 'S': '5',
25
- 'B': '8',
26
- 'G': '6',
27
- 'Z': '2'
28
  }
29
 
30
  for k, v in replacements.items():
@@ -34,7 +46,7 @@ def correct_ocr_mistakes(text):
34
 
35
 
36
  # =========================================================
37
- # GET LAST 3 DIGITS
38
  # =========================================================
39
 
40
  def extract_last_3_digits(val):
@@ -44,7 +56,7 @@ def extract_last_3_digits(val):
44
 
45
  val = correct_ocr_mistakes(val)
46
 
47
- digits = re.findall(r'\d', val)
48
 
49
  if len(digits) >= 3:
50
  return "".join(digits[-3:])
@@ -78,12 +90,12 @@ def parse_ocr_text(text):
78
  # -------------------------------------------------
79
 
80
  if (
81
- re.search(r'AW[B8]\s*[:\-]', line, re.IGNORECASE)
82
  or "AWB" in line.upper()
83
  ):
84
 
85
  m = re.search(
86
- r'AW[B8]\s*[:\-]?\s*([A-Z0-9_]+)',
87
  line,
88
  re.IGNORECASE
89
  )
@@ -100,13 +112,13 @@ def parse_ocr_text(text):
100
  # -------------------------------------------------
101
 
102
  if re.search(
103
- r'Packet\s*[I1][D0]',
104
  line,
105
  re.IGNORECASE
106
  ):
107
 
108
  m = re.search(
109
- r'Packet\s*[I1][D0]\s*[:\-]?\s*([A-Z0-9_]+)',
110
  line,
111
  re.IGNORECASE
112
  )
@@ -123,13 +135,13 @@ def parse_ocr_text(text):
123
  # -------------------------------------------------
124
 
125
  if re.search(
126
- r'Ship\s*T[o0]',
127
  line,
128
  re.IGNORECASE
129
  ):
130
 
131
  m = re.search(
132
- r'Ship\s*T[o0]\s*[:\-]?\s*(.+)',
133
  line,
134
  re.IGNORECASE
135
  )
@@ -159,11 +171,13 @@ def preprocess_image(image_path):
159
  if img is None:
160
  return []
161
 
 
162
  gray = cv2.cvtColor(
163
  img,
164
  cv2.COLOR_BGR2GRAY
165
  )
166
 
 
167
  gray = cv2.resize(
168
  gray,
169
  None,
@@ -172,6 +186,7 @@ def preprocess_image(image_path):
172
  interpolation=cv2.INTER_CUBIC
173
  )
174
 
 
175
  denoised = cv2.fastNlMeansDenoising(
176
  gray,
177
  None,
@@ -180,6 +195,7 @@ def preprocess_image(image_path):
180
  searchWindowSize=21
181
  )
182
 
 
183
  adaptive_thresh = cv2.adaptiveThreshold(
184
  denoised,
185
  255,
@@ -202,19 +218,36 @@ def preprocess_image(image_path):
202
  def process_images(files, progress=gr.Progress()):
203
 
204
  if not files:
205
- return pd.DataFrame(
206
- columns=["AWB", "Packet ID", "Ship To"]
207
- ), None
 
 
 
 
 
 
 
 
 
208
 
209
  results = []
210
 
 
 
211
  ocr_configs = [
212
- '--psm 6',
213
- '--psm 11'
214
  ]
215
 
 
216
  total_files = len(files)
217
 
 
 
 
 
 
218
  for index, file_obj in enumerate(files):
219
 
220
  progress(
@@ -222,25 +255,32 @@ def process_images(files, progress=gr.Progress()):
222
  desc=f"Processing {index + 1}/{total_files}"
223
  )
224
 
 
225
  # -------------------------------------------------
226
  # GET FILE PATH
227
  # -------------------------------------------------
228
 
229
  if isinstance(file_obj, str):
 
230
  filepath = file_obj
231
 
232
  elif hasattr(file_obj, "name"):
 
233
  filepath = file_obj.name
234
 
235
  else:
 
236
  filepath = str(file_obj)
237
 
238
 
239
  # -------------------------------------------------
240
- # PREPROCESS
241
  # -------------------------------------------------
242
 
243
- preprocessed_imgs = preprocess_image(filepath)
 
 
 
244
 
245
  final_awb = ""
246
  final_packet = ""
@@ -249,15 +289,16 @@ def process_images(files, progress=gr.Progress()):
249
  found_all = False
250
 
251
 
252
- # -------------------------------------------------
253
  # OCR
254
- # -------------------------------------------------
255
 
256
  for img in preprocessed_imgs:
257
 
258
  if found_all:
259
  break
260
 
 
261
  for config in ocr_configs:
262
 
263
  try:
@@ -268,34 +309,45 @@ def process_images(files, progress=gr.Progress()):
268
  )
269
 
270
  except Exception:
 
271
  continue
272
 
273
 
274
- awb, packet, ship = parse_ocr_text(text)
 
 
 
275
 
276
 
 
277
  if not final_awb and awb:
278
  final_awb = awb
279
 
 
 
280
  if not final_packet and packet:
281
  final_packet = packet
282
 
 
 
283
  if not final_ship and ship:
284
  final_ship = ship
285
 
286
 
 
287
  if (
288
  final_awb
289
  and final_packet
290
  and final_ship
291
  ):
 
292
  found_all = True
293
  break
294
 
295
 
296
- # -------------------------------------------------
297
- # SAVE RESULT
298
- # -------------------------------------------------
299
 
300
  results.append({
301
  "AWB": final_awb,
@@ -305,7 +357,7 @@ def process_images(files, progress=gr.Progress()):
305
 
306
 
307
  # =====================================================
308
- # DATAFRAME
309
  # =====================================================
310
 
311
  df = pd.DataFrame(
@@ -319,7 +371,7 @@ def process_images(files, progress=gr.Progress()):
319
 
320
 
321
  # =====================================================
322
- # EXCEL OUTPUT
323
  # =====================================================
324
 
325
  output_excel = os.path.abspath(
@@ -336,21 +388,28 @@ def process_images(files, progress=gr.Progress()):
336
 
337
 
338
  # =========================================================
339
- # GRADIO UI
340
  # =========================================================
341
 
342
  with gr.Blocks(
343
  title="RVP Label OCR Extractor"
344
  ) as interface:
345
 
 
 
 
 
 
346
  gr.Markdown(
347
  "# 📦 RVP Label OCR Extractor"
348
  )
349
 
 
350
  gr.Markdown(
351
  "Upload RVP label images to extract "
352
  "the last 3 digits of AWB, "
353
- "last 3 digits of Packet ID, and Ship To."
 
354
  )
355
 
356
 
@@ -371,7 +430,7 @@ with gr.Blocks(
371
 
372
 
373
  # -----------------------------------------------------
374
- # BUTTON
375
  # -----------------------------------------------------
376
 
377
  extract_btn = gr.Button(
@@ -381,7 +440,7 @@ with gr.Blocks(
381
 
382
 
383
  # -----------------------------------------------------
384
- # OUTPUT TABLE
385
  # -----------------------------------------------------
386
 
387
  output_df = gr.Dataframe(
 
4
  import pandas as pd
5
  import gradio as gr
6
  import pytesseract
7
+ import spaces
8
+
9
  from PIL import Image
10
 
11
 
12
+ # =========================================================
13
+ # ZERO GPU STARTUP CHECK
14
+ # =========================================================
15
+
16
+ @spaces.GPU
17
+ def zerogpu_probe():
18
+ return "OK"
19
+
20
+
21
  # =========================================================
22
  # OCR CORRECTION
23
  # =========================================================
24
 
25
  def correct_ocr_mistakes(text):
26
+
27
  if not text:
28
  return ""
29
 
30
  text = text.upper()
31
 
32
  replacements = {
33
+ "O": "0",
34
+ "I": "1",
35
+ "L": "1",
36
+ "S": "5",
37
+ "B": "8",
38
+ "G": "6",
39
+ "Z": "2"
40
  }
41
 
42
  for k, v in replacements.items():
 
46
 
47
 
48
  # =========================================================
49
+ # EXTRACT LAST 3 DIGITS
50
  # =========================================================
51
 
52
  def extract_last_3_digits(val):
 
56
 
57
  val = correct_ocr_mistakes(val)
58
 
59
+ digits = re.findall(r"\d", val)
60
 
61
  if len(digits) >= 3:
62
  return "".join(digits[-3:])
 
90
  # -------------------------------------------------
91
 
92
  if (
93
+ re.search(r"AW[B8]\s*[:\-]", line, re.IGNORECASE)
94
  or "AWB" in line.upper()
95
  ):
96
 
97
  m = re.search(
98
+ r"AW[B8]\s*[:\-]?\s*([A-Z0-9_]+)",
99
  line,
100
  re.IGNORECASE
101
  )
 
112
  # -------------------------------------------------
113
 
114
  if re.search(
115
+ r"Packet\s*[I1][D0]",
116
  line,
117
  re.IGNORECASE
118
  ):
119
 
120
  m = re.search(
121
+ r"Packet\s*[I1][D0]\s*[:\-]?\s*([A-Z0-9_]+)",
122
  line,
123
  re.IGNORECASE
124
  )
 
135
  # -------------------------------------------------
136
 
137
  if re.search(
138
+ r"Ship\s*T[o0]",
139
  line,
140
  re.IGNORECASE
141
  ):
142
 
143
  m = re.search(
144
+ r"Ship\s*T[o0]\s*[:\-]?\s*(.+)",
145
  line,
146
  re.IGNORECASE
147
  )
 
171
  if img is None:
172
  return []
173
 
174
+ # Grayscale
175
  gray = cv2.cvtColor(
176
  img,
177
  cv2.COLOR_BGR2GRAY
178
  )
179
 
180
+ # Resize
181
  gray = cv2.resize(
182
  gray,
183
  None,
 
186
  interpolation=cv2.INTER_CUBIC
187
  )
188
 
189
+ # Denoise
190
  denoised = cv2.fastNlMeansDenoising(
191
  gray,
192
  None,
 
195
  searchWindowSize=21
196
  )
197
 
198
+ # Adaptive threshold
199
  adaptive_thresh = cv2.adaptiveThreshold(
200
  denoised,
201
  255,
 
218
  def process_images(files, progress=gr.Progress()):
219
 
220
  if not files:
221
+
222
+ return (
223
+ pd.DataFrame(
224
+ columns=[
225
+ "AWB",
226
+ "Packet ID",
227
+ "Ship To"
228
+ ]
229
+ ),
230
+ None
231
+ )
232
+
233
 
234
  results = []
235
 
236
+
237
+ # OCR configurations
238
  ocr_configs = [
239
+ "--psm 6",
240
+ "--psm 11"
241
  ]
242
 
243
+
244
  total_files = len(files)
245
 
246
+
247
+ # =====================================================
248
+ # LOOP THROUGH FILES
249
+ # =====================================================
250
+
251
  for index, file_obj in enumerate(files):
252
 
253
  progress(
 
255
  desc=f"Processing {index + 1}/{total_files}"
256
  )
257
 
258
+
259
  # -------------------------------------------------
260
  # GET FILE PATH
261
  # -------------------------------------------------
262
 
263
  if isinstance(file_obj, str):
264
+
265
  filepath = file_obj
266
 
267
  elif hasattr(file_obj, "name"):
268
+
269
  filepath = file_obj.name
270
 
271
  else:
272
+
273
  filepath = str(file_obj)
274
 
275
 
276
  # -------------------------------------------------
277
+ # PREPROCESS IMAGE
278
  # -------------------------------------------------
279
 
280
+ preprocessed_imgs = preprocess_image(
281
+ filepath
282
+ )
283
+
284
 
285
  final_awb = ""
286
  final_packet = ""
 
289
  found_all = False
290
 
291
 
292
+ # =================================================
293
  # OCR
294
+ # =================================================
295
 
296
  for img in preprocessed_imgs:
297
 
298
  if found_all:
299
  break
300
 
301
+
302
  for config in ocr_configs:
303
 
304
  try:
 
309
  )
310
 
311
  except Exception:
312
+
313
  continue
314
 
315
 
316
+ # Parse OCR
317
+ awb, packet, ship = parse_ocr_text(
318
+ text
319
+ )
320
 
321
 
322
+ # Save AWB
323
  if not final_awb and awb:
324
  final_awb = awb
325
 
326
+
327
+ # Save Packet ID
328
  if not final_packet and packet:
329
  final_packet = packet
330
 
331
+
332
+ # Save Ship To
333
  if not final_ship and ship:
334
  final_ship = ship
335
 
336
 
337
+ # Stop if everything found
338
  if (
339
  final_awb
340
  and final_packet
341
  and final_ship
342
  ):
343
+
344
  found_all = True
345
  break
346
 
347
 
348
+ # =================================================
349
+ # ADD RESULT
350
+ # =================================================
351
 
352
  results.append({
353
  "AWB": final_awb,
 
357
 
358
 
359
  # =====================================================
360
+ # CREATE DATAFRAME
361
  # =====================================================
362
 
363
  df = pd.DataFrame(
 
371
 
372
 
373
  # =====================================================
374
+ # CREATE EXCEL
375
  # =====================================================
376
 
377
  output_excel = os.path.abspath(
 
388
 
389
 
390
  # =========================================================
391
+ # GRADIO INTERFACE
392
  # =========================================================
393
 
394
  with gr.Blocks(
395
  title="RVP Label OCR Extractor"
396
  ) as interface:
397
 
398
+
399
+ # -----------------------------------------------------
400
+ # TITLE
401
+ # -----------------------------------------------------
402
+
403
  gr.Markdown(
404
  "# 📦 RVP Label OCR Extractor"
405
  )
406
 
407
+
408
  gr.Markdown(
409
  "Upload RVP label images to extract "
410
  "the last 3 digits of AWB, "
411
+ "last 3 digits of Packet ID, "
412
+ "and Ship To."
413
  )
414
 
415
 
 
430
 
431
 
432
  # -----------------------------------------------------
433
+ # EXTRACT BUTTON
434
  # -----------------------------------------------------
435
 
436
  extract_btn = gr.Button(
 
440
 
441
 
442
  # -----------------------------------------------------
443
+ # RESULTS
444
  # -----------------------------------------------------
445
 
446
  output_df = gr.Dataframe(