OmidSakaki commited on
Commit
6ecc4f4
·
verified ·
1 Parent(s): 19169b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -61
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import easyocr
3
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
4
- from PIL import Image
5
  import numpy as np
6
  from typing import Tuple
7
 
@@ -14,116 +13,92 @@ class OCRProcessor:
14
  def extract_text(self, image: np.ndarray) -> str:
15
  """استخراج متن از تصویر با EasyOCR"""
16
  try:
17
- results = self.reader.readtext(image)
18
- return " ".join([result[1] for result in results]) if results else ""
19
  except Exception as e:
20
  raise RuntimeError(f"خطا در پردازش OCR: {str(e)}")
21
 
22
  class TextPostProcessor:
23
  def __init__(self):
24
- # تنظیمات پیش‌پردازش متن
25
  self.replacements = {
26
- 'ي': 'ی', 'ك': 'ک',
27
- '۰':'0', '۱':'1', '۲':'2', '۳':'3', '۴':'4',
28
- '۵':'5', '۶':'6', '۷':'7', '۸':'8', '۹':'9'
29
  }
30
-
31
- # بارگذاری مدل زبانی فارسی HooshvareLab/gpt2-fa
32
  try:
33
  self.llm = pipeline(
34
- "text-generation",
35
- model="HooshvareLab/gpt2-fa",
36
  tokenizer="HooshvareLab/gpt2-fa"
37
  )
38
  except Exception as e:
 
39
  self.llm = None
40
- print(f"خطا در بارگذاری مدل HooshvareLab/gpt2-fa: {str(e)}")
41
-
42
  def preprocess(self, text: str) -> str:
43
- """پیش‌پردازش متن استخراج شده"""
44
  if not text:
45
  return ""
46
- # نرمال‌سازی متن
47
  for old, new in self.replacements.items():
48
  text = text.replace(old, new)
49
  return " ".join(text.split())
50
-
51
  def enhance_with_llm(self, text: str) -> str:
52
- """بهبود متن با مدل زبانی"""
53
  if not text or not self.llm:
54
  return text
 
55
  try:
56
- prompt = f"متن زیر را ویرایش و روان‌تر کن:\n{text}\n"
57
- enhanced = self.llm(
58
  prompt,
59
- max_length=len(prompt) + 60,
60
  num_return_sequences=1,
61
  do_sample=True,
62
- temperature=0.8,
63
- pad_token_id=0
 
64
  )
65
- # فقط متن تولیدی پس از پرامپت را برگردان
66
- gen_text = enhanced[0]['generated_text']
67
- return gen_text[len(prompt):].strip() if gen_text.startswith(prompt) else gen_text.strip()
 
 
 
 
 
68
  except Exception as e:
69
- print(f"خطا در بهبود متن با LLM: {str(e)}")
70
  return text
71
 
72
- ## 2. پردازش اصلی
73
- # ----------------------------------
74
  def full_processing(image: np.ndarray) -> Tuple[str, str]:
75
- """پایپلاین کامل پردازش تصویر"""
76
  try:
77
- # 1. استخراج متن
78
  ocr_text = OCRProcessor().extract_text(image)
79
-
80
- # 2. پیش‌پردازش
81
  post_processor = TextPostProcessor()
82
  cleaned_text = post_processor.preprocess(ocr_text)
83
-
84
- # 3. بهبود با مدل زبانی
85
  enhanced_text = post_processor.enhance_with_llm(cleaned_text)
86
-
87
  return cleaned_text, enhanced_text
88
-
89
  except Exception as e:
90
  return f"خطا: {str(e)}", ""
91
 
92
  ## 3. رابط کاربری Gradio
93
- # ----------------------------------
94
- with gr.Blocks(title="پایپلاین OCR فارسی با LLM") as app:
95
  gr.Markdown("""
96
- # سیستم پیشرفته پردازش متن فارسی
97
- استخراج متن از تصاویر + پردازش با مدل زبانی
98
  """)
99
-
100
  with gr.Row():
101
  with gr.Column():
102
  img_input = gr.Image(label="تصویر ورودی", type="numpy")
103
  process_btn = gr.Button("پردازش تصویر", variant="primary")
104
-
105
  with gr.Column():
106
- with gr.Tab("نتایج پردازش"):
107
  raw_output = gr.Textbox(label="متن استخراج شده")
108
- enhanced_output = gr.Textbox(label="متن بهبود یافته")
109
-
110
- with gr.Tab("پیش‌نمایش"):
111
- gr.Markdown("### تصویر ورودی")
112
- img_preview = gr.Image(label="", interactive=False)
113
 
