suprimedev commited on
Commit
c83c9c5
·
verified ·
1 Parent(s): 1c795be

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OCR فارسی با یک خط بارگذاری تصویر + نمایش نتایج در گریدیو
3
+ """
4
+ import gradio as gr
5
+ import cv2, io, os
6
+ import numpy as np
7
+ from PIL import Image, ImageDraw, ImageFont
8
+ import tesserocr # حتماً در تصویر داکر نصب شده باشد
9
+ from tesserocr import PyTessBaseAPI
10
+
11
+ # -------------------------------
12
+ # تحریرک Tesseract ساده‌خط
13
+ # -------------------------------
14
+ DEFAULT_TESS_PATH = '/usr/share/tesseract-ocr/4.00/tessdata/' # در بیشتر تصاویر داکر HuggingFace
15
+ RESIZE_LONG_SIDE = 1024 # مقیاس برای کاهش هزینه پردازش
16
+
17
+
18
+ def resize_longest(img: Image.Image, max_long: int = RESIZE_LONG_SIDE):
19
+ w, h = img.size
20
+ ratio = max_long / max(w, h)
21
+ if ratio >= 1:
22
+ return img
23
+ new_w = int(w * ratio)
24
+ new_h = int(h * ratio)
25
+ return img.resize((new_w, new_h), Image.LANCZOS)
26
+
27
+
28
+ def persian_ocr_one(file):
29
+ if isinstance(file, tuple):
30
+ img = Image.open(file[0])
31
+ else:
32
+ img = Image.open(file)
33
+ img = img.convert("RGB")
34
+ img = resize_longest(img)
35
+ pix = np.array(img)
36
+
37
+ # تبدیل به طیف‌های تأثیرگذار برای متون فارسی
38
+ gray = cv2.cvtColor(pix, cv2.COLOR_RGB2GRAY)
39
+ den = cv2.fastNlMeansDenoising(gray, None, 10, 7, 21)
40
+
41
+ image_bin = Image.fromarray(den)
42
+
43
+ # راه‌اندازی Tesseract فقط یک‌بار در هر فراخوانی (به دلیل thread-safe بودن)
44
+ # دقت کنید زبان را روی 'fas' تنظیم کرده باشید
45
+ tess_args = (
46
+ 6, # PSM__SINGLE_BLOCK
47
+ {"lang": "fas"} # فارسی
48
+ )
49
+ api = PyTessBaseAPI(path=DEFAULT_TESS_PATH,
50
+ lang='fas',
51
+ psm=tesserocr.PSM.SINGLE_BLOCK)
52
+ api.SetImage(image_bin)
53
+ text = api.GetUTF8Text().strip()
54
+ api.End()
55
+
56
+ return text
57
+
58
+
59
+ # -------------------------------
60
+ # رابط کاربری مینیمال
61
+ # -------------------------------
62
+ demo = gr.Interface(
63
+ fn=persian_ocr_one,
64
+ inputs=gr.Image(type="filepath", label="تصویر"),
65
+ outputs=gr.Textbox(label="متن استخراج‌شده (فارسی)"),
66
+ title="OCR فارسی",
67
+ description="تصویری که شامل متن فارسی است را بارگذاری کنید تا متن داخل آن استخراج شود."
68
+ )
69
+
70
+ if __name__ == "__main__":
71
+ demo.queue(max_size=20).launch()