Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from paddleocr import PaddleOCR
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
4 |
+
from PIL import Image
|
5 |
+
import os
|
6 |
+
|
7 |
+
# --- مدلها ---
|
8 |
+
ocr_model = PaddleOCR(lang='fa', use_angle_cls=True)
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("persiannlp/mt5-small-parsinlu-grammar-correction")
|
10 |
+
nlp_model = AutoModelForSeq2SeqLM.from_pretrained("persiannlp/mt5-small-parsinlu-grammar-correction")
|
11 |
+
|
12 |
+
# --- توابع پردازش ---
|
13 |
+
def run_ocr(image):
|
14 |
+
image_path = image.name # مسیر فایل موقت
|
15 |
+
result = ocr_model.ocr(image_path, cls=True)
|
16 |
+
texts = [line[1][0] for line in result[0]] if result else []
|
17 |
+
os.remove(image_path) # حذف فایل موقت
|
18 |
+
return " ".join(texts)
|
19 |
+
|
20 |
+
def postprocess_text(text):
|
21 |
+
inputs = tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
|
22 |
+
outputs = nlp_model.generate(**inputs)
|
23 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
24 |
+
|
25 |
+
def process_image(image):
|
26 |
+
raw_text = run_ocr(image)
|
27 |
+
processed_text = postprocess_text(raw_text) if raw_text else "متنی یافت نشد!"
|
28 |
+
return raw_text, processed_text
|
29 |
+
|
30 |
+
# --- رابط Gradio ---
|
31 |
+
with gr.Blocks(title="OCR فارسی با پردازش NLP") as app:
|
32 |
+
gr.Markdown("## 🔠 OCR فارسی + پردازش متن با مدل زبانی")
|
33 |
+
gr.Markdown("متن را از تصاویر استخراج کنید و با مدل زبانی اصلاح کنید!")
|
34 |
+
|
35 |
+
with gr.Row():
|
36 |
+
image_input = gr.Image(type="filepath", label="تصویر ورودی")
|
37 |
+
with gr.Column():
|
38 |
+
raw_text_output = gr.Textbox(label="متن خام (OCR)")
|
39 |
+
processed_text_output = gr.Textbox(label="متن پردازششده (NLP)")
|
40 |
+
|
41 |
+
submit_btn = gr.Button("پردازش تصویر")
|
42 |
+
submit_btn.click(
|
43 |
+
fn=process_image,
|
44 |
+
inputs=image_input,
|
45 |
+
outputs=[raw_text_output, processed_text_output]
|
46 |
+
)
|
47 |
+
|
48 |
+
gr.Markdown("---")
|
49 |
+
gr.Markdown("### راهنما:\n1. تصویری حاوی متن فارسی آپلود کنید.\n2. روی دکمه پردازش کلیک کنید.")
|
50 |
+
|
51 |
+
# اجرای برنامه
|
52 |
+
if __name__ == "__main__":
|
53 |
+
app.launch()
|