Team Ai
Apppublic

azils3/bash

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
pdftools.py352 linesDownload Raw Back to plugins
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7"""8✘ Commands Available -9 10• `{i}pdf <page num> <reply to pdf file>`11    Extract & send page as an Image.(note-: For extracting all pages, just use .pdf)12    to upload selected range `{i}pdf 1-7`13 14• `{i}pdtext <page num> <reply to pdf file>`15    Extract Text From the Pdf.(note-: For Extraction all text just use .pdtext)16    to extract selected pages `{i}pdf 1-7`17 18• `{i}pdscan <reply to image>`19    It scan, crop & send image(s) as pdf.20 21• `{i}pdsave <reply to image/pdf>`22    It scan, crop & save file to merge.23    you can merge many pages in a single pdf.24 25• `{i}pdsend `26    Merge & send the pdf, collected from .pdsave.27"""28import glob29import os30import shutil31import time32 33import cv234import numpy as np35 36try:37    from PIL import Image38except ImportError:39    Image = None40    LOGS.info(f"{__file__}: PIL  not Installed.")41from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter42from telethon.errors.rpcerrorlist import PhotoSaveFileInvalidError43 44from pyUltroid.fns.tools import four_point_transform45 46from . import (47    HNDLR,48    LOGS,49    bash,50    check_filename,51    downloader,52    eor,53    get_string,54    ultroid_cmd,55)56 57if not os.path.isdir("pdf"):58    os.mkdir("pdf")59 60 61@ultroid_cmd(62    pattern="pdf( (.*)|$)",63)64async def pdfseimg(event):65    ok = await event.get_reply_message()66    msg = event.pattern_match.group(1).strip()67    if not (ok and (ok.document and (ok.document.mime_type == "application/pdf"))):68        await event.eor("`Reply The pdf u Want to Download..`")69        return70    xx = await event.eor(get_string("com_1"))71    file = ok.media.document72    k = time.time()73    filename = "hehe.pdf"74    result = await downloader(75        f"pdf/{filename}", file, xx, k, f"Downloading {filename}..."76    )77 78    await xx.delete()79    pdfp = "pdf/hehe.pdf"80    pdfp.replace(".pdf", "")81    pdf = PdfFileReader(pdfp)82    if not msg:83        ok = []84        for num in range(pdf.numPages):85            pw = PdfFileWriter()86            pw.addPage(pdf.getPage(num))87            fil = os.path.join(f"pdf/ult{num + 1}.png")88            ok.append(fil)89            with open(fil, "wb") as f:90                pw.write(f)91        os.remove(pdfp)92        for z in ok:93            await event.client.send_file(event.chat_id, z)94        shutil.rmtree("pdf")95        os.mkdir("pdf")96        await xx.delete()97    elif "-" in msg:98        ok = int(msg.split("-")[-1]) - 199        for o in range(ok):100            pw = PdfFileWriter()101            pw.addPage(pdf.getPage(o))102            with open(os.path.join("ult.png"), "wb") as f:103                pw.write(f)104            await event.reply(105                file="ult.png",106            )107            os.remove("ult.png")108        os.remove(pdfp)109    else:110        o = int(msg) - 1111        pw = PdfFileWriter()112        pw.addPage(pdf.getPage(o))113        with open(os.path.join("ult.png"), "wb") as f:114            pw.write(f)115        os.remove(pdfp)116        try:117            await event.reply(file="ult.png")118        except PhotoSaveFileInvalidError:119            await event.reply(file="ult.png", force_document=True)120        os.remove("ult.png")121 122 123@ultroid_cmd(124    pattern="pdtext( (.*)|$)",125)126async def pdfsetxt(event):127    ok = await event.get_reply_message()128    msg = event.pattern_match.group(1).strip()129    if not ok and ok.document and ok.document.mime_type == "application/pdf":130        await event.eor("`Reply The pdf u Want to Download..`")131        return132    xx = await event.eor(get_string("com_1"))133    file = ok.media.document134    k = time.time()135    filename = ok.file.name136    result = await downloader(filename, file, xx, k, f"Downloading {filename}...")137    await xx.delete()138    dl = result.name139    if not msg:140        pdf = PdfFileReader(dl)141        text = f"{dl.split('.')[0]}.txt"142        with open(text, "w") as f:143            for page_num in range(pdf.numPages):144                pageObj = pdf.getPage(page_num)145                txt = pageObj.extractText()146                f.write(f"Page {page_num + 1}\n")147                f.write("".center(100, "-"))148                f.write(txt)149        await event.client.send_file(150            event.chat_id,151            text,152            reply_to=event.reply_to_msg_id,153        )154        os.remove(text)155        os.remove(dl)156        return157    if "-" in msg:158        u, d = msg.split("-")159        a = PdfFileReader(dl)160        str = "".join(a.getPage(i).extractText() for i in range(int(u) - 1, int(d)))161        text = f"{dl.split('.')[0]} {msg}.txt"162    else:163        u = int(msg) - 1164        a = PdfFileReader(dl)165        str = a.getPage(u).extractText()166        text = f"{dl.split('.')[0]} Pg-{msg}.txt"167 168    with open(text, "w") as f:169        f.write(str)170    await event.client.send_file(171        event.chat_id,172        text,173        reply_to=event.reply_to_msg_id,174    )175    os.remove(text)176    os.remove(dl)177 178 179@ultroid_cmd(180    pattern="pdscan( (.*)|$)",181)182async def imgscan(event):183    ok = await event.get_reply_message()184    if not (ok and (ok.media)):185        await event.eor("`Reply The pdf u Want to Download..`")186        return187    if not (188        ok.photo189        or (ok.file.name and ok.file.name.endswith(("png", "jpg", "jpeg", "webp")))190    ):191        await event.eor("`Reply to a Image only...`")192        return193    ultt = await ok.download_media()194    xx = await event.eor(get_string("com_1"))195    image = cv2.imread(ultt)196    original_image = image.copy()197    ratio = image.shape[0] / 500.0198    hi, wid = image.shape[:2]199    ra = 500 / float(hi)200    dmes = (int(wid * ra), 500)201    image = cv2.resize(image, dmes, interpolation=cv2.INTER_AREA)202    image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)203    image_y = np.zeros(image_yuv.shape[:2], np.uint8)204    image_y[:, :] = image_yuv[:, :, 0]205    image_blurred = cv2.GaussianBlur(image_y, (3, 3), 0)206    edges = cv2.Canny(image_blurred, 50, 200, apertureSize=3)207    contours, hierarchy = cv2.findContours(208        edges,209        cv2.RETR_EXTERNAL,210        cv2.CHAIN_APPROX_SIMPLE,211    )212    polygons = []213    for cnt in contours:214        hull = cv2.convexHull(cnt)215        polygons.append(cv2.approxPolyDP(hull, 0.01 * cv2.arcLength(hull, True), False))216        sortedPoly = sorted(polygons, key=cv2.contourArea, reverse=True)217        cv2.drawContours(image, sortedPoly[0], -1, (0, 0, 255), 5)218        simplified_cnt = sortedPoly[0]219    if len(simplified_cnt) == 4:220        try:221            from skimage.filters import threshold_local222        except ImportError:223            LOGS.info(f"Scikit-Image is not Installed.")224            await xx.edit("`Installing Scikit-Image...\nThis may take some long...`")225            _, __ = await bash("pip install scikit-image")226            LOGS.info(_)227            from skimage.filters import threshold_local228        cropped_image = four_point_transform(229            original_image,230            simplified_cnt.reshape(4, 2) * ratio,231        )232        gray_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2GRAY)233        T = threshold_local(gray_image, 11, offset=10, method="gaussian")234        ok = (gray_image > T).astype("uint8") * 255235    if len(simplified_cnt) != 4:236        ok = cv2.detailEnhance(original_image, sigma_s=10, sigma_r=0.15)237    cv2.imwrite("o.png", ok)238    image1 = Image.open("o.png")239    im1 = image1.convert("RGB")240    scann = f"Scanned {ultt.split('.')[0]}.pdf"241    im1.save(scann)242    await event.client.send_file(event.chat_id, scann, reply_to=event.reply_to_msg_id)243    await xx.delete()244    os.remove(ultt)245    os.remove("o.png")246    os.remove(scann)247 248 249@ultroid_cmd(250    pattern="pdsave( (.*)|$)",251)252async def savepdf(event):253    ok = await event.get_reply_message()254    if not (ok and (ok.media)):255        await eor(256            event,257            "`Reply to Images/pdf which u want to merge as a single pdf..`",258        )259        return260    ultt = await ok.download_media()261    if ultt.endswith(("png", "jpg", "jpeg", "webp")):262        xx = await event.eor(get_string("com_1"))263        image = cv2.imread(ultt)264        original_image = image.copy()265        ratio = image.shape[0] / 500.0266        h_, _v = image.shape[:2]267        m_ = 500 / float(h_)268        image = cv2.resize(image, (int(_v * m_), 500), interpolation=cv2.INTER_AREA)269        image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)270        image_y = np.zeros(image_yuv.shape[:2], np.uint8)271        image_y[:, :] = image_yuv[:, :, 0]272        image_blurred = cv2.GaussianBlur(image_y, (3, 3), 0)273        edges = cv2.Canny(image_blurred, 50, 200, apertureSize=3)274        contours, hierarchy = cv2.findContours(275            edges,276            cv2.RETR_EXTERNAL,277            cv2.CHAIN_APPROX_SIMPLE,278        )279        polygons = []280        for cnt in contours:281            hull = cv2.convexHull(cnt)282            polygons.append(283                cv2.approxPolyDP(hull, 0.01 * cv2.arcLength(hull, True), False),284            )285            sortedPoly = sorted(polygons, key=cv2.contourArea, reverse=True)286            cv2.drawContours(image, sortedPoly[0], -1, (0, 0, 255), 5)287            simplified_cnt = sortedPoly[0]288        if len(simplified_cnt) == 4:289            try:290                from skimage.filters import threshold_local291            except ImportError:292                LOGS.info(f"Scikit-Image is not Installed.")293                await xx.edit(294                    "`Installing Scikit-Image...\nThis may take some long...`"295                )296                _, __ = await bash("pip install scikit-image")297                LOGS.info(_)298                from skimage.filters import threshold_local299            cropped_image = four_point_transform(300                original_image,301                simplified_cnt.reshape(4, 2) * ratio,302            )303            gray_image = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2GRAY)304            T = threshold_local(gray_image, 11, offset=10, method="gaussian")305            ok = (gray_image > T).astype("uint8") * 255306        if len(simplified_cnt) != 4:307            ok = cv2.detailEnhance(original_image, sigma_s=10, sigma_r=0.15)308        cv2.imwrite("o.png", ok)309        image1 = Image.open("o.png")310        im1 = image1.convert("RGB")311        a = check_filename("pdf/scan.pdf")312        im1.save(a)313        await xx.edit(314            f"Done, Now Reply Another Image/pdf if completed then use {HNDLR}pdsend to merge nd send all as pdf",315        )316        os.remove("o.png")317    elif ultt.endswith(".pdf"):318        a = check_filename("pdf/scan.pdf")319        await event.client.download_media(ok, a)320        await eor(321            event,322            f"Done, Now Reply Another Image/pdf if completed then use {HNDLR}pdsend to merge nd send all as pdf",323        )324    else:325        await event.eor("`Reply to a Image/pdf only...`")326    os.remove(ultt)327 328 329@ultroid_cmd(330    pattern="pdsend( (.*)|$)",331)332async def sendpdf(event):333    if not os.path.exists("pdf/scan.pdf"):334        await eor(335            event,336            "first select pages by replying .pdsave of which u want to make multi page pdf file",337        )338        return339    msg = event.pattern_match.group(1).strip()340    ok = f"{msg}.pdf" if msg else "My PDF File.pdf"341    merger = PdfFileMerger()342    afl = glob.glob("pdf/*")343    ok_ = [*sorted(afl)]344    for item in ok_:345        if item.endswith("pdf"):346            merger.append(item)347    merger.write(ok)348    await event.client.send_file(event.chat_id, ok_, reply_to=event.reply_to_msg_id)349    os.remove(ok_)350    shutil.rmtree("pdf/")351    os.makedirs("pdf/")352