Full Code of elebumm/RedditVideoMakerBot for AI

master 569f25098a64 cached
69 files
294.2 KB
70.0k tokens
119 symbols
1 requests
Download .txt
Showing preview only (312K chars total). Download the full file or copy to clipboard to get everything.
Repository: elebumm/RedditVideoMakerBot
Branch: master
Commit: 569f25098a64
Files: 69
Total size: 294.2 KB

Directory structure:
gitextract_1pn0lxmc/

├── .dockerignore
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       ├── fmt.yml
│       ├── lint.yml
│       └── stale.yml
├── .gitignore
├── .pylintrc
├── .python-version
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── GUI/
│   ├── backgrounds.html
│   ├── index.html
│   ├── layout.html
│   └── settings.html
├── GUI.py
├── LICENSE
├── README.md
├── TTS/
│   ├── GTTS.py
│   ├── TikTok.py
│   ├── __init__.py
│   ├── aws_polly.py
│   ├── elevenlabs.py
│   ├── engine_wrapper.py
│   ├── openai_tts.py
│   ├── pyttsx.py
│   └── streamlabs_polly.py
├── build.sh
├── fonts/
│   └── LICENSE.txt
├── install.sh
├── main.py
├── ptt.py
├── reddit/
│   └── subreddit.py
├── requirements.txt
├── run.bat
├── run.sh
├── utils/
│   ├── .config.template.toml
│   ├── __init__.py
│   ├── ai_methods.py
│   ├── background_audios.json
│   ├── background_videos.json
│   ├── cleanup.py
│   ├── console.py
│   ├── ffmpeg_install.py
│   ├── fonts.py
│   ├── gui_utils.py
│   ├── id.py
│   ├── imagenarator.py
│   ├── playwright.py
│   ├── posttextparser.py
│   ├── settings.py
│   ├── subreddit.py
│   ├── thumbnail.py
│   ├── version.py
│   ├── videos.py
│   └── voice.py
└── video_creation/
    ├── __init__.py
    ├── background.py
    ├── data/
    │   ├── cookie-dark-mode.json
    │   └── cookie-light-mode.json
    ├── final_video.py
    ├── screenshot_downloader.py
    └── voices.py

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

================================================
FILE: .dockerignore
================================================
Dockerfile
results

================================================
FILE: .gitattributes
================================================
* text=auto eol=lf

================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug Report
title: "[Bug]: "
labels: bug
description: Report broken or incorrect behaviour
body:
  - type: markdown
    attributes:
      value: >
        Thanks for taking the time to fill out a bug.
        Please note that this form is for bugs only!
  - type: textarea
    id: what-happened
    attributes:
      label: Describe the bug
      description: A clear and concise description of what the bug is.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Reproduction Steps
      description: >
         What you did to make it happen.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Expected behavior
      description: >
         A clear and concise description of what you expected to happen.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Screenshots
      description: >
         If applicable, add screenshots to help explain your problem.
    validations:
      required: false
  - type: textarea
    attributes:
      label: System Information
      description: please fill your system informations
      value: >
        Operating System : [e.g. Windows 11]

        Python version : [e.g. Python 3.6]

        App version / Branch : [e.g. latest, V2.0, master, develop]
    validations:
      required: true
  - type: checkboxes
    attributes:
      label: Checklist
      description: >
        Let's make sure you've properly done due diligence when reporting this issue!
      options:
        - label: I have searched the open issues for duplicates.
          required: true
        - label: I have shown the entire traceback, if possible.
          required: true
  - type: textarea
    attributes:
      label: Additional Context
      description: Add any other context about the problem here.


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Ask a question
    about: Join our discord server to ask questions and discuss with maintainers and contributors.
    url: https://discord.gg/swqtb7AsNQ

================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
name: Feature Request
description: Suggest an idea for this project
labels: enhancement
title: "[Feature]: "
body:
  - type: input
    attributes:
      label: Summary
      description: >
        A short summary of what your feature request is.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Is your feature request related to a problem?
      description: >
        if yes, what becomes easier or possible when this feature is implemented?
    validations:
      required: true
  - type: textarea
    attributes:
      label: Describe the solution you'd like
      description: >
        A clear and concise description of what you want to happen.
    validations:
      required: true
  - type: textarea
    attributes:
      label: Describe alternatives you've considered
      description: >
        A clear and concise description of any alternative solutions or features you've considered.
    validations:
      required: false


  - type: textarea
    attributes:
      label: Additional Context
      description: Add any other context or screenshots about the feature request here.

================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
# Description

<!-- Please include a summary of the change and which issue is fixed. Please also include relevant context. List any dependencies that are required for this change. -->

# Issue Fixes

<!-- Fixes #(issue) if relevant-->

None

# Checklist:

- [ ] I am pushing changes to the **develop** branch
- [ ] I am using the recommended development environment
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have formatted and linted my code using python-black and pylint
- [ ] I have cleaned up unnecessary files
- [ ] My changes generate no new warnings
- [ ] My changes follow the existing code-style
- [ ] My changes are relevant to the project

# Any other information (e.g how to test the changes)

None


================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
  - package-ecosystem: "pip" # See documentation for possible values
    directory: "/" # Location of package manifests
    schedule:
      interval: "daily"
    target-branch: "develop"


================================================
FILE: .github/workflows/codeql-analysis.yml
================================================

# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
  push:
    branches: [ "master", "develop" ]
  pull_request:
    # The branches below must be a subset of the branches above
    branches: [ "master", "develop" ]
  schedule:
    - cron: '16 14 * * 3'

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ 'python' ]
        # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
        # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v2
      with:
        languages: ${{ matrix.language }}
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.

        # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
        # queries: security-extended,security-and-quality


    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
    # If this step fails, then you should remove it and run the build manually (see below)
    - name: Autobuild
      uses: github/codeql-action/autobuild@v2

    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun

    #   If the Autobuild fails above, remove it and uncomment the following three lines.
    #   modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.

    # - run: |
    #   echo "Run, Build Application using script"
    #   ./location_of_script_within_repo/buildscript.sh

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v2


================================================
FILE: .github/workflows/fmt.yml
================================================
# GitHub Action that uses Black to reformat the Python code in an incoming pull request.
# If all Python code in the pull request is compliant with Black then this Action does nothing.
# Othewrwise, Black is run and its changes are committed back to the incoming pull request.
# https://github.com/cclauss/autoblack

name: fmt
on:
  push:
    branches: ["develop"]
jobs:
  format:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python 3.10
        uses: actions/setup-python@v5
        with:
          python-version: 3.10.14
      - name: Install Black & isort
        run: pip install black isort
      - name: Run black check
        run: black --check . --line-length 101
      - name: Run isort check
        run: isort . --check-only --diff --profile black
      - name: If needed, commit changes to the pull request
        if: failure()
        run: |
          black . --line-length 101
          isort . --profile black
          git config --global user.name github-actions
          git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
          git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
          git checkout $GITHUB_HEAD_REF
          git commit -am "fixup: Format Python code with Black"
          git push origin HEAD:develop

          


================================================
FILE: .github/workflows/lint.yml
================================================
name: Lint

