Full Code of lewangdev/youtube-drive for AI

main 9f4dde40f38b cached
12 files
32.4 KB
7.9k tokens
18 symbols
1 requests
Download .txt
Repository: lewangdev/youtube-drive
Branch: main
Commit: 9f4dde40f38b
Files: 12
Total size: 32.4 KB

Directory structure:
gitextract_904_pc17/

├── .gitignore
├── LICENSE
├── README.md
├── bin/
│   ├── youtube-drive
│   └── youtube-drive.bat
├── requirements.txt
├── setup.py
└── youtube_drive/
    ├── __init__.py
    ├── __main__.py
    ├── config.py
    ├── main.py
    └── youtube_codec.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# projects files
painting-retrieved*.jpg
*.mp4

# MacOS
.DS_Store
.vscode/

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# youtube-drive

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.

**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.

youtube-drive is a silly proof-of-concept, and I do not endorse its high-volume use either.

## Usage Example

**Upload**: Encode a file to video and upload to YouTube:

```sh
python -m youtube_drive upload examples/BesselJ.png
YouTube Video ID: EzqstWlMXyk
YouTube: https://youtu.be/EzqstWlMXyk

```

**Retrieve**: Download the video from YouTube and decode to a file:

```sh
python -m youtube_drive retrieve --video-id=EzqstWlMXyk -o BesselJ-retrieved.png
/var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4
[youtube] EzqstWlMXyk: Downloading webpage
[youtube] EzqstWlMXyk: Downloading MPD manifest
[download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4
[download] 100% of 1.74MiB in 00:25
[download] Destination: /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140
[download] 100% of 58.70KiB in 00:03
[ffmpeg] Merging formats into "/var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4"
Deleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.f136.mp4 (pass -k to keep)
Deleting original file /var/folders/md/dnr_ryfs2_x128p26xx2pnnc0000gn/T/tmp6qfm_msc.mp4.f140 (pass -k to keep)
```

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.

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.

I use opencv to produce mp4 video, if use ffmpeg with optimizing directly, the video maybe compress to a more smaller size.

**AGAIN:** It is a silly idea, just for fun.

## Installation

**Notice**:

- I only test with **Python 3.8 & 3.9 & 3.10** on **MacOS** with ffmpeg installed.
- If it works on your system, please feel free to let me know. Thanks.

For development:

```sh
git clone https://github.com/lewangdev/youtube-drive.git
cd youtube-drive
python -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt
```

Or run directly from sources:

```sh
git clone https://github.com/lewangdev/youtube-drive.git
cd youtube-drive
python -m venv .venv
. .venv/bin/activate
python setup.py install
```

## Setup

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.

You now need to create and use your own OAuth 2.0 file, it's a free service. Steps:

