Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import PyPDF2
|
2 |
+
import io
|
3 |
+
import gradio as gr
|
4 |
+
import langdetect
|
5 |
+
from langdetect import detect
|
6 |
+
import re
|
7 |
+
|
8 |
+
# تابع برای تشخیص زبان و استخراج متن
|
9 |
+
def extract_text_from_pdf(pdf_file, detect_language=True):
|
10 |
+
try:
|
11 |
+
# خواندن فایل PDF
|
12 |
+
pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_file))
|
13 |
+
text = ""
|
14 |
+
|
15 |
+
# استخراج متن از تمام صفحات
|
16 |
+
for page_num in range(len(pdf_reader.pages)):
|
17 |
+
page = pdf_reader.pages[page_num]
|
18 |
+
page_text = page.extract_text()
|
19 |
+
if page_text:
|
20 |
+
text += page_text + "\n\n"
|
21 |
+
|
22 |
+
# تشخیص زبان متن
|
23 |
+
detected_lang = "نامشخص"
|
24 |
+
if text and detect_language:
|
25 |
+
# گرفتن یک نمونه از متن برای تشخیص زبان
|
26 |
+
sample_text = text[:min(5000, len(text))]
|
27 |
+
sample_text = re.sub(r'\s+', ' ', sample_text).strip()
|
28 |
+
|
29 |
+
try:
|
30 |
+
detected_lang = detect(sample_text)
|
31 |
+
if detected_lang == 'fa':
|
32 |
+
detected_lang = "فارسی"
|
33 |
+
elif detected_lang == 'en':
|
34 |
+
detected_lang = "انگلیسی"
|
35 |
+
except langdetect.lang_detect_exception.LangDetectException:
|
36 |
+
detected_lang = "تشخیص داده نشد"
|
37 |
+
|
38 |
+
# برگرداندن نتیجه
|
39 |
+
result = f"**زبان تشخیص داده شده: {detected_lang}**\n\n"
|
40 |
+
result += text if text else "متنی استخراج نشد."
|
41 |
+
|
42 |
+
return result
|
43 |
+
|
44 |
+
except Exception as e:
|
45 |
+
return f"خطا در پردازش فایل PDF: {str(e)}"
|
46 |
+
|
47 |
+
# ساخت رابط کاربری با Gradio
|
48 |
+
def create_ui():
|
49 |
+
with gr.Blocks(title="استخراج متن از PDF با تشخیص زبان") as app:
|
50 |
+
gr.Markdown("## استخراج متن از فایل PDF با تشخیص خودکار زبان فارسی یا انگلیسی")
|
51 |
+
|
52 |
+
with gr.Row():
|
53 |
+
pdf_input = gr.File(label="فایل PDF را آپلود کنید", file_types=[".pdf"])
|
54 |
+
|
55 |
+
with gr.Row():
|
56 |
+
extract_btn = gr.Button("استخراج متن")
|
57 |
+
|
58 |
+
with gr.Row():
|
59 |
+
output_text = gr.Textbox(label="متن استخراج شده", lines=20, interactive=False)
|
60 |
+
|
61 |
+
extract_btn.click(
|
62 |
+
fn=extract_text_from_pdf,
|
63 |
+
inputs=[pdf_input],
|
64 |
+
outputs=output_text
|
65 |
+
)
|
66 |
+
|
67 |
+
return app
|
68 |
+
|
69 |
+
# اجرای برنامه
|
70 |
+
if __name__ == "__main__":
|
71 |
+
app = create_ui()
|
72 |
+
app.launch()
|