frompathlibimportPathfromtypingimportAnnotatedimporttyperfromtqdmimporttqdmfrom.importdecrypt_pdfapp=typer.Typer(name="decryptpdf",help="Decrypt PDF files using a password.",context_settings={"help_option_names":["-h","--help"]},)
[docs]@app.command()defcli(path:Annotated[Path,typer.Argument()],password:Annotated[str,typer.Option("-p","--password",prompt=True,hide_input=True,help="The password to decrypt the PDF file.",),],overwrite:Annotated[bool,typer.Option("-o/-n","--overwrite/--no-overwrite",help="Overwrite the original file, ""or save decrypted file as .decrypted.pdf",),]=True,)->None:""" Decrypts a PDF file. If PATH is a directory, recursively searches for PDF files. If PATH is a file and does not exist, checks if PATH with ".pdf" extension exists. If the file is not encrypted, skips it. """path_=Path(path)# If the path is a directory, recursively search for PDF files.# If not found, check if the path is a file and if it has a PDF extension.ifpath_.is_dir():input_paths=[pforpinpath_.rglob("*")ifp.suffix.lower()==".pdf"]iflen(input_paths)==0:raiseFileNotFoundError(f"No PDF files found in {path_}.")elifpath_.exists():input_paths=[path_]elifpath_.with_suffix(".pdf").exists():input_paths=[path_.with_suffix(".pdf")]elifpath_.with_suffix(".PDF").exists():input_paths=[path_.with_suffix(".PDF")]else:raiseFileNotFoundError(f"File {path_} does not exist.")pbar=tqdm(input_paths,desc="Decrypting PDF files",disable=len(input_paths)==1)forinput_pathinpbar:ifoverwrite:output_path=input_pathelse:output_path=input_path.with_suffix(".decrypted.pdf")try:decrypt_pdf(input_path,output_path,password)exceptExceptionase:pbar.write(f"Failed to decrypt {input_path}: {e}")