Go to the [Google Cloud Console](https://console.cloud.google.com/).

- Create project.
- Side menu: APIs & Services -> OAuth consent screen: Create app and add the test user you will updoad videos to.
- Side menu: APIs & Services -> Enabled API & services -> ENABLED API AND SERVICES -> Search `youtube` -> Choose `YouTube Data API v3` and enable it.
- Side menu: APIs & Services -> Credentials -> Create Credentials -> OAuth client ID: Application type choose `Desktop app`.
- Download JSON: Under the section "OAuth 2.0 client IDs". Save the file to your local system.
  Use this JSON as your credentials file: copy it to ~/.client_secrets.json.
  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.

If you feel any difficulty to create OAuth 2.0 file, here is the video I made for you: https://youtu.be/kL2oFZt2xHM

## Usage

**Commands:**

```sh
python -m youtube_drive -h
usage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ...

options:
  -h, --help            show this help message and exit

commands:
  {encode,en,decode,de,upload,up,retrieve,r}
    encode (en)         encode a file to mp4 video
    decode (de)         decode a video to a file
    upload (up)         upload a file to YouTube
    retrieve (r)        retrieve a video from YouTube save as <filename>

```

If you install from source, you can run the script directly:

```sh
youtube-drive -h
usage: youtube-drive [-h] {encode,en,decode,de,upload,up,retrieve,r} ...

options:
  -h, --help            show this help message and exit

commands:
  {encode,en,decode,de,upload,up,retrieve,r}
    encode (en)         encode a file to mp4 video
    decode (de)         decode a video to a file
    upload (up)         upload a file to YouTube
    retrieve (r)        retrieve a video from YouTube save as <filename>

```

**Upload:**

```sh
python -m youtube_drive up -h
usage: youtube-drive upload [-h] filename

positional arguments:
  filename    encode file <filename> to a video and upload to YouTube

options:
  -h, --help  show this help message and exit

```

**Retrieve:**

```sh
python -m youtube_drive r -h
usage: youtube-drive retrieve [-h] [--video-id video_id] [-o filename]

options:
  -h, --help           show this help message and exit
  --video-id video_id  download YouTube video with <video_id>
  -o filename          save file to <filename>

```

**Local Encode:**

```sh
python -m youtube_drive en -h
usage: youtube-drive encode [-h] [-i input_filename] [--video-fps video_fps] video_filename

positional arguments:
  video_filename        save the video to this filename

options:
  -h, --help            show this help message and exit
  -i input_filename     encode file <input_filename> to a video
  --video-fps video_fps
                        set video fps, default value is 20

```

**Local Decode:**

```
python -m youtube_drive de -h
usage: youtube-drive decode [-h] [-i input_video_filename] filename

positional arguments:
  filename              Save the output file to this filename

options:
  -h, --help            show this help message and exit
  -i input_video_filename
                        decode the video <input_video_filename> to a file
```

## The difference between **youtube-drive** and **YouTubeDrive**

I add 4 bytes for representing data length at the beginning for the file for easily padding to video frames


================================================
FILE: bin/youtube-drive
================================================
#!/usr/bin/env python

if __name__ == '__main__':

    # Allows you to a relative import from the parent folder
    import os.path
    import sys
    sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

    from youtube_upload import main    
    main.run()


================================================
FILE: bin/youtube-drive.bat
================================================
@python %~dp0youtube-drive %*

================================================
FILE: requirements.txt
================================================
numpy
opencv-python
pillow
youtube-dl
# youtube-upload
git+https://github.com/tokland/youtube-upload.git
PyCryptodome==3.17.0

================================================
FILE: setup.py
================================================
#!/usr/bin/python
"""Store files as YouTube videos."""
from distutils.core import setup

setup_kwargs = {
    "name": "youtube-drive",
    "version": "0.0.1",
    "description": "Store files as YouTube videos",
    "author": "Le Wang",
    "author_email": "lewang.dev@gmail.com",
    "url": "https://github.com/lewangdev/youtube-drive",
    "packages": ["youtube_drive/"],
    "scripts": ["bin/youtube-drive"],
    "license": "Apache-2.0 license",
    "long_description": " ".join(__doc__.strip().splitlines()),
    "classifiers": [
        'Topic :: Internet :: WWW/HTTP',
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python :: 3',
    ],
    "entry_points": {
        'console_scripts': [
            'youtube-drive = youtube_drive.main:run'
        ],
    },
    "install_requires": [
        'numpy',
        'opencv-python',
        'youtube-dl',
        'pillow',
        'youtube-upload==0.8.0'
    ],
    "dependency_links": [
        'git+https://github.com/tokland/youtube-upload.git#egg=youtube-upload-0.8.0'
    ]
}

setup(**setup_kwargs)


================================================
FILE: youtube_drive/__init__.py
================================================
VERSION = "0.0.1"


================================================
FILE: youtube_drive/__main__.py
================================================
#!/usr/bin/env python
from __future__ import unicode_literals

# Execute with
# $ python youtube_drive/__main__.py (2.6+)
# $ python -m youtube_drive          (2.7+)

import sys

if __package__ is None and not hasattr(sys, 'frozen'):
    # direct call of __main__.py
    import os.path
    path = os.path.realpath(os.path.abspath(__file__))
    sys.path.insert(0, os.path.dirname(os.path.dirname(path)))

import youtube_drive.main

if __name__ == '__main__':
    youtube_drive.main.main(sys.argv[1:])


================================================
FILE: youtube_drive/config.py
================================================
enable_encryption = False
encryption_key = 'DefaultEncryptionKey'

================================================
FILE: youtube_drive/main.py
================================================
import tempfile
import os
import sys
import uuid
import argparse
import youtube_dl
from youtube_upload import auth, lib, upload_video
from . import youtube_codec


def get_youtube_upload_handler():
    """Return the API Youtube object."""
    home = os.path.expanduser("~")
    client_secrets = os.path.join(home, ".client_secrets.json")
    credentials = os.path.join(home, ".youtube-upload-credentials.json")
    get_code_callback = (auth.console.get_code)
    return auth.get_resource(client_secrets, credentials,
                             get_code_callback=get_code_callback)


def upload_youtube_video(youtube, title, video_path):
    """Upload video with index (for split videos)."""
    u = lib.to_utf8
    title = u(title)

    request_body = {
        "snippet": {
            "title": title,
            "description": "",
            "categoryId": None,
            "tags": u(""),
            "defaultLanguage": None,
            "defaultAudioLanguage": None

        },
        "status": {
            "embeddable": True,
            "privacyStatus": "unlisted",
            "publishAt": None,
            "license": "youtube",
        },
        "recordingDetails": {
            "location": None,
            "recordingDate": None,
        },
    }

    return upload_video.upload(youtube, video_path, request_body)


def download_youtube_video(video_id, output_file_path):
    ydl_opts = {'outtmpl': output_file_path}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([f"https://www.youtube.com/watch?v={video_id}"])


def youtube_upload(upload_file_path):
    video_path = tempfile.mktemp(".mp4")
    youtube_codec.encode(upload_file_path, video_path)
    youtube = get_youtube_upload_handler()
    video_id = upload_youtube_video(youtube, f"DATA-{str(uuid.uuid4()).upper()}", video_path)
    os.remove(video_path)
    return video_id


def youtube_retrieve(video_id, output_file_path):
    video_path = tempfile.mktemp(".mp4")
    print(video_path)
    download_youtube_video(video_id, video_path)
    youtube_codec.decode(video_path, output_file_path)


def cmd_upload(args):
    video_id = youtube_upload(args.filename)
    print(f"YouTube Video ID: {video_id}", f"YouTube: https://youtu.be/{video_id}", sep="\n")


def cmd_retrieve(args):
    youtube_retrieve(args.video_id, args.o)


def cmd_encode(args):
    if args.encrypt and args.key is not None:
        args.key = str(args.key).encode("ascii")[:16]
    youtube_codec.encode(args.i, args.video_filename, args.encrypt, args.key, args.video_fps)


def cmd_decode(args):
    if args.decrypt and args.key is not None:
        args.key = str(args.key).encode("ascii")[:16]
    youtube_codec.decode(args.i, args.filename, args.decrypt, args.key)


def main(args):
    parser = argparse.ArgumentParser('youtube-drive')
    subparsers = parser.add_subparsers(title="commands")

    encode_parser = subparsers.add_parser('encode', aliases=['en'], help='encode a file to mp4 video')
    encode_parser.add_argument('-i',
                               action='store',
                               metavar="input_filename",
                               help='encode file <input_filename> to a video')
    encode_parser.add_argument('--video-fps',
                               action='store',
                               metavar="video_fps",
                               default=20,
                               type=int,
                               help='set video fps, default value is 20')
    encode_parser.add_argument('video_filename',
                               action='store',
                               help='save the video to this filename')
    encode_parser.add_argument('--encrypt',
                               action='store_true',
                               default=False,
                               help='encrypt the file')
    encode_parser.add_argument('--key',
                               action='store',
                               metavar="encryption_key",
                               default=None,
                               help='encryption key')
    encode_parser.set_defaults(handle=cmd_encode)

    decode_parser = subparsers.add_parser('decode', aliases=['de'], help='decode a video to a file')
    decode_parser.add_argument('-i',
                               action='store',
                               metavar="input_video_filename",
                               help='decode the video <input_video_filename> to a file')
    decode_parser.add_argument('filename',
                               action='store',
                               help='Save the output file to this filename')
    decode_parser.add_argument('--decrypt',
                               action='store_true',
                               default=False,
                               help='decrypt the file')
    decode_parser.add_argument('--key',
                               action='store',
                               metavar="decryption_key",
                               default=None,
                               help='decryption key')
    decode_parser.set_defaults(handle=cmd_decode)

    upload_parser = subparsers.add_parser('upload', aliases=['up'], help='upload a file to YouTube')
    upload_parser.add_argument('filename',
                               action='store',
                               help='encode file <filename> to a video and upload to YouTube')
    upload_parser.set_defaults(handle=cmd_upload)

    retrieve_parser = subparsers.add_parser("retrieve", aliases=['r'],
                                            help="retrieve a video from YouTube save as <filename>")
    retrieve_parser.add_argument('--video-id',
                                 action='store',
                                 metavar="video_id",
                                 help='download YouTube video with <video_id>')
    retrieve_parser.add_argument('-o',
                                 action='store',
                                 metavar="filename",
                                 help='save file to <filename>')
    retrieve_parser.set_defaults(handle=cmd_retrieve)
    arguments = parser.parse_args(args)
    if not hasattr(arguments, 'handle'):
        parser.print_help()
        sys.exit(1)

    arguments.handle(arguments)


def run():
    main(sys.argv[1:])


if __name__ == '__main__':
    # video_id = youtebe_upload("./examples/upload.mp4")
    # print(f"video_id: {video_id}")
    # youtube_codec.encode("./examples/painting.jpg", "./examples/upload.mp4")
    # youtube_codec.decode("./examples/upload.mp4", "./examples/painting-retrieved.jpg")
    # youtube_retrieve("gKhXk3IGW2s", "./examples/painting-retrieved-3.jpg")
    main(sys.argv[1:])


================================================
FILE: youtube_drive/youtube_codec.py
================================================
import numpy as np
from PIL import Image
import cv2

import base64
from Crypto.Cipher import AES
from . import config

ENABLE_ENCRYPTION = getattr(config, 'enable_encryption', False)
KEY = getattr(config, 'encryption_key', 'DefaultEncryptionKey').encode("ascii")[:16]


def quotient_remainder(divident, divsor):
    return divident // divsor, divident % divsor


def color_value(x):
    return x*255


def normal(x):
    return x/255


def encrypt_data_aes(data: bytes, key: bytes) -> bytes:
    cipher = AES.new(key, AES.MODE_EAX)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    return base64.urlsafe_b64encode(cipher.nonce + tag + ciphertext)


def decrypt_data_aes(data: bytes, key: bytes) -> bytes:
    raw = base64.urlsafe_b64decode(data)
    nonce, tag, ciphertext = raw[:16], raw[16:32], raw[32:]

    cipher = AES.new(key, AES.MODE_EAX, nonce)
    clear_data = cipher.decrypt_and_verify(ciphertext, tag)
    return clear_data


def encode(infile_path, outvideo_path, encrypt=ENABLE_ENCRYPTION, key=KEY,
           fps=20, num_cols_per_frame=64, num_rows_per_frame=36):
    fd = open(infile_path, 'rb')
    raw_data_bytes = fd.read()
    if encrypt:
        raw_data_bytes = encrypt_data_aes(raw_data_bytes, key)
    data_bytes = np.frombuffer(raw_data_bytes, dtype=np.uint8)
    len_of_data = len(data_bytes)
    num_bytes_per_row = int(num_cols_per_frame * 3 / 8)
    num_bytes_per_frame = num_bytes_per_row * num_rows_per_frame

    len_bytes = np.array(bytearray(len_of_data.to_bytes(4, byteorder='big')), dtype=np.uint8)
    (num_frames, num_leftover_bytes) = quotient_remainder(4 + len_of_data, num_bytes_per_frame)

    if num_leftover_bytes > 0:
        num_bytes_last_frame_padding = num_bytes_per_frame - num_leftover_bytes
        padding_bytes = np.full((num_bytes_last_frame_padding), 0, dtype=np.uint8)
        data_bytes = np.concatenate((len_bytes, data_bytes, padding_bytes))
        num_frames += 1
    else:
        data_bytes = np.concatenate((len_bytes, data_bytes))

    # Vedio: size=(1280, 720), fps=20
    size = (num_cols_per_frame * 20, num_rows_per_frame * 20)

    video = cv2.VideoWriter(outvideo_path, cv2.VideoWriter_fourcc(
        *'mp4v'), fps, size)

    for i in range(num_frames):
        frame_bytes = data_bytes[i * num_bytes_per_frame: (i + 1) * num_bytes_per_frame]
        frame_bits = np.unpackbits(frame_bytes)
        # Reshape array to array(36, 72, 3)
        frame = color_value(frame_bits).reshape(num_rows_per_frame, num_cols_per_frame, 3)
        img = Image.fromarray(frame, mode="RGB")
        # Scale image to (1280, 720)
        newimg = img.resize(size, Image.Resampling.BOX)
        video.write(np.asarray(newimg))
    fd.close()


def decode(invideo_path, outfile_path, decrypt=ENABLE_ENCRYPTION, key=KEY):
    i = 0
    step = 20
    data_bits_list = []
    cap = cv2.VideoCapture(invideo_path)
    ret, frame = cap.read()
    while ret:
        frame_shape = np.shape(frame)
        for j in range(0, frame_shape[0], step):
            for k in range(0, frame_shape[1], step):
                piece = frame[j:j+step, k:k+step].reshape(step*step, 3)
                round = normal(piece.mean(0)).round().astype(np.uint8)
                data_bits_list.append(round)
        ret, frame = cap.read()
        i += 1
    cap.release()
    data_bits = np.array(data_bits_list).reshape(len(data_bits_list) * 3, 1)
    data_bytes = np.packbits(data_bits)
    len_of_data = int.from_bytes(data_bytes[:4], byteorder='big')
    data_bytes_retrieved = data_bytes[4:len_of_data+4].tobytes()
    if decrypt:
        data_bytes_retrieved = decrypt_data_aes(data_bytes_retrieved, key)
    fd = open(outfile_path, 'wb')
    fd.write(data_bytes_retrieved)
    fd.close()


if __name__ == '__main__':
    # encode("../examples/painting.jpg", "../examples/upload.mp4")
    # decode("../examples/upload.mp4", "../examples/painting-retrieved2.jpg")
    pass
Download .txt
gitextract_904_pc17/

├── .gitignore
├── LICENSE
├── README.md
├── bin/
│   ├── youtube-drive
│   └── youtube-drive.bat
├── requirements.txt
├── setup.py
└── youtube_drive/
    ├── __init__.py
    ├── __main__.py
    ├── config.py
    ├── main.py
    └── youtube_codec.py
Download .txt
SYMBOL INDEX (18 symbols across 2 files)

FILE: youtube_drive/main.py
  function get_youtube_upload_handler (line 11) | def get_youtube_upload_handler():
  function upload_youtube_video (line 21) | def upload_youtube_video(youtube, title, video_path):
  function download_youtube_video (line 51) | def download_youtube_video(video_id, output_file_path):
  function youtube_upload (line 57) | def youtube_upload(upload_file_path):
  function youtube_retrieve (line 66) | def youtube_retrieve(video_id, output_file_path):
  function cmd_upload (line 73) | def cmd_upload(args):
  function cmd_retrieve (line 78) | def cmd_retrieve(args):
  function cmd_encode (line 82) | def cmd_encode(args):
  function cmd_decode (line 88) | def cmd_decode(args):
  function main (line 94) | def main(args):
  function run (line 167) | def run():

FILE: youtube_drive/youtube_codec.py
  function quotient_remainder (line 13) | def quotient_remainder(divident, divsor):
  function color_value (line 17) | def color_value(x):
  function normal (line 21) | def normal(x):
  function encrypt_data_aes (line 25) | def encrypt_data_aes(data: bytes, key: bytes) -> bytes:
  function decrypt_data_aes (line 31) | def decrypt_data_aes(data: bytes, key: bytes) -> bytes:
  function encode (line 40) | def encode(infile_path, outvideo_path, encrypt=ENABLE_ENCRYPTION, key=KEY,
  function decode (line 80) | def decode(invideo_path, outfile_path, decrypt=ENABLE_ENCRYPTION, key=KEY):
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".gitignore",
    "chars": 1875,
    "preview": "# projects files\npainting-retrieved*.jpg\n*.mp4\n\n# MacOS\n.DS_Store\n.vscode/\n\n# Byte-compiled / optimized / DLL files\n__py"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 6996,
    "preview": "# youtube-drive\n\nyoutube-drive is totally inspired by [YouTubeDrive](https://github.com/dzhang314/YouTubeDrive), a Wolfr"
  },
  {
    "path": "bin/youtube-drive",
    "chars": 295,
    "preview": "#!/usr/bin/env python\n\nif __name__ == '__main__':\n\n    # Allows you to a relative import from the parent folder\n    impo"
  },
  {
    "path": "bin/youtube-drive.bat",
    "chars": 29,
    "preview": "@python %~dp0youtube-drive %*"
  },
  {
    "path": "requirements.txt",
    "chars": 125,
    "preview": "numpy\nopencv-python\npillow\nyoutube-dl\n# youtube-upload\ngit+https://github.com/tokland/youtube-upload.git\nPyCryptodome==3"
  },
  {
    "path": "setup.py",
    "chars": 1266,
    "preview": "#!/usr/bin/python\n\"\"\"Store files as YouTube videos.\"\"\"\nfrom distutils.core import setup\n\nsetup_kwargs = {\n    \"name\": \"y"
  },
  {
    "path": "youtube_drive/__init__.py",
    "chars": 18,
    "preview": "VERSION = \"0.0.1\"\n"
  },
  {
    "path": "youtube_drive/__main__.py",
    "chars": 501,
    "preview": "#!/usr/bin/env python\nfrom __future__ import unicode_literals\n\n# Execute with\n# $ python youtube_drive/__main__.py (2.6+"
  },
  {
    "path": "youtube_drive/config.py",
    "chars": 65,
    "preview": "enable_encryption = False\nencryption_key = 'DefaultEncryptionKey'"
  },
  {
    "path": "youtube_drive/main.py",
    "chars": 6737,
    "preview": "import tempfile\nimport os\nimport sys\nimport uuid\nimport argparse\nimport youtube_dl\nfrom youtube_upload import auth, lib,"
  },
  {
    "path": "youtube_drive/youtube_codec.py",
    "chars": 3914,
    "preview": "import numpy as np\nfrom PIL import Image\nimport cv2\n\nimport base64\nfrom Crypto.Cipher import AES\nfrom . import config\n\nE"
  }
]

About this extraction

This page contains the full source code of the lewangdev/youtube-drive GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (32.4 KB), approximately 7.9k tokens, and a symbol index with 18 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!