on: [pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: psf/black@stable
        with:
          options: "--line-length 101"
      - uses: isort/isort-action@v1
        with:
          configuration: "--check-only --diff --profile black"


================================================
FILE: .github/workflows/stale.yml
================================================
name: 'Stale issue handler'
on:
  workflow_dispatch:
  schedule:
    - cron: '0 0 * * *'

jobs:

  stale:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
    steps:
      - uses: actions/stale@v9
        id: stale-issue
        name: stale-issue
        with:
          # general settings
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          stale-issue-message: 'This issue is stale because it has been open 7 days with no activity. Remove stale label or comment, or this will be closed in 10 days.'
          close-issue-message: 'Issue closed due to being stale. Please reopen if issue persists in latest version.'
          days-before-stale: 7
          days-before-close: 15
          stale-issue-label: 'stale'
          close-issue-label: 'outdated'
          exempt-issue-labels: 'enhancement,keep,blocked'
          exempt-all-issue-milestones: true
          operations-per-run: 300
          remove-stale-when-updated: true
          ascending: true
          #debug-only: true

          stale-pr-message: 'This pull request is stale as it has been open for 7 days with no activity. Remove stale label or comment, or this will be closed in 10 days.'
          close-pr-message: 'Pull request closed due to being stale.'
          close-pr-label: 'outdated'
          stale-pr-label: 'stale'
          exempt-pr-labels: 'keep,blocked,before next release,after next release'
  


================================================
FILE: .gitignore
================================================
# 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/
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/
cover/

# 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
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
#   For a library or package, you might want to ignore these files since the code is
#   intended to run in multiple environments; otherwise, check them in:
# .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

# poetry
#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
#   This is especially recommended for binary packages to ensure reproducibility, and is more
#   commonly ignored for libraries.
#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
#   in version control.
#   https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__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/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# SonarLint plugin
.idea/sonarlint/

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

assets/temp
assets/backgrounds
/.vscode
out
.DS_Store
.setup-done-before
results/*
reddit-bot-351418-5560ebc49cac.json
/.idea
*.pyc
video_creation/data/videos.json
video_creation/data/envvars.txt

config.toml
*.exe


================================================
FILE: .pylintrc
================================================
[MAIN]

# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no

# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=

# In error mode, checkers without error messages are disabled and for others,
# only the ERROR messages are displayed, and no reports are done by default.
#errors-only=

# Always return a 0 (non-error) status code, even if lint errors are found.
# This is primarily useful in continuous integration scripts.
#exit-zero=

# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=

# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=

# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=

# Specify a score threshold to be exceeded before program exits with error.
fail-under=10

# Interpret the stdin as a python script, whose filename needs to be passed as
# the module_or_package argument.
#from-stdin=

# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS

# Add files or directories matching the regex patterns to the ignore-list. The
# regex matches against paths and can be in Posix or Windows format.
ignore-paths=

# Files or directories matching the regex patterns are skipped. The regex
# matches against base names, not paths. The default value ignores Emacs file
# locks
ignore-patterns=^\.#

# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=

# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=

# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1

# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100

# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=

# Pickle collected data for later comparisons.
persistent=yes

# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.6

# Discover python modules and packages in the file system subtree.
recursive=no

# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes

# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no

# In verbose mode, extra non-checker-related info will be displayed.
#verbose=


[REPORTS]

# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))

# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=

# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=

# Tells whether to display a full report or only the messages.
reports=no

# Activate the evaluation score.
score=yes


[MESSAGES CONTROL]

# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
           CONTROL_FLOW,
           INFERENCE,
           INFERENCE_FAILURE,
           UNDEFINED

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
        bad-inline-option,
        locally-disabled,
        file-ignored,
        suppressed-message,
        useless-suppression,
        deprecated-pragma,
        use-symbolic-message-instead,
        attribute-defined-outside-init,
        invalid-name,
        missing-docstring,
        protected-access,
        too-few-public-methods,
        format, # handled by black

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member


[BASIC]

# Naming style matching correct argument names.
argument-naming-style=snake_case

# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=

# Naming style matching correct attribute names.
attr-naming-style=snake_case

# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=

# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
          bar,
          baz,
          toto,
          tutu,
          tata

# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=

# Naming style matching correct class attribute names.
class-attribute-naming-style=any

# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=

# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE

# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=

# Naming style matching correct class names.
class-naming-style=PascalCase

# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=

# Naming style matching correct constant names.
const-naming-style=UPPER_CASE

# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=

# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1

# Naming style matching correct function names.
function-naming-style=snake_case

# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=

# Good variable names which should always be accepted, separated by a comma.
good-names=i,
           j,
           k,
           ex,
           Run,
           _

# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=

# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no

# Naming style matching correct inline iteration names.
inlinevar-naming-style=any

# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=

# Naming style matching correct method names.
method-naming-style=snake_case

# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=

# Naming style matching correct module names.
module-naming-style=snake_case

# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=

# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=

# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_

# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty

# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=

# Naming style matching correct variable names.
variable-naming-style=snake_case

# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=


[CLASSES]

# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no

# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
                      __new__,
                      setUp,
                      __post_init__

# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
                  _fields,
                  _replace,
                  _source,
                  _make

# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls

# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls


[DESIGN]

# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=

# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=

# Maximum number of arguments for function / method.
max-args=5

# Maximum number of attributes for a class (see R0902).
max-attributes=7

# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5

# Maximum number of branch for function / method body.
max-branches=12

# Maximum number of locals for function / method body.
max-locals=15

# Maximum number of parents for a class (see R0901).
max-parents=7

# Maximum number of public methods for a class (see R0904).
max-public-methods=20

# Maximum number of return / yield for function / method body.
max-returns=6

# Maximum number of statements in function / method body.
max-statements=50

# Minimum number of public methods for a class (see R0903).
min-public-methods=2


[EXCEPTIONS]

# Exceptions that will emit a warning when caught.
overgeneral-exceptions=BaseException,
                       Exception


[FORMAT]

# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=

# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$

# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4

# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
# tab).
indent-string='    '

# Maximum number of characters on a single line.
max-line-length=100

# Maximum number of lines in a module.
max-module-lines=1000

# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no

# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no


[IMPORTS]

# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=

# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no

# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=

# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=

# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=

# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=

# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=

# Force import order to recognize a module as part of a third party library.
known-third-party=enchant

# Couples of modules and preferred modules, separated by a comma.
preferred-modules=


[LOGGING]

# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old

# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging


[MISCELLANEOUS]

# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
      XXX,
      TODO

# Regular expression of note tags to take in consideration.
notes-rgx=


[REFACTORING]

# Maximum number of nested blocks for function / method body
max-nested-blocks=5

# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error


[SIMILARITIES]

# Comments are removed from the similarity computation
ignore-comments=yes

# Docstrings are removed from the similarity computation
ignore-docstrings=yes

# Imports are removed from the similarity computation
ignore-imports=yes

# Signatures are removed from the similarity computation
ignore-signatures=yes

# Minimum lines number of a similarity.
min-similarity-lines=4


[SPELLING]

# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4

# Spelling dictionary name. Available dictionaries: none. To make it work,
# install the 'python-enchant' package.
spelling-dict=

# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:

# List of comma separated words that should not be checked.
spelling-ignore-words=

# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=

# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no


[STRING]

# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no

# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no


[TYPECHECK]

# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=

# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes

# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes

# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
                          not-async-context-manager,
                          not-context-manager,
                          attribute-defined-outside-init

# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace

# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes

# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1

# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1

# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin

# List of decorators that change the signature of a decorated function.
signature-mutators=


[VARIABLES]

# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=

# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes

# List of names allowed to shadow builtins
allowed-redefined-builtins=

# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
          _cb

# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_

# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_

# Tells whether we should check for unused import in __init__ files.
init-import=no

# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io


================================================
FILE: .python-version
================================================
3.10


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
  and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
  overall community

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or
  advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
  address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at the [discord server](https://discord.gg/yqNvvDMYpq).
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.


================================================
FILE: CONTRIBUTING.md
================================================

# Contributing to Reddit Video Maker Bot 🎥

Thanks for taking the time to contribute! ❤️

All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for the maintainers and smooth out the experience for all involved. We are looking forward to your contributions. 🎉

> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
>
> - ⭐ Star the project
> - 📣 Tweet about it
> - 🌲 Refer this project in your project's readme

## Table of Contents

- [Contributing to Reddit Video Maker Bot 🎥](#contributing-to-reddit-video-maker-bot-)
  - [Table of Contents](#table-of-contents)
  - [I Have a Question](#i-have-a-question)
  - [I Want To Contribute](#i-want-to-contribute)
    - [Reporting Bugs](#reporting-bugs)
      - [How Do I Submit a Good Bug Report?](#how-do-i-submit-a-good-bug-report)
    - [Suggesting Enhancements](#suggesting-enhancements)
      - [How Do I Submit a Good Enhancement Suggestion?](#how-do-i-submit-a-good-enhancement-suggestion)
    - [Your First Code Contribution](#your-first-code-contribution)
      - [Your environment](#your-environment)
      - [Making your first PR](#making-your-first-pr)
    - [Improving The Documentation](#improving-the-documentation)

## I Have a Question

> If you want to ask a question, we assume that you have read the available [Documentation](https://reddit-video-maker-bot.netlify.app/).

Before you ask a question, it is best to search for existing [Issues](https://github.com/elebumm/RedditVideoMakerBot/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.

If you then still feel the need to ask a question and need clarification, we recommend the following:

- Open an [Issue](https://github.com/elebumm/RedditVideoMakerBot/issues/new).
- Provide as much context as you can about what you're running into.
- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant.

We will then take care of the issue as soon as possible.

Additionally, there is a [Discord Server](https://discord.gg/swqtb7AsNQ) for any questions you may have

## I Want To Contribute

### Reporting Bugs

<details><summary><h4>Before Submitting a Bug Report</h4></summary>

A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.

- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g., using incompatible environment components/versions (Make sure that you have read the [documentation](https://luka-hietala.gitbook.io/documentation-for-the-reddit-bot/). If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [issues](https://github.com/elebumm/RedditVideoMakerBot/).
- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue - you probably aren't the first to get the error!
- Collect information about the bug:
  - Stack trace (Traceback) - preferably formatted in a code block.
  - OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
  - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
  - Your input and the output
  - Is the issue reproducible? Does it exist in previous versions?

#### How Do I Submit a Good Bug Report?

We use GitHub issues to track bugs and errors. If you run into an issue with the project:

- Open an [Issue](https://github.com/elebumm/RedditVideoMakerBot/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the _reproduction steps_ that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.

Once it's filed:

- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will try to support you as best as they can, but you may not receive an instant.
- If the team discovers that this is an issue it will be marked `bug` or `error`, as well as possibly other tags relating to the nature of the error), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
</details>

### Suggesting Enhancements

This section guides you through submitting an enhancement suggestion for Reddit Video Maker Bot, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.

<details><summary><h4>Before Submitting an Enhancement</h4></summary>

- Make sure that you are using the latest version.
- Read the [documentation](https://luka-hietala.gitbook.io/documentation-for-the-reddit-bot/) carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](https://github.com/elebumm/RedditVideoMakerBot/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset.

#### How Do I Submit a Good Enhancement Suggestion?

Enhancement suggestions are tracked as [GitHub issues](https://github.com/elebumm/RedditVideoMakerBot/issues).

- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. <!-- this should only be included if the project has a GUI -->
- **Explain why this enhancement would be useful** to most users. You may also want to point out the other projects that solved it better and which could serve as inspiration.

</details>

### Your First Code Contribution

#### Your environment

You development environment should follow the requirements stated in the [README file](README.md). If you are not using the specified versions, **please reference this in your pull request**, so reviewers can test your code on both versions.

#### Setting up your development repository

These steps are only specified for beginner developers trying to contribute to this repository.
If you know how to make a fork and clone, you can skip these steps.

Before contributing, follow these steps (if you are a beginner)

- Create a fork of this repository to your personal account
- Clone the repo to your computer
- Make sure that you have all dependencies installed
- Run `python main.py` to make sure that the program is working
- Now, you are all setup to contribute your own features to this repo!

Even if you are a beginner to working with python or contributing to open source software,
don't worry! You can still try contributing even to the documentation!

("Setting up your development repository" was written by a beginner developer themselves!)


#### Making your first PR

When making your PR, follow these guidelines:

- Your branch has a base of _develop_, **not** _master_
- You are merging your branch into the _develop_ branch
- You link any issues that are resolved or fixed by your changes. (this is done by typing "Fixes #\<issue number\>") in your pull request
- Where possible, you have used `git pull --rebase`, to avoid creating unnecessary merge commits
- You have meaningful commits, and if possible, follow the commit style guide of `type: explanation`
- Here are the commit types:
 - **feat** - a new feature
 - **fix** - a bug fix
 - **docs** - a change to documentation / commenting
 - **style** - formatting changes - does not impact code
 - **refactor** - refactored code
 - **chore** - updating configs, workflows etc - does not impact code

### Improving The Documentation

All updates to the documentation should be made in a pull request to [this repo](https://github.com/LukaHietala/RedditVideoMakerBot-website)


================================================
FILE: Dockerfile
================================================
FROM python:3.10.14-slim

RUN apt update
RUN apt-get install -y ffmpeg
RUN apt install python3-pip -y

RUN mkdir /app
ADD . /app
WORKDIR /app
RUN pip install -r requirements.txt

CMD ["python3", "main.py"]


================================================
FILE: GUI/backgrounds.html
================================================
{% extends "layout.html" %}
{% block main %}

<!-- Delete Background Modal -->
<div class="modal fade" id="deleteBtnModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete background</h5>
            </div>
            <div class="modal-body">
                Are you sure you want to delete this background?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <form action="background/delete" method="post">
                    <input type="hidden" id="background-key" name="background-key" value="">
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Add Background Modal -->
<div class="modal fade" id="backgroundAddModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add background video</h5>
            </div>
            <div class="modal-body">

                <!-- Add video form -->
                <form id="addBgForm" action="background/add" method="post" novalidate>
                    <div class="form-group row">
                        <label class="col-4 col-form-label" for="youtube_uri">YouTube URI</label>
                        <div class="col-8">
                            <div class="input-group">
                                <div class="input-group-text">
                                    <i class="bi bi-youtube"></i>
                                </div>
                                <input name="youtube_uri" placeholder="https://www.youtube.com/watch?v=..." type="text"
                                    class="form-control">
                            </div>
                            <span id="feedbackYT" class="form-text feedback-invalid"></span>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="filename" class="col-4 col-form-label">Filename</label>
                        <div class="col-8">
                            <div class="input-group">
                                <div class="input-group-text">
                                    <i class="bi bi-file-earmark"></i>
                                </div>
                                <input name="filename" placeholder="Example: cool-background" type="text"
                                    class="form-control">
                            </div>
                            <span id="feedbackFilename" class="form-text feedback-invalid"></span>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="citation" class="col-4 col-form-label">Credits (owner of the video)</label>
                        <div class="col-8">
                            <div class="input-group">
                                <div class="input-group-text">
                                    <i class="bi bi-person-circle"></i>
                                </div>
                                <input name="citation" placeholder="YouTube Channel" type="text" class="form-control">
                            </div>
                            <span class="form-text text-muted">Include the channel name of the
                                owner of the background video you are adding.</span>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="position" class="col-4 col-form-label">Position of screenshots</label>
                        <div class="col-8">
                            <div class="input-group">
                                <div class="input-group-text">
                                    <i class="bi bi-arrows-fullscreen"></i>
                                </div>
                                <input name="position" placeholder="Example: center" type="text" class="form-control">
                            </div>
                            <span class="form-text text-muted">Advanced option (you can leave it
                                empty). Valid options are "center" and decimal numbers</span>
                        </div>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button name="submit" type="submit" class="btn btn-success">Add background</button>
                </form>
            </div>
        </div>
    </div>
</div>

<main>
    <div class="album py-2 bg-light">
        <div class="container">

            <div class="row justify-content-between mt-2">
                <div class="col-12 col-md-3 mb-3">
                    <input type="text" class="form-control searchFilter" placeholder="Search backgrounds"
                        onkeyup="searchFilter()">
                </div>
                <div class="col-12 col-md-2 mb-3">
                    <button type="button" class="btn btn-primary form-control" data-toggle="modal"
                        data-target="#backgroundAddModal">
                        Add background video
                    </button>
                </div>
            </div>

            <div class="grid row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3" id="backgrounds">

            </div>
        </div>
    </div>
</main>

<script>
    var keys = [];
    var youtube_urls = [];

    // Show background videos
    $(document).ready(function () {
        $.getJSON("backgrounds.json",
            function (data) {
                delete data["__comment"];
                var background = '';
                $.each(data, function (key, value) {
                    // Add YT urls and keys (for validation)
                    keys.push(key);
                    youtube_urls.push(value[0]);

                    background += '<div class="col">';
                    background += '<div class="card shadow-sm">';
                    background += '<iframe class="bd-placeholder-img card-img-top" width="100%" height="225" src="https://www.youtube-nocookie.com/embed/' + value[0].split("?v=")[1] + '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
                    background += '<div class="card-body">';
                    background += '<p class="card-text">' + value[2] + ' • ' + key + '</p>';
                    background += '<div class="d-flex justify-content-between align-items-center">';
                    background += '<div class="btn-group">';
                    background += '<button type="button" class="btn btn-outline-danger" data-toggle="modal" data-target="#deleteBtnModal" data-background-key="' + key + '">Delete</button>';
                    background += '</div>';
                    background += '</div>';
                    background += '</div>';
                    background += '</div>';
                    background += '</div>';
                });

                $('#backgrounds').append(background);
            });
    });

    // Add background key when deleting
    $('#deleteBtnModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var key = button.data('background-key');

        $('#background-key').prop('value', key);
    });

    var searchFilter = () => {
        const input = document.querySelector(".searchFilter");
        const cards = document.getElementsByClassName("col");
        console.log(cards[1])
        let filter = input.value
        for (let i = 0; i < cards.length; i++) {
            let title = cards[i].querySelector(".card-text");
            if (title.innerText.toLowerCase().indexOf(filter.toLowerCase()) > -1) {
                cards[i].classList.remove("d-none")
            } else {
                cards[i].classList.add("d-none")
            }
        }
    }

    // Validate form
    $("#addBgForm").submit(function (event) {
        $("#addBgForm input").each(function () {
            if (!(validate($(this)))) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
    });

    $('#addBgForm input[type="text"]').on("keyup", function () {
        validate($(this));
    });

    function validate(object) {
        let bool = check(object.prop("name"), object.prop("value"));

        // Change class
        if (bool) {
            object.removeClass("is-invalid");
            object.addClass("is-valid");
        }
        else {
            object.removeClass("is-valid");
            object.addClass("is-invalid");
        }

        return bool;

        // Check values (return true/false)
        function check(name, value) {
            if (name == "youtube_uri") {
                // URI validation
                let regex = /(?:\/|%3D|v=|vi=)([0-9A-z-_]{11})(?:[%#?&]|$)/;
                if (!(regex.test(value))) {
                    $("#feedbackYT").html("Invalid URI");
                    $("#feedbackYT").show();
                    return false;
                }

                // Check if this background already exists
                if (youtube_urls.includes(value)) {
                    $("#feedbackYT").html("This background is already added");
                    $("#feedbackYT").show();
                    return false;
                }

                $("#feedbackYT").hide();
                return true;
            }

            if (name == "filename") {
                // Check if key is already taken
                if (keys.includes(value)) {
                    $("#feedbackFilename").html("This filename is already taken");
                    $("#feedbackFilename").show();
                    return false;
                }

                let regex = /^([a-zA-Z0-9\s_-]{1,100})$/;
                if (!(regex.test(value))) {
                    return false;
                }

                return true;
            }

            if (name == "citation") {
                if (value.trim()) {
                    return true;
                }
            }

            if (name == "position") {
                if (!(value == "center" || value.length == 0 || value % 1 == 0)) {
                    return false;
                }

                return true;
            }
        }
    }
</script>

{% endblock %}

================================================
FILE: GUI/index.html
================================================
{% extends "layout.html" %}
{% block main %}

<main>
    <div class="album py-2 bg-light">
        <div class="container">

            <div class="row mt-2">
                <div class="col-12 col-md-3 mb-3">
                    <input type="text" class="form-control searchFilter" placeholder="Search videos"
                        aria-label="Search videos" onkeyup="searchFilter()">
                </div>
            </div>

            <div class="grid row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3" id="videos">

            </div>
        </div>
    </div>
</main>

<script>
    const intervals = [
        { label: 'year', seconds: 31536000 },
        { label: 'month', seconds: 2592000 },
        { label: 'day', seconds: 86400 },
        { label: 'hour', seconds: 3600 },
        { label: 'minute', seconds: 60 },
        { label: 'second', seconds: 1 }
    ];

    function timeSince(date) {
        const seconds = Math.floor((Date.now() / 1000 - date));
        const interval = intervals.find(i => i.seconds < seconds);
        const count = Math.floor(seconds / interval.seconds);
        return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
    }

    $(document).ready(function () {
        $.getJSON("videos.json",
            function (data) {
                data.sort((b, a) => a['time'] - b['time'])
                var video = '';
                $.each(data, function (key, value) {
                    video += '<div class="col">';
                    video += '<div class="card shadow-sm">';
                    //keeping original themed image card for future thumbnail usage video += '<svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">r/'+value.subreddit+'</text></svg>';

                    video += '<div class="card-body">';
                    video += '<p class="card-text">r/' + value.subreddit + ' • ' + checkTitle(value.reddit_title, value.filename) + '</p>';
                    video += '<div class="d-flex justify-content-between align-items-center">';
                    video += '<div class="btn-group">';
                    video += '<a href="https://www.reddit.com/r/' + value.subreddit + '/comments/' + value.id + '/" class="btn btn-sm btn-outline-secondary" target="_blank">View</a>';
                    video += '<a href="http://localhost:4000/results/' + value.subreddit + '/' + value.filename + '" class="btn btn-sm btn-outline-secondary" download>Download</a>';
                    video += '</div>';
                    video += '<div class="btn-group">';
                    video += '<button type="button" data-toggle="tooltip" id="copy" data-original-title="Copy to clipboard" class="btn btn-sm btn-outline-secondary" data-clipboard-text="' + getCopyData(value.subreddit, value.reddit_title, value.filename, value.background_credit) + '"><i class="bi bi-card-text"></i></button>';
                    video += '<button type="button" data-toggle="tooltip" id="copy" data-original-title="Copy to clipboard" class="btn btn-sm btn-outline-secondary" data-clipboard-text="' + checkTitle(value.reddit_title, value.filename) + ' #Shorts #reddit"><i class="bi bi-youtube"></i></button>';
                    video += '<button type="button" data-toggle="tooltip" id="copy" data-original-title="Copy to clipboard" class="btn btn-sm btn-outline-secondary" data-clipboard-text="' + checkTitle(value.reddit_title, value.filename) + ' #reddit"><i class="bi bi-instagram"></i></button>';
                    video += '</div>';
                    video += '<small class="text-muted">' + timeSince(value.time) + '</small>';
                    video += '</div>';
                    video += '</div>';
                    video += '</div>';
                    video += '</div>';

                });

                $('#videos').append(video);
            });
    });

    $(document).ready(function () {
        $('[data-toggle="tooltip"]').tooltip();
        $('[data-toggle="tooltip"]').on('click', function () {
            $(this).tooltip('hide');
        });
    });

    $('#copy').tooltip({
        trigger: 'click',
        placement: 'bottom'
    });

    function setTooltip(btn, message) {
        $(btn).tooltip('hide')
            .attr('data-original-title', message)
            .tooltip('show');
    }

    function hoverTooltip(btn, message) {
        $(btn).tooltip('hide')
            .attr('data-original-title', message)
            .tooltip('show');
    }

    function hideTooltip(btn) {
        setTimeout(function () {
            $(btn).tooltip('hide');
        }, 1000);
    }

    function disposeTooltip(btn) {
        setTimeout(function () {
            $(btn).tooltip('dispose');
        }, 1500);
    }

    var clipboard = new ClipboardJS('#copy');

    clipboard.on('success', function (e) {
        e.clearSelection();
        console.info('Action:', e.action);
        console.info('Text:', e.text);
        console.info('Trigger:', e.trigger);
        setTooltip(e.trigger, 'Copied!');
        hideTooltip(e.trigger);
        disposeTooltip(e.trigger);
    });

    clipboard.on('error', function (e) {
        console.error('Action:', e.action);
        console.error('Trigger:', e.trigger);
        setTooltip(e.trigger, fallbackMessage(e.action));
        hideTooltip(e.trigger);
    });

    function getCopyData(subreddit, reddit_title, filename, background_credit) {

        if (subreddit == undefined) {
            subredditCopy = "";
        } else {
            subredditCopy = "r/" + subreddit + "\n\n";
        }

        const file = filename.slice(0, -4);
        if (reddit_title == file) {
            titleCopy = reddit_title;
        } else {
            titleCopy = file;
        }

        var copyData = "";
        copyData += subredditCopy;
        copyData += titleCopy;
        copyData += "\n\nBackground credit: " + background_credit;
        return copyData;
    }

    function getLink(subreddit, id, reddit_title) {
        if (subreddit == undefined) {
            return reddit_title;
        } else {
            return "<a target='_blank' href='https://www.reddit.com/r/" + subreddit + "/comments/" + id + "/'>" + reddit_title + "</a>";
        }
    }

    function checkTitle(reddit_title, filename) {
        const file = filename.slice(0, -4);
        if (reddit_title == file) {
            return reddit_title;
        } else {
            return file;
        }
    }

    var searchFilter = () => {
        const input = document.querySelector(".searchFilter");
        const cards = document.getElementsByClassName("col");
        console.log(cards[1])
        let filter = input.value
        for (let i = 0; i < cards.length; i++) {
            let title = cards[i].querySelector(".card-text");
            if (title.innerText.toLowerCase().indexOf(filter.toLowerCase()) > -1) {
                cards[i].classList.remove("d-none")
            } else {
                cards[i].classList.add("d-none")
            }
        }
    }
</script>
{% endblock %}

================================================
FILE: GUI/layout.html
================================================
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="cache-control" content="no-cache" />
    <title>RedditVideoMakerBot</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link href="https://getbootstrap.com/docs/5.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

    <style>
        .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            user-select: none;
        }

        .feedback-invalid {
            color: #dc3545;
        }

        @media (min-width: 768px) {
            .bd-placeholder-img-lg {
                font-size: 3.5rem;
            }
        }

        .bi {
            vertical-align: -.125em;
            fill: currentColor;
        }

        .nav {
            display: flex;
            flex-wrap: nowrap;
            padding-bottom: 1rem;
            margin-top: -1px;
            overflow-x: auto;
            text-align: center;
            white-space: nowrap;
            -webkit-overflow-scrolling: touch;
        }

        #tooltip {
            background-color: #333;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 13px;
        }

        .tooltip-inner {
            max-width: 500px !important;
        }
        #hard-reload {
            cursor: pointer;
            color: darkblue;
        }
        #hard-reload:hover {
            color: blue;
        }
    </style>
</head>

<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
    crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.3/dist/umd/popper.min.js"
    integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
    crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js"
    integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
    crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.10/clipboard.min.js"></script>
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>

<body>
    <header>
        {% if get_flashed_messages() %}
        {% for category, message in get_flashed_messages(with_categories=true) %}

        {% if category == "error" %}
        <div class="alert alert-danger mb-0 text-center" role="alert">
            {{ message }}
        </div>

        {% else %}
        <div class="alert alert-success mb-0 text-center" role="alert">
            {{ message }}
        </div>
        {% endif %}
        {% endfor %}
        {% endif %}
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a href="/" class="navbar-brand d-flex align-items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor"
                        stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="me-2"
                        viewBox="0 0 24 24">
                        <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
                        <circle cx="12" cy="13" r="4" />
                    </svg>
                    <strong>RedditVideoMakerBot</strong>
                </a>

                <div class="collapse navbar-collapse">
                    <ul class="navbar-nav mr-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="backgrounds">Background Manager</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="settings">Settings</a>
                        </li>
                    </ul>
                    <!-- Future feature
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <button class="btn btn-outline-success mr-auto mt-2 mt-lg-0">Create new short</button>
                        </li>
                    </ul>
                    -->
                </div>
            </div>
        </nav>
    </header>

    {% block main %}{% endblock %}

    <footer class="text-muted py-5">
        <div class="container">
            <p class="float-end mb-1">
                <a href="#">Back to top</a>
            </p>
            <p class="mb-1"><a href="https://getbootstrap.com/docs/5.2/examples/album/" target="_blank">Album</a>
                Example
                Theme by &copy; Bootstrap. <a
                    href="https://github.com/elebumm/RedditVideoMakerBot/blob/master/README.md#developers-and-maintainers"
                    target="_blank">Developers and Maintainers</a></p>
            <p class="mb-0">If your data is not refreshing, try to hard reload(Ctrl + F5) or click <a id="hard-reload">this</a> and visit your local

                <strong>{{ file }}</strong> file.
            </p>
        </div>
    </footer>
    <script>
        document.getElementById("hard-reload").addEventListener("click", function () {
            window.location.reload(true);
        });
    </script>
</body>

</html>

================================================
FILE: GUI/settings.html
================================================
{% extends "layout.html" %}
{% block main %}

<main>
    <br>
    <div class="container">
        <form id="settingsForm" action="/settings" method="post" novalidate>

            <!-- Reddit Credentials -->
            <p class="h4">Reddit Credentials</p>
            <div class="row mb-2">
                <label for="client_id" class="col-4">Client ID</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-person"></i>
                        </div>
                        <input name="client_id" value="{{ data.client_id }}" placeholder="Your Reddit app's client ID"
                            type="text" class="form-control" data-toggle="tooltip"
                            data-original-title='Text under "personal use script" on www.reddit.com/prefs/apps'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="client_secret" class="col-4">Client Secret</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-key-fill"></i>
                        </div>
                        <input name="client_secret" value="{{ data.client_secret }}"
                            placeholder="Your Reddit app's client secret" type="text" class="form-control"
                            data-toggle="tooltip" data-original-title='"Secret" on www.reddit.com/prefs/apps'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="username" class="col-4">Reddit Username</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-person-fill"></i>
                        </div>
                        <input name="username" value="{{ data.username }}" placeholder="Your Reddit account's username"
                            type="text" class="form-control">
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="password" class="col-4">Reddit Password</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-lock-fill"></i>
                        </div>
                        <input name="password" value="{{ data.password }}" placeholder="Your Reddit account's password"
                            type="password" class="form-control">
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label class="col-4">Do you have Reddit 2FA enabled?</label>
                <div class="col-8">
                    <div class="form-check form-switch">
                        <input name="2fa" class="form-check-input" type="checkbox" value="True" data-toggle="tooltip"
                            data-original-title='Check it if you have enabled 2FA on your Reddit account'>
                    </div>
                    <span class="form-text text-muted"><a
                            href="https://reddit-video-maker-bot.netlify.app/docs/configuring#setting-up-the-api"
                            target="_blank">Need help? Click here to open step-by-step guide.</a></span>
                </div>
            </div>

            <!-- Reddit Thread -->
            <p class="h4">Reddit Thread</p>
            <div class="row mb-2">
                <label class="col-4">Random Thread</label>
                <div class="col-8">
                    <div class="form-check form-switch">
                        <input name="random" class="form-check-input" type="checkbox" value="True" data-toggle="tooltip"
                            data-original-title='If disabled, it will ask you for a thread link, instead of picking random one'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="subreddit" class="col-4">Subreddit</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-reddit"></i>
                        </div>
                        <input value="{{ data.subreddit }}" name="subreddit" type="text" class="form-control"
                            placeholder="Subreddit to pull posts from (e.g. AskReddit)" data-toggle="tooltip"
                            data-original-title='You can have multiple subreddits,
                                    add "+" between them (e.g. AskReddit+Redditdev)'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="post_id" class="col-4">Post ID</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-file-text"></i>
                        </div>
                        <input value="{{ data.post_id }}" name="post_id" type="text" class="form-control"
                            placeholder="Used if you want to use a specific post (e.g. urdtfx)">
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="max_comment_length" class="col-4">Max Comment Length</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="max_comment_length" type="range" class="form-range" min="10" max="10000" step="1"
                            value="{{ data.max_comment_length }}" data-toggle="tooltip"
                            data-original-title="{{ data.max_comment_length }}">
                    </div>
                    <span class="form-text text-muted">Max number of characters a comment can have.</span>
                </div>
            </div>
            <div class="row mb-2">
                <label for="post_lang" class="col-4">Post Language</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-translate"></i>
                        </div>
                        <input value="{{ data.post_lang }}" name="post_lang" type="text" class="form-control"
                            placeholder="The language you would like to translate to">
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="min_comments" class="col-4">Minimum Comments</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="min_comments" type="range" class="form-range" min="15" max="1000" step="1"
                            value="{{ data.min_comments }}" data-toggle="tooltip"
                            data-original-title="{{ data.min_comments }}">
                    </div>
                    <span class="form-text text-muted">The minimum number of comments a post should have to be
                        included.</span>
                </div>
            </div>

            <!-- General Settings -->
            <p class="h4">General Settings</p>
            <div class="row mb-2">
                <label class="col-4">Allow NSFW</label>
                <div class="col-8">
                    <div class="form-check form-switch">
                        <input name="allow_nsfw" class="form-check-input" type="checkbox" value="True"
                            data-toggle="tooltip" data-original-title='If checked NSFW posts will be allowed'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="theme" class="col-4">Reddit Theme</label>
                <div class="col-8">
                    <select name="theme" class="form-select" data-toggle="tooltip"
                        data-original-title='Sets the theme of Reddit screenshots'>
                        <option value="dark">Dark</option>
                        <option value="light">Light</option>
                    </select>
                </div>
            </div>
            <div class="row mb-2">
                <label for="times_to_run" class="col-4">Times To Run</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="times_to_run" type="range" class="form-range" min="1" max="1000" step="1"
                            value="{{ data.times_to_run }}" data-toggle="tooltip"
                            data-original-title="{{ data.times_to_run }}">
                    </div>
                    <span class="form-text text-muted">Used if you want to create multiple videos.</span>
                </div>
            </div>
            <div class="row mb-2">
                <label for="opacity" class="col-4">Opacity Of Comments</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="opacity" type="range" class="form-range" min="0" max="1" step="0.05"
                            value="{{ data.opacity }}" data-toggle="tooltip" data-original-title="{{ data.opacity }}">
                    </div>
                    <span class="form-text text-muted">Sets the opacity of the comments when overlayed over the
                        background.</span>
                </div>
            </div>
            <div class="row mb-2">
                <label for="transition" class="col-4">Transition</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="transition" type="range" class="form-range" min="0" max="2" step="0.05"
                            value="{{ data.transition }}" data-toggle="tooltip"
                            data-original-title="{{ data.transition }}">
                    </div>
                    <span class="form-text text-muted">Sets the transition time (in seconds) between the
                        comments. Set to 0 if you want to disable it.</span>
                </div>
            </div>
            <div class="row mb-2">
                <label for="background_choice" class="col-4">Background Choice</label>
                <div class="col-8">
                    <select name="background_choice" class="form-select" data-toggle="tooltip"
                        data-original-title='Sets the background of the video'>
                        <option value=" ">Random Video</option>
                        {% for background in checks["background_video"]["options"][1:] %}
                        <option value="{{background}}">{{background}}</option>
                        {% endfor %}
                    </select>
                    <span class="form-text text-muted"><a href="/backgrounds" target="_blank">See all available
                            backgrounds</a></span>
                </div>
            </div>
            <div class="row mb-2">
                <label for="background_thumbnail" class="col-4">Background Thumbnail</label>
                <div class="col-8">
                    <div class="form-check form-switch">
                        <input name="background_thumbnail" class="form-check-input" type="checkbox" value="True"
                            data-toggle="tooltip"
                            data-original-title='If checked a thumbnail will be added to the video (put a thumbnail.png file in the assets/backgrounds directory for it to be used.)'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="background_thumbnail_font_family" class="col-4">Background Thumbnail Font Family (.ttf)</label>
                <div class="col-8">
                    <input name="background_thumbnail_font_family" type="text" class="form-control"
                        placeholder="arial" value="{{ data.background_thumbnail_font_family }}">
                </div>
            </div>
            <div class="row mb-2">
                <label for="background_thumbnail_font_size" class="col-4">Background Thumbnail Font Size (px)</label>
                <div class="col-8">
                    <input name="background_thumbnail_font_size" type="number" class="form-control"
                        placeholder="96" value="{{ data.background_thumbnail_font_size }}">
                </div>
            </div>
            <!-- need to create a color picker -->
            <div class="row mb-2">
                <label for="background_thumbnail_font_color" class="col-4">Background Thumbnail Font Color (rgb)</label>
                <div class="col-8">
                    <input name="background_thumbnail_font_color" type="text" class="form-control"
                        placeholder="255,255,255" value="{{ data.background_thumbnail_font_color }}">
                </div>
            </div>

            <!-- TTS Settings -->
            <p class="h4">TTS Settings</p>
            <div class="row mb-2">
                <label for="voice_choice" class="col-4">TTS Voice Choice</label>
                <div class="col-8">
                    <select name="voice_choice" class="form-select" data-toggle="tooltip"
                        data-original-title='The voice platform used for TTS generation'>
                        <option value="streamlabspolly">Streamlabspolly</option>
                        <option value="tiktok">TikTok</option>
                        <option value="googletranslate">Google Translate</option>
                        <option value="awspolly">AWS Polly</option>
                        <option value="pyttsx">Python TTS (pyttsx)</option>
                    </select>
                </div>
            </div>
            <div class="row mb-2">
                <label for="aws_polly_voice" class="col-4">AWS Polly Voice</label>
                <div class="col-8">
                    <div class="input-group voices">
                        <select name="aws_polly_voice" class="form-select" data-toggle="tooltip"
                            data-original-title='The voice used for AWS Polly'>
                            <option value="Brian">Brian</option>
                            <option value="Emma">Emma</option>
                            <option value="Russell">Russell</option>
                            <option value="Joey">Joey</option>
                            <option value="Matthew">Matthew</option>
                            <option value="Joanna">Joanna</option>
                            <option value="Kimberly">Kimberly</option>
                            <option value="Amy">Amy</option>
                            <option value="Geraint">Geraint</option>
                            <option value="Nicole">Nicole</option>
                            <option value="Justin">Justin</option>
                            <option value="Ivy">Ivy</option>
                            <option value="Kendra">Kendra</option>
                            <option value="Salli">Salli</option>
                            <option value="Raveena">Raveena</option>
                        </select>

                        <button type="button" class="btn btn-primary"><i id="awspolly_icon"
                                class="bi-volume-up-fill"></i></button>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="streamlabs_polly_voice" class="col-4">Streamlabs Polly Voice</label>
                <div class="col-8">
                    <div class="input-group voices">
                        <select id="streamlabs_polly_voice" name="streamlabs_polly_voice" class="form-select"
                            data-toggle="tooltip" data-original-title='The voice used for Streamlabs Polly'>
                            <option value="Brian">Brian</option>
                            <option value="Emma">Emma</option>
                            <option value="Russell">Russell</option>
                            <option value="Joey">Joey</option>
                            <option value="Matthew">Matthew</option>
                            <option value="Joanna">Joanna</option>
                            <option value="Kimberly">Kimberly</option>
                            <option value="Amy">Amy</option>
                            <option value="Geraint">Geraint</option>
                            <option value="Nicole">Nicole</option>
                            <option value="Justin">Justin</option>
                            <option value="Ivy">Ivy</option>
                            <option value="Kendra">Kendra</option>
                            <option value="Salli">Salli</option>
                            <option value="Raveena">Raveena</option>
                        </select>

                        <button type="button" class="btn btn-primary"><i id="streamlabs_icon"
                                class="bi bi-volume-up-fill"></i></button>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="tiktok_voice" class="col-4">TikTok Voice</label>
                <div class="col-8">
                    <div class="input-group voices">
                        <select name="tiktok_voice" class="form-select" data-toggle="tooltip"
                            data-original-title='The voice used for TikTok TTS'>
                            <option disabled value="">-----Disney Voices-----</option>
                            <option value="en_us_ghostface">Ghost Face</option>
                            <option value="en_us_chewbacca">Chewbacca</option>
                            <option value="en_us_c3po">C3PO</option>
                            <option value="en_us_stitch">Stitch</option>
                            <option value="en_us_stormtrooper">Stormtrooper</option>
                            <option value="en_us_rocket">Rocket</option>
                            <option disabled value="">-----English Voices-----</option>
                            <option value="en_au_001">English AU - Female</option>
                            <option value="en_au_002">English AU - Male</option>
                            <option value="en_uk_001">English UK - Male 1</option>
                            <option value="en_uk_003">English UK - Male 2</option>
                            <option value="en_us_001">English US - Female (Int. 1)</option>
                            <option value="en_us_002">English US - Female (Int. 2)</option>
                            <option value="en_us_006">English US - Male 1</option>
                            <option value="en_us_007">English US - Male 2</option>
                            <option value="en_us_009">English US - Male 3</option>
                            <option value="en_us_010">English US - Male 4</option>
                            <option disabled value="">-----European Voices-----</option>
                            <option value="fr_001">French - Male 1</option>
                            <option value="fr_002">French - Male 2</option>
                            <option value="de_001">German - Female</option>
                            <option value="de_002">German - Male</option>
                            <option value="es_002">Spanish - Male</option>
                            <option disabled value="">-----American Voices-----</option>
                            <option value="es_mx_002">Spanish MX - Male</option>
                            <option value="br_001">Portuguese BR - Female 1</option>
                            <option value="br_003">Portuguese BR - Female 2</option>
                            <option value="br_004">Portuguese BR - Female 3</option>
                            <option value="br_005">Portuguese BR - Male</option>
                            <option disabled value="">-----Asian Voices-----</option>
                            <option value="id_001">Indonesian - Female</option>
                            <option value="jp_001">Japanese - Female 1</option>
                            <option value="jp_003">Japanese - Female 2</option>
                            <option value="jp_005">Japanese - Female 3</option>
                            <option value="jp_006">Japanese - Male</option>
                            <option value="kr_002">Korean - Male 1</option>
                            <option value="kr_003">Korean - Female</option>
                            <option value="kr_004">Korean - Male 2</option>
                        </select>

                        <button type="button" class="btn btn-primary"><i id="tiktok_icon"
                                class="bi-volume-up-fill"></i></button>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="tiktok_sessionid" class="col-4">TikTok SessionId</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-mic-fill"></i>
                        </div>
                        <input value="{{ data.tiktok_sessionid }}" name="tiktok_sessionid" type="text" class="form-control"
                            data-toggle="tooltip"
                            data-original-title="TikTok sessionid needed for the TTS API request. Check documentation if you don't know how to obtain it.">
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="python_voice" class="col-4">Python Voice</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-mic-fill"></i>
                        </div>
                        <input value="{{ data.python_voice }}" name="python_voice" type="text" class="form-control"
                            data-toggle="tooltip"
                            data-original-title='The index of the system TTS voices (can be downloaded externally, run ptt.py to find value, start from zero)'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="py_voice_num" class="col-4">Py Voice Number</label>
                <div class="col-8">
                    <div class="input-group">
                        <div class="input-group-text">
                            <i class="bi bi-headset"></i>
                        </div>
                        <input value="{{ data.py_voice_num }}" name="py_voice_num" type="text" class="form-control"
                            data-toggle="tooltip"
                            data-original-title='The number of system voices (2 are pre-installed in Windows)'>
                    </div>
                </div>
            </div>
            <div class="row mb-2">
                <label for="silence_duration" class="col-4">Silence Duration</label>
                <div class="col-8">
                    <div class="input-group">
                        <input name="silence_duration" type="range" class="form-range" min="0" max="5" step="0.05"
                            value="{{ data.silence_duration }}" data-toggle="tooltip"
                            data-original-title="{{ data.silence_duration }}">
                    </div>
                    <span class="form-text text-muted">Time in seconds between TTS comments.</span>
                </div>
            </div>
            <div class="col text-center">
                <br>
                <button id="defaultSettingsBtn" type="button" class="btn btn-secondary">Default
                    Settings</button>
                <button id="submitButton" type="submit" class="btn btn-success">Save
                    Changes</button>
            </div>
        </form>
    </div>
    <audio src=""></audio>
</main>

<script>
    // Test voices buttons
    var playing = false;

    $(".voices button").click(function () {
        var icon = $(this).find("i");
        var audio = $("audio");

        if (playing) {
            playing.toggleClass("bi-volume-up-fill bi-stop-fill");

            // Clicked the same button - stop audio
            if (playing.prop("id") == icon.prop("id")) {
                audio[0].pause();
                playing = false;
                return;
            }
        }

        icon.toggleClass("bi-volume-up-fill bi-stop-fill");
        let path = "voices/" + $(this).closest(".voices").find("select").prop("value").toLowerCase() + ".mp3";

        audio.prop("src", path);
        audio[0].play();
        playing = icon;

        audio[0].onended = function () {
            icon.toggleClass("bi-volume-up-fill bi-stop-fill");
            playing = false;
        }
    });

    // Wait for DOM to load
    $(document).ready(function () {
        // Add tooltips
        $('[data-toggle="tooltip"]').tooltip();
        $('[data-toggle="tooltip"]').on('click', function () {
            $(this).tooltip('hide');
        });

        // Update slider tooltip
        $(".form-range").on("input", function () {
            $(this).attr("value", $(this).val());
            $(this).attr("data-original-title", $(this).val());
            $(this).tooltip("show");
        });

        // Get current config
        var data = JSON.parse('{{data | tojson}}');

        // Set current checkboxes
        $('.form-check-input').each(function () {
            $(this).prop("checked", data[$(this).prop("name")]);
        });

        // Set current select options
        $('.form-select').each(function () {
            $(this).prop("value", data[$(this).prop("name")]);
        });

        // Submit "False" when checkbox isn't ticked
        $('#settingsForm').submit(function () {
            $('.form-check-input').each(function () {
                if (!($(this).is(':checked'))) {
                    $(this).prop("value", "False");
                    $(this).prop("checked", true);
                }
            });
        });


        // Get validation values
        let validateChecks = JSON.parse('{{checks | tojson}}');

        // Set default values
        $("#defaultSettingsBtn").click(function (event) {
            $("#settingsForm input, #settingsForm select").each(function () {
                let check = validateChecks[$(this).prop("name")];

                if (check["default"]) {
                    $(this).prop("value", check["default"]);

                    // Update tooltip value for input[type="range"]
                    if ($(this).prop("type") == "range") {
                        $(this).attr("data-original-title", check["default"]);
                    }
                }
            });
        });

        // Validate form
        $('#settingsForm').submit(function (event) {
            $("#settingsForm input, #settingsForm select").each(function () {
                if (!(validate($(this)))) {
                    event.preventDefault();
                    event.stopPropagation();

                    $("html, body").animate({
                        scrollTop: $(this).offset().top
                    });
                }

            });
        });

        $("#settingsForm input").on("keyup", function () {
            validate($(this));
        });

        $("#settingsForm select").on("change", function () {
            validate($(this));
        });

        function validate(object) {
            let bool = check(object.prop("name"), object.prop("value"));

            // Change class
            if (bool) {
                object.removeClass("is-invalid");
                object.addClass("is-valid");
            }
            else {
                object.removeClass("is-valid");
                object.addClass("is-invalid");
            }

            return bool;

            // Check values (return true/false)
            function check(name, value) {
                let check = validateChecks[name];

                // If value is empty - check if it's optional
                if (value.length == 0) {
                    if (check["optional"] == false) {
                        return false;
                    }
                    else {
                        object.prop("value", check["default"]);
                        return true;
                    }
                }

                // Check if value is too short
                if (check["nmin"]) {
                    if (check["type"] == "int" || check["type"] == "float") {
                        if (value < check["nmin"]) {
                            return false;
                        }
                    }
                    else {
                        if (value.length < check["nmin"]) {
                            return false;
                        }

                    }
                }

                // Check if value is too long
                if (check["nmax"]) {
                    if (check["type"] == "int" || check["type"] == "float") {
                        if (value > check["nmax"]) {
                            return false;
                        }
                    }
                    else {
                        if (value.length > check["nmax"]) {
                            return false;
                        }

                    }
                }

                // Check if value matches regex
                if (check["regex"]) {
                    let regex = new RegExp(check["regex"]);
                    if (!(regex.test(value))) {
                        return false;
                    }
                }

                return true;
            }
        }
    });
</script>

{% endblock %}


================================================
FILE: GUI.py
================================================
import webbrowser
from pathlib import Path

# Used "tomlkit" instead of "toml" because it doesn't change formatting on "dump"
import tomlkit
from flask import (
    Flask,
    redirect,
    render_template,
    request,
    send_from_directory,
    url_for,
)

import utils.gui_utils as gui

# Set the hostname
HOST = "localhost"
# Set the port number
PORT = 4000

# Configure application
app = Flask(__name__, template_folder="GUI")

# Configure secret key only to use 'flash'
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'


# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


# Display index.html
@app.route("/")
def index():
    return render_template("index.html", file="videos.json")


@app.route("/backgrounds", methods=["GET"])
def backgrounds():
    return render_template("backgrounds.html", file="backgrounds.json")


@app.route("/background/add", methods=["POST"])
def background_add():
    # Get form values
    youtube_uri = request.form.get("youtube_uri").strip()
    filename = request.form.get("filename").strip()
    citation = request.form.get("citation").strip()
    position = request.form.get("position").strip()

    gui.add_background(youtube_uri, filename, citation, position)

    return redirect(url_for("backgrounds"))


@app.route("/background/delete", methods=["POST"])
def background_delete():
    key = request.form.get("background-key")
    gui.delete_background(key)

    return redirect(url_for("backgrounds"))


@app.route("/settings", methods=["GET", "POST"])
def settings():
    config_load = tomlkit.loads(Path("config.toml").read_text())
    config = gui.get_config(config_load)

    # Get checks for all values
    checks = gui.get_checks()

    if request.method == "POST":
        # Get data from form as dict
        data = request.form.to_dict()

        # Change settings
        config = gui.modify_settings(data, config_load, checks)

    return render_template("settings.html", file="config.toml", data=config, checks=checks)


# Make videos.json accessible
@app.route("/videos.json")
def videos_json():
    return send_from_directory("video_creation/data", "videos.json")


# Make backgrounds.json accessible
@app.route("/backgrounds.json")
def backgrounds_json():
    return send_from_directory("utils", "backgrounds.json")


# Make videos in results folder accessible
@app.route("/results/<path:name>")
def results(name):
    return send_from_directory("results", name, as_attachment=True)


# Make voices samples in voices folder accessible
@app.route("/voices/<path:name>")
def voices(name):
    return send_from_directory("GUI/voices", name, as_attachment=True)


# Run browser and start the app
if __name__ == "__main__":
    webbrowser.open(f"http://{HOST}:{PORT}", new=2)
    print("Website opened in new tab. Refresh if it didn't load.")
    app.run(port=PORT)


================================================
FILE: LICENSE
================================================
                 GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

                            Preamble

The GNU General Public License is a free, copyleft license for
software and other kinds of works.

The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.

Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

0. Definitions.

"This License" refers to version 3 of the GNU General Public License.

"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.

To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

A "covered work" means either the unmodified Program or a work based
on the Program.

To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

1. Source Code.

The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.

A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

The Corresponding Source for a work in source code form is that
same work.

2. Basic Permissions.

All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.

3. Protecting Users' Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

4. Conveying Verbatim Copies.

You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

7. Additional Terms.

"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

8. Termination.

You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

9. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.

An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

11. Patents.

A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".

A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

12. No Surrender of Others' Freedom.

If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

13. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

15. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# Reddit Video Maker Bot 🎥

All done WITHOUT video editing or asset compiling. Just pure ✨programming magic✨.

Created by Lewis Menelaws & [TMRRW](https://tmrrwinc.ca)

<a target="_blank" href="https://tmrrwinc.ca">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/6053155/170528535-e274dc0b-7972-4b27-af22-637f8c370133.png">
  <source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/6053155/170528582-cb6671e7-5a2f-4bd4-a048-0e6cfa54f0f7.png">
  <img src="https://user-images.githubusercontent.com/6053155/170528582-cb6671e7-5a2f-4bd4-a048-0e6cfa54f0f7.png" width="350">
</picture>

</a>

## Video Explainer

[![lewisthumbnail](https://user-images.githubusercontent.com/6053155/173631669-1d1b14ad-c478-4010-b57d-d79592a789f2.png)
](https://www.youtube.com/watch?v=3gjcY_00U1w)

## Motivation 🤔

These videos on TikTok, YouTube and Instagram get MILLIONS of views across all platforms and require very little effort.
The only original thing being done is the editing and gathering of all materials...

... but what if we can automate that process? 🤔

## Disclaimers 🚨

- **At the moment**, this repository won't attempt to upload this content through this bot. It will give you a file that
  you will then have to upload manually. This is for the sake of avoiding any sort of community guideline issues.

## Requirements

- Python 3.10
- Playwright (this should install automatically in installation)

## Installation 👩‍💻

1. Clone this repository:
    ```sh
    git clone https://github.com/elebumm/RedditVideoMakerBot.git
    cd RedditVideoMakerBot
    ```

2. Create and activate a virtual environment:
    - On **Windows**:
        ```sh
        python -m venv ./venv
        .\venv\Scripts\activate
        ```
    - On **macOS and Linux**:
        ```sh
        python3 -m venv ./venv
        source ./venv/bin/activate
        ```

3. Install the required dependencies:
    ```sh
    pip install -r requirements.txt
    ```

4. Install Playwright and its dependencies:
    ```sh
    python -m playwright install
    python -m playwright install-deps
    ```

---

**EXPERIMENTAL!!!!**

   - On macOS and Linux (Debian, Arch, Fedora, CentOS, and based on those), you can run an installation script that will automatically install steps 1 to 3. (requires bash)
   - `bash <(curl -sL https://raw.githubusercontent.com/elebumm/RedditVideoMakerBot/master/install.sh)`
   - This can also be used to update the installation

---

5. Run the bot:
    ```sh
    python main.py
    ```

6. Visit [the Reddit Apps page](https://www.reddit.com/prefs/apps), and set up an app that is a "script". Paste any URL in the redirect URL field, for example: `https://jasoncameron.dev`.

7. The bot will prompt you to fill in your details to connect to the Reddit API and configure the bot to your liking.

8. Enjoy 😎

9. If you need to reconfigure the bot, simply open the `config.toml` file and delete the lines that need to be changed. On the next run of the bot, it will help you reconfigure those options.

(Note: If you encounter any errors installing or running the bot, try using `python3` or `pip3` instead of `python` or `pip`.)

For a more detailed guide about the bot, please refer to the [documentation](https://reddit-video-maker-bot.netlify.app/).

## Video

https://user-images.githubusercontent.com/66544866/173453972-6526e4e6-c6ef-41c5-ab40-5d275e724e7c.mp4

## Contributing & Ways to improve 📈

In its current state, this bot does exactly what it needs to do. However, improvements can always be made!

I have tried to simplify the code so anyone can read it and start contributing at any skill level. Don't be shy :) contribute!

- [ ] Creating better documentation and adding a command line interface.
- [x] Allowing the user to choose background music for their videos.
- [x] Allowing users to choose a reddit thread instead of being randomized.
- [x] Allowing users to choose a background that is picked instead of the Minecraft one.
- [x] Allowing users to choose between any subreddit.
- [x] Allowing users to change voice.
- [x] Checks if a video has already been created
- [x] Light and Dark modes
- [x] NSFW post filter

Please read our [contributing guidelines](CONTRIBUTING.md) for more detailed information.

### For any questions or support join the [Discord](https://discord.gg/qfQSx45xCV) server

## Developers and maintainers.

Elebumm (Lewis#6305) - https://github.com/elebumm (Founder)

Jason Cameron - https://github.com/JasonLovesDoggo (Maintainer)

Simon (OpenSourceSimon) - https://github.com/OpenSourceSimon

CallumIO (c.#6837) - https://github.com/CallumIO

Verq (Verq#2338) - https://github.com/CordlessCoder

LukaHietala (Pix.#0001) - https://github.com/LukaHietala

Freebiell (Freebie#3263) - https://github.com/FreebieII

Aman Raza (electro199#8130) - https://github.com/electro199

Cyteon (cyteon) - https://github.com/cyteon


## LICENSE
[Roboto Fonts](https://fonts.google.com/specimen/Roboto/about) are licensed under [Apache License V2](https://www.apache.org/licenses/LICENSE-2.0)


================================================
FILE: TTS/GTTS.py
================================================
import random

from gtts import gTTS

from utils import settings


class GTTS:
    def __init__(self):
        self.max_chars = 5000
        self.voices = []

    def run(self, text, filepath, random_voice: bool = False):
        tts = gTTS(
            text=text,
            lang=settings.config["reddit"]["thread"]["post_lang"] or "en",
            slow=False,
        )
        tts.save(filepath)

    def randomvoice(self):
        return random.choice(self.voices)


================================================
FILE: TTS/TikTok.py
================================================
# documentation for tiktok api: https://github.com/oscie57/tiktok-voice/wiki
import base64
import random
import time
from typing import Final, Optional

import requests

from utils import settings

__all__ = ["TikTok", "TikTokTTSException"]

disney_voices: Final[tuple] = (
    "en_us_ghostface",  # Ghost Face
    "en_us_chewbacca",  # Chewbacca
    "en_us_c3po",  # C3PO
    "en_us_stitch",  # Stitch
    "en_us_stormtrooper",  # Stormtrooper
    "en_us_rocket",  # Rocket
    "en_female_madam_leota",  # Madame Leota
    "en_male_ghosthost",  # Ghost Host
    "en_male_pirate",  # pirate
)

eng_voices: Final[tuple] = (
    "en_au_001",  # English AU - Female
    "en_au_002",  # English AU - Male
    "en_uk_001",  # English UK - Male 1
    "en_uk_003",  # English UK - Male 2
    "en_us_001",  # English US - Female (Int. 1)
    "en_us_002",  # English US - Female (Int. 2)
    "en_us_006",  # English US - Male 1
    "en_us_007",  # English US - Male 2
    "en_us_009",  # English US - Male 3
    "en_us_010",  # English US - Male 4
    "en_male_narration",  # Narrator
    "en_male_funny",  # Funny
    "en_female_emotional",  # Peaceful
    "en_male_cody",  # Serious
)

non_eng_voices: Final[tuple] = (
    # Western European voices
    "fr_001",  # French - Male 1
    "fr_002",  # French - Male 2
    "de_001",  # German - Female
    "de_002",  # German - Male
    "es_002",  # Spanish - Male
    "it_male_m18",  # Italian - Male
    # South american voices
    "es_mx_002",  # Spanish MX - Male
    "br_001",  # Portuguese BR - Female 1
    "br_003",  # Portuguese BR - Female 2
    "br_004",  # Portuguese BR - Female 3
    "br_005",  # Portuguese BR - Male
    # asian voices
    "id_001",  # Indonesian - Female
    "jp_001",  # Japanese - Female 1
    "jp_003",  # Japanese - Female 2
    "jp_005",  # Japanese - Female 3
    "jp_006",  # Japanese - Male
    "kr_002",  # Korean - Male 1
    "kr_003",  # Korean - Female
    "kr_004",  # Korean - Male 2
)

vocals: Final[tuple] = (
    "en_female_f08_salut_damour",  # Alto
    "en_male_m03_lobby",  # Tenor
    "en_male_m03_sunshine_soon",  # Sunshine Soon
    "en_female_f08_warmy_breeze",  # Warmy Breeze
    "en_female_ht_f08_glorious",  # Glorious
    "en_male_sing_funny_it_goes_up",  # It Goes Up
    "en_male_m2_xhxs_m03_silly",  # Chipmunk
    "en_female_ht_f08_wonderful_world",  # Dramatic
)


class TikTok:
    """TikTok Text-to-Speech Wrapper"""

    def __init__(self):
        headers = {
            "User-Agent": "com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; "
            "Build/NRD90M;tt-ok/3.12.13.1)",
            "Cookie": f"sessionid={settings.config['settings']['tts']['tiktok_sessionid']}",
        }

        self.URI_BASE = "https://api16-normal-c-useast1a.tiktokv.com/media/api/text/speech/invoke/"
        self.max_chars = 200

        self._session = requests.Session()
        # set the headers to the session, so we don't have to do it for every request
        self._session.headers = headers

    def run(self, text: str, filepath: str, random_voice: bool = False):
        if random_voice:
            voice = self.random_voice()
        else:
            # if tiktok_voice is not set in the config file, then use a random voice
            voice = settings.config["settings"]["tts"].get("tiktok_voice", None)

        # get the audio from the TikTok API
        data = self.get_voices(voice=voice, text=text)

        # check if there was an error in the request
        status_code = data["status_code"]
        if status_code != 0:
            raise TikTokTTSException(status_code, data["message"])

        # decode data from base64 to binary
        try:
            raw_voices = data["data"]["v_str"]
        except:
            print(
                "The TikTok TTS returned an invalid response. Please try again later, and report this bug."
            )
            raise TikTokTTSException(0, "Invalid response")
        decoded_voices = base64.b64decode(raw_voices)

        # write voices to specified filepath
        with open(filepath, "wb") as out:
            out.write(decoded_voices)

    def get_voices(self, text: str, voice: Optional[str] = None) -> dict:
        """If voice is not passed, the API will try to use the most fitting voice"""
        # sanitize text
        text = text.replace("+", "plus").replace("&", "and").replace("r/", "")

        # prepare url request
        params = {"req_text": text, "speaker_map_type": 0, "aid": 1233}

        if voice is not None:
            params["text_speaker"] = voice

        # send request
        try:
            response = self._session.post(self.URI_BASE, params=params)
        except ConnectionError:
            time.sleep(random.randrange(1, 7))
            response = self._session.post(self.URI_BASE, params=params)

        return response.json()

    @staticmethod
    def random_voice() -> str:
        return random.choice(eng_voices)


class TikTokTTSException(Exception):
    def __init__(self, code: int, message: str):
        self._code = code
        self._message = message

    def __str__(self) -> str:
        if self._code == 1:
            return f"Code: {self._code}, reason: probably the aid value isn't correct, message: {self._message}"

        if self._code == 2:
            return f"Code: {self._code}, reason: the text is too long, message: {self._message}"

        if self._code == 4:
            return f"Code: {self._code}, reason: the speaker doesn't exist, message: {self._message}"

        return f"Code: {self._message}, reason: unknown, message: {self._message}"


================================================
FILE: TTS/__init__.py
================================================


================================================
FILE: TTS/aws_polly.py
================================================
import random
import sys

from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError, ProfileNotFound

from utils import settings

voices = [
    "Brian",
    "Emma",
    "Russell",
    "Joey",
    "Matthew",
    "Joanna",
    "Kimberly",
    "Amy",
    "Geraint",
    "Nicole",
    "Justin",
    "Ivy",
    "Kendra",
    "Salli",
    "Raveena",
]


class AWSPolly:
    def __init__(self):
        self.max_chars = 3000
        self.voices = voices

    def run(self, text, filepath, random_voice: bool = False):
        try:
            session = Session(profile_name="polly")
            polly = session.client("polly")
            if random_voice:
                voice = self.randomvoice()
            else:
                if not settings.config["settings"]["tts"]["aws_polly_voice"]:
                    raise ValueError(
                        f"Please set the TOML variable AWS_VOICE to a valid voice. options are: {voices}"
                    )
                voice = str(settings.config["settings"]["tts"]["aws_polly_voice"]).capitalize()
            try:
                # Request speech synthesis
                response = polly.synthesize_speech(
                    Text=text, OutputFormat="mp3", VoiceId=voice, Engine="neural"
                )
            except (BotoCoreError, ClientError) as error:
                # The service returned an error, exit gracefully
                print(error)
                sys.exit(-1)

            # Access the audio stream from the response
            if "AudioStream" in response:
                file = open(filepath, "wb")
                file.write(response["AudioStream"].read())
                file.close()
                # print_substep(f"Saved Text {idx} to MP3 files successfully.", style="bold green")

            else:
                # The response didn't contain audio data, exit gracefully
                print("Could not stream audio")
                sys.exit(-1)
        except ProfileNotFound:
            print("You need to install the AWS CLI and configure your profile")
            print(
                """
            Linux: https://docs.aws.amazon.com/polly/latest/dg/setup-aws-cli.html
            Windows: https://docs.aws.amazon.com/polly/latest/dg/install-voice-plugin2.html
            """
            )
            sys.exit(-1)

    def randomvoice(self):
        return random.choice(self.voices)


================================================
FILE: TTS/elevenlabs.py
================================================
import random

from elevenlabs import save
from elevenlabs.client import ElevenLabs

from utils import settings


class elevenlabs:
    def __init__(self):
        self.max_chars = 2500
        self.client: ElevenLabs = None

    def run(self, text, filepath, random_voice: bool = False):
        if self.client is None:
            self.initialize()
        if random_voice:
            voice = self.randomvoice()
        else:
            voice = str(settings.config["settings"]["tts"]["elevenlabs_voice_name"]).capitalize()

        audio = self.client.generate(text=text, voice=voice, model="eleven_multilingual_v1")
        save(audio=audio, filename=filepath)

    def initialize(self):
        if settings.config["settings"]["tts"]["elevenlabs_api_key"]:
            api_key = settings.config["settings"]["tts"]["elevenlabs_api_key"]
        else:
            raise ValueError(
                "You didn't set an Elevenlabs API key! Please set the config variable ELEVENLABS_API_KEY to a valid API key."
            )

        self.client = ElevenLabs(api_key=api_key)

    def randomvoice(self):
        if self.client is None:
            self.initialize()
        return random.choice(self.client.voices.get_all().voices).name


================================================
FILE: TTS/engine_wrapper.py
================================================
import os
import re
from pathlib import Path
from typing import Tuple

import numpy as np
import translators
from moviepy import AudioFileClip
from moviepy.audio.AudioClip import AudioClip
from moviepy.audio.fx import MultiplyVolume
from rich.progress import track

from utils import settings
from utils.console import print_step, print_substep
from utils.voice import sanitize_text

DEFAULT_MAX_LENGTH: int = (
    50  # Video length variable, edit this on your own risk. It should work, but it's not supported
)


class TTSEngine:
    """Calls the given TTS engine to reduce code duplication and allow multiple TTS engines.

    Args:
        tts_module            : The TTS module. Your module should handle the TTS itself and saving to the given path under the run method.
        reddit_object         : The reddit object that contains the posts to read.
        path (Optional)       : The unix style path to save the mp3 files to. This must not have leading or trailing slashes.
        max_length (Optional) : The maximum length of the mp3 files in total.

    Notes:
        tts_module must take the arguments text and filepath.
    """

    def __init__(
        self,
        tts_module,
        reddit_object: dict,
        path: str = "assets/temp/",
        max_length: int = DEFAULT_MAX_LENGTH,
        last_clip_length: int = 0,
    ):
        self.tts_module = tts_module()
        self.reddit_object = reddit_object

        self.redditid = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"])
        self.path = path + self.redditid + "/mp3"
        self.max_length = max_length
        self.length = 0
        self.last_clip_length = last_clip_length

    def add_periods(
        self,
    ):  # adds periods to the end of paragraphs (where people often forget to put them) so tts doesn't blend sentences
        for comment in self.reddit_object["comments"]:
            # remove links
            regex_urls = r"((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
            comment["comment_body"] = re.sub(regex_urls, " ", comment["comment_body"])
            comment["comment_body"] = comment["comment_body"].replace("\n", ". ")
            comment["comment_body"] = re.sub(r"\bAI\b", "A.I", comment["comment_body"])
            comment["comment_body"] = re.sub(r"\bAGI\b", "A.G.I", comment["comment_body"])
            if comment["comment_body"][-1] != ".":
                comment["comment_body"] += "."
            comment["comment_body"] = comment["comment_body"].replace(". . .", ".")
            comment["comment_body"] = comment["comment_body"].replace(".. . ", ".")
            comment["comment_body"] = comment["comment_body"].replace(". . ", ".")
            comment["comment_body"] = re.sub(r'\."\.', '".', comment["comment_body"])

    def run(self) -> Tuple[int, int]:
        Path(self.path).mkdir(parents=True, exist_ok=True)
        print_step("Saving Text to MP3 files...")

        self.add_periods()
        self.call_tts("title", process_text(self.reddit_object["thread_title"]))
        # processed_text = ##self.reddit_object["thread_post"] != ""
        idx = 0

        if settings.config["settings"]["storymode"]:
            if settings.config["settings"]["storymodemethod"] == 0:
                if len(self.reddit_object["thread_post"]) > self.tts_module.max_chars:
                    self.split_post(self.reddit_object["thread_post"], "postaudio")
                else:
                    self.call_tts("postaudio", process_text(self.reddit_object["thread_post"]))
            elif settings.config["settings"]["storymodemethod"] == 1:
                for idx, text in track(enumerate(self.reddit_object["thread_post"])):
                    self.call_tts(f"postaudio-{idx}", process_text(text))

        else:
            for idx, comment in track(enumerate(self.reddit_object["comments"]), "Saving..."):
                # ! Stop creating mp3 files if the length is greater than max length.
                if self.length > self.max_length and idx > 1:
                    self.length -= self.last_clip_length
                    idx -= 1
                    break
                if (
                    len(comment["comment_body"]) > self.tts_module.max_chars
                ):  # Split the comment if it is too long
                    self.split_post(comment["comment_body"], idx)  # Split the comment
                else:  # If the comment is not too long, just call the tts engine
                    self.call_tts(f"{idx}", process_text(comment["comment_body"]))

        print_substep("Saved Text to MP3 files successfully.", style="bold green")
        return self.length, idx

    def split_post(self, text: str, idx):
        split_files = []
        split_text = [
            x.group().strip()
            for x in re.finditer(
                r" *(((.|\n){0," + str(self.tts_module.max_chars) + "})(\.|.$))", text
            )
        ]
        self.create_silence_mp3()

        for idy, text_cut in enumerate(split_text):
            newtext = process_text(text_cut)
            # print(f"{idx}-{idy}: {newtext}\n")

            if not newtext or newtext.isspace():
                print("newtext was blank because sanitized split text resulted in none")
                continue
            else:
                self.call_tts(f"{idx}-{idy}.part", newtext)
                with open(f"{self.path}/list.txt", "w") as f:
                    for idz in range(0, len(split_text)):
                        f.write("file " + f"'{idx}-{idz}.part.mp3'" + "\n")
                    split_files.append(str(f"{self.path}/{idx}-{idy}.part.mp3"))
                    f.write("file " + f"'silence.mp3'" + "\n")

                os.system(
                    "ffmpeg -f concat -y -hide_banner -loglevel panic -safe 0 "
                    + "-i "
                    + f"{self.path}/list.txt "
                    + "-c copy "
                    + f"{self.path}/{idx}.mp3"
                )
        try:
            for i in range(0, len(split_files)):
                os.unlink(split_files[i])
        except FileNotFoundError as e:
            print("File not found: " + e.filename)
        except OSError:
            print("OSError")

    def call_tts(self, filename: str, text: str):
        if settings.config["settings"]["tts"]["voice_choice"] == "googletranslate":
            # GTTS does not have the argument 'random_voice'
            self.tts_module.run(
                text,
                filepath=f"{self.path}/{filename}.mp3",
            )
        else:
            self.tts_module.run(
                text,
                filepath=f"{self.path}/{filename}.mp3",
                random_voice=settings.config["settings"]["tts"]["random_voice"],
            )
        # try:
        #     self.length += MP3(f"{self.path}/{filename}.mp3").info.length
        # except (MutagenError, HeaderNotFoundError):
        #     self.length += sox.file_info.duration(f"{self.path}/{filename}.mp3")
        try:
            clip = AudioFileClip(f"{self.path}/{filename}.mp3")
            self.last_clip_length = clip.duration
            self.length += clip.duration
            clip.close()
        except:
            self.length = 0

    def create_silence_mp3(self):
        silence_duration = settings.config["settings"]["tts"]["silence_duration"]
        silence = AudioClip(
            frame_function=lambda t: np.sin(440 * 2 * np.pi * t),
            duration=silence_duration,
            fps=44100,
        )
        silence = silence.with_effects([MultiplyVolume(0)])
        silence.write_audiofile(f"{self.path}/silence.mp3", fps=44100, logger=None)


def process_text(text: str, clean: bool = True):
    lang = settings.config["reddit"]["thread"]["post_lang"]
    new_text = sanitize_text(text) if clean else text
    if lang:
        print_substep("Translating Text...")
        translated_text = translators.translate_text(text, translator="google", to_language=lang)
        new_text = sanitize_text(translated_text)
    return new_text


================================================
FILE: TTS/openai_tts.py
================================================
import random

import requests

from utils import settings


class OpenAITTS:
    """
    A Text-to-Speech engine that uses an OpenAI-like TTS API endpoint to generate audio from text.

    Attributes:
        max_chars (int): Maximum number of characters allowed per API call.
        api_key (str): API key loaded from settings.
        api_url (str): The complete API endpoint URL, built from a base URL provided in the config.
        available_voices (list): Static list of supported voices (according to current docs).
    """

    def __init__(self):
        # Set maximum input size based on API limits (4096 characters per request)
        self.max_chars = 4096
        self.api_key = settings.config["settings"]["tts"].get("openai_api_key")
        if not self.api_key:
            raise ValueError(
                "No OpenAI API key provided in settings! Please set 'openai_api_key' in your config."
            )

        # Read the base URL from the configuration (e.g., "https://api.openai.com/v1" or "https://api.openai.com/v1/")
        base_url = settings.config["settings"]["tts"].get(
            "openai_api_url", "https://api.openai.com/v1"
        )
        # Remove trailing slash if present
        if base_url.endswith("/"):
            base_url = base_url[:-1]
        # Append the TTS-specific path
        self.api_url = base_url + "/audio/speech"

        # Set the available voices to a static list as per OpenAI TTS documentation.
        self.available_voices = self.get_available_voices()

    def get_available_voices(self):
        """
        Return a static list of supported voices for the OpenAI TTS API.

        According to the documentation, supported voices include:
            "alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"
        """
        return ["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]

    def randomvoice(self):
        """
        Select and return a random voice from the available voices.
        """
        return random.choice(self.available_voices)

    def run(self, text, filepath, random_voice: bool = False):
        """
        Convert the provided text to speech and save the resulting audio to the specified filepath.

        Args:
            text (str): The input text to convert.
            filepath (str): The file path where the generated audio will be saved.
            random_voice (bool): If True, select a random voice from the available voices.
        """
        # Choose voice based on configuration or randomly if requested.
        if random_voice:
            voice = self.randomvoice()
        else:
            voice = settings.config["settings"]["tts"].get("openai_voice_name", "alloy")
            voice = str(voice).lower()  # Ensure lower-case as expected by the API

        # Select the model from configuration; default to 'tts-1'
        model = settings.config["settings"]["tts"].get("openai_model", "tts-1")

        # Create payload for API request
        payload = {
            "model": model,
            "voice": voice,
            "input": text,
            "response_format": "mp3",  # allowed formats: "mp3", "aac", "opus", "flac", "pcm" or "wav"
        }
        headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
        try:
            response = requests.post(self.api_url, headers=headers, json=payload)
            if response.status_code != 200:
                raise RuntimeError(f"Error from TTS API: {response.status_code} {response.text}")
            # Write response as binary into file.
            with open(filepath, "wb") as f:
                f.write(response.content)
        except Exception as e:
            raise RuntimeError(f"Failed to generate audio with OpenAI TTS API: {str(e)}")


================================================
FILE: TTS/pyttsx.py
================================================
import random

import pyttsx3

from utils import settings


class pyttsx:
    def __init__(self):
        self.max_chars = 5000
        self.voices = []

    def run(
        self,
        text: str,
        filepath: str,
        random_voice=False,
    ):
        voice_id = settings.config["settings"]["tts"]["python_voice"]
        voice_num = settings.config["settings"]["tts"]["py_voice_num"]
        if voice_id == "" or voice_num == "":
            voice_id = 2
            voice_num = 3
            raise ValueError("set pyttsx values to a valid value, switching to defaults")
        else:
            voice_id = int(voice_id)
            voice_num = int(voice_num)
        for i in range(voice_num):
            self.voices.append(i)
            i = +1
        if random_voice:
            voice_id = self.randomvoice()
        engine = pyttsx3.init()
        voices = engine.getProperty("voices")
        engine.setProperty(
            "voice", voices[voice_id].id
        )  # changing index changes voices but ony 0 and 1 are working here
        engine.save_to_file(text, f"{filepath}")
        engine.runAndWait()

    def randomvoice(self):
        return random.choice(self.voices)


================================================
FILE: TTS/streamlabs_polly.py
================================================
import random

import requests
from requests.exceptions import JSONDecodeError

from utils import settings
from utils.voice import check_ratelimit

voices = [
    "Brian",
    "Emma",
    "Russell",
    "Joey",
    "Matthew",
    "Joanna",
    "Kimberly",
    "Amy",
    "Geraint",
    "Nicole",
    "Justin",
    "Ivy",
    "Kendra",
    "Salli",
    "Raveena",
]


# valid voices https://lazypy.ro/tts/


class StreamlabsPolly:
    def __init__(self):
        self.url = "https://streamlabs.com/polly/speak"
        self.max_chars = 550
        self.voices = voices

    def run(self, text, filepath, random_voice: bool = False):
        if random_voice:
            voice = self.randomvoice()
        else:
            if not settings.config["settings"]["tts"]["streamlabs_polly_voice"]:
                raise ValueError(
                    f"Please set the config variable STREAMLABS_POLLY_VOICE to a valid voice. options are: {voices}"
                )
            voice = str(settings.config["settings"]["tts"]["streamlabs_polly_voice"]).capitalize()

        body = {"voice": voice, "text": text, "service": "polly"}
        headers = {"Referer": "https://streamlabs.com/"}
        response = requests.post(self.url, headers=headers, data=body)

        if not check_ratelimit(response):
            self.run(text, filepath, random_voice)

        else:
            try:
                voice_data = requests.get(response.json()["speak_url"])
                with open(filepath, "wb") as f:
                    f.write(voice_data.content)
            except (KeyError, JSONDecodeError):
                try:
                    if response.json()["error"] == "No text specified!":
                        raise ValueError("Please specify a text to convert to speech.")
                except (KeyError, JSONDecodeError):
                    print("Error occurred calling Streamlabs Polly")

    def randomvoice(self):
        return random.choice(self.voices)


================================================
FILE: build.sh
================================================
#!/bin/sh
docker build -t rvmt .


================================================
FILE: fonts/LICENSE.txt
================================================

                                 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: install.sh
================================================
#!/bin/bash 

# If the install fails, then print an error and exit.
function install_fail() {
    echo "Installation failed" 
    exit 1 
} 

# This is the help fuction. It helps users withe the options
function Help(){ 
    echo "Usage: install.sh [option]" 
    echo "Options:" 
    echo "  -h: Show this help message and exit" 
    echo "  -d: Install only dependencies" 
    echo "  -p: Install only python dependencies (including playwright)" 
    echo "  -b: Install just the bot"
    echo "  -l: Install the bot and the python dependencies"
} 

# Options
while getopts ":hydpbl" option; do
    case $option in
        # -h, prints help message
        h)
            Help exit 0;;
        # -y, assumes yes
        y)
            ASSUME_YES=1;;
        # -d install only dependencies
        d)
            DEPS_ONLY=1;;
        # -p install only python dependencies
        p)
            PYTHON_ONLY=1;;
        b)
            JUST_BOT=1;;
        l)
            BOT_AND_PYTHON=1;;
        # if a bad argument is given, then throw an error
        \?)
            echo "Invalid option: -$OPTARG" >&2 Help exit 1;;
        :)
            echo "Option -$OPTARG requires an argument." >&2 Help exit 1;;
    esac
done 

# Install dependencies for MacOS
function install_macos(){
    # Check if homebrew is installed
    if [ ! command -v brew &> /dev/null ]; then
        echo "Installing Homebrew"
        # if it's is not installed, then install it in a NONINTERACTIVE way
        NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)" 
        # Check for what arcitecture, so you can place path.
        if [[ "uname -m" == "x86_64" ]]; then
            echo "export PATH=/usr/local/bin:$PATH" >> ~/.bash_profile && source ~/.bash_profile
        fi
    # If not
    else
        # Print that it's already installed
        echo "Homebrew is already installed"
    fi
    # Install the required packages
    echo "Installing required Packages" 
    if [! command --version python3 &> /dev/null ]; then
	    echo "Installing python3"
	    brew install python@3.10
    else
	    echo "python3 already installed."
    fi
    brew install tcl-tk python-tk
} 

# Function to install for arch (and other forks like manjaro)
function install_arch(){ 
    echo "Installing required packages"
    sudo pacman -S --needed python3 tk git && python3 -m ensurepip unzip || install_fail
} 

# Function to install for debian (and ubuntu)
function install_deb(){ 
    echo "Installing required packages"
    sudo apt install python3 python3-dev python3-tk python3-pip unzip || install_fail
} 

# Function to install for fedora (and other forks)
function install_fedora(){ 
    echo "Installing required packages" 
    sudo dnf install python3 python3-tkinter python3-pip python3-devel unzip || install_fail
} 

# Function to install for centos (and other forks based on it)
function install_centos(){
    echo "Installing required packages"
    sudo yum install -y python3 || install_fail
    sudo yum install -y python3-tkinter epel-release python3-pip unzip|| install_fail
} 

function get_the_bot(){ 
    echo "Downloading the bot" 
    rm -rf RedditVideoMakerBot-master
    curl -sL https://github.com/elebumm/RedditVideoMakerBot/archive/refs/heads/master.zip -o master.zip
    unzip master.zip
    rm -rf master.zip
} 

#install python dependencies
function install_python_dep(){ 
    # tell the user that the script is going to install the python dependencies
    echo "Installing python dependencies" 
    # cd into the directory
    cd RedditVideoMakerBot-master
    # install the dependencies
    pip3 install -r requirements.txt 
    # cd out
    cd ..
} 

# install playwright function
function install_playwright(){
    # tell the user that the script is going to install playwright 
    echo "Installing playwright"
    # cd into the directory where the script is downloaded
    cd RedditVideoMakerBot-master
    # run the install script
    python3 -m playwright install 
    python3 -m playwright install-deps 
    # give a note
    printf "Note, if these gave any errors, playwright may not be officially supported on your OS, check this issues page for support\nhttps://github.com/microsoft/playwright/issues"
    if [ -x "$(command -v pacman)" ]; then
        printf "It seems you are on and Arch based distro.\nTry installing these from the AUR for playwright to run:\nenchant1.6\nicu66\nlibwebp052\n"
    fi
    cd ..
} 

# Install depndencies
function install_deps(){ 
    # if the platform is mac, install macos
    if [ "$(uname)" == "Darwin" ]; then
        install_macos || install_fail
    # if pacman is found
    elif [ -x "$(command -v pacman)" ]; then
        # install for arch
        install_arch || install_fail
    # if apt-get is found
    elif [ -x "$(command -v apt-get)" ]; then
        # install fro debian
        install_deb || install_fail
    # if dnf is found
    elif [ -x "$(command -v dnf)" ]; then
        # install for fedora
        install_fedora || install_fail
    # if yum is found
    elif [ -x "$(command -v yum)" ]; then
        # install for centos
        install_centos || install_fail
    # else
    else
        # print an error message and exit
        printf "Your OS is not supported\n Please install python3, pip3 and git manually\n After that, run the script again with the -pb option to install python and playwright dependencies\n If you want to add support for your OS, please open a pull request on github\n
https://github.com/elebumm/RedditVideoMakerBot"
        exit 1
    fi
}

# Main function
function install_main(){ 
    # Print that are installing
    echo "Installing..." 
    # if -y (assume yes) continue 
    if [[ ASSUME_YES -eq 1 ]]; then
        echo "Assuming yes"
    # else, ask if they want to continue
    else
        echo "Continue? (y/n)" 
        read answer 
        # if the answer is not yes, then exit
        if [ "$answer" != "y" ]; then
            echo "Aborting" 
            exit 1
        fi
    fi 
    # if the -d (only dependencies) options is selected install just the dependencies
    if [[ DEPS_ONLY -eq 1 ]]; then
        echo "Installing only dependencies" 
        install_deps
    elif [[ PYTHON_ONLY -eq 1 ]]; then
    # if the -p (only python dependencies) options is selected install just the python dependencies and playwright
        echo "Installing only python dependencies" 
        install_python_dep 
        install_playwright
    # if the -b (only the bot) options is selected install just the bot
    elif [[ JUST_BOT -eq 1 ]]; then
        echo "Installing only the bot"
        get_the_bot
    # if the -l (bot and python) options is selected install just the bot and python dependencies
    elif [[ BOT_AND_PYTHON -eq 1 ]]; then
        echo "Installing only the bot and python dependencies"
        get_the_bot
        install_python_dep
    # else, install everything
    else
        echo "Installing all" 
        install_deps 
        get_the_bot 
        install_python_dep
        install_playwright
    fi

    DIR="./RedditVideoMakerBot-master"
    if [ -d "$DIR" ]; then
        printf "\nThe bot is installed, want to run it?"
        # if -y (assume yes) continue 
        if [[ ASSUME_YES -eq 1 ]]; then
            echo "Assuming yes"
            # else, ask if they want to continue
        else
            echo "Continue? (y/n)" 
            read answer 
            # if the answer is not yes, then exit
            if [ "$answer" != "y" ]; then
                echo "Aborting" 
                exit 1
            fi
        fi
        cd RedditVideoMakerBot-master
        python3 main.py
    fi
}

# Run the main function
install_main


================================================
FILE: main.py
================================================
#!/usr/bin/env python
import math
import sys
from os import name
from pathlib import Path
from subprocess import Popen
from typing import Dict, NoReturn

from prawcore import ResponseException

from reddit.subreddit import get_subreddit_threads
from utils import settings
from utils.cleanup import cleanup
from utils.console import print_markdown, print_step, print_substep
from utils.ffmpeg_install import ffmpeg_install
from utils.id import extract_id
from utils.version import checkversion
from video_creation.background import (
    chop_background,
    download_background_audio,
    download_background_video,
    get_background_config,
)
from video_creation.final_video import make_final_video
from video_creation.screenshot_downloader import get_screenshots_of_reddit_posts
from video_creation.voices import save_text_to_mp3

__VERSION__ = "3.4.0"

print(
    """
██████╗ ███████╗██████╗ ██████╗ ██╗████████╗    ██╗   ██╗██╗██████╗ ███████╗ ██████╗     ███╗   ███╗ █████╗ ██╗  ██╗███████╗██████╗
██╔══██╗██╔════╝██╔══██╗██╔══██╗██║╚══██╔══╝    ██║   ██║██║██╔══██╗██╔════╝██╔═══██╗    ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝██╔══██╗
██████╔╝█████╗  ██║  ██║██║  ██║██║   ██║       ██║   ██║██║██║  ██║█████╗  ██║   ██║    ██╔████╔██║███████║█████╔╝ █████╗  ██████╔╝
██╔══██╗██╔══╝  ██║  ██║██║  ██║██║   ██║       ╚██╗ ██╔╝██║██║  ██║██╔══╝  ██║   ██║    ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝  ██╔══██╗
██║  ██║███████╗██████╔╝██████╔╝██║   ██║        ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝    ██║ ╚═╝ ██║██║  ██║██║  ██╗███████╗██║  ██║
╚═╝  ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝   ╚═╝         ╚═══╝  ╚═╝╚═════╝ ╚══════╝ ╚═════╝     ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝
"""
)
print_markdown(
    "### Thanks for using this tool! Feel free to contribute to this project on GitHub! If you have any questions, feel free to join my Discord server or submit a GitHub issue. You can find solutions to many common problems in the documentation: https://reddit-video-maker-bot.netlify.app/"
)
checkversion(__VERSION__)

reddit_id: str
reddit_object: Dict[str, str | list]


def main(POST_ID=None) -> None:
    global reddit_id, reddit_object
    reddit_object = get_subreddit_threads(POST_ID)
    reddit_id = extract_id(reddit_object)
    print_substep(f"Thread ID is {reddit_id}", style="bold blue")
    length, number_of_comments = save_text_to_mp3(reddit_object)
    length = math.ceil(length)
    get_screenshots_of_reddit_posts(reddit_object, number_of_comments)
    bg_config = {
        "video": get_background_config("video"),
        "audio": get_background_config("audio"),
    }
    download_background_video(bg_config["video"])
    download_background_audio(bg_config["audio"])
    chop_background(bg_config, length, reddit_object)
    make_final_video(number_of_comments, length, reddit_object, bg_config)


def run_many(times) -> None:
    for x in range(1, times + 1):
        print_step(
            f'on the {x}{("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")[x % 10]} iteration of {times}'
        )
        ma
Download .txt
gitextract_1pn0lxmc/

├── .dockerignore
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug_report.yml
│   │   ├── config.yml
│   │   └── feature_request.yml
│   ├── PULL_REQUEST_TEMPLATE.md
│   ├── dependabot.yml
│   └── workflows/
│       ├── codeql-analysis.yml
│       ├── fmt.yml
│       ├── lint.yml
│       └── stale.yml
├── .gitignore
├── .pylintrc
├── .python-version
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── GUI/
│   ├── backgrounds.html
│   ├── index.html
│   ├── layout.html
│   └── settings.html
├── GUI.py
├── LICENSE
├── README.md
├── TTS/
│   ├── GTTS.py
│   ├── TikTok.py
│   ├── __init__.py
│   ├── aws_polly.py
│   ├── elevenlabs.py
│   ├── engine_wrapper.py
│   ├── openai_tts.py
│   ├── pyttsx.py
│   └── streamlabs_polly.py
├── build.sh
├── fonts/
│   └── LICENSE.txt
├── install.sh
├── main.py
├── ptt.py
├── reddit/
│   └── subreddit.py
├── requirements.txt
├── run.bat
├── run.sh
├── utils/
│   ├── .config.template.toml
│   ├── __init__.py
│   ├── ai_methods.py
│   ├── background_audios.json
│   ├── background_videos.json
│   ├── cleanup.py
│   ├── console.py
│   ├── ffmpeg_install.py
│   ├── fonts.py
│   ├── gui_utils.py
│   ├── id.py
│   ├── imagenarator.py
│   ├── playwright.py
│   ├── posttextparser.py
│   ├── settings.py
│   ├── subreddit.py
│   ├── thumbnail.py
│   ├── version.py
│   ├── videos.py
│   └── voice.py
└── video_creation/
    ├── __init__.py
    ├── background.py
    ├── data/
    │   ├── cookie-dark-mode.json
    │   └── cookie-light-mode.json
    ├── final_video.py
    ├── screenshot_downloader.py
    └── voices.py
Download .txt
SYMBOL INDEX (119 symbols across 31 files)

FILE: GUI.py
  function after_request (line 31) | def after_request(response):
  function index (line 40) | def index():
  function backgrounds (line 45) | def backgrounds():
  function background_add (line 50) | def background_add():
  function background_delete (line 63) | def background_delete():
  function settings (line 71) | def settings():
  function videos_json (line 90) | def videos_json():
  function backgrounds_json (line 96) | def backgrounds_json():
  function results (line 102) | def results(name):
  function voices (line 108) | def voices(name):

FILE: TTS/GTTS.py
  class GTTS (line 8) | class GTTS:
    method __init__ (line 9) | def __init__(self):
    method run (line 13) | def run(self, text, filepath, random_voice: bool = False):
    method randomvoice (line 21) | def randomvoice(self):

FILE: TTS/TikTok.py
  class TikTok (line 79) | class TikTok:
    method __init__ (line 82) | def __init__(self):
    method run (line 96) | def run(self, text: str, filepath: str, random_voice: bool = False):
    method get_voices (line 125) | def get_voices(self, text: str, voice: Optional[str] = None) -> dict:
    method random_voice (line 146) | def random_voice() -> str:
  class TikTokTTSException (line 150) | class TikTokTTSException(Exception):
    method __init__ (line 151) | def __init__(self, code: int, message: str):
    method __str__ (line 155) | def __str__(self) -> str:

FILE: TTS/aws_polly.py
  class AWSPolly (line 28) | class AWSPolly:
    method __init__ (line 29) | def __init__(self):
    method run (line 33) | def run(self, text, filepath, random_voice: bool = False):
    method randomvoice (line 76) | def randomvoice(self):

FILE: TTS/elevenlabs.py
  class elevenlabs (line 9) | class elevenlabs:
    method __init__ (line 10) | def __init__(self):
    method run (line 14) | def run(self, text, filepath, random_voice: bool = False):
    method initialize (line 25) | def initialize(self):
    method randomvoice (line 35) | def randomvoice(self):

FILE: TTS/engine_wrapper.py
  class TTSEngine (line 22) | class TTSEngine:
    method __init__ (line 35) | def __init__(
    method add_periods (line 52) | def add_periods(
    method run (line 69) | def run(self) -> Tuple[int, int]:
    method split_post (line 105) | def split_post(self, text: str, idx):
    method call_tts (line 145) | def call_tts(self, filename: str, text: str):
    method create_silence_mp3 (line 170) | def create_silence_mp3(self):
  function process_text (line 181) | def process_text(text: str, clean: bool = True):

FILE: TTS/openai_tts.py
  class OpenAITTS (line 8) | class OpenAITTS:
    method __init__ (line 19) | def __init__(self):
    method get_available_voices (line 41) | def get_available_voices(self):
    method randomvoice (line 50) | def randomvoice(self):
    method run (line 56) | def run(self, text, filepath, random_voice: bool = False):

FILE: TTS/pyttsx.py
  class pyttsx (line 8) | class pyttsx:
    method __init__ (line 9) | def __init__(self):
    method run (line 13) | def run(
    method randomvoice (line 41) | def randomvoice(self):

FILE: TTS/streamlabs_polly.py
  class StreamlabsPolly (line 31) | class StreamlabsPolly:
    method __init__ (line 32) | def __init__(self):
    method run (line 37) | def run(self, text, filepath, random_voice: bool = False):
    method randomvoice (line 66) | def randomvoice(self):

FILE: main.py
  function main (line 49) | def main(POST_ID=None) -> None:
  function run_many (line 67) | def run_many(times) -> None:
  function shutdown (line 76) | def shutdown() -> NoReturn:

FILE: reddit/subreddit.py
  function get_subreddit_threads (line 16) | def get_subreddit_threads(POST_ID: str):

FILE: utils/ai_methods.py
  function mean_pooling (line 7) | def mean_pooling(model_output, attention_mask):
  function sort_by_similarity (line 16) | def sort_by_similarity(thread_objects, keywords):

FILE: utils/cleanup.py
  function _listdir (line 6) | def _listdir(d):  # listdir with full path
  function cleanup (line 10) | def cleanup(reddit_id) -> int:

FILE: utils/console.py
  function print_markdown (line 13) | def print_markdown(text) -> None:
  function print_step (line 20) | def print_step(text) -> None:
  function print_table (line 27) | def print_table(items) -> None:
  function print_substep (line 33) | def print_substep(text, style="") -> None:
  function handle_input (line 38) | def handle_input(

FILE: utils/ffmpeg_install.py
  function ffmpeg_install_windows (line 8) | def ffmpeg_install_windows():
  function ffmpeg_install_linux (line 69) | def ffmpeg_install_linux():
  function ffmpeg_install_mac (line 87) | def ffmpeg_install_mac():
  function ffmpeg_install (line 104) | def ffmpeg_install():

FILE: utils/fonts.py
  function getsize (line 4) | def getsize(font: ImageFont | FreeTypeFont, text: str):
  function getheight (line 11) | def getheight(font: ImageFont | FreeTypeFont, text: str):

FILE: utils/gui_utils.py
  function get_checks (line 11) | def get_checks():
  function get_config (line 28) | def get_config(obj: dict, done=None):
  function check (line 41) | def check(value, checks):
  function modify_settings (line 94) | def modify_settings(data: dict, config_load, checks: dict):
  function delete_background (line 129) | def delete_background(key):
  function add_background (line 153) | def add_background(youtube_uri, filename, citation, position):

FILE: utils/id.py
  function extract_id (line 7) | def extract_id(reddit_obj: dict, field: Optional[str] = "thread_id"):

FILE: utils/imagenarator.py
  function draw_multiple_line_text (line 13) | def draw_multiple_line_text(
  function imagemaker (line 57) | def imagemaker(theme, reddit_obj: dict, txtclr, padding=5, transparent=F...

FILE: utils/playwright.py
  function clear_cookie_by_name (line 1) | def clear_cookie_by_name(context, cookie_cleared_name):

FILE: utils/posttextparser.py
  function posttextparser (line 13) | def posttextparser(obj, *, tried: bool = False) -> List[str]:

FILE: utils/settings.py
  function crawl (line 14) | def crawl(obj: dict, func=lambda x, y: print(x, y, end="\n"), path=None):
  function check (line 24) | def check(value, checks, name):
  function crawl_and_check (line 96) | def crawl_and_check(obj: dict, path: list, checks: dict = {}, name=""):
  function check_vars (line 105) | def check_vars(path, checks):
  function check_toml (line 110) | def check_toml(template_file, config_file) -> Tuple[bool, Dict]:

FILE: utils/subreddit.py
  function _contains_blocked_words (line 9) | def _contains_blocked_words(text: str) -> bool:
  function get_subreddit_undone (line 19) | def get_subreddit_undone(submissions: list, subreddit, times_checked=0, ...
  function already_done (line 109) | def already_done(done_videos: list, submission) -> bool:

FILE: utils/thumbnail.py
  function create_thumbnail (line 4) | def create_thumbnail(thumbnail, font_family, font_size, font_color, widt...

FILE: utils/version.py
  function checkversion (line 6) | def checkversion(__VERSION__: str):

FILE: utils/videos.py
  function check_done (line 10) | def check_done(
  function save_data (line 36) | def save_data(subreddit: str, filename: str, reddit_title: str, reddit_i...

FILE: utils/voice.py
  function check_ratelimit (line 16) | def check_ratelimit(response: Response) -> bool:
  function sleep_until (line 33) | def sleep_until(time) -> None:
  function sanitize_text (line 68) | def sanitize_text(text: str) -> str:

FILE: video_creation/background.py
  function load_background_options (line 16) | def load_background_options():
  function get_start_and_end_times (line 39) | def get_start_and_end_times(video_length: int, length_of_clip: int) -> T...
  function get_background_config (line 60) | def get_background_config(mode: str):
  function download_background_video (line 76) | def download_background_video(background_config: Tuple[str, str, str, An...
  function download_background_audio (line 99) | def download_background_audio(background_config: Tuple[str, str, str]):
  function chop_background (line 123) | def chop_background(background_config: Dict[str, Tuple], video_length: i...

FILE: video_creation/final_video.py
  class ProgressFfmpeg (line 29) | class ProgressFfmpeg(threading.Thread):
    method __init__ (line 30) | def __init__(self, vid_duration_seconds, progress_update_callback):
    method run (line 37) | def run(self):
    method get_latest_ms_progress (line 45) | def get_latest_ms_progress(self):
    method stop (line 59) | def stop(self):
    method __enter__ (line 62) | def __enter__(self):
    method __exit__ (line 66) | def __exit__(self, *args, **kwargs):
  function name_normalize (line 70) | def name_normalize(name: str) -> str:
  function prepare_background (line 87) | def prepare_background(reddit_id: str, W: int, H: int) -> str:
  function get_text_height (line 112) | def get_text_height(draw, text, font, max_width):
  function create_fancy_thumbnail (line 121) | def create_fancy_thumbnail(image, text, text_color, padding, wrap=35):
  function merge_background_audio (line 179) | def merge_background_audio(audio: ffmpeg, reddit_id: str):
  function make_final_video (line 199) | def make_final_video(

FILE: video_creation/screenshot_downloader.py
  function get_screenshots_of_reddit_posts (line 19) | def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num:...

FILE: video_creation/voices.py
  function save_text_to_mp3 (line 29) | def save_text_to_mp3(reddit_obj) -> Tuple[int, int]:
  function get_case_insensitive_key_value (line 54) | def get_case_insensitive_key_value(input_dict, key):
Condensed preview — 69 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (318K chars).
[
  {
    "path": ".dockerignore",
    "chars": 18,
    "preview": "Dockerfile\nresults"
  },
  {
    "path": ".gitattributes",
    "chars": 18,
    "preview": "* text=auto eol=lf"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "chars": 1838,
    "preview": "name: Bug Report\ntitle: \"[Bug]: \"\nlabels: bug\ndescription: Report broken or incorrect behaviour\nbody:\n  - type: markdown"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 205,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Ask a question\n    about: Join our discord server to ask questions "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "chars": 1131,
    "preview": "name: Feature Request\ndescription: Suggest an idea for this project\nlabels: enhancement\ntitle: \"[Feature]: \"\nbody:\n  - t"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "chars": 801,
    "preview": "# Description\n\n<!-- Please include a summary of the change and which issue is fixed. Please also include relevant contex"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 530,
    "preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "chars": 2731,
    "preview": "\n# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# "
  },
  {
    "path": ".github/workflows/fmt.yml",
    "chars": 1398,
    "preview": "# GitHub Action that uses Black to reformat the Python code in an incoming pull request.\n# If all Python code in the pul"
  },
  {
    "path": ".github/workflows/lint.yml",
    "chars": 315,
    "preview": "name: Lint\n\non: [pull_request]\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n  "
  },
  {
    "path": ".github/workflows/stale.yml",
    "chars": 1439,
    "preview": "name: 'Stale issue handler'\non:\n  workflow_dispatch:\n  schedule:\n    - cron: '0 0 * * *'\n\njobs:\n\n  stale:\n    runs-on: u"
  },
  {
    "path": ".gitignore",
    "chars": 4518,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": ".pylintrc",
    "chars": 20269,
    "preview": "[MAIN]\n\n# Analyse import fallback blocks. This can be used to support both Python 2 and\n# 3 compatible code, which means"
  },
  {
    "path": ".python-version",
    "chars": 5,
    "preview": "3.10\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 5252,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participa"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 9893,
    "preview": "\n# Contributing to Reddit Video Maker Bot 🎥\n\nThanks for taking the time to contribute! ❤️\n\nAll types of contributions ar"
  },
  {
    "path": "Dockerfile",
    "chars": 206,
    "preview": "FROM python:3.10.14-slim\n\nRUN apt update\nRUN apt-get install -y ffmpeg\nRUN apt install python3-pip -y\n\nRUN mkdir /app\nAD"
  },
  {
    "path": "GUI/backgrounds.html",
    "chars": 10946,
    "preview": "{% extends \"layout.html\" %}\n{% block main %}\n\n<!-- Delete Background Modal -->\n<div class=\"modal fade\" id=\"deleteBtnModa"
  },
  {
    "path": "GUI/index.html",
    "chars": 7278,
    "preview": "{% extends \"layout.html\" %}\n{% block main %}\n\n<main>\n    <div class=\"album py-2 bg-light\">\n        <div class=\"container"
  },
  {
    "path": "GUI/layout.html",
    "chars": 5746,
    "preview": "<html lang=\"en\">\n\n<head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale"
  },
  {
    "path": "GUI/settings.html",
    "chars": 30521,
    "preview": "{% extends \"layout.html\" %}\n{% block main %}\n\n<main>\n    <br>\n    <div class=\"container\">\n        <form id=\"settingsForm"
  },
  {
    "path": "GUI.py",
    "chars": 3139,
    "preview": "import webbrowser\r\nfrom pathlib import Path\r\n\r\n# Used \"tomlkit\" instead of \"toml\" because it doesn't change formatting o"
  },
  {
    "path": "LICENSE",
    "chars": 34885,
    "preview": "                 GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\nCopyright (C) 2007 Free Soft"
  },
  {
    "path": "README.md",
    "chars": 5117,
    "preview": "# Reddit Video Maker Bot 🎥\n\nAll done WITHOUT video editing or asset compiling. Just pure ✨programming magic✨.\n\nCreated b"
  },
  {
    "path": "TTS/GTTS.py",
    "chars": 471,
    "preview": "import random\n\nfrom gtts import gTTS\n\nfrom utils import settings\n\n\nclass GTTS:\n    def __init__(self):\n        self.max_"
  },
  {
    "path": "TTS/TikTok.py",
    "chars": 5621,
    "preview": "# documentation for tiktok api: https://github.com/oscie57/tiktok-voice/wiki\nimport base64\nimport random\nimport time\nfro"
  },
  {
    "path": "TTS/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "TTS/aws_polly.py",
    "chars": 2422,
    "preview": "import random\nimport sys\n\nfrom boto3 import Session\nfrom botocore.exceptions import BotoCoreError, ClientError, ProfileN"
  },
  {
    "path": "TTS/elevenlabs.py",
    "chars": 1237,
    "preview": "import random\n\nfrom elevenlabs import save\nfrom elevenlabs.client import ElevenLabs\n\nfrom utils import settings\n\n\nclass "
  },
  {
    "path": "TTS/engine_wrapper.py",
    "chars": 8073,
    "preview": "import os\nimport re\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport numpy as np\nimport translators\nfrom moviep"
  },
  {
    "path": "TTS/openai_tts.py",
    "chars": 3824,
    "preview": "import random\n\nimport requests\n\nfrom utils import settings\n\n\nclass OpenAITTS:\n    \"\"\"\n    A Text-to-Speech engine that u"
  },
  {
    "path": "TTS/pyttsx.py",
    "chars": 1201,
    "preview": "import random\n\nimport pyttsx3\n\nfrom utils import settings\n\n\nclass pyttsx:\n    def __init__(self):\n        self.max_chars"
  },
  {
    "path": "TTS/streamlabs_polly.py",
    "chars": 1969,
    "preview": "import random\n\nimport requests\nfrom requests.exceptions import JSONDecodeError\n\nfrom utils import settings\nfrom utils.vo"
  },
  {
    "path": "build.sh",
    "chars": 33,
    "preview": "#!/bin/sh\ndocker build -t rvmt .\n"
  },
  {
    "path": "fonts/LICENSE.txt",
    "chars": 11560,
    "preview": "\r\n                                 Apache License\r\n                           Version 2.0, January 2004\r\n               "
  },
  {
    "path": "install.sh",
    "chars": 7740,
    "preview": "#!/bin/bash \n\n# If the install fails, then print an error and exit.\nfunction install_fail() {\n    echo \"Installation fai"
  },
  {
    "path": "main.py",
    "chars": 5675,
    "preview": "#!/usr/bin/env python\nimport math\nimport sys\nfrom os import name\nfrom pathlib import Path\nfrom subprocess import Popen\nf"
  },
  {
    "path": "ptt.py",
    "chars": 241,
    "preview": "import pyttsx3\n\nengine = pyttsx3.init()\nvoices = engine.getProperty(\"voices\")\nfor voice in voices:\n    print(voice, voic"
  },
  {
    "path": "reddit/subreddit.py",
    "chars": 7017,
    "preview": "import re\n\nimport praw\nfrom praw.models import MoreComments\nfrom prawcore.exceptions import ResponseException\n\nfrom util"
  },
  {
    "path": "requirements.txt",
    "chars": 335,
    "preview": "boto3==1.36.8\nbotocore==1.36.8\ngTTS==2.5.4\nmoviepy==2.2.1\nplaywright==1.49.1\npraw==7.8.1\nrequests==2.32.3\nrich==13.9.4\nt"
  },
  {
    "path": "run.bat",
    "chars": 275,
    "preview": "@echo off\nset VENV_DIR=.venv\n\nif exist \"%VENV_DIR%\" (\n    echo Activating virtual environment...\n    call \"%VENV_DIR%\\Sc"
  },
  {
    "path": "run.sh",
    "chars": 82,
    "preview": "#!/bin/sh\ndocker run -v $(pwd)/out/:/app/assets -v $(pwd)/.env:/app/.env -it rvmt\n"
  },
  {
    "path": "utils/.config.template.toml",
    "chars": 11734,
    "preview": "[reddit.creds]\nclient_id = { optional = false, nmin = 12, nmax = 30, explanation = \"The ID of your Reddit app of SCRIPT "
  },
  {
    "path": "utils/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "utils/ai_methods.py",
    "chars": 2793,
    "preview": "import numpy as np\nimport torch\nfrom transformers import AutoModel, AutoTokenizer\n\n\n# Mean Pooling - Take attention mask"
  },
  {
    "path": "utils/background_audios.json",
    "chars": 479,
    "preview": "{\n    \"__comment\": \"Supported Backgrounds Audio. Can add/remove background audio here...\",\n    \"lofi\": [\n        \"https:"
  },
  {
    "path": "utils/background_videos.json",
    "chars": 1559,
    "preview": "{\n    \"__comment\": \"Supported Backgrounds. Can add/remove background video here...\",\n    \"motor-gta\": [\n        \"https:/"
  },
  {
    "path": "utils/cleanup.py",
    "chars": 422,
    "preview": "import os\nimport shutil\nfrom os.path import exists\n\n\ndef _listdir(d):  # listdir with full path\n    return [os.path.join"
  },
  {
    "path": "utils/console.py",
    "chars": 3999,
    "preview": "import re\n\nfrom rich.columns import Columns\nfrom rich.console import Console\nfrom rich.markdown import Markdown\nfrom ric"
  },
  {
    "path": "utils/ffmpeg_install.py",
    "chars": 5250,
    "preview": "import os\nimport subprocess\nimport zipfile\n\nimport requests\n\n\ndef ffmpeg_install_windows():\n    try:\n        ffmpeg_url "
  },
  {
    "path": "utils/fonts.py",
    "chars": 348,
    "preview": "from PIL.ImageFont import FreeTypeFont, ImageFont\n\n\ndef getsize(font: ImageFont | FreeTypeFont, text: str):\n    left, to"
  },
  {
    "path": "utils/gui_utils.py",
    "chars": 6574,
    "preview": "import json\nimport re\nfrom pathlib import Path\n\nimport toml\nimport tomlkit\nfrom flask import flash\n\n\n# Get validation ch"
  },
  {
    "path": "utils/id.py",
    "chars": 436,
    "preview": "import re\r\nfrom typing import Optional\r\n\r\nfrom utils.console import print_substep\r\n\r\n\r\ndef extract_id(reddit_obj: dict, "
  },
  {
    "path": "utils/imagenarator.py",
    "chars": 2528,
    "preview": "import os\nimport re\nimport textwrap\n\nfrom PIL import Image, ImageDraw, ImageFont\nfrom rich.progress import track\n\nfrom T"
  },
  {
    "path": "utils/playwright.py",
    "chars": 253,
    "preview": "def clear_cookie_by_name(context, cookie_cleared_name):\n    cookies = context.cookies()\n    filtered_cookies = [cookie f"
  },
  {
    "path": "utils/posttextparser.py",
    "chars": 844,
    "preview": "import os\nimport re\nimport time\nfrom typing import List\n\nimport spacy\n\nfrom utils.console import print_step\nfrom utils.v"
  },
  {
    "path": "utils/settings.py",
    "chars": 5546,
    "preview": "import re\nfrom pathlib import Path\nfrom typing import Dict, Tuple\n\nimport toml\nfrom rich.console import Console\n\nfrom ut"
  },
  {
    "path": "utils/subreddit.py",
    "chars": 4848,
    "preview": "import json\nfrom os.path import exists\n\nfrom utils import settings\nfrom utils.ai_methods import sort_by_similarity\nfrom "
  },
  {
    "path": "utils/thumbnail.py",
    "chars": 1421,
    "preview": "from PIL import ImageDraw, ImageFont\n\n\ndef create_thumbnail(thumbnail, font_family, font_size, font_color, width, height"
  },
  {
    "path": "utils/version.py",
    "chars": 848,
    "preview": "import requests\r\n\r\nfrom utils.console import print_step\r\n\r\n\r\ndef checkversion(__VERSION__: str):\r\n    response = request"
  },
  {
    "path": "utils/videos.py",
    "chars": 2162,
    "preview": "import json\nimport time\n\nfrom praw.models import Submission\n\nfrom utils import settings\nfrom utils.console import print_"
  },
  {
    "path": "utils/voice.py",
    "chars": 2886,
    "preview": "import re\nimport sys\nimport time as pytime\nfrom datetime import datetime\nfrom time import sleep\n\nfrom cleantext import c"
  },
  {
    "path": "video_creation/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "video_creation/background.py",
    "chars": 7132,
    "preview": "import json\nimport random\nimport re\nfrom pathlib import Path\nfrom random import randrange\nfrom typing import Any, Dict, "
  },
  {
    "path": "video_creation/data/cookie-dark-mode.json",
    "chars": 511,
    "preview": "[\n  {\n\t\"name\": \"USER\",\n\t\"value\": \"eyJwcmVmcyI6eyJ0b3BDb250ZW50RGlzbWlzc2FsVGltZSI6MCwiZ2xvYmFsVGhlbWUiOiJSRURESVQiLCJuaW"
  },
  {
    "path": "video_creation/data/cookie-light-mode.json",
    "chars": 132,
    "preview": "[\n  {\n\t\"name\": \"eu_cookie\",\n\t\"value\": \"{%22opted%22:true%2C%22nonessential%22:false}\",\n\t\"domain\": \".reddit.com\",\n\t\"path\""
  },
  {
    "path": "video_creation/final_video.py",
    "chars": 19136,
    "preview": "import multiprocessing\nimport os\nimport re\nimport tempfile\nimport textwrap\nimport threading\nimport time\nfrom os.path imp"
  },
  {
    "path": "video_creation/screenshot_downloader.py",
    "chars": 11665,
    "preview": "import json\nimport re\nfrom pathlib import Path\nfrom typing import Dict, Final\n\nimport translators\nfrom playwright.sync_a"
  },
  {
    "path": "video_creation/voices.py",
    "chars": 1827,
    "preview": "from typing import Tuple\n\nfrom rich.console import Console\n\nfrom TTS.aws_polly import AWSPolly\nfrom TTS.elevenlabs impor"
  }
]

About this extraction

This page contains the full source code of the elebumm/RedditVideoMakerBot GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 69 files (294.2 KB), approximately 70.0k tokens, and a symbol index with 119 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!