Spaces:
Sleeping
Sleeping
| import PyPDF2 | |
| import io | |
| import gradio as gr | |
| import langdetect | |
| from langdetect import detect | |
| import re | |
| # تابع برای تشخیص زبان و استخراج متن | |
| def extract_text_from_pdf(pdf_file, detect_language=True): | |
| try: | |
| # خواندن فایل PDF | |
| pdf_reader = PyPDF2.PdfReader(io.BytesIO(pdf_file)) | |
| text = "" | |
| # استخراج متن از تمام صفحات | |
| for page_num in range(len(pdf_reader.pages)): | |
| page = pdf_reader.pages[page_num] | |
| page_text = page.extract_text() | |
| if page_text: | |
| text += page_text + "\n\n" | |
| # تشخیص زبان متن | |
| detected_lang = "نامشخص" | |
| if text and detect_language: | |
| # گرفتن یک نمونه از متن برای تشخیص زبان | |
| sample_text = text[:min(5000, len(text))] | |
| sample_text = re.sub(r'\s+', ' ', sample_text).strip() | |
| try: | |
| detected_lang = detect(sample_text) | |
| if detected_lang == 'fa': | |
| detected_lang = "فارسی" | |
| elif detected_lang == 'en': | |
| detected_lang = "انگلیسی" | |
| except langdetect.lang_detect_exception.LangDetectException: | |
| detected_lang = "تشخیص داده نشد" | |
| # برگرداندن نتیجه | |
| result = f"**زبان تشخیص داده شده: {detected_lang}**\n\n" | |
| result += text if text else "متنی استخراج نشد." | |
| return result | |
| except Exception as e: | |
| return f"خطا در پردازش فایل PDF: {str(e)}" | |
| # ساخت رابط کاربری با Gradio | |
| def create_ui(): | |
| with gr.Blocks(title="استخراج متن از PDF با تشخیص زبان") as app: | |
| gr.Markdown("## استخراج متن از فایل PDF با تشخیص خودکار زبان فارسی یا انگلیسی") | |
| with gr.Row(): | |
| pdf_input = gr.File(label="فایل PDF را آپلود کنید", file_types=[".pdf"]) | |
| with gr.Row(): | |
| extract_btn = gr.Button("استخراج متن") | |
| with gr.Row(): | |
| output_text = gr.Textbox(label="متن استخراج شده", lines=20, interactive=False) | |
| extract_btn.click( | |
| fn=extract_text_from_pdf, | |
| inputs=[pdf_input], | |
| outputs=output_text | |
| ) | |
| return app | |
| # اجرای برنامه | |
| if __name__ == "__main__": | |
| app = create_ui() | |
| app.launch() |