├── .github └── workflows │ └── check-pull-request.yaml ├── .gitignore ├── LICENCE.md ├── README.md ├── docs ├── pdf-screenshot.png ├── terminology.md └── video-screenshot.png ├── fonts └── DejaVuSansCondensed.ttf ├── requirements.txt ├── src ├── __init__.py ├── content_segment_exporter.py ├── main.py ├── plot.py ├── subtitle_part.py ├── subtitle_segment_finder.py ├── subtitle_srt_parser.py ├── subtitle_webvtt_parser.py ├── time_utils.py └── video_segment_finder.py └── tests ├── __init__.py ├── snapshots ├── __init__.py ├── snap_test_main │ ├── video_1_with_srt_file.pdf │ ├── video_1_with_webvtt_file.pdf │ ├── video_1_without_subtitles.pdf │ ├── video_2_with_srt_file.pdf │ ├── video_2_with_webvtt_file.pdf │ ├── video_2_without_subtitles.pdf │ ├── video_7_with_srt_file.pdf │ ├── video_7_without_subtitles.pdf │ ├── video_8_with_srt_file.pdf │ ├── video_8_with_webvtt_file.pdf │ └── video_8_without_subtitles.pdf └── snap_test_subtitle_segment_finder.py ├── subtitles ├── subtitles_1.srt ├── subtitles_1.vtt ├── subtitles_2.srt ├── subtitles_2.vtt ├── subtitles_7.srt ├── subtitles_8.srt └── subtitles_8.vtt ├── test_main.py ├── test_subtitle_segment_finder.py ├── test_subtitle_srt_parser.py ├── test_subtitle_webvtt_parser.py ├── test_time_utils.py ├── test_video_segment_finder.py ├── utils ├── __init__.py └── pdf_snapshot.py └── videos ├── input_1.mp4 ├── input_2.mp4 ├── input_3.mp4 ├── input_4.mp4 ├── input_5.mp4 ├── input_6.mp4 ├── input_7.mp4 └── input_8.mp4 /.github/workflows/check-pull-request.yaml: -------------------------------------------------------------------------------- 1 | ################################################################## 2 | # A Github action used to check pull requests 3 | # More info at https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions 4 | ################################################################## 5 | 6 | name: Check the pull request automatically 7 | on: 8 | push: 9 | branches: [main] 10 | pull_request: 11 | branches: [main] 12 | 13 | jobs: 14 | run-tests: 15 | name: Runs all tests 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout branch 19 | uses: actions/checkout@v2 20 | 21 | - name: Setup Python 22 | uses: actions/setup-python@v4 23 | with: 24 | python-version: "3.9" 25 | 26 | - name: Cache dependencies 27 | uses: actions/cache@v3.0.11 28 | with: 29 | path: "**/node_modules" 30 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/requirements.txt') }} 31 | 32 | - name: Install dependencies 33 | run: | 34 | sudo apt install ghostscript 35 | sudo apt install imagemagick 36 | sudo apt install graphicsmagick 37 | sudo apt install pdftk 38 | 39 | # Remove the policy to allow pdf generation 40 | sudo rm /etc/ImageMagick-6/policy.xml 41 | 42 | python -m pip install --upgrade pip 43 | pip install -r requirements.txt 44 | 45 | - name: Run all test cases 46 | run: | 47 | python3 -m unittest discover 48 | 49 | run-app: 50 | name: Run the app 51 | runs-on: ubuntu-latest 52 | steps: 53 | - name: Checkout branch 54 | uses: actions/checkout@v2 55 | 56 | - name: Setup Python 57 | uses: actions/setup-python@v4 58 | with: 59 | python-version: "3.9" 60 | 61 | - name: Cache dependencies 62 | uses: actions/cache@v3.0.11 63 | with: 64 | path: "**/node_modules" 65 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/requirements.txt') }} 66 | 67 | - name: Install dependencies 68 | run: | 69 | python -m pip install --upgrade pip 70 | pip install -r requirements.txt 71 | 72 | - name: Run the app with sample input 73 | run: python3 -m src.main tests/videos/input_1.mp4 -s tests/subtitles/subtitles_1.vtt -o output.pdf 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.pkl 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | bin/ 117 | include/ 118 | share/ 119 | pyvenv.cfg 120 | 121 | # Spyder project settings 122 | .spyderproject 123 | .spyproject 124 | 125 | # Rope project settings 126 | .ropeproject 127 | 128 | # mkdocs documentation 129 | /site 130 | 131 | # mypy 132 | .mypy_cache/ 133 | .dmypy.json 134 | dmypy.json 135 | 136 | # Pyre type checker 137 | .pyre/ 138 | 139 | # pytype static type analyzer 140 | .pytype/ 141 | 142 | # Cython debug symbols 143 | cython_debug/ 144 | 145 | # vs code folder 146 | .vscode/ 147 | 148 | # temp folders generated by this project 149 | tmp/ 150 | plot-output/ 151 | output.pdf 152 | 153 | # Mac files 154 | .DS_Store -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Convert Lecture Videos to PDF 2 | 3 | ### Description 4 | 5 | Want to go through lecture videos faster without missing any information? Wish you can **read** the lecture video instead of watching it? Now you can! With this python app, you can convert lecture videos to PDF files! The PDF file will contain a screenshot of lecture slides presented in the video, along with a transcription of your instructor explaining those lecture slide. It can also handle instructors making annotations on their lecture slides and mild amounts of PowerPoint animations. 6 | 7 | ### Table of Contents 8 | 9 | - Walkthrough 10 | - Getting Started 11 | - Tweeking the Application 12 | - Next steps 13 | - Usage 14 | - Credits 15 | - License 16 | 17 | ### Walkthrough of this project 18 | 19 | Users will need to download a video file of their lecture. For instance, the video file might look like this: 20 | 21 |
22 |

23 | 24 |

25 |
26 | 27 | Users will also need a copy of the video's subtitles. 28 | 29 | After running the command line tool, they will get a PDF that looks like this: 30 | 31 |
32 |

33 | 34 |

