OmidSakaki commited on
Commit
57fa964
·
verified ·
1 Parent(s): 28a9f71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -22
app.py CHANGED
@@ -2,7 +2,9 @@ import gradio as gr
2
  import easyocr
3
  import numpy as np
4
  from typing import Tuple
 
5
 
 
6
  class OCRProcessor:
7
  def __init__(self):
8
  self.reader = easyocr.Reader(['fa'])
@@ -14,33 +16,49 @@ class OCRProcessor:
14
  except Exception as e:
15
  raise RuntimeError(f"خطا در پردازش OCR: {str(e)}")
16
 
17
- class TextPostProcessor:
 
18
  def __init__(self):
19
- self.replacements = {
20
- 'ي': 'ی', 'ك': 'ک',
21
- '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
22
- '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9'
23
- }
24
-
25
- def preprocess(self, text: str) -> str:
26
- if not text:
27
- return ""
28
- for old, new in self.replacements.items():
29
- text = text.replace(old, new)
30
- return " ".join(text.split())
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def full_processing(image: np.ndarray) -> Tuple[str, str]:
33
  try:
 
34
  ocr_text = OCRProcessor().extract_text(image)
35
- post_processor = TextPostProcessor()
36
- cleaned_text = post_processor.preprocess(ocr_text)
37
- return cleaned_text, cleaned_text
 
 
38
  except Exception as e:
39
- return f"خطا: {str(e)}", ""
 
40
 
41
- with gr.Blocks(title="پایپلاین OCR و تصحیح متن فارسی") as app:
 
42
  gr.Markdown("""
43
- # استخراج و تصحیح متن فارسی از تصویر
44
  """)
45
 
46
  with gr.Row():
@@ -48,10 +66,14 @@ with gr.Blocks(title="پایپلاین OCR و تصحیح متن فارسی") as
48
  img_input = gr.Image(label="تصویر ورودی", type="numpy")
49
  process_btn = gr.Button("پردازش تصویر", variant="primary")
50
  with gr.Column():
51
- raw_output = gr.Textbox(label="متن استخراج شده", lines=8, max_lines=None)
52
- enhanced_output = gr.Textbox(label="متن نهایی", lines=10, max_lines=None)
53
 
54
- process_btn.click(fn=full_processing, inputs=img_input, outputs=[raw_output, enhanced_output])
 
 
 
 
55
 
56
  if __name__ == "__main__":
57
  app.launch()
 
2
  import easyocr
3
  import numpy as np
4
  from typing import Tuple
5
+ from transformers import pipeline
6
 
7
+ # --- 1. کلاس OCR برای استخراج متن از تصویر ---
8
  class OCRProcessor:
9
  def __init__(self):
10
  self.reader = easyocr.Reader(['fa'])
 
16
  except Exception as e:
17
  raise RuntimeError(f"خطا در پردازش OCR: {str(e)}")
18
 
19
+ # --- 2. کلاس تصحیح متن با مدل زبانی ---
20
+ class TextCorrector:
21
  def __init__(self):
22
+ # استفاده از مدل ParsBERT برای تصحیح متن فارسی
23
+ self.corrector = pipeline(
24
+ "text2text-generation",
25
+ model="persiannlp/parsbert-uncased", # مدل زبانی فارسی
26
+ tokenizer="persiannlp/parsbert-uncased"
27
+ )
 
 
 
 
 
 
28
 
29
+ def correct(self, text: str) -> str:
30
+ if not text.strip():
31
+ return text
32
+ try:
33
+ corrected = self.corrector(
34
+ text,
35
+ max_length=512,
36
+ num_beams=5,
37
+ early_stopping=True
38
+ )
39
+ return corrected[0]['generated_text']
40
+ except Exception as e:
41
+ print(f"خطا در تصحیح متن: {e}")
42
+ return text
43
+
44
+ # --- 3. پردازش کامل (OCR + تصحیح خودکار) ---
45
  def full_processing(image: np.ndarray) -> Tuple[str, str]:
46
  try:
47
+ # استخراج متن از تصویر
48
  ocr_text = OCRProcessor().extract_text(image)
49
+
50
+ # تصحیح متن با مدل زبانی
51
+ corrected_text = TextCorrector().correct(ocr_text)
52
+
53
+ return ocr_text, corrected_text
54
  except Exception as e:
55
+ error_msg = f"خطا: {str(e)}"
56
+ return error_msg, error_msg
57
 
58
+ # --- 4. رابط کاربری Gradio ---
59
+ with gr.Blocks(title="پایپلاین OCR + تصحیح خودکار متن فارسی") as app:
60
  gr.Markdown("""
61
+ # استخراج و تصحیح هوشمند متن فارسی از تصویر
62
  """)
63
 
64
  with gr.Row():
 
66
  img_input = gr.Image(label="تصویر ورودی", type="numpy")
67
  process_btn = gr.Button("پردازش تصویر", variant="primary")
68
  with gr.Column():
69
+ raw_output = gr.Textbox(label="متن استخراج شده (خام)", lines=8, interactive=True)
70
+ corrected_output = gr.Textbox(label="متن تصحیح شده (هوشمند)", lines=10, interactive=True)
71
 
72
+ process_btn.click(
73
+ fn=full_processing,
74
+ inputs=img_input,
75
+ outputs=[raw_output, corrected_output]
76
+ )
77
 
78
  if __name__ == "__main__":
79
  app.launch()