suprimedev commited on
Commit
c8d9a94
·
verified ·
1 Parent(s): 6b784e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -46
app.py CHANGED
@@ -1,54 +1,85 @@
1
  import gradio as gr
2
- import fitz
3
  import arabic_reshaper
 
 
4
  from PIL import Image
5
- import easyocr
6
-
7
- # Reader سبک برای کاهش مصرف CPU و زمان لود
8
- reader = easyocr.Reader(['fa','ar','en'], gpu=False, detector='craft_mini')
9
 
10
  def extract_text_from_pdf(pdf_file):
11
- if pdf_file is None:
12
- return "لطفاً یک فایل PDF آپلود کنید.", None
13
-
14
- pdf_path = pdf_file.name if hasattr(pdf_file, "name") else pdf_file
15
-
16
- all_text = []
17
- pdf_document = fitz.open(pdf_path)
18
-
19
- for page_num, page in enumerate(pdf_document):
20
- text = page.get_text("text")
21
-
22
- # فقط اگر متن خالی یا مشکل‌دار بود → OCR
23
- if not text.strip() or len(set(text)) < 10:
24
- pix = page.get_pixmap(dpi=150)
25
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
26
- text = "\n".join(reader.readtext(img, detail=0))
27
-
28
- if any('\u0600' <= c <= '\u06FF' or '\u0750' <= c <= '\u077F' for c in text):
29
- text = arabic_reshaper.reshape(text)
30
-
31
- all_text.append(f"--- صفحه {page_num + 1} ---\n{text}\n")
32
-
33
- pdf_document.close()
34
- extracted_text = "\n".join(all_text)
35
-
36
- output_file = "extracted_text.txt"
37
- with open(output_file, "w", encoding="utf-8") as f:
38
- f.write(extracted_text)
39
-
40
- return extracted_text, output_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- def create_interface():
43
- with gr.Blocks() as interface:
44
- gr.Markdown("## استخراج متن PDF سریع و کم‌مصرف")
45
- pdf_input = gr.File(label="آپلود PDF", file_types=[".pdf"], type="filepath")
46
- extract_btn = gr.Button("استخراج متن")
47
- text_output = gr.Textbox(label="متن استخراج شده", lines=20)
48
- download_output = gr.File(label="دانلود TXT")
49
- extract_btn.click(fn=extract_text_from_pdf, inputs=pdf_input, outputs=[text_output, download_output])
50
- return interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  if __name__ == "__main__":
53
- interface = create_interface()
54
- interface.launch()
 
1
  import gradio as gr
2
+ import fitz # PyMuPDF
3
  import arabic_reshaper
4
+ from bidi.algorithm import get_display
5
+ import pytesseract
6
  from PIL import Image
7
+ import io
8
+ import numpy as np
 
 
9
 
10
  def extract_text_from_pdf(pdf_file):
11
+ try:
12
+ # باز کردن فایل PDF
13
+ doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
14
+ full_text = ""
15
+ has_ocr_processed = False
16
+
17
+ # استخراج متن از تمام صفحات
18
+ for page_num in range(len(doc)):
19
+ page = doc.load_page(page_num)
20
+
21
+ # ابتدا سعی می‌کنیم متن را مستقیماً استخراج کنیم
22
+ text = page.get_text()
23
+
24
+ # اگر متن کمی استخراج شده (صفحه احتمالاً تصویری است)
25
+ if len(text.strip()) < 100:
26
+ # تبدیل صفحه به تصویر با وضوح بالا
27
+ mat = fitz.Matrix(300/72, 300/72) # وضوح 300 DPI
28
+ pix = page.get_pixmap(matrix=mat)
29
+ img_data = pix.tobytes("ppm")
30
+
31
+ # استفاده از OCR برای استخراج متن از تصویر
32
+ image = Image.open(io.BytesIO(img_data))
33
+ ocr_text = pytesseract.image_to_string(image, lang='fas+ara+eng')
34
+ text = ocr_text
35
+ has_ocr_processed = True
36
+
37
+ full_text += f"--- صفحه {page_num + 1} ---\n"
38
+ full_text += text + "\n\n"
39
+
40
+ doc.close()
41
+
42
+ # پردازش متن برای زبان‌های راست‌به‌چپ
43
+ try:
44
+ reshaped_text = arabic_reshaper.reshape(full_text)
45
+ bidi_text = get_display(reshaped_text)
46
+
47
+ if has_ocr_processed:
48
+ bidi_text = "[⚠️ برخی صفحات با OCR پردازش شدند]\n\n" + bidi_text
49
+
50
+ return bidi_text
51
+ except:
52
+ return full_text
53
+
54
+ except Exception as e:
55
+ return f"خطا در پردازش فایل: {str(e)}"
56
 
57
+ # ایجاد رابط Gradio
58
+ with gr.Blocks(title="PDF Text Extractor with OCR") as demo:
59
+ gr.Markdown("# 📄 استخراج متن از فایل PDF")
60
+ gr.Markdown("با قابلیت پردازش OCR برای PDFهای تصویری")
61
+
62
+ with gr.Row():
63
+ pdf_input = gr.File(label="فایل PDF را انتخاب کنید", file_types=[".pdf"])
64
+
65
+ extract_btn = gr.Button("🔄 استخراج متن")
66
+
67
+ with gr.Row():
68
+ text_output = gr.Textbox(label="متن استخراج شده", lines=20, interactive=False)
69
+
70
+ gr.Markdown("""
71
+ **⚠️ توجه:**
72
+ - برای PDFهای متنی، متن مستقیماً استخراج می‌شود
73
+ - برای PDFهای تصویری، از OCR استفاده می‌شود
74
+ - پشتیبانی از زبان‌های فارسی، عربی و انگلیسی
75
+ - پردازش ممکن است برای فایل‌های بزرگ کمی زمان‌بر باشد
76
+ """)
77
+
78
+ extract_btn.click(
79
+ fn=extract_text_from_pdf,
80
+ inputs=pdf_input,
81
+ outputs=text_output
82
+ )
83
 
84
  if __name__ == "__main__":
85
+ demo.launch()