OmidSakaki commited on
Commit
4e751ce
·
verified ·
1 Parent(s): b0ea6e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -61
app.py CHANGED
@@ -3,88 +3,51 @@ import easyocr
3
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
4
  from PIL import Image
5
  import numpy as np
6
- import os
7
 
8
  # Initialize EasyOCR for Persian
9
  reader = easyocr.Reader(['fa'])
10
 
11
- # Load NLP model for text correction
12
- tokenizer = AutoTokenizer.from_pretrained("persiannlp/mt5-small-parsinlu-grammar-correction")
13
- model = AutoModelForSeq2SeqLM.from_pretrained("persiannlp/mt5-small-parsinlu-grammar-correction")
 
 
 
 
14
 
15
  def run_ocr(image):
16
  """استخراج متن از تصویر با EasyOCR"""
17
  try:
18
- # Convert PIL Image to numpy array if needed
19
  if isinstance(image, Image.Image):
20
  image = np.array(image)
21
-
22
  results = reader.readtext(image)
23
- texts = [result[1] for result in results]
24
- return " ".join(texts) if texts else "متنی یافت نشد!"
25
  except Exception as e:
26
- return f"خطا در پردازش تصویر: {str(e)}"
27
 
28
- def postprocess_text(text):
29
- """پردازش متن با مدل زبانی"""
30
- try:
31
- inputs = tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
32
- outputs = model.generate(**inputs)
33
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
34
- except Exception as e:
35
- return f"خطا در پردازش متن: {str(e)}"
36
 
37
- def process_image(image):
38
- """پردازش کامل تصویر"""
39
- # استخراج متن
40
- raw_text = run_ocr(image)
41
-
42
- # پردازش متن
43
- processed_text = postprocess_text(raw_text) if raw_text and raw_text != "متنی یافت نشد!" else raw_text
44
-
45
- return raw_text, processed_text
46
-
47
- # رابط کاربری Gradio
48
- with gr.Blocks(title="OCR فارسی با پردازش NLP") as app:
49
- gr.Markdown("""
50
- ## 🔠 OCR فارسی + پردازش متن با مدل زبانی
51
- متن را از تصاویر استخراج کنید و با مدل زبانی اصلاح کنید!
52
- """)
53
 
54
  with gr.Row():
55
  with gr.Column():
56
- image_input = gr.Image(label="تصویر حاوی متن فارسی را آپلود کنید", type="pil")
57
- process_btn = gr.Button("پردازش تصویر", variant="primary")
58
 
59
  with gr.Column():
60
- with gr.Tab("نتایج"):
61
- raw_output = gr.Textbox(label="متن خام (OCR)")
62
- processed_output = gr.Textbox(label="متن پردازش‌شده (NLP)")
63
-
64
- with gr.Tab("تصویر"):
65
- image_output = gr.Image(label="تصویر ورودی")
66
-
67
- # پردازش هنگام کلیک یا آپلود تصویر
68
- process_btn.click(
69
- fn=process_image,
70
- inputs=image_input,
71
- outputs=[raw_output, processed_output]
72
- )
73
 
74
- # نمایش خودکار تصویر ورودی
75
- image_input.change(
76
- fn=lambda img: img,
77
- inputs=image_input,
78
- outputs=image_output
79
  )
80
-
81
- gr.Markdown("---")
82
- gr.Markdown("""
83
- **راهنما**:
84
- 1. تصویری حاوی متن فارسی آپلود کنید
85
- 2. روی دکمه 'پردازش تصویر' کلیک کنید
86
- 3. نتایج استخراج متن و پردازش زبان طبیعی را مشاهده کنید
87
- """)
88
 
89
  if __name__ == "__main__":
90
  app.launch()
 
3
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
4
  from PIL import Image
5
  import numpy as np
 
6
 
7
  # Initialize EasyOCR for Persian
8
  reader = easyocr.Reader(['fa'])
9
 
10
+ # Load NLP model - استفاده از مدل جایگزین
11
+ model_name = "HooshvareLab/bert-fa-base-uncased"
12
+ try:
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
15
+ except Exception as e:
16
+ raise gr.Error(f"خطا در بارگذاری مدل زبانی: {str(e)}")
17
 
18
  def run_ocr(image):
19
  """استخراج متن از تصویر با EasyOCR"""
20
  try:
 
21
  if isinstance(image, Image.Image):
22
  image = np.array(image)
 
23
  results = reader.readtext(image)
24
+ return " ".join([result[1] for result in results]) if results else "متنی یافت نشد!"
 
25
  except Exception as e:
26
+ return f"خطا در OCR: {str(e)}"
27
 
28
+ def process_text(text):
29
+ """پردازش متن (ساده‌شده)"""
30
+ # در این نسخه ساده، فقط متن را برمی‌گردانیم
31
+ # می‌توانید پردازش‌های دیگر اضافه کنید
32
+ return text if text != "متنی یافت نشد!" else text
 
 
 
33
 
34
+ with gr.Blocks(title="OCR فارسی") as app:
35
+ gr.Markdown("## استخراج متن فارسی از تصاویر")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  with gr.Row():
38
  with gr.Column():
39
+ img_input = gr.Image(label="تصویر ورودی", type="pil")
40
+ btn = gr.Button("پردازش")
41
 
42
  with gr.Column():
43
+ ocr_output = gr.Textbox(label="متن استخراج شده")
44
+ # nl_output = gr.Textbox(label="متن پردازش شده") # غیرفعال شده
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ btn.click(
47
+ fn=lambda x: (run_ocr(x), process_text(run_ocr(x))),
48
+ inputs=img_input,
49
+ outputs=[ocr_output] # فقط خروجی OCR نمایش داده می‌شود
 
50
  )
 
 
 
 
 
 
 
 
51
 
52
  if __name__ == "__main__":
53
  app.launch()