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