Best Python code snippet using slash
EndToEndTest.py
Source:EndToEndTest.py  
1# coding=UTF-82u"""3Py_Pov 0.0.1 Copyright (c) Martin Tönnishoff, 2013.4based on:5PyPov-0.0.X Copyright (c) Simon Burton, 20036See LICENSE file.7Some modifications by W.T. Bridgman, 2006-2007.8@TODO: Add rendering tests that call povray to make sure it works9"""10import os11import unittest12import difflib13from pov.atmeff.Fog import Fog14from pov.atmeff.SkySphere import SkySphere15from pov.basic.SceneFile import SceneFile16from pov.basic.Vector import Vector, x, y, z17from pov.basic.Color import Color18from pov.global_settings.GlobalSettings import GlobalSettings19from pov.finite_solid.Sphere import Sphere20from pov.infinite_solid.Plane import Plane21from pov.language_directive.Version import Version22from pov.language_directive.Default import Default23from pov.language_directive.Include import Include24from pov.object_modifier.Translate import Translate25from pov.other.Camera import Camera26from pov.other.LightSource import LightSource27from pov.texture.Finish import Finish28from pov.texture.Texture import Texture29from pov.texture.Pigment import Pigment30from pov.texture.ColorMap import ColorMap31from pov.texture.Normal import Normal32from pov.texture.Reflection import Reflection33from pov.texture.ImageMap import ImageMap34from pov.texture.Filter import Filter35class EndToEndTestCase(unittest.TestCase):36    """End To End Tests."""37    # @unittest.skip38    def test_scene1(self):39        """40        Test Scene 1.41        Example taken from:42        http://www.f-lohmueller.de/pov_tut/basic/povkurs3.htm43        """44        lsep = os.linesep45        ref = "#version 3.6;" + lsep46        ref += "global_settings {" + lsep47        ref += "  assumed_gamma 1.0" + lsep48        ref += "}" + lsep49        ref += "#default {" + lsep50        ref += "  finish {" + lsep51        ref += "    ambient 0.1" + lsep52        ref += "    diffuse 0.9" + lsep53        ref += "  }" + lsep54        ref += "}" + lsep55        ref += "#include \"pov/tests/fixture/colors.inc\"" + lsep56        ref += "#include \"pov/tests/fixture/textures.inc\"" + lsep57        ref += "camera {" + lsep58        ref += "  location <0.0, 1.0, -3.0>" + lsep59        ref += "  angle 75" + lsep60        ref += "  right <1.33333333333, 0.0, 0.0>" + lsep61        ref += "  look_at <0.0, 1.0, 0.0>" + lsep62        ref += "}" + lsep63        ref += "light_source {" + lsep64        ref += "  <1500, 3000, -2500>" + lsep65        ref += "  color White" + lsep66        ref += "}" + lsep67        ref += "plane {" + lsep68        ref += "  <0.0, 1.0, 0.0>, 1.0" + lsep69        ref += "  texture {" + lsep70        ref += "    pigment {" + lsep71        ref += "      bozo" + lsep72        ref += "      color_map {" + lsep73        ref += "        [0.0 color rgb <0.05, 0.15, 0.45>]" + lsep74        ref += "        [0.5 color rgb <0.05, 0.15, 0.45>]" + lsep75        ref += "        [0.85 color rgb <0.2, 0.2, 0.2>]" + lsep76        ref += "        [1.0 color rgb <0.5, 0.5, 0.5>]" + lsep77        ref += "        [0.7 color rgb <1.0, 1.0, 1.0>]" + lsep78        ref += "      }" + lsep79        ref += "      scale <2.5, 2.5, 3.75>" + lsep80        ref += "      translate <0.0, 0.0, 0.0>" + lsep81        ref += "      turbulence 0.92" + lsep82        ref += "    }" + lsep83        ref += "    finish {" + lsep84        ref += "      ambient 1.0" + lsep85        ref += "      diffuse 0.0" + lsep86        ref += "    }" + lsep87        ref += "  }" + lsep88        ref += "  hollow" + lsep89        ref += "  scale 10000.0" + lsep90        ref += "}" + lsep91        ref += "fog {" + lsep92        ref += "  color rgb <0.8, 0.8, 0.8>" + lsep93        ref += "  turbulence 1.8" + lsep94        ref += "  fog_offset 0.1" + lsep95        ref += "  fog_alt 1.5" + lsep96        ref += "  fog_type 2" + lsep97        ref += "  distance 50.0" + lsep98        ref += "}" + lsep99        ref += "plane {" + lsep100        ref += "  <0.0, 1.0, 0.0>, 0.0" + lsep101        ref += "  texture {" + lsep102        ref += "    pigment {" + lsep103        ref += "      color rgb <0.22, 0.45, 0.0>" + lsep104        ref += "    }" + lsep105        ref += "    normal {" + lsep106        ref += "      bumps 0.75" + lsep107        ref += "      scale 0.015" + lsep108        ref += "    }" + lsep109        ref += "    finish {" + lsep110        ref += "      phong 0.1" + lsep111        ref += "    }" + lsep112        ref += "  }" + lsep113        ref += "}" + lsep114        ref += "sphere {" + lsep115        ref += "  <0.0, 0.0, 0.0>, 0.75" + lsep116        ref += "  texture {" + lsep117        ref += "    pigment {" + lsep118        ref += "      color rgb <0.9, 0.55, 0.0>" + lsep119        ref += "    }" + lsep120        ref += "    finish {" + lsep121        ref += "      phong 1.0" + lsep122        ref += "    }" + lsep123        ref += "  }" + lsep124        ref += "  translate <0.85, 1.1, 0.0>" + lsep125        ref += "}" + lsep126        fix = SceneFile('test.pov')127        fix.append(Version(3.6))128        fix.append(129            GlobalSettings(assumed_gamma=1.0)130        )131        fix.append(132            Default(133                Finish(134                    ambient=0.1,135                    diffuse=0.9136                )137            )138        )139        fix.append(140            Include('pov/tests/fixture/colors.inc'),141            Include('pov/tests/fixture/textures.inc')142        )143        # @TODO: Read from Config144        image_width = 800145        # @TODO: Read from Config146        image_height = 600147        fix.append(148            Camera(149                location=Vector(0.0, 1.0, -3.0),150                look_at=Vector(0.0, 1.0, 0.0),151                right=(x * image_width / image_height),152                angle=75153            ),154            LightSource(155                Vector(1500, 3000, -2500),156                color='White'157            )158        )159        fix.append(160            Plane(161                Vector(0.0, 1.0, 0.0),162                1.0,163                Texture(164                    Pigment(165                        ColorMap({166                            0.00: Color(rgb=Vector(0.05, 0.15, 0.45)),167                            0.50: Color(rgb=Vector(0.05, 0.15, 0.45)),168                            0.70: Color(rgb=Vector(1.0, 1.0, 1.0)),169                            0.85: Color(rgb=Vector(0.2, 0.2, 0.2)),170                            1.00: Color(rgb=Vector(0.5, 0.5, 0.5))171                        }),172                        bozo=True,173                        turbulence=0.92,174                        scale=Vector(1.0, 1.0, 1.5) * 2.5,175                        translate=Vector(0.0, 0.0, 0.0)176                    ),177                    Finish(178                        ambient=1.0,179                        diffuse=0.0180                    )181                ),182                hollow=True,183                scale=10000.0184            )185        )186        fix.append(187            Fog(188                Color(rgb=Vector(1, 1, 1)) * 0.8,189                fog_type=2,190                turbulence=1.8,191                fog_offset=0.1,192                fog_alt=1.5,193                distance=50.0194            )195        )196        fix.append(197            Plane(198                Vector(0.0, 1.0, 0.0),199                0.0,200                Texture(201                    Pigment(202                        Color(rgb=Vector(0.22, 0.45, 0.0))203                    ),204                    Normal(205                        bumps=0.75,206                        scale=0.015207                    ),208                    Finish(209                        phong=0.1210                    )211                )212            ),213            Sphere(214                Vector(0.0, 0.0, 0.0),215                0.75,216                Texture(217                    Pigment(218                        Color(rgb=Vector(0.9, 0.55, 0.0))219                    ),220                    Finish(221                        phong=1.0222                    )223                ),224                Translate(Vector(0.85, 1.1, 0.0))225            )226        )227        # ----------------------------------------------------228        msg = '\n' + ''.join(difflib.ndiff(229            ref.splitlines(1),230            str(fix).splitlines(1)231        ))232        self.assertEqual(ref, str(fix), msg)233    # @unittest.skip234    def test_examples_basic_scene(self):235        """Test examples/basic_scene.pov."""236        lsep = os.linesep237        ref = '#version 3.6;' + lsep238        ref += '#include "pov/tests/fixture/colors.inc"' + lsep239        ref += 'global_settings {' + lsep240        ref += '  assumed_gamma 1.0' + lsep241        ref += '}' + lsep242        ref += 'camera {' + lsep243        ref += '  location <0.0, 0.5, -4.0>' + lsep244        ref += '  look_at <0.0, 0.0, 0.0>' + lsep245        ref += '  right <1.33333333333, 0.0, 0.0>' + lsep246        ref += '  direction <0.0, 0.0, 1.5>' + lsep247        ref += '}' + lsep248        ref += 'sky_sphere {' + lsep249        ref += '  pigment {' + lsep250        ref += '    color_map {' + lsep251        ref += '      [0.0 color rgb <0.6, 0.7, 1.0>]' + lsep252        ref += '      [0.7 color rgb <0.0, 0.1, 0.8>]' + lsep253        ref += '    }' + lsep254        ref += '    gradient <0.0, 1.0, 0.0>' + lsep255        ref += '  }' + lsep256        ref += '}' + lsep257        ref += 'light_source {' + lsep258        ref += '  <0.0, 0.0, 0.0>' + lsep259        ref += '  color rgb <1.0, 1.0, 1.0>' + lsep260        ref += '  translate <-30.0, 30.0, -30.0>' + lsep261        ref += '}' + lsep262        ref += 'plane {' + lsep263        ref += '  <0.0, 1.0, 0.0>, -1' + lsep264        ref += '  pigment {' + lsep265        ref += '    color rgb <0.7, 0.5, 0.3>' + lsep266        ref += '  }' + lsep267        ref += '}' + lsep268        ref += 'sphere {' + lsep269        ref += '  <0.0, 0.0, 0.0>, 1.0' + lsep270        ref += '  texture {' + lsep271        ref += '    pigment {' + lsep272        ref += '      radial color_map {' + lsep273        ref += '        [0.0 color rgb <1.0, 0.4, 0.2>]' + lsep274        ref += '        [1.0 color rgb <1.0, 0.4, 0.2>]' + lsep275        ref += '        [0.66 color rgb <0.4, 1.0, 0.2>]' + lsep276        ref += '        [0.33 color rgb <0.2, 0.4, 1.0>]' + lsep277        ref += '      }' + lsep278        ref += '      frequency 8' + lsep279        ref += '    }' + lsep280        ref += '    finish {' + lsep281        ref += '      specular 0.6' + lsep282        ref += '    }' + lsep283        ref += '  }' + lsep284        ref += '}' + lsep285        fix = SceneFile('test.pov')286        fix.append(Version(3.6))287        fix.append(Include('pov/tests/fixture/colors.inc'))288        fix.append(289            GlobalSettings(assumed_gamma=1.0)290        )291        # @TODO: Read from Config292        image_width = 800293        # @TODO: Read from Config294        image_height = 600295        fix.append(296            Camera(297                location=Vector(0.0, 0.5, -4.0),298                direction=1.5 * z,299                right=x * image_width / image_height,300                look_at=Vector(0.0, 0.0, 0.0)301            )302        )303        fix.append(304            SkySphere(305                Pigment(306                    ColorMap(307                        {0.0: Color(rgb=Vector(0.6, 0.7, 1.0)),308                         0.7: Color(rgb=Vector(0.0, 0.1, 0.8))}309                    ),310                    gradient=y311                )312            ),313            LightSource(314                (0.0, 0.0, 0.0),315                Color(rgb=Vector(1.0, 1.0, 1.0)),316                translate=Vector(-30.0, 30.0, -30.0)317            )318        )319        fix.append(320            Plane(321                y, -1,322                Pigment(323                    Color(rgb=Vector(0.7, 0.5, 0.3))324                )325            ),326            Sphere(327                Vector(0.0, 0.0, 0.0),328                1.0,329                Texture(330                    Pigment(331                        radial=ColorMap({332                            0.00: Color(rgb=Vector(1.0, 0.4, 0.2)),333                            0.33: Color(rgb=Vector(0.2, 0.4, 1.0)),334                            0.66: Color(rgb=Vector(0.4, 1.0, 0.2)),335                            1.00: Color(rgb=Vector(1.0, 0.4, 0.2))336                        }),337                        frequency=8338                    ),339                    Finish(340                        specular=0.6341                    )342                )343            )344        )345        # ----------------------------------------------------346        msg = '\n' + ''.join(difflib.ndiff(347            ref.splitlines(1),348            str(fix).splitlines(1)349        ))350        self.assertEqual(ref, str(fix), msg)351    # @unittest.skip352    def test_checkered_floor_example(self):353        """Test examples/checkered_floor.pov."""354        lsep = os.linesep355        ref = '#version 3.6;' + lsep356        ref += '#include "pov/tests/fixture/colors.inc"' + lsep357        ref += 'global_settings {' + lsep358        ref += '  assumed_gamma 1.0' + lsep359        ref += '  max_trace_level 5' + lsep360        ref += '}' + lsep361        ref += 'camera {' + lsep362        ref += '  location <0.0, 0.5, -4.0>' + lsep363        ref += '  look_at <0.0, 0.0, 0.0>' + lsep364        ref += '  right <1.33333333333, 0.0, 0.0>' + lsep365        ref += '  direction <0.0, 0.0, 1.5>' + lsep366        ref += '}' + lsep367        ref += 'sky_sphere {' + lsep368        ref += '  pigment {' + lsep369        ref += '    color_map {' + lsep370        ref += '      [0.0 color rgb <0.6, 0.7, 1.0>]' + lsep371        ref += '      [0.7 color rgb <0.0, 0.1, 0.8>]' + lsep372        ref += '    }' + lsep373        ref += '    gradient <0.0, 1.0, 0.0>' + lsep374        ref += '  }' + lsep375        ref += '}' + lsep376        ref += 'light_source {' + lsep377        ref += '  <0, 0, 0>' + lsep378        ref += '  color rgb <1, 1, 1>' + lsep379        ref += '  translate <-30, 30, -30>' + lsep380        ref += '}' + lsep381        ref += 'plane {' + lsep382        ref += '  <0.0, 1.0, 0.0>, -1' + lsep383        ref += '  texture {' + lsep384        ref += '    pigment {' + lsep385        ref += '      checker' + lsep386        ref += '      color rgb <1, 1, 1>' + lsep387        ref += '      color rgbft <0, 0, 1, 0, 0>' + lsep388        ref += '      scale 0.5' + lsep389        ref += '    }' + lsep390        ref += '    finish {' + lsep391        ref += '      ambient 0.1' + lsep392        ref += '      diffuse 0.8' + lsep393        ref += '    }' + lsep394        ref += '  }' + lsep395        ref += '}' + lsep396        ref += 'sphere {' + lsep397        ref += '  <0, 0, 0>, 1' + lsep398        ref += '  texture {' + lsep399        ref += '    pigment {' + lsep400        ref += '      color rgb <0.8, 0.8, 1.0>' + lsep401        ref += '    }' + lsep402        ref += '    finish {' + lsep403        ref += '      conserve_energy' + lsep404        ref += '      reflection {' + lsep405        ref += '        metallic' + lsep406        ref += '        0.8' + lsep407        ref += '      }' + lsep408        ref += '      diffuse 0.3' + lsep409        ref += '      ambient 0.0' + lsep410        ref += '      specular 0.6' + lsep411        ref += '    }' + lsep412        ref += '  }' + lsep413        ref += '}' + lsep414        fix = SceneFile('test.pov')415        fix.append(Version(3.6))416        fix.append(Include('pov/tests/fixture/colors.inc'))417        fix.append(418            GlobalSettings(419                assumed_gamma=1.0,420                max_trace_level=5421            )422        )423        # @TODO: Read from Config424        image_width = 800425        # @TODO: Read from Config426        image_height = 600427        fix.append(428            Camera(429                location=Vector(0.0, 0.5, -4.0),430                direction=1.5 * z,431                right=x * image_width / image_height,432                look_at=Vector(0.0, 0.0, 0.0)433            ),434            SkySphere(435                Pigment(436                    ColorMap({437                        0.0: Color(rgb=Vector(0.6, 0.7, 1.0)),438                        0.7: Color(rgb=Vector(0.0, 0.1, 0.8))439                    }),440                    gradient=y441                )442            ),443            LightSource(444                Vector(0, 0, 0),445                Color(rgb=Vector(1, 1, 1)),446                Translate(Vector(-30, 30, -30))447            )448        )449        fix.append(450            Plane(451                y, -1,452                Texture(453                    Pigment(454                        Color(rgb=Vector(1, 1, 1)),455                        Color(blue=1),456                        checker=True,457                        scale=0.5458                    ),459                    Finish(460                        diffuse=0.8,461                        ambient=0.1462                    )463                )464            ),465            Sphere(466                (0, 0, 0), 1,467                Texture(468                    Pigment(469                        Color(rgb=Vector(0.8, 0.8, 1.0))470                    ),471                    Finish(472                        Reflection(473                            0.8,474                            metallic=True475                        ),476                        diffuse=0.3,477                        ambient=0.0,478                        specular=0.6,479                        conserve_energy=True480                    )481                )482            )483        )484        # ----------------------------------------------------485        msg = '\n' + ''.join(difflib.ndiff(486            ref.splitlines(1),487            str(fix).splitlines(1)488        ))489        self.assertEqual(ref, str(fix), msg)490    # @unittest.skip491    def test_image_map_example(self):492        """@TODO: Apidoc."""493        ref = os.linesep.join([494            '#version 3.6;',495            '#include "pov/tests/fixture/colors.inc"',496            'global_settings {',497            '  assumed_gamma 1.0',498            '}',499            'camera {',500            '  location <0.0, 0.0, -4.0>',501            '  look_at <0.0, 0.0, 0.0>',502            '  right <1.33333333333, 0.0, 0.0>',503            '  direction <0.0, 0.0, 2.0>',504            '}',505            'sky_sphere {',506            '  pigment {',507            '    color_map {',508            '      [0.0 color rgbft <0, 0, 0.6, 0, 0>]',509            '      [1.0 color rgb <1, 1, 1>]',510            '    }',511            '    gradient <0.0, 1.0, 0.0>',512            '  }',513            '}',514            'light_source {',515            '  <0, 0, 0>',516            '  color rgb <1, 1, 1>',517            '  translate <-30, 30, -30>',518            '}',519            'plane {',520            '  <0.0, 1.0, 0.0>, -1',521            '  texture {',522            '    pigment {',523            '      checker',524            '      color rgb <1, 1, 1>',525            '      color rgbft <0, 0, 1, 0, 0>',526            '      scale 0.5',527            '    }',528            '    finish {',529            '      reflection 0.2',530            '    }',531            '  }',532            '}',533            'plane {',534            '  <0.0, 0.0, 1.0>, -1',535            '  texture {',536            '    pigment {',537            '      image_map {',538            '        png "test.png"',539            '        filter 0 0.8',540            '        filter 1 0.8',541            '        once',542            '        interpolate 2',543            '      }',544            '      translate <-0.5, -0.5, -0.0>',545            '      scale 2',546            '    }',547            '    finish {',548            '      ambient 0.3',549            '    }',550            '  }',551            '}',552            ''553        ])554        fix = SceneFile('test.pov')555        fix.append(Version(3.6))556        fix.append(Include('pov/tests/fixture/colors.inc'))557        fix.append(558            GlobalSettings(559                assumed_gamma=1.0,560            )561        )562        # @TODO: Read from Config563        image_width = 800564        # @TODO: Read from Config565        image_height = 600566        fix.append(567            Camera(568                location=Vector(0.0, 0.0, -4.0),569                direction=2 * z,570                right=x * image_width / image_height,571                look_at=Vector(0.0, 0.0, 0.0)572            ),573            SkySphere(574                Pigment(575                    ColorMap({576                        0.0: Color(blue=0.6),577                        1.0: Color(rgb=Vector(1, 1, 1))578                    }),579                    gradient=y580                )581            ),582            LightSource(583                Vector(0, 0, 0),584                Color(rgb=Vector(1, 1, 1)),585                Translate(Vector(-30, 30, -30))586            )587        )588        fix.append(589            Plane(590                y, -1,591                Texture(592                    Pigment(593                        Color(rgb=Vector(1, 1, 1)),594                        Color(blue=1),595                        checker=True,596                        scale=0.5597                    ),598                    Finish(599                        reflection=0.2600                    )601                )602            ),603            Plane(604                z, -1,605                Texture(606                    Pigment(607                        ImageMap(608                            'png', 'test.png',609                            Filter(0, 0.8),610                            Filter(1, 0.8),611                            interpolate=2,612                            once=True,613                        ),614                        Translate(-0.5 * (x + y)),615                        scale=2616                    ),617                    Finish(618                        ambient=0.3619                    )620                )621            )622        )623        # ----------------------------------------------------624        msg = '\n' + ''.join(difflib.ndiff(625            ref.splitlines(1),626            str(fix).splitlines(1)627        ))...main.py
Source:main.py  
1import os2import sys3import threading4import pikepdf5from tqdm import tqdm6#####7# Author Mustafa Azim8# HackPDF Tool9#####10dsep = os.sep11lsep = os.linesep12rsep = '\r'13ver = '0.1'14event = threading.Event()15completed = threading.Event()16def progressbar(progress: int):17    try:18        bar = tqdm(range(progress))19        bar.colour = 'GREEN'20        bar.unit = ' PDF/Sec'21        for i in bar:22            event.wait(0.01)23            event.clear()24        completed.set()25    except Exception as ex:26        print(f'Error progressbar    {ex}   {ex.args}')27        main.event = False28        completed.set()29def findpdf() -> list:30    files = os.listdir(os.getcwd())31    pdf = []32    completed.clear()33    event.clear()34    th = threading.Thread(target=progressbar, args=(100,))35    th.start()36    for f in files:37        if f.endswith('.pdf'):38            pdf.append(f)39            event.set()40    event.set()41    if len(pdf) > 0:42        os.makedirs(name='Output', exist_ok=True)43        print(f'Working on PDF' + f's:{rsep}' if len(pdf) > 1 else f':{rsep}')44        for p in pdf:45            print(f'-   {p}{rsep}')46        return pdf47    else:48        print(f'No PDF file(s) found!{lsep}')49def removepass():50    pdf = findpdf()51    path = os.getcwd()52    try:53        for pdffile in pdf:54            password = ''55            while True:56                try:57                    with pikepdf.Pdf.open(filename_or_stream=pdffile, password=password,58                                          allow_overwriting_input=True) as pfile:59                        pfile.save(filename_or_stream=f'{path}{dsep}Output{dsep}{pdffile}', encryption=False)60                        pfile.close()61                        break62                except Exception as ex:63                    for e in ex.args:64                        if str(e).lower().__contains__('invalid password'):65                            password = input(f'{pdffile} protected, enter password:')66                        else:67                            break68    except Exception as ex:69        print(f'Error removepass {ex.args}')70def merge():71    pdf = findpdf()72    path = os.getcwd()73    ordinalpdf = []74    try:75        unordered = []76        ordered = []77        isstringarray = False78        for i in pdf:79            n = str(i).split('_') if (str(i).__contains__('_')) else i80            if type(n) is list:81                if len(n) > 0 and n[0].isnumeric():82                    isstringarray = False83            elif str(n).isnumeric() and not str(n).isalpha():84                isstringarray = False85            else:86                isstringarray = True87                break88        if not isstringarray:89            for i in pdf:90                n = str(i).split('_') if (str(i).__contains__('_')) else i91                if type(n) is list:92                    if len(n) > 0 and n[0].isnumeric():93                        unordered.append(int(n[0]))94                elif str(n).isnumeric() and not str(n).isalpha():95                    unordered.append(int(n[0]))96                else:97                    unordered.append(n)98            _unordered = unordered99            cnt = len(unordered) - 1100            while cnt >= 0:101                if type(_unordered[cnt]) == int:102                    m = min(_unordered)103                    ordered.append(m)104                    _unordered.remove(m)105                elif type(_unordered[cnt]) == str:106                    ordered = _unordered107                    break108                cnt -= 1109            if len(ordinalpdf) < 1:110                for o in ordered:111                    for p in pdf:112                        if str(p).startswith(str(o)):113                            ordinalpdf.append(p)114                            break115        else:116            ordinalpdf = pdf117        m_password = ''118        if len(ordinalpdf) > 0:119            while True:120                try:121                    with pikepdf.Pdf.open(filename_or_stream=ordinalpdf[0], password=m_password,122                                          allow_overwriting_input=True) as masterpdf:123                        ordained = ordinalpdf124                        ordained.remove(ordained[0])125                        completed.clear()126                        event.clear()127                        th = threading.Thread(target=progressbar, args=(len(pdf),))128                        th.start()129                        for pdffile in ordained:130                            password = ''131                            event.clear()132                            while True:133                                try:134                                    with pikepdf.Pdf.open(filename_or_stream=pdffile, password=password,135                                                          allow_overwriting_input=True) as pfile:136                                        masterpdf.pages.extend(pfile.pages)137                                        event.set()138                                        pfile.close()139                                        break140                                except Exception as ex:141                                    for e in ex.args:142                                        if str(e).lower().__contains__('invalid password'):143                                            password = input(f'{pdffile} protected, enter password:')144                                        else:145                                            break146                        event.set()147                        masterpdf.save(filename_or_stream=f'{path}{dsep}Output{dsep}Merged.pdf', encryption=False)148                        break149                except Exception as ex:150                    for e in ex.args:151                        if str(e).lower().__contains__('invalid password'):152                            m_password = input(f'{pdffile} protected, enter password:')153                        else:154                            break155    except Exception as ex:156        print(f'Error merge {ex.args}')157def extractimages():158    pdf = findpdf()159    path = os.getcwd()160    try:161        for pdffile in pdf:162            password = ''163            while True:164                try:165                    with pikepdf.Pdf.open(filename_or_stream=pdffile, password=password,166                                          allow_overwriting_input=True) as pfile:167                        os.makedirs(f'Output{dsep}{pdffile}_imanges', exist_ok=True)168                        for p in pfile.pages:169                            for i in p.images.keys():170                                image = p.images[i]171                                pdfi = pikepdf.PdfImage(image)172                                pimage = pdfi.as_pil_image()173                                pimage.save(fp=f'{path}{dsep}Output{dsep}{pdffile}_imanges{dsep}{i}_page{p.index}.jpg')174                        pfile.close()175                        break176                except Exception as ex:177                    for e in ex.args:178                        if str(e).lower().__contains__('invalid password'):179                            password = input(f'{pdffile} protected, enter password:')180                        else:181                            break182    except Exception as ex:183        print(f'Error extractimages {ex.args}')184def options():185    print(f'What would you like to do for PDF file(s):{lsep}{lsep}'186          f'[1] Remove Password from file(s) (Requires old Password){lsep}'187          f'[2] Extract Images from file(s){lsep}'188          f'[3] Merge PDF files {lsep}'189          f'    if PDF files\' names contain ordinal number (n_) where n is integer number followed by \'_\'{lsep}'190          f'the merge will be executed in order.'191          f'Example: 1_a.pdf 2_a.pdf 3_a.pdf will be merged in order as 1_a.pdf 2_a.pdf 3_a.pdf and so on{lsep}'192          f'[4] Exit{lsep}{lsep}'193          f'          Processed files will be in Output folder in the script\'s directory         {lsep}'194          f'{os.getcwd()}{dsep}Output{lsep}'195          f'==========================================================================================================='196          f'{lsep}{lsep}'197          f'          PDFs files should be copied to the script\'s directory        {lsep}'198          f'{os.getcwd()}{lsep}'199          f'==========================================================================================================='200          f'{lsep}{lsep}')201    try:202        inp = input(f'Enter the option number:{lsep}')203        match inp:204            case '1':205                removepass()206            case '2':207                extractimages()208            case '3':209                merge()210            case '4':211                pass212            case _:213                pass214    except Exception as ex:215        print(f'options   {ex.args}')216def version():217    print(f'HackPDF tool    {ver}v    Mustafa Azim'218          f'    mustafaz.com{lsep}')219def main():220    try:221        os.chdir(str(__file__).removesuffix('/main').removesuffix('/main.py'))222        version()223        options()224        completed.wait(timeout=300)225        print(f'Done!   Exiting...')226        sys.exit()227    except KeyboardInterrupt:228        sys.exit(0)229if __name__ == '__main__':...PortScannerResultsHandler.py
Source:PortScannerResultsHandler.py  
1#! /usr/bin/python32from Threading import Thread3from custom_modules.NmapPortScanner import is_port_open as ipo4from custom_modules.TypeTester import arg_is_a_string as aias, arg_is_a_list as aial5from custom_modules.FileOperator import append_file as af6from custom_modules.PlatformConstants import LINE_SEP as lsep7def handle_results(results):8    protocols = None9    command = None10    scan_info = None11    dict_tcp_keys = None12    csv = None13    tcp = None14    state = None15    product = None16    reason = None17    name = None18    version = None19    extra = None20    conf = None21    # results = ipo(hosts, ports, verbose, timeout, report)22    """if results[host].state:23        state = results[host].state()24    if results[host].all_protocols:25        protocols = results[host].all_protocols()26    if results.command_line:27        command = results.command_line()28    if results.scaninfo:29        scan_info = results.scaninfo()30    if "tcp" in results[host]:31        dict_tcp_keys = results[host]["tcp"].keys()32    if results.csv:33        csv = results.csv"""34    all_hosts = results.all_hosts()35    for _host in all_hosts:36        if results[_host].state:37            state = results[_host].state()38        if results[_host].all_protocols:39            protocols = results[_host].all_protocols()40        if results.command_line:41            command = results.command_line()42        if results.scaninfo:43            scan_info = results.scaninfo()44        if "tcp" in results[_host]:45            dict_tcp_keys = results[_host]["tcp"].keys()46        if results.csv:47            csv = results.csv()48        print("-" * 100 + "\n")49        print("Host:\t{}".format(_host))50        print("State:\t{}".format(state))51        # print("Command:\t{}".format(command))52        # print("Scann Info:\t{}".format(scan_info))53        # print("CSV:\t{}".format(csv))54        # print("-" * 100 + "\n\n")55        if protocols:56            for protocol in protocols:57                info = scan_info[protocol]58                print("Protocol:\t{}".format(protocol))59                print(60                    "Scan Info =\t\tAction: {}\tPorts: {}".format(61                        info["method"], info["services"]62                    )63                )64                if protocol == "tcp":65                    dict_tcp_keys = results[_host][protocol].keys()66                    print("Open Ports")67                    print(*dict_tcp_keys, sep="\t")68                    print("\n")69                    for tcp_key in dict_tcp_keys:70                        key = results[_host][protocol][tcp_key]71                        # print("TCP Key:\t{}".format(key))72                        state = key["state"]73                        reason = key["reason"]74                        product = key["product"]75                        name = key["name"]76                        version = key["version"]77                        extra = key["extrainfo"]78                        conf = key["conf"]79                        cpe = key["cpe"]80                        print("Port:\t\t{}".format(tcp_key))81                        print("State:\t\t{}".format(state))82                        print("Reason:\t\t{}".format(reason))83                        print("Name:\t\t{}".format(name))84                        print("Product:\t\t{}".format(product))85                        print("Version:\t\t{}".format(version))86                        print("Extra:\t\t{}".format(extra))87                        print("Conf:\t\t{}".format(conf))88                        print("CPE:\t\t{}\n".format(cpe))89# Print results to file90def print_nmap_report(results):91    protocols = None92    scan_info = None93    dict_tcp_keys = None94    state = None95    product = None96    reason = None97    name = None98    version = None99    extra = None100    conf = None101    data = []102    line = ""103    all_hosts = results.all_hosts()104    for _host in all_hosts:105        if results[_host].state:106            state = results[_host].state()107        if results[_host].all_protocols:108            protocols = results[_host].all_protocols()109        if results.command_line:110            command = results.command_line()111        if results.scaninfo:112            scan_info = results.scaninfo()113        if "tcp" in results[_host]:114            dict_tcp_keys = results[_host]["tcp"].keys()115        if results.csv:116            csv = results.csv()117        line = "-" * 100 + "{}".format(lsep)118        data.append(line)119        data.append("Host:\t{}{}".format(_host, lsep))120        data.append("State:\t{}{}".format(state, lsep))121        if protocols:122            for protocol in protocols:123                info = scan_info[protocol]124                data.append("Protocol:\t{}{}".format(protocol, lsep))125                data.append(126                    "Scan Info =\t\tAction: {}\tPorts: {}{}".format(127                        info["method"], info["services"], lsep128                    )129                )130                if protocol == "tcp":131                    dict_tcp_keys = results[_host][protocol].keys()132                    data.append("Open Ports{}".format(lsep))133                    line = ""134                    for dtk in dict_tcp_keys:135                        line += "{}\t".format(dtk)136                    data.append(line)137                    data.append("{}{}".format(lsep, lsep))138                    for tcp_key in dict_tcp_keys:139                        key = results[_host][protocol][tcp_key]140                        state = key["state"]141                        reason = key["reason"]142                        product = key["product"]143                        name = key["name"]144                        version = key["version"]145                        extra = key["extrainfo"]146                        conf = key["conf"]147                        cpe = key["cpe"]148                        data.append("Port:\t\t{}{}".format(tcp_key, lsep))149                        data.append("State:\t\t{}{}".format(state, lsep))150                        data.append("Reason:\t\t{}{}".format(reason, lsep))151                        data.append("Name:\t\t{}{}".format(name, lsep))152                        data.append("Product:\t\t{}{}".format(product, lsep))153                        data.append("Version:\t\t{}{}".format(version, lsep))154                        data.append("Extra:\t\t{}{}".format(extra, lsep))155                        data.append("Conf:\t\t{}{}".format(conf, lsep))156                        data.append("CPE:\t\t{}{}{}".format(cpe, lsep, lsep))157    results = af("nmap-port-scanner-results.txt", data)158    return results159def print_report(data):160    if not data == None:161        if aial(data):162            collection = []163            for d in data:164                collection.append(d + "{}".format(lsep))165            if len(collection) > 0:166                report = af("port-scanner-results.txt", collection)167                return report...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