35 |
36 | 37 | where each page contains an image of the lecture video, and a transcription of the instructor explaining about that slide. 38 | 39 | ### Getting Started 40 | 41 | 1. Ensure Python3 and Pip is installed on your machine 42 | 2. Next, install package dependencies by running: 43 | 44 | `pip3 install -r requirements.txt` 45 | 46 | 3. Now, run: 47 | 48 | `python3 -m src.main tests/videos/input_1.mp4 -s tests/subtitles/subtitles_1.vtt -o output.pdf` 49 | 50 | to generate a PDF of [this lecture video](tests/videos/input_1.mp4) with [these subtitles](```tests/subtitles/subtitles_1.vtt```) 51 | 52 | Note: If you don't want subtitles in the pdf, you can use the `-S` flag, like: 53 | 54 | `python3 -m src.main tests/videos/input_1.mp4 -S -o output.pdf` 55 | 56 | 4. The generated PDF will be saved as _output.pdf_ 57 | 58 | ### Running Tests 59 | 60 | 1. Install graphicsmagick, imagemagick, and pdftk on your machine 61 | 2. To run all unit tests, run `python3 -m unittest discover` 62 | 3. To run a specific unit tests (ex: tests/test_main.py), run `python3 -m unittest tests/test_main.py` 63 | 64 | Note: Running the `tests/test_main.py` takes a while 65 | 66 | ### Tweeking the Application 67 | 68 | This application uses computer vision with OpenCV to detect when the instructor has moved on to the next PowerPoint slide, detect animations, etc. 69 | 70 | You can adjust the sensitivity to video frame changes in the `src/video_segment_finder.py` file. You can also visualize how well the application detect transitions and animations via the `src/plot.py` tool. 71 | 72 | ### Next Steps 73 | 74 | - [ ] Automatically generate subtitles 75 | - [ ] Wrap project into a web app? 76 | 77 | ### Usage 78 | 79 | Please note that this project is used for educational purposes and is not intended to be used commercially. We are not liable for any damages/changes done by this project. 80 | 81 | ### Credits 82 | 83 | Emilio Kartono, who made the entire project. 84 | 85 | The fonts for generating the PDF is from [DejaVu fonts](https://dejavu-fonts.github.io/) 86 | 87 | ### License 88 | 89 | This project is protected under the GNU licence. Please refer to the LICENSE.txt for more information. 90 | -------------------------------------------------------------------------------- /docs/pdf-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/docs/pdf-screenshot.png -------------------------------------------------------------------------------- /docs/terminology.md: -------------------------------------------------------------------------------- 1 | # Terminology: 2 | * Content segments: 3 | * Is a part of the video from a particular start and end time that is explaining one content 4 | * Ex: 00:02:05 - 00:04:00 of the video is explaining about a slide on planet Mars 5 | * It contains a video segment and its corresponding subtitle segment 6 | 7 | * Video segment: 8 | * Is the last video frame of a content segment 9 | * Ex: the video segment of 00:02:05 - 00:04:00 is the last video frame in 00:02:05 - 00:04:00 10 | 11 | * Subtitle segment: 12 | * Is the text component of a content segment 13 | * Ex: the subtitle segment of 00:02:05 - 00:04:00 is "In this slide, we are going to ..." 14 | 15 | * Subtitle parts: 16 | * Is a subset of the video's subtitles 17 | * Is created when reading in the video's subtitles -------------------------------------------------------------------------------- /docs/video-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/docs/video-screenshot.png -------------------------------------------------------------------------------- /fonts/DejaVuSansCondensed.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/fonts/DejaVuSansCondensed.ttf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.4 2 | black==21.5b2 3 | blis==0.7.5 4 | catalogue==2.0.6 5 | certifi==2020.12.5 6 | chardet==4.0.0 7 | charset-normalizer==2.0.10 8 | click==7.1.2 9 | cymem==2.0.6 10 | distlib==0.3.1 11 | docopt==0.6.2 12 | fastdiff==0.3.0 13 | filelock==3.0.12 14 | fpdf2==2.2.0 15 | greenlet==1.1.1 16 | idna==3.3 17 | Jinja2==3.0.3 18 | langcodes==3.3.0 19 | MarkupSafe==2.0.1 20 | murmurhash==1.0.6 21 | mypy-extensions==0.4.3 22 | numpy==1.19.5 23 | opencv-python==4.5.1.48 24 | packaging==21.3 25 | parameterized==0.8.1 26 | pathspec==0.8.1 27 | pathy==0.6.1 28 | Pillow==8.1.0 29 | pipenv==2020.11.15 30 | playwright==1.15.0 31 | preshed==3.0.6 32 | pydantic==1.8.2 33 | pyee==8.2.2 34 | pyparsing==3.0.6 35 | pypdftk==0.5 36 | pysrt==1.1.2 37 | python-dotenv==0.19.0 38 | regex==2020.11.13 39 | requests==2.27.1 40 | rope==0.18.0 41 | six==1.15.0 42 | smart-open==5.2.1 43 | snapshottest==0.6.0 44 | spacy-legacy==3.0.8 45 | spacy-loggers==1.0.1 46 | srsly==2.4.2 47 | srt==3.5.0 48 | termcolor==1.1.0 49 | thinc==8.0.13 50 | toml==0.10.2 51 | tqdm==4.62.3 52 | typed-ast==1.4.2 53 | typer==0.4.0 54 | typing-extensions==3.7.4.3 55 | urllib3==1.26.8 56 | virtualenv==20.4.4 57 | virtualenv-clone==0.5.4 58 | Wand==0.6.10 59 | wasabi==0.9.0 60 | wasmer==1.1.0 61 | wasmer_compiler_cranelift==1.1.0 62 | websockets==10.0 63 | webvtt-py==0.4.6 64 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- 1 | from .subtitle_part import SubtitlePart 2 | from .subtitle_webvtt_parser import SubtitleWebVTTParser 3 | from .subtitle_segment_finder import SubtitleGenerator, SubtitleSegmentFinder 4 | from .subtitle_srt_parser import SubtitleSRTParser 5 | from .time_utils import ( 6 | convert_clock_time_to_timestamp_ms, 7 | convert_timestamp_ms_to_clock_time, 8 | ) 9 | from .content_segment_exporter import ContentSegment, ContentSegmentPdfBuilder 10 | from .video_segment_finder import VideoSegmentFinder 11 | -------------------------------------------------------------------------------- /src/content_segment_exporter.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | from fpdf import FPDF 4 | import tempfile 5 | 6 | from .subtitle_webvtt_parser import SubtitleWebVTTParser 7 | from .subtitle_segment_finder import SubtitleSegmentFinder 8 | from .video_segment_finder import VideoSegmentFinder 9 | 10 | 11 | class ContentSegment: 12 | """This class represents the image and the text that represents one segment of the video 13 | For instance, an image could be a powerpoint slide and the text could be the explaination of that slide 14 | 15 | Attributes 16 | ---------- 17 | image : np.array(x, y, 3) 18 | The image 19 | text : str 20 | The text 21 | """ 22 | 23 | def __init__(self, image, text): 24 | self.image = image 25 | self.text = text 26 | 27 | 28 | class ContentSegmentPdfBuilder: 29 | """This class creates a PDF from a lecture segment""" 30 | 31 | def generate_pdf(self, pages, output_filepath): 32 | """Generates and saves a PDF from an ordered list of lecture segments 33 | 34 | Parameters 35 | ---------- 36 | pages : ContentSegment[] 37 | An ordered list of lecture segments 38 | output_filepath: str 39 | The filepath for the output pdf 40 | """ 41 | with tempfile.TemporaryDirectory() as temp_dir_path: 42 | pdf = FPDF() 43 | pdf.add_font("DejaVu", "", "fonts/DejaVuSansCondensed.ttf", uni=True) 44 | 45 | for i in range(0, len(pages)): 46 | # Temporarily save the frames 47 | temp_filepath = os.path.join(temp_dir_path, f"{i}_frame.jpeg") 48 | cv2.imwrite(temp_filepath, pages[i].image) 49 | 50 | pdf.add_page() 51 | 52 | # Add the image 53 | pdf.image(temp_filepath, w=195) 54 | 55 | # Add the captions if exist 56 | if pages[i].text is not None: 57 | pdf.set_font("DejaVu", "", 12) 58 | pdf.multi_cell(0, 10, pages[i].text) 59 | 60 | pdf.output(output_filepath, "F") 61 | 62 | 63 | if __name__ == "__main__": 64 | # Get the selected frames 65 | selected_frames_data = VideoSegmentFinder().get_best_segment_frames( 66 | "../tests/videos/input_1.mp4" 67 | ) 68 | frame_nums = sorted(selected_frames_data.keys()) 69 | selected_frames = [selected_frames_data[i]["frame"] for i in frame_nums] 70 | 71 | # Get the subtitles for each frame 72 | pager = SubtitleSegmentFinder( 73 | SubtitleWebVTTParser("../tests/subtitles/subtitles_1.vtt").get_subtitle_parts() 74 | ) 75 | subtitle_breaks = [selected_frames_data[i]["timestamp"] for i in frame_nums] 76 | pages = pager.get_subtitle_segments(subtitle_breaks) 77 | 78 | # Merge the frame and subtitles for each frame to create a pdf 79 | video_subtitle_pages = [] 80 | 81 | for i in range(0, len(selected_frames)): 82 | frame = selected_frames[i] 83 | subtitle_page = pages[i] 84 | video_subtitle_pages.append(ContentSegment(frame, subtitle_page)) 85 | 86 | printer = ContentSegmentPdfBuilder() 87 | pdf = printer.generate_pdf(video_subtitle_pages, "myfile.pdf") 88 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import argparse 3 | from .subtitle_segment_finder import SubtitleGenerator, SubtitleSegmentFinder 4 | from .subtitle_webvtt_parser import SubtitleWebVTTParser 5 | from .subtitle_srt_parser import SubtitleSRTParser 6 | from .video_segment_finder import VideoSegmentFinder 7 | from .content_segment_exporter import ContentSegment, ContentSegmentPdfBuilder 8 | 9 | 10 | class CommandLineArgRunner: 11 | def __init__(self): 12 | self.parser = argparse.ArgumentParser( 13 | description="Generate a readable pdf from lecture videos" 14 | ) 15 | self.parser.add_argument("video", type=str, help="File path to lecture video") 16 | self.parser.add_argument( 17 | "-s", 18 | "--subtitle", 19 | type=str, 20 | default=None, 21 | help="File path to video subtitle. If omitted, it will generate subtitles", 22 | ) 23 | self.parser.add_argument( 24 | "-S", 25 | "--skip-subtitles", 26 | action="store_true", 27 | help="If flag is set, it will ignore setting subtitles to lecture slides", 28 | ) 29 | self.parser.add_argument( 30 | "-o", 31 | "--output", 32 | type=str, 33 | default="output.pdf", 34 | help="Output file to generated pdf", 35 | ) 36 | 37 | def run(self, args): 38 | opts = self.parser.parse_args(args) 39 | 40 | video_filepath = opts.video 41 | subtitle_filepath = opts.subtitle 42 | output_filepath = opts.output 43 | is_skip_subtitles = opts.skip_subtitles 44 | 45 | if is_skip_subtitles and subtitle_filepath is not None: 46 | print("Omit the -S / --skip-subtitles flag to add subtitles to pdf") 47 | raise AssertionError() 48 | 49 | video_segment_finder = VideoSegmentFinder() 50 | 51 | if is_skip_subtitles: 52 | self.__generate_pdf_without_subtitles__( 53 | video_segment_finder, video_filepath, output_filepath 54 | ) 55 | else: 56 | if subtitle_filepath is None: 57 | subtitle_parser = SubtitleGenerator(video_filepath) 58 | elif subtitle_filepath.endswith(".srt"): 59 | subtitle_parser = SubtitleSRTParser(subtitle_filepath) 60 | else: 61 | subtitle_parser = SubtitleWebVTTParser(subtitle_filepath) 62 | 63 | self.__generate_pdf_with_subtitles__( 64 | video_segment_finder, video_filepath, subtitle_parser, output_filepath 65 | ) 66 | 67 | def __generate_pdf_with_subtitles__( 68 | self, video_segment_finder, video_filepath, subtitle_parser, output_filepath 69 | ): 70 | # Get the selected frames 71 | print("Getting selected frames") 72 | selected_frames_data = video_segment_finder.get_best_segment_frames( 73 | video_filepath 74 | ) 75 | frame_nums = sorted(selected_frames_data.keys()) 76 | selected_frames = [selected_frames_data[i]["frame"] for i in frame_nums] 77 | 78 | print("Number of frames:", len(selected_frames)) 79 | 80 | # Get the subtitles for each frame 81 | print("Getting subtitles for each frame") 82 | segment_finder = SubtitleSegmentFinder(subtitle_parser.get_subtitle_parts()) 83 | subtitle_breaks = [selected_frames_data[i]["timestamp"] for i in frame_nums] 84 | segments = segment_finder.get_subtitle_segments(subtitle_breaks) 85 | 86 | # Merge the frame and subtitles for each frame to create a pdf 87 | print("Merging frames and subtitles") 88 | video_subtitle_pages = [] 89 | 90 | for i in range(0, len(selected_frames)): 91 | frame = selected_frames[i] 92 | subtitle_page = segments[i] 93 | video_subtitle_pages.append(ContentSegment(frame, subtitle_page)) 94 | 95 | print("Generating PDF file") 96 | printer = ContentSegmentPdfBuilder() 97 | printer.generate_pdf(video_subtitle_pages, output_filepath) 98 | 99 | def __generate_pdf_without_subtitles__( 100 | self, video_segment_finder, video_filepath, output_filepath 101 | ): 102 | # Get the selected frames 103 | print("Getting selected frames") 104 | selected_frames_data = video_segment_finder.get_best_segment_frames( 105 | video_filepath 106 | ) 107 | frame_nums = sorted(selected_frames_data.keys()) 108 | selected_frames = [selected_frames_data[i]["frame"] for i in frame_nums] 109 | 110 | print("Number of frames:", len(selected_frames)) 111 | 112 | # Generating PDF file 113 | print("Generating PDF file") 114 | video_subtitle_pages = [ 115 | ContentSegment(frame, None) for frame in selected_frames 116 | ] 117 | printer = ContentSegmentPdfBuilder() 118 | printer.generate_pdf(video_subtitle_pages, output_filepath) 119 | 120 | 121 | if __name__ == "__main__": 122 | runner = CommandLineArgRunner() 123 | runner.run(sys.argv[1:]) 124 | -------------------------------------------------------------------------------- /src/plot.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import matplotlib.pyplot as plt 4 | import cv2 5 | from .video_segment_finder import VideoSegmentFinder 6 | 7 | 8 | def plot_timestamps_vs_pixel_change(stats): 9 | simple_timestamp = {} 10 | 11 | for frame_num in stats: 12 | timestamp_ms = stats[frame_num]["timestamp"] 13 | timestamp_seconds = int(float(timestamp_ms) / 100) 14 | num_pixels_changed = stats[frame_num]["num_pixels_changed"] 15 | 16 | if timestamp_seconds not in simple_timestamp: 17 | simple_timestamp[timestamp_seconds] = [sys.maxsize, 0, 0, 0] 18 | 19 | simple_timestamp[timestamp_seconds] = [ 20 | min(simple_timestamp[timestamp_seconds][0], num_pixels_changed), # min 21 | max(simple_timestamp[timestamp_seconds][1], num_pixels_changed), # max 22 | simple_timestamp[timestamp_seconds][2] + num_pixels_changed, # avg 23 | simple_timestamp[timestamp_seconds][3] + 1, # num points 24 | ] 25 | 26 | # Compute avg 27 | for k in simple_timestamp: 28 | simple_timestamp[k][2] /= simple_timestamp[k][3] 29 | 30 | x_vals = sorted(simple_timestamp.keys()) 31 | 32 | plt.plot(x_vals, [simple_timestamp[x][0] for x in x_vals], label="min") 33 | plt.plot(x_vals, [simple_timestamp[x][1] for x in x_vals], label="max") 34 | plt.plot(x_vals, [simple_timestamp[x][2] for x in x_vals], label="avg") 35 | 36 | plt.xlabel("timestamp") 37 | plt.ylabel("score") 38 | 39 | plt.legend() 40 | plt.show() 41 | 42 | 43 | def save_selected_frames(selected_frames): 44 | # Prepare the output folder 45 | if not os.path.exists("./plot-output"): 46 | os.mkdir("plot-output") 47 | for f in glob.glob("./plot-output/*"): 48 | os.remove(f) 49 | 50 | # Save the frames into the output folder 51 | for frame_num in selected_frames: 52 | timestamp = selected_frames[frame_num]["timestamp"] 53 | pixel_changes = selected_frames[frame_num]["num_pixels_changed"] 54 | frame = selected_frames[frame_num]["frame"] 55 | next_frame = selected_frames[frame_num]["next_frame"] 56 | mask = selected_frames[frame_num]["mask"] 57 | 58 | cv2.imwrite( 59 | "plot-output/{}_{}_cur_frame.jpeg".format(timestamp, pixel_changes), frame 60 | ) 61 | cv2.imwrite( 62 | "plot-output/{}_{}_next_frame.jpeg".format(timestamp, pixel_changes), 63 | next_frame, 64 | ) 65 | cv2.imwrite( 66 | "plot-output/{}_{}_mask_frame.jpeg".format(timestamp, pixel_changes), mask 67 | ) 68 | 69 | 70 | if __name__ == "__main__": 71 | selected_frames, stats = VideoSegmentFinder().get_segment_frames_with_stats( 72 | "./tests/videos/input_6.mp4" 73 | ) 74 | save_selected_frames(selected_frames) 75 | plot_timestamps_vs_pixel_change(stats) 76 | -------------------------------------------------------------------------------- /src/subtitle_part.py: -------------------------------------------------------------------------------- 1 | class SubtitlePart: 2 | """A class that represents a part of the entire video's subtitle 3 | 4 | Attributes 5 | ---------- 6 | start_time : int 7 | The starting time of this subtitle's part in milliseconds 8 | end_time : int 9 | The end time of this subtitle's part in milliseconds 10 | text : str 11 | The text corresponding to the subtitle's part 12 | """ 13 | 14 | def __init__(self, start_time, end_time, text): 15 | self.start_time = start_time 16 | self.end_time = end_time 17 | self.text = text 18 | 19 | def __str__(self): 20 | return "{}-{}".format(self.start_time, self.end_time) 21 | 22 | def __repr__(self): 23 | return self.__str__() 24 | -------------------------------------------------------------------------------- /src/subtitle_segment_finder.py: -------------------------------------------------------------------------------- 1 | from .subtitle_webvtt_parser import SubtitleWebVTTParser 2 | from .subtitle_srt_parser import SubtitleSRTParser 3 | 4 | 5 | class SubtitleGenerator: 6 | def __init__(self, video_file): 7 | self.video_file = video_file 8 | 9 | def get_segments(self): 10 | pass 11 | 12 | 13 | class SubtitleSegmentFinder: 14 | """This class finds the best subtitle segments from the end times of video segments""" 15 | 16 | def __init__(self, parts): 17 | self.parts = parts 18 | 19 | def get_subtitle_segments(self, video_segment_end_times): 20 | """Returns the subtitles of video segments given the end times of each video segment 21 | 22 | For instance, given times: 23 | [ "00:00:10", "00:00:20", "00:00:30" ] 24 | it will return the subtitles for times: 25 | 00:00:00 - 00:00:10 26 | 00:00:10 - 00:00:20 27 | 00:00:20 - 00:00:30 28 | 29 | Parameters 30 | ---------- 31 | video_segment_end_times : int[] 32 | A list of timestamps representing the end times of each video segment 33 | 34 | Returns 35 | ------- 36 | segments : str[] 37 | A list of subtitle segments 38 | """ 39 | part_positions = [] 40 | 41 | for i in range(len(video_segment_end_times)): 42 | time_break = video_segment_end_times[i] 43 | 44 | prev_time_break = 0 45 | if i > 0: 46 | prev_time_break = video_segment_end_times[i - 1] 47 | 48 | next_time_break = float('inf') 49 | if i < len(video_segment_end_times) - 1: 50 | next_time_break = video_segment_end_times[i + 1] 51 | 52 | pos = self.__get_part_position_of_time_break__(time_break, prev_time_break, next_time_break) 53 | part_positions.append(pos) 54 | 55 | start_pos = (0, 0) 56 | segments = [] 57 | for end_pos in part_positions: 58 | segment = None 59 | 60 | if start_pos[0] > end_pos[0]: 61 | segment = "" 62 | 63 | elif start_pos[0] == end_pos[0] and start_pos[1] > end_pos[1]: 64 | segment = "" 65 | 66 | elif start_pos[0] == end_pos[0] and start_pos[1] <= end_pos[1]: 67 | segment = self.parts[start_pos[0]].text[start_pos[1] : end_pos[1] + 1] 68 | 69 | elif start_pos[0] < end_pos[0]: 70 | segment = " ".join( 71 | [self.parts[start_pos[0]].text[start_pos[1] :].strip()] 72 | + [self.parts[i].text for i in range(start_pos[0] + 1, end_pos[0])] 73 | + [self.parts[end_pos[0]].text[0 : end_pos[1] + 1].strip()] 74 | ) 75 | 76 | segment = segment.strip() 77 | 78 | start_pos = (end_pos[0], end_pos[1] + 1) 79 | 80 | segments.append(segment) 81 | 82 | return segments 83 | 84 | def __get_part_position_of_time_break__(self, time_break, min_time_break, max_time_break): 85 | min_part_idx = self.__find_part__(min_time_break) 86 | max_part_idx = self.__find_part__(max_time_break) 87 | part_index = self.__find_part__(time_break) 88 | 89 | if min_part_idx is None: 90 | min_part_idx = 0 91 | 92 | if max_part_idx is None: 93 | max_part_idx = len(self.parts) 94 | 95 | # If the page_break_time > last fragment's time, then that page needs to capture the entire thing 96 | if time_break >= self.parts[-1].end_time: 97 | return len(self.parts) - 1, len(self.parts[-1].text) - 1 98 | 99 | if part_index is None: 100 | return 0, -1 101 | 102 | part = self.parts[part_index] 103 | 104 | # Get the char index in the fragment equal to the time_break 105 | ratio = (time_break - part.start_time) / (part.end_time - part.start_time) 106 | part_char_index = int(ratio * len(part.text)) 107 | 108 | # Find the nearest position of a '.' left or right of 'part_index' and 'part_char_index' 109 | left_part_index = part_index 110 | left_part_char_index = part_char_index 111 | right_part_index = part_index 112 | right_part_char_index = part_char_index 113 | 114 | while left_part_index >= min_part_idx and right_part_index < max_part_idx: 115 | if self.parts[left_part_index].text[left_part_char_index] == ".": 116 | return left_part_index, left_part_char_index 117 | 118 | if self.parts[right_part_index].text[right_part_char_index] == ".": 119 | return right_part_index, right_part_char_index 120 | 121 | left_part_char_index -= 1 122 | right_part_char_index += 1 123 | 124 | if left_part_char_index < 0: 125 | left_part_index -= 1 126 | left_part_char_index = len(self.parts[left_part_index].text) - 1 127 | 128 | if right_part_char_index >= len(self.parts[right_part_index].text): 129 | right_part_index += 1 130 | right_part_char_index = 0 131 | 132 | while left_part_index >= min_part_idx: 133 | if self.parts[left_part_index].text[left_part_char_index] == ".": 134 | return left_part_index, left_part_char_index 135 | 136 | left_part_char_index -= 1 137 | 138 | if left_part_char_index < 0: 139 | left_part_index -= 1 140 | left_part_char_index = len(self.parts[left_part_index].text) - 1 141 | 142 | while right_part_index < max_part_idx: 143 | if self.parts[right_part_index].text[right_part_char_index] == ".": 144 | return right_part_index, right_part_char_index 145 | 146 | right_part_char_index += 1 147 | 148 | if right_part_char_index >= len(self.parts[right_part_index].text): 149 | right_part_index += 1 150 | right_part_char_index = 0 151 | 152 | # Fallback: return the found part index and part char 153 | return part_index, part_char_index 154 | 155 | def __find_part__(self, timestamp_ms): 156 | left = 0 157 | right = len(self.parts) - 1 158 | 159 | while left <= right: 160 | mid = (left + right) // 2 161 | cur_part = self.parts[mid] 162 | 163 | if cur_part.start_time <= timestamp_ms < cur_part.end_time: 164 | return mid 165 | elif timestamp_ms < cur_part.start_time: 166 | right = mid - 1 167 | else: 168 | left = mid + 1 169 | 170 | return None 171 | 172 | 173 | if __name__ == "__main__": 174 | 175 | def test1(): 176 | parser = SubtitleWebVTTParser("../tests/subtitles/subtitles_2.vtt") 177 | parts = parser.get_subtitle_parts() 178 | segment_finder = SubtitleSegmentFinder(parts) 179 | 180 | breaks = [14000, 130000, 338000, 478000, 637000, 652000, 654000] 181 | 182 | """ We will have transcriptions at these times: 183 | > 0 - 14000 184 | > 14000 - 130000 185 | > 130000 - 338000 186 | > 338000 - 478000 187 | > 478000 - 637000 188 | > 637000 - 652000 189 | > 652000 - 654000 190 | """ 191 | transcript_pages = segment_finder.get_subtitle_segments(breaks) 192 | 193 | print(len(transcript_pages)) 194 | for transcript_page in transcript_pages: 195 | print("-----------------------") 196 | print(transcript_page) 197 | print("-----------------------") 198 | 199 | def test2(): 200 | parser = SubtitleSRTParser("../tests/subtitles/subtitles_7.srt") 201 | parts = parser.get_subtitle_parts() 202 | print(len(parts)) 203 | segment_finder = SubtitleSegmentFinder(parts) 204 | 205 | breaks = [ 206 | 10520.0, 207 | 103680.0, 208 | 143360.0, 209 | 773040.0, 210 | 1118240.0, 211 | 1693000.0, 212 | 1704760.0, 213 | ] 214 | 215 | """ We will have transcriptions at these times: 216 | > 0 - 14000 217 | > 14000 - 130000 218 | > 130000 - 338000 219 | > 338000 - 478000 220 | > 478000 - 637000 221 | > 637000 - 652000 222 | > 652000 - 654000 223 | """ 224 | transcript_pages = segment_finder.get_subtitle_segments(breaks) 225 | 226 | print(len(transcript_pages)) 227 | for transcript_page in transcript_pages: 228 | print("-----------------------") 229 | print(transcript_page) 230 | print("-----------------------") 231 | 232 | test2() 233 | -------------------------------------------------------------------------------- /src/subtitle_srt_parser.py: -------------------------------------------------------------------------------- 1 | import srt 2 | from .subtitle_part import SubtitlePart 3 | 4 | class SubtitleSRTParser: 5 | """Parses the subtitles and its parts from a .srt file 6 | 7 | Attributes 8 | ---------- 9 | input_file : str 10 | The file path to the subtitles 11 | """ 12 | 13 | def __init__(self, input_file): 14 | self.input_file = input_file 15 | 16 | def get_subtitle_parts(self): 17 | """Parses and gets the subtitle parts from the subtitle's file 18 | It also expands the subtitles in cases where there are gaps between subtitles 19 | 20 | Returns 21 | ------- 22 | parts : SubtitlePart[] 23 | An ordered list of subtitle parts 24 | """ 25 | parts = [] 26 | with open(self.input_file, mode='r') as f: 27 | for sub in srt.parse(f): 28 | start_time = self.__convert_timedelta_to_ms__(sub.start) 29 | end_time = self.__convert_timedelta_to_ms__(sub.end) 30 | clean_text = self.__filter_text__(sub.content) 31 | 32 | if len(clean_text) == 0: 33 | continue 34 | 35 | parts.append(SubtitlePart(start_time, end_time, clean_text)) 36 | 37 | # Extend certain subtitle times to fill in gaps 38 | for i in range(len(parts) - 1): 39 | cur = parts[i] 40 | next = parts[i + 1] 41 | 42 | if cur.end_time != next.start_time: 43 | cur.end_time = next.start_time 44 | 45 | return parts 46 | 47 | def __convert_timedelta_to_ms__(self, timedelta_obj): 48 | return timedelta_obj.total_seconds() * 1000 49 | 50 | def __filter_text__(self, segment_text): 51 | """Takes in the text of a subtitle segment and cleans it""" 52 | return segment_text.replace("\n", " ").strip() 53 | -------------------------------------------------------------------------------- /src/subtitle_webvtt_parser.py: -------------------------------------------------------------------------------- 1 | import webvtt 2 | from .subtitle_part import SubtitlePart 3 | from .time_utils import convert_clock_time_to_timestamp_ms 4 | 5 | class SubtitleWebVTTParser: 6 | """Parses the subtitles and its parts from a .vtt file 7 | 8 | Attributes 9 | ---------- 10 | input_file : str 11 | The file path to the subtitles 12 | """ 13 | 14 | def __init__(self, input_file): 15 | self.input_file = input_file 16 | 17 | def get_subtitle_parts(self): 18 | """Parses and gets the subtitle parts from the subtitle's file 19 | It also expands the subtitles in cases where there are gaps between subtitles 20 | 21 | Returns 22 | ------- 23 | parts : SubtitlePart[] 24 | An ordered list of subtitle parts 25 | """ 26 | parts = [] 27 | for caption in webvtt.read(self.input_file): 28 | start_time = convert_clock_time_to_timestamp_ms(caption.start) 29 | end_time = convert_clock_time_to_timestamp_ms(caption.end) 30 | clean_text = self.__filter_text__(caption.text) 31 | 32 | if len(clean_text) == 0: 33 | continue 34 | 35 | parts.append(SubtitlePart(start_time, end_time, clean_text)) 36 | 37 | # Extend certain subtitle times to fill in gaps 38 | for i in range(len(parts) - 1): 39 | cur = parts[i] 40 | next = parts[i + 1] 41 | 42 | if cur.end_time != next.start_time: 43 | cur.end_time = next.start_time 44 | 45 | return parts 46 | 47 | def __filter_text__(self, segment_text): 48 | """Takes in the text of a subtitle segment and cleans it""" 49 | return segment_text.replace("\n", " ").strip() 50 | -------------------------------------------------------------------------------- /src/time_utils.py: -------------------------------------------------------------------------------- 1 | def convert_clock_time_to_timestamp_ms(clock_time): 2 | """Converts time from HH:MM:SS format to timestamp format (in milliseconds) 3 | For instance, given "00:05:38", it will return 338000 4 | 5 | Parameters 6 | ---------- 7 | clock_time : str 8 | The clock time in HH:mm:ss format 9 | 10 | Returns 11 | ------- 12 | timestamp_ms : int 13 | Timestamp in milliseconds 14 | """ 15 | clock_time_parts = clock_time.split(":") 16 | if len(clock_time_parts) != 3: 17 | raise Exception( 18 | "Illegal argument! Expected 3 parts, instead {} in {}".format( 19 | len(clock_time_parts), clock_time 20 | ) 21 | ) 22 | 23 | hours = int(clock_time_parts[0]) 24 | minutes = int(clock_time_parts[1]) 25 | seconds = float(clock_time_parts[2]) 26 | 27 | return (hours * 3600000) + (minutes * 60000) + (seconds * 1000) 28 | 29 | 30 | def convert_timestamp_ms_to_clock_time(timestamp_ms): 31 | """Converts time in milliseconds to clock time 32 | For instance, given 338000, it will return "00:05:38" 33 | 34 | Parameters 35 | ---------- 36 | timestamp_ms : int 37 | Timestamp in milliseconds 38 | 39 | Returns 40 | ------- 41 | clock_time : str 42 | The clock time in HH:mm:ss format 43 | """ 44 | hours = int(timestamp_ms / 3600000) 45 | minute = int((timestamp_ms % 3600000) / 60000) 46 | seconds = float((timestamp_ms % 3600000 % 60000) / 1000) 47 | 48 | if int(seconds) == seconds: 49 | seconds = int(seconds) 50 | 51 | formatted_seconds = str(seconds) 52 | if seconds < 10: 53 | formatted_seconds = "0" + str(seconds) 54 | 55 | return str(hours).zfill(2) + ":" + str(minute).zfill(2) + ":" + formatted_seconds 56 | -------------------------------------------------------------------------------- /src/video_segment_finder.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | 5 | class PastFrameChangesTracker: 6 | """ A class that keeps track of changes from previous frames """ 7 | 8 | def __init__(self): 9 | self.prev_frame_changes = [False, False, False, False, False] 10 | 11 | def are_previous_frames_stable(self): 12 | """Checks if all previous frames had no changes 13 | 14 | Returns 15 | ------- 16 | is_stable : boolean 17 | True if all past frames had no changes; else False 18 | """ 19 | return sum([1 if x else 0 for x in self.prev_frame_changes]) == 0 20 | 21 | def add_frame_change(self, has_changed): 22 | """Adds a change to the tracker 23 | If there are more than 5 items in the tracker, it will evict the oldest frame change 24 | 25 | Parameters 26 | ---------- 27 | has_changed : boolean 28 | True if there was a change with the current frame vs the past frame; else False 29 | 30 | Returns 31 | ------- 32 | is_stable : boolean 33 | True if all past frames had no changes; else False 34 | """ 35 | self.prev_frame_changes.append(has_changed) 36 | 37 | if len(self.prev_frame_changes) > 5: 38 | self.prev_frame_changes.pop(0) 39 | 40 | 41 | class VideoSegmentFinder: 42 | """A class responsible for finding a list of best possible video segments 43 | A good video segment (a, t1, t2) is when image a is best explained when watching the video from time t1 to t2 44 | 45 | Attributes 46 | ---------- 47 | threshold : int 48 | Is the min. difference between the color of two images on one pixel location for it to be distinct 49 | min_change : int 50 | Is the min. number of pixel changes between two adjacent video frames for the two to be considered distinct 51 | """ 52 | 53 | def __init__(self, threshold=20, min_change=10000): 54 | self.threshold = threshold 55 | self.min_change = min_change 56 | 57 | def get_best_segment_frames(self, video_file): 58 | ''' Finds a list of best possible video segments 59 | It returns a map, where the key is the frame number, and the value is the frame data 60 | 61 | The frame data is of this format: 62 | { 63 | "timestamp": , 64 | "frame": , 65 | "next_frame": , 66 | "mask": , 67 | "num_pixels_changed": , 68 | } 69 | 70 | The video segment can be obtained by two adjacent frame data, f1, f2 where: 71 | a = f2.frame 72 | t1 = f1.timestamp 73 | t2 = f2.timestamp 74 | 75 | Returns 76 | ------- 77 | selected_frames : { a -> b } 78 | A map of frame number a to the frame data b 79 | ''' 80 | selected_frames, _ = self.get_segment_frames_with_stats( 81 | video_file, save_stats_for_all_frames=False 82 | ) 83 | return selected_frames 84 | 85 | def get_segment_frames_with_stats(self, video_file, save_stats_for_all_frames=True): 86 | ''' Returns a list of frames for the best possible video segments (refer to get_best_segment_frames()) 87 | 88 | It also outputs statistics on all frames, where the statistic on frame i is: 89 | { 90 | "timestamp": the timestamp of frame i 91 | "num_pixels_changed": number of pixel changes from frame i - 1 to frame i 92 | } 93 | 94 | Returns 95 | ------- 96 | selected_frames : { a -> b } 97 | A map of frame number to its frame data 98 | stats : { a -> c } 99 | A map of frame number to its statistic 100 | ''' 101 | 102 | video_reader = cv2.VideoCapture(video_file) 103 | 104 | # Get the Default resolutions 105 | frame_width = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH)) 106 | frame_height = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)) 107 | 108 | # Get the FPS 109 | fps = int(video_reader.get(cv2.CAP_PROP_FPS)) 110 | 111 | frame_num = 0 112 | frame_num_to_stats = {} 113 | selected_frames = {} 114 | 115 | prev_timestamp = 0 116 | prev_frame = 255 * np.ones( 117 | (frame_height, frame_width, 3), np.uint8 118 | ) # A blank screen 119 | prev_video_changes = PastFrameChangesTracker() 120 | 121 | while video_reader.isOpened(): 122 | is_read, cur_frame = video_reader.read() 123 | timestamp = video_reader.get(cv2.CAP_PROP_POS_MSEC) 124 | 125 | # Is when the stream is ending 126 | if not is_read: 127 | break 128 | 129 | results = self.__compare_frames__(prev_frame, cur_frame) 130 | 131 | # Store the results 132 | if save_stats_for_all_frames: 133 | frame_num_to_stats[frame_num] = { 134 | "timestamp": timestamp, 135 | "num_pixels_changed": results["num_pixels_changed"], 136 | } 137 | 138 | has_changed = results["num_pixels_changed"] > self.min_change 139 | save_frame = False 140 | 141 | if prev_video_changes.are_previous_frames_stable() and has_changed: 142 | save_frame = True 143 | 144 | if save_frame: 145 | selected_frames[frame_num] = { 146 | "timestamp": prev_timestamp, 147 | "frame": prev_frame, 148 | "next_frame": cur_frame, 149 | "mask": results["mask"], 150 | "num_pixels_changed": results["num_pixels_changed"], 151 | } 152 | 153 | prev_video_changes.add_frame_change(has_changed) 154 | 155 | prev_frame = cur_frame 156 | prev_timestamp = timestamp 157 | 158 | frame_num += 1 159 | 160 | # Add the last frame of the video 161 | selected_frames[frame_num] = { 162 | "timestamp": prev_timestamp, 163 | "frame": prev_frame, 164 | "next_frame": 255 165 | * np.ones((frame_height, frame_width, 3), np.uint8), # A blank screen, 166 | "mask": prev_frame, 167 | "num_pixels_changed": 0, 168 | } 169 | 170 | # Rare case: if there are two selected frames s.t. they differ by 1 second, then there is a glitch 171 | # and we pick the frame that is the earliest 172 | selected_frame_nums = sorted(selected_frames.keys()) 173 | i = 0 174 | while i < len(selected_frame_nums) - 1: 175 | cur_frame = selected_frames[selected_frame_nums[i]] 176 | next_frame = selected_frames[selected_frame_nums[i + 1]] 177 | 178 | if (next_frame["timestamp"] - cur_frame["timestamp"]) < 2000: 179 | del selected_frames[selected_frame_nums[i + 1]] 180 | i += 1 181 | 182 | i += 1 183 | 184 | # Edge case: delete the first selected frame since it is just a blank screen 185 | del selected_frames[selected_frame_nums[0]] 186 | 187 | video_reader.release() 188 | cv2.destroyAllWindows() 189 | 190 | return selected_frames, frame_num_to_stats 191 | 192 | def __compare_frames__(self, prev_frame, cur_frame): 193 | diff = cv2.absdiff(prev_frame, cur_frame) 194 | mask = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) 195 | num_pixels_changed = np.sum(mask > self.threshold) 196 | 197 | return {"num_pixels_changed": num_pixels_changed, "mask": mask, "diff": diff} 198 | 199 | 200 | if __name__ == "__main__": 201 | splitter = VideoSegmentFinder() 202 | splitter.get_best_segment_frames("../tests/videos/input_2.mp4") 203 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/__init__.py -------------------------------------------------------------------------------- /tests/snapshots/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/__init__.py -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_1_with_srt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_1_with_srt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_1_with_webvtt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_1_with_webvtt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_1_without_subtitles.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_1_without_subtitles.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_2_with_srt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_2_with_srt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_2_with_webvtt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_2_with_webvtt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_2_without_subtitles.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_2_without_subtitles.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_7_with_srt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_7_with_srt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_7_without_subtitles.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_7_without_subtitles.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_8_with_srt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_8_with_srt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_8_with_webvtt_file.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_8_with_webvtt_file.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_main/video_8_without_subtitles.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/snapshots/snap_test_main/video_8_without_subtitles.pdf -------------------------------------------------------------------------------- /tests/snapshots/snap_test_subtitle_segment_finder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # snapshottest: v1 - https://goo.gl/zC4yUc 3 | from __future__ import unicode_literals 4 | 5 | from snapshottest import Snapshot 6 | 7 | 8 | snapshots = Snapshot() 9 | 10 | snapshots['SubtitleSplitterTests::test_get_pages_given_subtitle_1_should_return_correct_pages 1'] = [ 11 | "So now that we understand what a secure PRG is, and we understand what semantic security means, we can actually argue that a stream cipher with a secure PRG is, in fact, a semantically secure. So that's our goal for this, segment. It's a fairly straightforward proof, and we'll see how it goes.", 12 | "So the theory we wanna prove is that, basically, given a generator G that happens to be a secured, psedo-random generator. In fact, the stream cipher that's derived from this generator is going to be semantically secure. Okay and I want to emphasize. That there was no hope of proving a theorem like this for perfect secrecy. For Shannons concept of perfect secrecy. Because we know that a stream cipher can not be perfectly secure because it has short keys. And perfect secrecy requires the keys to be as long as the message. So this is really kind of the first example the we see where we're able to prove that a cipher with short keys has security. The concept of security is semantic security. And this actually validates that, really, this is a very useful concept. And in fact, you know, we'll be using semantic security many, many times throughout the course. Okay, so how do we prove a theory like this? What we're actually gonna be doing, is we're gonna be proving the contrapositive. What we're gonna show is the following. So we're gonna prove this statement down here, but let me parse it for you. Suppose. You give me a semantic security adversary A. What we'll do is we'll build PRG adversary B to satisfy this inequality here. Now why is this inequality useful? Basically what do we know? We know that if B is an efficient adversary. Then we know that since G is a secure generator, we know that this advantage is negligible, right? A secure generator has a negligible advantage against any efficient statistical test. So the right hand side, basically, is gonna be negligible. But because the right hand side is negligible, we can deduce that the left hand side is negligible. And therefore, the adversary that you looked at actually has negligible advantage in attacking the stream cipher E. Okay. So this is how this, this will work. Basically all we have to do is given an adversary A we're going to build an adversary B. We know that B has negligible advantage against generator but that implies that A has negligible advantage against the stream cipher. So let's do that. So all we have to do again is given A, we have to build B.", 13 | "So let A be a semantic security adversary against the stream cipher. So let me remind you what that means. Basically, there's a challenger. The challenger starts off by choosing the key K. And then the adversary is gonna output two messages, two equal length messages. And he's gonna receive the encryption of M0 or M1 and outputs B1. Okay, that's what a semantic security adversary is going to do. So now we're going to start playing games with this adversary. And that's how we're going to prove our lemma. Alright, so the first thing we're going to do is we're going to make the challenger. Also choose a random R. Okay, a random string R. So, well you know the adversary doesn't really care what the challenger does internally. The challenger never uses R, so this doesn't affect the adversary's advantage at all. The adversary just doesn't care that the challenger also picks R. But now comes the trick. What we're going to do is we're going to, instead of encrypting using GK. We're going to encrypt using R. You can see basically what we're doing here. Essentially we're changing the challenger so now the challenge cipher text is encrypted using a truly random pad. As opposed to just pseudo random pad GK. Okay. Now, the property of the pseudo-random generator is that its output is indistinguishable from truly random. So, because the PRG is secure, the adversary can't tell that we made this change. The adversary can't tell that we switched from a pseudo-random string to a truly random string. Again, because the generator is secure. Well, but now look at the game that we ended up with. So the adversary's advantage couldn't have changed by much, because he can't tell the difference. But now look at the game that we ended up with. Now this game is truly a one time pad game. This a semantic security game against the one time pad. Because now the adversary is getting a one time pad encryption of M0 or M1 But in the one time pad we know that the adversaries advantage is zero, because you can't beat the one time pad. The one time pad is secure Unconditionally secure. And as a result, because of this. Essentially because the adversary couldn't have told the difference when we moved from pseudo random to random. But he couldn't win the random game. That also means that he couldn't win the sudo random game. And as a result, the stream cipher, the original stream cipher must be secure. So that's the intuition for how the proof is gonna go. But I wanna do it rigorously once. From now on, we're just gonna argue by playing games with our challenger. And, we won't be doing things as formal as I'm gonna do next. But I wanna do formally and precisely once, just so that you see how these proofs actually work. Okay, so I'm gonna have to introduce some notation. And I'll do the usual notation, basically. If the original semantics are here at the beginning, when we're actually using a pseudo-random pad, I'm gonna use W0 and W1 to denote the event that the adversary outputs one, when it gets the encryption of M0, or gets the encryption of M1, respectively. Okay? So W0 corresponds to outputting 1 when receiving the encryption of M0. And W1 corresponds to outputting 1 when receiving the encryption of M1. So that's the standard definition of semantic security. Now once we flip to the random pad. I'm gonna use R0 and R1 to denote the event that the adversary outputs 1 when receiving the one-type pad encryption of M0 or the one-time pad encryption of M1. So we have four events, W0, W1 from the original semmantics security game, and R0 and R1 from the semmantics security game once we switch over to the one-time pad.", 14 | "So now let's look at relations between these variables. So first of all, R0 and R1 are basically events from a semmantics security game against a one-time pad. So the difference between these probabilities is that, as we said, basically the advantage of algorithm A, of adversary A, against the one-time pad. Which we know is zero. Okay, so that's great. So that basically means that probability of, of R0 is equal to the probability of R1. So now, let's put these events on a line, on a line segment between zero and one. So here are the events. W0 and W1 are the events we're interested in. We wanna show that these two are close. Okay. And the way we're going to do it is basically by showing, oh and I should say, here is probability R0 and R1, it says they're both same, I just put them in the same place. What we're gonna do is we're gonna show that both W0 and W1 are actually close to the probability of RB and as a result they must be close to one another. Okay, so the way we do that is using a second claim, so now we're interested in the distance between probability of Wb and the probability of Rb. Okay so we'll prove the claim in a second. Let me just state the claim. The claim says that there exists in adversary B. Such that the difference of these two probabilities is basically the advantage of B against the generator G and this is for both b's. Okay? So given these two claims, like the theorem is done because basically what do we know. We know this distance is less than the advantage of B against G. That's from claim two and similarly, this distance actually is even equal to, I'm not gonna say less but is equal to the advantage. Of B against G, and as a result you can see that the distance between W0 and W1 is basically almost twice the advantage of B against G. That's basically the thing that we are trying to prove. Okay the only thing that remains is just proving this claim two and if you think about what claim two says, it basically captures the question of what happens in experiment zero what happens when we replace the pseudo random pad GK, by truly random pad R. Here in experiment zero say we're using the pseudo random pad and here in experiment zero we are using a Truly random pad and we are asking can the adversary tell the difference between these two and we wanna argue that he cannot because the generator is secure.", 15 | "Okay so here's what we are gonna do. So let's prove claim two. So we are gonna argue that in fact there is a PRG adversary B that has exactly the difference of the two probabilities as it's advantage. Okay and since the point is since this is negligible this is negligible. And that's basically what we wanted to prove. Okay, so let's look at the statistical test b. So, what, our statistical test b is gonna use adversary A in his belly, so we get to build statistical test b however we want. As we said, it's gonna use adversary A inside of it, for its operation, and it's a regular statistical test, so it takes an n-bit string as inputs, and it's supposed to output, you know, random or non-random, zero or one. Okay, so let's see. So it's, first thing it's gonna do, is it's gonna run adversary A, and adversary A is gonna output two messages, M0 and M1. And then, what adversary b's gonna do, is basically gonna respond. With M0 XOR or the string that it was given as inputs. Alright? That's the statistical lesson, then. Whenever A outputs, it's gonna output, its output. And now let's look at its advantage. So what can we say about the advantage of this statistical test against the generator? Well, so by definition, it's the probability that, if you choose a truly random string. So here are 01 to the N, so probability that R, that B outputs 1 minus the probability, is that when we choose a pseudo random string, B outputs 1, okay? Okay, but let's think about what this is. What can you tell me about the first expressions? What can you tell me about this expression over here? Well, by the definition that's exactly if you think about what's going on here, that's this is exactly the probability R0 right? Because this game that we are playing with the adversary here is basically he helped us M0 and M1 right here he helped add M0 and m1 and he got the encryption of M0 under truly one time pad. Okay, so this is basically a [inaudible]. Here let me write this a little better. That's the basic level probability of R0. Now, what can we say about the next expression, well what can we say about when B is given a pseudo random string Y as input. Well in that case, this is exactly experiment zero and true stream cipher game because now we're computing M XOR M0, XOR GK. This is exactly W0. Okay, that's exactly what we have to prove. So it's kind of a trivial proof. Okay, so that completes the proof of claim two.", 16 | "And again, just to make sure this is all clear, once we have claim two, we know that W0 must be close to W1, and that's the theorem. That's what we have to prove. Okay, so now we've established that a stream cypher is in fact symmantically secure, assuming that the PRG is secure.", 17 | '' 18 | ] 19 | 20 | snapshots['SubtitleSplitterTests::test_get_pages_given_subtitle_8_should_return_correct_pages 1'] = [ 21 | '[', 22 | 'M', 23 | '', 24 | '', 25 | '', 26 | 'u', 27 | 'si', 28 | 'c]', 29 | 'well i welcome y', 30 | 'ou all to th', 31 | 'e lecture four of week', 32 | 'five in this week we will be studying the important building block of an automated system that is microprocessor', 33 | 'technology let us look at the outline of this lec', 34 | 'ture at start of the lecture we will see the definition of a micropro', 35 | 'cessor then we will see its architecture it has various elements how these el', 36 | 'ements operate then we will learn what is the difference between a microcontroller and a microprocessor the definition of microcontroller will be studied after that we will study the microcomputers which we are using for our regu', 37 | 'lar day-to-day activities at the end of the lecture we will study about the plcs the programmable logic controllers which are used in the automation industry its elements configuration and operation will be studied in detail fine', 38 | 'let us begin in this lecture we will be studying various programmable logic devices in a in our previous lectures we have seen the elements of measurement system such as the sensors and the signal conditioning devices after that we have also seen how we can convert the signals from one form to the another form now let us look at the fundamentals of programmable logic devices as the name suggests the programmable logic devices has two words these are programmable and logic the devices which are carrying out logical operations on the data are called as the logic devices but when we are able to program them when the users are able to program these logic devices then we are call them as the programmable logic devices programmable means we can teach we can instruct we can train these logic devices to carry out a certain set of instructions in the given sequence so what kind of operations these programmable logical logic devices are carrying out they are carrying out various control functions according to the instructions written in its memory so whatever the commands that we are giving they are the low level language commands we will see what is the meaning of the low level and the high level language in the next few', 39 | 'slides the first pld is the microprocessor microprocessor is a digital integrated circuit it is an electronic circuit and it carries out various digital functions which are necessary to process the information which are necessary to process the data given to the micropr', 40 | 'ocessor the microcomputer is utilizing the microprocessor as its cpu that is a central processing unit and it contains all functions of a computer so micro computer may have memory it can communicate with the outside world with input output devices so here you must know the difference between the processor and a computer processor is a simple circuit while computer is a system it has processor as the cpu central proc', 41 | 'essing unit third pld which is very widely used which is very important as far as the automated system is concerned is plc that is programmable logic controller programmable logic controller also incorporates the microprocessor as the central processing unit and it controls the operations of electromechanical devices but plc is working in very harsh condition so the construction of the plc must be very rugged very r', 42 | 'obust the general microprocessors which are used in automation industry are the embedded microprocessor some of the features of this microprocessor are first these kind of microprocessors are dedicated to a specific function control of a specific function for example we want to have an automatic control system to control the temperature of an electric furnace here the function is to control the temperature of the furnace if the temperature if the inside temperature of the furnace is above the set value the microprocessor should cut off the supply of electricity to that electric furnace so a simple electronic circuitry which is embedded inside the electric furnace is nothing but the embedded microprocessor so it is dedicated to carry out specific functions second feature of the embedded microprocessor is they are self starting so the processors are starting on their own as we switch on the system the processor will start on i', 43 | 'ts own why we are incorporating the microprocessor is in automation as we have seen the definition of automation that we want to reduce the human intervention we want to have no intervention so to carry out the operations in auto mode we are taking help of the electronic spec circuitry that is nothing', 44 | 'but the microprocessors these are completely self-contained the embedded microprocessor has their own memory has may have their own battery backup as well they may have their own energy sou', 45 | "rce as well the microprocessor which are used in automation which are embedded in in the products or systems has their own operating system so we can say an embedded microprocessor will be dedicated to a specific function it is self-starting it doesn't require any human intervention these are completely self-contained everything is there inside the system and they do have their own operating syst", 46 | 'em the microprocessor a multi-purpose programmable device it basically reads the binary instructions from a storage device that called memory the memory may be the temporary memory or it may be the permanent memory so whatever the signals which are getting in will be stored in a temporary memory the microprocessor process this information as per the need as per the instructions given in th', 47 | 'e program it process that information according to the instructions and it provides the results as the output so getting the information reading the information and processing the information based upon the instructions given are the functions of a microprocessor but how these functions are carried out to carry out these functions the microprocessor basically has three elements the processor memory element and input output devices to carry out these functions the microprocessor basically has hardware and this and the hardware is nothing but the electronic parts which are integrated together to carry out the intended operation the processor is an electrical circuitry memory is an electronic part and input output devices are are the electromechanical parts well these components are integrated together but their coordinated operation will be carried out by a set of instructions and that of set of instruction is nothing but the program and when we group together a variety of programs then we call that as a software so let us see what this processor does the processor recognizes the program instructions and it carry out it execute that program instructions as per the order given as per the sequence given the microprocessor has the in input output interfaces so the microprocessor is also carrying out the communication between the cpu that is the processor and the outside world through the input output interfaces so in general we call the interface as port in our day to day language as well we are using the word port quite often the third element which is there that is a memory the memory basically holds the program instructions and the data the applications of microprocessor can be classified basically in two categories so based upon the applications of the microprocessor we can say that the microprocessor can be utilized as a reprogrammable system device such as the microcomputer so whatever the computing devices that we do have we can reprogram these systems we can change its operating system we can install some programs we can modify uh these programs we can edit the programs so to carry out these operations in microcomputers we are using the microprocessor so when we are using the microprocessor utility for developing the reprogrammable system that we call the application of microprocessor to have the microcomputers in the second application we we want to have the dedicated functions that to be carried out by the microprocessor and these are nothing but the embedded systems which we have already talked about let us consider the typical automated system such as a conveyor belt automated guided vehicles automatic furnaces all the manufacturing industry equipment whether it may be processing equipment or it is the conveying equipment or it is the monitoring equipment so whenever we are saying we want to carry out the intended application the desired application in automatic mode there also we need the microprocessor so the application of microprocessor to carry out specific functions in automatic mode that is nothing but the embedded system these processors do operate in binary digits that is 0 and 1 these digits are called bits if the electrical voltage given to the machine is of low level then the bit would be 0 and if a high voltage is applied high electrical energy is applied then we are considering that as the beat 1.' 48 | ] 49 | -------------------------------------------------------------------------------- /tests/subtitles/subtitles_1.srt: -------------------------------------------------------------------------------- 1 | 1 2 | 00:00:00,000 --> 00:00:04,134 3 | So now that we understand what a secure 4 | PRG is, and we understand what semantic 5 | 6 | 2 7 | 00:00:04,134 --> 00:00:08,425 8 | security means, we can actually argue that 9 | a stream cipher with a secure PRG is, in 10 | 11 | 3 12 | 00:00:08,425 --> 00:00:12,559 13 | fact, a semantically secure. So that's our 14 | goal for this, segment. It's a fairly 15 | 16 | 4 17 | 00:00:12,559 --> 00:00:16,746 18 | straightforward proof, and we'll see how 19 | it goes. So the theory we wanna prove is 20 | 21 | 5 22 | 00:00:16,746 --> 00:00:20,932 23 | that, basically, given a generator G that 24 | happens to be a secured, psedo-random 25 | 26 | 6 27 | 00:00:20,932 --> 00:00:24,805 28 | generator. In fact, the stream cipher 29 | that's derived from this generator is 30 | 31 | 7 32 | 00:00:24,805 --> 00:00:28,924 33 | going to be semantically secure. Okay and 34 | I want to emphasize. That there was no 35 | 36 | 8 37 | 00:00:28,924 --> 00:00:33,085 38 | hope of proving a theorem like this for 39 | perfect secrecy. For Shannons concept of 40 | 41 | 9 42 | 00:00:33,085 --> 00:00:37,193 43 | perfect secrecy. Because we know that a 44 | stream cipher can not be perfectly 45 | 46 | 10 47 | 00:00:37,193 --> 00:00:41,264 48 | secure because it has short keys. And 49 | perfect secrecy requires the keys to be as 50 | 51 | 11 52 | 00:00:41,264 --> 00:00:45,321 53 | long as the message. So this is really 54 | kind of the first example the we see where 55 | 56 | 12 57 | 00:00:45,321 --> 00:00:49,229 58 | we're able to prove that a cipher with 59 | short keys has security. The concept of 60 | 61 | 13 62 | 00:00:49,229 --> 00:00:53,236 63 | security is semantic security. And this 64 | actually validates that, really, this is a 65 | 66 | 14 67 | 00:00:53,236 --> 00:00:56,943 68 | very useful concept. And in fact, you 69 | know, we'll be using semantic security 70 | 71 | 15 72 | 00:00:56,943 --> 00:01:00,750 73 | many, many times throughout the course. 74 | Okay, so how do we prove a theory like 75 | 76 | 16 77 | 00:01:00,750 --> 00:01:04,257 78 | this? What we're actually gonna be doing, 79 | is we're gonna be proving the 80 | 81 | 17 82 | 00:01:04,257 --> 00:01:08,264 83 | contrapositive. What we're gonna show is 84 | the following. So we're gonna prove this 85 | 86 | 18 87 | 00:01:08,264 --> 00:01:12,815 88 | statement down here, but let me parse it 89 | for you. Suppose. You give me a semantic 90 | 91 | 19 92 | 00:01:12,815 --> 00:01:18,345 93 | security adversary A. What we'll do is 94 | we'll build PRG adversary B to satisfy 95 | 96 | 20 97 | 00:01:18,345 --> 00:01:23,686 98 | this inequality here. Now why is this 99 | inequality useful? Basically what do we 100 | 101 | 21 102 | 00:01:23,686 --> 00:01:28,878 103 | know? We know that if B is an efficient 104 | adversary. Then we know that since G is a 105 | 106 | 22 107 | 00:01:28,878 --> 00:01:33,053 108 | secure generator, we know that this 109 | advantage is negligible, right? A secure 110 | 111 | 23 112 | 00:01:33,053 --> 00:01:37,510 113 | generator has a negligible advantage 114 | against any efficient statistical test. So 115 | 116 | 24 117 | 00:01:37,510 --> 00:01:42,023 118 | the right hand side, basically, is gonna 119 | be negligible. But because the right hand 120 | 121 | 25 122 | 00:01:42,023 --> 00:01:46,023 123 | side is negligible, we can deduce that the 124 | left hand side is negligible. 125 | 126 | 26 127 | 00:01:46,023 --> 00:01:50,767 128 | And therefore, the adversary that you looked 129 | at actually has negligible advantage in 130 | 131 | 27 132 | 00:01:50,767 --> 00:01:54,538 133 | attacking the stream cipher E. Okay. So 134 | this is how this, this will work. 135 | 136 | 28 137 | 00:01:54,538 --> 00:01:58,486 138 | Basically all we have to do is given an 139 | adversary A we're going to build an 140 | 141 | 29 142 | 00:01:58,486 --> 00:02:02,591 143 | adversary B. We know that B has negligible 144 | advantage against generator but that 145 | 146 | 30 147 | 00:02:02,591 --> 00:02:06,036 148 | implies that A has negligible advantage 149 | against the stream cipher. 150 | 151 | 31 152 | 00:02:06,082 --> 00:02:10,994 153 | So let's do that. So all we have to do again 154 | is given A, we have to build B. 155 | 156 | 32 157 | 00:02:10,994 --> 00:02:15,183 158 | So let A be a semantic security adversary against 159 | the stream cipher. So let me remind you 160 | 161 | 33 162 | 00:02:15,183 --> 00:02:19,320 163 | what that means. Basically, there's a 164 | challenger. The challenger starts off by 165 | 166 | 34 167 | 00:02:19,320 --> 00:02:23,509 168 | choosing the key K. And then the adversary 169 | is gonna output two messages, two equal 170 | 171 | 35 172 | 00:02:23,509 --> 00:02:27,383 173 | length messages. And he's gonna receive 174 | the encryption of M0 or M1 175 | 176 | 36 177 | 00:02:27,383 --> 00:02:31,226 178 | and outputs B1. Okay, that's 179 | what a semantic security adversary is 180 | 181 | 37 182 | 00:02:31,226 --> 00:02:34,933 183 | going to do. So now we're going to start 184 | playing games with this adversary. And 185 | 186 | 38 187 | 00:02:34,933 --> 00:02:38,498 188 | that's how we're going to prove our lemma. Alright, so the first thing 189 | 190 | 39 191 | 00:02:38,498 --> 00:02:42,535 192 | we're going to do is we're going to make 193 | the challenger. Also choose a random R. 194 | 195 | 40 196 | 00:02:42,535 --> 00:02:47,500 197 | Okay, a random string R. So, well you know 198 | the adversary doesn't really care what the 199 | 200 | 41 201 | 00:02:47,500 --> 00:02:52,405 202 | challenger does internally. The challenger 203 | never uses R, so this doesn't affect the 204 | 205 | 42 206 | 00:02:52,405 --> 00:02:56,365 207 | adversary's advantage at all. The 208 | adversary just doesn't care that the 209 | 210 | 43 211 | 00:02:56,365 --> 00:03:00,706 212 | challenger also picks R. But now comes the 213 | trick. What we're going to do is we're 214 | 215 | 44 216 | 00:03:00,706 --> 00:03:05,042 217 | going to, instead of encrypting using GK. 218 | We're going to encrypt using R. You can 219 | 220 | 45 221 | 00:03:05,042 --> 00:03:09,993 222 | see basically what we're doing 223 | here. Essentially we're changing the 224 | 225 | 46 226 | 00:03:09,993 --> 00:03:14,219 227 | challenger so now the challenge 228 | cipher text is encrypted using a 229 | 230 | 47 231 | 00:03:14,219 --> 00:03:19,006 232 | truly random pad. As opposed to just pseudo 233 | random pad GK. Okay. Now, the property of 234 | 235 | 48 236 | 00:03:19,006 --> 00:03:23,639 237 | the pseudo-random generator is that its 238 | output is indistinguishable from truly 239 | 240 | 49 241 | 00:03:23,639 --> 00:03:28,273 242 | random. So, because the PRG is secure, the 243 | adversary can't tell that we made this 244 | 245 | 50 246 | 00:03:28,273 --> 00:03:33,082 247 | change. The adversary can't tell that we 248 | switched from a pseudo-random string to a 249 | 250 | 51 251 | 00:03:33,082 --> 00:03:37,422 252 | truly random string. Again, because the generator is secure. Well, but now look at 253 | 254 | 52 255 | 00:03:37,422 --> 00:03:41,762 256 | the game that we ended up with. So the 257 | adversary's advantage couldn't have 258 | 259 | 53 260 | 00:03:41,762 --> 00:03:46,630 261 | changed by much, because he can't tell the 262 | difference. But now look at the game that 263 | 264 | 54 265 | 00:03:46,630 --> 00:03:51,073 266 | we ended up with. Now this game is truly a 267 | one time pad game. This a semantic 268 | 269 | 55 270 | 00:03:51,073 --> 00:03:55,803 271 | security game against the one time pad. 272 | Because now the adversary is getting a one 273 | 274 | 56 275 | 00:03:55,803 --> 00:04:00,238 276 | time pad encryption of M0 or M1 But in the 277 | one time pad we know that the adversaries 278 | 279 | 57 280 | 00:04:00,238 --> 00:04:04,048 281 | advantage is zero, because you can't beat 282 | the one time pad. The one time pad is 283 | 284 | 58 285 | 00:04:04,048 --> 00:04:08,165 286 | secure Unconditionally secure. And as a 287 | result, because of this. Essentially 288 | 289 | 59 290 | 00:04:08,165 --> 00:04:12,674 291 | because the adversary couldn't have told 292 | the difference when 293 | 294 | 60 295 | 00:04:12,674 --> 00:04:17,013 296 | we moved from pseudo random to random. But he couldn't win the 297 | random game. That also means that he 298 | 299 | 61 300 | 00:04:17,013 --> 00:04:21,411 301 | couldn't win the sudo random game. And as 302 | a result, the stream cipher, the original 303 | 304 | 62 305 | 00:04:21,411 --> 00:04:25,634 306 | stream cipher must be secure. So that's 307 | the intuition for how the proof is gonna go. 308 | 309 | 63 310 | 00:04:25,634 --> 00:04:29,594 311 | But I wanna do it rigorously once. 312 | From now on, we're just gonna argue by 313 | 314 | 64 315 | 00:04:29,594 --> 00:04:33,975 316 | playing games with our challenger. And, we 317 | won't be doing things as formal as I'm 318 | 319 | 65 320 | 00:04:33,975 --> 00:04:38,304 321 | gonna do next. But I wanna do formally and 322 | precisely once, just so that you see how 323 | 324 | 66 325 | 00:04:38,304 --> 00:04:42,629 326 | these proofs actually work. Okay, so I'm 327 | gonna have to introduce some notation. And 328 | 329 | 67 330 | 00:04:42,629 --> 00:04:47,751 331 | I'll do the usual notation, basically. If 332 | the original semantics are here at the 333 | 334 | 68 335 | 00:04:47,751 --> 00:04:52,937 336 | beginning, when we're actually using a 337 | pseudo-random pad, I'm gonna use W0 and W1 338 | 339 | 69 340 | 00:04:52,937 --> 00:04:58,059 341 | to denote the event that the adversary 342 | outputs one, when it gets the encryption 343 | 344 | 70 345 | 00:04:58,059 --> 00:05:02,856 346 | of M0, or gets the encryption of M1, 347 | respectively. Okay? So W0 corresponds to 348 | 349 | 71 350 | 00:05:02,856 --> 00:05:07,719 351 | outputting 1 when receiving the 352 | encryption of M0. And W1 corresponds 353 | 354 | 72 355 | 00:05:07,719 --> 00:05:13,141 356 | to outputting 1 when receiving the encryption of M1. So that's the standard 357 | 358 | 73 359 | 00:05:13,141 --> 00:05:19,606 360 | definition of semantic security. Now once 361 | we flip to the random pad. I'm gonna use 362 | 363 | 74 364 | 00:05:19,606 --> 00:05:24,505 365 | R0 and R1 to denote the event that the 366 | adversary outputs 1 when receiving the 367 | 368 | 75 369 | 00:05:24,505 --> 00:05:29,125 370 | one-type pad encryption of M0 or the 371 | one-time pad encryption of M1. So we have 372 | 373 | 76 374 | 00:05:29,125 --> 00:05:33,567 375 | four events, W0, W1 from the original 376 | semmantics security game, and R0 and R1 377 | 378 | 77 379 | 00:05:33,567 --> 00:05:38,365 380 | from the semmantics security game once we 381 | switch over to the one-time pad. So now 382 | 383 | 78 384 | 00:05:38,365 --> 00:05:42,985 385 | let's look at relations between these 386 | variables. So first of all, R0 and R1 are 387 | 388 | 79 389 | 00:05:42,985 --> 00:05:47,427 390 | basically events from a semmantics 391 | security game against a one-time pad. So 392 | 393 | 80 394 | 00:05:47,427 --> 00:05:51,929 395 | the difference between these probabilities 396 | is that, as we said, basically the 397 | 398 | 81 399 | 00:05:51,929 --> 00:05:56,902 400 | advantage of algorithm A, of adversary A, 401 | against the one-time pad. Which we know is 402 | 403 | 82 404 | 00:05:56,902 --> 00:06:01,231 405 | zero. Okay, so that's great. So that 406 | basically means that probability of, of R0 407 | 408 | 83 409 | 00:06:01,231 --> 00:06:05,662 410 | is equal to the probability of R1. So now, 411 | let's put these events on a line, on a 412 | 413 | 84 414 | 00:06:05,662 --> 00:06:10,261 415 | line segment between zero and one. So here 416 | are the events. W0 and W1 are the events 417 | 418 | 85 419 | 00:06:10,261 --> 00:06:14,499 420 | we're interested in. We wanna show that 421 | these two are close. Okay. And the way 422 | 423 | 86 424 | 00:06:14,499 --> 00:06:18,490 425 | we're going to do it is basically by 426 | showing, oh and I should say, here is 427 | 428 | 87 429 | 00:06:18,490 --> 00:06:22,754 430 | probability R0 and R1, it says 431 | they're both same, I just put them in the 432 | 433 | 88 434 | 00:06:22,754 --> 00:06:27,237 435 | same place. What we're gonna do is we're 436 | gonna show that both W0 and W1 are 437 | 438 | 89 439 | 00:06:27,237 --> 00:06:31,720 440 | actually close to the probability of RB 441 | and as a result they must be close to one 442 | 443 | 90 444 | 00:06:31,720 --> 00:06:35,656 445 | another. Okay, so the way we do that is 446 | using a second claim, so now we're 447 | 448 | 91 449 | 00:06:35,656 --> 00:06:39,865 450 | interested in the distance between 451 | probability of Wb and the probability of 452 | 453 | 92 454 | 00:06:39,865 --> 00:06:44,730 455 | Rb. Okay so we'll prove the claim in a 456 | second. Let me just state the claim. The 457 | 458 | 93 459 | 00:06:44,730 --> 00:06:49,938 460 | claim says that there exists in adversary 461 | B. Such that the difference of these two 462 | 463 | 94 464 | 00:06:49,938 --> 00:06:55,081 465 | probabilities is basically the advantage 466 | of B against the generator G and this is 467 | 468 | 95 469 | 00:06:55,081 --> 00:06:59,833 470 | for both b's. Okay? So given these two 471 | claims, like the theorem is done because 472 | 473 | 96 474 | 00:06:59,833 --> 00:07:04,771 475 | basically what do we know. We know this 476 | distance is less than the advantage of B 477 | 478 | 97 479 | 00:07:04,771 --> 00:07:09,523 480 | against G. That's from claim two and 481 | similarly, this distance actually is even 482 | 483 | 98 484 | 00:07:09,523 --> 00:07:14,401 485 | equal to, I'm not gonna say 486 | less but is equal to the advantage. Of B 487 | 488 | 99 489 | 00:07:14,401 --> 00:07:19,455 490 | against G, and as a result you can see 491 | that the distance between W0 and W1 492 | 493 | 100 494 | 00:07:19,455 --> 00:07:24,446 495 | is basically almost twice the 496 | advantage of B against G. That's basically 497 | 498 | 101 499 | 00:07:24,446 --> 00:07:29,375 500 | the thing that we are trying to prove. 501 | Okay the only thing that remains is just 502 | 503 | 102 504 | 00:07:29,375 --> 00:07:34,304 505 | proving this claim two and if you think 506 | about what claim two says, it basically 507 | 508 | 103 509 | 00:07:34,304 --> 00:07:39,170 510 | captures the question of what happens in 511 | experiment zero what happens when we 512 | 513 | 104 514 | 00:07:39,170 --> 00:07:43,530 515 | replace the pseudo random pad GK, by 516 | truly random pad R. Here in 517 | 518 | 105 519 | 00:07:43,530 --> 00:07:48,910 520 | experiment zero say we're using the pseudo 521 | random pad and here in experiment zero we 522 | 523 | 106 524 | 00:07:48,910 --> 00:07:53,593 525 | are using a Truly random pad and we are 526 | asking can the adversary tell the 527 | 528 | 107 529 | 00:07:53,593 --> 00:07:58,972 530 | difference between these two and we wanna 531 | argue that he cannot because the generator 532 | 533 | 108 534 | 00:07:58,972 --> 00:08:03,845 535 | is secure. Okay so here's what we are 536 | gonna do. So let's prove claim two. So we 537 | 538 | 109 539 | 00:08:03,845 --> 00:08:08,728 540 | are gonna argue that in fact there is a 541 | PRG adversary B that has exactly the 542 | 543 | 110 544 | 00:08:08,728 --> 00:08:13,764 545 | difference of the two probabilities as 546 | it's advantage. Okay and since the point 547 | 548 | 111 549 | 00:08:13,764 --> 00:08:18,319 550 | is since this is negligible this is 551 | negligible. And that's basically what we 552 | 553 | 112 554 | 00:08:18,319 --> 00:08:22,323 555 | wanted to prove. Okay, so let's look at 556 | the statistical test b. So, what, our 557 | 558 | 113 559 | 00:08:22,323 --> 00:08:26,514 560 | statistical test b is gonna use adversary 561 | A in his belly, so we get to build 562 | 563 | 114 564 | 00:08:26,514 --> 00:08:31,091 565 | statistical test b however we want. As we 566 | said, it's gonna use adversary A inside of 567 | 568 | 115 569 | 00:08:31,091 --> 00:08:35,558 570 | it, for its operation, and it's a regular 571 | statistical test, so it takes an n-bit 572 | 573 | 116 574 | 00:08:35,558 --> 00:08:39,694 575 | string as inputs, and it's supposed to 576 | output, you know, random or non-random, 577 | 578 | 117 579 | 00:08:39,694 --> 00:08:43,995 580 | zero or one. Okay, so let's see. So it's, 581 | first thing it's gonna do, is it's gonna 582 | 583 | 118 584 | 00:08:43,995 --> 00:08:48,407 585 | run adversary A, and adversary A is gonna 586 | output two messages, M0 and M1. And then, 587 | 588 | 119 589 | 00:08:48,407 --> 00:08:54,053 590 | what adversary b's gonna do, is basically 591 | gonna respond. With M0 XOR or the string that 592 | 593 | 120 594 | 00:08:54,053 --> 00:08:59,942 595 | it was given as inputs. Alright? That's 596 | the statistical lesson, then. Whenever A 597 | 598 | 121 599 | 00:08:59,942 --> 00:09:05,418 600 | outputs, it's gonna output, its output. 601 | And now let's look at its advantage. So 602 | 603 | 122 604 | 00:09:05,418 --> 00:09:10,477 605 | what can we say about the advantage of 606 | this statistical test against the 607 | 608 | 123 609 | 00:09:10,477 --> 00:09:15,606 610 | generator? Well, so by definition, it's 611 | the probability that, if you choose a 612 | 613 | 124 614 | 00:09:15,606 --> 00:09:20,527 615 | truly random string. So here are 01 to the N, so probability 616 | 617 | 125 618 | 00:09:20,527 --> 00:09:25,587 619 | that R, that B outputs 1 minus the 620 | probability, is that when we choose a 621 | 622 | 126 623 | 00:09:25,587 --> 00:09:32,603 624 | pseudo random string, B outputs 1, okay? 625 | Okay, but let's think about what this is. 626 | 627 | 127 628 | 00:09:32,603 --> 00:09:37,398 629 | What can you tell me about the first 630 | expressions? What can you tell me about 631 | 632 | 128 633 | 00:09:37,398 --> 00:09:42,256 634 | this expression over here? Well, by the 635 | definition that's exactly if you think 636 | 637 | 129 638 | 00:09:42,256 --> 00:09:47,366 639 | about what's going on here, that's this is 640 | exactly the probability R0 right? 641 | 642 | 130 643 | 00:09:47,366 --> 00:09:52,729 644 | Because this game that we are playing with 645 | the adversary here is basically he helped 646 | 647 | 131 648 | 00:09:52,729 --> 00:09:58,028 649 | us M0 and M1 right here he helped add M0 and m1 and he got the encryption 650 | 651 | 132 652 | 00:09:58,028 --> 00:10:03,919 653 | of M0 under truly one time pad. Okay, 654 | so this is basically a [inaudible]. Here 655 | 656 | 133 657 | 00:10:03,919 --> 00:10:10,214 658 | let me write this a little better. That's 659 | the basic level probability of R0. 660 | 661 | 134 662 | 00:10:10,660 --> 00:10:15,467 663 | Now, what can we say about the next 664 | expression, well what can we say about 665 | 666 | 135 667 | 00:10:15,467 --> 00:10:19,100 668 | when B is given a pseudo random 669 | string Y as input. 670 | 671 | 136 672 | 00:10:19,100 --> 00:10:23,493 673 | Well in that case, this is exactly experiment zero and 674 | true stream cipher game 675 | 676 | 137 677 | 00:10:23,493 --> 00:10:29,999 678 | because now we're computing M XOR M0, XOR GK. This is 679 | exactly W0. 680 | 681 | 138 682 | 00:10:29,999 --> 00:10:33,015 683 | Okay, that's exactly what we have to prove. So it's kind of a trivial proof. 684 | 685 | 139 686 | 00:10:33,015 --> 00:10:39,563 687 | Okay, so that completes the proof of claim two. And again, just to 688 | make sure this is all clear, once we have 689 | 690 | 140 691 | 00:10:39,563 --> 00:10:43,799 692 | claim two, we know that W0 must be close 693 | to W1, and that's the theorem. 694 | 695 | 141 696 | 00:10:43,814 --> 00:10:50,383 697 | That's what we have to prove. Okay, so now we've 698 | established that a stream cypher is in 699 | 700 | 142 701 | 00:10:50,383 --> 00:10:53,880 702 | fact symmantically secure, assuming that 703 | the PRG is secure. 704 | 705 | -------------------------------------------------------------------------------- /tests/subtitles/subtitles_1.vtt: -------------------------------------------------------------------------------- 1 | WEBVTT 2 | 3 | 1 4 | 00:00:00.000 --> 00:00:04.134 5 | So now that we understand what a secure 6 | PRG is, and we understand what semantic 7 | 8 | 2 9 | 00:00:04.134 --> 00:00:08.425 10 | security means, we can actually argue that 11 | a stream cipher with a secure PRG is, in 12 | 13 | 3 14 | 00:00:08.425 --> 00:00:12.559 15 | fact, a semantically secure. So that's our 16 | goal for this, segment. It's a fairly 17 | 18 | 4 19 | 00:00:12.559 --> 00:00:16.746 20 | straightforward proof, and we'll see how 21 | it goes. So the theory we wanna prove is 22 | 23 | 5 24 | 00:00:16.746 --> 00:00:20.932 25 | that, basically, given a generator G that 26 | happens to be a secured, psedo-random 27 | 28 | 6 29 | 00:00:20.932 --> 00:00:24.805 30 | generator. In fact, the stream cipher 31 | that's derived from this generator is 32 | 33 | 7 34 | 00:00:24.805 --> 00:00:28.924 35 | going to be semantically secure. Okay and 36 | I want to emphasize. That there was no 37 | 38 | 8 39 | 00:00:28.924 --> 00:00:33.085 40 | hope of proving a theorem like this for 41 | perfect secrecy. For Shannons concept of 42 | 43 | 9 44 | 00:00:33.085 --> 00:00:37.193 45 | perfect secrecy. Because we know that a 46 | stream cipher can not be perfectly 47 | 48 | 10 49 | 00:00:37.193 --> 00:00:41.264 50 | secure because it has short keys. And 51 | perfect secrecy requires the keys to be as 52 | 53 | 11 54 | 00:00:41.264 --> 00:00:45.321 55 | long as the message. So this is really 56 | kind of the first example the we see where 57 | 58 | 12 59 | 00:00:45.321 --> 00:00:49.229 60 | we're able to prove that a cipher with 61 | short keys has security. The concept of 62 | 63 | 13 64 | 00:00:49.229 --> 00:00:53.236 65 | security is semantic security. And this 66 | actually validates that, really, this is a 67 | 68 | 14 69 | 00:00:53.236 --> 00:00:56.943 70 | very useful concept. And in fact, you 71 | know, we'll be using semantic security 72 | 73 | 15 74 | 00:00:56.943 --> 00:01:00.750 75 | many, many times throughout the course. 76 | Okay, so how do we prove a theory like 77 | 78 | 16 79 | 00:01:00.750 --> 00:01:04.257 80 | this? What we're actually gonna be doing, 81 | is we're gonna be proving the 82 | 83 | 17 84 | 00:01:04.257 --> 00:01:08.264 85 | contrapositive. What we're gonna show is 86 | the following. So we're gonna prove this 87 | 88 | 18 89 | 00:01:08.264 --> 00:01:12.815 90 | statement down here, but let me parse it 91 | for you. Suppose. You give me a semantic 92 | 93 | 19 94 | 00:01:12.815 --> 00:01:18.345 95 | security adversary A. What we'll do is 96 | we'll build PRG adversary B to satisfy 97 | 98 | 20 99 | 00:01:18.345 --> 00:01:23.686 100 | this inequality here. Now why is this 101 | inequality useful? Basically what do we 102 | 103 | 21 104 | 00:01:23.686 --> 00:01:28.878 105 | know? We know that if B is an efficient 106 | adversary. Then we know that since G is a 107 | 108 | 22 109 | 00:01:28.878 --> 00:01:33.053 110 | secure generator, we know that this 111 | advantage is negligible, right? A secure 112 | 113 | 23 114 | 00:01:33.053 --> 00:01:37.510 115 | generator has a negligible advantage 116 | against any efficient statistical test. So 117 | 118 | 24 119 | 00:01:37.510 --> 00:01:42.023 120 | the right hand side, basically, is gonna 121 | be negligible. But because the right hand 122 | 123 | 25 124 | 00:01:42.023 --> 00:01:46.023 125 | side is negligible, we can deduce that the 126 | left hand side is negligible. 127 | 128 | 26 129 | 00:01:46.023 --> 00:01:50.767 130 | And therefore, the adversary that you looked 131 | at actually has negligible advantage in 132 | 133 | 27 134 | 00:01:50.767 --> 00:01:54.538 135 | attacking the stream cipher E. Okay. So 136 | this is how this, this will work. 137 | 138 | 28 139 | 00:01:54.538 --> 00:01:58.486 140 | Basically all we have to do is given an 141 | adversary A we're going to build an 142 | 143 | 29 144 | 00:01:58.486 --> 00:02:02.591 145 | adversary B. We know that B has negligible 146 | advantage against generator but that 147 | 148 | 30 149 | 00:02:02.591 --> 00:02:06.036 150 | implies that A has negligible advantage 151 | against the stream cipher. 152 | 153 | 31 154 | 00:02:06.082 --> 00:02:10.994 155 | So let's do that. So all we have to do again 156 | is given A, we have to build B. 157 | 158 | 32 159 | 00:02:10.994 --> 00:02:15.183 160 | So let A be a semantic security adversary against 161 | the stream cipher. So let me remind you 162 | 163 | 33 164 | 00:02:15.183 --> 00:02:19.320 165 | what that means. Basically, there's a 166 | challenger. The challenger starts off by 167 | 168 | 34 169 | 00:02:19.320 --> 00:02:23.509 170 | choosing the key K. And then the adversary 171 | is gonna output two messages, two equal 172 | 173 | 35 174 | 00:02:23.509 --> 00:02:27.383 175 | length messages. And he's gonna receive 176 | the encryption of M0 or M1 177 | 178 | 36 179 | 00:02:27.383 --> 00:02:31.226 180 | and outputs B1. Okay, that's 181 | what a semantic security adversary is 182 | 183 | 37 184 | 00:02:31.226 --> 00:02:34.933 185 | going to do. So now we're going to start 186 | playing games with this adversary. And 187 | 188 | 38 189 | 00:02:34.933 --> 00:02:38.498 190 | that's how we're going to prove our lemma. Alright, so the first thing 191 | 192 | 39 193 | 00:02:38.498 --> 00:02:42.535 194 | we're going to do is we're going to make 195 | the challenger. Also choose a random R. 196 | 197 | 40 198 | 00:02:42.535 --> 00:02:47.500 199 | Okay, a random string R. So, well you know 200 | the adversary doesn't really care what the 201 | 202 | 41 203 | 00:02:47.500 --> 00:02:52.405 204 | challenger does internally. The challenger 205 | never uses R, so this doesn't affect the 206 | 207 | 42 208 | 00:02:52.405 --> 00:02:56.365 209 | adversary's advantage at all. The 210 | adversary just doesn't care that the 211 | 212 | 43 213 | 00:02:56.365 --> 00:03:00.706 214 | challenger also picks R. But now comes the 215 | trick. What we're going to do is we're 216 | 217 | 44 218 | 00:03:00.706 --> 00:03:05.042 219 | going to, instead of encrypting using GK. 220 | We're going to encrypt using R. You can 221 | 222 | 45 223 | 00:03:05.042 --> 00:03:09.993 224 | see basically what we're doing 225 | here. Essentially we're changing the 226 | 227 | 46 228 | 00:03:09.993 --> 00:03:14.219 229 | challenger so now the challenge 230 | cipher text is encrypted using a 231 | 232 | 47 233 | 00:03:14.219 --> 00:03:19.006 234 | truly random pad. As opposed to just pseudo 235 | random pad GK. Okay. Now, the property of 236 | 237 | 48 238 | 00:03:19.006 --> 00:03:23.639 239 | the pseudo-random generator is that its 240 | output is indistinguishable from truly 241 | 242 | 49 243 | 00:03:23.639 --> 00:03:28.273 244 | random. So, because the PRG is secure, the 245 | adversary can't tell that we made this 246 | 247 | 50 248 | 00:03:28.273 --> 00:03:33.082 249 | change. The adversary can't tell that we 250 | switched from a pseudo-random string to a 251 | 252 | 51 253 | 00:03:33.082 --> 00:03:37.422 254 | truly random string. Again, because the generator is secure. Well, but now look at 255 | 256 | 52 257 | 00:03:37.422 --> 00:03:41.762 258 | the game that we ended up with. So the 259 | adversary's advantage couldn't have 260 | 261 | 53 262 | 00:03:41.762 --> 00:03:46.630 263 | changed by much, because he can't tell the 264 | difference. But now look at the game that 265 | 266 | 54 267 | 00:03:46.630 --> 00:03:51.073 268 | we ended up with. Now this game is truly a 269 | one time pad game. This a semantic 270 | 271 | 55 272 | 00:03:51.073 --> 00:03:55.803 273 | security game against the one time pad. 274 | Because now the adversary is getting a one 275 | 276 | 56 277 | 00:03:55.803 --> 00:04:00.238 278 | time pad encryption of M0 or M1 But in the 279 | one time pad we know that the adversaries 280 | 281 | 57 282 | 00:04:00.238 --> 00:04:04.048 283 | advantage is zero, because you can't beat 284 | the one time pad. The one time pad is 285 | 286 | 58 287 | 00:04:04.048 --> 00:04:08.165 288 | secure Unconditionally secure. And as a 289 | result, because of this. Essentially 290 | 291 | 59 292 | 00:04:08.165 --> 00:04:12.674 293 | because the adversary couldn't have told 294 | the difference when 295 | 296 | 60 297 | 00:04:12.674 --> 00:04:17.013 298 | we moved from pseudo random to random. But he couldn't win the 299 | random game. That also means that he 300 | 301 | 61 302 | 00:04:17.013 --> 00:04:21.411 303 | couldn't win the sudo random game. And as 304 | a result, the stream cipher, the original 305 | 306 | 62 307 | 00:04:21.411 --> 00:04:25.634 308 | stream cipher must be secure. So that's 309 | the intuition for how the proof is gonna go. 310 | 311 | 63 312 | 00:04:25.634 --> 00:04:29.594 313 | But I wanna do it rigorously once. 314 | From now on, we're just gonna argue by 315 | 316 | 64 317 | 00:04:29.594 --> 00:04:33.975 318 | playing games with our challenger. And, we 319 | won't be doing things as formal as I'm 320 | 321 | 65 322 | 00:04:33.975 --> 00:04:38.304 323 | gonna do next. But I wanna do formally and 324 | precisely once, just so that you see how 325 | 326 | 66 327 | 00:04:38.304 --> 00:04:42.629 328 | these proofs actually work. Okay, so I'm 329 | gonna have to introduce some notation. And 330 | 331 | 67 332 | 00:04:42.629 --> 00:04:47.751 333 | I'll do the usual notation, basically. If 334 | the original semantics are here at the 335 | 336 | 68 337 | 00:04:47.751 --> 00:04:52.937 338 | beginning, when we're actually using a 339 | pseudo-random pad, I'm gonna use W0 and W1 340 | 341 | 69 342 | 00:04:52.937 --> 00:04:58.059 343 | to denote the event that the adversary 344 | outputs one, when it gets the encryption 345 | 346 | 70 347 | 00:04:58.059 --> 00:05:02.856 348 | of M0, or gets the encryption of M1, 349 | respectively. Okay? So W0 corresponds to 350 | 351 | 71 352 | 00:05:02.856 --> 00:05:07.719 353 | outputting 1 when receiving the 354 | encryption of M0. And W1 corresponds 355 | 356 | 72 357 | 00:05:07.719 --> 00:05:13.141 358 | to outputting 1 when receiving the encryption of M1. So that's the standard 359 | 360 | 73 361 | 00:05:13.141 --> 00:05:19.606 362 | definition of semantic security. Now once 363 | we flip to the random pad. I'm gonna use 364 | 365 | 74 366 | 00:05:19.606 --> 00:05:24.505 367 | R0 and R1 to denote the event that the 368 | adversary outputs 1 when receiving the 369 | 370 | 75 371 | 00:05:24.505 --> 00:05:29.125 372 | one-type pad encryption of M0 or the 373 | one-time pad encryption of M1. So we have 374 | 375 | 76 376 | 00:05:29.125 --> 00:05:33.567 377 | four events, W0, W1 from the original 378 | semmantics security game, and R0 and R1 379 | 380 | 77 381 | 00:05:33.567 --> 00:05:38.365 382 | from the semmantics security game once we 383 | switch over to the one-time pad. So now 384 | 385 | 78 386 | 00:05:38.365 --> 00:05:42.985 387 | let's look at relations between these 388 | variables. So first of all, R0 and R1 are 389 | 390 | 79 391 | 00:05:42.985 --> 00:05:47.427 392 | basically events from a semmantics 393 | security game against a one-time pad. So 394 | 395 | 80 396 | 00:05:47.427 --> 00:05:51.929 397 | the difference between these probabilities 398 | is that, as we said, basically the 399 | 400 | 81 401 | 00:05:51.929 --> 00:05:56.902 402 | advantage of algorithm A, of adversary A, 403 | against the one-time pad. Which we know is 404 | 405 | 82 406 | 00:05:56.902 --> 00:06:01.231 407 | zero. Okay, so that's great. So that 408 | basically means that probability of, of R0 409 | 410 | 83 411 | 00:06:01.231 --> 00:06:05.662 412 | is equal to the probability of R1. So now, 413 | let's put these events on a line, on a 414 | 415 | 84 416 | 00:06:05.662 --> 00:06:10.261 417 | line segment between zero and one. So here 418 | are the events. W0 and W1 are the events 419 | 420 | 85 421 | 00:06:10.261 --> 00:06:14.499 422 | we're interested in. We wanna show that 423 | these two are close. Okay. And the way 424 | 425 | 86 426 | 00:06:14.499 --> 00:06:18.490 427 | we're going to do it is basically by 428 | showing, oh and I should say, here is 429 | 430 | 87 431 | 00:06:18.490 --> 00:06:22.754 432 | probability R0 and R1, it says 433 | they're both same, I just put them in the 434 | 435 | 88 436 | 00:06:22.754 --> 00:06:27.237 437 | same place. What we're gonna do is we're 438 | gonna show that both W0 and W1 are 439 | 440 | 89 441 | 00:06:27.237 --> 00:06:31.720 442 | actually close to the probability of RB 443 | and as a result they must be close to one 444 | 445 | 90 446 | 00:06:31.720 --> 00:06:35.656 447 | another. Okay, so the way we do that is 448 | using a second claim, so now we're 449 | 450 | 91 451 | 00:06:35.656 --> 00:06:39.865 452 | interested in the distance between 453 | probability of Wb and the probability of 454 | 455 | 92 456 | 00:06:39.865 --> 00:06:44.730 457 | Rb. Okay so we'll prove the claim in a 458 | second. Let me just state the claim. The 459 | 460 | 93 461 | 00:06:44.730 --> 00:06:49.938 462 | claim says that there exists in adversary 463 | B. Such that the difference of these two 464 | 465 | 94 466 | 00:06:49.938 --> 00:06:55.081 467 | probabilities is basically the advantage 468 | of B against the generator G and this is 469 | 470 | 95 471 | 00:06:55.081 --> 00:06:59.833 472 | for both b's. Okay? So given these two 473 | claims, like the theorem is done because 474 | 475 | 96 476 | 00:06:59.833 --> 00:07:04.771 477 | basically what do we know. We know this 478 | distance is less than the advantage of B 479 | 480 | 97 481 | 00:07:04.771 --> 00:07:09.523 482 | against G. That's from claim two and 483 | similarly, this distance actually is even 484 | 485 | 98 486 | 00:07:09.523 --> 00:07:14.401 487 | equal to, I'm not gonna say 488 | less but is equal to the advantage. Of B 489 | 490 | 99 491 | 00:07:14.401 --> 00:07:19.455 492 | against G, and as a result you can see 493 | that the distance between W0 and W1 494 | 495 | 100 496 | 00:07:19.455 --> 00:07:24.446 497 | is basically almost twice the 498 | advantage of B against G. That's basically 499 | 500 | 101 501 | 00:07:24.446 --> 00:07:29.375 502 | the thing that we are trying to prove. 503 | Okay the only thing that remains is just 504 | 505 | 102 506 | 00:07:29.375 --> 00:07:34.304 507 | proving this claim two and if you think 508 | about what claim two says, it basically 509 | 510 | 103 511 | 00:07:34.304 --> 00:07:39.170 512 | captures the question of what happens in 513 | experiment zero what happens when we 514 | 515 | 104 516 | 00:07:39.170 --> 00:07:43.530 517 | replace the pseudo random pad GK, by 518 | truly random pad R. Here in 519 | 520 | 105 521 | 00:07:43.530 --> 00:07:48.910 522 | experiment zero say we're using the pseudo 523 | random pad and here in experiment zero we 524 | 525 | 106 526 | 00:07:48.910 --> 00:07:53.593 527 | are using a Truly random pad and we are 528 | asking can the adversary tell the 529 | 530 | 107 531 | 00:07:53.593 --> 00:07:58.972 532 | difference between these two and we wanna 533 | argue that he cannot because the generator 534 | 535 | 108 536 | 00:07:58.972 --> 00:08:03.845 537 | is secure. Okay so here's what we are 538 | gonna do. So let's prove claim two. So we 539 | 540 | 109 541 | 00:08:03.845 --> 00:08:08.728 542 | are gonna argue that in fact there is a 543 | PRG adversary B that has exactly the 544 | 545 | 110 546 | 00:08:08.728 --> 00:08:13.764 547 | difference of the two probabilities as 548 | it's advantage. Okay and since the point 549 | 550 | 111 551 | 00:08:13.764 --> 00:08:18.319 552 | is since this is negligible this is 553 | negligible. And that's basically what we 554 | 555 | 112 556 | 00:08:18.319 --> 00:08:22.323 557 | wanted to prove. Okay, so let's look at 558 | the statistical test b. So, what, our 559 | 560 | 113 561 | 00:08:22.323 --> 00:08:26.514 562 | statistical test b is gonna use adversary 563 | A in his belly, so we get to build 564 | 565 | 114 566 | 00:08:26.514 --> 00:08:31.091 567 | statistical test b however we want. As we 568 | said, it's gonna use adversary A inside of 569 | 570 | 115 571 | 00:08:31.091 --> 00:08:35.558 572 | it, for its operation, and it's a regular 573 | statistical test, so it takes an n-bit 574 | 575 | 116 576 | 00:08:35.558 --> 00:08:39.694 577 | string as inputs, and it's supposed to 578 | output, you know, random or non-random, 579 | 580 | 117 581 | 00:08:39.694 --> 00:08:43.995 582 | zero or one. Okay, so let's see. So it's, 583 | first thing it's gonna do, is it's gonna 584 | 585 | 118 586 | 00:08:43.995 --> 00:08:48.407 587 | run adversary A, and adversary A is gonna 588 | output two messages, M0 and M1. And then, 589 | 590 | 119 591 | 00:08:48.407 --> 00:08:54.053 592 | what adversary b's gonna do, is basically 593 | gonna respond. With M0 XOR or the string that 594 | 595 | 120 596 | 00:08:54.053 --> 00:08:59.942 597 | it was given as inputs. Alright? That's 598 | the statistical lesson, then. Whenever A 599 | 600 | 121 601 | 00:08:59.942 --> 00:09:05.418 602 | outputs, it's gonna output, its output. 603 | And now let's look at its advantage. So 604 | 605 | 122 606 | 00:09:05.418 --> 00:09:10.477 607 | what can we say about the advantage of 608 | this statistical test against the 609 | 610 | 123 611 | 00:09:10.477 --> 00:09:15.606 612 | generator? Well, so by definition, it's 613 | the probability that, if you choose a 614 | 615 | 124 616 | 00:09:15.606 --> 00:09:20.527 617 | truly random string. So here are 01 to the N, so probability 618 | 619 | 125 620 | 00:09:20.527 --> 00:09:25.587 621 | that R, that B outputs 1 minus the 622 | probability, is that when we choose a 623 | 624 | 126 625 | 00:09:25.587 --> 00:09:32.603 626 | pseudo random string, B outputs 1, okay? 627 | Okay, but let's think about what this is. 628 | 629 | 127 630 | 00:09:32.603 --> 00:09:37.398 631 | What can you tell me about the first 632 | expressions? What can you tell me about 633 | 634 | 128 635 | 00:09:37.398 --> 00:09:42.256 636 | this expression over here? Well, by the 637 | definition that's exactly if you think 638 | 639 | 129 640 | 00:09:42.256 --> 00:09:47.366 641 | about what's going on here, that's this is 642 | exactly the probability R0 right? 643 | 644 | 130 645 | 00:09:47.366 --> 00:09:52.729 646 | Because this game that we are playing with 647 | the adversary here is basically he helped 648 | 649 | 131 650 | 00:09:52.729 --> 00:09:58.028 651 | us M0 and M1 right here he helped add M0 and m1 and he got the encryption 652 | 653 | 132 654 | 00:09:58.028 --> 00:10:03.919 655 | of M0 under truly one time pad. Okay, 656 | so this is basically a [inaudible]. Here 657 | 658 | 133 659 | 00:10:03.919 --> 00:10:10.214 660 | let me write this a little better. That's 661 | the basic level probability of R0. 662 | 663 | 134 664 | 00:10:10.660 --> 00:10:15.467 665 | Now, what can we say about the next 666 | expression, well what can we say about 667 | 668 | 135 669 | 00:10:15.467 --> 00:10:19.100 670 | when B is given a pseudo random 671 | string Y as input. 672 | 673 | 136 674 | 00:10:19.100 --> 00:10:23.493 675 | Well in that case, this is exactly experiment zero and 676 | true stream cipher game 677 | 678 | 137 679 | 00:10:23.493 --> 00:10:29.999 680 | because now we're computing M XOR M0, XOR GK. This is 681 | exactly W0. 682 | 683 | 138 684 | 00:10:29.999 --> 00:10:33.015 685 | Okay, that's exactly what we have to prove. So it's kind of a trivial proof. 686 | 687 | 139 688 | 00:10:33.015 --> 00:10:39.563 689 | Okay, so that completes the proof of claim two. And again, just to 690 | make sure this is all clear, once we have 691 | 692 | 140 693 | 00:10:39.563 --> 00:10:43.799 694 | claim two, we know that W0 must be close 695 | to W1, and that's the theorem. 696 | 697 | 141 698 | 00:10:43.814 --> 00:10:50.383 699 | That's what we have to prove. Okay, so now we've 700 | established that a stream cypher is in 701 | 702 | 142 703 | 00:10:50.383 --> 00:10:53.880 704 | fact symmantically secure, assuming that 705 | the PRG is secure. -------------------------------------------------------------------------------- /tests/subtitles/subtitles_2.srt: -------------------------------------------------------------------------------- 1 | 1 2 | 00:00:00,000 --> 00:00:04,528 3 | The next thing we're going to look at is 4 | how to compute modular large integers. So 5 | 6 | 2 7 | 00:00:04,528 --> 00:00:09,023 8 | the first question is how do we represent 9 | large integers in a computer? So that's 10 | 11 | 3 12 | 00:00:09,023 --> 00:00:13,615 13 | actually fairly straightforward. So 14 | imagine we're on a 64 bit machine, what we 15 | 16 | 4 17 | 00:00:13,615 --> 00:00:18,361 18 | would do is we would break the number we 19 | want to represent, into 32 bit buckets And 20 | 21 | 5 22 | 00:00:18,361 --> 00:00:22,686 23 | then, we will basically have these n/32 bit buckets, and together they will 24 | 25 | 6 26 | 00:00:22,686 --> 00:00:26,906 27 | represent the number that we want to store 28 | on the computer. Now, I should mention 29 | 30 | 7 31 | 00:00:26,906 --> 00:00:30,705 32 | that I'm only giving 64 bit registers as 33 | an example. In fact, many modern 34 | 35 | 8 36 | 00:00:30,705 --> 00:00:34,977 37 | processors have 128 bit registers or more, 38 | and you can even do multiplications on 39 | 40 | 9 41 | 00:00:34,977 --> 00:00:38,987 42 | them. So normally you would actually use 43 | much larger blocks than just 32 bits. The 44 | 45 | 10 46 | 00:00:38,987 --> 00:00:42,943 47 | reason, by the way, you want to limit 48 | yourself to 32 bits is so that you can 49 | 50 | 11 51 | 00:00:42,943 --> 00:00:46,952 52 | multiply two blocks together, and the 53 | result will still be less than 64 bits, 54 | 55 | 12 56 | 00:00:46,952 --> 00:00:51,189 57 | less than the word size on the machine. So 58 | now let's look at particular arithmetic 59 | 60 | 13 61 | 00:00:51,189 --> 00:00:54,788 62 | operations and see how long each one 63 | takes. So addition and subtraction 64 | 65 | 14 66 | 00:00:54,788 --> 00:00:58,742 67 | basically what you would do is that 68 | addition would carry or subtraction would 69 | 70 | 15 71 | 00:00:58,742 --> 00:01:03,000 72 | borrow and those are basically linear time 73 | operations. In other words, if you want to 74 | 75 | 16 76 | 00:01:03,000 --> 00:01:06,954 77 | add or subtract two n bit integers the 78 | running time is basically 79 | 80 | 17 81 | 00:01:06,954 --> 00:01:12,626 82 | linear in n. Multiplication 83 | naively will take quadratic time. In fact, 84 | 85 | 18 86 | 00:01:12,626 --> 00:01:16,676 87 | this is what's called the high school 88 | algorithm. This is what you kind of 89 | 90 | 19 91 | 00:01:16,676 --> 00:01:21,114 92 | learned in school, where if you think 93 | about this for a minute you'll see that, 94 | 95 | 20 96 | 00:01:21,114 --> 00:01:25,662 97 | that algorithm basically is quadratic in 98 | the length of the numbers that are being 99 | 100 | 21 101 | 00:01:25,662 --> 00:01:30,156 102 | multiplied. So a big surprise in the 1960s 103 | was an algorithm due to Karatsuba that 104 | 105 | 22 106 | 00:01:30,156 --> 00:01:34,150 107 | actually achieves much better than 108 | quadratic time in fact, it achieved a 109 | 110 | 23 111 | 00:01:34,150 --> 00:01:38,567 112 | running time of n to the 1.585. And 113 | there's actually no point in me showing 114 | 115 | 24 116 | 00:01:38,567 --> 00:01:43,166 117 | you how the algorithm actually worked, 118 | I'll just mention the main idea What 119 | 120 | 25 121 | 00:01:43,166 --> 00:01:48,071 122 | Karatsuba realized, is that in fact when 123 | you want to multiply two numbers, you can 124 | 125 | 26 126 | 00:01:48,071 --> 00:01:52,976 127 | write them as, you can take the first 128 | number x, write it as 2 to the b times 129 | 130 | 27 131 | 00:01:52,976 --> 00:01:57,882 132 | x2 plus x1. Where x2 and x1 are roughly 133 | the size of the square root of x. Okay, so 134 | 135 | 28 136 | 00:01:57,882 --> 00:02:02,910 137 | we can kind of break the number x into the 138 | left part of x and the right part of x. 139 | 140 | 29 141 | 00:02:02,910 --> 00:02:07,654 142 | And basically, you're writing x as if it 143 | was written base 2 to the b. So it's got 144 | 145 | 30 146 | 00:02:07,654 --> 00:02:12,398 147 | two digits base 2 to the b. And you do 148 | the same thing with, y. You write y base 149 | 150 | 31 151 | 00:02:12,398 --> 00:02:16,911 152 | 2 to the b. Again, you would write it 153 | as, the sum of the left half plus the 154 | 155 | 32 156 | 00:02:16,911 --> 00:02:21,540 157 | right half, And then, normally, if you try 158 | to do this multiplication, when you open 159 | 160 | 33 161 | 00:02:21,540 --> 00:02:27,486 162 | up the parentheses. You see that, this 163 | would require 4 multiplications, right? 164 | 165 | 34 166 | 00:02:27,486 --> 00:02:33,365 167 | It would require x2 times y2, x2 times y1, 168 | x1 times y2, and x1 times y1. What 169 | 170 | 35 171 | 00:02:33,365 --> 00:02:39,879 172 | Karatsuba realized is there's a way to do 173 | this multiplication of x by y using only 174 | 175 | 36 176 | 00:02:39,879 --> 00:02:45,847 177 | three multiplications of x1 x2 y1 y2. So it's just a big multiplication of x times y 178 | 179 | 37 180 | 00:02:45,847 --> 00:02:50,214 181 | only it takes three little multiplications. You can now recursively 182 | 183 | 38 184 | 00:02:50,214 --> 00:02:55,087 185 | apply exactly the same procedure to 186 | multiplying x2 by y2, and x2 by y1, and so 187 | 188 | 39 189 | 00:02:55,087 --> 00:02:59,960 190 | on and so forth. And you would get this 191 | recursive algorithm. And if you do the 192 | 193 | 40 194 | 00:02:59,960 --> 00:03:05,087 195 | recursive analysis, you will see that 196 | basically, you get a running time of n to the 1.585. 197 | 198 | 41 199 | 00:03:05,087 --> 00:03:13,640 200 | This number is basically, the 1.585 is basically, log of 3 base 2. 201 | 202 | 42 203 | 00:03:13,640 --> 00:03:17,836 204 | Surprisingly, it turns out that Karatsuba 205 | isn't even the best multiplication 206 | 207 | 43 208 | 00:03:17,836 --> 00:03:23,912 209 | algorithm out there. It turns out that, in fact, you can do multiplication in about nlog(n) time. 210 | 211 | 44 212 | 00:03:23,912 --> 00:03:28,678 213 | So you can do multiplication in almost linear time. However, this is an extremely asymptotic results. 214 | 215 | 45 216 | 00:03:28,678 --> 00:03:31,477 217 | The big O here hides very big constants. And as a 218 | 219 | 46 220 | 00:03:31,477 --> 00:03:35,452 221 | result, this algorithm only becomes 222 | practical when the numbers are absolutely 223 | 224 | 47 225 | 00:03:35,452 --> 00:03:39,152 226 | enormous. And so this algorithm is 227 | actually not used very often. But 228 | 229 | 48 230 | 00:03:39,152 --> 00:03:43,183 231 | Karatsuba's algorithm is very practical. 232 | And in fact, most crypto-libraries 233 | 234 | 49 235 | 00:03:43,183 --> 00:03:47,885 236 | implement Karatsuba's algorithm for 237 | multiplication. However, for simplicity 238 | 239 | 50 240 | 00:03:47,885 --> 00:03:51,923 241 | here, I'm just gonna ignore Karatsuba's 242 | algorithm, and just for simplicity, I'm 243 | 244 | 51 245 | 00:03:51,923 --> 00:03:55,960 246 | gonna assume that multiplication runs in 247 | quadratic time. But in your mind, you 248 | 249 | 52 250 | 00:03:55,960 --> 00:03:59,893 251 | should always be thinking all multiplication really is a little bit faster than quadratic. 252 | 253 | 53 254 | 00:03:59,893 --> 00:04:04,794 255 | And then the next question after multiplication is what about 256 | 257 | 54 258 | 00:04:04,794 --> 00:04:10,297 259 | division with remainder and it turns out 260 | that's also a quadratic time algorithm. 261 | 262 | 55 263 | 00:04:10,297 --> 00:04:15,420 264 | So the main operation that remains, and one 265 | that we've used many times so far, and 266 | 267 | 56 268 | 00:04:15,420 --> 00:04:20,346 269 | I've never, actually never, ever told you 270 | how to actually compute it, is this 271 | 272 | 57 273 | 00:04:20,346 --> 00:04:26,339 274 | question of exponentiation. So let's solve 275 | this exponentiation problem a bit more 276 | 277 | 58 278 | 00:04:26,339 --> 00:04:31,558 279 | abstractly. So imagine we have a finite 280 | cyclic group G. All this means is that 281 | 282 | 59 283 | 00:04:31,558 --> 00:04:37,115 284 | this group is generated from the powers of 285 | some generator little g. So for example 286 | 287 | 60 288 | 00:04:37,115 --> 00:04:42,673 289 | think of this group as simply ZP, and think of little g as some generator of 290 | 291 | 61 292 | 00:04:42,673 --> 00:04:48,886 293 | big G. The reason I'm sitting in this way, 294 | is I'm, I want you to start getting used 295 | 296 | 62 297 | 00:04:48,886 --> 00:04:54,023 298 | to this abstraction where we deal with a 299 | generic group G and ZP really is just 300 | 301 | 63 302 | 00:04:54,023 --> 00:04:58,915 303 | one example of such a group. But, in fact, 304 | there are many other examples of finite 305 | 306 | 64 307 | 00:04:58,915 --> 00:05:03,379 308 | cyclic groups. And again I want to 309 | emphasis basically that group G, all it 310 | 311 | 65 312 | 00:05:03,379 --> 00:05:08,087 313 | is, it's simply this powers of this 314 | generator up to the order of the group. 315 | 316 | 66 317 | 00:05:08,087 --> 00:05:15,153 318 | I'll write it as G to the Q. So our goal 319 | now is given this element g, and some 320 | 321 | 67 322 | 00:05:15,153 --> 00:05:20,797 323 | exponent x, our goal is to compute the 324 | value of g to the x. Now normally what you 325 | 326 | 68 327 | 00:05:20,797 --> 00:05:24,810 328 | would say is, you would think well, you 329 | know, if x is equal to 3 then I'm 330 | 331 | 69 332 | 00:05:24,810 --> 00:05:28,898 333 | gonna compute you know, g cubed. Well, 334 | there's really nothing to do. All I do is 335 | 336 | 70 337 | 00:05:28,898 --> 00:05:32,795 338 | I just do g times g times g and I get g 339 | cubed, which is what I wanted. So that's 340 | 341 | 71 342 | 00:05:32,795 --> 00:05:36,790 343 | actually pretty easy. But in fact, that's 344 | not the case that we're interested in. In 345 | 346 | 72 347 | 00:05:36,790 --> 00:05:40,638 348 | our case, our exponents are gonna be 349 | enormous. And so if you try, you know, 350 | 351 | 73 352 | 00:05:40,638 --> 00:05:45,644 353 | think of like a 500-bit number and so if 354 | you try to compute g to the power of a 355 | 356 | 74 357 | 00:05:45,644 --> 00:05:50,710 358 | 500-bit number simply by multiplying g by 359 | g by g by g this is gonna take quite a 360 | 361 | 75 362 | 00:05:50,710 --> 00:05:55,716 363 | while. In fact it will take exponential 364 | time which is not something that we want 365 | 366 | 76 367 | 00:05:55,897 --> 00:06:00,722 368 | to do. So the question is whether even 369 | though x is enormous, can we still compute 370 | 371 | 77 372 | 00:06:00,722 --> 00:06:05,667 373 | g to the x relatively fast and the answer 374 | is yes and the algorithm that does that 375 | 376 | 78 377 | 00:06:05,667 --> 00:06:10,822 378 | is called a repeated squaring algorithm. 379 | And so let me show you how repeated 380 | 381 | 79 382 | 00:06:10,822 --> 00:06:15,593 383 | squaring works. So let's take as an 384 | example, 53. Naively you would have to do 385 | 386 | 80 387 | 00:06:15,593 --> 00:06:20,295 388 | 53 multiplications of g by g by g by g 389 | until you get to g by the 53 but I want to 390 | 391 | 81 392 | 00:06:20,295 --> 00:06:25,275 393 | show you how you can do it very quickly. 394 | So what we'll do is we'll write 53 in 395 | 396 | 82 397 | 00:06:25,275 --> 00:06:30,497 398 | binary. So here this is the binary 399 | representation of 53. And all that means 400 | 401 | 83 402 | 00:06:30,497 --> 00:06:36,282 403 | is, you notice this one corresponds to 32, 404 | this one corresponds to 16, this one 405 | 406 | 84 407 | 00:06:36,282 --> 00:06:41,292 408 | corresponds to 4, and this one 409 | corresponds to 1. So really 53 is 32 410 | 411 | 85 412 | 00:06:41,292 --> 00:06:47,038 413 | plus 16 plus 4 plus 1. But what 414 | that means is that g to the power of 53 is 415 | 416 | 86 417 | 00:06:47,038 --> 00:06:51,801 418 | g to the power of 32+16+4+1. And we can 419 | break that up, using again, the rules of 420 | 421 | 87 422 | 00:06:51,801 --> 00:06:57,235 423 | exponentiation. We can break that up as g 424 | to the 32 times g to the 16 times g to the 425 | 426 | 88 427 | 00:06:57,235 --> 00:07:02,938 428 | 4 times g to the 1, Now that should start 429 | giving you an idea for how to compute g to 430 | 431 | 89 432 | 00:07:02,938 --> 00:07:07,141 433 | the 53 very quickly. What we'll do is, 434 | simply, we'll take g and we'll start 435 | 436 | 90 437 | 00:07:07,141 --> 00:07:11,459 438 | squaring it. So what square wants, g wants 439 | to get g squared. We square it again to 440 | 441 | 91 442 | 00:07:11,459 --> 00:07:15,778 443 | get g to the 4, turn g to the 8. 444 | Turn g to the 16, g to the 32. So 445 | 446 | 92 447 | 00:07:15,778 --> 00:07:20,607 448 | we've computed all these squares of g. And 449 | now, what we're gonna do is we're simply 450 | 451 | 93 452 | 00:07:20,607 --> 00:07:25,719 453 | gonna multiply the appropriate powers to 454 | give us the g to the 53. So this is g to 455 | 456 | 94 457 | 00:07:25,719 --> 00:07:30,390 458 | the one times g to the 4 times g to the 16 times g to the 32, is basically 459 | 460 | 95 461 | 00:07:30,390 --> 00:07:35,376 462 | gonna give us the value that we want, 463 | which is g to the 53. So here you see that 464 | 465 | 96 466 | 00:07:35,376 --> 00:07:40,173 467 | all we had to do was just compute, let's 468 | see, we had to do one, two, three, four, 469 | 470 | 97 471 | 00:07:40,173 --> 00:07:49,343 472 | five squaring, plus four more multiplications 473 | so with 9 multiplications we computed g 474 | 475 | 98 476 | 00:07:49,343 --> 00:07:53,726 477 | to the 53. Okay so that's pretty 478 | interesting. And it turns out this is a 479 | 480 | 99 481 | 00:07:53,726 --> 00:07:58,253 482 | general phenomena that allows us to raise 483 | g to very, very high powers and do it very 484 | 485 | 100 486 | 00:07:58,253 --> 00:08:02,509 487 | quickly. So let me show you the algorithm, 488 | as I said this is called the repeated 489 | 490 | 101 491 | 00:08:02,509 --> 00:08:06,497 492 | squaring algorithm. So the input to the 493 | algorithm is the element g and the 494 | 495 | 102 496 | 00:08:06,497 --> 00:08:10,858 497 | exponent x. And the output is g to the x. 498 | So what we're gonna do is we're gonna 499 | 500 | 103 501 | 00:08:10,858 --> 00:08:15,415 502 | write x in binary notation. So let's say 503 | that x has n bits. And this is the actual 504 | 505 | 104 506 | 00:08:15,415 --> 00:08:19,521 507 | bit representation of x as a binary 508 | number. And then what we'll do is the 509 | 510 | 105 511 | 00:08:19,521 --> 00:08:24,246 512 | following. We'll have these two registers. 513 | y is gonna be a register that's constantly 514 | 515 | 106 516 | 00:08:24,246 --> 00:08:28,127 517 | squared. And then z is gonna be an 518 | accumulator that multiplies in the 519 | 520 | 107 521 | 00:08:28,127 --> 00:08:32,683 522 | appropriate powers of g as needed. So all 523 | we do is the following we loop through the 524 | 525 | 108 526 | 00:08:32,683 --> 00:08:36,526 527 | bits of x starting from the least 528 | significant bits, And then we do the 529 | 530 | 109 531 | 00:08:36,526 --> 00:08:41,414 532 | following: in every iteration we're simply 533 | gonna square y. Okay, so y just keeps on 534 | 535 | 110 536 | 00:08:41,414 --> 00:08:45,940 537 | squaring at every iteration. And then 538 | whenever the corresponding bit of the 539 | 540 | 111 541 | 00:08:45,940 --> 00:08:50,554 542 | exponent x happens to be one, we simply 543 | accumulate the current value of y into 544 | 545 | 112 546 | 00:08:50,554 --> 00:08:55,173 547 | this accumulator z and then at the end, we 548 | simply output z. That's it. That's the 549 | 550 | 113 551 | 00:08:55,173 --> 00:08:59,558 552 | whole algorithm, and that's the repeated 553 | squaring algorithm. So, let's see an 554 | 555 | 114 556 | 00:08:59,558 --> 00:09:04,060 557 | example with G to the 53. So, 558 | you can see the two columns. y is one 559 | 560 | 115 561 | 00:09:04,060 --> 00:09:08,387 562 | column, as it evolves through the 563 | iterations, and z is another column, again 564 | 565 | 116 566 | 00:09:08,387 --> 00:09:13,064 567 | as it evolves through the iterations. So, 568 | y is not very interesting. Basically, all 569 | 570 | 117 571 | 00:09:13,064 --> 00:09:17,449 572 | that happens to y is that at every 573 | iteration, it simply gets squared. And so 574 | 575 | 118 576 | 00:09:17,449 --> 00:09:22,299 577 | it just walks through the powers of two 578 | and the exponents and that's it. z is the 579 | 580 | 119 581 | 00:09:22,299 --> 00:09:26,915 582 | more interesting register where what it 583 | does is it accumulates the appropriate 584 | 585 | 120 586 | 00:09:26,915 --> 00:09:31,882 587 | powers of g whenever the corresponding bit 588 | to the exponent is one. So for example the 589 | 590 | 121 591 | 00:09:31,882 --> 00:09:36,031 592 | first bit of the exponent is one, 593 | therefore, the, at the end of the first 594 | 595 | 122 596 | 00:09:36,031 --> 00:09:41,219 597 | iteration the value of z is simply equal to 598 | g. The second bit of the exponent is zero 599 | 600 | 123 601 | 00:09:41,219 --> 00:09:46,473 602 | so the value of z doesn't change after the 603 | second iteration. And at the end of the 604 | 605 | 124 606 | 00:09:46,473 --> 00:09:51,856 607 | third iteration well the third bit of the 608 | exponent is one so we accumulate g to the 609 | 610 | 125 611 | 00:09:51,856 --> 00:09:56,662 612 | fourth into z. The next bit of the 613 | exponent is zero so z doesn't change. The 614 | 615 | 126 616 | 00:09:56,662 --> 00:10:02,109 617 | next bit of the exponent is one and so now 618 | we're supposed to accumulate the previous 619 | 620 | 127 621 | 00:10:02,109 --> 00:10:07,491 622 | value of y into the accumulator z so let 623 | me ask you so what's gonna be the value of z? 624 | 625 | 128 626 | 00:10:10,868 --> 00:10:14,245 627 | Well, we simply accumulate g to the 628 | 16 into z and so we simply compute the sum 629 | 630 | 129 631 | 00:10:14,245 --> 00:10:19,594 632 | of 16 and 5 we get g to the 21. 633 | Finally, the last bit is also set to one 634 | 635 | 130 636 | 00:10:19,594 --> 00:10:24,943 637 | so we accumulate it into z, we do 32 plus 21 and we get the finally output g to the 53. 638 | 639 | 131 640 | 00:10:24,943 --> 00:10:30,022 641 | Okay, so this gives you an idea of how 642 | this repeated squaring algorithm works. 643 | 644 | 132 645 | 00:10:30,022 --> 00:10:35,777 646 | It's is quite an interesting algorithm and 647 | it allows us to compute enormous powers of 648 | 649 | 133 650 | 00:10:35,777 --> 00:10:41,064 651 | g very, very, very quickly. So the number 652 | of iterations here, essentially, would be 653 | 654 | 134 655 | 00:10:41,064 --> 00:10:46,456 656 | log base 2 of x. Okay. You notice the 657 | number of iterations simply depends on the 658 | 659 | 135 660 | 00:10:46,456 --> 00:10:51,954 661 | number of digits of x, which is basically 662 | the log base 2 of x. So even if x is a 663 | 664 | 136 665 | 00:10:51,954 --> 00:10:56,519 666 | 500 bit number in 500 multiplication, 667 | well, 500 iterations, really 1,000 668 | 669 | 137 670 | 00:10:56,519 --> 00:11:01,736 671 | multiplications because we have to square 672 | and we have to accumulate. So in 1,000 673 | 674 | 138 675 | 00:11:01,736 --> 00:11:06,627 676 | multiplications we'll be able to raise g 677 | to the power of a 500 bit exponent. 678 | 679 | 139 680 | 00:11:06,627 --> 00:11:12,760 681 | Okay so now we can summarize kind of the running times so suppose we 682 | 683 | 140 684 | 00:11:12,760 --> 00:11:17,680 685 | have an N bit modulus capital N as we 686 | said addition and subtraction in ZN takes 687 | 688 | 141 689 | 00:11:17,680 --> 00:11:22,157 690 | linear time. Multiplication of just, you 691 | know, as I said, Karatsuba's actually makes this 692 | 693 | 142 694 | 00:11:22,157 --> 00:11:26,897 695 | more efficient, but for simplicity we'll 696 | just say that it takes quadratic time. And 697 | 698 | 143 699 | 00:11:26,897 --> 00:11:31,579 700 | then exponentiation, as I said, basically 701 | takes log of x iterations, and at each 702 | 703 | 144 704 | 00:11:31,579 --> 00:11:35,509 705 | iteration we basically do two 706 | multiplications. So it's O(log (x)) 707 | 708 | 145 709 | 00:11:35,509 --> 00:11:40,307 710 | times the time to multiply. And let's say 711 | that the time to multiply is quadratic. So 712 | 713 | 146 714 | 00:11:40,307 --> 00:11:44,758 715 | the running time would be, really, N 716 | squared log x. And since x is always gonna 717 | 718 | 147 719 | 00:11:44,758 --> 00:11:49,168 720 | be less than N, by Fermat's theorem 721 | there's no point in raising g to a power 722 | 723 | 148 724 | 00:11:49,168 --> 00:11:53,958 725 | that's larger than the modulus. So x is 726 | gonna be less than N. Let's suppose that x 727 | 728 | 149 729 | 00:11:53,958 --> 00:11:58,570 730 | is also an N-bit integer, then, really 731 | exponentiation is a cubic-time algorithm. 732 | 733 | 150 734 | 00:11:58,570 --> 00:12:02,970 735 | Okay so that's what I wanted you to 736 | remember, that exponentiation is actually 737 | 738 | 151 739 | 00:12:02,970 --> 00:12:07,163 740 | a relatively slow. These days, it actually 741 | takes a few microseconds on a modern 742 | 743 | 152 744 | 00:12:07,163 --> 00:12:11,259 745 | computer. But still, microseconds for a, 746 | for a, say a four gigahertz processor is 747 | 748 | 153 749 | 00:12:11,259 --> 00:12:15,092 750 | quite a bit of work. And so just keep in 751 | mind that all the exponentiation 752 | 753 | 154 754 | 00:12:15,092 --> 00:12:19,556 755 | operations we talked about. For example, 756 | for determining if a number is a quadratic 757 | 758 | 155 759 | 00:12:19,556 --> 00:12:23,600 760 | residue or not, All those, all those 761 | exponentiations basically take cubic time. 762 | 763 | 156 764 | 00:12:24,780 --> 00:12:29,677 765 | Okay, so that completes our discussion of 766 | arithmetic algorithms, and then in the 767 | 768 | 157 769 | 00:12:29,677 --> 00:12:34,078 770 | next segment we'll start talking about 771 | hard problems, modulo, primes and composites. 772 | 773 | -------------------------------------------------------------------------------- /tests/subtitles/subtitles_2.vtt: -------------------------------------------------------------------------------- 1 | WEBVTT 2 | 3 | 1 4 | 00:00:00.000 --> 00:00:04.528 5 | The next thing we're going to look at is 6 | how to compute modular large integers. So 7 | 8 | 2 9 | 00:00:04.528 --> 00:00:09.023 10 | the first question is how do we represent 11 | large integers in a computer? So that's 12 | 13 | 3 14 | 00:00:09.023 --> 00:00:13.615 15 | actually fairly straightforward. So 16 | imagine we're on a 64 bit machine, what we 17 | 18 | 4 19 | 00:00:13.615 --> 00:00:18.361 20 | would do is we would break the number we 21 | want to represent, into 32 bit buckets And 22 | 23 | 5 24 | 00:00:18.361 --> 00:00:22.686 25 | then, we will basically have these n/32 bit buckets, and together they will 26 | 27 | 6 28 | 00:00:22.686 --> 00:00:26.906 29 | represent the number that we want to store 30 | on the computer. Now, I should mention 31 | 32 | 7 33 | 00:00:26.906 --> 00:00:30.705 34 | that I'm only giving 64 bit registers as 35 | an example. In fact, many modern 36 | 37 | 8 38 | 00:00:30.705 --> 00:00:34.977 39 | processors have 128 bit registers or more, 40 | and you can even do multiplications on 41 | 42 | 9 43 | 00:00:34.977 --> 00:00:38.987 44 | them. So normally you would actually use 45 | much larger blocks than just 32 bits. The 46 | 47 | 10 48 | 00:00:38.987 --> 00:00:42.943 49 | reason, by the way, you want to limit 50 | yourself to 32 bits is so that you can 51 | 52 | 11 53 | 00:00:42.943 --> 00:00:46.952 54 | multiply two blocks together, and the 55 | result will still be less than 64 bits, 56 | 57 | 12 58 | 00:00:46.952 --> 00:00:51.189 59 | less than the word size on the machine. So 60 | now let's look at particular arithmetic 61 | 62 | 13 63 | 00:00:51.189 --> 00:00:54.788 64 | operations and see how long each one 65 | takes. So addition and subtraction 66 | 67 | 14 68 | 00:00:54.788 --> 00:00:58.742 69 | basically what you would do is that 70 | addition would carry or subtraction would 71 | 72 | 15 73 | 00:00:58.742 --> 00:01:03.000 74 | borrow and those are basically linear time 75 | operations. In other words, if you want to 76 | 77 | 16 78 | 00:01:03.000 --> 00:01:06.954 79 | add or subtract two n bit integers the 80 | running time is basically 81 | 82 | 17 83 | 00:01:06.954 --> 00:01:12.626 84 | linear in n. Multiplication 85 | naively will take quadratic time. In fact, 86 | 87 | 18 88 | 00:01:12.626 --> 00:01:16.676 89 | this is what's called the high school 90 | algorithm. This is what you kind of 91 | 92 | 19 93 | 00:01:16.676 --> 00:01:21.114 94 | learned in school, where if you think 95 | about this for a minute you'll see that, 96 | 97 | 20 98 | 00:01:21.114 --> 00:01:25.662 99 | that algorithm basically is quadratic in 100 | the length of the numbers that are being 101 | 102 | 21 103 | 00:01:25.662 --> 00:01:30.156 104 | multiplied. So a big surprise in the 1960s 105 | was an algorithm due to Karatsuba that 106 | 107 | 22 108 | 00:01:30.156 --> 00:01:34.150 109 | actually achieves much better than 110 | quadratic time in fact, it achieved a 111 | 112 | 23 113 | 00:01:34.150 --> 00:01:38.567 114 | running time of n to the 1.585. And 115 | there's actually no point in me showing 116 | 117 | 24 118 | 00:01:38.567 --> 00:01:43.166 119 | you how the algorithm actually worked, 120 | I'll just mention the main idea What 121 | 122 | 25 123 | 00:01:43.166 --> 00:01:48.071 124 | Karatsuba realized, is that in fact when 125 | you want to multiply two numbers, you can 126 | 127 | 26 128 | 00:01:48.071 --> 00:01:52.976 129 | write them as, you can take the first 130 | number x, write it as 2 to the b times 131 | 132 | 27 133 | 00:01:52.976 --> 00:01:57.882 134 | x2 plus x1. Where x2 and x1 are roughly 135 | the size of the square root of x. Okay, so 136 | 137 | 28 138 | 00:01:57.882 --> 00:02:02.910 139 | we can kind of break the number x into the 140 | left part of x and the right part of x. 141 | 142 | 29 143 | 00:02:02.910 --> 00:02:07.654 144 | And basically, you're writing x as if it 145 | was written base 2 to the b. So it's got 146 | 147 | 30 148 | 00:02:07.654 --> 00:02:12.398 149 | two digits base 2 to the b. And you do 150 | the same thing with, y. You write y base 151 | 152 | 31 153 | 00:02:12.398 --> 00:02:16.911 154 | 2 to the b. Again, you would write it 155 | as, the sum of the left half plus the 156 | 157 | 32 158 | 00:02:16.911 --> 00:02:21.540 159 | right half, And then, normally, if you try 160 | to do this multiplication, when you open 161 | 162 | 33 163 | 00:02:21.540 --> 00:02:27.486 164 | up the parentheses. You see that, this 165 | would require 4 multiplications, right? 166 | 167 | 34 168 | 00:02:27.486 --> 00:02:33.365 169 | It would require x2 times y2, x2 times y1, 170 | x1 times y2, and x1 times y1. What 171 | 172 | 35 173 | 00:02:33.365 --> 00:02:39.879 174 | Karatsuba realized is there's a way to do 175 | this multiplication of x by y using only 176 | 177 | 36 178 | 00:02:39.879 --> 00:02:45.847 179 | three multiplications of x1 x2 y1 y2. So it's just a big multiplication of x times y 180 | 181 | 37 182 | 00:02:45.847 --> 00:02:50.214 183 | only it takes three little multiplications. You can now recursively 184 | 185 | 38 186 | 00:02:50.214 --> 00:02:55.087 187 | apply exactly the same procedure to 188 | multiplying x2 by y2, and x2 by y1, and so 189 | 190 | 39 191 | 00:02:55.087 --> 00:02:59.960 192 | on and so forth. And you would get this 193 | recursive algorithm. And if you do the 194 | 195 | 40 196 | 00:02:59.960 --> 00:03:05.087 197 | recursive analysis, you will see that 198 | basically, you get a running time of n to the 1.585. 199 | 200 | 41 201 | 00:03:05.087 --> 00:03:13.640 202 | This number is basically, the 1.585 is basically, log of 3 base 2. 203 | 204 | 42 205 | 00:03:13.640 --> 00:03:17.836 206 | Surprisingly, it turns out that Karatsuba 207 | isn't even the best multiplication 208 | 209 | 43 210 | 00:03:17.836 --> 00:03:23.912 211 | algorithm out there. It turns out that, in fact, you can do multiplication in about nlog(n) time. 212 | 213 | 44 214 | 00:03:23.912 --> 00:03:28.678 215 | So you can do multiplication in almost linear time. However, this is an extremely asymptotic results. 216 | 217 | 45 218 | 00:03:28.678 --> 00:03:31.477 219 | The big O here hides very big constants. And as a 220 | 221 | 46 222 | 00:03:31.477 --> 00:03:35.452 223 | result, this algorithm only becomes 224 | practical when the numbers are absolutely 225 | 226 | 47 227 | 00:03:35.452 --> 00:03:39.152 228 | enormous. And so this algorithm is 229 | actually not used very often. But 230 | 231 | 48 232 | 00:03:39.152 --> 00:03:43.183 233 | Karatsuba's algorithm is very practical. 234 | And in fact, most crypto-libraries 235 | 236 | 49 237 | 00:03:43.183 --> 00:03:47.885 238 | implement Karatsuba's algorithm for 239 | multiplication. However, for simplicity 240 | 241 | 50 242 | 00:03:47.885 --> 00:03:51.923 243 | here, I'm just gonna ignore Karatsuba's 244 | algorithm, and just for simplicity, I'm 245 | 246 | 51 247 | 00:03:51.923 --> 00:03:55.960 248 | gonna assume that multiplication runs in 249 | quadratic time. But in your mind, you 250 | 251 | 52 252 | 00:03:55.960 --> 00:03:59.893 253 | should always be thinking all multiplication really is a little bit faster than quadratic. 254 | 255 | 53 256 | 00:03:59.893 --> 00:04:04.794 257 | And then the next question after multiplication is what about 258 | 259 | 54 260 | 00:04:04.794 --> 00:04:10.297 261 | division with remainder and it turns out 262 | that's also a quadratic time algorithm. 263 | 264 | 55 265 | 00:04:10.297 --> 00:04:15.420 266 | So the main operation that remains, and one 267 | that we've used many times so far, and 268 | 269 | 56 270 | 00:04:15.420 --> 00:04:20.346 271 | I've never, actually never, ever told you 272 | how to actually compute it, is this 273 | 274 | 57 275 | 00:04:20.346 --> 00:04:26.339 276 | question of exponentiation. So let's solve 277 | this exponentiation problem a bit more 278 | 279 | 58 280 | 00:04:26.339 --> 00:04:31.558 281 | abstractly. So imagine we have a finite 282 | cyclic group G. All this means is that 283 | 284 | 59 285 | 00:04:31.558 --> 00:04:37.115 286 | this group is generated from the powers of 287 | some generator little g. So for example 288 | 289 | 60 290 | 00:04:37.115 --> 00:04:42.673 291 | think of this group as simply ZP, and think of little g as some generator of 292 | 293 | 61 294 | 00:04:42.673 --> 00:04:48.886 295 | big G. The reason I'm sitting in this way, 296 | is I'm, I want you to start getting used 297 | 298 | 62 299 | 00:04:48.886 --> 00:04:54.023 300 | to this abstraction where we deal with a 301 | generic group G and ZP really is just 302 | 303 | 63 304 | 00:04:54.023 --> 00:04:58.915 305 | one example of such a group. But, in fact, 306 | there are many other examples of finite 307 | 308 | 64 309 | 00:04:58.915 --> 00:05:03.379 310 | cyclic groups. And again I want to 311 | emphasis basically that group G, all it 312 | 313 | 65 314 | 00:05:03.379 --> 00:05:08.087 315 | is, it's simply this powers of this 316 | generator up to the order of the group. 317 | 318 | 66 319 | 00:05:08.087 --> 00:05:15.153 320 | I'll write it as G to the Q. So our goal 321 | now is given this element g, and some 322 | 323 | 67 324 | 00:05:15.153 --> 00:05:20.797 325 | exponent x, our goal is to compute the 326 | value of g to the x. Now normally what you 327 | 328 | 68 329 | 00:05:20.797 --> 00:05:24.810 330 | would say is, you would think well, you 331 | know, if x is equal to 3 then I'm 332 | 333 | 69 334 | 00:05:24.810 --> 00:05:28.898 335 | gonna compute you know, g cubed. Well, 336 | there's really nothing to do. All I do is 337 | 338 | 70 339 | 00:05:28.898 --> 00:05:32.795 340 | I just do g times g times g and I get g 341 | cubed, which is what I wanted. So that's 342 | 343 | 71 344 | 00:05:32.795 --> 00:05:36.790 345 | actually pretty easy. But in fact, that's 346 | not the case that we're interested in. In 347 | 348 | 72 349 | 00:05:36.790 --> 00:05:40.638 350 | our case, our exponents are gonna be 351 | enormous. And so if you try, you know, 352 | 353 | 73 354 | 00:05:40.638 --> 00:05:45.644 355 | think of like a 500-bit number and so if 356 | you try to compute g to the power of a 357 | 358 | 74 359 | 00:05:45.644 --> 00:05:50.710 360 | 500-bit number simply by multiplying g by 361 | g by g by g this is gonna take quite a 362 | 363 | 75 364 | 00:05:50.710 --> 00:05:55.716 365 | while. In fact it will take exponential 366 | time which is not something that we want 367 | 368 | 76 369 | 00:05:55.897 --> 00:06:00.722 370 | to do. So the question is whether even 371 | though x is enormous, can we still compute 372 | 373 | 77 374 | 00:06:00.722 --> 00:06:05.667 375 | g to the x relatively fast and the answer 376 | is yes and the algorithm that does that 377 | 378 | 78 379 | 00:06:05.667 --> 00:06:10.822 380 | is called a repeated squaring algorithm. 381 | And so let me show you how repeated 382 | 383 | 79 384 | 00:06:10.822 --> 00:06:15.593 385 | squaring works. So let's take as an 386 | example, 53. Naively you would have to do 387 | 388 | 80 389 | 00:06:15.593 --> 00:06:20.295 390 | 53 multiplications of g by g by g by g 391 | until you get to g by the 53 but I want to 392 | 393 | 81 394 | 00:06:20.295 --> 00:06:25.275 395 | show you how you can do it very quickly. 396 | So what we'll do is we'll write 53 in 397 | 398 | 82 399 | 00:06:25.275 --> 00:06:30.497 400 | binary. So here this is the binary 401 | representation of 53. And all that means 402 | 403 | 83 404 | 00:06:30.497 --> 00:06:36.282 405 | is, you notice this one corresponds to 32, 406 | this one corresponds to 16, this one 407 | 408 | 84 409 | 00:06:36.282 --> 00:06:41.292 410 | corresponds to 4, and this one 411 | corresponds to 1. So really 53 is 32 412 | 413 | 85 414 | 00:06:41.292 --> 00:06:47.038 415 | plus 16 plus 4 plus 1. But what 416 | that means is that g to the power of 53 is 417 | 418 | 86 419 | 00:06:47.038 --> 00:06:51.801 420 | g to the power of 32+16+4+1. And we can 421 | break that up, using again, the rules of 422 | 423 | 87 424 | 00:06:51.801 --> 00:06:57.235 425 | exponentiation. We can break that up as g 426 | to the 32 times g to the 16 times g to the 427 | 428 | 88 429 | 00:06:57.235 --> 00:07:02.938 430 | 4 times g to the 1, Now that should start 431 | giving you an idea for how to compute g to 432 | 433 | 89 434 | 00:07:02.938 --> 00:07:07.141 435 | the 53 very quickly. What we'll do is, 436 | simply, we'll take g and we'll start 437 | 438 | 90 439 | 00:07:07.141 --> 00:07:11.459 440 | squaring it. So what square wants, g wants 441 | to get g squared. We square it again to 442 | 443 | 91 444 | 00:07:11.459 --> 00:07:15.778 445 | get g to the 4, turn g to the 8. 446 | Turn g to the 16, g to the 32. So 447 | 448 | 92 449 | 00:07:15.778 --> 00:07:20.607 450 | we've computed all these squares of g. And 451 | now, what we're gonna do is we're simply 452 | 453 | 93 454 | 00:07:20.607 --> 00:07:25.719 455 | gonna multiply the appropriate powers to 456 | give us the g to the 53. So this is g to 457 | 458 | 94 459 | 00:07:25.719 --> 00:07:30.390 460 | the one times g to the 4 times g to the 16 times g to the 32, is basically 461 | 462 | 95 463 | 00:07:30.390 --> 00:07:35.376 464 | gonna give us the value that we want, 465 | which is g to the 53. So here you see that 466 | 467 | 96 468 | 00:07:35.376 --> 00:07:40.173 469 | all we had to do was just compute, let's 470 | see, we had to do one, two, three, four, 471 | 472 | 97 473 | 00:07:40.173 --> 00:07:49.343 474 | five squaring, plus four more multiplications 475 | so with 9 multiplications we computed g 476 | 477 | 98 478 | 00:07:49.343 --> 00:07:53.726 479 | to the 53. Okay so that's pretty 480 | interesting. And it turns out this is a 481 | 482 | 99 483 | 00:07:53.726 --> 00:07:58.253 484 | general phenomena that allows us to raise 485 | g to very, very high powers and do it very 486 | 487 | 100 488 | 00:07:58.253 --> 00:08:02.509 489 | quickly. So let me show you the algorithm, 490 | as I said this is called the repeated 491 | 492 | 101 493 | 00:08:02.509 --> 00:08:06.497 494 | squaring algorithm. So the input to the 495 | algorithm is the element g and the 496 | 497 | 102 498 | 00:08:06.497 --> 00:08:10.858 499 | exponent x. And the output is g to the x. 500 | So what we're gonna do is we're gonna 501 | 502 | 103 503 | 00:08:10.858 --> 00:08:15.415 504 | write x in binary notation. So let's say 505 | that x has n bits. And this is the actual 506 | 507 | 104 508 | 00:08:15.415 --> 00:08:19.521 509 | bit representation of x as a binary 510 | number. And then what we'll do is the 511 | 512 | 105 513 | 00:08:19.521 --> 00:08:24.246 514 | following. We'll have these two registers. 515 | y is gonna be a register that's constantly 516 | 517 | 106 518 | 00:08:24.246 --> 00:08:28.127 519 | squared. And then z is gonna be an 520 | accumulator that multiplies in the 521 | 522 | 107 523 | 00:08:28.127 --> 00:08:32.683 524 | appropriate powers of g as needed. So all 525 | we do is the following we loop through the 526 | 527 | 108 528 | 00:08:32.683 --> 00:08:36.526 529 | bits of x starting from the least 530 | significant bits, And then we do the 531 | 532 | 109 533 | 00:08:36.526 --> 00:08:41.414 534 | following: in every iteration we're simply 535 | gonna square y. Okay, so y just keeps on 536 | 537 | 110 538 | 00:08:41.414 --> 00:08:45.940 539 | squaring at every iteration. And then 540 | whenever the corresponding bit of the 541 | 542 | 111 543 | 00:08:45.940 --> 00:08:50.554 544 | exponent x happens to be one, we simply 545 | accumulate the current value of y into 546 | 547 | 112 548 | 00:08:50.554 --> 00:08:55.173 549 | this accumulator z and then at the end, we 550 | simply output z. That's it. That's the 551 | 552 | 113 553 | 00:08:55.173 --> 00:08:59.558 554 | whole algorithm, and that's the repeated 555 | squaring algorithm. So, let's see an 556 | 557 | 114 558 | 00:08:59.558 --> 00:09:04.060 559 | example with G to the 53. So, 560 | you can see the two columns. y is one 561 | 562 | 115 563 | 00:09:04.060 --> 00:09:08.387 564 | column, as it evolves through the 565 | iterations, and z is another column, again 566 | 567 | 116 568 | 00:09:08.387 --> 00:09:13.064 569 | as it evolves through the iterations. So, 570 | y is not very interesting. Basically, all 571 | 572 | 117 573 | 00:09:13.064 --> 00:09:17.449 574 | that happens to y is that at every 575 | iteration, it simply gets squared. And so 576 | 577 | 118 578 | 00:09:17.449 --> 00:09:22.299 579 | it just walks through the powers of two 580 | and the exponents and that's it. z is the 581 | 582 | 119 583 | 00:09:22.299 --> 00:09:26.915 584 | more interesting register where what it 585 | does is it accumulates the appropriate 586 | 587 | 120 588 | 00:09:26.915 --> 00:09:31.882 589 | powers of g whenever the corresponding bit 590 | to the exponent is one. So for example the 591 | 592 | 121 593 | 00:09:31.882 --> 00:09:36.031 594 | first bit of the exponent is one, 595 | therefore, the, at the end of the first 596 | 597 | 122 598 | 00:09:36.031 --> 00:09:41.219 599 | iteration the value of z is simply equal to 600 | g. The second bit of the exponent is zero 601 | 602 | 123 603 | 00:09:41.219 --> 00:09:46.473 604 | so the value of z doesn't change after the 605 | second iteration. And at the end of the 606 | 607 | 124 608 | 00:09:46.473 --> 00:09:51.856 609 | third iteration well the third bit of the 610 | exponent is one so we accumulate g to the 611 | 612 | 125 613 | 00:09:51.856 --> 00:09:56.662 614 | fourth into z. The next bit of the 615 | exponent is zero so z doesn't change. The 616 | 617 | 126 618 | 00:09:56.662 --> 00:10:02.109 619 | next bit of the exponent is one and so now 620 | we're supposed to accumulate the previous 621 | 622 | 127 623 | 00:10:02.109 --> 00:10:07.491 624 | value of y into the accumulator z so let 625 | me ask you so what's gonna be the value of z? 626 | 627 | 128 628 | 00:10:10.868 --> 00:10:14.245 629 | Well, we simply accumulate g to the 630 | 16 into z and so we simply compute the sum 631 | 632 | 129 633 | 00:10:14.245 --> 00:10:19.594 634 | of 16 and 5 we get g to the 21. 635 | Finally, the last bit is also set to one 636 | 637 | 130 638 | 00:10:19.594 --> 00:10:24.943 639 | so we accumulate it into z, we do 32 plus 21 and we get the finally output g to the 53. 640 | 641 | 131 642 | 00:10:24.943 --> 00:10:30.022 643 | Okay, so this gives you an idea of how 644 | this repeated squaring algorithm works. 645 | 646 | 132 647 | 00:10:30.022 --> 00:10:35.777 648 | It's is quite an interesting algorithm and 649 | it allows us to compute enormous powers of 650 | 651 | 133 652 | 00:10:35.777 --> 00:10:41.064 653 | g very, very, very quickly. So the number 654 | of iterations here, essentially, would be 655 | 656 | 134 657 | 00:10:41.064 --> 00:10:46.456 658 | log base 2 of x. Okay. You notice the 659 | number of iterations simply depends on the 660 | 661 | 135 662 | 00:10:46.456 --> 00:10:51.954 663 | number of digits of x, which is basically 664 | the log base 2 of x. So even if x is a 665 | 666 | 136 667 | 00:10:51.954 --> 00:10:56.519 668 | 500 bit number in 500 multiplication, 669 | well, 500 iterations, really 1,000 670 | 671 | 137 672 | 00:10:56.519 --> 00:11:01.736 673 | multiplications because we have to square 674 | and we have to accumulate. So in 1,000 675 | 676 | 138 677 | 00:11:01.736 --> 00:11:06.627 678 | multiplications we'll be able to raise g 679 | to the power of a 500 bit exponent. 680 | 681 | 139 682 | 00:11:06.627 --> 00:11:12.760 683 | Okay so now we can summarize kind of the running times so suppose we 684 | 685 | 140 686 | 00:11:12.760 --> 00:11:17.680 687 | have an N bit modulus capital N as we 688 | said addition and subtraction in ZN takes 689 | 690 | 141 691 | 00:11:17.680 --> 00:11:22.157 692 | linear time. Multiplication of just, you 693 | know, as I said, Karatsuba's actually makes this 694 | 695 | 142 696 | 00:11:22.157 --> 00:11:26.897 697 | more efficient, but for simplicity we'll 698 | just say that it takes quadratic time. And 699 | 700 | 143 701 | 00:11:26.897 --> 00:11:31.579 702 | then exponentiation, as I said, basically 703 | takes log of x iterations, and at each 704 | 705 | 144 706 | 00:11:31.579 --> 00:11:35.509 707 | iteration we basically do two 708 | multiplications. So it's O(log (x)) 709 | 710 | 145 711 | 00:11:35.509 --> 00:11:40.307 712 | times the time to multiply. And let's say 713 | that the time to multiply is quadratic. So 714 | 715 | 146 716 | 00:11:40.307 --> 00:11:44.758 717 | the running time would be, really, N 718 | squared log x. And since x is always gonna 719 | 720 | 147 721 | 00:11:44.758 --> 00:11:49.168 722 | be less than N, by Fermat's theorem 723 | there's no point in raising g to a power 724 | 725 | 148 726 | 00:11:49.168 --> 00:11:53.958 727 | that's larger than the modulus. So x is 728 | gonna be less than N. Let's suppose that x 729 | 730 | 149 731 | 00:11:53.958 --> 00:11:58.570 732 | is also an N-bit integer, then, really 733 | exponentiation is a cubic-time algorithm. 734 | 735 | 150 736 | 00:11:58.570 --> 00:12:02.970 737 | Okay so that's what I wanted you to 738 | remember, that exponentiation is actually 739 | 740 | 151 741 | 00:12:02.970 --> 00:12:07.163 742 | a relatively slow. These days, it actually 743 | takes a few microseconds on a modern 744 | 745 | 152 746 | 00:12:07.163 --> 00:12:11.259 747 | computer. But still, microseconds for a, 748 | for a, say a four gigahertz processor is 749 | 750 | 153 751 | 00:12:11.259 --> 00:12:15.092 752 | quite a bit of work. And so just keep in 753 | mind that all the exponentiation 754 | 755 | 154 756 | 00:12:15.092 --> 00:12:19.556 757 | operations we talked about. For example, 758 | for determining if a number is a quadratic 759 | 760 | 155 761 | 00:12:19.556 --> 00:12:23.600 762 | residue or not, All those, all those 763 | exponentiations basically take cubic time. 764 | 765 | 156 766 | 00:12:24.780 --> 00:12:29.677 767 | Okay, so that completes our discussion of 768 | arithmetic algorithms, and then in the 769 | 770 | 157 771 | 00:12:29.677 --> 00:12:34.078 772 | next segment we'll start talking about 773 | hard problems, modulo, primes and composites. -------------------------------------------------------------------------------- /tests/test_main.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | from src.main import CommandLineArgRunner 3 | from unittest import mock, TestCase 4 | from parameterized import parameterized 5 | from tests.utils.pdf_snapshot import assert_match_pdf_snapshot 6 | 7 | 8 | @mock.patch("time.time", mock.MagicMock(return_value=12345)) 9 | class MainTests(TestCase): 10 | @parameterized.expand( 11 | [ 12 | ("input_1.mp4", "subtitles_1.srt", "video_1_with_srt_file.pdf"), 13 | ("input_1.mp4", "subtitles_1.vtt", "video_1_with_webvtt_file.pdf"), 14 | ("input_2.mp4", "subtitles_2.srt", "video_2_with_srt_file.pdf"), 15 | ("input_2.mp4", "subtitles_2.vtt", "video_2_with_webvtt_file.pdf"), 16 | ("input_7.mp4", "subtitles_7.srt", "video_7_with_srt_file.pdf"), 17 | ("input_8.mp4", "subtitles_8.srt", "video_8_with_srt_file.pdf"), 18 | ("input_8.mp4", "subtitles_8.vtt", "video_8_with_webvtt_file.pdf"), 19 | ] 20 | ) 21 | def test_run_given_video_and_subtitles_should_generate_pdf_correctly( 22 | self, video_filename, subtitle_filename, output_filename 23 | ): 24 | test_output_file = tempfile.NamedTemporaryFile(suffix=".pdf") 25 | 26 | cli = CommandLineArgRunner() 27 | cli.run( 28 | [ 29 | f"tests/videos/{video_filename}", 30 | "-s", 31 | f"tests/subtitles/{subtitle_filename}", 32 | "-o", 33 | test_output_file.name, 34 | ] 35 | ) 36 | 37 | assert_match_pdf_snapshot( 38 | f"tests/snapshots/snap_test_main/{output_filename}", 39 | test_output_file.name, 40 | ) 41 | 42 | @parameterized.expand( 43 | [ 44 | ("input_1.mp4", "video_1_without_subtitles.pdf"), 45 | ("input_2.mp4", "video_2_without_subtitles.pdf"), 46 | ("input_7.mp4", "video_7_without_subtitles.pdf"), 47 | ("input_8.mp4", "video_8_without_subtitles.pdf"), 48 | ] 49 | ) 50 | def test_run_given_video_and_skip_subtitles_flag_should_generate_pdf_correctly( 51 | self, video_filename, output_filename 52 | ): 53 | test_output_file = tempfile.NamedTemporaryFile(suffix=".pdf") 54 | 55 | cli = CommandLineArgRunner() 56 | cli.run( 57 | [ 58 | f"tests/videos/{video_filename}", 59 | "-S", 60 | "-o", 61 | test_output_file.name, 62 | ] 63 | ) 64 | 65 | assert_match_pdf_snapshot( 66 | f"tests/snapshots/snap_test_main/{output_filename}", 67 | test_output_file.name, 68 | ) 69 | 70 | def test_run_given_video_and_subtitles_and_skip_subtitles_flag_should_throw_error( 71 | self, 72 | ): 73 | test_output_file = tempfile.NamedTemporaryFile(suffix=".pdf") 74 | 75 | cli = CommandLineArgRunner() 76 | func_to_test = lambda: cli.run( 77 | [ 78 | "tests/videos/input_1.mp4", 79 | "-S", 80 | "-s", 81 | "tests/subtitles/subtitles_1.srt", 82 | "-o", 83 | test_output_file.name, 84 | ] 85 | ) 86 | 87 | self.assertRaises(AssertionError, func_to_test) 88 | -------------------------------------------------------------------------------- /tests/test_subtitle_segment_finder.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import snapshottest 3 | from src.time_utils import convert_clock_time_to_timestamp_ms as get_timestamp 4 | from src.subtitle_segment_finder import SubtitleSegmentFinder 5 | from src.subtitle_part import SubtitlePart 6 | from src.subtitle_webvtt_parser import SubtitleWebVTTParser 7 | from src.subtitle_srt_parser import SubtitleSRTParser 8 | 9 | 10 | class SubtitleSplitterTests(snapshottest.TestCase): 11 | def test_get_pages_given_subtitle_without_periods_and_future_timestamp_should_return_correct_pages( 12 | self, 13 | ): 14 | segments = [ 15 | SubtitlePart( 16 | get_timestamp("00:00:00"), 17 | get_timestamp("00:00:10"), 18 | "hi there my name is Bob", 19 | ) 20 | ] 21 | pager = SubtitleSegmentFinder(segments) 22 | time_breaks = [get_timestamp("00:00:14")] 23 | transcript_pages = pager.get_subtitle_segments(time_breaks) 24 | 25 | self.assertEqual(transcript_pages[0], "hi there my name is Bob") 26 | 27 | def test_get_pages_given_subtitle_without_periods_and_middle_timestamp_should_return_correct_pages( 28 | self, 29 | ): 30 | segments = [ 31 | SubtitlePart( 32 | get_timestamp("00:00:00"), 33 | get_timestamp("00:00:10"), 34 | "hi there my name is Bob", 35 | ) 36 | ] 37 | pager = SubtitleSegmentFinder(segments) 38 | time_breaks = [get_timestamp("00:00:05")] 39 | transcript_pages = pager.get_subtitle_segments(time_breaks) 40 | 41 | self.assertEqual(transcript_pages[0], "hi there my") 42 | 43 | def test_get_pages_given_subtitle_without_periods_and_past_timestamp_should_return_correct_pages( 44 | self, 45 | ): 46 | segments = [ 47 | SubtitlePart( 48 | get_timestamp("00:00:10"), 49 | get_timestamp("00:00:20"), 50 | "hi there my name is Bob", 51 | ) 52 | ] 53 | pager = SubtitleSegmentFinder(segments) 54 | time_breaks = [get_timestamp("00:00:05")] 55 | transcript_pages = pager.get_subtitle_segments(time_breaks) 56 | 57 | self.assertEqual(transcript_pages[0], "") 58 | 59 | def test_get_pages_given_subtitle_with_period_should_return_correct_pages(self): 60 | segments = [ 61 | SubtitlePart( 62 | get_timestamp("00:00:00"), 63 | get_timestamp("00:00:10"), 64 | "Hi. My name is Bob", 65 | ) 66 | ] 67 | pager = SubtitleSegmentFinder(segments) 68 | time_breaks = [get_timestamp("00:00:05")] 69 | transcript_pages = pager.get_subtitle_segments(time_breaks) 70 | self.assertEqual(transcript_pages[0], "Hi.") 71 | 72 | def test_get_pages_given_multiple_subtitle_segments_should_return_correct_pages( 73 | self, 74 | ): 75 | segments = [ 76 | SubtitlePart( 77 | get_timestamp("00:00:00"), 78 | get_timestamp("00:00:10"), 79 | "Hi. My name is Bob", 80 | ), 81 | SubtitlePart( 82 | get_timestamp("00:00:10"), 83 | get_timestamp("00:00:20"), 84 | "and his name is Alice. Today, we are", 85 | ), 86 | ] 87 | pager = SubtitleSegmentFinder(segments) 88 | time_breaks = [get_timestamp("00:00:02"), get_timestamp("00:00:15")] 89 | transcript_pages = pager.get_subtitle_segments(time_breaks) 90 | 91 | self.assertEqual(transcript_pages[0], "Hi.") 92 | self.assertEqual(transcript_pages[1], "My name is Bob and his name is Alice.") 93 | 94 | def test_get_pages_given_multiple_subtitle_segments_when_selecting_subtitle_at_break_should_return_correct_pages( 95 | self, 96 | ): 97 | segments = [ 98 | SubtitlePart( 99 | get_timestamp("00:00:00"), 100 | get_timestamp("00:00:10"), 101 | "Hi. My name is Bob", 102 | ), 103 | SubtitlePart( 104 | get_timestamp("00:00:10"), 105 | get_timestamp("00:00:20"), 106 | "and his name is Alice. Today, we are", 107 | ), 108 | ] 109 | pager = SubtitleSegmentFinder(segments) 110 | time_breaks = [get_timestamp("00:00:10"), get_timestamp("00:00:20")] 111 | transcript_pages = pager.get_subtitle_segments(time_breaks) 112 | 113 | self.assertEqual(len(transcript_pages), 2) 114 | self.assertEqual(transcript_pages[0], "Hi.") 115 | self.assertEqual( 116 | transcript_pages[1], "My name is Bob and his name is Alice. Today, we are" 117 | ) 118 | 119 | def test_get_pages_given_subtitle_1_should_return_correct_pages(self): 120 | segments = SubtitleWebVTTParser( 121 | "tests/subtitles/subtitles_1.vtt" 122 | ).get_subtitle_parts() 123 | pager = SubtitleSegmentFinder(segments) 124 | 125 | breaks = [ 126 | get_timestamp("00:00:14"), 127 | get_timestamp("00:02:10"), 128 | get_timestamp("00:05:38"), 129 | get_timestamp("00:07:58"), 130 | get_timestamp("00:10:37"), 131 | get_timestamp("00:10:52"), 132 | get_timestamp("00:10:54"), 133 | ] 134 | transcript_pages = pager.get_subtitle_segments(breaks) 135 | 136 | self.assertEqual(len(transcript_pages), 7) 137 | self.assertMatchSnapshot(transcript_pages) 138 | 139 | def test_get_pages_given_subtitle_8_should_return_correct_pages(self): 140 | segments = SubtitleSRTParser( 141 | "tests/subtitles/subtitles_8.srt" 142 | ).get_subtitle_parts() 143 | pager = SubtitleSegmentFinder(segments) 144 | 145 | breaks = [ 146 | get_timestamp("00:00:04"), 147 | get_timestamp("00:00:05"), 148 | get_timestamp("00:00:06"), 149 | get_timestamp("00:00:07"), 150 | get_timestamp("00:00:08"), 151 | get_timestamp("00:00:09"), 152 | get_timestamp("00:00:15"), 153 | get_timestamp("00:00:23"), 154 | get_timestamp("00:00:26"), 155 | get_timestamp("00:00:27"), 156 | get_timestamp("00:00:31"), 157 | get_timestamp("00:00:41"), 158 | get_timestamp("00:00:45"), 159 | get_timestamp("00:00:53"), 160 | get_timestamp("00:01:03"), 161 | get_timestamp("00:01:25"), 162 | get_timestamp("00:01:47"), 163 | get_timestamp("00:04:00"), 164 | get_timestamp("00:04:30"), 165 | get_timestamp("00:05:15"), 166 | get_timestamp("00:05:58"), 167 | get_timestamp("00:07:33"), 168 | get_timestamp("00:08:04"), 169 | get_timestamp("00:08:24"), 170 | get_timestamp("00:09:02"), 171 | get_timestamp("00:09:42"), 172 | get_timestamp("00:10:00"), 173 | ] 174 | transcript_pages = pager.get_subtitle_segments(breaks) 175 | 176 | self.assertEqual(len(transcript_pages), 27) 177 | self.assertMatchSnapshot(transcript_pages) 178 | 179 | def test_get_pages_given_subtitles_with_no_dots_should_return_correct_pages(self): 180 | segments = [ 181 | SubtitlePart( 182 | get_timestamp("00:00:00"), 183 | get_timestamp("00:00:10"), 184 | "Hi my name is Bob", 185 | ), 186 | SubtitlePart( 187 | get_timestamp("00:00:10"), 188 | get_timestamp("00:00:20"), 189 | "and his name is Alice Today, we are", 190 | ), 191 | ] 192 | pager = SubtitleSegmentFinder(segments) 193 | time_breaks = [get_timestamp("00:00:08"), get_timestamp("00:00:20")] 194 | transcript_pages = pager.get_subtitle_segments(time_breaks) 195 | 196 | self.assertEqual(len(transcript_pages), 2) 197 | self.assertEqual(transcript_pages[0], "Hi my name is") 198 | self.assertEqual(transcript_pages[1], "Bob and his name is Alice Today, we are") 199 | -------------------------------------------------------------------------------- /tests/test_subtitle_srt_parser.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import unittest 3 | from src.time_utils import convert_clock_time_to_timestamp_ms as get_timestamp 4 | from src.subtitle_srt_parser import SubtitleSRTParser 5 | 6 | 7 | class SubtitleSRTParserTests(unittest.TestCase): 8 | def test_get_subtitle_parts_given_subtitles_should_return_correct_subtitles(self): 9 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 10 | tmpFile.writelines( 11 | [ 12 | "1\n", 13 | "00:00:00,000 --> 00:00:04,134\n", 14 | "So now that we understand what a secure\n", 15 | "PRG is, and we understand what semantic\n", 16 | "\n", 17 | "2\n", 18 | "00:00:04,134 --> 00:00:08,425\n", 19 | "security means, we can actually argue that\n", 20 | "a stream cipher with a secure PRG is, in\n", 21 | ] 22 | ) 23 | tmpFile.flush() 24 | 25 | segments = SubtitleSRTParser(tmpFile.name).get_subtitle_parts() 26 | 27 | self.assertEqual(len(segments), 2) 28 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 29 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:04.134")) 30 | self.assertEqual( 31 | segments[0].text, 32 | "So now that we understand what a secure PRG is, and we understand what semantic", 33 | ) 34 | 35 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:04.134")) 36 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:08.425")) 37 | self.assertEqual( 38 | segments[1].text, 39 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 40 | ) 41 | 42 | def test_get_subtitle_parts_given_subtitles_with_no_text_should_not_include_empty_subtitles( 43 | self, 44 | ): 45 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 46 | tmpFile.writelines( 47 | [ 48 | "1\n", 49 | "00:00:00,000 --> 00:00:04,134\n", 50 | "So now that we understand what a secure\n", 51 | "PRG is, and we understand what semantic\n", 52 | "\n", 53 | "2\n", 54 | "00:00:04,134 --> 00:00:10,134\n", 55 | "\n", 56 | "\n", 57 | "\n", 58 | "3\n", 59 | "00:00:10,134 --> 00:00:18,425\n", 60 | "security means, we can actually argue that\n", 61 | "a stream cipher with a secure PRG is, in\n", 62 | ] 63 | ) 64 | tmpFile.flush() 65 | 66 | segments = SubtitleSRTParser(tmpFile.name).get_subtitle_parts() 67 | 68 | self.assertEqual(len(segments), 2) 69 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 70 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:10.134")) 71 | self.assertEqual( 72 | segments[0].text, 73 | "So now that we understand what a secure PRG is, and we understand what semantic", 74 | ) 75 | 76 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:10.134")) 77 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:18.425")) 78 | self.assertEqual( 79 | segments[1].text, 80 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 81 | ) 82 | 83 | def test_get_subtitle_parts_given_subtitles_that_are_not_continuous_should_return_correct_subtitles( 84 | self, 85 | ): 86 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 87 | tmpFile.writelines( 88 | [ 89 | "1\n", 90 | "00:00:00,000 --> 00:00:04,134\n", 91 | "So now that we understand what a secure\n", 92 | "PRG is, and we understand what semantic\n", 93 | "\n", 94 | "2\n", 95 | "00:00:04,134 --> 00:00:08,425\n", 96 | "security means, we can actually argue that\n", 97 | "a stream cipher with a secure PRG is, in\n", 98 | ] 99 | ) 100 | tmpFile.flush() 101 | 102 | segments = SubtitleSRTParser(tmpFile.name).get_subtitle_parts() 103 | 104 | self.assertEqual(len(segments), 2) 105 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 106 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:04.134")) 107 | self.assertEqual( 108 | segments[0].text, 109 | "So now that we understand what a secure PRG is, and we understand what semantic", 110 | ) 111 | 112 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:04.134")) 113 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:08.425")) 114 | self.assertEqual( 115 | segments[1].text, 116 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 117 | ) 118 | -------------------------------------------------------------------------------- /tests/test_subtitle_webvtt_parser.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import unittest 3 | from src.time_utils import convert_timestamp_ms_to_clock_time as get_clock_time 4 | from src.time_utils import convert_clock_time_to_timestamp_ms as get_timestamp 5 | from src.subtitle_webvtt_parser import SubtitleWebVTTParser 6 | 7 | 8 | class SubtitleWebVTTParserTests(unittest.TestCase): 9 | def test_get_subtitle_parts_given_subtitles_should_return_correct_subtitles(self): 10 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 11 | tmpFile.writelines( 12 | [ 13 | "WEBVTT\n", 14 | "\n", 15 | "1\n", 16 | "00:00:00.000 --> 00:00:04.134\n", 17 | "So now that we understand what a secure\n", 18 | "PRG is, and we understand what semantic\n", 19 | "\n", 20 | "2\n", 21 | "00:00:04.134 --> 00:00:08.425\n", 22 | "security means, we can actually argue that\n", 23 | "a stream cipher with a secure PRG is, in\n", 24 | ] 25 | ) 26 | tmpFile.flush() 27 | 28 | segments = SubtitleWebVTTParser(tmpFile.name).get_subtitle_parts() 29 | 30 | self.assertEqual(len(segments), 2) 31 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 32 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:04.134")) 33 | self.assertEqual( 34 | segments[0].text, 35 | "So now that we understand what a secure PRG is, and we understand what semantic", 36 | ) 37 | 38 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:04.134")) 39 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:08.425")) 40 | self.assertEqual( 41 | segments[1].text, 42 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 43 | ) 44 | 45 | def test_get_subtitle_parts_given_subtitles_with_no_text_should_not_include_empty_subtitles( 46 | self, 47 | ): 48 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 49 | tmpFile.writelines( 50 | [ 51 | "WEBVTT\n", 52 | "\n", 53 | "1\n", 54 | "00:00:00.000 --> 00:00:04.134\n", 55 | "So now that we understand what a secure\n", 56 | "PRG is, and we understand what semantic\n", 57 | "\n", 58 | "2\n", 59 | "00:00:04.134 --> 00:00:10.134\n", 60 | "\n", 61 | "\n", 62 | "\n", 63 | "3\n", 64 | "00:00:10.134 --> 00:00:18.425\n", 65 | "security means, we can actually argue that\n", 66 | "a stream cipher with a secure PRG is, in\n", 67 | ] 68 | ) 69 | tmpFile.flush() 70 | 71 | segments = SubtitleWebVTTParser(tmpFile.name).get_subtitle_parts() 72 | 73 | self.assertEqual(len(segments), 2) 74 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 75 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:10.134")) 76 | self.assertEqual( 77 | segments[0].text, 78 | "So now that we understand what a secure PRG is, and we understand what semantic", 79 | ) 80 | 81 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:10.134")) 82 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:18.425")) 83 | self.assertEqual( 84 | segments[1].text, 85 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 86 | ) 87 | 88 | def test_get_subtitle_parts_given_subtitles_that_are_not_continuous_should_return_correct_subtitles( 89 | self, 90 | ): 91 | with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as tmpFile: 92 | tmpFile.writelines( 93 | [ 94 | "WEBVTT\n", 95 | "\n", 96 | "1\n", 97 | "00:00:00.000 --> 00:00:04.134\n", 98 | "So now that we understand what a secure\n", 99 | "PRG is, and we understand what semantic\n", 100 | "\n", 101 | "2\n", 102 | "00:00:05.000 --> 00:00:08.425\n", 103 | "security means, we can actually argue that\n", 104 | "a stream cipher with a secure PRG is, in\n", 105 | ] 106 | ) 107 | tmpFile.flush() 108 | 109 | segments = SubtitleWebVTTParser(tmpFile.name).get_subtitle_parts() 110 | 111 | self.assertEqual(len(segments), 2) 112 | self.assertEqual(segments[0].start_time, get_timestamp("00:00:00")) 113 | self.assertEqual(segments[0].end_time, get_timestamp("00:00:05.000")) 114 | self.assertEqual( 115 | segments[0].text, 116 | "So now that we understand what a secure PRG is, and we understand what semantic", 117 | ) 118 | 119 | self.assertEqual(segments[1].start_time, get_timestamp("00:00:05.000")) 120 | self.assertEqual(segments[1].end_time, get_timestamp("00:00:08.425")) 121 | self.assertEqual( 122 | segments[1].text, 123 | "security means, we can actually argue that a stream cipher with a secure PRG is, in", 124 | ) 125 | -------------------------------------------------------------------------------- /tests/test_time_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from src.time_utils import convert_timestamp_ms_to_clock_time as get_clock_time 3 | from src.time_utils import convert_clock_time_to_timestamp_ms as get_timestamp 4 | 5 | 6 | class TimeUtilsTests(unittest.TestCase): 7 | def test_given_hh_mm_ss_it_should_convert_to_clock_time_correctly(self): 8 | self.assertEqual(get_clock_time(7538000), "02:05:38") 9 | 10 | def test_given_mm_ss_it_should_convert_to_clock_time_correctly(self): 11 | self.assertEqual(get_clock_time(338000), "00:05:38") 12 | 13 | def test_given_seconds_it_should_convert_to_clock_time_correctly(self): 14 | self.assertEqual(get_clock_time(38456), "00:00:38.456") 15 | 16 | def test_given_zero_seconds_it_should_convert_to_clock_time_correctly(self): 17 | self.assertEqual(get_clock_time(456), "00:00:00.456") 18 | 19 | def test_given_timestamp_ms_with_hours_it_should_convert_to_timestamp_ms_correctly( 20 | self, 21 | ): 22 | self.assertEqual(get_timestamp("02:05:38"), 7538000) 23 | 24 | def test_given_time_without_hours_it_should_convert_to_timestamp_ms_correctly(self): 25 | self.assertEqual(get_timestamp("00:05:38"), 338000) 26 | 27 | def test_given_time_minutes_or_hours_it_should_convert_to_timestamp_ms_correctly( 28 | self, 29 | ): 30 | self.assertEqual(get_timestamp("00:00:38.456"), 38456) 31 | 32 | def test_given_zero_seconds_it_should_convert_to_timestamp_ms_correctly(self): 33 | self.assertEqual(get_timestamp("00:00:00.456"), 456) 34 | -------------------------------------------------------------------------------- /tests/test_video_segment_finder.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from src.video_segment_finder import VideoSegmentFinder # get_frames 3 | from src.time_utils import convert_timestamp_ms_to_clock_time as get_clock 4 | 5 | 6 | class VideoBreaksTest(unittest.TestCase): 7 | def test_get_frames_of_video_with_human_should_return_correct_breaks(self): 8 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_1.mp4") 9 | # data = get_frames('videos/input_1.mp4') 10 | frame_nums = sorted(data.keys()) 11 | 12 | self.assertEqual(len(frame_nums), 7) 13 | 14 | # Check if the timestamps (in ms) matches the ones that we picked out manually 15 | self.assertEqual( 16 | get_clock(data[frame_nums[0]]["timestamp"]), "00:00:14.147480814147482" 17 | ) 18 | self.assertEqual( 19 | get_clock(data[frame_nums[1]]["timestamp"]), "00:02:10.330330330330325" 20 | ) 21 | self.assertEqual( 22 | get_clock(data[frame_nums[2]]["timestamp"]), "00:05:38.071404738071436" 23 | ) 24 | self.assertEqual( 25 | get_clock(data[frame_nums[3]]["timestamp"]), "00:07:58.41174507841177" 26 | ) 27 | self.assertEqual( 28 | get_clock(data[frame_nums[4]]["timestamp"]), "00:10:37.53753753753752" 29 | ) 30 | self.assertEqual( 31 | get_clock(data[frame_nums[5]]["timestamp"]), "00:10:52.05205205205211" 32 | ) 33 | self.assertEqual( 34 | get_clock(data[frame_nums[6]]["timestamp"]), "00:10:54.38772105438775" 35 | ) 36 | 37 | def test_get_frames_of_video_without_human_should_return_correct_breaks(self): 38 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_2.mp4") 39 | frame_nums = sorted(data.keys()) 40 | 41 | self.assertEqual(len(frame_nums), 7) 42 | 43 | # Check if the timestamps (in ms) matches the ones that we picked out manually 44 | self.assertEqual( 45 | get_clock(data[frame_nums[0]]["timestamp"]), "00:00:04.337671004337671" 46 | ) 47 | self.assertEqual( 48 | get_clock(data[frame_nums[1]]["timestamp"]), "00:00:49.215882549215884" 49 | ) 50 | self.assertEqual( 51 | get_clock(data[frame_nums[2]]["timestamp"]), "00:04:10.784117450784136" 52 | ) 53 | self.assertEqual( 54 | get_clock(data[frame_nums[3]]["timestamp"]), "00:07:59.01234567901236" 55 | ) 56 | self.assertEqual( 57 | get_clock(data[frame_nums[4]]["timestamp"]), "00:11:09.669669669669704" 58 | ) 59 | self.assertEqual( 60 | get_clock(data[frame_nums[5]]["timestamp"]), "00:12:24.878211544878198" 61 | ) 62 | self.assertEqual( 63 | get_clock(data[frame_nums[6]]["timestamp"]), "00:12:34.788121454788254" 64 | ) 65 | 66 | def test_get_frames_of_video_with_lots_of_animations_should_return_correct_breaks( 67 | self, 68 | ): 69 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_3.mp4") 70 | frame_nums = sorted(data.keys()) 71 | 72 | self.assertEqual(len(frame_nums), 12) 73 | 74 | # Check if the timestamps (in ms) matches the ones that we picked out manually 75 | self.assertEqual( 76 | get_clock(data[frame_nums[0]]["timestamp"]), "00:00:37.69527777777778" 77 | ) 78 | self.assertEqual( 79 | get_clock(data[frame_nums[1]]["timestamp"]), "00:00:56.49292222222223" 80 | ) 81 | self.assertEqual( 82 | get_clock(data[frame_nums[2]]["timestamp"]), "00:01:13.5407888888889" 83 | ) 84 | self.assertEqual( 85 | get_clock(data[frame_nums[3]]["timestamp"]), "00:01:43.53703333333334" 86 | ) 87 | self.assertEqual( 88 | get_clock(data[frame_nums[4]]["timestamp"]), "00:02:57.783333333333346" 89 | ) 90 | self.assertEqual( 91 | get_clock(data[frame_nums[5]]["timestamp"]), "00:03:33.183333333333344" 92 | ) 93 | self.assertEqual( 94 | get_clock(data[frame_nums[6]]["timestamp"]), "00:03:45.98333333333334" 95 | ) 96 | self.assertEqual( 97 | get_clock(data[frame_nums[7]]["timestamp"]), "00:03:59.183333333333344" 98 | ) 99 | self.assertEqual( 100 | get_clock(data[frame_nums[8]]["timestamp"]), "00:04:09.833333333333343" 101 | ) 102 | self.assertEqual( 103 | get_clock(data[frame_nums[9]]["timestamp"]), "00:04:42.48333333333337" 104 | ) 105 | self.assertEqual( 106 | get_clock(data[frame_nums[10]]["timestamp"]), "00:05:52.933333333333316" 107 | ) 108 | self.assertEqual( 109 | get_clock(data[frame_nums[11]]["timestamp"]), "00:06:40.98333333333337" 110 | ) 111 | 112 | def test_get_frames_of_video_with_blur_animations_should_return_correct_breaks( 113 | self, 114 | ): 115 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_4.mp4") 116 | frame_nums = sorted(data.keys()) 117 | 118 | self.assertEqual(len(frame_nums), 2) 119 | 120 | # Check if the timestamps (in ms) matches the ones that we picked out manually 121 | self.assertEqual( 122 | get_clock(data[frame_nums[0]]["timestamp"]), "00:00:03.7495333333333334" 123 | ) 124 | self.assertEqual( 125 | get_clock(data[frame_nums[1]]["timestamp"]), "00:00:07.649044444444445" 126 | ) 127 | 128 | def test_get_frames_of_video_with_blur_annotations_should_return_correct_breaks( 129 | self, 130 | ): 131 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_5.mp4") 132 | frame_nums = sorted(data.keys()) 133 | 134 | self.assertEqual(len(frame_nums), 2) 135 | 136 | # Check if the timestamps (in ms) matches the ones that we picked out manually 137 | self.assertEqual( 138 | get_clock(data[frame_nums[0]]["timestamp"]), "00:01:54.34768101434769" 139 | ) 140 | self.assertEqual( 141 | get_clock(data[frame_nums[1]]["timestamp"]), "00:02:25.47881214547882" 142 | ) 143 | 144 | def test_get_frames_of_video_with_add_animations_should_return_correct_breaks(self): 145 | data = VideoSegmentFinder().get_best_segment_frames("tests/videos/input_6.mp4") 146 | frame_nums = sorted(data.keys()) 147 | 148 | self.assertEqual(len(frame_nums), 3) 149 | 150 | # Check if the timestamps (in ms) matches the ones that we picked out manually 151 | self.assertEqual(get_clock(data[frame_nums[0]]["timestamp"]), "00:01:31.15") 152 | self.assertEqual( 153 | get_clock(data[frame_nums[1]]["timestamp"]), "00:01:34.850000000000016" 154 | ) 155 | self.assertEqual(get_clock(data[frame_nums[2]]["timestamp"]), "00:01:41.5") 156 | -------------------------------------------------------------------------------- /tests/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/utils/__init__.py -------------------------------------------------------------------------------- /tests/utils/pdf_snapshot.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import os 3 | from os import path 4 | import shutil 5 | import pypdftk 6 | from wand.image import Image 7 | 8 | 9 | def assert_match_pdf_snapshot(expected_filepath, actual_filepath, max_diff_val=0.0): 10 | """Verifies if the pdf matches the expected pdf snapshot 11 | If the pdf file doesn't exist yet, it will save it 12 | 13 | Parameters 14 | ---------- 15 | expected_filepath : str 16 | The file path to the expected pdf file 17 | actual_filepath: str 18 | The file path to the actual pdf file (must be different than expected_filepath) 19 | max_diff_val: num 20 | The max. value the difference between any pages, from 0-100 21 | """ 22 | 23 | if not path.exists(actual_filepath): 24 | raise ValueError(f"Actual file {actual_filepath} doesn't exist") 25 | 26 | if not path.exists(expected_filepath): 27 | os.makedirs(os.path.dirname(expected_filepath), exist_ok=True) 28 | shutil.copy(actual_filepath, expected_filepath) 29 | else: 30 | # Get num pages for each pdf 31 | expected_num_pages = pypdftk.get_num_pages(expected_filepath) 32 | actual_num_pages = pypdftk.get_num_pages(actual_filepath) 33 | 34 | if expected_num_pages != actual_num_pages: 35 | raise ValueError( 36 | f"Expected {expected_num_pages} num pages; got {actual_num_pages} pages" 37 | ) 38 | 39 | # Create temp dirs for each pdf 40 | try: 41 | expected_split_dir = tempfile.TemporaryDirectory() 42 | actual_split_dir = tempfile.TemporaryDirectory() 43 | 44 | # Split the pdf into different pages 45 | exp_split_files = pypdftk.split(expected_filepath, expected_split_dir.name)[ 46 | 1: 47 | ] 48 | act_split_files = pypdftk.split(actual_filepath, actual_split_dir.name)[1:] 49 | 50 | # Compare each page 51 | has_diff = False 52 | for page_idx in range(len(exp_split_files)): 53 | with Image(filename=exp_split_files[page_idx]) as expected_page: 54 | with Image(filename=act_split_files[page_idx]) as actual_page: 55 | expected_page.fuzz = 0.25 * expected_page.quantum_range 56 | expected_page.artifacts["compare:highlight-color"] = "red" 57 | expected_page.artifacts[ 58 | "compare:lowlight-color" 59 | ] = "transparent" 60 | diff_img, diff_val = expected_page.compare( 61 | actual_page, "root_mean_square" 62 | ) 63 | 64 | if diff_val > max_diff_val: 65 | diff_img_filepath = os.path.join( 66 | os.path.dirname(expected_filepath), 67 | f"{os.path.basename(expected_filepath)}-{page_idx}-diff.jpg", 68 | ) 69 | diff_img.save(filename=diff_img_filepath) 70 | has_diff = True 71 | 72 | diff_img.close() 73 | 74 | if has_diff: 75 | print("One or more pages in the pdf is different") 76 | print(f"See folder in {os.path.dirname(expected_filepath)} for diff") 77 | raise ValueError() 78 | finally: 79 | # Clean up the dirs 80 | expected_split_dir.cleanup() 81 | actual_split_dir.cleanup() 82 | -------------------------------------------------------------------------------- /tests/videos/input_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_1.mp4 -------------------------------------------------------------------------------- /tests/videos/input_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_2.mp4 -------------------------------------------------------------------------------- /tests/videos/input_3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_3.mp4 -------------------------------------------------------------------------------- /tests/videos/input_4.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_4.mp4 -------------------------------------------------------------------------------- /tests/videos/input_5.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_5.mp4 -------------------------------------------------------------------------------- /tests/videos/input_6.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_6.mp4 -------------------------------------------------------------------------------- /tests/videos/input_7.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_7.mp4 -------------------------------------------------------------------------------- /tests/videos/input_8.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EKarton/Lecture-Video-to-PDF/acad45548ed706d10b0820bb66549690f6a8c16d/tests/videos/input_8.mp4 --------------------------------------------------------------------------------