├── .gitignore ├── LICENSE ├── README.md ├── bin ├── youtube-drive └── youtube-drive.bat ├── examples ├── BesselJ.png └── painting.jpg ├── requirements.txt ├── setup.py └── youtube_drive ├── __init__.py ├── __main__.py ├── config.py ├── main.py └── youtube_codec.py /.gitignore: -------------------------------------------------------------------------------- 1 | # projects files 2 | painting-retrieved*.jpg 3 | *.mp4 4 | 5 | # MacOS 6 | .DS_Store 7 | .vscode/ 8 | 9 | # Byte-compiled / optimized / DLL files 10 | __pycache__/ 11 | *.py[cod] 12 | *$py.class 13 | 14 | # C extensions 15 | *.so 16 | 17 | # Distribution / packaging 18 | .Python 19 | build/ 20 | develop-eggs/ 21 | dist/ 22 | downloads/ 23 | eggs/ 24 | .eggs/ 25 | lib/ 26 | lib64/ 27 | parts/ 28 | sdist/ 29 | var/ 30 | wheels/ 31 | pip-wheel-metadata/ 32 | share/python-wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | MANIFEST 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .nox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *.cover 58 | *.py,cover 59 | .hypothesis/ 60 | .pytest_cache/ 61 | 62 | # Translations 63 | *.mo 64 | *.pot 65 | 66 | # Django stuff: 67 | *.log 68 | local_settings.py 69 | db.sqlite3 70 | db.sqlite3-journal 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | target/ 84 | 85 | # Jupyter Notebook 86 | .ipynb_checkpoints 87 | 88 | # IPython 89 | profile_default/ 90 | ipython_config.py 91 | 92 | # pyenv 93 | .python-version 94 | 95 | # pipenv 96 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 97 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 98 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 99 | # install all needed dependencies. 100 | #Pipfile.lock 101 | 102 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 103 | __pypackages__/ 104 | 105 | # Celery stuff 106 | celerybeat-schedule 107 | celerybeat.pid 108 | 109 | # SageMath parsed files 110 | *.sage.py 111 | 112 | # Environments 113 | .env 114 | .venv 115 | env/ 116 | venv/ 117 | ENV/ 118 | env.bak/ 119 | venv.bak/ 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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # youtube-drive 2 | 3 | youtube-drive is totally inspired by [YouTubeDrive](https://github.com/dzhang314/YouTubeDrive), a Wolfram Language (aka Mathematica) package. I read the source code of **YouTubeDrive** and write a Python version with a little change for fun. 4 | 5 | **youtube-drive** is a Python library encodes/decodes arbitrary data to/from simple RGB videos which are automatically uploaded to/downloaded from YouTube. Since YouTube imposes no limits on the total number or length of videos users can upload, this provides an effectively infinite but extremely slow form of file storage. 6 | 7 | youtube-drive is a silly proof-of-concept, and I do not endorse its high-volume use either. 8 | 9 | ## Usage Example 10 | 11 | **Upload**: Encode a file to video and upload to YouTube: 12 | 13 | ```sh 14 | python -m youtube_drive upload examples/BesselJ.png 15 | YouTube Video ID: EzqstWlMXyk 16 | YouTube: https://youtu.be/EzqstWlMXyk 17 | 18 | ``` 19 | 20 | **Retrieve**: Download the video from YouTube and decode to a file: 21 | 22 | ```sh 23 | python -m youtube_drive retrieve --video-id=EzqstWlMXyk -o BesselJ-retrieved.png 24 | /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4 25 | [youtube] EzqstWlMXyk: Downloading webpage 26 | [youtube] EzqstWlMXyk: Downloading MPD manifest 27 | [download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4 28 | [download] 100% of 1.74MiB in 00:25 29 | [download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140 30 | [download] 100% of 58.70KiB in 00:03 31 | [ffmpeg] Merging formats into "/var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4" 32 | Deleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4 (pass -k to keep) 33 | Deleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140 (pass -k to keep) 34 | ``` 35 | 36 | The video, video ID is **EzqstWlMXyk**, youtube-drive produces in this example can be viewed at https://youtu.be/EzqstWlMXyk. The video is encoded from the image [BesselJ.png](https://github.com/lewangdev/youtube-drive/blob/main/examples/BesselJ.png). A 62KB image file will produce a video of size 10+MB. 37 | 38 | Another file I uploaded to YouTube is [painting.jpg](https://github.com/lewangdev/youtube-drive/blob/main/examples/painting.jpg), it produces a video of size 127.5MB, and the original size is 476KB. The video can be viewed at https://youtu.be/gKhXk3IGW2s. 39 | 40 | I use opencv to produce mp4 video, if use ffmpeg with optimizing directly, the video maybe compress to a more smaller size. 41 | 42 | **AGAIN:** It is a silly idea, just for fun. 43 | 44 | ## Installation 45 | 46 | **Notice**: 47 | 48 | - I only test with **Python 3.8 & 3.9 & 3.10** on **MacOS** with ffmpeg installed. 49 | - If it works on your system, please feel free to let me know. Thanks. 50 | 51 | For development: 52 | 53 | ```sh 54 | git clone https://github.com/lewangdev/youtube-drive.git 55 | cd youtube-drive 56 | python -m venv .venv 57 | . .venv/bin/activate 58 | pip install -r requirements.txt 59 | ``` 60 | 61 | Or run directly from sources: 62 | 63 | ```sh 64 | git clone https://github.com/lewangdev/youtube-drive.git 65 | cd youtube-drive 66 | python -m venv .venv 67 | . .venv/bin/activate 68 | python setup.py install 69 | ``` 70 | 71 | ## Setup 72 | 73 | The first time you try to upload a video to YouTube, you will be asked to follow a URL in your browser to get an authentication token. If you have multiple channels for the logged in user, you will also be asked to pick which one you want to upload the videos to. 74 | 75 | You now need to create and use your own OAuth 2.0 file, it's a free service. Steps: 76 | 77 | Go to the [Google Cloud Console](https://console.cloud.google.com/). 78 | 79 | - Create project. 80 | - Side menu: APIs & Services -> OAuth consent screen: Create app and add the test user you will updoad videos to. 81 | - Side menu: APIs & Services -> Enabled API & services -> ENABLED API AND SERVICES -> Search `youtube` -> Choose `YouTube Data API v3` and enable it. 82 | - Side menu: APIs & Services -> Credentials -> Create Credentials -> OAuth client ID: Application type choose `Desktop app`. 83 | - Download JSON: Under the section "OAuth 2.0 client IDs". Save the file to your local system. 84 | Use this JSON as your credentials file: copy it to ~/.client_secrets.json. 85 | Note: client_secrets.json is a file you can download from the developer console, the credentials file is something auto generated after the first time the script is run and the google account sign in is followed, the file is stored at ~/.youtube-upload-credentials.json. 86 | 87 | If you feel any difficulty to create OAuth 2.0 file, here is the video I made for you: https://youtu.be/kL2oFZt2xHM 88 | 89 | ## Usage 90 | 91 | **Commands:** 92 | 93 | ```sh 94 | python -m youtube_drive -h 95 | usage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ... 96 | 97 | options: 98 | -h, --help show this help message and exit 99 | 100 | commands: 101 | {encode,en,decode,de,upload,up,retrieve,r} 102 | encode (en) encode a file to mp4 video 103 | decode (de) decode a video to a file 104 | upload (up) upload a file to YouTube 105 | retrieve (r) retrieve a video from YouTube save as 106 | 107 | ``` 108 | 109 | If you install from source, you can run the script directly: 110 | 111 | ```sh 112 | youtube-drive -h 113 | usage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ... 114 | 115 | options: 116 | -h, --help show this help message and exit 117 | 118 | commands: 119 | {encode,en,decode,de,upload,up,retrieve,r} 120 | encode (en) encode a file to mp4 video 121 | decode (de) decode a video to a file 122 | upload (up) upload a file to YouTube 123 | retrieve (r) retrieve a video from YouTube save as 124 | 125 | ``` 126 | 127 | **Upload:** 128 | 129 | ```sh 130 | python -m youtube_drive up -h 131 | usage: youtube-drive upload [-h] filename 132 | 133 | positional arguments: 134 | filename encode file to a video and upload to YouTube 135 | 136 | options: 137 | -h, --help show this help message and exit 138 | 139 | ``` 140 | 141 | **Retrieve:** 142 | 143 | ```sh 144 | python -m youtube_drive r -h 145 | usage: youtube-drive retrieve [-h] [--video-id video_id] [-o filename] 146 | 147 | options: 148 | -h, --help show this help message and exit 149 | --video-id video_id download YouTube video with 150 | -o filename save file to 151 | 152 | ``` 153 | 154 | **Local Encode:** 155 | 156 | ```sh 157 | python -m youtube_drive en -h 158 | usage: youtube-drive encode [-h] [-i input_filename] [--video-fps video_fps] video_filename 159 | 160 | positional arguments: 161 | video_filename save the video to this filename 162 | 163 | options: 164 | -h, --help show this help message and exit 165 | -i input_filename encode file to a video 166 | --video-fps video_fps 167 | set video fps, default value is 20 168 | 169 | ``` 170 | 171 | **Local Decode:** 172 | 173 | ``` 174 | python -m youtube_drive de -h 175 | usage: youtube-drive decode [-h] [-i input_video_filename] filename 176 | 177 | positional arguments: 178 | filename Save the output file to this filename 179 | 180 | options: 181 | -h, --help show this help message and exit 182 | -i input_video_filename 183 | decode the video to a file 184 | ``` 185 | 186 | ## The difference between **youtube-drive** and **YouTubeDrive** 187 | 188 | I add 4 bytes for representing data length at the beginning for the file for easily padding to video frames 189 | -------------------------------------------------------------------------------- /bin/youtube-drive: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | if __name__ == '__main__': 4 | 5 | # Allows you to a relative import from the parent folder 6 | import os.path 7 | import sys 8 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) 9 | 10 | from youtube_upload import main 11 | main.run() 12 | -------------------------------------------------------------------------------- /bin/youtube-drive.bat: -------------------------------------------------------------------------------- 1 | @python %~dp0youtube-drive %* -------------------------------------------------------------------------------- /examples/BesselJ.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lewangdev/youtube-drive/9f4dde40f38bdc48a8e0c937f4b0ba04f73505da/examples/BesselJ.png -------------------------------------------------------------------------------- /examples/painting.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lewangdev/youtube-drive/9f4dde40f38bdc48a8e0c937f4b0ba04f73505da/examples/painting.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | opencv-python 3 | pillow 4 | youtube-dl 5 | # youtube-upload 6 | git+https://github.com/tokland/youtube-upload.git 7 | PyCryptodome==3.17.0 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """Store files as YouTube videos.""" 3 | from distutils.core import setup 4 | 5 | setup_kwargs = { 6 | "name": "youtube-drive", 7 | "version": "0.0.1", 8 | "description": "Store files as YouTube videos", 9 | "author": "Le Wang", 10 | "author_email": "lewang.dev@gmail.com", 11 | "url": "https://github.com/lewangdev/youtube-drive", 12 | "packages": ["youtube_drive/"], 13 | "scripts": ["bin/youtube-drive"], 14 | "license": "Apache-2.0 license", 15 | "long_description": " ".join(__doc__.strip().splitlines()), 16 | "classifiers": [ 17 | 'Topic :: Internet :: WWW/HTTP', 18 | 'Development Status :: 4 - Beta', 19 | 'Environment :: Console', 20 | 'License :: OSI Approved :: Apache Software License', 21 | 'Operating System :: POSIX', 22 | 'Operating System :: Microsoft :: Windows', 23 | 'Programming Language :: Python :: 3', 24 | ], 25 | "entry_points": { 26 | 'console_scripts': [ 27 | 'youtube-drive = youtube_drive.main:run' 28 | ], 29 | }, 30 | "install_requires": [ 31 | 'numpy', 32 | 'opencv-python', 33 | 'youtube-dl', 34 | 'pillow', 35 | 'youtube-upload==0.8.0' 36 | ], 37 | "dependency_links": [ 38 | 'git+https://github.com/tokland/youtube-upload.git#egg=youtube-upload-0.8.0' 39 | ] 40 | } 41 | 42 | setup(**setup_kwargs) 43 | -------------------------------------------------------------------------------- /youtube_drive/__init__.py: -------------------------------------------------------------------------------- 1 | VERSION = "0.0.1" 2 | -------------------------------------------------------------------------------- /youtube_drive/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import unicode_literals 3 | 4 | # Execute with 5 | # $ python youtube_drive/__main__.py (2.6+) 6 | # $ python -m youtube_drive (2.7+) 7 | 8 | import sys 9 | 10 | if __package__ is None and not hasattr(sys, 'frozen'): 11 | # direct call of __main__.py 12 | import os.path 13 | path = os.path.realpath(os.path.abspath(__file__)) 14 | sys.path.insert(0, os.path.dirname(os.path.dirname(path))) 15 | 16 | import youtube_drive.main 17 | 18 | if __name__ == '__main__': 19 | youtube_drive.main.main(sys.argv[1:]) 20 | -------------------------------------------------------------------------------- /youtube_drive/config.py: -------------------------------------------------------------------------------- 1 | enable_encryption = False 2 | encryption_key = 'DefaultEncryptionKey' -------------------------------------------------------------------------------- /youtube_drive/main.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import os 3 | import sys 4 | import uuid 5 | import argparse 6 | import youtube_dl 7 | from youtube_upload import auth, lib, upload_video 8 | from . import youtube_codec 9 | 10 | 11 | def get_youtube_upload_handler(): 12 | """Return the API Youtube object.""" 13 | home = os.path.expanduser("~") 14 | client_secrets = os.path.join(home, ".client_secrets.json") 15 | credentials = os.path.join(home, ".youtube-upload-credentials.json") 16 | get_code_callback = (auth.console.get_code) 17 | return auth.get_resource(client_secrets, credentials, 18 | get_code_callback=get_code_callback) 19 | 20 | 21 | def upload_youtube_video(youtube, title, video_path): 22 | """Upload video with index (for split videos).""" 23 | u = lib.to_utf8 24 | title = u(title) 25 | 26 | request_body = { 27 | "snippet": { 28 | "title": title, 29 | "description": "", 30 | "categoryId": None, 31 | "tags": u(""), 32 | "defaultLanguage": None, 33 | "defaultAudioLanguage": None 34 | 35 | }, 36 | "status": { 37 | "embeddable": True, 38 | "privacyStatus": "unlisted", 39 | "publishAt": None, 40 | "license": "youtube", 41 | }, 42 | "recordingDetails": { 43 | "location": None, 44 | "recordingDate": None, 45 | }, 46 | } 47 | 48 | return upload_video.upload(youtube, video_path, request_body) 49 | 50 | 51 | def download_youtube_video(video_id, output_file_path): 52 | ydl_opts = {'outtmpl': output_file_path} 53 | with youtube_dl.YoutubeDL(ydl_opts) as ydl: 54 | ydl.download([f"https://www.youtube.com/watch?v={video_id}"]) 55 | 56 | 57 | def youtube_upload(upload_file_path): 58 | video_path = tempfile.mktemp(".mp4") 59 | youtube_codec.encode(upload_file_path, video_path) 60 | youtube = get_youtube_upload_handler() 61 | video_id = upload_youtube_video(youtube, f"DATA-{str(uuid.uuid4()).upper()}", video_path) 62 | os.remove(video_path) 63 | return video_id 64 | 65 | 66 | def youtube_retrieve(video_id, output_file_path): 67 | video_path = tempfile.mktemp(".mp4") 68 | print(video_path) 69 | download_youtube_video(video_id, video_path) 70 | youtube_codec.decode(video_path, output_file_path) 71 | 72 | 73 | def cmd_upload(args): 74 | video_id = youtube_upload(args.filename) 75 | print(f"YouTube Video ID: {video_id}", f"YouTube: https://youtu.be/{video_id}", sep="\n") 76 | 77 | 78 | def cmd_retrieve(args): 79 | youtube_retrieve(args.video_id, args.o) 80 | 81 | 82 | def cmd_encode(args): 83 | if args.encrypt and args.key is not None: 84 | args.key = str(args.key).encode("ascii")[:16] 85 | youtube_codec.encode(args.i, args.video_filename, args.encrypt, args.key, args.video_fps) 86 | 87 | 88 | def cmd_decode(args): 89 | if args.decrypt and args.key is not None: 90 | args.key = str(args.key).encode("ascii")[:16] 91 | youtube_codec.decode(args.i, args.filename, args.decrypt, args.key) 92 | 93 | 94 | def main(args): 95 | parser = argparse.ArgumentParser('youtube-drive') 96 | subparsers = parser.add_subparsers(title="commands") 97 | 98 | encode_parser = subparsers.add_parser('encode', aliases=['en'], help='encode a file to mp4 video') 99 | encode_parser.add_argument('-i', 100 | action='store', 101 | metavar="input_filename", 102 | help='encode file to a video') 103 | encode_parser.add_argument('--video-fps', 104 | action='store', 105 | metavar="video_fps", 106 | default=20, 107 | type=int, 108 | help='set video fps, default value is 20') 109 | encode_parser.add_argument('video_filename', 110 | action='store', 111 | help='save the video to this filename') 112 | encode_parser.add_argument('--encrypt', 113 | action='store_true', 114 | default=False, 115 | help='encrypt the file') 116 | encode_parser.add_argument('--key', 117 | action='store', 118 | metavar="encryption_key", 119 | default=None, 120 | help='encryption key') 121 | encode_parser.set_defaults(handle=cmd_encode) 122 | 123 | decode_parser = subparsers.add_parser('decode', aliases=['de'], help='decode a video to a file') 124 | decode_parser.add_argument('-i', 125 | action='store', 126 | metavar="input_video_filename", 127 | help='decode the video to a file') 128 | decode_parser.add_argument('filename', 129 | action='store', 130 | help='Save the output file to this filename') 131 | decode_parser.add_argument('--decrypt', 132 | action='store_true', 133 | default=False, 134 | help='decrypt the file') 135 | decode_parser.add_argument('--key', 136 | action='store', 137 | metavar="decryption_key", 138 | default=None, 139 | help='decryption key') 140 | decode_parser.set_defaults(handle=cmd_decode) 141 | 142 | upload_parser = subparsers.add_parser('upload', aliases=['up'], help='upload a file to YouTube') 143 | upload_parser.add_argument('filename', 144 | action='store', 145 | help='encode file to a video and upload to YouTube') 146 | upload_parser.set_defaults(handle=cmd_upload) 147 | 148 | retrieve_parser = subparsers.add_parser("retrieve", aliases=['r'], 149 | help="retrieve a video from YouTube save as ") 150 | retrieve_parser.add_argument('--video-id', 151 | action='store', 152 | metavar="video_id", 153 | help='download YouTube video with ') 154 | retrieve_parser.add_argument('-o', 155 | action='store', 156 | metavar="filename", 157 | help='save file to ') 158 | retrieve_parser.set_defaults(handle=cmd_retrieve) 159 | arguments = parser.parse_args(args) 160 | if not hasattr(arguments, 'handle'): 161 | parser.print_help() 162 | sys.exit(1) 163 | 164 | arguments.handle(arguments) 165 | 166 | 167 | def run(): 168 | main(sys.argv[1:]) 169 | 170 | 171 | if __name__ == '__main__': 172 | # video_id = youtebe_upload("./examples/upload.mp4") 173 | # print(f"video_id: {video_id}") 174 | # youtube_codec.encode("./examples/painting.jpg", "./examples/upload.mp4") 175 | # youtube_codec.decode("./examples/upload.mp4", "./examples/painting-retrieved.jpg") 176 | # youtube_retrieve("gKhXk3IGW2s", "./examples/painting-retrieved-3.jpg") 177 | main(sys.argv[1:]) 178 | -------------------------------------------------------------------------------- /youtube_drive/youtube_codec.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from PIL import Image 3 | import cv2 4 | 5 | import base64 6 | from Crypto.Cipher import AES 7 | from . import config 8 | 9 | ENABLE_ENCRYPTION = getattr(config, 'enable_encryption', False) 10 | KEY = getattr(config, 'encryption_key', 'DefaultEncryptionKey').encode("ascii")[:16] 11 | 12 | 13 | def quotient_remainder(divident, divsor): 14 | return divident // divsor, divident % divsor 15 | 16 | 17 | def color_value(x): 18 | return x*255 19 | 20 | 21 | def normal(x): 22 | return x/255 23 | 24 | 25 | def encrypt_data_aes(data: bytes, key: bytes) -> bytes: 26 | cipher = AES.new(key, AES.MODE_EAX) 27 | ciphertext, tag = cipher.encrypt_and_digest(data) 28 | return base64.urlsafe_b64encode(cipher.nonce + tag + ciphertext) 29 | 30 | 31 | def decrypt_data_aes(data: bytes, key: bytes) -> bytes: 32 | raw = base64.urlsafe_b64decode(data) 33 | nonce, tag, ciphertext = raw[:16], raw[16:32], raw[32:] 34 | 35 | cipher = AES.new(key, AES.MODE_EAX, nonce) 36 | clear_data = cipher.decrypt_and_verify(ciphertext, tag) 37 | return clear_data 38 | 39 | 40 | def encode(infile_path, outvideo_path, encrypt=ENABLE_ENCRYPTION, key=KEY, 41 | fps=20, num_cols_per_frame=64, num_rows_per_frame=36): 42 | fd = open(infile_path, 'rb') 43 | raw_data_bytes = fd.read() 44 | if encrypt: 45 | raw_data_bytes = encrypt_data_aes(raw_data_bytes, key) 46 | data_bytes = np.frombuffer(raw_data_bytes, dtype=np.uint8) 47 | len_of_data = len(data_bytes) 48 | num_bytes_per_row = int(num_cols_per_frame * 3 / 8) 49 | num_bytes_per_frame = num_bytes_per_row * num_rows_per_frame 50 | 51 | len_bytes = np.array(bytearray(len_of_data.to_bytes(4, byteorder='big')), dtype=np.uint8) 52 | (num_frames, num_leftover_bytes) = quotient_remainder(4 + len_of_data, num_bytes_per_frame) 53 | 54 | if num_leftover_bytes > 0: 55 | num_bytes_last_frame_padding = num_bytes_per_frame - num_leftover_bytes 56 | padding_bytes = np.full((num_bytes_last_frame_padding), 0, dtype=np.uint8) 57 | data_bytes = np.concatenate((len_bytes, data_bytes, padding_bytes)) 58 | num_frames += 1 59 | else: 60 | data_bytes = np.concatenate((len_bytes, data_bytes)) 61 | 62 | # Vedio: size=(1280, 720), fps=20 63 | size = (num_cols_per_frame * 20, num_rows_per_frame * 20) 64 | 65 | video = cv2.VideoWriter(outvideo_path, cv2.VideoWriter_fourcc( 66 | *'mp4v'), fps, size) 67 | 68 | for i in range(num_frames): 69 | frame_bytes = data_bytes[i * num_bytes_per_frame: (i + 1) * num_bytes_per_frame] 70 | frame_bits = np.unpackbits(frame_bytes) 71 | # Reshape array to array(36, 72, 3) 72 | frame = color_value(frame_bits).reshape(num_rows_per_frame, num_cols_per_frame, 3) 73 | img = Image.fromarray(frame, mode="RGB") 74 | # Scale image to (1280, 720) 75 | newimg = img.resize(size, Image.Resampling.BOX) 76 | video.write(np.asarray(newimg)) 77 | fd.close() 78 | 79 | 80 | def decode(invideo_path, outfile_path, decrypt=ENABLE_ENCRYPTION, key=KEY): 81 | i = 0 82 | step = 20 83 | data_bits_list = [] 84 | cap = cv2.VideoCapture(invideo_path) 85 | ret, frame = cap.read() 86 | while ret: 87 | frame_shape = np.shape(frame) 88 | for j in range(0, frame_shape[0], step): 89 | for k in range(0, frame_shape[1], step): 90 | piece = frame[j:j+step, k:k+step].reshape(step*step, 3) 91 | round = normal(piece.mean(0)).round().astype(np.uint8) 92 | data_bits_list.append(round) 93 | ret, frame = cap.read() 94 | i += 1 95 | cap.release() 96 | data_bits = np.array(data_bits_list).reshape(len(data_bits_list) * 3, 1) 97 | data_bytes = np.packbits(data_bits) 98 | len_of_data = int.from_bytes(data_bytes[:4], byteorder='big') 99 | data_bytes_retrieved = data_bytes[4:len_of_data+4].tobytes() 100 | if decrypt: 101 | data_bytes_retrieved = decrypt_data_aes(data_bytes_retrieved, key) 102 | fd = open(outfile_path, 'wb') 103 | fd.write(data_bytes_retrieved) 104 | fd.close() 105 | 106 | 107 | if __name__ == '__main__': 108 | # encode("../examples/painting.jpg", "../examples/upload.mp4") 109 | # decode("../examples/upload.mp4", "../examples/painting-retrieved2.jpg") 110 | pass 111 | --------------------------------------------------------------------------------