suprimedev commited on
Commit
d67ab18
·
verified ·
1 Parent(s): 9172e12

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +58 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import fitz # PyMuPDF
3
+ import arabic_reshaper
4
+ import easyocr
5
+ from PIL import Image
6
+ import io
7
+
8
+ reader = easyocr.Reader(['fa','ar','en'], gpu=False)
9
+
10
+ def extract_text_from_pdf(pdf_file):
11
+ if pdf_file is None:
12
+ return "لطفاً یک فایل PDF آپلود کنید.", None
13
+ try:
14
+ pdf_document = fitz.open(pdf_file)
15
+ all_text = []
16
+ for page_num in range(len(pdf_document)):
17
+ page = pdf_document[page_num]
18
+ text = page.get_text("text")
19
+ if not text.strip() or len(set(text)) < 10:
20
+ pix = page.get_pixmap(dpi=150)
21
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
22
+ text_lines = reader.readtext(img, detail=0)
23
+ text = "\n".join(text_lines)
24
+ if any('\u0600' <= char <= '\u06FF' or '\u0750' <= char <= '\u077F' for char in text):
25
+ text = arabic_reshaper.reshape(text)
26
+ all_text.append(f"--- صفحه {page_num + 1} ---\n{text}\n")
27
+ pdf_document.close()
28
+ extracted_text = "\n".join(all_text)
29
+ output_file = "extracted_text.txt"
30
+ with open(output_file, "w", encoding="utf-8") as f:
31
+ f.write(extracted_text)
32
+ return extracted_text, output_file
33
+ except Exception as e:
34
+ return f"خطا در پردازش فایل: {str(e)}", None
35
+
36
+ def create_interface():
37
+ with gr.Blocks(theme=gr.themes.Soft()) as interface:
38
+ gr.Markdown("""# 📄 استخراج متن از PDF با OCR بهینه
39
+ این برنامه متن PDF را استخراج می‌کند.
40
+ - اگر PDF متن واقعی داشته باشد مستقیم می‌خواند.
41
+ - اگر اسکن شده باشد فقط صفحات خالی یا غیرقابل‌خواندن OCR می‌شوند.
42
+ ### نحوه استفاده:
43
+ 1. فایل PDF را آپلود کنید
44
+ 2. روی "استخراج متن" کلیک کنید
45
+ 3. متن استخراج‌شده را مشاهده و دانلود کنید""")
46
+ with gr.Row():
47
+ with gr.Column(scale=1):
48
+ pdf_input = gr.File(label="📂 آپلود PDF", file_types=[".pdf"], type="filepath")
49
+ extract_btn = gr.Button("🔍 استخراج متن", variant="primary")
50
+ with gr.Column(scale=2):
51
+ text_output = gr.Textbox(label="📝 متن استخراج شده", placeholder="متن PDF اینجا نمایش داده می‌شود...", lines=20, max_lines=30)
52
+ download_output = gr.File(label="⬇️ دانلود txt")
53
+ extract_btn.click(fn=extract_text_from_pdf, inputs=pdf_input, outputs=[text_output, download_output])
54
+ return interface
55
+
56
+ if __name__ == "__main__":
57
+ interface = create_interface()
58
+ interface.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ PyMuPDF
3
+ arabic-reshaper
4
+ python-bidi
5
+ pillow
6
+ easyocr