[
  {
    "path": ".gitignore",
    "content": "# projects files\npainting-retrieved*.jpg\n*.mp4\n\n# MacOS\n.DS_Store\n.vscode/\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# youtube-drive\n\nyoutube-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.\n\n**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.\n\nyoutube-drive is a silly proof-of-concept, and I do not endorse its high-volume use either.\n\n## Usage Example\n\n**Upload**: Encode a file to video and upload to YouTube:\n\n```sh\npython -m youtube_drive upload examples/BesselJ.png\nYouTube Video ID: EzqstWlMXyk\nYouTube: https://youtu.be/EzqstWlMXyk\n\n```\n\n**Retrieve**: Download the video from YouTube and decode to a file:\n\n```sh\npython -m youtube_drive retrieve --video-id=EzqstWlMXyk -o BesselJ-retrieved.png\n/var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4\n[youtube] EzqstWlMXyk: Downloading webpage\n[youtube] EzqstWlMXyk: Downloading MPD manifest\n[download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4\n[download] 100% of 1.74MiB in 00:25\n[download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140\n[download] 100% of 58.70KiB in 00:03\n[ffmpeg] Merging formats into \"/var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4\"\nDeleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4 (pass -k to keep)\nDeleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140 (pass -k to keep)\n```\n\nThe 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.\n\nAnother 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.\n\nI use opencv to produce mp4 video, if use ffmpeg with optimizing directly, the video maybe compress to a more smaller size.\n\n**AGAIN:** It is a silly idea, just for fun.\n\n## Installation\n\n**Notice**:\n\n- I only test with **Python 3.8 & 3.9 & 3.10** on **MacOS** with ffmpeg installed.\n- If it works on your system, please feel free to let me know. Thanks.\n\nFor development:\n\n```sh\ngit clone https://github.com/lewangdev/youtube-drive.git\ncd youtube-drive\npython -m venv .venv\n. .venv/bin/activate\npip install -r requirements.txt\n```\n\nOr run directly from sources:\n\n```sh\ngit clone https://github.com/lewangdev/youtube-drive.git\ncd youtube-drive\npython -m venv .venv\n. .venv/bin/activate\npython setup.py install\n```\n\n## Setup\n\nThe 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.\n\nYou now need to create and use your own OAuth 2.0 file, it's a free service. Steps:\n\nGo to the [Google Cloud Console](https://console.cloud.google.com/).\n\n- Create project.\n- Side menu: APIs & Services -> OAuth consent screen: Create app and add the test user you will updoad videos to.\n- Side menu: APIs & Services -> Enabled API & services -> ENABLED API AND SERVICES -> Search `youtube` -> Choose `YouTube Data API v3` and enable it.\n- Side menu: APIs & Services -> Credentials -> Create Credentials -> OAuth client ID: Application type choose `Desktop app`.\n- Download JSON: Under the section \"OAuth 2.0 client IDs\". Save the file to your local system.\n  Use this JSON as your credentials file: copy it to ~/.client_secrets.json.\n  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.\n\nIf you feel any difficulty to create OAuth 2.0 file, here is the video I made for you: https://youtu.be/kL2oFZt2xHM\n\n## Usage\n\n**Commands:**\n\n```sh\npython -m youtube_drive -h\nusage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ...\n\noptions:\n  -h, --help            show this help message and exit\n\ncommands:\n  {encode,en,decode,de,upload,up,retrieve,r}\n    encode (en)         encode a file to mp4 video\n    decode (de)         decode a video to a file\n    upload (up)         upload a file to YouTube\n    retrieve (r)        retrieve a video from YouTube save as <filename>\n\n```\n\nIf you install from source, you can run the script directly:\n\n```sh\nyoutube-drive -h\nusage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ...\n\noptions:\n  -h, --help            show this help message and exit\n\ncommands:\n  {encode,en,decode,de,upload,up,retrieve,r}\n    encode (en)         encode a file to mp4 video\n    decode (de)         decode a video to a file\n    upload (up)         upload a file to YouTube\n    retrieve (r)        retrieve a video from YouTube save as <filename>\n\n```\n\n**Upload:**\n\n```sh\npython -m youtube_drive up -h\nusage: youtube-drive upload [-h] filename\n\npositional arguments:\n  filename    encode file <filename> to a video and upload to YouTube\n\noptions:\n  -h, --help  show this help message and exit\n\n```\n\n**Retrieve:**\n\n```sh\npython -m youtube_drive r -h\nusage: youtube-drive retrieve [-h] [--video-id video_id] [-o filename]\n\noptions:\n  -h, --help           show this help message and exit\n  --video-id video_id  download YouTube video with <video_id>\n  -o filename          save file to <filename>\n\n```\n\n**Local Encode:**\n\n```sh\npython -m youtube_drive en -h\nusage: youtube-drive encode [-h] [-i input_filename] [--video-fps video_fps] video_filename\n\npositional arguments:\n  video_filename        save the video to this filename\n\noptions:\n  -h, --help            show this help message and exit\n  -i input_filename     encode file <input_filename> to a video\n  --video-fps video_fps\n                        set video fps, default value is 20\n\n```\n\n**Local Decode:**\n\n```\npython -m youtube_drive de -h\nusage: youtube-drive decode [-h] [-i input_video_filename] filename\n\npositional arguments:\n  filename              Save the output file to this filename\n\noptions:\n  -h, --help            show this help message and exit\n  -i input_video_filename\n                        decode the video <input_video_filename> to a file\n```\n\n## The difference between **youtube-drive** and **YouTubeDrive**\n\nI add 4 bytes for representing data length at the beginning for the file for easily padding to video frames\n"
  },
  {
    "path": "bin/youtube-drive",
    "content": "#!/usr/bin/env python\n\nif __name__ == '__main__':\n\n    # Allows you to a relative import from the parent folder\n    import os.path\n    import sys\n    sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))\n\n    from youtube_upload import main    \n    main.run()\n"
  },
  {
    "path": "bin/youtube-drive.bat",
    "content": "@python %~dp0youtube-drive %*"
  },
  {
    "path": "requirements.txt",
    "content": "numpy\nopencv-python\npillow\nyoutube-dl\n# youtube-upload\ngit+https://github.com/tokland/youtube-upload.git\nPyCryptodome==3.17.0"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/python\n\"\"\"Store files as YouTube videos.\"\"\"\nfrom distutils.core import setup\n\nsetup_kwargs = {\n    \"name\": \"youtube-drive\",\n    \"version\": \"0.0.1\",\n    \"description\": \"Store files as YouTube videos\",\n    \"author\": \"Le Wang\",\n    \"author_email\": \"lewang.dev@gmail.com\",\n    \"url\": \"https://github.com/lewangdev/youtube-drive\",\n    \"packages\": [\"youtube_drive/\"],\n    \"scripts\": [\"bin/youtube-drive\"],\n    \"license\": \"Apache-2.0 license\",\n    \"long_description\": \" \".join(__doc__.strip().splitlines()),\n    \"classifiers\": [\n        'Topic :: Internet :: WWW/HTTP',\n        'Development Status :: 4 - Beta',\n        'Environment :: Console',\n        'License :: OSI Approved :: Apache Software License',\n        'Operating System :: POSIX',\n        'Operating System :: Microsoft :: Windows',\n        'Programming Language :: Python :: 3',\n    ],\n    \"entry_points\": {\n        'console_scripts': [\n            'youtube-drive = youtube_drive.main:run'\n        ],\n    },\n    \"install_requires\": [\n        'numpy',\n        'opencv-python',\n        'youtube-dl',\n        'pillow',\n        'youtube-upload==0.8.0'\n    ],\n    \"dependency_links\": [\n        'git+https://github.com/tokland/youtube-upload.git#egg=youtube-upload-0.8.0'\n    ]\n}\n\nsetup(**setup_kwargs)\n"
  },
  {
    "path": "youtube_drive/__init__.py",
    "content": "VERSION = \"0.0.1\"\n"
  },
  {
    "path": "youtube_drive/__main__.py",
    "content": "#!/usr/bin/env python\nfrom __future__ import unicode_literals\n\n# Execute with\n# $ python youtube_drive/__main__.py (2.6+)\n# $ python -m youtube_drive          (2.7+)\n\nimport sys\n\nif __package__ is None and not hasattr(sys, 'frozen'):\n    # direct call of __main__.py\n    import os.path\n    path = os.path.realpath(os.path.abspath(__file__))\n    sys.path.insert(0, os.path.dirname(os.path.dirname(path)))\n\nimport youtube_drive.main\n\nif __name__ == '__main__':\n    youtube_drive.main.main(sys.argv[1:])\n"
  },
  {
    "path": "youtube_drive/config.py",
    "content": "enable_encryption = False\nencryption_key = 'DefaultEncryptionKey'"
  },
  {
    "path": "youtube_drive/main.py",
    "content": "import tempfile\nimport os\nimport sys\nimport uuid\nimport argparse\nimport youtube_dl\nfrom youtube_upload import auth, lib, upload_video\nfrom . import youtube_codec\n\n\ndef get_youtube_upload_handler():\n    \"\"\"Return the API Youtube object.\"\"\"\n    home = os.path.expanduser(\"~\")\n    client_secrets = os.path.join(home, \".client_secrets.json\")\n    credentials = os.path.join(home, \".youtube-upload-credentials.json\")\n    get_code_callback = (auth.console.get_code)\n    return auth.get_resource(client_secrets, credentials,\n                             get_code_callback=get_code_callback)\n\n\ndef upload_youtube_video(youtube, title, video_path):\n    \"\"\"Upload video with index (for split videos).\"\"\"\n    u = lib.to_utf8\n    title = u(title)\n\n    request_body = {\n        \"snippet\": {\n            \"title\": title,\n            \"description\": \"\",\n            \"categoryId\": None,\n            \"tags\": u(\"\"),\n            \"defaultLanguage\": None,\n            \"defaultAudioLanguage\": None\n\n        },\n        \"status\": {\n            \"embeddable\": True,\n            \"privacyStatus\": \"unlisted\",\n            \"publishAt\": None,\n            \"license\": \"youtube\",\n        },\n        \"recordingDetails\": {\n            \"location\": None,\n            \"recordingDate\": None,\n        },\n    }\n\n    return upload_video.upload(youtube, video_path, request_body)\n\n\ndef download_youtube_video(video_id, output_file_path):\n    ydl_opts = {'outtmpl': output_file_path}\n    with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n        ydl.download([f\"https://www.youtube.com/watch?v={video_id}\"])\n\n\ndef youtube_upload(upload_file_path):\n    video_path = tempfile.mktemp(\".mp4\")\n    youtube_codec.encode(upload_file_path, video_path)\n    youtube = get_youtube_upload_handler()\n    video_id = upload_youtube_video(youtube, f\"DATA-{str(uuid.uuid4()).upper()}\", video_path)\n    os.remove(video_path)\n    return video_id\n\n\ndef youtube_retrieve(video_id, output_file_path):\n    video_path = tempfile.mktemp(\".mp4\")\n    print(video_path)\n    download_youtube_video(video_id, video_path)\n    youtube_codec.decode(video_path, output_file_path)\n\n\ndef cmd_upload(args):\n    video_id = youtube_upload(args.filename)\n    print(f\"YouTube Video ID: {video_id}\", f\"YouTube: https://youtu.be/{video_id}\", sep=\"\\n\")\n\n\ndef cmd_retrieve(args):\n    youtube_retrieve(args.video_id, args.o)\n\n\ndef cmd_encode(args):\n    if args.encrypt and args.key is not None:\n        args.key = str(args.key).encode(\"ascii\")[:16]\n    youtube_codec.encode(args.i, args.video_filename, args.encrypt, args.key, args.video_fps)\n\n\ndef cmd_decode(args):\n    if args.decrypt and args.key is not None:\n        args.key = str(args.key).encode(\"ascii\")[:16]\n    youtube_codec.decode(args.i, args.filename, args.decrypt, args.key)\n\n\ndef main(args):\n    parser = argparse.ArgumentParser('youtube-drive')\n    subparsers = parser.add_subparsers(title=\"commands\")\n\n    encode_parser = subparsers.add_parser('encode', aliases=['en'], help='encode a file to mp4 video')\n    encode_parser.add_argument('-i',\n                               action='store',\n                               metavar=\"input_filename\",\n                               help='encode file <input_filename> to a video')\n    encode_parser.add_argument('--video-fps',\n                               action='store',\n                               metavar=\"video_fps\",\n                               default=20,\n                               type=int,\n                               help='set video fps, default value is 20')\n    encode_parser.add_argument('video_filename',\n                               action='store',\n                               help='save the video to this filename')\n    encode_parser.add_argument('--encrypt',\n                               action='store_true',\n                               default=False,\n                               help='encrypt the file')\n    encode_parser.add_argument('--key',\n                               action='store',\n                               metavar=\"encryption_key\",\n                               default=None,\n                               help='encryption key')\n    encode_parser.set_defaults(handle=cmd_encode)\n\n    decode_parser = subparsers.add_parser('decode', aliases=['de'], help='decode a video to a file')\n    decode_parser.add_argument('-i',\n                               action='store',\n                               metavar=\"input_video_filename\",\n                               help='decode the video <input_video_filename> to a file')\n    decode_parser.add_argument('filename',\n                               action='store',\n                               help='Save the output file to this filename')\n    decode_parser.add_argument('--decrypt',\n                               action='store_true',\n                               default=False,\n                               help='decrypt the file')\n    decode_parser.add_argument('--key',\n                               action='store',\n                               metavar=\"decryption_key\",\n                               default=None,\n                               help='decryption key')\n    decode_parser.set_defaults(handle=cmd_decode)\n\n    upload_parser = subparsers.add_parser('upload', aliases=['up'], help='upload a file to YouTube')\n    upload_parser.add_argument('filename',\n                               action='store',\n                               help='encode file <filename> to a video and upload to YouTube')\n    upload_parser.set_defaults(handle=cmd_upload)\n\n    retrieve_parser = subparsers.add_parser(\"retrieve\", aliases=['r'],\n                                            help=\"retrieve a video from YouTube save as <filename>\")\n    retrieve_parser.add_argument('--video-id',\n                                 action='store',\n                                 metavar=\"video_id\",\n                                 help='download YouTube video with <video_id>')\n    retrieve_parser.add_argument('-o',\n                                 action='store',\n                                 metavar=\"filename\",\n                                 help='save file to <filename>')\n    retrieve_parser.set_defaults(handle=cmd_retrieve)\n    arguments = parser.parse_args(args)\n    if not hasattr(arguments, 'handle'):\n        parser.print_help()\n        sys.exit(1)\n\n    arguments.handle(arguments)\n\n\ndef run():\n    main(sys.argv[1:])\n\n\nif __name__ == '__main__':\n    # video_id = youtebe_upload(\"./examples/upload.mp4\")\n    # print(f\"video_id: {video_id}\")\n    # youtube_codec.encode(\"./examples/painting.jpg\", \"./examples/upload.mp4\")\n    # youtube_codec.decode(\"./examples/upload.mp4\", \"./examples/painting-retrieved.jpg\")\n    # youtube_retrieve(\"gKhXk3IGW2s\", \"./examples/painting-retrieved-3.jpg\")\n    main(sys.argv[1:])\n"
  },
  {
    "path": "youtube_drive/youtube_codec.py",
    "content": "import numpy as np\nfrom PIL import Image\nimport cv2\n\nimport base64\nfrom Crypto.Cipher import AES\nfrom . import config\n\nENABLE_ENCRYPTION = getattr(config, 'enable_encryption', False)\nKEY = getattr(config, 'encryption_key', 'DefaultEncryptionKey').encode(\"ascii\")[:16]\n\n\ndef quotient_remainder(divident, divsor):\n    return divident // divsor, divident % divsor\n\n\ndef color_value(x):\n    return x*255\n\n\ndef normal(x):\n    return x/255\n\n\ndef encrypt_data_aes(data: bytes, key: bytes) -> bytes:\n    cipher = AES.new(key, AES.MODE_EAX)\n    ciphertext, tag = cipher.encrypt_and_digest(data)\n    return base64.urlsafe_b64encode(cipher.nonce + tag + ciphertext)\n\n\ndef decrypt_data_aes(data: bytes, key: bytes) -> bytes:\n    raw = base64.urlsafe_b64decode(data)\n    nonce, tag, ciphertext = raw[:16], raw[16:32], raw[32:]\n\n    cipher = AES.new(key, AES.MODE_EAX, nonce)\n    clear_data = cipher.decrypt_and_verify(ciphertext, tag)\n    return clear_data\n\n\ndef encode(infile_path, outvideo_path, encrypt=ENABLE_ENCRYPTION, key=KEY,\n           fps=20, num_cols_per_frame=64, num_rows_per_frame=36):\n    fd = open(infile_path, 'rb')\n    raw_data_bytes = fd.read()\n    if encrypt:\n        raw_data_bytes = encrypt_data_aes(raw_data_bytes, key)\n    data_bytes = np.frombuffer(raw_data_bytes, dtype=np.uint8)\n    len_of_data = len(data_bytes)\n    num_bytes_per_row = int(num_cols_per_frame * 3 / 8)\n    num_bytes_per_frame = num_bytes_per_row * num_rows_per_frame\n\n    len_bytes = np.array(bytearray(len_of_data.to_bytes(4, byteorder='big')), dtype=np.uint8)\n    (num_frames, num_leftover_bytes) = quotient_remainder(4 + len_of_data, num_bytes_per_frame)\n\n    if num_leftover_bytes > 0:\n        num_bytes_last_frame_padding = num_bytes_per_frame - num_leftover_bytes\n        padding_bytes = np.full((num_bytes_last_frame_padding), 0, dtype=np.uint8)\n        data_bytes = np.concatenate((len_bytes, data_bytes, padding_bytes))\n        num_frames += 1\n    else:\n        data_bytes = np.concatenate((len_bytes, data_bytes))\n\n    # Vedio: size=(1280, 720), fps=20\n    size = (num_cols_per_frame * 20, num_rows_per_frame * 20)\n\n    video = cv2.VideoWriter(outvideo_path, cv2.VideoWriter_fourcc(\n        *'mp4v'), fps, size)\n\n    for i in range(num_frames):\n        frame_bytes = data_bytes[i * num_bytes_per_frame: (i + 1) * num_bytes_per_frame]\n        frame_bits = np.unpackbits(frame_bytes)\n        # Reshape array to array(36， 72， 3)\n        frame = color_value(frame_bits).reshape(num_rows_per_frame, num_cols_per_frame, 3)\n        img = Image.fromarray(frame, mode=\"RGB\")\n        # Scale image to (1280, 720)\n        newimg = img.resize(size, Image.Resampling.BOX)\n        video.write(np.asarray(newimg))\n    fd.close()\n\n\ndef decode(invideo_path, outfile_path, decrypt=ENABLE_ENCRYPTION, key=KEY):\n    i = 0\n    step = 20\n    data_bits_list = []\n    cap = cv2.VideoCapture(invideo_path)\n    ret, frame = cap.read()\n    while ret:\n        frame_shape = np.shape(frame)\n        for j in range(0, frame_shape[0], step):\n            for k in range(0, frame_shape[1], step):\n                piece = frame[j:j+step, k:k+step].reshape(step*step, 3)\n                round = normal(piece.mean(0)).round().astype(np.uint8)\n                data_bits_list.append(round)\n        ret, frame = cap.read()\n        i += 1\n    cap.release()\n    data_bits = np.array(data_bits_list).reshape(len(data_bits_list) * 3, 1)\n    data_bytes = np.packbits(data_bits)\n    len_of_data = int.from_bytes(data_bytes[:4], byteorder='big')\n    data_bytes_retrieved = data_bytes[4:len_of_data+4].tobytes()\n    if decrypt:\n        data_bytes_retrieved = decrypt_data_aes(data_bytes_retrieved, key)\n    fd = open(outfile_path, 'wb')\n    fd.write(data_bytes_retrieved)\n    fd.close()\n\n\nif __name__ == '__main__':\n    # encode(\"../examples/painting.jpg\", \"../examples/upload.mp4\")\n    # decode(\"../examples/upload.mp4\", \"../examples/painting-retrieved2.jpg\")\n    pass\n"
  }
]