commit
38d8594e32
@ -1,20 +1,90 @@
|
||||
REDDIT_CLIENT_ID=""
|
||||
REDDIT_CLIENT_SECRET=""
|
||||
|
||||
REDDIT_USERNAME=""
|
||||
REDDIT_PASSWORD=""
|
||||
REDDIT_CLIENT_ID="" #fFAGRNJru1FTz70BzhT3Zg
|
||||
#EXPLANATION the ID of your Reddit app of SCRIPT type
|
||||
#RANGE 12:30
|
||||
#MATCH_REGEX [-a-zA-Z0-9._~+/]+=*$
|
||||
#OOB_ERROR The ID should be over 12 and under 30 characters, double check your input.
|
||||
|
||||
# Valid options are "yes" and "no"
|
||||
REDDIT_2FA=""
|
||||
REDDIT_CLIENT_SECRET="" #fFAGRNJru1FTz70BzhT3Zg
|
||||
#EXPLANATION the SECRET of your Reddit app of SCRIPT type
|
||||
#RANGE 20:40
|
||||
#MATCH_REGEX [-a-zA-Z0-9._~+/]+=*$
|
||||
#OOB_ERROR The secret should be over 20 and under 40 characters, double check your input.
|
||||
|
||||
#If no, it will ask you a thread link to extract the thread, if yes it will randomize it.
|
||||
RANDOM_THREAD="yes"
|
||||
REDDIT_USERNAME="" #asdfghjkl
|
||||
#EXPLANATION the username of your reddit account
|
||||
#RANGE 3:20
|
||||
#MATCH_REGEX [_0-9a-zA-Z]+$
|
||||
#OOB_ERROR A username HAS to be between 3 and 20 characters
|
||||
|
||||
# Valid options are "light" and "dark"
|
||||
THEME=""
|
||||
REDDIT_PASSWORD="" #fFAGRNJru1FTz70BzhT3Zg
|
||||
#EXPLANATION the password of your reddit account
|
||||
#RANGE 8:None
|
||||
#OOB_ERROR Password too short
|
||||
|
||||
# Enter a subreddit, e.g. "AskReddit"
|
||||
SUBREDDIT=""
|
||||
#OPTIONAL
|
||||
RANDOM_THREAD="no"
|
||||
# If set to no, it will ask you a thread link to extract the thread, if yes it will randomize it. Default: "no"
|
||||
|
||||
# Range is 0 -> 1
|
||||
OPACITY="0.9"
|
||||
REDDIT_2FA="" #no
|
||||
#MATCH_REGEX ^(yes|no)
|
||||
#EXPLANATION Whether you have Reddit 2FA enabled, Valid options are "yes" and "no"
|
||||
|
||||
SUBREDDIT="AskReddit"
|
||||
#EXPLANATION what subreddit to pull posts from, the name of the sub, not the URL
|
||||
#RANGE 3:20
|
||||
#MATCH_REGEX [_0-9a-zA-Z]+$
|
||||
#OOB_ERROR A subreddit name HAS to be between 3 and 20 characters
|
||||
|
||||
ALLOW_NSFW="False"
|
||||
#EXPLANATION Whether to allow NSFW content, True or False
|
||||
#MATCH_REGEX ^(True|False)$
|
||||
|
||||
POST_ID=""
|
||||
#MATCH_REGEX ^((?!://|://).)*$
|
||||
#EXPLANATION Used if you want to use a specific post. example of one is urdtfx
|
||||
|
||||
THEME="LIGHT" #dark
|
||||
#EXPLANATION sets the Reddit theme, either LIGHT or DARK
|
||||
#MATCH_REGEX ^(dark|light|DARK|LIGHT)$
|
||||
|
||||
TIMES_TO_RUN="" #2
|
||||
#EXPLANATION used if you want to run multiple times. set to an int e.g. 4 or 29 and leave blank for 1
|
||||
|
||||
MAX_COMMENT_LENGTH="500" #500
|
||||
#EXPLANATION max number of characters a comment can have. default is 500
|
||||
#RANGE 0:10000
|
||||
#MATCH_TYPE int
|
||||
#OOB_ERROR the max comment length should be between 0 and 10000
|
||||
|
||||
OPACITY="1" #.8
|
||||
#EXPLANATION Sets the opacity of the comments when overlayed over the background
|
||||
#RANGE 0:1
|
||||
#MATCH_TYPE float
|
||||
#OOB_ERROR The opacity HAS to be between 0 and 1
|
||||
|
||||
# If you want to translate the comments to another language, set the language code here.
|
||||
# If empty, no translation will be done.
|
||||
POSTLANG=""
|
||||
#EXPLANATION Activates the translation feature, set the language code for translate or leave blank
|
||||
|
||||
# see different voice options: todo: add docs
|
||||
VOICE="Matthew" # e.g. en_us_002
|
||||
#EXPLANATION sets the voice the TTS uses
|
||||
|
||||
TTSCHOICE="Polly"
|
||||
#EXPLANATION the backend used for TTS. Without anything specified, the user will be prompted to choose one.
|
||||
# IMPORTANT NOTE: if you use translate, you need to set this to googletranslate or tiktok and use custom voice in your language
|
||||
|
||||
STREAMLABS_VOICE="Joanna"
|
||||
#EXPLANATION Sets the voice for the Streamlabs Polly TTS Engine. Check the file for more information on different voices.
|
||||
|
||||
AWS_VOICE="Joanna"
|
||||
#EXPLANATION Sets the voice for the AWS Polly TTS Engine. Check the file for more information on different voices.
|
||||
|
||||
TIKTOK_VOICE="en_us_006"
|
||||
#EXPLANATION Sets the voice for the TikTok TTS Engine. Check the file for more information on different voices.
|
||||
|
||||
#OPTIONAL
|
||||
STORYMODE="False"
|
||||
# IN-PROGRESS - not yet implemented
|
||||
|
@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
@ -0,0 +1,28 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ""
|
||||
labels: bug
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**System (please complete the following information):**
|
||||
|
||||
- Python Version: [e.g. Python 3.6]
|
||||
- OS: [e.g. Windows 11]
|
||||
- App version / Branch [e.g. latest, V2.0, master, develop ]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered** (optional)
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context** (optional)
|
||||
Add any other context or screenshots about the feature request here.
|
@ -0,0 +1,25 @@
|
||||
# Description
|
||||
|
||||
<!-- Please include a summary of the change and which issue is fixed. Please also include relevant context. List any dependencies that are required for this change. -->
|
||||
|
||||
# Issue Fixes
|
||||
|
||||
<!-- Fixes #(issue) if relevant-->
|
||||
|
||||
None
|
||||
|
||||
# Checklist:
|
||||
|
||||
- [ ] I am pushing changes to the **develop** branch
|
||||
- [ ] I am using the recommended development environment
|
||||
- [ ] I have performed a self-review of my own code
|
||||
- [ ] I have commented my code, particularly in hard-to-understand areas
|
||||
- [ ] I have formatted and linted my code using python-black and pylint
|
||||
- [ ] I have cleaned up unnecessary files
|
||||
- [ ] My changes generate no new warnings
|
||||
- [ ] My changes follow the existing code-style
|
||||
- [ ] My changes are relevant to the project
|
||||
|
||||
# Any other information (e.g how to test the changes)
|
||||
|
||||
None
|
@ -0,0 +1,11 @@
|
||||
# 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"
|
@ -1,11 +1,243 @@
|
||||
assets/
|
||||
reddit/__pycache__/
|
||||
utils/__pycache__/
|
||||
# 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
|
||||
reddit-bot-351418-5560ebc49cac.json
|
||||
video_creation/__pycache__/
|
||||
.setup-done-before
|
||||
__pycache__
|
||||
.idea/
|
||||
.DS_Store
|
||||
.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/
|
||||
out
|
||||
.DS_Store
|
||||
.setup-done-before
|
||||
results/*
|
||||
reddit-bot-351418-5560ebc49cac.json
|
||||
/.idea
|
||||
*.pyc
|
||||
video_creation/data/videos.json
|
||||
video_creation/data/envvars.txt
|
||||
|
@ -0,0 +1,614 @@
|
||||
[MAIN]
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Load and enable all available extensions. Use --list-extensions to see a list
|
||||
# all available extensions.
|
||||
#enable-all-extensions=
|
||||
|
||||
# In error mode, checkers without error messages are disabled and for others,
|
||||
# only the ERROR messages are displayed, and no reports are done by default.
|
||||
#errors-only=
|
||||
|
||||
# Always return a 0 (non-error) status code, even if lint errors are found.
|
||||
# This is primarily useful in continuous integration scripts.
|
||||
#exit-zero=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code.
|
||||
extension-pkg-allow-list=
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
|
||||
# for backward compatibility.)
|
||||
extension-pkg-whitelist=
|
||||
|
||||
# Return non-zero exit code if any of these messages/categories are detected,
|
||||
# even if score is above --fail-under value. Syntax same as enable. Messages
|
||||
# specified are enabled, while categories only check already-enabled messages.
|
||||
fail-on=
|
||||
|
||||
# Specify a score threshold to be exceeded before program exits with error.
|
||||
fail-under=10
|
||||
|
||||
# Interpret the stdin as a python script, whose filename needs to be passed as
|
||||
# the module_or_package argument.
|
||||
#from-stdin=
|
||||
|
||||
# Files or directories to be skipped. They should be base names, not paths.
|
||||
ignore=CVS
|
||||
|
||||
# Add files or directories matching the regex patterns to the ignore-list. The
|
||||
# regex matches against paths and can be in Posix or Windows format.
|
||||
ignore-paths=
|
||||
|
||||
# Files or directories matching the regex patterns are skipped. The regex
|
||||
# matches against base names, not paths. The default value ignores Emacs file
|
||||
# locks
|
||||
ignore-patterns=^\.#
|
||||
|
||||
# List of module names for which member attributes should not be checked
|
||||
# (useful for modules/projects where namespaces are manipulated during runtime
|
||||
# and thus existing member attributes cannot be deduced by static analysis). It
|
||||
# supports qualified module names, as well as Unix pattern matching.
|
||||
ignored-modules=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||
# number of processors available to use.
|
||||
jobs=1
|
||||
|
||||
# Control the amount of potential inferred values when inferring a single
|
||||
# object. This can help the performance when dealing with large functions or
|
||||
# complex, nested conditions.
|
||||
limit-inference-results=100
|
||||
|
||||
# List of plugins (as comma separated values of python module names) to load,
|
||||
# usually to register additional checkers.
|
||||
load-plugins=
|
||||
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# Minimum Python version to use for version dependent checks. Will default to
|
||||
# the version used to run pylint.
|
||||
py-version=3.6
|
||||
|
||||
# Discover python modules and packages in the file system subtree.
|
||||
recursive=no
|
||||
|
||||
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||
# user-friendly hints instead of false-positive error messages.
|
||||
suggestion-mode=yes
|
||||
|
||||
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
||||
# active Python interpreter and may run arbitrary code.
|
||||
unsafe-load-any-extension=no
|
||||
|
||||
# In verbose mode, extra non-checker-related info will be displayed.
|
||||
#verbose=
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a score less than or equal to 10. You
|
||||
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
|
||||
# 'convention', and 'info' which contain the number of messages in each
|
||||
# category, as well as 'statement' which is the total number of statements
|
||||
# analyzed. This score is used by the global evaluation report (RP0004).
|
||||
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details.
|
||||
msg-template=
|
||||
|
||||
# Set the output format. Available formats are text, parseable, colorized, json
|
||||
# and msvs (visual studio). You can also give a reporter class, e.g.
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
#output-format=
|
||||
|
||||
# Tells whether to display a full report or only the messages.
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
|
||||
# UNDEFINED.
|
||||
confidence=HIGH,
|
||||
CONTROL_FLOW,
|
||||
INFERENCE,
|
||||
INFERENCE_FAILURE,
|
||||
UNDEFINED
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once). You can also use "--disable=all" to
|
||||
# disable everything first and then re-enable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use "--disable=all --enable=classes
|
||||
# --disable=W".
|
||||
disable=raw-checker-failed,
|
||||
bad-inline-option,
|
||||
locally-disabled,
|
||||
file-ignored,
|
||||
suppressed-message,
|
||||
useless-suppression,
|
||||
deprecated-pragma,
|
||||
use-symbolic-message-instead,
|
||||
attribute-defined-outside-init,
|
||||
invalid-name,
|
||||
missing-docstring,
|
||||
protected-access,
|
||||
too-few-public-methods,
|
||||
format, # handled by black
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=c-extension-no-member
|
||||
|
||||
|
||||
[BASIC]
|
||||
|
||||
# Naming style matching correct argument names.
|
||||
argument-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct argument names. Overrides argument-
|
||||
# naming-style. If left empty, argument names will be checked with the set
|
||||
# naming style.
|
||||
#argument-rgx=
|
||||
|
||||
# Naming style matching correct attribute names.
|
||||
attr-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct attribute names. Overrides attr-naming-
|
||||
# style. If left empty, attribute names will be checked with the set naming
|
||||
# style.
|
||||
#attr-rgx=
|
||||
|
||||
# Bad variable names which should always be refused, separated by a comma.
|
||||
bad-names=foo,
|
||||
bar,
|
||||
baz,
|
||||
toto,
|
||||
tutu,
|
||||
tata
|
||||
|
||||
# Bad variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be refused
|
||||
bad-names-rgxs=
|
||||
|
||||
# Naming style matching correct class attribute names.
|
||||
class-attribute-naming-style=any
|
||||
|
||||
# Regular expression matching correct class attribute names. Overrides class-
|
||||
# attribute-naming-style. If left empty, class attribute names will be checked
|
||||
# with the set naming style.
|
||||
#class-attribute-rgx=
|
||||
|
||||
# Naming style matching correct class constant names.
|
||||
class-const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct class constant names. Overrides class-
|
||||
# const-naming-style. If left empty, class constant names will be checked with
|
||||
# the set naming style.
|
||||
#class-const-rgx=
|
||||
|
||||
# Naming style matching correct class names.
|
||||
class-naming-style=PascalCase
|
||||
|
||||
# Regular expression matching correct class names. Overrides class-naming-
|
||||
# style. If left empty, class names will be checked with the set naming style.
|
||||
#class-rgx=
|
||||
|
||||
# Naming style matching correct constant names.
|
||||
const-naming-style=UPPER_CASE
|
||||
|
||||
# Regular expression matching correct constant names. Overrides const-naming-
|
||||
# style. If left empty, constant names will be checked with the set naming
|
||||
# style.
|
||||
#const-rgx=
|
||||
|
||||
# Minimum line length for functions/classes that require docstrings, shorter
|
||||
# ones are exempt.
|
||||
docstring-min-length=-1
|
||||
|
||||
# Naming style matching correct function names.
|
||||
function-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct function names. Overrides function-
|
||||
# naming-style. If left empty, function names will be checked with the set
|
||||
# naming style.
|
||||
#function-rgx=
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma.
|
||||
good-names=i,
|
||||
j,
|
||||
k,
|
||||
ex,
|
||||
Run,
|
||||
_
|
||||
|
||||
# Good variable names regexes, separated by a comma. If names match any regex,
|
||||
# they will always be accepted
|
||||
good-names-rgxs=
|
||||
|
||||
# Include a hint for the correct naming format with invalid-name.
|
||||
include-naming-hint=no
|
||||
|
||||
# Naming style matching correct inline iteration names.
|
||||
inlinevar-naming-style=any
|
||||
|
||||
# Regular expression matching correct inline iteration names. Overrides
|
||||
# inlinevar-naming-style. If left empty, inline iteration names will be checked
|
||||
# with the set naming style.
|
||||
#inlinevar-rgx=
|
||||
|
||||
# Naming style matching correct method names.
|
||||
method-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct method names. Overrides method-naming-
|
||||
# style. If left empty, method names will be checked with the set naming style.
|
||||
#method-rgx=
|
||||
|
||||
# Naming style matching correct module names.
|
||||
module-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct module names. Overrides module-naming-
|
||||
# style. If left empty, module names will be checked with the set naming style.
|
||||
#module-rgx=
|
||||
|
||||
# Colon-delimited sets of names that determine each other's naming style when
|
||||
# the name regexes allow several styles.
|
||||
name-group=
|
||||
|
||||
# Regular expression which should only match function or class names that do
|
||||
# not require a docstring.
|
||||
no-docstring-rgx=^_
|
||||
|
||||
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
||||
# to this list to register other decorators that produce valid properties.
|
||||
# These decorators are taken in consideration only for invalid-name.
|
||||
property-classes=abc.abstractproperty
|
||||
|
||||
# Regular expression matching correct type variable names. If left empty, type
|
||||
# variable names will be checked with the set naming style.
|
||||
#typevar-rgx=
|
||||
|
||||
# Naming style matching correct variable names.
|
||||
variable-naming-style=snake_case
|
||||
|
||||
# Regular expression matching correct variable names. Overrides variable-
|
||||
# naming-style. If left empty, variable names will be checked with the set
|
||||
# naming style.
|
||||
#variable-rgx=
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# Warn about protected attribute access inside special methods
|
||||
check-protected-access-in-special-methods=no
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,
|
||||
__new__,
|
||||
setUp,
|
||||
__post_init__
|
||||
|
||||
# List of member names, which should be excluded from the protected access
|
||||
# warning.
|
||||
exclude-protected=_asdict,
|
||||
_fields,
|
||||
_replace,
|
||||
_source,
|
||||
_make
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=cls
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# List of regular expressions of class ancestor names to ignore when counting
|
||||
# public methods (see R0903)
|
||||
exclude-too-few-public-methods=
|
||||
|
||||
# List of qualified class names to ignore when counting class parents (see
|
||||
# R0901)
|
||||
ignored-parents=
|
||||
|
||||
# Maximum number of arguments for function / method.
|
||||
max-args=5
|
||||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
max-attributes=7
|
||||
|
||||
# Maximum number of boolean expressions in an if statement (see R0916).
|
||||
max-bool-expr=5
|
||||
|
||||
# Maximum number of branch for function / method body.
|
||||
max-branches=12
|
||||
|
||||
# Maximum number of locals for function / method body.
|
||||
max-locals=15
|
||||
|
||||
# Maximum number of parents for a class (see R0901).
|
||||
max-parents=7
|
||||
|
||||
# Maximum number of public methods for a class (see R0904).
|
||||
max-public-methods=20
|
||||
|
||||
# Maximum number of return / yield for function / method body.
|
||||
max-returns=6
|
||||
|
||||
# Maximum number of statements in function / method body.
|
||||
max-statements=50
|
||||
|
||||
# Minimum number of public methods for a class (see R0903).
|
||||
min-public-methods=2
|
||||
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when caught.
|
||||
overgeneral-exceptions=BaseException,
|
||||
Exception
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
expected-line-ending-format=
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=100
|
||||
|
||||
# Maximum number of lines in a module.
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# List of modules that can be imported at any level, not just the top level
|
||||
# one.
|
||||
allow-any-import-level=
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma.
|
||||
deprecated-modules=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of external dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
ext-import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of all (i.e. internal and
|
||||
# external) dependencies to the given file (report RP0402 must not be
|
||||
# disabled).
|
||||
import-graph=
|
||||
|
||||
# Output a graph (.gv or any supported image format) of internal dependencies
|
||||
# to the given file (report RP0402 must not be disabled).
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
# Couples of modules and preferred modules, separated by a comma.
|
||||
preferred-modules=
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# The type of string formatting that logging methods do. `old` means using %
|
||||
# formatting, `new` is for `{}` formatting.
|
||||
logging-format-style=old
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format.
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
notes=FIXME,
|
||||
XXX,
|
||||
TODO
|
||||
|
||||
# Regular expression of note tags to take in consideration.
|
||||
notes-rgx=
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
# Complete name of functions that never returns. When checking for
|
||||
# inconsistent-return-statements if a never returning function is called then
|
||||
# it will be considered as an explicit return statement and no message will be
|
||||
# printed.
|
||||
never-returning-functions=sys.exit,argparse.parse_error
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Comments are removed from the similarity computation
|
||||
ignore-comments=yes
|
||||
|
||||
# Docstrings are removed from the similarity computation
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Imports are removed from the similarity computation
|
||||
ignore-imports=yes
|
||||
|
||||
# Signatures are removed from the similarity computation
|
||||
ignore-signatures=yes
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=4
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Limits count of emitted suggestions for spelling mistakes.
|
||||
max-spelling-suggestions=4
|
||||
|
||||
# Spelling dictionary name. Available dictionaries: none. To make it work,
|
||||
# install the 'python-enchant' package.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should be considered directives if they
|
||||
# appear at the beginning of a comment and should not be checked.
|
||||
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains the private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to the private dictionary (see the
|
||||
# --spelling-private-dict-file option) instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[STRING]
|
||||
|
||||
# This flag controls whether inconsistent-quotes generates a warning when the
|
||||
# character used as a quote delimiter is used inconsistently within a module.
|
||||
check-quote-consistency=no
|
||||
|
||||
# This flag controls whether the implicit-str-concat should generate a warning
|
||||
# on implicit string concatenation in sequences defined over several lines.
|
||||
check-str-concat-over-line-jumps=no
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether to warn about missing members when the owner of the attribute
|
||||
# is inferred to be None.
|
||||
ignore-none=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of symbolic message names to ignore for Mixin members.
|
||||
ignored-checks-for-mixins=no-member,
|
||||
not-async-context-manager,
|
||||
not-context-manager,
|
||||
attribute-defined-outside-init
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
# Regex pattern to define which classes are considered mixins.
|
||||
mixin-class-rgx=.*[Mm]ixin
|
||||
|
||||
# List of decorators that change the signature of a decorated function.
|
||||
signature-mutators=
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid defining new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of names allowed to shadow builtins
|
||||
allowed-redefined-builtins=
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,
|
||||
_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expected to
|
||||
# not be used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored. Default to name
|
||||
# with leading underscore.
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
@ -0,0 +1,127 @@
|
||||
# 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.
|
@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
import random
|
||||
import os
|
||||
from gtts import gTTS
|
||||
|
||||
max_chars = 0
|
||||
|
||||
|
||||
class GTTS:
|
||||
def __init__(self):
|
||||
self.max_chars = 0
|
||||
self.voices = []
|
||||
|
||||
def run(self, text, filepath):
|
||||
tts = gTTS(text=text, lang=os.getenv("POSTLANG") or "en", slow=False)
|
||||
tts.save(filepath)
|
||||
|
||||
def randomvoice(self):
|
||||
return random.choice(self.voices)
|
@ -0,0 +1,100 @@
|
||||
import base64
|
||||
import os
|
||||
import random
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
# from profanity_filter import ProfanityFilter
|
||||
# pf = ProfanityFilter()
|
||||
# Code by @JasonLovesDoggo
|
||||
# https://twitter.com/scanlime/status/1512598559769702406
|
||||
|
||||
nonhuman = [ # DISNEY VOICES
|
||||
"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
|
||||
# ENGLISH VOICES
|
||||
]
|
||||
human = [
|
||||
"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",
|
||||
]
|
||||
voices = nonhuman + human
|
||||
|
||||
noneng = [
|
||||
"fr_001", # French - Male 1
|
||||
"fr_002", # French - Male 2
|
||||
"de_001", # German - Female
|
||||
"de_002", # German - Male
|
||||
"es_002", # Spanish - Male
|
||||
# AMERICA 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
|
||||
# ASIA 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
|
||||
]
|
||||
|
||||
|
||||
# good_voices = {'good': ['en_us_002', 'en_us_006'],
|
||||
# 'ok': ['en_au_002', 'en_uk_001']} # less en_us_stormtrooper more less en_us_rocket en_us_ghostface
|
||||
|
||||
|
||||
class TikTok: # TikTok Text-to-Speech Wrapper
|
||||
def __init__(self):
|
||||
self.URI_BASE = "https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/?text_speaker="
|
||||
self.max_chars = 300
|
||||
self.voices = {"human": human, "nonhuman": nonhuman, "noneng": noneng}
|
||||
|
||||
def run(self, text, filepath, random_voice: bool = False):
|
||||
# if censor:
|
||||
# req_text = pf.censor(req_text)
|
||||
# pass
|
||||
voice = (
|
||||
self.randomvoice()
|
||||
if random_voice
|
||||
else (os.getenv("TIKTOK_VOICE") or random.choice(self.voices["human"]))
|
||||
)
|
||||
try:
|
||||
r = requests.post(
|
||||
f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0"
|
||||
)
|
||||
except requests.exceptions.SSLError:
|
||||
# https://stackoverflow.com/a/47475019/18516611
|
||||
session = requests.Session()
|
||||
retry = Retry(connect=3, backoff_factor=0.5)
|
||||
adapter = HTTPAdapter(max_retries=retry)
|
||||
session.mount("http://", adapter)
|
||||
session.mount("https://", adapter)
|
||||
r = session.post(
|
||||
f"{self.URI_BASE}{voice}&req_text={text}&speaker_map_type=0"
|
||||
)
|
||||
# print(r.text)
|
||||
vstr = [r.json()["data"]["v_str"]][0]
|
||||
b64d = base64.b64decode(vstr)
|
||||
|
||||
with open(filepath, "wb") as out:
|
||||
out.write(b64d)
|
||||
|
||||
def randomvoice(self):
|
||||
return random.choice(self.voices["human"])
|
@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
from boto3 import Session
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
import sys
|
||||
import os
|
||||
import random
|
||||
|
||||
voices = [
|
||||
"Brian",
|
||||
"Emma",
|
||||
"Russell",
|
||||
"Joey",
|
||||
"Matthew",
|
||||
"Joanna",
|
||||
"Kimberly",
|
||||
"Amy",
|
||||
"Geraint",
|
||||
"Nicole",
|
||||
"Justin",
|
||||
"Ivy",
|
||||
"Kendra",
|
||||
"Salli",
|
||||
"Raveena",
|
||||
]
|
||||
|
||||
|
||||
class AWSPolly:
|
||||
def __init__(self):
|
||||
self.max_chars = 0
|
||||
self.voices = voices
|
||||
|
||||
def run(self, text, filepath, random_voice: bool = False):
|
||||
session = Session(profile_name="polly")
|
||||
polly = session.client("polly")
|
||||
if random_voice:
|
||||
voice = self.randomvoice()
|
||||
else:
|
||||
if not os.getenv("VOICE"):
|
||||
return ValueError(
|
||||
f"Please set the environment variable VOICE to a valid voice. options are: {voices}"
|
||||
)
|
||||
voice = str(os.getenv("AWS_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)
|
||||
|
||||
def randomvoice(self):
|
||||
return random.choice(self.voices)
|
@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
from typing import Tuple
|
||||
import re
|
||||
from os import getenv
|
||||
from mutagen.mp3 import MP3
|
||||
import translators as ts
|
||||
from rich.progress import track
|
||||
from moviepy.editor import AudioFileClip, CompositeAudioClip, concatenate_audioclips
|
||||
from utils.console import print_step, print_substep
|
||||
from utils.voice import sanitize_text
|
||||
|
||||
|
||||
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/mp3",
|
||||
max_length: int = 50,
|
||||
):
|
||||
self.tts_module = tts_module()
|
||||
self.reddit_object = reddit_object
|
||||
self.path = path
|
||||
self.max_length = max_length
|
||||
self.length = 0
|
||||
|
||||
def run(self) -> Tuple[int, int]:
|
||||
|
||||
Path(self.path).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# This file needs to be removed in case this post does not use post text, so that it wont appear in the final video
|
||||
try:
|
||||
Path(f"{self.path}/posttext.mp3").unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
print_step("Saving Text to MP3 files...")
|
||||
|
||||
self.call_tts("title", self.reddit_object["thread_title"])
|
||||
if (
|
||||
self.reddit_object["thread_post"] != ""
|
||||
and getenv("STORYMODE", "").casefold() == "true"
|
||||
):
|
||||
self.call_tts("posttext", self.reddit_object["thread_post"])
|
||||
|
||||
idx = None
|
||||
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:
|
||||
break
|
||||
if not self.tts_module.max_chars:
|
||||
self.call_tts(f"{idx}", comment["comment_body"])
|
||||
else:
|
||||
self.split_post(comment["comment_body"], idx)
|
||||
|
||||
print_substep("Saved Text to MP3 files successfully.", style="bold green")
|
||||
return self.length, idx
|
||||
|
||||
def split_post(self, text: str, idx: int) -> str:
|
||||
split_files = []
|
||||
split_text = [
|
||||
x.group().strip()
|
||||
for x in re.finditer(
|
||||
rf" *((.{{0,{self.tts_module.max_chars}}})(\.|.$))", text
|
||||
)
|
||||
]
|
||||
|
||||
idy = None
|
||||
for idy, text_cut in enumerate(split_text):
|
||||
# print(f"{idx}-{idy}: {text_cut}\n")
|
||||
self.call_tts(f"{idx}-{idy}.part", text_cut)
|
||||
split_files.append(AudioFileClip(f"{self.path}/{idx}-{idy}.part.mp3"))
|
||||
CompositeAudioClip([concatenate_audioclips(split_files)]).write_audiofile(
|
||||
f"{self.path}/{idx}.mp3", fps=44100, verbose=False, logger=None
|
||||
)
|
||||
|
||||
for i in range(0, idy + 1):
|
||||
# print(f"Cleaning up {self.path}/{idx}-{i}.part.mp3")
|
||||
Path(f"{self.path}/{idx}-{i}.part.mp3").unlink()
|
||||
|
||||
def call_tts(self, filename: str, text: str):
|
||||
self.tts_module.run(
|
||||
text=process_text(text), filepath=f"{self.path}/{filename}.mp3"
|
||||
)
|
||||
self.length += MP3(f"{self.path}/{filename}.mp3").info.length
|
||||
|
||||
|
||||
def process_text(text: str):
|
||||
lang = getenv("POSTLANG", "")
|
||||
new_text = sanitize_text(text)
|
||||
if lang:
|
||||
print_substep("Translating Text...")
|
||||
new_text = ts.google(text, to_language=lang)
|
||||
return new_text
|
@ -0,0 +1,53 @@
|
||||
import random
|
||||
import os
|
||||
import requests
|
||||
from requests.exceptions import JSONDecodeError
|
||||
|
||||
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 = 349
|
||||
self.voices = voices
|
||||
|
||||
def run(self, text, filepath, random_voice: bool = False):
|
||||
if random_voice:
|
||||
voice = self.randomvoice()
|
||||
else:
|
||||
if not os.getenv("VOICE"):
|
||||
return ValueError(
|
||||
f"Please set the environment variable VOICE to a valid voice. options are: {voices}"
|
||||
)
|
||||
voice = str(os.getenv("STREAMLABS_VOICE")).capitalize()
|
||||
body = {"voice": voice, "text": text, "service": "polly"}
|
||||
response = requests.post(self.url, data=body)
|
||||
try:
|
||||
voice_data = requests.get(response.json()["speak_url"])
|
||||
with open(filepath, "wb") as f:
|
||||
f.write(voice_data.content)
|
||||
except (KeyError, JSONDecodeError):
|
||||
print("Error occured calling Streamlabs Polly")
|
||||
|
||||
def randomvoice(self):
|
||||
return random.choice(self.voices)
|
Binary file not shown.
Binary file not shown.
@ -1,100 +1,68 @@
|
||||
# Main
|
||||
from utils.console import print_markdown
|
||||
from utils.console import print_step
|
||||
from utils.console import print_substep
|
||||
from rich.console import Console
|
||||
import time
|
||||
from reddit.subreddit import get_subreddit_threads
|
||||
from video_creation.background import download_background, chop_background_video
|
||||
from video_creation.voices import save_text_to_mp3
|
||||
from video_creation.screenshot_downloader import download_screenshots_of_reddit_posts
|
||||
from video_creation.final_video import make_final_video
|
||||
from utils.loader import Loader
|
||||
from dotenv import load_dotenv
|
||||
#!/usr/bin/env python
|
||||
|
||||
console = Console()
|
||||
from subprocess import Popen
|
||||
from dotenv import load_dotenv
|
||||
import os, time, shutil
|
||||
|
||||
configured = True
|
||||
REQUIRED_VALUES = [
|
||||
"REDDIT_CLIENT_ID",
|
||||
"REDDIT_CLIENT_SECRET",
|
||||
"REDDIT_USERNAME",
|
||||
"REDDIT_PASSWORD",
|
||||
"OPACITY",
|
||||
]
|
||||
from os import getenv, name
|
||||
from reddit.subreddit import get_subreddit_threads
|
||||
from utils.cleanup import cleanup
|
||||
from utils.console import print_markdown, print_step
|
||||
|
||||
# from utils.checker import envUpdate
|
||||
from video_creation.background import download_background, chop_background_video
|
||||
from video_creation.final_video import make_final_video
|
||||
from video_creation.screenshot_downloader import download_screenshots_of_reddit_posts
|
||||
from video_creation.voices import save_text_to_mp3
|
||||
from utils.checker import check_env
|
||||
|
||||
VERSION = 2.1
|
||||
print(
|
||||
"""
|
||||
██████╗ ███████╗██████╗ ██████╗ ██╗████████╗ ██╗ ██╗██╗██████╗ ███████╗ ██████╗ ███╗ ███╗ █████╗ ██╗ ██╗███████╗██████╗
|
||||
██╔══██╗██╔════╝██╔══██╗██╔══██╗██║╚══██╔══╝ ██║ ██║██║██╔══██╗██╔════╝██╔═══██╗ ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝██╔══██╗
|
||||
██████╔╝█████╗ ██║ ██║██║ ██║██║ ██║ ██║ ██║██║██║ ██║█████╗ ██║ ██║ ██╔████╔██║███████║█████╔╝ █████╗ ██████╔╝
|
||||
██╔══██╗██╔══╝ ██║ ██║██║ ██║██║ ██║ ╚██╗ ██╔╝██║██║ ██║██╔══╝ ██║ ██║ ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝ ██╔══██╗
|
||||
██║ ██║███████╗██████╔╝██████╔╝██║ ██║ ╚████╔╝ ██║██████╔╝███████╗╚██████╔╝ ██║ ╚═╝ ██║██║ ██║██║ ██╗███████╗██║ ██║
|
||||
╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═╝╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
|
||||
"""
|
||||
)
|
||||
# Modified by JasonLovesDoggo
|
||||
print_markdown(
|
||||
"### Thanks for using this tool! [Feel free to contribute to this project on GitHub!](https://lewismenelaws.com) If you have any questions, feel free to reach out to me on Twitter or submit a GitHub issue."
|
||||
"### Thanks for using this tool! [Feel free to contribute to this project on GitHub!](https://lewismenelaws.com) If you have any questions, feel free to reach out to me on Twitter or submit a GitHub issue. You can find solutions to many common problems in the [Documentation](https://luka-hietala.gitbook.io/documentation-for-the-reddit-bot/)"
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
Load .env file if exists. If it doesnt exist, print a warning and launch the setup wizard.
|
||||
If there is a .env file, check if the required variables are set. If not, print a warning and launch the setup wizard.
|
||||
|
||||
"""
|
||||
def main():
|
||||
if check_env() is not True:
|
||||
exit()
|
||||
load_dotenv()
|
||||
cleanup()
|
||||
|
||||
client_id = os.getenv("REDDIT_CLIENT_ID")
|
||||
client_secret = os.getenv("REDDIT_CLIENT_SECRET")
|
||||
username = os.getenv("REDDIT_USERNAME")
|
||||
password = os.getenv("REDDIT_PASSWORD")
|
||||
reddit2fa = os.getenv("REDDIT_2FA")
|
||||
|
||||
load_dotenv()
|
||||
|
||||
console.log("[bold green]Checking environment variables...")
|
||||
time.sleep(1)
|
||||
reddit_object = get_subreddit_threads()
|
||||
length, number_of_comments = save_text_to_mp3(reddit_object)
|
||||
download_screenshots_of_reddit_posts(reddit_object, number_of_comments)
|
||||
download_background()
|
||||
chop_background_video(length)
|
||||
make_final_video(number_of_comments, length)
|
||||
|
||||
|
||||
if not os.path.exists(".env"):
|
||||
configured = False
|
||||
console.log("[red] Your .env file is invalid, or was never created. Standby.")
|
||||
def run_many(times):
|
||||
for x in range(1, times + 1):
|
||||
print_step(
|
||||
f'on the {x}{("st" if x == 1 else ("nd" if x == 2 else ("rd" if x == 3 else "th")))} iteration of {times}'
|
||||
) # correct 1st 2nd 3rd 4th 5th....
|
||||
main()
|
||||
Popen("cls" if name == "nt" else "clear", shell=True).wait()
|
||||
|
||||
for val in REQUIRED_VALUES:
|
||||
#print(os.getenv(val))
|
||||
if val not in os.environ or not os.getenv(val):
|
||||
console.log(f'[bold red]Missing Variable: "{val}"')
|
||||
configured = False
|
||||
console.log(
|
||||
"[red]Looks like you need to set your Reddit credentials in the .env file. Please follow the instructions in the README.md file to set them up."
|
||||
)
|
||||
time.sleep(0.5)
|
||||
console.log(
|
||||
"[red]We can also launch the easy setup wizard. type yes to launch it, or no to quit the program."
|
||||
)
|
||||
setup_ask = input("Launch setup wizard? > ")
|
||||
if setup_ask == "yes":
|
||||
console.log("[bold green]Here goes nothing! Launching setup wizard...")
|
||||
time.sleep(0.5)
|
||||
os.system("python3 setup.py")
|
||||
|
||||
elif setup_ask == "no":
|
||||
console.print("[red]Exiting...")
|
||||
time.sleep(0.5)
|
||||
exit()
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
if getenv("TIMES_TO_RUN") and isinstance(int(getenv("TIMES_TO_RUN")), int):
|
||||
run_many(int(getenv("TIMES_TO_RUN")))
|
||||
else:
|
||||
console.print("[red]I don't understand that. Exiting...")
|
||||
time.sleep(0.5)
|
||||
exit()
|
||||
try:
|
||||
float(os.getenv("OPACITY"))
|
||||
except:
|
||||
console.log(
|
||||
f"[red]Please ensure that OPACITY is set between 0 and 1 in your .env file"
|
||||
)
|
||||
configured = False
|
||||
exit()
|
||||
console.log("[bold green]Enviroment Variables are set! Continuing...")
|
||||
|
||||
if configured:
|
||||
reddit_object = get_subreddit_threads()
|
||||
length, number_of_comments = save_text_to_mp3(reddit_object)
|
||||
download_screenshots_of_reddit_posts(
|
||||
reddit_object, number_of_comments, os.getenv("THEME", "light")
|
||||
)
|
||||
download_background()
|
||||
chop_background_video(length)
|
||||
final_video = make_final_video(number_of_comments)
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
print_markdown("## Clearing temp files")
|
||||
cleanup()
|
||||
exit()
|
||||
|
@ -1,83 +1,117 @@
|
||||
from rich.console import Console
|
||||
from utils.console import print_markdown, print_step, print_substep
|
||||
from dotenv import load_dotenv
|
||||
import re
|
||||
from os import getenv, environ
|
||||
|
||||
console = Console()
|
||||
import os, random, praw, re
|
||||
import praw
|
||||
|
||||
from utils.console import print_step, print_substep
|
||||
from utils.subreddit import get_subreddit_undone
|
||||
from utils.videos import check_done
|
||||
from praw.models import MoreComments
|
||||
|
||||
TEXT_WHITELIST = set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890")
|
||||
|
||||
|
||||
def textify(text):
|
||||
return "".join(filter(TEXT_WHITELIST.__contains__, text))
|
||||
|
||||
|
||||
def try_env(param, backup):
|
||||
try:
|
||||
return environ[param]
|
||||
except KeyError:
|
||||
return backup
|
||||
|
||||
|
||||
def get_subreddit_threads():
|
||||
global submission
|
||||
"""
|
||||
Returns a list of threads from the AskReddit subreddit.
|
||||
"""
|
||||
global submission
|
||||
print_substep("Logging into Reddit.")
|
||||
|
||||
load_dotenv()
|
||||
|
||||
if os.getenv("REDDIT_2FA", default="no").casefold() == "yes":
|
||||
content = {}
|
||||
if str(getenv("REDDIT_2FA")).casefold() == "yes":
|
||||
print(
|
||||
"\nEnter your two-factor authentication code from your authenticator app.\n"
|
||||
)
|
||||
code = input("> ")
|
||||
print()
|
||||
pw = os.getenv("REDDIT_PASSWORD")
|
||||
pw = getenv("REDDIT_PASSWORD")
|
||||
passkey = f"{pw}:{code}"
|
||||
else:
|
||||
passkey = os.getenv("REDDIT_PASSWORD")
|
||||
|
||||
content = {}
|
||||
passkey = getenv("REDDIT_PASSWORD")
|
||||
reddit = praw.Reddit(
|
||||
client_id=os.getenv("REDDIT_CLIENT_ID"),
|
||||
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
|
||||
user_agent="Accessing AskReddit threads",
|
||||
username=os.getenv("REDDIT_USERNAME"),
|
||||
password=passkey,
|
||||
client_id=getenv("REDDIT_CLIENT_ID"),
|
||||
client_secret=getenv("REDDIT_CLIENT_SECRET"),
|
||||
user_agent="Accessing Reddit threads",
|
||||
username=getenv("REDDIT_USERNAME"),
|
||||
passkey=passkey,
|
||||
check_for_async=False,
|
||||
)
|
||||
|
||||
# If the user specifies that he doesnt want a random thread, or if he doesn't insert the "RANDOM_THREAD" variable at all, ask the thread link
|
||||
if not os.getenv("RANDOM_THREAD") or os.getenv("RANDOM_THREAD") == "no":
|
||||
print_substep("Insert the full thread link:", style="bold green")
|
||||
thread_link = input()
|
||||
print_step(f"Getting the inserted thread...")
|
||||
submission = reddit.submission(url=thread_link)
|
||||
else:
|
||||
# Otherwise, picks a random thread from the inserted subreddit
|
||||
if os.getenv("SUBREDDIT"):
|
||||
subreddit = reddit.subreddit(re.sub(r"r\/", "", os.getenv("SUBREDDIT")))
|
||||
else:
|
||||
# ! Prompt the user to enter a subreddit
|
||||
try:
|
||||
subreddit = reddit.subreddit(
|
||||
re.sub(r"r\/", "",input("What subreddit would you like to pull from? "))
|
||||
"""
|
||||
Ask user for subreddit input
|
||||
"""
|
||||
print_step("Getting subreddit threads...")
|
||||
if not getenv(
|
||||
"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? ")
|
||||
)
|
||||
except ValueError:
|
||||
subreddit = reddit.subreddit("askreddit")
|
||||
print_substep("Subreddit not defined. Using AskReddit.")
|
||||
# removes the r/ from the input
|
||||
)
|
||||
except ValueError:
|
||||
subreddit = reddit.subreddit("askreddit")
|
||||
print_substep("Subreddit not defined. Using AskReddit.")
|
||||
else:
|
||||
print_substep(
|
||||
f"Using subreddit: r/{getenv('SUBREDDIT')} from environment variable config"
|
||||
)
|
||||
subreddit = reddit.subreddit(
|
||||
getenv("SUBREDDIT")
|
||||
) # Allows you to specify in .env. Done for automation purposes.
|
||||
|
||||
if getenv("POST_ID"):
|
||||
submission = reddit.submission(id=getenv("POST_ID"))
|
||||
else:
|
||||
threads = subreddit.hot(limit=25)
|
||||
submission = list(threads)[random.randrange(0, 25)]
|
||||
|
||||
print_substep(f"Video will be: {submission.title} :thumbsup:")
|
||||
console.log("Getting video comments...")
|
||||
try:
|
||||
content["thread_url"] = submission.url
|
||||
content["thread_title"] = submission.title
|
||||
content["thread_post"] = submission.selftext
|
||||
content["comments"] = []
|
||||
submission = get_subreddit_undone(threads, subreddit)
|
||||
submission = check_done(submission) # double checking
|
||||
if submission is None:
|
||||
return get_subreddit_threads() # submission already done. rerun
|
||||
upvotes = submission.score
|
||||
ratio = submission.upvote_ratio * 100
|
||||
num_comments = submission.num_comments
|
||||
|
||||
for top_level_comment in submission.comments:
|
||||
if not top_level_comment.stickied:
|
||||
if not top_level_comment.author == None:
|
||||
content["comments"].append(
|
||||
{
|
||||
"comment_body": top_level_comment.body,
|
||||
"comment_url": top_level_comment.permalink,
|
||||
"comment_id": top_level_comment.id,
|
||||
}
|
||||
)
|
||||
|
||||
except AttributeError as e:
|
||||
pass
|
||||
print_substep("Received AskReddit threads successfully.", style="bold green")
|
||||
print_substep(f"Video will be: {submission.title} :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")
|
||||
environ["VIDEO_TITLE"] = str(
|
||||
textify(submission.title)
|
||||
) # todo use global instend of env vars
|
||||
environ["VIDEO_ID"] = str(textify(submission.id))
|
||||
|
||||
content["thread_url"] = f"https://reddit.com{submission.permalink}"
|
||||
content["thread_title"] = submission.title
|
||||
content["thread_post"] = submission.selftext
|
||||
content["comments"] = []
|
||||
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 not top_level_comment.stickied:
|
||||
if len(top_level_comment.body) <= int(try_env("MAX_COMMENT_LENGTH", 500)):
|
||||
if not top_level_comment.author == None:
|
||||
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
|
||||
|
@ -1,8 +1,12 @@
|
||||
boto3==1.24.12
|
||||
botocore==1.27.12
|
||||
gTTS==2.2.4
|
||||
moviepy==1.0.3
|
||||
mutagen==1.45.1
|
||||
playwright==1.22.0
|
||||
praw==7.6.0
|
||||
python-dotenv==0.20.0
|
||||
pytube==12.1.0
|
||||
requests==2.28.0
|
||||
rich==12.4.4
|
||||
yt_dlp==2022.5.18
|
||||
translators==5.2.2
|
||||
|
@ -1 +1,2 @@
|
||||
docker run -v $(pwd)/out/:/app/assets -v $(pwd)/.env:/app/.env -it rvmt
|
||||
#!/bin/sh
|
||||
docker run -v $(pwd)/out/:/app/assets -v $(pwd)/.env:/app/.env -it rvmt
|
||||
|
@ -1,122 +1,168 @@
|
||||
"""
|
||||
|
||||
Setup Script for RedditVideoMakerBot
|
||||
#!/usr/bin/env python3
|
||||
# Setup Script for RedditVideoMakerBot
|
||||
|
||||
"""
|
||||
|
||||
# Imports
|
||||
import os
|
||||
import time
|
||||
import subprocess
|
||||
import re
|
||||
from utils.console import print_markdown
|
||||
from utils.console import print_step
|
||||
from utils.console import print_substep
|
||||
from rich.console import Console
|
||||
from utils.loader import Loader
|
||||
from os.path import exists
|
||||
from utils.console import handle_input
|
||||
|
||||
console = Console()
|
||||
|
||||
setup_done = exists(".setup-done-before")
|
||||
|
||||
if setup_done == True:
|
||||
console.log("[red]Setup was already completed! Please make sure you have to run this script again. If you have to, please delete the file .setup-done-before")
|
||||
exit()
|
||||
if os.path.isfile(".setup-done-before"):
|
||||
console.print(
|
||||
"[red]WARNING: Setup was already completed! Please make sure you have to run this script again. If that is such, delete the file .setup-done-before"
|
||||
)
|
||||
exit()
|
||||
|
||||
# These lines ensure the user:
|
||||
# - knows they are in setup mode
|
||||
# - knows that they are about to erase any other setup files/data.
|
||||
|
||||
print_step("Setup Assistant")
|
||||
|
||||
print_markdown(
|
||||
"### You're in the setup wizard. Ensure you're supposed to be here, then type yes to continue. If you're not sure, type no to quit."
|
||||
"### You're in the setup wizard. Ensure you're supposed to be here, then type yes to continue. If you're not sure, type no to quit."
|
||||
)
|
||||
|
||||
|
||||
# This Input is used to ensure the user is sure they want to continue.
|
||||
ensureSetupIsRequired = input("Are you sure you want to continue? > ").casefold()
|
||||
if ensureSetupIsRequired != "yes":
|
||||
console.print("[red]Exiting...")
|
||||
time.sleep(0.5)
|
||||
exit()
|
||||
else:
|
||||
# Again, let them know they are about to erase all other setup data.
|
||||
console.print("[bold red] This will overwrite your current settings. Are you sure you want to continue? [bold green]yes/no")
|
||||
overwriteSettings = input("Are you sure you want to continue? > ").casefold()
|
||||
if overwriteSettings != "yes":
|
||||
console.print("[red]Abort mission! Exiting...")
|
||||
time.sleep(0.5)
|
||||
exit()
|
||||
else:
|
||||
# Once they confirm, move on with the script.
|
||||
console.print("[bold green]Alright! Let's get started!")
|
||||
time.sleep(1)
|
||||
|
||||
console.log("Ensure you have the following ready to enter:")
|
||||
console.log("[bold green]Reddit Client ID")
|
||||
console.log("[bold green]Reddit Client Secret")
|
||||
console.log("[bold green]Reddit Username")
|
||||
console.log("[bold green]Reddit Password")
|
||||
console.log("[bold green]Reddit 2FA (yes or no)")
|
||||
console.log("[bold green]Opacity (range of 0-1, decimals are OK)")
|
||||
console.log("[bold green]Subreddit (without r/ or /r/)")
|
||||
console.log("[bold green]Theme (light or dark)")
|
||||
time.sleep(0.5)
|
||||
console.print("[green]If you don't have these, please follow the instructions in the README.md file to set them up.")
|
||||
console.print("[green]If you do have these, type yes to continue. If you dont, go ahead and grab those quickly and come back.")
|
||||
confirmUserHasCredentials = input("Are you sure you have the credentials? > ").casefold()
|
||||
if confirmUserHasCredentials != "yes":
|
||||
console.print("[red]I don't understand that.")
|
||||
console.print("[red]Exiting...")
|
||||
exit()
|
||||
else:
|
||||
console.print("[bold green]Alright! Let's get started!")
|
||||
time.sleep(1)
|
||||
if input("Are you sure you want to continue? > ").strip().casefold() != "yes":
|
||||
console.print("[red]Exiting...")
|
||||
exit()
|
||||
# This code is inaccessible if the prior check fails, and thus an else statement is unnecessary
|
||||
|
||||
"""
|
||||
|
||||
Begin the setup process.
|
||||
# Again, let them know they are about to erase all other setup data.
|
||||
console.print(
|
||||
"[bold red] This will overwrite your current settings. Are you sure you want to continue? [bold green]yes/no"
|
||||
)
|
||||
|
||||
|
||||
if input("Are you sure you want to continue? > ").strip().casefold() != "yes":
|
||||
console.print("[red]Abort mission! Exiting...")
|
||||
exit()
|
||||
# This is once again inaccessible if the prior checks fail
|
||||
# Once they confirm, move on with the script.
|
||||
console.print("[bold green]Alright! Let's get started!")
|
||||
|
||||
print()
|
||||
console.print("Ensure you have the following ready to enter:")
|
||||
console.print("[bold green]Reddit Client ID")
|
||||
console.print("[bold green]Reddit Client Secret")
|
||||
console.print("[bold green]Reddit Username")
|
||||
console.print("[bold green]Reddit Password")
|
||||
console.print("[bold green]Reddit 2FA (yes or no)")
|
||||
console.print("[bold green]Opacity (range of 0-1, decimals are OK)")
|
||||
console.print("[bold green]Subreddit (without r/ or /r/)")
|
||||
console.print("[bold green]Theme (light or dark)")
|
||||
console.print(
|
||||
"[green]If you don't have these, please follow the instructions in the README.md file to set them up."
|
||||
)
|
||||
console.print(
|
||||
"[green]If you do have these, type yes to continue. If you dont, go ahead and grab those quickly and come back."
|
||||
)
|
||||
print()
|
||||
|
||||
|
||||
if input("Are you sure you have the credentials? > ").strip().casefold() != "yes":
|
||||
console.print("[red]I don't understand that.")
|
||||
console.print("[red]Exiting...")
|
||||
exit()
|
||||
|
||||
|
||||
console.print("[bold green]Alright! Let's get started!")
|
||||
|
||||
# Begin the setup process.
|
||||
|
||||
console.print("Enter your credentials now.")
|
||||
client_id = handle_input(
|
||||
"Client ID > ",
|
||||
False,
|
||||
"[-a-zA-Z0-9._~+/]+=*",
|
||||
"That is somehow not a correct ID, try again.",
|
||||
12,
|
||||
30,
|
||||
"The ID should be over 12 and under 30 characters, double check your input.",
|
||||
)
|
||||
client_sec = handle_input(
|
||||
"Client Secret > ",
|
||||
False,
|
||||
"[-a-zA-Z0-9._~+/]+=*",
|
||||
"That is somehow not a correct secret, try again.",
|
||||
20,
|
||||
40,
|
||||
"The secret should be over 20 and under 40 characters, double check your input.",
|
||||
)
|
||||
user = handle_input(
|
||||
"Username > ",
|
||||
False,
|
||||
r"[_0-9a-zA-Z]+",
|
||||
"That is not a valid user",
|
||||
3,
|
||||
20,
|
||||
"A username HAS to be between 3 and 20 characters",
|
||||
)
|
||||
passw = handle_input("Password > ", False, ".*", "", 8, None, "Password too short")
|
||||
twofactor = handle_input(
|
||||
"2fa Enabled? (yes/no) > ",
|
||||
False,
|
||||
r"(yes)|(no)",
|
||||
"You need to input either yes or no",
|
||||
)
|
||||
opacity = handle_input(
|
||||
"Opacity? (range of 0-1) > ",
|
||||
float,
|
||||
".*",
|
||||
"You need to input a number between 0 and 1",
|
||||
0,
|
||||
1,
|
||||
"Your number is not between 0 and 1",
|
||||
)
|
||||
subreddit = handle_input(
|
||||
"Subreddit (without r/) > ",
|
||||
False,
|
||||
r"[_0-9a-zA-Z]+",
|
||||
"This subreddit cannot exist, make sure you typed it in correctly and removed the r/ (or /r/).",
|
||||
3,
|
||||
20,
|
||||
"A subreddit name HAS to be between 3 and 20 characters",
|
||||
)
|
||||
theme = handle_input(
|
||||
"Theme? (light or dark) > ",
|
||||
False,
|
||||
r"(light)|(dark)",
|
||||
"You need to input 'light' or 'dark'",
|
||||
)
|
||||
loader = Loader("Attempting to save your credentials...", "Done!").start()
|
||||
# you can also put a while loop here, e.g. while VideoIsBeingMade == True: ...
|
||||
console.print("Writing to the .env file...")
|
||||
with open(".env", "w") as f:
|
||||
f.write(
|
||||
f"""REDDIT_CLIENT_ID="{client_id}"
|
||||
REDDIT_CLIENT_SECRET="{client_sec}"
|
||||
REDDIT_USERNAME="{user}"
|
||||
REDDIT_PASSWORD="{passw}"
|
||||
REDDIT_2FA="{twofactor}"
|
||||
THEME="{theme}"
|
||||
SUBREDDIT="{subreddit}"
|
||||
OPACITY={opacity}
|
||||
"""
|
||||
)
|
||||
|
||||
console.log("Enter your credentials now.")
|
||||
cliID = input("Client ID > ")
|
||||
cliSec = input("Client Secret > ")
|
||||
user = input("Username > ")
|
||||
passw = input("Password > ")
|
||||
twofactor = input("2fa Enabled? (yes/no) > ")
|
||||
opacity = input("Opacity? (range of 0-1) > ")
|
||||
subreddit = input("Subreddit (without r/) > ")
|
||||
theme = input("Theme? (light or dark) > ")
|
||||
console.log("Attempting to save your credentials...")
|
||||
loader = Loader("Saving Credentials...", "Done!").start()
|
||||
# you can also put a while loop here, e.g. while VideoIsBeingMade == True: ...
|
||||
time.sleep(0.5)
|
||||
console.log("Removing old .env file...")
|
||||
os.remove(".env")
|
||||
time.sleep(0.5)
|
||||
console.log("Creating new .env file...")
|
||||
with open('.env', 'a') as f:
|
||||
f.write(f'REDDIT_CLIENT_ID="{cliID}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'REDDIT_CLIENT_SECRET="{cliSec}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'REDDIT_USERNAME="{user}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'REDDIT_PASSWORD="{passw}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'REDDIT_2FA="{twofactor}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'THEME="{theme}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'SUBREDDIT="{subreddit}"\n')
|
||||
time.sleep(0.5)
|
||||
f.write(f'OPACITY="{opacity}"\n')
|
||||
|
||||
with open('.setup-done-before', 'a') as f:
|
||||
f.write("This file blocks the setup assistant from running again. Delete this file to run setup again.")
|
||||
with open(".setup-done-before", "w") as f:
|
||||
f.write(
|
||||
"This file blocks the setup assistant from running again. Delete this file to run setup again."
|
||||
)
|
||||
|
||||
loader.stop()
|
||||
|
||||
console.log("[bold green]Setup Complete! Returning...")
|
||||
console.print("[bold green]Setup Complete! Returning...")
|
||||
|
||||
# Post-Setup: send message and try to run main.py again.
|
||||
os.system("python3 main.py")
|
||||
subprocess.call("python3 main.py", shell=True)
|
||||
|
@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich import box
|
||||
import re
|
||||
import dotenv
|
||||
from utils.console import handle_input
|
||||
|
||||
console = Console()
|
||||
|
||||
|
||||
def check_env() -> bool:
|
||||
"""Checks to see what's been put in .env
|
||||
|
||||
Returns:
|
||||
bool: Whether or not everything was put in properly
|
||||
"""
|
||||
if not os.path.exists(".env.template"):
|
||||
console.print("[red]Couldn't find .env.template. Unable to check variables.")
|
||||
return True
|
||||
if not os.path.exists(".env"):
|
||||
console.print("[red]Couldn't find the .env file, creating one now.")
|
||||
with open(".env", "x") as file:
|
||||
file.write("")
|
||||
success = True
|
||||
with open(".env.template", "r") as template:
|
||||
# req_envs = [env.split("=")[0] for env in template.readlines() if "=" in env]
|
||||
matching = {}
|
||||
explanations = {}
|
||||
bounds = {}
|
||||
types = {}
|
||||
oob_errors = {}
|
||||
examples = {}
|
||||
req_envs = []
|
||||
var_optional = False
|
||||
for line in template.readlines():
|
||||
if line.startswith("#") is not True and "=" in line and var_optional is not True:
|
||||
req_envs.append(line.split("=")[0])
|
||||
if "#" in line:
|
||||
examples[line.split("=")[0]] = "#".join(line.split("#")[1:]).strip()
|
||||
elif "#OPTIONAL" in line:
|
||||
var_optional = True
|
||||
elif line.startswith("#MATCH_REGEX "):
|
||||
matching[req_envs[-1]] = line.removeprefix("#MATCH_REGEX ")[:-1]
|
||||
var_optional = False
|
||||
elif line.startswith("#OOB_ERROR "):
|
||||
oob_errors[req_envs[-1]] = line.removeprefix("#OOB_ERROR ")[:-1]
|
||||
var_optional = False
|
||||
elif line.startswith("#RANGE "):
|
||||
bounds[req_envs[-1]] = tuple(
|
||||
map(
|
||||
lambda x: float(x) if x != "None" else None,
|
||||
line.removeprefix("#RANGE ")[:-1].split(":"),
|
||||
)
|
||||
)
|
||||
var_optional = False
|
||||
elif line.startswith("#MATCH_TYPE "):
|
||||
types[req_envs[-1]] = eval(line.removeprefix("#MATCH_TYPE ")[:-1].split()[0])
|
||||
var_optional = False
|
||||
elif line.startswith("#EXPLANATION "):
|
||||
explanations[req_envs[-1]] = line.removeprefix("#EXPLANATION ")[:-1]
|
||||
var_optional = False
|
||||
else:
|
||||
var_optional = False
|
||||
missing = set()
|
||||
incorrect = set()
|
||||
dotenv.load_dotenv()
|
||||
for env in req_envs:
|
||||
value = os.getenv(env)
|
||||
if value is None:
|
||||
missing.add(env)
|
||||
continue
|
||||
if env in matching.keys():
|
||||
re.match(matching[env], value) is None and incorrect.add(env)
|
||||
if env in bounds.keys() and env not in types.keys():
|
||||
len(value) >= bounds[env][0] or (
|
||||
len(bounds[env]) > 1 and bounds[env][1] >= len(value)
|
||||
) or incorrect.add(env)
|
||||
continue
|
||||
if env in types.keys():
|
||||
try:
|
||||
temp = types[env](value)
|
||||
if env in bounds.keys():
|
||||
(bounds[env][0] <= temp or incorrect.add(env)) and len(bounds[env]) > 1 and (
|
||||
bounds[env][1] >= temp or incorrect.add(env)
|
||||
)
|
||||
except ValueError:
|
||||
incorrect.add(env)
|
||||
|
||||
if len(missing):
|
||||
table = Table(
|
||||
title="Missing variables",
|
||||
highlight=True,
|
||||
show_lines=True,
|
||||
box=box.ROUNDED,
|
||||
border_style="#414868",
|
||||
header_style="#C0CAF5 bold",
|
||||
title_justify="left",
|
||||
title_style="#C0CAF5 bold",
|
||||
)
|
||||
table.add_column("Variable", justify="left", style="#7AA2F7 bold", no_wrap=True)
|
||||
table.add_column("Explanation", justify="left", style="#BB9AF7", no_wrap=False)
|
||||
table.add_column("Example", justify="center", style="#F7768E", no_wrap=True)
|
||||
table.add_column("Min", justify="right", style="#F7768E", no_wrap=True)
|
||||
table.add_column("Max", justify="left", style="#F7768E", no_wrap=True)
|
||||
for env in missing:
|
||||
table.add_row(
|
||||
env,
|
||||
explanations[env] if env in explanations.keys() else "No explanation given",
|
||||
examples[env] if env in examples.keys() else "",
|
||||
str(bounds[env][0]) if env in bounds.keys() and bounds[env][1] is not None else "",
|
||||
str(bounds[env][1])
|
||||
if env in bounds.keys() and len(bounds[env]) > 1 and bounds[env][1] is not None
|
||||
else "",
|
||||
)
|
||||
console.print(table)
|
||||
success = False
|
||||
if len(incorrect):
|
||||
table = Table(
|
||||
title="Incorrect variables",
|
||||
highlight=True,
|
||||
show_lines=True,
|
||||
box=box.ROUNDED,
|
||||
border_style="#414868",
|
||||
header_style="#C0CAF5 bold",
|
||||
title_justify="left",
|
||||
title_style="#C0CAF5 bold",
|
||||
)
|
||||
table.add_column("Variable", justify="left", style="#7AA2F7 bold", no_wrap=True)
|
||||
table.add_column("Current value", justify="left", style="#F7768E", no_wrap=False)
|
||||
table.add_column("Explanation", justify="left", style="#BB9AF7", no_wrap=False)
|
||||
table.add_column("Example", justify="center", style="#F7768E", no_wrap=True)
|
||||
table.add_column("Min", justify="right", style="#F7768E", no_wrap=True)
|
||||
table.add_column("Max", justify="left", style="#F7768E", no_wrap=True)
|
||||
for env in incorrect:
|
||||
table.add_row(
|
||||
env,
|
||||
os.getenv(env),
|
||||
explanations[env] if env in explanations.keys() else "No explanation given",
|
||||
str(types[env].__name__) if env in types.keys() else "str",
|
||||
str(bounds[env][0]) if env in bounds.keys() else "None",
|
||||
str(bounds[env][1]) if env in bounds.keys() and len(bounds[env]) > 1 else "None",
|
||||
)
|
||||
missing.add(env)
|
||||
console.print(table)
|
||||
success = False
|
||||
if success is True:
|
||||
return True
|
||||
console.print(
|
||||
"[green]Do you want to automatically overwrite incorrect variables and add the missing variables? (y/n)"
|
||||
)
|
||||
if not input().casefold().startswith("y"):
|
||||
console.print("[red]Aborting: Unresolved missing variables")
|
||||
return False
|
||||
if len(incorrect):
|
||||
with open(".env", "r+") as env_file:
|
||||
lines = []
|
||||
for line in env_file.readlines():
|
||||
line.split("=")[0].strip() not in incorrect and lines.append(line)
|
||||
env_file.seek(0)
|
||||
env_file.write("\n".join(lines))
|
||||
env_file.truncate()
|
||||
console.print("[green]Successfully removed incorrectly set variables from .env")
|
||||
with open(".env", "a") as env_file:
|
||||
for env in missing:
|
||||
env_file.write(
|
||||
env
|
||||
+ "="
|
||||
+ ('"' if env not in types.keys() else "")
|
||||
+ str(
|
||||
handle_input(
|
||||
"[#F7768E bold]" + env + "[#C0CAF5 bold]=",
|
||||
types[env] if env in types.keys() else False,
|
||||
matching[env] if env in matching.keys() else ".*",
|
||||
explanations[env]
|
||||
if env in explanations.keys()
|
||||
else "Incorrect input. Try again.",
|
||||
bounds[env][0] if env in bounds.keys() else None,
|
||||
bounds[env][1] if env in bounds.keys() and len(bounds[env]) > 1 else None,
|
||||
oob_errors[env] if env in oob_errors.keys() else "Input too long/short.",
|
||||
extra_info="[#C0CAF5 bold]⮶ "
|
||||
+ (
|
||||
explanations[env] if env in explanations.keys() else "No info available"
|
||||
),
|
||||
)
|
||||
)
|
||||
+ ('"' if env not in types.keys() else "")
|
||||
+ "\n"
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_env()
|
@ -0,0 +1,27 @@
|
||||
import os
|
||||
from os.path import exists
|
||||
|
||||
|
||||
def cleanup() -> int:
|
||||
"""Deletes all temporary assets in assets/temp
|
||||
|
||||
Returns:
|
||||
int: How many files were deleted
|
||||
"""
|
||||
if exists("./assets/temp"):
|
||||
count = 0
|
||||
files = [f for f in os.listdir(".") if f.endswith(".mp4") and "temp" in f.lower()]
|
||||
count += len(files)
|
||||
for f in files:
|
||||
os.remove(f)
|
||||
try:
|
||||
for file in os.listdir("./assets/temp/mp4"):
|
||||
count += 1
|
||||
os.remove("./assets/temp/mp4/" + file)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
for file in os.listdir("./assets/temp/mp3"):
|
||||
count += 1
|
||||
os.remove("./assets/temp/mp3/" + file)
|
||||
return count
|
||||
return 0
|
@ -0,0 +1,40 @@
|
||||
# write a class that takes .env file and parses it into a dictionary
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
DEFAULTS = {
|
||||
"SUBREDDIT": "AskReddit",
|
||||
"ALLOW_NSFW": "False",
|
||||
"POST_ID": "",
|
||||
"THEME": "DARK",
|
||||
"REDDIT_2FA": "no",
|
||||
"TIMES_TO_RUN": "",
|
||||
"MAX_COMMENT_LENGTH": "500",
|
||||
"OPACITY": "1",
|
||||
"VOICE": "en_us_001",
|
||||
"STORYMODE": "False",
|
||||
}
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self):
|
||||
self.raw = dotenv_values("../.env")
|
||||
self.load_attrs()
|
||||
|
||||
def __getattr__(self, attr): # code completion for attributes fix.
|
||||
return getattr(self, attr)
|
||||
|
||||
def load_attrs(self):
|
||||
for key, value in self.raw.items():
|
||||
self.add_attr(key, value)
|
||||
|
||||
def add_attr(self, key, value):
|
||||
if value is None or value == "":
|
||||
setattr(self, key, DEFAULTS[key])
|
||||
else:
|
||||
setattr(self, key, str(value))
|
||||
|
||||
|
||||
config = Config()
|
||||
|
||||
print(config.SUBREDDIT)
|
@ -0,0 +1,53 @@
|
||||
from typing import List
|
||||
import json
|
||||
from os import getenv
|
||||
from utils.console import print_substep
|
||||
|
||||
|
||||
def get_subreddit_undone(submissions: list, subreddit):
|
||||
"""_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
|
||||
"""
|
||||
"""
|
||||
recursively checks if the top submission in the list was already done.
|
||||
"""
|
||||
with open("./video_creation/data/videos.json", "r") as done_vids_raw:
|
||||
done_videos = json.load(done_vids_raw)
|
||||
for submission in submissions:
|
||||
if already_done(done_videos, submission):
|
||||
continue
|
||||
if submission.over_18:
|
||||
try:
|
||||
if getenv("ALLOW_NSFW").casefold() == "false":
|
||||
print_substep("NSFW Post Detected. Skipping...")
|
||||
continue
|
||||
except AttributeError:
|
||||
print_substep("NSFW settings not defined. Skipping NSFW post...")
|
||||
return submission
|
||||
print("all submissions have been done going by top submission order")
|
||||
return get_subreddit_undone(
|
||||
subreddit.top(time_filter="hour"), subreddit
|
||||
) # all of 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
|
@ -0,0 +1,30 @@
|
||||
import json
|
||||
from os import getenv
|
||||
|
||||
from utils.console import print_step
|
||||
|
||||
|
||||
def check_done(
|
||||
redditobj:dict[str],
|
||||
)->dict[str]|None: # 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 (dict[str]): Reddit object gotten from reddit/subreddit.py
|
||||
|
||||
Returns:
|
||||
dict[str]|None: Reddit object in args
|
||||
"""
|
||||
|
||||
with open("./video_creation/data/videos.json", "r") as done_vids_raw:
|
||||
done_videos = json.load(done_vids_raw)
|
||||
for video in done_videos:
|
||||
if video["id"] == str(redditobj):
|
||||
if getenv("POST_ID"):
|
||||
print_step(
|
||||
"You already have done this video but since it was declared specifically in the .env file the program will continue"
|
||||
)
|
||||
return redditobj
|
||||
print_step("Getting new post as the current one has already been done")
|
||||
return None
|
||||
return redditobj
|
@ -1,51 +1,84 @@
|
||||
import random
|
||||
from os import listdir, environ
|
||||
from pathlib import Path
|
||||
from random import randrange
|
||||
|
||||
from yt_dlp import YoutubeDL
|
||||
|
||||
from pathlib import Path
|
||||
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
|
||||
from moviepy.editor import VideoFileClip
|
||||
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
|
||||
from pytube import YouTube
|
||||
|
||||
from utils.console import print_step, print_substep
|
||||
|
||||
|
||||
def get_start_and_end_times(video_length, length_of_clip):
|
||||
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 beckground 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
|
||||
"""
|
||||
random_time = randrange(180, int(length_of_clip) - int(video_length))
|
||||
return random_time, random_time + video_length
|
||||
|
||||
def download_background():
|
||||
"""Downloads the background video from youtube.
|
||||
|
||||
Shoutout to: bbswitzer (https://www.youtube.com/watch?v=n_Dv4JMiwK8)
|
||||
"""
|
||||
|
||||
if not Path("assets/mp4/background.mp4").is_file():
|
||||
def download_background():
|
||||
"""Downloads the backgrounds/s video from YouTube."""
|
||||
Path("./assets/backgrounds/").mkdir(parents=True, exist_ok=True)
|
||||
background_options = [ # uri , filename , credit
|
||||
("https://www.youtube.com/watch?v=n_Dv4JMiwK8", "parkour.mp4", "bbswitzer"),
|
||||
# (
|
||||
# "https://www.youtube.com/watch?v=2X9QGY__0II",
|
||||
# "rocket_league.mp4",
|
||||
# "Orbital Gameplay",
|
||||
# ),
|
||||
]
|
||||
# note: make sure the file name doesn't include an - in it
|
||||
if not len(listdir("./assets/backgrounds")) >= len(
|
||||
background_options
|
||||
): # if there are any background videos not installed
|
||||
print_step(
|
||||
"We need to download the Minecraft background video. This is fairly large but it's only done once."
|
||||
"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 🙏 ")
|
||||
for uri, filename, credit in background_options:
|
||||
if Path(f"assets/backgrounds/{credit}-{filename}").is_file():
|
||||
continue # adds check to see if file exists before downloading
|
||||
print_substep(f"Downloading {filename} from {uri}")
|
||||
YouTube(uri).streams.filter(res="1080p").first().download(
|
||||
"assets/backgrounds", filename=f"{credit}-{filename}"
|
||||
)
|
||||
|
||||
print_substep("Downloading the background video... please be patient.")
|
||||
|
||||
ydl_opts = {
|
||||
"outtmpl": "assets/mp4/background.mp4",
|
||||
"merge_output_format": "mp4",
|
||||
}
|
||||
print_substep(
|
||||
"Background videos downloaded successfully! 🎉", style="bold green"
|
||||
)
|
||||
|
||||
with YoutubeDL(ydl_opts) as ydl:
|
||||
ydl.download("https://www.youtube.com/watch?v=n_Dv4JMiwK8")
|
||||
|
||||
print_substep("Background video downloaded successfully!", style="bold green")
|
||||
def chop_background_video(video_length:int):
|
||||
"""Generates the background footage to be used in the video and writes it to assets/temp/background.mp4
|
||||
|
||||
Args:
|
||||
video_length (int): Length of the clip where the background footage is to be taken out of
|
||||
"""
|
||||
print_step("Finding a spot in the backgrounds video to chop...✂️")
|
||||
choice = random.choice(listdir("assets/backgrounds"))
|
||||
environ["background_credit"] = choice.split("-")[0]
|
||||
|
||||
def chop_background_video(video_length):
|
||||
print_step("Finding a spot in the background video to chop...")
|
||||
background = VideoFileClip("assets/mp4/background.mp4")
|
||||
background = VideoFileClip(f"assets/backgrounds/{choice}")
|
||||
|
||||
start_time, end_time = get_start_and_end_times(video_length, background.duration)
|
||||
ffmpeg_extract_subclip(
|
||||
"assets/mp4/background.mp4",
|
||||
start_time,
|
||||
end_time,
|
||||
targetname="assets/mp4/clip.mp4",
|
||||
)
|
||||
try:
|
||||
ffmpeg_extract_subclip(
|
||||
f"assets/backgrounds/{choice}",
|
||||
start_time,
|
||||
end_time,
|
||||
targetname="assets/temp/background.mp4",
|
||||
)
|
||||
except (OSError, IOError): # ffmpeg issue see #348
|
||||
print_substep("FFMPEG issue. Trying again...")
|
||||
with VideoFileClip(f"assets/backgrounds/{choice}") as video:
|
||||
new = video.subclip(start_time, end_time)
|
||||
new.write_videofile("assets/temp/background.mp4")
|
||||
print_substep("Background video chopped successfully!", style="bold green")
|
||||
|
@ -1,8 +1,8 @@
|
||||
[
|
||||
{
|
||||
"name": "USER",
|
||||
"value": "eyJwcmVmcyI6eyJ0b3BDb250ZW50RGlzbWlzc2FsVGltZSI6MCwiZ2xvYmFsVGhlbWUiOiJSRURESVQiLCJuaWdodG1vZGUiOnRydWUsImNvbGxhcHNlZFRyYXlTZWN0aW9ucyI6eyJmYXZvcml0ZXMiOmZhbHNlLCJtdWx0aXMiOmZhbHNlLCJtb2RlcmF0aW5nIjpmYWxzZSwic3Vic2NyaXB0aW9ucyI6ZmFsc2UsInByb2ZpbGVzIjpmYWxzZX0sInRvcENvbnRlbnRUaW1lc0Rpc21pc3NlZCI6MH19",
|
||||
"domain": ".reddit.com",
|
||||
"path": "/"
|
||||
"name": "USER",
|
||||
"value": "eyJwcmVmcyI6eyJ0b3BDb250ZW50RGlzbWlzc2FsVGltZSI6MCwiZ2xvYmFsVGhlbWUiOiJSRURESVQiLCJuaWdodG1vZGUiOnRydWUsImNvbGxhcHNlZFRyYXlTZWN0aW9ucyI6eyJmYXZvcml0ZXMiOmZhbHNlLCJtdWx0aXMiOmZhbHNlLCJtb2RlcmF0aW5nIjpmYWxzZSwic3Vic2NyaXB0aW9ucyI6ZmFsc2UsInByb2ZpbGVzIjpmYWxzZX0sInRvcENvbnRlbnRUaW1lc0Rpc21pc3NlZCI6MH19",
|
||||
"domain": ".reddit.com",
|
||||
"path": "/"
|
||||
}
|
||||
]
|
||||
|
@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"name": "USER",
|
||||
"value": "eyJwcmVmcyI6eyJ0b3BDb250ZW50RGlzbWlzc2FsVGltZSI6MCwiZ2xvYmFsVGhlbWUiOiJSRURESVQiLCJuaWdodG1vZGUiOnRydWUsImNvbGxhcHNlZFRyYXlTZWN0aW9ucyI6eyJmYXZvcml0ZXMiOmZhbHNlLCJtdWx0aXMiOmZhbHNlLCJtb2RlcmF0aW5nIjpmYWxzZSwic3Vic2NyaXB0aW9ucyI6ZmFsc2UsInByb2ZpbGVzIjpmYWxzZX0sInRvcENvbnRlbnRUaW1lc0Rpc21pc3NlZCI6MH19",
|
||||
"domain": ".reddit.com",
|
||||
"path": "/"
|
||||
},
|
||||
{
|
||||
"name": "eu_cookie",
|
||||
"value": "{%22opted%22:true%2C%22nonessential%22:false}",
|
||||
"domain": ".reddit.com",
|
||||
"path": "/"
|
||||
}
|
||||
]
|
@ -0,0 +1,8 @@
|
||||
[
|
||||
{
|
||||
"name": "eu_cookie",
|
||||
"value": "{%22opted%22:true%2C%22nonessential%22:false}",
|
||||
"domain": ".reddit.com",
|
||||
"path": "/"
|
||||
}
|
||||
]
|
@ -0,0 +1 @@
|
||||
[]
|
@ -1,44 +1,67 @@
|
||||
from gtts import gTTS
|
||||
from pathlib import Path
|
||||
from mutagen.mp3 import MP3
|
||||
from utils.console import print_step, print_substep
|
||||
from rich.progress import track
|
||||
#!/usr/bin/env python
|
||||
|
||||
import os
|
||||
|
||||
def save_text_to_mp3(reddit_obj):
|
||||
"""Saves Text to MP3 files.
|
||||
from rich.console import Console
|
||||
|
||||
from TTS.engine_wrapper import TTSEngine
|
||||
from TTS.GTTS import GTTS
|
||||
from TTS.streamlabs_polly import StreamlabsPolly
|
||||
from TTS.aws_polly import AWSPolly
|
||||
from TTS.TikTok import TikTok
|
||||
|
||||
from utils.console import print_table, print_step
|
||||
|
||||
|
||||
console = Console()
|
||||
|
||||
TTSProviders = {
|
||||
"GoogleTranslate": GTTS,
|
||||
"AWSPolly": AWSPolly,
|
||||
"StreamlabsPolly": StreamlabsPolly,
|
||||
"TikTok": TikTok,
|
||||
}
|
||||
|
||||
VIDEO_LENGTH: int = 40 # secs
|
||||
|
||||
|
||||
def save_text_to_mp3(reddit_obj:dict[str])->tuple[int,int]:
|
||||
"""Saves text to MP3 files. Goes through the reddit_obj and generates the title MP3 file and a certain number of comments until the total amount of time exceeds VIDEO_LENGTH seconds.
|
||||
|
||||
Args:
|
||||
reddit_obj : The reddit object you received from the reddit API in the askreddit.py file.
|
||||
reddit_obj (dict[str]): 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)
|
||||
"""
|
||||
print_step("Saving Text to MP3 files...")
|
||||
length = 0
|
||||
|
||||
# Create a folder for the mp3 files.
|
||||
Path("assets/mp3").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
tts = gTTS(text=reddit_obj["thread_title"], lang="en", slow=False)
|
||||
tts.save(f"assets/mp3/title.mp3")
|
||||
length += MP3(f"assets/mp3/title.mp3").info.length
|
||||
|
||||
try:
|
||||
Path(f"assets/mp3/posttext.mp3").unlink()
|
||||
except OSError as e:
|
||||
pass
|
||||
|
||||
if reddit_obj["thread_post"] != "":
|
||||
tts = gTTS(text=reddit_obj["thread_post"], lang="en", slow=False)
|
||||
tts.save(f"assets/mp3/posttext.mp3")
|
||||
length += MP3(f"assets/mp3/posttext.mp3").info.length
|
||||
|
||||
for idx, comment in track(enumerate(reddit_obj["comments"]), "Saving..."):
|
||||
# ! Stop creating mp3 files if the length is greater than 50 seconds. This can be longer, but this is just a good starting point
|
||||
if length > 50:
|
||||
break
|
||||
tts = gTTS(text=comment["comment_body"], lang="en", slow=False)
|
||||
tts.save(f"assets/mp3/{idx}.mp3")
|
||||
length += MP3(f"assets/mp3/{idx}.mp3").info.length
|
||||
|
||||
print_substep("Saved Text to MP3 files successfully.", style="bold green")
|
||||
# ! Return the index so we know how many screenshots of comments we need to make.
|
||||
return length, idx
|
||||
|
||||
env = os.getenv("TTSCHOICE", "")
|
||||
if env.casefold() in map(lambda _: _.casefold(), TTSProviders):
|
||||
text_to_mp3 = TTSEngine(
|
||||
get_case_insensitive_key_value(TTSProviders, env), reddit_obj
|
||||
)
|
||||
else:
|
||||
choice = ""
|
||||
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,
|
||||
)
|
||||
|
Loading…
Reference in new issue