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 # Issue Fixes 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*(# )??$ # 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

Before Submitting a Bug Report

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).
### 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.

Before Submitting an Enhancement

- 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. - **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.
### 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 #\") 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 %}
{% endblock %} ================================================ FILE: GUI/index.html ================================================ {% extends "layout.html" %} {% block main %}
{% endblock %} ================================================ FILE: GUI/layout.html ================================================ RedditVideoMakerBot
{% if get_flashed_messages() %} {% for category, message in get_flashed_messages(with_categories=true) %} {% if category == "error" %} {% else %} {% endif %} {% endfor %} {% endif %}
{% block main %}{% endblock %} ================================================ FILE: GUI/settings.html ================================================ {% extends "layout.html" %} {% block main %}

Reddit Credentials

Reddit Thread

Max number of characters a comment can have.
The minimum number of comments a post should have to be included.

General Settings

Used if you want to create multiple videos.
Sets the opacity of the comments when overlayed over the background.
Sets the transition time (in seconds) between the comments. Set to 0 if you want to disable it.
See all available backgrounds

TTS Settings

Time in seconds between TTS comments.

{% 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/") def results(name): return send_from_directory("results", name, as_attachment=True) # Make voices samples in voices folder accessible @app.route("/voices/") 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. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ 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) ## 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}' ) main() Popen("cls" if name == "nt" else "clear", shell=True).wait() def shutdown() -> NoReturn: if "reddit_id" in globals(): print_markdown("## Clearing temp files") cleanup(reddit_id) print("Exiting...") sys.exit() if __name__ == "__main__": if sys.version_info.major != 3 or sys.version_info.minor not in [10, 11, 12]: print( "Hey! Congratulations, you've made it so far (which is pretty rare with no Python 3.10). Unfortunately, this program only works on Python 3.10. Please install Python 3.10 and try again." ) sys.exit() ffmpeg_install() directory = Path().absolute() config = settings.check_toml( f"{directory}/utils/.config.template.toml", f"{directory}/config.toml" ) config is False and sys.exit() if ( not settings.config["settings"]["tts"]["tiktok_sessionid"] or settings.config["settings"]["tts"]["tiktok_sessionid"] == "" ) and config["settings"]["tts"]["voice_choice"] == "tiktok": print_substep( "TikTok voice requires a sessionid! Check our documentation on how to obtain one.", "bold red", ) sys.exit() try: if config["reddit"]["thread"]["post_id"]: for index, post_id in enumerate(config["reddit"]["thread"]["post_id"].split("+")): index += 1 print_step( f'on the {index}{("st" if index % 10 == 1 else ("nd" if index % 10 == 2 else ("rd" if index % 10 == 3 else "th")))} post of {len(config["reddit"]["thread"]["post_id"].split("+"))}' ) main(post_id) Popen("cls" if name == "nt" else "clear", shell=True).wait() elif config["settings"]["times_to_run"]: run_many(config["settings"]["times_to_run"]) else: main() except KeyboardInterrupt: shutdown() except ResponseException: print_markdown("## Invalid credentials") print_markdown("Please check your credentials in the config.toml file") shutdown() except Exception as err: config["settings"]["tts"]["tiktok_sessionid"] = "REDACTED" config["settings"]["tts"]["elevenlabs_api_key"] = "REDACTED" config["settings"]["tts"]["openai_api_key"] = "REDACTED" print_step( f"Sorry, something went wrong with this version! Try again, and feel free to report this issue at GitHub or the Discord community.\n" f"Version: {__VERSION__} \n" f"Error: {err} \n" f'Config: {config["settings"]}' ) raise err ================================================ FILE: ptt.py ================================================ import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty("voices") for voice in voices: print(voice, voice.id) engine.setProperty("voice", voice.id) engine.say("Hello World!") engine.runAndWait() engine.stop() ================================================ FILE: reddit/subreddit.py ================================================ import re import praw from praw.models import MoreComments from prawcore.exceptions import ResponseException from utils import settings from utils.ai_methods import sort_by_similarity from utils.console import print_step, print_substep from utils.posttextparser import posttextparser from utils.subreddit import _contains_blocked_words, get_subreddit_undone from utils.videos import check_done from utils.voice import sanitize_text def get_subreddit_threads(POST_ID: str): """ Returns a list of threads from the AskReddit subreddit. """ print_substep("Logging into Reddit.") content = {} if settings.config["reddit"]["creds"]["2fa"]: print("\nEnter your two-factor authentication code from your authenticator app.\n") code = input("> ") print() pw = settings.config["reddit"]["creds"]["password"] passkey = f"{pw}:{code}" else: passkey = settings.config["reddit"]["creds"]["password"] username = settings.config["reddit"]["creds"]["username"] if str(username).casefold().startswith("u/"): username = username[2:] try: reddit = praw.Reddit( client_id=settings.config["reddit"]["creds"]["client_id"], client_secret=settings.config["reddit"]["creds"]["client_secret"], user_agent="Accessing Reddit threads", username=username, passkey=passkey, check_for_async=False, ) except ResponseException as e: if e.response.status_code == 401: print("Invalid credentials - please check them in config.toml") except: print("Something went wrong...") # Ask user for subreddit input print_step("Getting subreddit threads...") similarity_score = 0 if not settings.config["reddit"]["thread"][ "subreddit" ]: # note to user. you can have multiple subreddits via reddit.subreddit("redditdev+learnpython") try: subreddit = reddit.subreddit( re.sub(r"r\/", "", input("What subreddit would you like to pull from? ")) # removes the r/ from the input ) except ValueError: subreddit = reddit.subreddit("askreddit") print_substep("Subreddit not defined. Using AskReddit.") else: sub = settings.config["reddit"]["thread"]["subreddit"] print_substep(f"Using subreddit: r/{sub} from TOML config") subreddit_choice = sub if str(subreddit_choice).casefold().startswith("r/"): # removes the r/ from the input subreddit_choice = subreddit_choice[2:] subreddit = reddit.subreddit(subreddit_choice) if POST_ID: # would only be called if there are multiple queued posts submission = reddit.submission(id=POST_ID) elif ( settings.config["reddit"]["thread"]["post_id"] and len(str(settings.config["reddit"]["thread"]["post_id"]).split("+")) == 1 ): submission = reddit.submission(id=settings.config["reddit"]["thread"]["post_id"]) elif settings.config["ai"]["ai_similarity_enabled"]: # ai sorting based on comparison threads = subreddit.hot(limit=50) keywords = settings.config["ai"]["ai_similarity_keywords"].split(",") keywords = [keyword.strip() for keyword in keywords] # Reformat the keywords for printing keywords_print = ", ".join(keywords) print(f"Sorting threads by similarity to the given keywords: {keywords_print}") threads, similarity_scores = sort_by_similarity(threads, keywords) submission, similarity_score = get_subreddit_undone( threads, subreddit, similarity_scores=similarity_scores ) else: threads = subreddit.hot(limit=25) submission = get_subreddit_undone(threads, subreddit) if submission is None: return get_subreddit_threads(POST_ID) # submission already done. rerun elif not submission.num_comments and settings.config["settings"]["storymode"] == "false": print_substep("No comments found. Skipping.") exit() submission = check_done(submission) # double-checking upvotes = submission.score ratio = submission.upvote_ratio * 100 num_comments = submission.num_comments threadurl = f"https://new.reddit.com/{submission.permalink}" print_substep(f"Video will be: {submission.title} :thumbsup:", style="bold green") print_substep(f"Thread url is: {threadurl} :thumbsup:", style="bold green") print_substep(f"Thread has {upvotes} upvotes", style="bold blue") print_substep(f"Thread has a upvote ratio of {ratio}%", style="bold blue") print_substep(f"Thread has {num_comments} comments", style="bold blue") if similarity_score: print_substep( f"Thread has a similarity score up to {round(similarity_score * 100)}%", style="bold blue", ) content["thread_url"] = threadurl content["thread_title"] = submission.title content["thread_id"] = submission.id content["is_nsfw"] = submission.over_18 content["comments"] = [] if settings.config["settings"]["storymode"]: if settings.config["settings"]["storymodemethod"] == 1: content["thread_post"] = posttextparser(submission.selftext) else: content["thread_post"] = submission.selftext else: for top_level_comment in submission.comments: if isinstance(top_level_comment, MoreComments): continue if top_level_comment.body in ["[removed]", "[deleted]"]: continue # # see https://github.com/JasonLovesDoggo/RedditVideoMakerBot/issues/78 if _contains_blocked_words(top_level_comment.body): continue if not top_level_comment.stickied: sanitised = sanitize_text(top_level_comment.body) if not sanitised or sanitised == " ": continue if len(top_level_comment.body) <= int( settings.config["reddit"]["thread"]["max_comment_length"] ): if len(top_level_comment.body) >= int( settings.config["reddit"]["thread"]["min_comment_length"] ): if ( top_level_comment.author is not None and sanitize_text(top_level_comment.body) is not None ): # if errors occur with this change to if not. content["comments"].append( { "comment_body": top_level_comment.body, "comment_url": top_level_comment.permalink, "comment_id": top_level_comment.id, } ) print_substep("Received subreddit threads Successfully.", style="bold green") return content ================================================ FILE: requirements.txt ================================================ boto3==1.36.8 botocore==1.36.8 gTTS==2.5.4 moviepy==2.2.1 playwright==1.49.1 praw==7.8.1 requests==2.32.3 rich==13.9.4 toml==0.10.2 translators==5.9.9 pyttsx3==2.98 tomlkit==0.13.2 Flask==3.1.1 clean-text==0.6.0 unidecode==1.4.0 spacy==3.8.7 torch==2.7.0 transformers==4.52.4 ffmpeg-python==0.2.0 elevenlabs==1.57.0 yt-dlp==2025.10.22 ================================================ FILE: run.bat ================================================ @echo off set VENV_DIR=.venv if exist "%VENV_DIR%" ( echo Activating virtual environment... call "%VENV_DIR%\Scripts\activate.bat" ) echo Running Python script... python main.py if errorlevel 1 ( echo An error occurred. Press any key to exit. pause >nul ) ================================================ FILE: run.sh ================================================ #!/bin/sh docker run -v $(pwd)/out/:/app/assets -v $(pwd)/.env:/app/.env -it rvmt ================================================ FILE: utils/.config.template.toml ================================================ [reddit.creds] client_id = { optional = false, nmin = 12, nmax = 30, explanation = "The ID of your Reddit app of SCRIPT type", example = "fFAGRNJru1FTz70BzhT3Zg", regex = "^[-a-zA-Z0-9._~+/]+=*$", input_error = "The client ID can only contain printable characters.", oob_error = "The ID should be over 12 and under 30 characters, double check your input." } client_secret = { optional = false, nmin = 20, nmax = 40, explanation = "The SECRET of your Reddit app of SCRIPT type", example = "fFAGRNJru1FTz70BzhT3Zg", regex = "^[-a-zA-Z0-9._~+/]+=*$", input_error = "The client ID can only contain printable characters.", oob_error = "The secret should be over 20 and under 40 characters, double check your input." } username = { optional = false, nmin = 3, nmax = 20, explanation = "The username of your reddit account", example = "JasonLovesDoggo", regex = "^[-_0-9a-zA-Z]+$", oob_error = "A username HAS to be between 3 and 20 characters" } password = { optional = false, nmin = 8, explanation = "The password of your reddit account", example = "fFAGRNJru1FTz70BzhT3Zg", oob_error = "Password too short" } 2fa = { optional = true, type = "bool", options = [true, false, ], default = false, explanation = "Whether you have Reddit 2FA enabled, Valid options are True and False", example = true } [reddit.thread] random = { optional = true, options = [true, false, ], default = false, type = "bool", explanation = "If set to no, it will ask you a thread link to extract the thread, if yes it will randomize it. Default: 'False'", example = "True" } subreddit = { optional = false, regex = "[_0-9a-zA-Z\\+]+$", nmin = 3, explanation = "What subreddit to pull posts from, the name of the sub, not the URL. You can have multiple subreddits, add an + with no spaces.", example = "AskReddit+Redditdev", oob_error = "A subreddit name HAS to be between 3 and 20 characters" } post_id = { optional = true, default = "", regex = "^((?!://|://)[+a-zA-Z0-9])*$", explanation = "Used if you want to use a specific post.", example = "urdtfx" } max_comment_length = { default = 500, optional = false, nmin = 10, nmax = 10000, type = "int", explanation = "max number of characters a comment can have. default is 500", example = 500, oob_error = "the max comment length should be between 10 and 10000" } min_comment_length = { default = 1, optional = true, nmin = 0, nmax = 10000, type = "int", explanation = "min_comment_length number of characters a comment can have. default is 0", example = 50, oob_error = "the max comment length should be between 1 and 100" } post_lang = { default = "", optional = true, explanation = "The language you would like to translate to.", example = "es-cr", options = ['','af', 'ak', 'am', 'ar', 'as', 'ay', 'az', 'be', 'bg', 'bho', 'bm', 'bn', 'bs', 'ca', 'ceb', 'ckb', 'co', 'cs', 'cy', 'da', 'de', 'doi', 'dv', 'ee', 'el', 'en', 'en-US', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gom', 'gu', 'ha', 'haw', 'hi', 'hmn', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'iw', 'ja', 'jw', 'ka', 'kk', 'km', 'kn', 'ko', 'kri', 'ku', 'ky', 'la', 'lb', 'lg', 'ln', 'lo', 'lt', 'lus', 'lv', 'mai', 'mg', 'mi', 'mk', 'ml', 'mn', 'mni-Mtei', 'mr', 'ms', 'mt', 'my', 'ne', 'nl', 'no', 'nso', 'ny', 'om', 'or', 'pa', 'pl', 'ps', 'pt', 'qu', 'ro', 'ru', 'rw', 'sa', 'sd', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'st', 'su', 'sv', 'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tr', 'ts', 'tt', 'ug', 'uk', 'ur', 'uz', 'vi', 'xh', 'yi', 'yo', 'zh-CN', 'zh-TW', 'zu'] } min_comments = { default = 20, optional = false, nmin = 10, type = "int", explanation = "The minimum number of comments a post should have to be included. default is 20", example = 29, oob_error = "the minimum number of comments should be between 15 and 999999" } blocked_words = { optional = true, default = "", type = "str", explanation = "Comma-separated list of words/phrases. Posts and comments containing any of these will be skipped.", example = "nsfw, spoiler, politics" } [ai] ai_similarity_enabled = {optional = true, option = [true, false], default = false, type = "bool", explanation = "Threads read from Reddit are sorted based on their similarity to the keywords given below"} ai_similarity_keywords = {optional = true, type="str", example= 'Elon Musk, Twitter, Stocks', explanation = "Every keyword or even sentence, seperated with comma, is used to sort the reddit threads based on similarity"} [settings] allow_nsfw = { optional = false, type = "bool", default = false, example = false, options = [true, false, ], explanation = "Whether to allow NSFW content, True or False" } theme = { optional = false, default = "dark", example = "light", options = ["dark", "light", "transparent", ], explanation = "Sets the Reddit theme, either LIGHT or DARK. For story mode you can also use a transparent background." } times_to_run = { optional = false, default = 1, example = 2, explanation = "Used if you want to run multiple times. Set to an int e.g. 4 or 29 or 1", type = "int", nmin = 1, oob_error = "It's very hard to run something less than once." } opacity = { optional = false, default = 0.9, example = 0.8, explanation = "Sets the opacity of the comments when overlayed over the background", type = "float", nmin = 0, nmax = 1, oob_error = "The opacity HAS to be between 0 and 1", input_error = "The opacity HAS to be a decimal number between 0 and 1" } #transition = { optional = true, default = 0.2, example = 0.2, explanation = "Sets the transition time (in seconds) between the comments. Set to 0 if you want to disable it.", type = "float", nmin = 0, nmax = 2, oob_error = "The transition HAS to be between 0 and 2", input_error = "The opacity HAS to be a decimal number between 0 and 2" } storymode = { optional = true, type = "bool", default = false, example = false, options = [true, false,], explanation = "Only read out title and post content, great for subreddits with stories" } storymodemethod= { optional = true, default = 1, example = 1, explanation = "Style that's used for the storymode. Set to 0 for single picture display in whole video, set to 1 for fancy looking video ", type = "int", nmin = 0, oob_error = "It's very hard to run something less than once.", options = [0, 1] } storymode_max_length = { optional = true, default = 1000, example = 1000, explanation = "Max length of the storymode video in characters. 200 characters are approximately 50 seconds.", type = "int", nmin = 1, oob_error = "It's very hard to make a video under a second." } resolution_w = { optional = false, default = 1080, example = 1440, explantation = "Sets the width in pixels of the final video" } resolution_h = { optional = false, default = 1920, example = 2560, explantation = "Sets the height in pixels of the final video" } zoom = { optional = true, default = 1, example = 1.1, explanation = "Sets the browser zoom level. Useful if you want the text larger.", type = "float", nmin = 0.1, nmax = 2, oob_error = "The text is really difficult to read at a zoom level higher than 2" } channel_name = { optional = true, default = "Reddit Tales", example = "Reddit Stories", explanation = "Sets the channel name for the video" } [settings.background] background_video = { optional = true, default = "minecraft", example = "rocket-league", options = ["minecraft", "gta", "rocket-league", "motor-gta", "csgo-surf", "cluster-truck", "minecraft-2","multiversus","fall-guys","steep", ""], explanation = "Sets the background for the video based on game name" } background_audio = { optional = true, default = "lofi", example = "chill-summer", options = ["lofi","lofi-2","chill-summer",""], explanation = "Sets the background audio for the video" } background_audio_volume = { optional = true, type = "float", nmin = 0, nmax = 1, default = 0.15, example = 0.05, explanation="Sets the volume of the background audio. If you don't want background audio, set it to 0.", oob_error = "The volume HAS to be between 0 and 1", input_error = "The volume HAS to be a float number between 0 and 1"} enable_extra_audio = { optional = true, type = "bool", default = false, example = false, explanation="Used if you want to render another video without background audio in a separate folder", input_error = "The value HAS to be true or false"} background_thumbnail = { optional = true, type = "bool", default = false, example = false, options = [true, false,], explanation = "Generate a thumbnail for the video (put a thumbnail.png file in the assets/backgrounds directory.)" } background_thumbnail_font_family = { optional = true, default = "arial", example = "arial", explanation = "Font family for the thumbnail text" } background_thumbnail_font_size = { optional = true, type = "int", default = 96, example = 96, explanation = "Font size in pixels for the thumbnail text" } background_thumbnail_font_color = { optional = true, default = "255,255,255", example = "255,255,255", explanation = "Font color in RGB format for the thumbnail text" } [settings.tts] voice_choice = { optional = false, default = "tiktok", options = ["elevenlabs", "streamlabspolly", "tiktok", "googletranslate", "awspolly", "pyttsx", "OpenAI"], example = "tiktok", explanation = "The voice platform used for TTS generation. " } random_voice = { optional = false, type = "bool", default = true, example = true, options = [true, false,], explanation = "Randomizes the voice used for each comment" } elevenlabs_voice_name = { optional = false, default = "Bella", example = "Bella", explanation = "The voice used for elevenlabs", options = ["Adam", "Antoni", "Arnold", "Bella", "Domi", "Elli", "Josh", "Rachel", "Sam", ] } elevenlabs_api_key = { optional = true, example = "21f13f91f54d741e2ae27d2ab1b99d59", explanation = "Elevenlabs API key" } aws_polly_voice = { optional = false, default = "Matthew", example = "Matthew", explanation = "The voice used for AWS Polly" } streamlabs_polly_voice = { optional = false, default = "Matthew", example = "Matthew", explanation = "The voice used for Streamlabs Polly" } tiktok_voice = { optional = true, default = "en_us_001", example = "en_us_006", explanation = "The voice used for TikTok TTS" } tiktok_sessionid = { optional = true, example = "c76bcc3a7625abcc27b508c7db457ff1", explanation = "TikTok sessionid needed if you're using the TikTok TTS. Check documentation if you don't know how to obtain it." } python_voice = { optional = false, default = "1", example = "1", explanation = "The index of the system tts voices (can be downloaded externally, run ptt.py to find value, start from zero)" } py_voice_num = { optional = false, default = "2", example = "2", explanation = "The number of system voices (2 are pre-installed in Windows)" } silence_duration = { optional = true, example = "0.1", explanation = "Time in seconds between TTS comments", default = 0.3, type = "float" } no_emojis = { optional = false, type = "bool", default = false, example = false, options = [true, false,], explanation = "Whether to remove emojis from the comments" } openai_api_url = { optional = true, default = "https://api.openai.com/v1/", example = "https://api.openai.com/v1/", explanation = "The API endpoint URL for OpenAI TTS generation" } openai_api_key = { optional = true, example = "sk-abc123def456...", explanation = "Your OpenAI API key for TTS generation" } openai_voice_name = { optional = false, default = "alloy", example = "alloy", explanation = "The voice used for OpenAI TTS generation", options = ["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "af_heart"] } openai_model = { optional = false, default = "tts-1", example = "tts-1", explanation = "The model variant used for OpenAI TTS generation", options = ["tts-1", "tts-1-hd", "gpt-4o-mini-tts"] } ================================================ FILE: utils/__init__.py ================================================ ================================================ FILE: utils/ai_methods.py ================================================ import numpy as np import torch from transformers import AutoModel, AutoTokenizer # Mean Pooling - Take attention mask into account for correct averaging def mean_pooling(model_output, attention_mask): token_embeddings = model_output[0] # First element of model_output contains all token embeddings input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp( input_mask_expanded.sum(1), min=1e-9 ) # This function sorts the given threads based on their total similarity with the given keywords def sort_by_similarity(thread_objects, keywords): # Initialize tokenizer + model. tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") # Transform the generator to a list of Submission Objects, so we can sort later based on context similarity to # keywords thread_objects = list(thread_objects) threads_sentences = [] for i, thread in enumerate(thread_objects): threads_sentences.append(" ".join([thread.title, thread.selftext])) # Threads inference encoded_threads = tokenizer( threads_sentences, padding=True, truncation=True, return_tensors="pt" ) with torch.no_grad(): threads_embeddings = model(**encoded_threads) threads_embeddings = mean_pooling(threads_embeddings, encoded_threads["attention_mask"]) # Keyword inference encoded_keywords = tokenizer(keywords, padding=True, truncation=True, return_tensors="pt") with torch.no_grad(): keywords_embeddings = model(**encoded_keywords) keywords_embeddings = mean_pooling(keywords_embeddings, encoded_keywords["attention_mask"]) # Compare every keyword w/ every thread embedding threads_embeddings_tensor = torch.tensor(threads_embeddings) total_scores = torch.zeros(threads_embeddings_tensor.shape[0]) cosine_similarity = torch.nn.CosineSimilarity() for keyword_embedding in keywords_embeddings: keyword_embedding = torch.tensor(keyword_embedding).repeat( threads_embeddings_tensor.shape[0], 1 ) similarity = cosine_similarity(keyword_embedding, threads_embeddings_tensor) total_scores += similarity similarity_scores, indices = torch.sort(total_scores, descending=True) # threads_sentences = np.array(threads_sentences)[indices.numpy()] thread_objects = np.array(thread_objects)[indices.numpy()].tolist() # print('Similarity Thread Ranking') # for i, thread in enumerate(thread_objects): # print(f'{i}) {threads_sentences[i]} score {similarity_scores[i]}') return thread_objects, similarity_scores ================================================ FILE: utils/background_audios.json ================================================ { "__comment": "Supported Backgrounds Audio. Can add/remove background audio here...", "lofi": [ "https://www.youtube.com/watch?v=LTphVIore3A", "lofi.mp3", "Super Lofi World" ], "lofi-2":[ "https://www.youtube.com/watch?v=BEXL80LS0-I", "lofi-2.mp3", "stompsPlaylist" ], "chill-summer":[ "https://www.youtube.com/watch?v=EZE8JagnBI8", "chill-summer.mp3", "Mellow Vibes Radio" ] } ================================================ FILE: utils/background_videos.json ================================================ { "__comment": "Supported Backgrounds. Can add/remove background video here...", "motor-gta": [ "https://www.youtube.com/watch?v=vw5L4xCPy9Q", "bike-parkour-gta.mp4", "Achy Gaming", "center" ], "rocket-league": [ "https://www.youtube.com/watch?v=2X9QGY__0II", "rocket_league.mp4", "Orbital Gameplay", "center" ], "minecraft": [ "https://www.youtube.com/watch?v=n_Dv4JMiwK8", "parkour.mp4", "bbswitzer", "center" ], "gta": [ "https://www.youtube.com/watch?v=qGa9kWREOnE", "gta-stunt-race.mp4", "Achy Gaming", "center" ], "csgo-surf": [ "https://www.youtube.com/watch?v=E-8JlyO59Io", "csgo-surf.mp4", "Aki", "center" ], "cluster-truck": [ "https://www.youtube.com/watch?v=uVKxtdMgJVU", "cluster_truck.mp4", "No Copyright Gameplay", "center" ], "minecraft-2": [ "https://www.youtube.com/watch?v=Pt5_GSKIWQM", "minecraft-2.mp4", "Itslpsn", "center" ], "multiversus": [ "https://www.youtube.com/watch?v=66oK1Mktz6g", "multiversus.mp4", "MKIceAndFire", "center" ], "fall-guys": [ "https://www.youtube.com/watch?v=oGSsgACIc6Q", "fall-guys.mp4", "Throneful", "center" ], "steep": [ "https://www.youtube.com/watch?v=EnGiQrWBrko", "steep.mp4", "joel", "center" ] } ================================================ FILE: utils/cleanup.py ================================================ import os import shutil from os.path import exists def _listdir(d): # listdir with full path return [os.path.join(d, f) for f in os.listdir(d)] def cleanup(reddit_id) -> int: """Deletes all temporary assets in assets/temp Returns: int: How many files were deleted """ directory = f"../assets/temp/{reddit_id}/" if exists(directory): shutil.rmtree(directory) return 1 ================================================ FILE: utils/console.py ================================================ import re from rich.columns import Columns from rich.console import Console from rich.markdown import Markdown from rich.padding import Padding from rich.panel import Panel from rich.text import Text console = Console() def print_markdown(text) -> None: """Prints a rich info message. Support Markdown syntax.""" md = Padding(Markdown(text), 2) console.print(md) def print_step(text) -> None: """Prints a rich info message.""" panel = Panel(Text(text, justify="left")) console.print(panel) def print_table(items) -> None: """Prints items in a table.""" console.print(Columns([Panel(f"[yellow]{item}", expand=True) for item in items])) def print_substep(text, style="") -> None: """Prints a rich colored info message without the panelling.""" console.print(text, style=style) def handle_input( message: str = "", check_type=False, match: str = "", err_message: str = "", nmin=None, nmax=None, oob_error="", extra_info="", options: list = None, default=NotImplemented, optional=False, ): if optional: console.print(message + "\n[green]This is an optional value. Do you want to skip it? (y/n)") if input().casefold().startswith("y"): return default if default is not NotImplemented else "" if default is not NotImplemented: console.print( "[green]" + message + '\n[blue bold]The default value is "' + str(default) + '"\nDo you want to use it?(y/n)' ) if input().casefold().startswith("y"): return default if options is None: match = re.compile(match) console.print("[green bold]" + extra_info, no_wrap=True) while True: console.print(message, end="") user_input = input("").strip() if check_type is not False: try: user_input = check_type(user_input) if (nmin is not None and user_input < nmin) or ( nmax is not None and user_input > nmax ): # FAILSTATE Input out of bounds console.print("[red]" + oob_error) continue break # Successful type conversion and number in bounds except ValueError: # Type conversion failed console.print("[red]" + err_message) continue elif match != "" and re.match(match, user_input) is None: console.print("[red]" + err_message + "\nAre you absolutely sure it's correct?(y/n)") if input().casefold().startswith("y"): break continue else: # FAILSTATE Input STRING out of bounds if (nmin is not None and len(user_input) < nmin) or ( nmax is not None and len(user_input) > nmax ): console.print("[red bold]" + oob_error) continue break # SUCCESS Input STRING in bounds return user_input console.print(extra_info, no_wrap=True) while True: console.print(message, end="") user_input = input("").strip() if check_type is not False: try: isinstance(eval(user_input), check_type) # fixme: remove eval return check_type(user_input) except: console.print( "[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + "." ) continue if user_input in options: return user_input console.print( "[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + "." ) ================================================ FILE: utils/ffmpeg_install.py ================================================ import os import subprocess import zipfile import requests def ffmpeg_install_windows(): try: ffmpeg_url = ( "https://github.com/GyanD/codexffmpeg/releases/download/6.0/ffmpeg-6.0-full_build.zip" ) ffmpeg_zip_filename = "ffmpeg.zip" ffmpeg_extracted_folder = "ffmpeg" # Check if ffmpeg.zip already exists if os.path.exists(ffmpeg_zip_filename): os.remove(ffmpeg_zip_filename) # Download FFmpeg r = requests.get(ffmpeg_url) with open(ffmpeg_zip_filename, "wb") as f: f.write(r.content) # Check if the extracted folder already exists if os.path.exists(ffmpeg_extracted_folder): # Remove existing extracted folder and its contents for root, dirs, files in os.walk(ffmpeg_extracted_folder, topdown=False): for file in files: os.remove(os.path.join(root, file)) for directory in dirs: os.rmdir(os.path.join(root, directory)) os.rmdir(ffmpeg_extracted_folder) # Extract FFmpeg with zipfile.ZipFile(ffmpeg_zip_filename, "r") as zip_ref: zip_ref.extractall() os.remove("ffmpeg.zip") # Rename and move files os.rename(f"{ffmpeg_extracted_folder}-6.0-full_build", ffmpeg_extracted_folder) for file in os.listdir(os.path.join(ffmpeg_extracted_folder, "bin")): os.rename( os.path.join(ffmpeg_extracted_folder, "bin", file), os.path.join(".", file), ) os.rmdir(os.path.join(ffmpeg_extracted_folder, "bin")) for file in os.listdir(os.path.join(ffmpeg_extracted_folder, "doc")): os.remove(os.path.join(ffmpeg_extracted_folder, "doc", file)) for file in os.listdir(os.path.join(ffmpeg_extracted_folder, "presets")): os.remove(os.path.join(ffmpeg_extracted_folder, "presets", file)) os.rmdir(os.path.join(ffmpeg_extracted_folder, "presets")) os.rmdir(os.path.join(ffmpeg_extracted_folder, "doc")) os.remove(os.path.join(ffmpeg_extracted_folder, "LICENSE")) os.remove(os.path.join(ffmpeg_extracted_folder, "README.txt")) os.rmdir(ffmpeg_extracted_folder) print( "FFmpeg installed successfully! Please restart your computer and then re-run the program." ) except Exception as e: print( "An error occurred while trying to install FFmpeg. Please try again. Otherwise, please install FFmpeg manually and try again." ) print(e) exit() def ffmpeg_install_linux(): try: subprocess.run( "sudo apt install ffmpeg", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except Exception as e: print( "An error occurred while trying to install FFmpeg. Please try again. Otherwise, please install FFmpeg manually and try again." ) print(e) exit() print("FFmpeg installed successfully! Please re-run the program.") exit() def ffmpeg_install_mac(): try: subprocess.run( "brew install ffmpeg", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except FileNotFoundError: print( "Homebrew is not installed. Please install it and try again. Otherwise, please install FFmpeg manually and try again." ) exit() print("FFmpeg installed successfully! Please re-run the program.") exit() def ffmpeg_install(): try: # Try to run the FFmpeg command subprocess.run( ["ffmpeg", "-version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) except FileNotFoundError: # Check if there's ffmpeg.exe in the current directory if os.path.exists("./ffmpeg.exe"): print( "FFmpeg is installed on this system! If you are seeing this error for the second time, restart your computer." ) print("FFmpeg is not installed on this system.") resp = input( "We can try to automatically install it for you. Would you like to do that? (y/n): " ) if resp.lower() == "y": print("Installing FFmpeg...") if os.name == "nt": ffmpeg_install_windows() elif os.name == "posix": ffmpeg_install_linux() elif os.name == "mac": ffmpeg_install_mac() else: print("Your OS is not supported. Please install FFmpeg manually and try again.") exit() else: print("Please install FFmpeg manually and try again.") exit() except Exception as e: print( "Welcome fellow traveler! You're one of the few who have made it this far. We have no idea how you got at this error, but we're glad you're here. Please report this error to the developer, and we'll try to fix it as soon as possible. Thank you for your patience!" ) print(e) return None ================================================ FILE: utils/fonts.py ================================================ from PIL.ImageFont import FreeTypeFont, ImageFont def getsize(font: ImageFont | FreeTypeFont, text: str): left, top, right, bottom = font.getbbox(text) width = right - left height = bottom - top return width, height def getheight(font: ImageFont | FreeTypeFont, text: str): _, height = getsize(font, text) return height ================================================ FILE: utils/gui_utils.py ================================================ import json import re from pathlib import Path import toml import tomlkit from flask import flash # Get validation checks from template def get_checks(): template = toml.load("utils/.config.template.toml") checks = {} def unpack_checks(obj: dict): for key in obj.keys(): if "optional" in obj[key].keys(): checks[key] = obj[key] else: unpack_checks(obj[key]) unpack_checks(template) return checks # Get current config (from config.toml) as dict def get_config(obj: dict, done=None): if done is None: done = {} for key in obj.keys(): if not isinstance(obj[key], dict): done[key] = obj[key] else: get_config(obj[key], done) return done # Checks if value is valid def check(value, checks): incorrect = False if value == "False": value = "" if not incorrect and "type" in checks: try: value = eval(checks["type"])(value) # fixme remove eval except Exception: incorrect = True if ( not incorrect and "options" in checks and value not in checks["options"] ): # FAILSTATE Value isn't one of the options incorrect = True if ( not incorrect and "regex" in checks and ( (isinstance(value, str) and re.match(checks["regex"], value) is None) or not isinstance(value, str) ) ): # FAILSTATE Value doesn't match regular expression, or has regular expression but isn't a string. incorrect = True if ( not incorrect and not hasattr(value, "__iter__") and ( ("nmin" in checks and checks["nmin"] is not None and value < checks["nmin"]) or ("nmax" in checks and checks["nmax"] is not None and value > checks["nmax"]) ) ): incorrect = True if ( not incorrect and hasattr(value, "__iter__") and ( ("nmin" in checks and checks["nmin"] is not None and len(value) < checks["nmin"]) or ("nmax" in checks and checks["nmax"] is not None and len(value) > checks["nmax"]) ) ): incorrect = True if incorrect: return "Error" return value # Modify settings (after the form is submitted) def modify_settings(data: dict, config_load, checks: dict): # Modify config settings def modify_config(obj: dict, config_name: str, value: any): for key in obj.keys(): if config_name == key: obj[key] = value elif not isinstance(obj[key], dict): continue else: modify_config(obj[key], config_name, value) # Remove empty/incorrect key-value pairs data = {key: value for key, value in data.items() if value and key in checks.keys()} # Validate values for name in data.keys(): value = check(data[name], checks[name]) # Value is invalid if value == "Error": flash("Some values were incorrect and didn't save!", "error") else: # Value is valid modify_config(config_load, name, value) # Save changes in config.toml with Path("config.toml").open("w") as toml_file: toml_file.write(tomlkit.dumps(config_load)) flash("Settings saved!") return get_config(config_load) # Delete background video def delete_background(key): # Read backgrounds.json with open("utils/backgrounds.json", "r", encoding="utf-8") as backgrounds: data = json.load(backgrounds) # Remove background from backgrounds.json with open("utils/backgrounds.json", "w", encoding="utf-8") as backgrounds: if data.pop(key, None): json.dump(data, backgrounds, ensure_ascii=False, indent=4) else: flash("Couldn't find this background. Try refreshing the page.", "error") return # Remove background video from ".config.template.toml" config = tomlkit.loads(Path("utils/.config.template.toml").read_text()) config["settings"]["background"]["background_choice"]["options"].remove(key) with Path("utils/.config.template.toml").open("w") as toml_file: toml_file.write(tomlkit.dumps(config)) flash(f'Successfully removed "{key}" background!') # Add background video def add_background(youtube_uri, filename, citation, position): # Validate YouTube URI regex = re.compile(r"(?:\/|%3D|v=|vi=)([0-9A-z\-_]{11})(?:[%#?&]|$)").search(youtube_uri) if not regex: flash("YouTube URI is invalid!", "error") return youtube_uri = f"https://www.youtube.com/watch?v={regex.group(1)}" # Check if the position is valid if position == "" or position == "center": position = "center" elif position.isdecimal(): position = int(position) else: flash('Position is invalid! It can be "center" or decimal number.', "error") return # Sanitize filename regex = re.compile(r"^([a-zA-Z0-9\s_-]{1,100})$").match(filename) if not regex: flash("Filename is invalid!", "error") return filename = filename.replace(" ", "_") # Check if the background doesn't already exist with open("utils/backgrounds.json", "r", encoding="utf-8") as backgrounds: data = json.load(backgrounds) # Check if key isn't already taken if filename in list(data.keys()): flash("Background video with this name already exist!", "error") return # Check if the YouTube URI isn't already used under different name if youtube_uri in [data[i][0] for i in list(data.keys())]: flash("Background video with this YouTube URI is already added!", "error") return # Add background video to json file with open("utils/backgrounds.json", "r+", encoding="utf-8") as backgrounds: data = json.load(backgrounds) data[filename] = [youtube_uri, filename + ".mp4", citation, position] backgrounds.seek(0) json.dump(data, backgrounds, ensure_ascii=False, indent=4) # Add background video to ".config.template.toml" config = tomlkit.loads(Path("utils/.config.template.toml").read_text()) config["settings"]["background"]["background_choice"]["options"].append(filename) with Path("utils/.config.template.toml").open("w") as toml_file: toml_file.write(tomlkit.dumps(config)) flash(f'Added "{citation}-{filename}.mp4" as a new background video!') return ================================================ FILE: utils/id.py ================================================ import re from typing import Optional from utils.console import print_substep def extract_id(reddit_obj: dict, field: Optional[str] = "thread_id"): """ This function takes a reddit object and returns the post id """ if field not in reddit_obj.keys(): raise ValueError(f"Field '{field}' not found in reddit object") reddit_id = re.sub(r"[^\w\s-]", "", reddit_obj[field]) return reddit_id ================================================ FILE: utils/imagenarator.py ================================================ import os import re import textwrap from PIL import Image, ImageDraw, ImageFont from rich.progress import track from TTS.engine_wrapper import process_text from utils.fonts import getheight, getsize from utils.id import extract_id def draw_multiple_line_text( image, text, font, text_color, padding, wrap=50, transparent=False ) -> None: """ Draw multiline text over given image """ draw = ImageDraw.Draw(image) font_height = getheight(font, text) image_width, image_height = image.size lines = textwrap.wrap(text, width=wrap) y = (image_height / 2) - (((font_height + (len(lines) * padding) / len(lines)) * len(lines)) / 2) for line in lines: line_width, line_height = getsize(font, line) if transparent: shadowcolor = "black" for i in range(1, 5): draw.text( ((image_width - line_width) / 2 - i, y - i), line, font=font, fill=shadowcolor, ) draw.text( ((image_width - line_width) / 2 + i, y - i), line, font=font, fill=shadowcolor, ) draw.text( ((image_width - line_width) / 2 - i, y + i), line, font=font, fill=shadowcolor, ) draw.text( ((image_width - line_width) / 2 + i, y + i), line, font=font, fill=shadowcolor, ) draw.text(((image_width - line_width) / 2, y), line, font=font, fill=text_color) y += line_height + padding def imagemaker(theme, reddit_obj: dict, txtclr, padding=5, transparent=False) -> None: """ Render Images for video """ texts = reddit_obj["thread_post"] reddit_id = extract_id(reddit_obj) if transparent: font = ImageFont.truetype(os.path.join("fonts", "Roboto-Bold.ttf"), 100) else: font = ImageFont.truetype(os.path.join("fonts", "Roboto-Regular.ttf"), 100) size = (1920, 1080) for idx, text in track(enumerate(texts), "Rendering Image"): image = Image.new("RGBA", size, theme) text = process_text(text, False) draw_multiple_line_text(image, text, font, txtclr, padding, wrap=30, transparent=transparent) image.save(f"assets/temp/{reddit_id}/png/img{idx}.png") ================================================ FILE: utils/playwright.py ================================================ def clear_cookie_by_name(context, cookie_cleared_name): cookies = context.cookies() filtered_cookies = [cookie for cookie in cookies if cookie["name"] != cookie_cleared_name] context.clear_cookies() context.add_cookies(filtered_cookies) ================================================ FILE: utils/posttextparser.py ================================================ import os import re import time from typing import List import spacy from utils.console import print_step from utils.voice import sanitize_text # working good def posttextparser(obj, *, tried: bool = False) -> List[str]: text: str = re.sub("\n", " ", obj) try: nlp = spacy.load("en_core_web_sm") except OSError as e: if not tried: os.system("python -m spacy download en_core_web_sm") time.sleep(5) return posttextparser(obj, tried=True) print_step( "The spacy model can't load. You need to install it with the command \npython -m spacy download en_core_web_sm " ) raise e doc = nlp(text) newtext: list = [] for line in doc.sents: if sanitize_text(line.text): newtext.append(line.text) return newtext ================================================ FILE: utils/settings.py ================================================ import re from pathlib import Path from typing import Dict, Tuple import toml from rich.console import Console from utils.console import handle_input console = Console() config = dict # autocomplete def crawl(obj: dict, func=lambda x, y: print(x, y, end="\n"), path=None): if path is None: # path Default argument value is mutable path = [] for key in obj.keys(): if type(obj[key]) is dict: crawl(obj[key], func, path + [key]) continue func(path + [key], obj[key]) def check(value, checks, name): def get_check_value(key, default_result): return checks[key] if key in checks else default_result incorrect = False if value == {}: incorrect = True if not incorrect and "type" in checks: try: value = eval(checks["type"])(value) # fixme remove eval except: incorrect = True if ( not incorrect and "options" in checks and value not in checks["options"] ): # FAILSTATE Value is not one of the options incorrect = True if ( not incorrect and "regex" in checks and ( (isinstance(value, str) and re.match(checks["regex"], value) is None) or not isinstance(value, str) ) ): # FAILSTATE Value doesn't match regex, or has regex but is not a string. incorrect = True if ( not incorrect and not hasattr(value, "__iter__") and ( ("nmin" in checks and checks["nmin"] is not None and value < checks["nmin"]) or ("nmax" in checks and checks["nmax"] is not None and value > checks["nmax"]) ) ): incorrect = True if ( not incorrect and hasattr(value, "__iter__") and ( ("nmin" in checks and checks["nmin"] is not None and len(value) < checks["nmin"]) or ("nmax" in checks and checks["nmax"] is not None and len(value) > checks["nmax"]) ) ): incorrect = True if incorrect: value = handle_input( message=( (("[blue]Example: " + str(checks["example"]) + "\n") if "example" in checks else "") + "[red]" + ("Non-optional ", "Optional ")["optional" in checks and checks["optional"] is True] ) + "[#C0CAF5 bold]" + str(name) + "[#F7768E bold]=", extra_info=get_check_value("explanation", ""), check_type=eval(get_check_value("type", "False")), # fixme remove eval default=get_check_value("default", NotImplemented), match=get_check_value("regex", ""), err_message=get_check_value("input_error", "Incorrect input"), nmin=get_check_value("nmin", None), nmax=get_check_value("nmax", None), oob_error=get_check_value( "oob_error", "Input out of bounds(Value too high/low/long/short)" ), options=get_check_value("options", None), optional=get_check_value("optional", False), ) return value def crawl_and_check(obj: dict, path: list, checks: dict = {}, name=""): if len(path) == 0: return check(obj, checks, name) if path[0] not in obj.keys(): obj[path[0]] = {} obj[path[0]] = crawl_and_check(obj[path[0]], path[1:], checks, path[0]) return obj def check_vars(path, checks): global config crawl_and_check(config, path, checks) def check_toml(template_file, config_file) -> Tuple[bool, Dict]: global config config = None try: template = toml.load(template_file) except Exception as error: console.print(f"[red bold]Encountered error when trying to to load {template_file}: {error}") return False try: config = toml.load(config_file) except toml.TomlDecodeError: console.print( f"""[blue]Couldn't read {config_file}. Overwrite it?(y/n)""" ) if not input().startswith("y"): print("Unable to read config, and not allowed to overwrite it. Giving up.") return False else: try: with open(config_file, "w") as f: f.write("") except: console.print( f"[red bold]Failed to overwrite {config_file}. Giving up.\nSuggestion: check {config_file} permissions for the user." ) return False except FileNotFoundError: console.print( f"""[blue]Couldn't find {config_file} Creating it now.""" ) try: with open(config_file, "x") as f: f.write("") config = {} except: console.print( f"[red bold]Failed to write to {config_file}. Giving up.\nSuggestion: check the folder's permissions for the user." ) return False console.print( """\ [blue bold]############################### # # # Checking TOML configuration # # # ############################### If you see any prompts, that means that you have unset/incorrectly set variables, please input the correct values.\ """ ) crawl(template, check_vars) with open(config_file, "w") as f: toml.dump(config, f) return config if __name__ == "__main__": directory = Path().absolute() check_toml(f"{directory}/utils/.config.template.toml", "config.toml") ================================================ FILE: utils/subreddit.py ================================================ import json from os.path import exists from utils import settings from utils.ai_methods import sort_by_similarity from utils.console import print_substep def _contains_blocked_words(text: str) -> bool: """Returns True if the text contains any blocked words from config.""" blocked_raw = settings.config["reddit"]["thread"].get("blocked_words", "") if not blocked_raw: return False blocked = [w.strip().lower() for w in blocked_raw.split(",") if w.strip()] text_lower = text.lower() return any(word in text_lower for word in blocked) def get_subreddit_undone(submissions: list, subreddit, times_checked=0, similarity_scores=None): """_summary_ Args: submissions (list): List of posts that are going to potentially be generated into a video subreddit (praw.Reddit.SubredditHelper): Chosen subreddit Returns: Any: The submission that has not been done """ # Second try of getting a valid Submission if times_checked and settings.config["ai"]["ai_similarity_enabled"]: print("Sorting based on similarity for a different date filter and thread limit..") submissions = sort_by_similarity( submissions, keywords=settings.config["ai"]["ai_similarity_enabled"] ) # recursively checks if the top submission in the list was already done. if not exists("./video_creation/data/videos.json"): with open("./video_creation/data/videos.json", "w+") as f: json.dump([], f) with open("./video_creation/data/videos.json", "r", encoding="utf-8") as done_vids_raw: done_videos = json.load(done_vids_raw) for i, submission in enumerate(submissions): if already_done(done_videos, submission): continue if submission.over_18: try: if not settings.config["settings"]["allow_nsfw"]: print_substep("NSFW Post Detected. Skipping...") continue except AttributeError: print_substep("NSFW settings not defined. Skipping NSFW post...") if submission.stickied: print_substep("This post was pinned by moderators. Skipping...") continue if _contains_blocked_words(submission.title + " " + (submission.selftext or "")): print_substep("Post contains a blocked word. Skipping...") continue if ( submission.num_comments <= int(settings.config["reddit"]["thread"]["min_comments"]) and not settings.config["settings"]["storymode"] ): print_substep( f'This post has under the specified minimum of comments ({settings.config["reddit"]["thread"]["min_comments"]}). Skipping...' ) continue if settings.config["settings"]["storymode"]: if not submission.selftext: print_substep("You are trying to use story mode on post with no post text") continue else: # Check for the length of the post text if len(submission.selftext) > ( settings.config["settings"]["storymode_max_length"] or 2000 ): print_substep( f"Post is too long ({len(submission.selftext)}), try with a different post. ({settings.config['settings']['storymode_max_length']} character limit)" ) continue elif len(submission.selftext) < 30: continue if settings.config["settings"]["storymode"] and not submission.is_self: continue if similarity_scores is not None: return submission, similarity_scores[i].item() return submission print("all submissions have been done going by top submission order") VALID_TIME_FILTERS = [ "day", "hour", "month", "week", "year", "all", ] # set doesn't have __getitem__ index = times_checked + 1 if index == len(VALID_TIME_FILTERS): print("All submissions have been done.") return get_subreddit_undone( subreddit.top( time_filter=VALID_TIME_FILTERS[index], limit=(50 if int(index) == 0 else index + 1 * 50), ), subreddit, times_checked=index, ) # all the videos in hot have already been done def already_done(done_videos: list, submission) -> bool: """Checks to see if the given submission is in the list of videos Args: done_videos (list): Finished videos submission (Any): The submission Returns: Boolean: Whether the video was found in the list """ for video in done_videos: if video["id"] == str(submission): return True return False ================================================ FILE: utils/thumbnail.py ================================================ from PIL import ImageDraw, ImageFont def create_thumbnail(thumbnail, font_family, font_size, font_color, width, height, title): font = ImageFont.truetype(font_family + ".ttf", font_size) Xaxis = width - (width * 0.2) # 20% of the width sizeLetterXaxis = font_size * 0.5 # 50% of the font size XaxisLetterQty = round(Xaxis / sizeLetterXaxis) # Quantity of letters that can fit in the X axis MarginYaxis = height * 0.12 # 12% of the height MarginXaxis = width * 0.05 # 5% of the width # 1.1 rem LineHeight = font_size * 1.1 # rgb = "255,255,255" transform to list rgb = font_color.split(",") rgb = (int(rgb[0]), int(rgb[1]), int(rgb[2])) arrayTitle = [] for word in title.split(): if len(arrayTitle) == 0: # colocar a primeira palavra no arrayTitl# put the first word in the arrayTitle arrayTitle.append(word) else: # if the size of arrayTitle is less than qtLetters if len(arrayTitle[-1]) + len(word) < XaxisLetterQty: arrayTitle[-1] = arrayTitle[-1] + " " + word else: arrayTitle.append(word) draw = ImageDraw.Draw(thumbnail) # loop for put the title in the thumbnail for i in range(0, len(arrayTitle)): # 1.1 rem draw.text((MarginXaxis, MarginYaxis + (LineHeight * i)), arrayTitle[i], rgb, font=font) return thumbnail ================================================ FILE: utils/version.py ================================================ import requests from utils.console import print_step def checkversion(__VERSION__: str): response = requests.get( "https://api.github.com/repos/elebumm/RedditVideoMakerBot/releases/latest" ) latestversion = response.json()["tag_name"] if __VERSION__ == latestversion: print_step(f"You are using the newest version ({__VERSION__}) of the bot") return True elif __VERSION__ < latestversion: print_step( f"You are using an older version ({__VERSION__}) of the bot. Download the newest version ({latestversion}) from https://github.com/elebumm/RedditVideoMakerBot/releases/latest" ) else: print_step( f"Welcome to the test version ({__VERSION__}) of the bot. Thanks for testing and feel free to report any bugs you find." ) ================================================ FILE: utils/videos.py ================================================ import json import time from praw.models import Submission from utils import settings from utils.console import print_step def check_done( redditobj: Submission, ) -> Submission: # don't set this to be run anyplace that isn't subreddit.py bc of inspect stack """Checks if the chosen post has already been generated Args: redditobj (Submission): Reddit object gotten from reddit/subreddit.py Returns: Submission|None: Reddit object in args """ with open("./video_creation/data/videos.json", "r", encoding="utf-8") as done_vids_raw: done_videos = json.load(done_vids_raw) for video in done_videos: if video["id"] == str(redditobj): if settings.config["reddit"]["thread"]["post_id"]: print_step( "You already have done this video but since it was declared specifically in the config file the program will continue" ) return redditobj print_step("Getting new post as the current one has already been done") return None return redditobj def save_data(subreddit: str, filename: str, reddit_title: str, reddit_id: str, credit: str): """Saves the videos that have already been generated to a JSON file in video_creation/data/videos.json Args: filename (str): The finished video title name @param subreddit: @param filename: @param reddit_id: @param reddit_title: """ with open("./video_creation/data/videos.json", "r+", encoding="utf-8") as raw_vids: done_vids = json.load(raw_vids) if reddit_id in [video["id"] for video in done_vids]: return # video already done but was specified to continue anyway in the config file payload = { "subreddit": subreddit, "id": reddit_id, "time": str(int(time.time())), "background_credit": credit, "reddit_title": reddit_title, "filename": filename, } done_vids.append(payload) raw_vids.seek(0) json.dump(done_vids, raw_vids, ensure_ascii=False, indent=4) ================================================ FILE: utils/voice.py ================================================ import re import sys import time as pytime from datetime import datetime from time import sleep from cleantext import clean from requests import Response from utils import settings if sys.version_info[0] >= 3: from datetime import timezone def check_ratelimit(response: Response) -> bool: """ Checks if the response is a ratelimit response. If it is, it sleeps for the time specified in the response. """ if response.status_code == 429: try: time = int(response.headers["X-RateLimit-Reset"]) print(f"Ratelimit hit. Sleeping for {time - int(pytime.time())} seconds.") sleep_until(time) return False except KeyError: # if the header is not present, we don't know how long to wait return False return True def sleep_until(time) -> None: """ Pause your program until a specific end time. 'time' is either a valid datetime object or unix timestamp in seconds (i.e. seconds since Unix epoch) """ end = time # Convert datetime to unix timestamp and adjust for locality if isinstance(time, datetime): # If we're on Python 3 and the user specified a timezone, convert to UTC and get the timestamp. if sys.version_info[0] >= 3 and time.tzinfo: end = time.astimezone(timezone.utc).timestamp() else: zoneDiff = pytime.time() - (datetime.now() - datetime(1970, 1, 1)).total_seconds() end = (time - datetime(1970, 1, 1)).total_seconds() + zoneDiff # Type check if not isinstance(end, (int, float)): raise Exception("The time parameter is not a number or datetime object") # Now we wait while True: now = pytime.time() diff = end - now # # Time is up! # if diff <= 0: break else: # 'logarithmic' sleeping to minimize loop iterations sleep(diff / 2) def sanitize_text(text: str) -> str: r"""Sanitizes the text for tts. What gets removed: - following characters`^_~@!&;#:-%“”‘"%*/{}[]()\|<>?=+` - any http or https links Args: text (str): Text to be sanitized Returns: str: Sanitized text """ # remove any urls from the text regex_urls = r"((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*" result = re.sub(regex_urls, " ", text) # note: not removing apostrophes regex_expr = r"\s['|’]|['|’]\s|[\^_~@!&;#:\-%—“”‘\"%\*/{}\[\]\(\)\\|<>=+]" result = re.sub(regex_expr, " ", result) result = result.replace("+", "plus").replace("&", "and") # emoji removal if the setting is enabled if settings.config["settings"]["tts"]["no_emojis"]: result = clean(result, no_emoji=True) # remove extra whitespace return " ".join(result.split()) ================================================ FILE: video_creation/__init__.py ================================================ ================================================ FILE: video_creation/background.py ================================================ import json import random import re from pathlib import Path from random import randrange from typing import Any, Dict, Tuple import yt_dlp from moviepy import AudioFileClip, VideoFileClip from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip from utils import settings from utils.console import print_step, print_substep def load_background_options(): _background_options = {} # Load background videos with open("./utils/background_videos.json") as json_file: _background_options["video"] = json.load(json_file) # Load background audios with open("./utils/background_audios.json") as json_file: _background_options["audio"] = json.load(json_file) # Remove "__comment" from backgrounds del _background_options["video"]["__comment"] del _background_options["audio"]["__comment"] for name in list(_background_options["video"].keys()): pos = _background_options["video"][name][3] if pos != "center": _background_options["video"][name][3] = lambda t: ("center", pos + t) return _background_options def get_start_and_end_times(video_length: int, length_of_clip: int) -> Tuple[int, int]: """Generates a random interval of time to be used as the background of the video. Args: video_length (int): Length of the video length_of_clip (int): Length of the video to be used as the background Returns: tuple[int,int]: Start and end time of the randomized interval """ initialValue = 180 # Issue #1649 - Ensures that will be a valid interval in the video while int(length_of_clip) <= int(video_length + initialValue): if initialValue == initialValue // 2: raise Exception("Your background is too short for this video length") else: initialValue //= 2 # Divides the initial value by 2 until reach 0 random_time = randrange(initialValue, int(length_of_clip) - int(video_length)) return random_time, random_time + video_length def get_background_config(mode: str): """Fetch the background/s configuration""" try: choice = str(settings.config["settings"]["background"][f"background_{mode}"]).casefold() except AttributeError: print_substep("No background selected. Picking random background'") choice = None # Handle default / not supported background using default option. # Default : pick random from supported background. if not choice or choice not in background_options[mode]: choice = random.choice(list(background_options[mode].keys())) return background_options[mode][choice] def download_background_video(background_config: Tuple[str, str, str, Any]): """Downloads the background/s video from YouTube.""" Path("./assets/backgrounds/video/").mkdir(parents=True, exist_ok=True) # note: make sure the file name doesn't include an - in it uri, filename, credit, _ = background_config if Path(f"assets/backgrounds/video/{credit}-{filename}").is_file(): return print_step( "We need to download the backgrounds videos. they are fairly large but it's only done once. 😎" ) print_substep("Downloading the backgrounds videos... please be patient 🙏 ") print_substep(f"Downloading {filename} from {uri}") ydl_opts = { "format": "bestvideo[height<=1080][ext=mp4]", "outtmpl": f"assets/backgrounds/video/{credit}-{filename}", "retries": 10, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download(uri) print_substep("Background video downloaded successfully! 🎉", style="bold green") def download_background_audio(background_config: Tuple[str, str, str]): """Downloads the background/s audio from YouTube.""" Path("./assets/backgrounds/audio/").mkdir(parents=True, exist_ok=True) # note: make sure the file name doesn't include an - in it uri, filename, credit = background_config if Path(f"assets/backgrounds/audio/{credit}-{filename}").is_file(): return print_step( "We need to download the backgrounds audio. they are fairly large but it's only done once. 😎" ) print_substep("Downloading the backgrounds audio... please be patient 🙏 ") print_substep(f"Downloading {filename} from {uri}") ydl_opts = { "outtmpl": f"./assets/backgrounds/audio/{credit}-{filename}", "format": "bestaudio/best", "extract_audio": True, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([uri]) print_substep("Background audio downloaded successfully! 🎉", style="bold green") def chop_background(background_config: Dict[str, Tuple], video_length: int, reddit_object: dict): """Generates the background audio and footage to be used in the video and writes it to assets/temp/background.mp3 and assets/temp/background.mp4 Args: reddit_object (Dict[str,str]) : Reddit object background_config (Dict[str,Tuple]]) : Current background configuration video_length (int): Length of the clip where the background footage is to be taken out of """ thread_id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"]) if settings.config["settings"]["background"][f"background_audio_volume"] == 0: print_step("Volume was set to 0. Skipping background audio creation . . .") else: print_step("Finding a spot in the backgrounds audio to chop...✂️") audio_choice = f"{background_config['audio'][2]}-{background_config['audio'][1]}" background_audio = AudioFileClip(f"assets/backgrounds/audio/{audio_choice}") start_time_audio, end_time_audio = get_start_and_end_times( video_length, background_audio.duration ) background_audio = background_audio.subclipped(start_time_audio, end_time_audio) background_audio.write_audiofile(f"assets/temp/{thread_id}/background.mp3") print_step("Finding a spot in the backgrounds video to chop...✂️") video_choice = f"{background_config['video'][2]}-{background_config['video'][1]}" background_video = VideoFileClip(f"assets/backgrounds/video/{video_choice}") start_time_video, end_time_video = get_start_and_end_times( video_length, background_video.duration ) # Extract video subclip try: with VideoFileClip(f"assets/backgrounds/video/{video_choice}") as video: new = video.subclipped(start_time_video, end_time_video) new.write_videofile(f"assets/temp/{thread_id}/background.mp4") except (OSError, IOError): # ffmpeg issue see #348 print_substep("FFMPEG issue. Trying again...") ffmpeg_extract_subclip( f"assets/backgrounds/video/{video_choice}", start_time_video, end_time_video, outputfile=f"assets/temp/{thread_id}/background.mp4", ) print_substep("Background video chopped successfully!", style="bold green") return background_config["video"][2] # Create a tuple for downloads background (background_audio_options, background_video_options) background_options = load_background_options() ================================================ FILE: video_creation/data/cookie-dark-mode.json ================================================ [ { "name": "USER", "value": "eyJwcmVmcyI6eyJ0b3BDb250ZW50RGlzbWlzc2FsVGltZSI6MCwiZ2xvYmFsVGhlbWUiOiJSRURESVQiLCJuaWdodG1vZGUiOnRydWUsImNvbGxhcHNlZFRyYXlTZWN0aW9ucyI6eyJmYXZvcml0ZXMiOmZhbHNlLCJtdWx0aXMiOmZhbHNlLCJtb2RlcmF0aW5nIjpmYWxzZSwic3Vic2NyaXB0aW9ucyI6ZmFsc2UsInByb2ZpbGVzIjpmYWxzZX0sInRvcENvbnRlbnRUaW1lc0Rpc21pc3NlZCI6MH19", "domain": ".reddit.com", "path": "/" }, { "name": "eu_cookie", "value": "{%22opted%22:true%2C%22nonessential%22:false}", "domain": ".reddit.com", "path": "/" } ] ================================================ FILE: video_creation/data/cookie-light-mode.json ================================================ [ { "name": "eu_cookie", "value": "{%22opted%22:true%2C%22nonessential%22:false}", "domain": ".reddit.com", "path": "/" } ] ================================================ FILE: video_creation/final_video.py ================================================ import multiprocessing import os import re import tempfile import textwrap import threading import time from os.path import exists # Needs to be imported specifically from pathlib import Path from typing import Dict, Final, Tuple import ffmpeg import translators from PIL import Image, ImageDraw, ImageFont from rich.console import Console from rich.progress import track from utils import settings from utils.cleanup import cleanup from utils.console import print_step, print_substep from utils.fonts import getheight from utils.id import extract_id from utils.thumbnail import create_thumbnail from utils.videos import save_data console = Console() class ProgressFfmpeg(threading.Thread): def __init__(self, vid_duration_seconds, progress_update_callback): threading.Thread.__init__(self, name="ProgressFfmpeg") self.stop_event = threading.Event() self.output_file = tempfile.NamedTemporaryFile(mode="w+", delete=False) self.vid_duration_seconds = vid_duration_seconds self.progress_update_callback = progress_update_callback def run(self): while not self.stop_event.is_set(): latest_progress = self.get_latest_ms_progress() if latest_progress is not None: completed_percent = latest_progress / self.vid_duration_seconds self.progress_update_callback(completed_percent) time.sleep(1) def get_latest_ms_progress(self): lines = self.output_file.readlines() if lines: for line in lines: if "out_time_ms" in line: out_time_ms_str = line.split("=")[1].strip() if out_time_ms_str.isnumeric(): return float(out_time_ms_str) / 1000000.0 else: # Handle the case when "N/A" is encountered return None return None def stop(self): self.stop_event.set() def __enter__(self): self.start() return self def __exit__(self, *args, **kwargs): self.stop() def name_normalize(name: str) -> str: name = re.sub(r'[?\\"%*:|<>]', "", name) name = re.sub(r"( [w,W]\s?\/\s?[o,O,0])", r" without", name) name = re.sub(r"( [w,W]\s?\/)", r" with", name) name = re.sub(r"(\d+)\s?\/\s?(\d+)", r"\1 of \2", name) name = re.sub(r"(\w+)\s?\/\s?(\w+)", r"\1 or \2", name) name = re.sub(r"\/", r"", name) lang = settings.config["reddit"]["thread"]["post_lang"] if lang: print_substep("Translating filename...") translated_name = translators.translate_text(name, translator="google", to_language=lang) return translated_name else: return name def prepare_background(reddit_id: str, W: int, H: int) -> str: output_path = f"assets/temp/{reddit_id}/background_noaudio.mp4" output = ( ffmpeg.input(f"assets/temp/{reddit_id}/background.mp4") .filter("crop", f"ih*({W}/{H})", "ih") .output( output_path, an=None, **{ "c:v": "h264_nvenc", "b:v": "20M", "b:a": "192k", "threads": multiprocessing.cpu_count(), }, ) .overwrite_output() ) try: output.run(quiet=True) except ffmpeg.Error as e: print(e.stderr.decode("utf8")) exit(1) return output_path def get_text_height(draw, text, font, max_width): lines = textwrap.wrap(text, width=max_width) total_height = 0 for line in lines: _, _, _, height = draw.textbbox((0, 0), line, font=font) total_height += height return total_height def create_fancy_thumbnail(image, text, text_color, padding, wrap=35): """ It will take the 1px from the middle of the template and will be resized (stretched) vertically to accommodate the extra height needed for the title. """ print_step(f"Creating fancy thumbnail for: {text}") font_title_size = 47 font = ImageFont.truetype(os.path.join("fonts", "Roboto-Bold.ttf"), font_title_size) image_width, image_height = image.size # Calculate text height to determine new image height draw = ImageDraw.Draw(image) text_height = get_text_height(draw, text, font, wrap) lines = textwrap.wrap(text, width=wrap) # This is -50 to reduce the empty space at the bottom of the image, # change it as per your requirement if needed otherwise leave it. new_image_height = image_height + text_height + padding * (len(lines) - 1) - 50 # Separate the image into top, middle (1px), and bottom parts top_part_height = image_height // 2 middle_part_height = 1 # 1px height middle section bottom_part_height = image_height - top_part_height - middle_part_height top_part = image.crop((0, 0, image_width, top_part_height)) middle_part = image.crop((0, top_part_height, image_width, top_part_height + middle_part_height)) bottom_part = image.crop((0, top_part_height + middle_part_height, image_width, image_height)) # Stretch the middle part new_middle_height = new_image_height - top_part_height - bottom_part_height middle_part = middle_part.resize((image_width, new_middle_height)) # Create new image with the calculated height new_image = Image.new("RGBA", (image_width, new_image_height)) # Paste the top, stretched middle, and bottom parts into the new image new_image.paste(top_part, (0, 0)) new_image.paste(middle_part, (0, top_part_height)) new_image.paste(bottom_part, (0, top_part_height + new_middle_height)) # Draw the title text on the new image draw = ImageDraw.Draw(new_image) y = top_part_height + padding for line in lines: draw.text((120, y), line, font=font, fill=text_color, align="left") y += get_text_height(draw, line, font, wrap) + padding # Draw the username "PlotPulse" at the specific position username_font = ImageFont.truetype(os.path.join("fonts", "Roboto-Bold.ttf"), 30) draw.text( (205, 825), settings.config["settings"]["channel_name"], font=username_font, fill=text_color, align="left", ) return new_image def merge_background_audio(audio: ffmpeg, reddit_id: str): """Gather an audio and merge with assets/backgrounds/background.mp3 Args: audio (ffmpeg): The TTS final audio but without background. reddit_id (str): The ID of subreddit """ background_audio_volume = settings.config["settings"]["background"]["background_audio_volume"] if background_audio_volume == 0: return audio # Return the original audio else: # sets volume to config bg_audio = ffmpeg.input(f"assets/temp/{reddit_id}/background.mp3").filter( "volume", background_audio_volume, ) # Merges audio and background_audio merged_audio = ffmpeg.filter([audio, bg_audio], "amix", duration="longest") return merged_audio # Return merged audio def make_final_video( number_of_clips: int, length: int, reddit_obj: dict, background_config: Dict[str, Tuple], ): """Gathers audio clips, gathers all screenshots, stitches them together and saves the final video to assets/temp Args: number_of_clips (int): Index to end at when going through the screenshots' length (int): Length of the video reddit_obj (dict): The reddit object that contains the posts to read. background_config (Tuple[str, str, str, Any]): The background config to use. """ # settings values W: Final[int] = int(settings.config["settings"]["resolution_w"]) H: Final[int] = int(settings.config["settings"]["resolution_h"]) opacity = settings.config["settings"]["opacity"] reddit_id = extract_id(reddit_obj) allowOnlyTTSFolder: bool = ( settings.config["settings"]["background"]["enable_extra_audio"] and settings.config["settings"]["background"]["background_audio_volume"] != 0 ) print_step("Creating the final video 🎥") background_clip = ffmpeg.input(prepare_background(reddit_id, W=W, H=H)) # Gather all audio clips audio_clips = list() if number_of_clips == 0 and settings.config["settings"]["storymode"] == "false": print( "No audio clips to gather. Please use a different TTS or post." ) # This is to fix the TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' exit() if settings.config["settings"]["storymode"]: if settings.config["settings"]["storymodemethod"] == 0: audio_clips = [ffmpeg.input(f"assets/temp/{reddit_id}/mp3/title.mp3")] audio_clips.insert(1, ffmpeg.input(f"assets/temp/{reddit_id}/mp3/postaudio.mp3")) elif settings.config["settings"]["storymodemethod"] == 1: audio_clips = [ ffmpeg.input(f"assets/temp/{reddit_id}/mp3/postaudio-{i}.mp3") for i in track(range(number_of_clips + 1), "Collecting the audio files...") ] audio_clips.insert(0, ffmpeg.input(f"assets/temp/{reddit_id}/mp3/title.mp3")) else: audio_clips = [ ffmpeg.input(f"assets/temp/{reddit_id}/mp3/{i}.mp3") for i in range(number_of_clips) ] audio_clips.insert(0, ffmpeg.input(f"assets/temp/{reddit_id}/mp3/title.mp3")) audio_clips_durations = [ float(ffmpeg.probe(f"assets/temp/{reddit_id}/mp3/{i}.mp3")["format"]["duration"]) for i in range(number_of_clips) ] audio_clips_durations.insert( 0, float(ffmpeg.probe(f"assets/temp/{reddit_id}/mp3/title.mp3")["format"]["duration"]), ) audio_concat = ffmpeg.concat(*audio_clips, a=1, v=0) ffmpeg.output( audio_concat, f"assets/temp/{reddit_id}/audio.mp3", **{"b:a": "192k"} ).overwrite_output().run(quiet=True) console.log(f"[bold green] Video Will Be: {length} Seconds Long") screenshot_width = int((W * 45) // 100) audio = ffmpeg.input(f"assets/temp/{reddit_id}/audio.mp3") final_audio = merge_background_audio(audio, reddit_id) image_clips = list() Path(f"assets/temp/{reddit_id}/png").mkdir(parents=True, exist_ok=True) # Credits to tim (beingbored) # get the title_template image and draw a text in the middle part of it with the title of the thread title_template = Image.open("assets/title_template.png") title = reddit_obj["thread_title"] title = name_normalize(title) font_color = "#000000" padding = 5 # create_fancy_thumbnail(image, text, text_color, padding title_img = create_fancy_thumbnail(title_template, title, font_color, padding) title_img.save(f"assets/temp/{reddit_id}/png/title.png") image_clips.insert( 0, ffmpeg.input(f"assets/temp/{reddit_id}/png/title.png")["v"].filter( "scale", screenshot_width, -1 ), ) current_time = 0 if settings.config["settings"]["storymode"]: audio_clips_durations = [ float( ffmpeg.probe(f"assets/temp/{reddit_id}/mp3/postaudio-{i}.mp3")["format"]["duration"] ) for i in range(number_of_clips) ] audio_clips_durations.insert( 0, float(ffmpeg.probe(f"assets/temp/{reddit_id}/mp3/title.mp3")["format"]["duration"]), ) if settings.config["settings"]["storymodemethod"] == 0: image_clips.insert( 1, ffmpeg.input(f"assets/temp/{reddit_id}/png/story_content.png").filter( "scale", screenshot_width, -1 ), ) background_clip = background_clip.overlay( image_clips[0], enable=f"between(t,{current_time},{current_time + audio_clips_durations[0]})", x="(main_w-overlay_w)/2", y="(main_h-overlay_h)/2", ) current_time += audio_clips_durations[0] elif settings.config["settings"]["storymodemethod"] == 1: for i in track(range(0, number_of_clips + 1), "Collecting the image files..."): image_clips.append( ffmpeg.input(f"assets/temp/{reddit_id}/png/img{i}.png")["v"].filter( "scale", screenshot_width, -1 ) ) background_clip = background_clip.overlay( image_clips[i], enable=f"between(t,{current_time},{current_time + audio_clips_durations[i]})", x="(main_w-overlay_w)/2", y="(main_h-overlay_h)/2", ) current_time += audio_clips_durations[i] else: for i in range(0, number_of_clips + 1): image_clips.append( ffmpeg.input(f"assets/temp/{reddit_id}/png/comment_{i}.png")["v"].filter( "scale", screenshot_width, -1 ) ) image_overlay = image_clips[i].filter("colorchannelmixer", aa=opacity) assert ( audio_clips_durations is not None ), "Please make a GitHub issue if you see this. Ping @JasonLovesDoggo on GitHub." background_clip = background_clip.overlay( image_overlay, enable=f"between(t,{current_time},{current_time + audio_clips_durations[i]})", x="(main_w-overlay_w)/2", y="(main_h-overlay_h)/2", ) current_time += audio_clips_durations[i] title = extract_id(reddit_obj, "thread_title") idx = extract_id(reddit_obj) title_thumb = reddit_obj["thread_title"] filename = f"{name_normalize(title)[:251]}" subreddit = settings.config["reddit"]["thread"]["subreddit"] if not exists(f"./results/{subreddit}"): print_substep("The 'results' folder could not be found so it was automatically created.") os.makedirs(f"./results/{subreddit}") if not exists(f"./results/{subreddit}/OnlyTTS") and allowOnlyTTSFolder: print_substep("The 'OnlyTTS' folder could not be found so it was automatically created.") os.makedirs(f"./results/{subreddit}/OnlyTTS") # create a thumbnail for the video settingsbackground = settings.config["settings"]["background"] if settingsbackground["background_thumbnail"]: if not exists(f"./results/{subreddit}/thumbnails"): print_substep( "The 'results/thumbnails' folder could not be found so it was automatically created." ) os.makedirs(f"./results/{subreddit}/thumbnails") # get the first file with the .png extension from assets/backgrounds and use it as a background for the thumbnail first_image = next( (file for file in os.listdir("assets/backgrounds") if file.endswith(".png")), None, ) if first_image is None: print_substep("No png files found in assets/backgrounds", "red") else: font_family = settingsbackground["background_thumbnail_font_family"] font_size = settingsbackground["background_thumbnail_font_size"] font_color = settingsbackground["background_thumbnail_font_color"] thumbnail = Image.open(f"assets/backgrounds/{first_image}") width, height = thumbnail.size thumbnailSave = create_thumbnail( thumbnail, font_family, font_size, font_color, width, height, title_thumb, ) thumbnailSave.save(f"./assets/temp/{reddit_id}/thumbnail.png") print_substep(f"Thumbnail - Building Thumbnail in assets/temp/{reddit_id}/thumbnail.png") text = f"Background by {background_config['video'][2]}" background_clip = ffmpeg.drawtext( background_clip, text=text, x=f"(w-text_w)", y=f"(h-text_h)", fontsize=5, fontcolor="White", fontfile=os.path.join("fonts", "Roboto-Regular.ttf"), ) background_clip = background_clip.filter("scale", W, H) print_step("Rendering the video 🎥") from tqdm import tqdm pbar = tqdm(total=100, desc="Progress: ", bar_format="{l_bar}{bar}", unit=" %") def on_update_example(progress) -> None: status = round(progress * 100, 2) old_percentage = pbar.n pbar.update(status - old_percentage) defaultPath = f"results/{subreddit}" with ProgressFfmpeg(length, on_update_example) as progress: path = defaultPath + f"/{filename}" path = ( path[:251] + ".mp4" ) # Prevent a error by limiting the path length, do not change this. try: ffmpeg.output( background_clip, final_audio, path, f="mp4", **{ "c:v": "h264_nvenc", "b:v": "20M", "b:a": "192k", "threads": multiprocessing.cpu_count(), }, ).overwrite_output().global_args("-progress", progress.output_file.name).run( quiet=True, overwrite_output=True, capture_stdout=False, capture_stderr=False, ) except ffmpeg.Error as e: print(e.stderr.decode("utf8")) exit(1) old_percentage = pbar.n pbar.update(100 - old_percentage) if allowOnlyTTSFolder: path = defaultPath + f"/OnlyTTS/{filename}" path = ( path[:251] + ".mp4" ) # Prevent a error by limiting the path length, do not change this. print_step("Rendering the Only TTS Video 🎥") with ProgressFfmpeg(length, on_update_example) as progress: try: ffmpeg.output( background_clip, audio, path, f="mp4", **{ "c:v": "h264_nvenc", "b:v": "20M", "b:a": "192k", "threads": multiprocessing.cpu_count(), }, ).overwrite_output().global_args("-progress", progress.output_file.name).run( quiet=True, overwrite_output=True, capture_stdout=False, capture_stderr=False, ) except ffmpeg.Error as e: print(e.stderr.decode("utf8")) exit(1) old_percentage = pbar.n pbar.update(100 - old_percentage) pbar.close() save_data(subreddit, filename + ".mp4", title, idx, background_config["video"][2]) print_step("Removing temporary files 🗑") cleanups = cleanup(reddit_id) print_substep(f"Removed {cleanups} temporary files 🗑") print_step("Done! 🎉 The video is in the results folder 📁") ================================================ FILE: video_creation/screenshot_downloader.py ================================================ import json import re from pathlib import Path from typing import Dict, Final import translators from playwright.sync_api import ViewportSize, sync_playwright from rich.progress import track from utils import settings from utils.console import print_step, print_substep from utils.imagenarator import imagemaker from utils.playwright import clear_cookie_by_name from utils.videos import save_data __all__ = ["get_screenshots_of_reddit_posts"] def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int): """Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png Args: reddit_object (Dict): Reddit object received from reddit/subreddit.py screenshot_num (int): Number of screenshots to download """ # settings values W: Final[int] = int(settings.config["settings"]["resolution_w"]) H: Final[int] = int(settings.config["settings"]["resolution_h"]) lang: Final[str] = settings.config["reddit"]["thread"]["post_lang"] storymode: Final[bool] = settings.config["settings"]["storymode"] print_step("Downloading screenshots of reddit posts...") reddit_id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"]) # ! Make sure the reddit screenshots folder exists Path(f"assets/temp/{reddit_id}/png").mkdir(parents=True, exist_ok=True) # set the theme and turn off non-essential cookies if settings.config["settings"]["theme"] == "dark": cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8") bgcolor = (33, 33, 36, 255) txtcolor = (240, 240, 240) transparent = False elif settings.config["settings"]["theme"] == "transparent": if storymode: # Transparent theme bgcolor = (0, 0, 0, 0) txtcolor = (255, 255, 255) transparent = True cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8") else: # Switch to dark theme cookie_file = open("./video_creation/data/cookie-dark-mode.json", encoding="utf-8") bgcolor = (33, 33, 36, 255) txtcolor = (240, 240, 240) transparent = False else: cookie_file = open("./video_creation/data/cookie-light-mode.json", encoding="utf-8") bgcolor = (255, 255, 255, 255) txtcolor = (0, 0, 0) transparent = False if storymode and settings.config["settings"]["storymodemethod"] == 1: print_substep("Generating images...") return imagemaker( theme=bgcolor, reddit_obj=reddit_object, txtclr=txtcolor, transparent=transparent, ) screenshot_num: int with sync_playwright() as p: print_substep("Launching Headless Browser...") browser = p.chromium.launch( headless=True ) # headless=False will show the browser for debugging purposes # Device scale factor (or dsf for short) allows us to increase the resolution of the screenshots # When the dsf is 1, the width of the screenshot is 600 pixels # so we need a dsf such that the width of the screenshot is greater than the final resolution of the video dsf = (W // 600) + 1 context = browser.new_context( locale=lang or "en-CA,en;q=0.9", color_scheme="dark", viewport=ViewportSize(width=W, height=H), device_scale_factor=dsf, user_agent=f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{browser.version}.0.0.0 Safari/537.36", extra_http_headers={ "Dnt": "1", "Sec-Ch-Ua": '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"', }, ) cookies = json.load(cookie_file) cookie_file.close() context.add_cookies(cookies) # load preference cookies # Login to Reddit print_substep("Logging in to Reddit...") page = context.new_page() page.goto("https://www.reddit.com/login", timeout=0) page.set_viewport_size(ViewportSize(width=1920, height=1080)) page.wait_for_load_state() page.locator(f'input[name="username"]').fill(settings.config["reddit"]["creds"]["username"]) page.locator(f'input[name="password"]').fill(settings.config["reddit"]["creds"]["password"]) page.get_by_role("button", name="Log In").click() page.wait_for_timeout(5000) login_error_div = page.locator(".AnimatedForm__errorMessage").first if login_error_div.is_visible(): print_substep( "Your reddit credentials are incorrect! Please modify them accordingly in the config.toml file.", style="red", ) exit() else: pass page.wait_for_load_state() # Handle the redesign # Check if the redesign optout cookie is set if page.locator("#redesign-beta-optin-btn").is_visible(): # Clear the redesign optout cookie clear_cookie_by_name(context, "redesign_optout") # Reload the page for the redesign to take effect page.reload() # Get the thread screenshot page.goto(reddit_object["thread_url"], timeout=0) page.set_viewport_size(ViewportSize(width=W, height=H)) page.wait_for_load_state() page.wait_for_timeout(5000) if page.locator( "#t3_12hmbug > div > div._3xX726aBn29LDbsDtzr_6E._1Ap4F5maDtT1E1YuCiaO0r.D3IL3FD0RFy_mkKLPwL4 > div > div > button" ).is_visible(): # This means the post is NSFW and requires to click the proceed button. print_substep("Post is NSFW. You are spicy...") page.locator( "#t3_12hmbug > div > div._3xX726aBn29LDbsDtzr_6E._1Ap4F5maDtT1E1YuCiaO0r.D3IL3FD0RFy_mkKLPwL4 > div > div > button" ).click() page.wait_for_load_state() # Wait for page to fully load # translate code if page.locator( "#SHORTCUT_FOCUSABLE_DIV > div:nth-child(7) > div > div > div > header > div > div._1m0iFpls1wkPZJVo38-LSh > button > i" ).is_visible(): page.locator( "#SHORTCUT_FOCUSABLE_DIV > div:nth-child(7) > div > div > div > header > div > div._1m0iFpls1wkPZJVo38-LSh > button > i" ).click() # Interest popup is showing, this code will close it if lang: print_substep("Translating post...") texts_in_tl = translators.translate_text( reddit_object["thread_title"], to_language=lang, translator="google", ) page.evaluate( "tl_content => document.querySelector('[data-adclicklocation=\"title\"] > div > div > h1').textContent = tl_content", texts_in_tl, ) else: print_substep("Skipping translation...") postcontentpath = f"assets/temp/{reddit_id}/png/title.png" try: if settings.config["settings"]["zoom"] != 1: # store zoom settings zoom = settings.config["settings"]["zoom"] # zoom the body of the page page.evaluate("document.body.style.zoom=" + str(zoom)) # as zooming the body doesn't change the properties of the divs, we need to adjust for the zoom location = page.locator('[data-test-id="post-content"]').bounding_box() for i in location: location[i] = float("{:.2f}".format(location[i] * zoom)) page.screenshot(clip=location, path=postcontentpath) else: page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath) except Exception as e: print_substep("Something went wrong!", style="red") resp = input( "Something went wrong with making the screenshots! Do you want to skip the post? (y/n) " ) if resp.casefold().startswith("y"): save_data("", "", "skipped", reddit_id, "") print_substep( "The post is successfully skipped! You can now restart the program and this post will skipped.", "green", ) resp = input("Do you want the error traceback for debugging purposes? (y/n)") if not resp.casefold().startswith("y"): exit() raise e if storymode: page.locator('[data-click-id="text"]').first.screenshot( path=f"assets/temp/{reddit_id}/png/story_content.png" ) else: for idx, comment in enumerate( track( reddit_object["comments"][:screenshot_num], "Downloading screenshots...", ) ): # Stop if we have reached the screenshot_num if idx >= screenshot_num: break if page.locator('[data-testid="content-gate"]').is_visible(): page.locator('[data-testid="content-gate"] button').click() page.goto(f"https://new.reddit.com/{comment['comment_url']}") # translate code if settings.config["reddit"]["thread"]["post_lang"]: comment_tl = translators.translate_text( comment["comment_body"], translator="google", to_language=settings.config["reddit"]["thread"]["post_lang"], ) page.evaluate( '([tl_content, tl_id]) => document.querySelector(`#t1_${tl_id} > div:nth-child(2) > div > div[data-testid="comment"] > div`).textContent = tl_content', [comment_tl, comment["comment_id"]], ) try: if settings.config["settings"]["zoom"] != 1: # store zoom settings zoom = settings.config["settings"]["zoom"] # zoom the body of the page page.evaluate("document.body.style.zoom=" + str(zoom)) # scroll comment into view page.locator(f"#t1_{comment['comment_id']}").scroll_into_view_if_needed() # as zooming the body doesn't change the properties of the divs, we need to adjust for the zoom location = page.locator(f"#t1_{comment['comment_id']}").bounding_box() for i in location: location[i] = float("{:.2f}".format(location[i] * zoom)) page.screenshot( clip=location, path=f"assets/temp/{reddit_id}/png/comment_{idx}.png", ) else: page.locator(f"#t1_{comment['comment_id']}").screenshot( path=f"assets/temp/{reddit_id}/png/comment_{idx}.png" ) except TimeoutError: del reddit_object["comments"] screenshot_num += 1 print("TimeoutError: Skipping screenshot...") continue # close browser instance when we are done using it browser.close() print_substep("Screenshots downloaded Successfully.", style="bold green") ================================================ FILE: video_creation/voices.py ================================================ from typing import Tuple from rich.console import Console from TTS.aws_polly import AWSPolly from TTS.elevenlabs import elevenlabs from TTS.engine_wrapper import TTSEngine from TTS.GTTS import GTTS from TTS.openai_tts import OpenAITTS from TTS.pyttsx import pyttsx from TTS.streamlabs_polly import StreamlabsPolly from TTS.TikTok import TikTok from utils import settings from utils.console import print_step, print_table console = Console() TTSProviders = { "GoogleTranslate": GTTS, "AWSPolly": AWSPolly, "StreamlabsPolly": StreamlabsPolly, "TikTok": TikTok, "pyttsx": pyttsx, "ElevenLabs": elevenlabs, "OpenAI": OpenAITTS, } def save_text_to_mp3(reddit_obj) -> Tuple[int, int]: """Saves text to MP3 files. Args: reddit_obj (): Reddit object received from reddit API in reddit/subreddit.py Returns: tuple[int,int]: (total length of the audio, the number of comments audio was generated for) """ voice = settings.config["settings"]["tts"]["voice_choice"] if str(voice).casefold() in map(lambda _: _.casefold(), TTSProviders): text_to_mp3 = TTSEngine(get_case_insensitive_key_value(TTSProviders, voice), reddit_obj) else: while True: print_step("Please choose one of the following TTS providers: ") print_table(TTSProviders) choice = input("\n") if choice.casefold() in map(lambda _: _.casefold(), TTSProviders): break print("Unknown Choice") text_to_mp3 = TTSEngine(get_case_insensitive_key_value(TTSProviders, choice), reddit_obj) return text_to_mp3.run() def get_case_insensitive_key_value(input_dict, key): return next( (value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None, )