114
- # پردازش خودکار هنگام آپلود تصویر
115
- img_input.change(
116
- fn=lambda x: x,
117
- inputs=img_input,
118
- outputs=img_preview
119
- )
120
-
121
- # پردازش اصلی هنگام کلیک دکمه
122
- process_btn.click(
123
- fn=full_processing,
124
- inputs=img_input,
125
- outputs=[raw_output, enhanced_output]
126
- )
127
 
128
  if __name__ == "__main__":
129
  app.launch()
 
1
  import gradio as gr
2
  import easyocr
3
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
 
4
  import numpy as np
5
  from typing import Tuple
6
 
 
13
  def extract_text(self, image: np.ndarray) -> str:
14
  """استخراج متن از تصویر با EasyOCR"""
15
  try:
16
+ results = self.reader.readtext(image, detail=0, paragraph=True)
17
+ return "\n".join(results) if results else ""
18
  except Exception as e:
19
  raise RuntimeError(f"خطا در پردازش OCR: {str(e)}")
20
 
21
  class TextPostProcessor:
22
  def __init__(self):
 
23
  self.replacements = {
24
+ 'ي': 'ی', 'ك': 'ک',
25
+ '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
26
+ '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9'
27
  }
 
 
28
  try:
29
  self.llm = pipeline(
30
+ "text-generation",
31
+ model="HooshvareLab/gpt2-fa",
32
  tokenizer="HooshvareLab/gpt2-fa"
33
  )
34
  except Exception as e:
35
+ print("خطا در بارگذاری مدل زبانی:", e)
36
  self.llm = None
37
+
 
38
  def preprocess(self, text: str) -> str:
39
+ """نرمال‌سازی ساده متن"""
40
  if not text:
41
  return ""
 
42
  for old, new in self.replacements.items():
43
  text = text.replace(old, new)
44
  return " ".join(text.split())
45
+
46
  def enhance_with_llm(self, text: str) -> str:
47
+ """بازنویسی یا بهبود متن با LLM فارسی"""
48
  if not text or not self.llm:
49
  return text
50
+ prompt = f"متن زیر را بازنویسی کن و به صورت روان و صحیح برگردان:\n{text}\nبازنویسی:"
51
  try:
52
+ output = self.llm(
 
53
  prompt,
54
+ max_length=len(prompt) + len(text) + 60,
55
  num_return_sequences=1,
56
  do_sample=True,
57
+ temperature=0.9,
58
+ pad_token_id=0,
59
+ eos_token_id=2
60
  )
61
+ gen_text = output[0]['generated_text']
62
+ # فقط بخش بازنویسی شده را جدا کن
63
+ if "بازنویسی:" in gen_text:
64
+ gen_text = gen_text.split("بازنویسی:")[-1].strip()
65
+ # اگر بازنویسی مدل بی‌معنا یا کوتاه بود، همان متن را برگردان
66
+ if len(gen_text) < 8:
67
+ return text
68
+ return gen_text
69
  except Exception as e:
70
+ print("خطا در بازنویسی با LLM:", e)
71
  return text
72
 
73
+ ## 2. پایپلاین اصلی
 
74
  def full_processing(image: np.ndarray) -> Tuple[str, str]:
 
75
  try:
 
76
  ocr_text = OCRProcessor().extract_text(image)
 
 
77
  post_processor = TextPostProcessor()
78
  cleaned_text = post_processor.preprocess(ocr_text)
 
 
79
  enhanced_text = post_processor.enhance_with_llm(cleaned_text)
 
80
  return cleaned_text, enhanced_text
 
81
  except Exception as e:
82
  return f"خطا: {str(e)}", ""
83
 
84
  ## 3. رابط کاربری Gradio
85
+ with gr.Blocks(title="پایپلاین OCR و بازنویسی متن فارسی") as app:
 
86
  gr.Markdown("""
87
+ # سیستم استخراج و بازنویسی متن فارسی از تصویر
88
+ تصویر را بارگذاری کنید، متن استخراج و سپس با مدل زبانی بازنویسی می‌شود.
89
  """)
 
90
  with gr.Row():
91
  with gr.Column():
92
  img_input = gr.Image(label="تصویر ورودی", type="numpy")
93
  process_btn = gr.Button("پردازش تصویر", variant="primary")
 
94
  with gr.Column():
95
+ with gr.Tab("متن استخراج شده"):
96
  raw_output = gr.Textbox(label="متن استخراج شده")
97
+ with gr.Tab("متن بازنویسی شده"):
98
+ enhanced_output = gr.Textbox(label="متن بازنویسی شده")
 
 
 
99
 
100
+ img_input.change(fn=lambda x: x, inputs=img_input, outputs=img_preview)
101
+ process_btn.click(fn=full_processing, inputs=img_input, outputs=[raw_output, enhanced_output])
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  if __name__ == "__main__":
104
  app.launch()