Repository: FujiwaraChoki/MoneyPrinterV2 Branch: main Commit: aa1d8f645022 Files: 34 Total size: 163.3 KB Directory structure: gitextract_fa8ip_7i/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .python-version ├── AGENTS.md ├── CLAUDE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets/ │ └── banner.txt ├── config.example.json ├── docs/ │ ├── AffiliateMarketing.md │ ├── Configuration.md │ ├── Roadmap.md │ ├── TwitterBot.md │ └── YouTube.md ├── requirements.txt ├── scripts/ │ ├── preflight_local.py │ ├── setup_local.sh │ └── upload_video.sh └── src/ ├── art.py ├── cache.py ├── classes/ │ ├── AFM.py │ ├── Outreach.py │ ├── Tts.py │ ├── Twitter.py │ └── YouTube.py ├── config.py ├── constants.py ├── cron.py ├── llm_provider.py ├── main.py ├── status.py └── utils.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [FujiwaraChoki] ================================================ FILE: .gitignore ================================================ __pycache__ config.json .mp/ venv/ Songs/ google-maps-scraper-0.9.7/ niche.txt *.exe auto.sh .DS_Store ================================================ FILE: .python-version ================================================ 3.12 ================================================ FILE: AGENTS.md ================================================ # Repository Guidelines ## Project Structure & Module Organization - `src/` contains the application code. Use `src/main.py` as the interactive entrypoint. - `src/classes/` holds provider-specific components (for example `YouTube.py`, `Twitter.py`, `Tts.py`, `AFM.py`, `Outreach.py`). - Shared utilities and configuration live in modules like `src/config.py`, `src/utils.py`, `src/cache.py`, and `src/constants.py`. - `scripts/` contains helper workflows such as setup, preflight checks, and upload helpers. - `docs/` contains feature documentation; `assets/` and `fonts/` contain static resources. ## Build, Test, and Development Commands - `bash scripts/setup_local.sh`: bootstrap local development (creates `venv`, installs deps, seeds `config.json`, runs preflight). - `source venv/bin/activate && pip install -r requirements.txt`: manual dependency install/update. - `python3 scripts/preflight_local.py`: validate local provider/config readiness before running tasks. - `python3 src/main.py`: start the CLI app. - `bash scripts/upload_video.sh`: run direct script-based upload flow from repo root. ## Coding Style & Naming Conventions - Target Python 3.12 (project requirement in `README.md`). - Use 4-space indentation and follow existing Python conventions: - `snake_case` for functions/variables - `PascalCase` for classes - `UPPER_SNAKE_CASE` for constants - Keep new business logic in focused modules under `src/`; keep provider/integration code in `src/classes/`. - Prefer small, explicit functions and preserve existing CLI-first behavior. ## Testing Guidelines - There is currently no enforced automated test suite or coverage threshold. - Minimum validation for changes: - Run `python3 scripts/preflight_local.py` - Smoke-test impacted flows via `python3 src/main.py` - When adding tests, place them in a top-level `tests/` directory with names like `test_.py`. ## Commit & Pull Request Guidelines - Follow the existing commit style: imperative summaries like `Fix ...`, `Update ...`, optionally with issue refs (for example `(#128)`). - Open PRs against `main`. - Link each PR to an issue, keep scope to one feature/fix, and use a clear title + description. - Mark not-ready PRs with `WIP` and remove it when ready for review. ## Security & Configuration Tips - Treat `config.json` as environment-specific; do not commit real API keys or private profile paths. - Start from `config.example.json` and prefer environment variables where supported (for example `GEMINI_API_KEY`). ================================================ FILE: CLAUDE.md ================================================ # CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview MoneyPrinterV2 (MPV2) is a Python 3.12 CLI tool that automates four online workflows: 1. **YouTube Shorts** — generate video (LLM script → TTS → images → MoviePy composite) and upload via Selenium 2. **Twitter/X Bot** — generate and post tweets via Selenium 3. **Affiliate Marketing** — scrape Amazon product info, generate pitch, share on Twitter 4. **Local Business Outreach** — scrape Google Maps (Go binary), extract emails, send cold outreach via SMTP There is no web UI, no REST API, no test suite, no CI, and no linting config. ## Running the Application ```bash # First-time setup cp config.example.json config.json # then fill in values python -m venv venv && source venv/bin/activate pip install -r requirements.txt # macOS quick setup (auto-configures Ollama, ImageMagick, Firefox profile) bash scripts/setup_local.sh # Preflight check (validates services are reachable) python scripts/preflight_local.py # Run python src/main.py ``` The app **must** be run from the project root. `python src/main.py` adds `src/` to `sys.path`, so all imports use bare module names (e.g., `from config import *`, not `from src.config import *`). ## Architecture ### Entry Points - `src/main.py` — interactive menu loop (primary) - `src/cron.py` — headless runner invoked by the scheduler as a subprocess: `python src/cron.py ` ### Provider Pattern Two service categories use a string-based dispatch pattern configured in `config.json`: | Category | Config key | Options | |---|---|---| | LLM | `ollama_model` | Ollama (via `ollama` Python SDK). If empty, user picks from available models at startup. | | Image gen | — | `nanobanana2` (Gemini image API) | | STT | `stt_provider` | `local_whisper`, `third_party_assemblyai` | LLM always uses the local Ollama server. Image generation always uses Nano Banana 2. ### Key Modules - **`src/llm_provider.py`** — unified `generate_text(prompt)` function using the Ollama Python SDK - **`src/config.py`** — 30+ getter functions, each re-reads `config.json` on every call (no caching). `ROOT_DIR` = project root, computed as `os.path.dirname(sys.path[0])` - **`src/cache.py`** — JSON file persistence in `.mp/` directory (accounts, videos, posts, products) - **`src/constants.py`** — menu strings, Selenium selectors (YouTube Studio, X.com, Amazon) - **`src/classes/YouTube.py`** — most complex class; full pipeline: topic → script → metadata → image prompts → images → TTS → subtitles → MoviePy combine → Selenium upload - **`src/classes/Twitter.py`** — Selenium automation against x.com - **`src/classes/AFM.py`** — Amazon scraping + LLM pitch generation - **`src/classes/Outreach.py`** — Google Maps scraper (requires Go) + email sending via yagmail - **`src/classes/Tts.py`** — KittenTTS wrapper ### Data Storage All persistent state lives in `.mp/` at the project root as JSON files (`youtube.json`, `twitter.json`, `afm.json`). This directory also serves as scratch space for temporary WAV, PNG, SRT, and MP4 files — non-JSON files are cleaned on each run by `rem_temp_files()`. ### Browser Automation Selenium uses pre-authenticated Firefox profiles (never handles login). The profile path is stored per-account in the cache JSON and also in `config.json` as a default. ### CRON Scheduling Uses Python's `schedule` library (in-process, not OS cron). The scheduled job spawns `subprocess.run(["python", "src/cron.py", platform, account_id])`. ## Configuration All config lives in `config.json` at the project root. See `config.example.json` for the full template and `docs/Configuration.md` for reference. Key external dependencies to configure: - **ImageMagick** — required for MoviePy subtitle rendering (`imagemagick_path`) - **Firefox profile** — must be pre-logged-in to target platforms (`firefox_profile`) - **Ollama** — for LLM text generation (via `ollama` Python SDK) - **Nano Banana 2** — for image generation (Gemini image API) - **Go** — only needed for Outreach (Google Maps scraper) ## Contributing PRs go against `main`. One feature/fix per PR. Open an issue first. Use `WIP` label for in-progress PRs. ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Code of Conduct Our values guide us in our day-to-day interactions and decision-making. Our open source projects are no exception. Trust, respect, collaboration and transparency are core values we believe should live and breathe within our projects. Our community welcomes participants from around the world with different experiences, unique perspectives, and great ideas to share. ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, 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. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Attempting collaboration before conflict - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - Violence, threats of violence, or inciting others to commit self-harm - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, intentionally spreading misinformation, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Abuse of the reporting process to intentionally harass or exclude others - Advocating for, or encouraging, any of the above behavior - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers 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, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting us anonymously through [our discord](https://dsc.gg/fuji-community). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. If you are unsure whether an incident is a violation, or whether the space where the incident took place is covered by our Code of Conduct, **we encourage you to still report it**. We would prefer to have a few extra reports where we decide to take no action, than to leave an incident go unnoticed and unresolved that may result in an individual or group to feel like they can no longer participate in the community. Reports deemed as not a violation will also allow us to improve our Code of Conduct and processes surrounding it. If you witness a dangerous situation or someone in distress, we encourage you to report even if you are only an observer. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html). ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing MoneyPrinterV2 is an open source project and we encourage contributions. However, we ask that you follow these guidelines when opening a Pull Request (PR): 1. **The `main` branch is the default branch.** All PRs should be opened against the `main` branch. 2. **All PRs should be opened against an issue.** If there is no issue for your PR, please open one first and then open a PR against it. 3. **All PRs should be opened with a clear title and description.** The title should be a short description of the changes and the description should be a more detailed explanation of the changes. 4. **Only one feature or bug fix per PR.** If you have multiple changes, please open multiple PRs. 5. **All PRs should be opened with the `WIP` label if they are not ready to be merged.** If your PR is not ready to be merged, please open it with the `WIP` label and remove the label when it is ready to be merged. If you have any questions about contributing, please open an issue and ask. We are happy to help you get started. # Code of Conduct We have adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be tolerated. ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 2024 FujiwaraChoki This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # MoneyPrinter V2 > ♥︎ **Sponsor**: The Best AI Chat App: [shiori.ai](https://www.shiori.ai) --- > 𝕏 Also, follow me on X: [@DevBySami](https://x.com/DevBySami). [![madewithlove](https://img.shields.io/badge/made_with-%E2%9D%A4-red?style=for-the-badge&labelColor=orange)](https://github.com/FujiwaraChoki/MoneyPrinterV2) [![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-Donate-brightgreen?logo=buymeacoffee)](https://www.buymeacoffee.com/fujicodes) [![GitHub license](https://img.shields.io/github/license/FujiwaraChoki/MoneyPrinterV2?style=for-the-badge)](https://github.com/FujiwaraChoki/MoneyPrinterV2/blob/main/LICENSE) [![GitHub issues](https://img.shields.io/github/issues/FujiwaraChoki/MoneyPrinterV2?style=for-the-badge)](https://github.com/FujiwaraChoki/MoneyPrinterV2/issues) [![GitHub stars](https://img.shields.io/github/stars/FujiwaraChoki/MoneyPrinterV2?style=for-the-badge)](https://github.com/FujiwaraChoki/MoneyPrinterV2/stargazers) [![Discord](https://img.shields.io/discord/1134848537704804432?style=for-the-badge)](https://dsc.gg/fuji-community) An Application that automates the process of making money online. MPV2 (MoneyPrinter Version 2) is, as the name suggests, the second version of the MoneyPrinter project. It is a complete rewrite of the original project, with a focus on a wider range of features and a more modular architecture. > **Note:** MPV2 needs Python 3.12 to function effectively. > Watch the YouTube video [here](https://youtu.be/wAZ_ZSuIqfk) ## Features - [x] Twitter Bot (with CRON Jobs => `scheduler`) - [x] YouTube Shorts Automater (with CRON Jobs => `scheduler`) - [x] Affiliate Marketing (Amazon + Twitter) - [x] Find local businesses & cold outreach ## Versions MoneyPrinter has different versions for multiple languages developed by the community for the community. Here are some known versions: - Chinese: [MoneyPrinterTurbo](https://github.com/harry0703/MoneyPrinterTurbo) If you would like to submit your own version/fork of MoneyPrinter, please open an issue describing the changes you made to the fork. ## Installation > ⚠️ If you are planning to reach out to scraped businesses per E-Mail, please first install the [Go Programming Language](https://golang.org/). ```bash git clone https://github.com/FujiwaraChoki/MoneyPrinterV2.git cd MoneyPrinterV2 # Copy Example Configuration and fill out values in config.json cp config.example.json config.json # Create a virtual environment python -m venv venv # Activate the virtual environment - Windows .\venv\Scripts\activate # Activate the virtual environment - Unix source venv/bin/activate # Install the requirements pip install -r requirements.txt ``` ## Usage ```bash # Run the application python src/main.py ``` ## Documentation All relevant document can be found [here](docs/). ## Scripts For easier usage, there are some scripts in the `scripts` directory, that can be used to directly access the core functionality of MPV2, without the need of user interaction. All scripts need to be run from the root directory of the project, e.g. `bash scripts/upload_video.sh`. ## Contributing Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. Check out [docs/Roadmap.md](docs/Roadmap.md) for a list of features that need to be implemented. ## Code of Conduct Please read [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for details on our code of conduct, and the process for submitting pull requests to us. ## License MoneyPrinterV2 is licensed under `Affero General Public License v3.0`. See [LICENSE](LICENSE) for more information. ## Acknowledgments - [KittenTTS](https://github.com/KittenML/KittenTTS) - [gpt4free](https://github.com/xtekky/gpt4free) ## Disclaimer This project is for educational purposes only. The author will not be responsible for any misuse of the information provided. All the information on this website is published in good faith and for general information purpose only. The author does not make any warranties about the completeness, reliability, and accuracy of this information. Any action you take upon the information you find on this website (FujiwaraChoki/MoneyPrinterV2), is strictly at your own risk. The author will not be liable for any losses and/or damages in connection with the use of our website. ================================================ FILE: assets/banner.txt ================================================ __ __ _____ _ _ __ _____ | \/ | | __ \ (_) | | \ \ / /__ \ | \ / | ___ _ __ ___ _ _| |__) | __ _ _ __ | |_ ___ _ __ \ \ / / ) | | |\/| |/ _ \| '_ \ / _ \ | | | ___/ '__| | '_ \| __/ _ \ '__| \ \/ / / / | | | | (_) | | | | __/ |_| | | | | | | | | | || __/ | \ / / /_ |_| |_|\___/|_| |_|\___|\__, |_| |_| |_|_| |_|\__\___|_| \/ |____| __/ | |___/ ================================================ FILE: config.example.json ================================================ { "verbose": true, "firefox_profile": "", "headless": false, "ollama_base_url": "http://127.0.0.1:11434", "ollama_model": "", "twitter_language": "English", "nanobanana2_api_base_url": "https://generativelanguage.googleapis.com/v1beta", "nanobanana2_api_key": "", "nanobanana2_model": "gemini-3.1-flash-image-preview", "nanobanana2_aspect_ratio": "9:16", "threads": 2, "zip_url": "", "is_for_kids": false, "google_maps_scraper": "https://github.com/gosom/google-maps-scraper/archive/refs/tags/v0.9.7.zip", "email": { "smtp_server": "smtp.gmail.com", "smtp_port": 587, "username": "", "password": "" }, "google_maps_scraper_niche": "", "scraper_timeout": 300, "outreach_message_subject": "I have a question...", "outreach_message_body_file": "outreach_message.html", "stt_provider": "local_whisper", "whisper_model": "base", "whisper_device": "auto", "whisper_compute_type": "int8", "assembly_ai_api_key": "", "tts_voice": "Jasper", "font": "bold_font.ttf", "imagemagick_path": "Path to magick.exe or on linux/macOS just /usr/bin/convert", "script_sentence_length": 4 } ================================================ FILE: docs/AffiliateMarketing.md ================================================ # AFM This class is responsible for the Affiliate Marketing part of MPV2. It uses Ollama (as all other classes) as its way to utilize the power of LLMs, in this case, to generate tweets, based on information about an **Amazon Product**. MPV2 will scrape the page of the product, and save the **product title**, and **product features**, thus having enough information to be able to create a pitch for the product, and post it on Twitter. ## Relevant Configuration In your `config.json`, you need the following attributes filled out, so that the bot can function correctly. ```json { "firefox_profile": "The path to your Firefox profile (used to log in to Twitter)", "headless": true, "ollama_base_url": "http://127.0.0.1:11434", "threads": 4 } ``` ## Roadmap Here are some features that are planned for the future: - [ ] Scrape more information about the product, to be able to create a more detailed pitch. - [ ] Join online communities related to the product, and post a pitch (with a link to the product) there. - [ ] Reply to tweets that are related to the product, with a pitch for the product. ================================================ FILE: docs/Configuration.md ================================================ # Configuration All your configurations will be in a file in the root directory, called `config.json`, which is a copy of `config.example.json`. You can change the values in `config.json` to your liking. ## Values - `verbose`: `boolean` - If `true`, the application will print out more information. - `firefox_profile`: `string` - The path to your Firefox profile. This is used to use your Social Media Accounts without having to log in every time you run the application. - `headless`: `boolean` - If `true`, the application will run in headless mode. This means that the browser will not be visible. - `ollama_base_url`: `string` - Base URL of your local Ollama server (default: `http://127.0.0.1:11434`). - `ollama_model`: `string` - Ollama model to use for text generation (e.g. `llama3.2:3b`). If empty, the app queries Ollama at startup and lets you pick from the available models interactively. - `twitter_language`: `string` - The language that will be used to generate & post tweets. - `nanobanana2_api_base_url`: `string` - Nano Banana 2 API base URL (default: `https://generativelanguage.googleapis.com/v1beta`). - `nanobanana2_api_key`: `string` - API key for Nano Banana 2 (Gemini image API). If empty, MPV2 falls back to environment variable `GEMINI_API_KEY`. - `nanobanana2_model`: `string` - Nano Banana 2 model name (default: `gemini-3.1-flash-image-preview`). - `nanobanana2_aspect_ratio`: `string` - Aspect ratio for generated images (default: `9:16`). - `threads`: `number` - The amount of threads that will be used to execute operations, e.g. writing to a file using MoviePy. - `is_for_kids`: `boolean` - If `true`, the application will upload the video to YouTube Shorts as a video for kids. - `google_maps_scraper`: `string` - The URL to the Google Maps scraper. This will be used to scrape Google Maps for local businesses. It is recommended to use the default value. - `zip_url`: `string` - The URL to the ZIP file that contains the to be used Songs for the YouTube Shorts Automater. - `email`: `object`: - `smtp_server`: `string` - Your SMTP server. - `smtp_port`: `number` - The port of your SMTP server. - `username`: `string` - Your email address. - `password`: `string` - Your email password. - `google_maps_scraper_niche`: `string` - The niche you want to scrape Google Maps for. - `scraper_timeout`: `number` - The timeout for the Google Maps scraper. - `outreach_message_subject`: `string` - The subject of your outreach message. `{{COMPANY_NAME}}` will be replaced with the company name. - `outreach_message_body_file`: `string` - The file that contains the body of your outreach message, should be HTML. `{{COMPANY_NAME}}` will be replaced with the company name. - `stt_provider`: `string` - Provider for subtitle transcription. Default is `local_whisper`. Options: * `local_whisper` * `third_party_assemblyai` - `whisper_model`: `string` - Whisper model for local transcription (for example `base`, `small`, `medium`, `large-v3`). - `whisper_device`: `string` - Device for local Whisper (`auto`, `cpu`, `cuda`). - `whisper_compute_type`: `string` - Compute type for local Whisper (`int8`, `float16`, etc.). - `assembly_ai_api_key`: `string` - Your Assembly AI API key. Get yours from [here](https://www.assemblyai.com/app/). - `tts_voice`: `string` - Voice for KittenTTS text-to-speech. Default is `Jasper`. Options: `Bella`, `Jasper`, `Luna`, `Bruno`, `Rosie`, `Hugo`, `Kiki`, `Leo`. - `font`: `string` - The font that will be used to generate images. This should be a `.ttf` file in the `fonts/` directory. - `imagemagick_path`: `string` - The path to the ImageMagick binary. This is used by MoviePy to manipulate images. Install ImageMagick from [here](https://imagemagick.org/script/download.php) and set the path to the `magick.exe` on Windows, or on Linux/MacOS the path to `convert` (usually /usr/bin/convert). - `script_sentence_length`: `number` - The number of sentences in the generated video script (default: `4`). ## Example ```json { "verbose": true, "firefox_profile": "", "headless": false, "ollama_base_url": "http://127.0.0.1:11434", "ollama_model": "", "twitter_language": "English", "nanobanana2_api_base_url": "https://generativelanguage.googleapis.com/v1beta", "nanobanana2_api_key": "", "nanobanana2_model": "gemini-3.1-flash-image-preview", "nanobanana2_aspect_ratio": "9:16", "threads": 2, "zip_url": "", "is_for_kids": false, "google_maps_scraper": "https://github.com/gosom/google-maps-scraper/archive/refs/tags/v0.9.7.zip", "email": { "smtp_server": "smtp.gmail.com", "smtp_port": 587, "username": "", "password": "" }, "google_maps_scraper_niche": "", "scraper_timeout": 300, "outreach_message_subject": "I have a question...", "outreach_message_body_file": "outreach_message.html", "stt_provider": "local_whisper", "whisper_model": "base", "whisper_device": "auto", "whisper_compute_type": "int8", "assembly_ai_api_key": "", "tts_voice": "Jasper", "font": "bold_font.ttf", "imagemagick_path": "Path to magick.exe or on linux/macOS just /usr/bin/convert", "script_sentence_length": 4 } ``` ## Environment Variable Fallbacks - `GEMINI_API_KEY`: used when `nanobanana2_api_key` is empty. Example: ```bash export GEMINI_API_KEY="your_api_key_here" ``` ================================================ FILE: docs/Roadmap.md ================================================ # MPV2 Roadmap This document outlines the features that need to be implemented in MPV2. ## Features - [ ] Automated Cold Calling - [ ] Item Flipping (such as sneakers) - [ ] Create a Short based on long-form content - [ ] Subtitles for Shorts ## Adding a new feature If you want to add a new feature to MPV2, please create a new issue and label it with `enhancement`. After that, create a new branch and start working on the feature. Once you are done, create a pull request and assign it to the issue you created earlier. ## Contributing Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. ================================================ FILE: docs/TwitterBot.md ================================================ # Twitter Bot This bot is designed to automate the process of growing a Twitter account. Once you created a new account, provide the path to the Firefox Profile and the bot will start posting tweets based on the subject you provided during the account creation. ## Relevant Configuration In your `config.json`, you need the following attributes filled out, so that the bot can function correctly. ```json { "twitter_language": "Any Language, formatting doesn't matter", "headless": true, "llm": "The Large Language Model you want to use, check Configuration.md for more information", } ``` ================================================ FILE: docs/YouTube.md ================================================ # YouTube Shorts Automater MPV2 uses a similar implementation of V1 (see [MPV1](https://github.com/FujiwaraChoki/MoneyPrinter)), to generate Video-Files and upload them to YouTube Shorts. In contrast to V1, V2 uses AI generated images as the visuals for the video, instead of using stock footage. This makes the videos more unique and less likely to be flagged by YouTube. V2 also supports music right from the get-go. ## Relevant Configuration In your `config.json`, you need the following attributes filled out, so that the bot can function correctly. ```json { "firefox_profile": "The path to your Firefox profile (used to log in to YouTube)", "headless": true, "llm": "The Large Language Model you want to use to generate the video script.", "image_model": "What AI Model you want to use to generate images.", "threads": 4, "is_for_kids": true } ``` ## Roadmap Here are some features that are planned for the future: - [ ] Subtitles (using either AssemblyAI or locally assembling them) ================================================ FILE: requirements.txt ================================================ wheel termcolor schedule kittentts @ https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl soundfile prettytable webdriver_manager selenium_firefox selenium ollama moviepy Pillow>=10.0.0 yagmail assemblyai faster-whisper srt_equalizer undetected_chromedriver platformdirs ================================================ FILE: scripts/preflight_local.py ================================================ #!/usr/bin/env python3 import json import os import sys from typing import Tuple import requests ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONFIG_PATH = os.path.join(ROOT_DIR, "config.json") def ok(msg: str) -> None: print(f"[OK] {msg}") def warn(msg: str) -> None: print(f"[WARN] {msg}") def fail(msg: str) -> None: print(f"[FAIL] {msg}") def check_url(url: str, timeout: int = 3) -> Tuple[bool, str]: try: response = requests.get(url, timeout=timeout) return True, f"HTTP {response.status_code}" except Exception as exc: return False, str(exc) def main() -> int: if not os.path.exists(CONFIG_PATH): fail(f"Missing config file: {CONFIG_PATH}") return 1 with open(CONFIG_PATH, "r", encoding="utf-8") as f: cfg = json.load(f) failures = 0 stt_provider = str(cfg.get("stt_provider", "local_whisper")).lower() ok(f"stt_provider={stt_provider}") imagemagick_path = cfg.get("imagemagick_path", "") if imagemagick_path and os.path.exists(imagemagick_path): ok(f"imagemagick_path exists: {imagemagick_path}") else: warn( "imagemagick_path is not set to a valid executable path. " "MoviePy subtitle rendering may fail." ) firefox_profile = cfg.get("firefox_profile", "") if firefox_profile: if os.path.isdir(firefox_profile): ok(f"firefox_profile exists: {firefox_profile}") else: warn(f"firefox_profile does not exist: {firefox_profile}") else: warn("firefox_profile is empty. Twitter/YouTube automation requires this.") # Ollama (LLM) base = str(cfg.get("ollama_base_url", "http://127.0.0.1:11434")).rstrip("/") reachable, detail = check_url(f"{base}/api/tags") if not reachable: fail(f"Ollama is not reachable at {base}: {detail}") failures += 1 else: ok(f"Ollama reachable at {base}") try: tags = requests.get(f"{base}/api/tags", timeout=5).json() models = [m.get("name") for m in tags.get("models", [])] if models: ok(f"Ollama models available: {', '.join(models[:10])}") else: warn("No models found on Ollama. Pull a model first (e.g. 'ollama pull llama3.2:3b').") except Exception as exc: warn(f"Could not validate Ollama model list: {exc}") # Nano Banana 2 (image generation) api_key = cfg.get("nanobanana2_api_key", "") or os.environ.get("GEMINI_API_KEY", "") nb2_base = str( cfg.get( "nanobanana2_api_base_url", "https://generativelanguage.googleapis.com/v1beta", ) ).rstrip("/") if api_key: ok("nanobanana2_api_key is set") else: fail("nanobanana2_api_key is empty (and GEMINI_API_KEY is not set)") failures += 1 reachable, detail = check_url(nb2_base, timeout=8) if not reachable: warn(f"Nano Banana 2 base URL could not be reached: {detail}") else: ok(f"Nano Banana 2 base URL reachable: {nb2_base}") if stt_provider == "local_whisper": try: import faster_whisper # noqa: F401 ok("faster-whisper is installed") except Exception as exc: fail(f"faster-whisper is not importable: {exc}") failures += 1 if failures: print("") print(f"Preflight completed with {failures} blocking issue(s).") return 1 print("") print("Preflight passed. Local setup looks ready.") return 0 if __name__ == "__main__": sys.exit(main()) ================================================ FILE: scripts/setup_local.sh ================================================ #!/usr/bin/env bash set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT_DIR" echo "[setup] Root: $ROOT_DIR" if [[ ! -f "config.json" ]]; then cp config.example.json config.json echo "[setup] Created config.json from config.example.json" fi PYTHON_BIN="${ROOT_DIR}/venv/bin/python" if [[ ! -x "$PYTHON_BIN" ]]; then python3 -m venv venv echo "[setup] Created virtual environment at venv/" fi "$PYTHON_BIN" -m ensurepip --upgrade >/dev/null 2>&1 || true "$PYTHON_BIN" -m pip install --upgrade pip setuptools wheel "$PYTHON_BIN" -m pip install -r requirements.txt MAGICK_PATH="$(command -v magick || true)" if [[ -z "$MAGICK_PATH" ]]; then MAGICK_PATH="$(command -v convert || true)" fi FIREFOX_PROFILE="" if [[ -d "$HOME/Library/Application Support/Firefox/Profiles" ]]; then FIREFOX_PROFILE="$(find "$HOME/Library/Application Support/Firefox/Profiles" -maxdepth 1 -type d -name "*default-release*" | head -n 1 || true)" if [[ -z "$FIREFOX_PROFILE" ]]; then FIREFOX_PROFILE="$(find "$HOME/Library/Application Support/Firefox/Profiles" -maxdepth 1 -type d | tail -n +2 | head -n 1 || true)" fi fi OLLAMA_MODELS_JSON="$(curl -sS http://127.0.0.1:11434/api/tags || true)" MAGICK_PATH="$MAGICK_PATH" FIREFOX_PROFILE="$FIREFOX_PROFILE" "$PYTHON_BIN" - <<'PY' import json import os import subprocess ROOT_DIR = os.getcwd() cfg_path = os.path.join(ROOT_DIR, "config.json") with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) # Set defaults per service without overriding explicit user choices. cfg.setdefault("llm_provider", "local_ollama") cfg.setdefault("image_provider", "local_automatic1111") cfg.setdefault("stt_provider", "local_whisper") cfg.setdefault("ollama_base_url", "http://127.0.0.1:11434") cfg.setdefault("automatic1111_base_url", "http://127.0.0.1:7860") cfg.setdefault("cloudflare_worker_url", "") cfg.setdefault("whisper_model", "base") cfg.setdefault("whisper_device", "auto") cfg.setdefault("whisper_compute_type", "int8") magick_path = os.environ.get("MAGICK_PATH", "") if magick_path: cfg["imagemagick_path"] = magick_path firefox_profile = os.environ.get("FIREFOX_PROFILE", "") if firefox_profile and not cfg.get("firefox_profile"): cfg["firefox_profile"] = firefox_profile # Pick a reasonable installed Ollama model. ollama_model = cfg.get("ollama_model", "llama3.2:3b") installed = [] try: out = subprocess.check_output( ["curl", "-sS", "http://127.0.0.1:11434/api/tags"], text=True, ) payload = json.loads(out) installed = [m.get("name") for m in payload.get("models", []) if m.get("name")] except Exception: installed = [] if installed: preferred = [ "glm-4.7-flash:latest", "qwen3:14b", "phi4:latest", "phi4:14b", "gpt-oss:20b", "deepseek-r1:32b", ] selected = None for candidate in preferred: if candidate in installed: selected = candidate break if selected is None: selected = installed[0] if ollama_model not in installed or ollama_model != selected: cfg["ollama_model"] = selected with open(cfg_path, "w", encoding="utf-8") as f: json.dump(cfg, f, indent=2) f.write("\n") print(f"[setup] Updated {cfg_path}") print(f"[setup] llm_provider={cfg.get('llm_provider')} model={cfg.get('ollama_model')}") print(f"[setup] image_provider={cfg.get('image_provider')}") print(f"[setup] stt_provider={cfg.get('stt_provider')}") PY echo "[setup] Running local preflight..." "$PYTHON_BIN" scripts/preflight_local.py || true echo "" echo "[setup] Done." echo "[setup] Start app with: source venv/bin/activate && python3 src/main.py" ================================================ FILE: scripts/upload_video.sh ================================================ #!/bin/bash # Script to generate & Upload a video to YT Shorts # Check which interpreter to use (python) if [ -x "$(command -v python3)" ]; then PYTHON=python3 else PYTHON=python fi # Read .mp/youtube.json file, loop through accounts array, get each id and print every id youtube_ids=$($PYTHON -c "import json; print('\n'.join([account['id'] for account in json.load(open('.mp/youtube.json'))['accounts']]))") echo "What account do you want to upload the video to?" # Print the ids for id in $youtube_ids; do echo $id done # Ask for the id read -p "Enter the id: " id # Check if the id is in the list if [[ " ${youtube_ids[@]} " =~ " ${id} " ]]; then echo "ID found" else echo "ID not found" exit 1 fi # Run python script $PYTHON src/cron.py youtube $id ================================================ FILE: src/art.py ================================================ from config import ROOT_DIR from termcolor import colored def print_banner() -> None: """ Prints the introductory ASCII Art Banner. Returns: None """ with open(f"{ROOT_DIR}/assets/banner.txt", "r") as file: print(colored(file.read(), "green")) ================================================ FILE: src/cache.py ================================================ import os import json from typing import List from config import ROOT_DIR def get_cache_path() -> str: """ Gets the path to the cache file. Returns: path (str): The path to the cache folder """ return os.path.join(ROOT_DIR, '.mp') def get_afm_cache_path() -> str: """ Gets the path to the Affiliate Marketing cache file. Returns: path (str): The path to the AFM cache folder """ return os.path.join(get_cache_path(), 'afm.json') def get_twitter_cache_path() -> str: """ Gets the path to the Twitter cache file. Returns: path (str): The path to the Twitter cache folder """ return os.path.join(get_cache_path(), 'twitter.json') def get_youtube_cache_path() -> str: """ Gets the path to the YouTube cache file. Returns: path (str): The path to the YouTube cache folder """ return os.path.join(get_cache_path(), 'youtube.json') def get_provider_cache_path(provider: str) -> str: """ Gets the cache path for a supported account provider. Args: provider (str): The provider name ("twitter" or "youtube") Returns: path (str): The provider-specific cache path Raises: ValueError: If the provider is unsupported """ if provider == "twitter": return get_twitter_cache_path() if provider == "youtube": return get_youtube_cache_path() raise ValueError(f"Unsupported provider '{provider}'. Expected 'twitter' or 'youtube'.") def get_accounts(provider: str) -> List[dict]: """ Gets the accounts from the cache. Args: provider (str): The provider to get the accounts for Returns: account (List[dict]): The accounts """ cache_path = get_provider_cache_path(provider) if not os.path.exists(cache_path): # Create the cache file with open(cache_path, 'w') as file: json.dump({ "accounts": [] }, file, indent=4) with open(cache_path, 'r') as file: parsed = json.load(file) if parsed is None: return [] if 'accounts' not in parsed: return [] # Get accounts dictionary return parsed['accounts'] def add_account(provider: str, account: dict) -> None: """ Adds an account to the cache. Args: provider (str): The provider to add the account to ("twitter" or "youtube") account (dict): The account to add Returns: None """ cache_path = get_provider_cache_path(provider) # Get the current accounts accounts = get_accounts(provider) # Add the new account accounts.append(account) # Write the new accounts to the cache with open(cache_path, 'w') as file: json.dump({ "accounts": accounts }, file, indent=4) def remove_account(provider: str, account_id: str) -> None: """ Removes an account from the cache. Args: provider (str): The provider to remove the account from ("twitter" or "youtube") account_id (str): The ID of the account to remove Returns: None """ # Get the current accounts accounts = get_accounts(provider) # Remove the account accounts = [account for account in accounts if account['id'] != account_id] # Write the new accounts to the cache cache_path = get_provider_cache_path(provider) with open(cache_path, 'w') as file: json.dump({ "accounts": accounts }, file, indent=4) def get_products() -> List[dict]: """ Gets the products from the cache. Returns: products (List[dict]): The products """ if not os.path.exists(get_afm_cache_path()): # Create the cache file with open(get_afm_cache_path(), 'w') as file: json.dump({ "products": [] }, file, indent=4) with open(get_afm_cache_path(), 'r') as file: parsed = json.load(file) # Get the products return parsed["products"] def add_product(product: dict) -> None: """ Adds a product to the cache. Args: product (dict): The product to add Returns: None """ # Get the current products products = get_products() # Add the new product products.append(product) # Write the new products to the cache with open(get_afm_cache_path(), 'w') as file: json.dump({ "products": products }, file, indent=4) def get_results_cache_path() -> str: """ Gets the path to the results cache file. Returns: path (str): The path to the results cache folder """ return os.path.join(get_cache_path(), 'scraper_results.csv') ================================================ FILE: src/classes/AFM.py ================================================ import os from urllib.parse import urlparse from typing import Any from status import * from config import * from constants import * from llm_provider import generate_text from .Twitter import Twitter from selenium_firefox import * from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options from webdriver_manager.firefox import GeckoDriverManager class AffiliateMarketing: """ This class will be used to handle all the affiliate marketing related operations. """ def __init__( self, affiliate_link: str, fp_profile_path: str, twitter_account_uuid: str, account_nickname: str, topic: str, ) -> None: """ Initializes the Affiliate Marketing class. Args: affiliate_link (str): The affiliate link fp_profile_path (str): The path to the Firefox profile twitter_account_uuid (str): The Twitter account UUID account_nickname (str): The account nickname topic (str): The topic of the product Returns: None """ self._fp_profile_path: str = fp_profile_path # Initialize the Firefox profile self.options: Options = Options() # Set headless state of browser if get_headless(): self.options.add_argument("--headless") if not os.path.isdir(fp_profile_path): raise ValueError( f"Firefox profile path does not exist or is not a directory: {fp_profile_path}" ) # Set the profile path self.options.add_argument("-profile") self.options.add_argument(fp_profile_path) # Set the service self.service: Service = Service(GeckoDriverManager().install()) # Initialize the browser self.browser: webdriver.Firefox = webdriver.Firefox( service=self.service, options=self.options ) # Set the affiliate link self.affiliate_link: str = affiliate_link parsed_link = urlparse(self.affiliate_link) if parsed_link.scheme not in ["http", "https"] or not parsed_link.netloc: raise ValueError( f"Affiliate link is invalid. Expected a full URL, got: {self.affiliate_link}" ) # Set the Twitter account UUID self.account_uuid: str = twitter_account_uuid # Set the Twitter account nickname self.account_nickname: str = account_nickname # Set the Twitter topic self.topic: str = topic # Scrape the product information self.scrape_product_information() def scrape_product_information(self) -> None: """ This method will be used to scrape the product information from the affiliate link. """ # Open the affiliate link self.browser.get(self.affiliate_link) # Get the product name product_title: str = self.browser.find_element( By.ID, AMAZON_PRODUCT_TITLE_ID ).text # Get the features of the product features: Any = self.browser.find_elements(By.ID, AMAZON_FEATURE_BULLETS_ID) if get_verbose(): info(f"Product Title: {product_title}") if get_verbose(): info(f"Features: {features}") # Set the product title self.product_title: str = product_title # Set the features self.features: Any = features def generate_response(self, prompt: str) -> str: """ This method will be used to generate the response for the user. Args: prompt (str): The prompt for the user. Returns: response (str): The response for the user. """ return generate_text(prompt) def generate_pitch(self) -> str: """ This method will be used to generate a pitch for the product. Returns: pitch (str): The pitch for the product. """ # Generate the response pitch: str = ( self.generate_response( f'I want to promote this product on my website. Generate a brief pitch about this product, return nothing else except the pitch. Information:\nTitle: "{self.product_title}"\nFeatures: "{str(self.features)}"' ) + "\nYou can buy the product here: " + self.affiliate_link ) self.pitch: str = pitch # Return the response return pitch def share_pitch(self, where: str) -> None: """ This method will be used to share the pitch on the specified platform. Args: where (str): The platform where the pitch will be shared. """ if where == "twitter": # Initialize the Twitter class twitter: Twitter = Twitter( self.account_uuid, self.account_nickname, self._fp_profile_path, self.topic, ) # Share the pitch twitter.post(self.pitch) def quit(self) -> None: """ This method will be used to quit the browser. """ # Quit the browser self.browser.quit() ================================================ FILE: src/classes/Outreach.py ================================================ import os import io import re import csv import time import glob import shlex import zipfile import yagmail import requests import subprocess import platform from cache import * from status import * from config import * class Outreach: """ Class that houses the methods to reach out to businesses. """ def __init__(self) -> None: """ Constructor for the Outreach class. Returns: None """ # Check if go is installed self.go_installed = os.system("go version") == 0 # Set niche self.niche = get_google_maps_scraper_niche() # Set email credentials self.email_creds = get_email_credentials() def _find_scraper_dir(self) -> str: candidates = sorted(glob.glob("google-maps-scraper-*")) for candidate in candidates: if os.path.isdir(candidate) and os.path.exists( os.path.join(candidate, "go.mod") ): return candidate return "" def is_go_installed(self) -> bool: """ Check if go is installed. Returns: bool: True if go is installed, False otherwise. """ # Check if go is installed try: subprocess.call(["go", "version"]) return True except Exception as e: return False def unzip_file(self, zip_link: str) -> None: """ Unzip the file. Args: zip_link (str): The link to the zip file. Returns: None """ if self._find_scraper_dir(): info("=> Scraper already unzipped. Skipping unzip.") return r = requests.get(zip_link) z = zipfile.ZipFile(io.BytesIO(r.content)) for member in z.namelist(): if ".." in member or member.startswith("/"): warning(f"Skipping suspicious path in archive: {member}") continue z.extract(member) def build_scraper(self) -> None: """ Build the scraper. Returns: None """ binary_name = ( "google-maps-scraper.exe" if platform.system() == "Windows" else "google-maps-scraper" ) if os.path.exists(binary_name): print(colored("=> Scraper already built. Skipping build.", "blue")) return scraper_dir = self._find_scraper_dir() if not scraper_dir: raise FileNotFoundError( "Could not locate extracted google-maps-scraper directory." ) subprocess.run(["go", "mod", "download"], cwd=scraper_dir, check=True) subprocess.run(["go", "build"], cwd=scraper_dir, check=True) built_binary = os.path.join(scraper_dir, binary_name) if not os.path.exists(built_binary): raise FileNotFoundError(f"Expected built scraper binary at: {built_binary}") os.replace(built_binary, binary_name) def run_scraper_with_args_for_30_seconds(self, args: str, timeout=300) -> None: """ Run the scraper with the specified arguments for 30 seconds. Args: args (str): The arguments to run the scraper with. timeout (int): The time to run the scraper for. Returns: None """ info(" => Running scraper...") binary_name = ( "google-maps-scraper.exe" if platform.system() == "Windows" else "google-maps-scraper" ) command = [os.path.join(os.getcwd(), binary_name)] + shlex.split(args) try: scraper_process = subprocess.run(command, timeout=float(timeout)) if scraper_process.returncode == 0: print(colored("=> Scraper finished successfully.", "green")) else: print(colored("=> Scraper finished with an error.", "red")) except subprocess.TimeoutExpired: print(colored("=> Scraper timed out.", "red")) except Exception as e: print(colored("An error occurred while running the scraper:", "red")) print(str(e)) def get_items_from_file(self, file_name: str) -> list: """ Read and return items from a file. Args: file_name (str): The name of the file to read from. Returns: list: The items from the file. """ # Read and return items from a file with open(file_name, "r", errors="ignore") as f: items = f.readlines() items = [item.strip() for item in items[1:]] return items def set_email_for_website(self, index: int, website: str, output_file: str): """Extracts an email address from a website and updates a CSV file with it. This method sends a GET request to the specified website, searches for the first email address in the HTML content, and appends it to the specified row in a CSV file. If no email address is found, no changes are made to the CSV file. Args: index (int): The row index in the CSV file where the email should be appended. website (str): The URL of the website to extract the email address from. output_file (str): The path to the CSV file to update with the extracted email.""" # Extract and set an email for a website email = "" r = requests.get(website) if r.status_code == 200: # Define a regular expression pattern to match email addresses email_pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b" # Find all email addresses in the HTML string email_addresses = re.findall(email_pattern, r.text) email = email_addresses[0] if len(email_addresses) > 0 else "" if email: print(f"=> Setting email {email} for website {website}") with open(output_file, "r", newline="", errors="ignore") as csvfile: csvreader = csv.reader(csvfile) items = list(csvreader) items[index].append(email) with open(output_file, "w", newline="", errors="ignore") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerows(items) def start(self) -> None: """ Start the outreach process. Returns: None """ # Check if go is installed if not self.is_go_installed(): error("Go is not installed. Please install go and try again.") return # Unzip the scraper self.unzip_file(get_google_maps_scraper_zip_url()) # Build the scraper self.build_scraper() # Write the niche to a file with open("niche.txt", "w") as f: f.write(self.niche) output_path = get_results_cache_path() message_subject = get_outreach_message_subject() message_body = get_outreach_message_body_file() # Run self.run_scraper_with_args_for_30_seconds( f'-input niche.txt -results "{output_path}"', timeout=get_scraper_timeout() ) if not os.path.exists(output_path): error( f" => Scraper output not found at {output_path}. Check scraper logs and configuration." ) os.remove("niche.txt") return # Get the items from the file items = self.get_items_from_file(output_path) success(f" => Scraped {len(items)} items.") # Remove the niche file os.remove("niche.txt") time.sleep(2) # Create a yagmail SMTP client outside the loop yag = yagmail.SMTP( user=self.email_creds["username"], password=self.email_creds["password"], host=self.email_creds["smtp_server"], port=self.email_creds["smtp_port"], ) # Get the email for each business for index, item in enumerate(items, start=1): try: # Check if the item"s website is valid website = item.split(",") website = [w for w in website if w.startswith("http")] website = website[0] if len(website) > 0 else "" if website != "": test_r = requests.get(website) if test_r.status_code == 200: self.set_email_for_website(index, website, output_path) # Send emails using the existing SMTP connection receiver_email = item.split(",")[-1] if "@" not in receiver_email: warning(f" => No email provided. Skipping...") continue company_name = item.split(",")[0] subject = message_subject.replace( "{{COMPANY_NAME}}", company_name ) body = ( open(message_body, "r") .read() .replace("{{COMPANY_NAME}}", company_name) ) info(f" => Sending email to {receiver_email}...") yag.send( to=receiver_email, subject=subject, contents=body, ) success(f" => Sent email to {receiver_email}") else: warning(f" => Website {website} is invalid. Skipping...") except Exception as err: error(f" => Error: {err}...") continue ================================================ FILE: src/classes/Tts.py ================================================ import os import soundfile as sf from kittentts import KittenTTS as KittenModel from config import ROOT_DIR, get_tts_voice KITTEN_MODEL = "KittenML/kitten-tts-mini-0.8" KITTEN_SAMPLE_RATE = 24000 class TTS: def __init__(self) -> None: self._model = KittenModel(KITTEN_MODEL) self._voice = get_tts_voice() def synthesize(self, text, output_file=os.path.join(ROOT_DIR, ".mp", "audio.wav")): audio = self._model.generate(text, voice=self._voice) sf.write(output_file, audio, KITTEN_SAMPLE_RATE) return output_file ================================================ FILE: src/classes/Twitter.py ================================================ import re import sys import time import os import json from cache import * from config import * from status import * from llm_provider import generate_text from typing import List, Optional from datetime import datetime from termcolor import colored from selenium_firefox import * from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options from webdriver_manager.firefox import GeckoDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Twitter: """ Class for the Bot, that grows a Twitter account. """ def __init__( self, account_uuid: str, account_nickname: str, fp_profile_path: str, topic: str ) -> None: """ Initializes the Twitter Bot. Args: account_uuid (str): The account UUID account_nickname (str): The account nickname fp_profile_path (str): The path to the Firefox profile Returns: None """ self.account_uuid: str = account_uuid self.account_nickname: str = account_nickname self.fp_profile_path: str = fp_profile_path self.topic: str = topic # Initialize the Firefox profile self.options: Options = Options() # Set headless state of browser if get_headless(): self.options.add_argument("--headless") if not os.path.isdir(fp_profile_path): raise ValueError( f"Firefox profile path does not exist or is not a directory: {fp_profile_path}" ) # Set the profile path self.options.add_argument("-profile") self.options.add_argument(fp_profile_path) # Set the service self.service: Service = Service(GeckoDriverManager().install()) # Initialize the browser self.browser: webdriver.Firefox = webdriver.Firefox( service=self.service, options=self.options ) self.wait: WebDriverWait = WebDriverWait(self.browser, 30) def post(self, text: Optional[str] = None) -> None: """ Starts the Twitter Bot. Args: text (str): The text to post Returns: None """ bot: webdriver.Firefox = self.browser verbose: bool = get_verbose() bot.get("https://x.com/compose/post") post_content: str = text if text is not None else self.generate_post() now: datetime = datetime.now() print(colored(" => Posting to Twitter:", "blue"), post_content[:30] + "...") body = post_content text_box = None text_box_selectors = [ (By.CSS_SELECTOR, "div[data-testid='tweetTextarea_0'][role='textbox']"), (By.XPATH, "//div[@data-testid='tweetTextarea_0']//div[@role='textbox']"), (By.XPATH, "//div[@role='textbox']"), ] for selector in text_box_selectors: try: text_box = self.wait.until(EC.element_to_be_clickable(selector)) text_box.click() text_box.send_keys(body) break except Exception: continue if text_box is None: raise RuntimeError( "Could not find tweet text box. Ensure you are logged into X in this Firefox profile." ) post_button = None post_button_selectors = [ (By.XPATH, "//button[@data-testid='tweetButtonInline']"), (By.XPATH, "//button[@data-testid='tweetButton']"), (By.XPATH, "//span[text()='Post']/ancestor::button"), ] for selector in post_button_selectors: try: post_button = self.wait.until(EC.element_to_be_clickable(selector)) post_button.click() break except Exception: continue if post_button is None: raise RuntimeError("Could not find the Post button on X compose screen.") if verbose: print(colored(" => Pressed [ENTER] Button on Twitter..", "blue")) time.sleep(2) # Add the post to the cache self.add_post({"content": body, "date": now.strftime("%m/%d/%Y, %H:%M:%S")}) success("Posted to Twitter successfully!") def get_posts(self) -> List[dict]: """ Gets the posts from the cache. Returns: posts (List[dict]): The posts """ if not os.path.exists(get_twitter_cache_path()): # Create the cache file with open(get_twitter_cache_path(), "w") as file: json.dump({"accounts": []}, file, indent=4) with open(get_twitter_cache_path(), "r") as file: parsed = json.load(file) # Find our account accounts = parsed["accounts"] for account in accounts: if account["id"] == self.account_uuid: posts = account["posts"] if posts is None: return [] # Return the posts return posts return [] def add_post(self, post: dict) -> None: """ Adds a post to the cache. Args: post (dict): The post to add Returns: None """ posts = self.get_posts() posts.append(post) with open(get_twitter_cache_path(), "r") as file: previous_json = json.loads(file.read()) # Find our account accounts = previous_json["accounts"] for account in accounts: if account["id"] == self.account_uuid: account["posts"].append(post) # Commit changes with open(get_twitter_cache_path(), "w") as f: f.write(json.dumps(previous_json)) def generate_post(self) -> str: """ Generates a post for the Twitter account based on the topic. Returns: post (str): The post """ completion = generate_text( f"Generate a Twitter post about: {self.topic} in {get_twitter_language()}. " "The Limit is 2 sentences. Choose a specific sub-topic of the provided topic." ) if get_verbose(): info("Generating a post...") if completion is None: error("Failed to generate a post. Please try again.") sys.exit(1) # Apply Regex to remove all * completion = re.sub(r"\*", "", completion).replace('"', "") if get_verbose(): info(f"Length of post: {len(completion)}") if len(completion) >= 260: return completion[:257].rsplit(" ", 1)[0] + "..." return completion ================================================ FILE: src/classes/YouTube.py ================================================ import re import base64 import json import time import os import requests import assemblyai as aai from utils import * from cache import * from .Tts import TTS from llm_provider import generate_text from config import * from status import * from uuid import uuid4 from constants import * from typing import List from moviepy.editor import * from termcolor import colored from selenium_firefox import * from selenium import webdriver from moviepy.video.fx.all import crop from moviepy.config import change_settings from selenium.webdriver.common.by import By from selenium.webdriver.firefox.service import Service from selenium.webdriver.firefox.options import Options from moviepy.video.tools.subtitles import SubtitlesClip from webdriver_manager.firefox import GeckoDriverManager from datetime import datetime # Set ImageMagick Path change_settings({"IMAGEMAGICK_BINARY": get_imagemagick_path()}) class YouTube: """ Class for YouTube Automation. Steps to create a YouTube Short: 1. Generate a topic [DONE] 2. Generate a script [DONE] 3. Generate metadata (Title, Description, Tags) [DONE] 4. Generate AI Image Prompts [DONE] 4. Generate Images based on generated Prompts [DONE] 5. Convert Text-to-Speech [DONE] 6. Show images each for n seconds, n: Duration of TTS / Amount of images [DONE] 7. Combine Concatenated Images with the Text-to-Speech [DONE] """ def __init__( self, account_uuid: str, account_nickname: str, fp_profile_path: str, niche: str, language: str, ) -> None: """ Constructor for YouTube Class. Args: account_uuid (str): The unique identifier for the YouTube account. account_nickname (str): The nickname for the YouTube account. fp_profile_path (str): Path to the firefox profile that is logged into the specificed YouTube Account. niche (str): The niche of the provided YouTube Channel. language (str): The language of the Automation. Returns: None """ self._account_uuid: str = account_uuid self._account_nickname: str = account_nickname self._fp_profile_path: str = fp_profile_path self._niche: str = niche self._language: str = language self.images = [] # Initialize the Firefox profile self.options: Options = Options() # Set headless state of browser if get_headless(): self.options.add_argument("--headless") if not os.path.isdir(self._fp_profile_path): raise ValueError( f"Firefox profile path does not exist or is not a directory: {self._fp_profile_path}" ) self.options.add_argument("-profile") self.options.add_argument(self._fp_profile_path) # Set the service self.service: Service = Service(GeckoDriverManager().install()) # Initialize the browser self.browser: webdriver.Firefox = webdriver.Firefox( service=self.service, options=self.options ) @property def niche(self) -> str: """ Getter Method for the niche. Returns: niche (str): The niche """ return self._niche @property def language(self) -> str: """ Getter Method for the language to use. Returns: language (str): The language """ return self._language def generate_response(self, prompt: str, model_name: str = None) -> str: """ Generates an LLM Response based on a prompt and the user-provided model. Args: prompt (str): The prompt to use in the text generation. Returns: response (str): The generated AI Repsonse. """ return generate_text(prompt, model_name=model_name) def generate_topic(self) -> str: """ Generates a topic based on the YouTube Channel niche. Returns: topic (str): The generated topic. """ completion = self.generate_response( f"Please generate a specific video idea that takes about the following topic: {self.niche}. Make it exactly one sentence. Only return the topic, nothing else." ) if not completion: error("Failed to generate Topic.") self.subject = completion return completion def generate_script(self) -> str: """ Generate a script for a video, depending on the subject of the video, the number of paragraphs, and the AI model. Returns: script (str): The script of the video. """ sentence_length = get_script_sentence_length() prompt = f""" Generate a script for a video in {sentence_length} sentences, depending on the subject of the video. The script is to be returned as a string with the specified number of paragraphs. Here is an example of a string: "This is an example string." Do not under any circumstance reference this prompt in your response. Get straight to the point, don't start with unnecessary things like, "welcome to this video". Obviously, the script should be related to the subject of the video. YOU MUST NOT EXCEED THE {sentence_length} SENTENCES LIMIT. MAKE SURE THE {sentence_length} SENTENCES ARE SHORT. YOU MUST NOT INCLUDE ANY TYPE OF MARKDOWN OR FORMATTING IN THE SCRIPT, NEVER USE A TITLE. YOU MUST WRITE THE SCRIPT IN THE LANGUAGE SPECIFIED IN [LANGUAGE]. ONLY RETURN THE RAW CONTENT OF THE SCRIPT. DO NOT INCLUDE "VOICEOVER", "NARRATOR" OR SIMILAR INDICATORS OF WHAT SHOULD BE SPOKEN AT THE BEGINNING OF EACH PARAGRAPH OR LINE. YOU MUST NOT MENTION THE PROMPT, OR ANYTHING ABOUT THE SCRIPT ITSELF. ALSO, NEVER TALK ABOUT THE AMOUNT OF PARAGRAPHS OR LINES. JUST WRITE THE SCRIPT Subject: {self.subject} Language: {self.language} """ completion = self.generate_response(prompt) # Apply regex to remove * completion = re.sub(r"\*", "", completion) if not completion: error("The generated script is empty.") return if len(completion) > 5000: if get_verbose(): warning("Generated Script is too long. Retrying...") return self.generate_script() self.script = completion return completion def generate_metadata(self) -> dict: """ Generates Video metadata for the to-be-uploaded YouTube Short (Title, Description). Returns: metadata (dict): The generated metadata. """ title = self.generate_response( f"Please generate a YouTube Video Title for the following subject, including hashtags: {self.subject}. Only return the title, nothing else. Limit the title under 100 characters." ) if len(title) > 100: if get_verbose(): warning("Generated Title is too long. Retrying...") return self.generate_metadata() description = self.generate_response( f"Please generate a YouTube Video Description for the following script: {self.script}. Only return the description, nothing else." ) self.metadata = {"title": title, "description": description} return self.metadata def generate_prompts(self) -> List[str]: """ Generates AI Image Prompts based on the provided Video Script. Returns: image_prompts (List[str]): Generated List of image prompts. """ n_prompts = len(self.script) / 3 prompt = f""" Generate {n_prompts} Image Prompts for AI Image Generation, depending on the subject of a video. Subject: {self.subject} The image prompts are to be returned as a JSON-Array of strings. Each search term should consist of a full sentence, always add the main subject of the video. Be emotional and use interesting adjectives to make the Image Prompt as detailed as possible. YOU MUST ONLY RETURN THE JSON-ARRAY OF STRINGS. YOU MUST NOT RETURN ANYTHING ELSE. YOU MUST NOT RETURN THE SCRIPT. The search terms must be related to the subject of the video. Here is an example of a JSON-Array of strings: ["image prompt 1", "image prompt 2", "image prompt 3"] For context, here is the full text: {self.script} """ completion = ( str(self.generate_response(prompt)) .replace("```json", "") .replace("```", "") ) image_prompts = [] if "image_prompts" in completion: image_prompts = json.loads(completion)["image_prompts"] else: try: image_prompts = json.loads(completion) if get_verbose(): info(f" => Generated Image Prompts: {image_prompts}") except Exception: if get_verbose(): warning( "LLM returned an unformatted response. Attempting to clean..." ) # Get everything between [ and ], and turn it into a list r = re.compile(r"\[.*\]") image_prompts = r.findall(completion) if len(image_prompts) == 0: if get_verbose(): warning("Failed to generate Image Prompts. Retrying...") return self.generate_prompts() if len(image_prompts) > n_prompts: image_prompts = image_prompts[: int(n_prompts)] self.image_prompts = image_prompts success(f"Generated {len(image_prompts)} Image Prompts.") return image_prompts def _persist_image(self, image_bytes: bytes, provider_label: str) -> str: """ Writes generated image bytes to a PNG file in .mp. Args: image_bytes (bytes): Image payload provider_label (str): Label for logging Returns: path (str): Absolute image path """ image_path = os.path.join(ROOT_DIR, ".mp", str(uuid4()) + ".png") with open(image_path, "wb") as image_file: image_file.write(image_bytes) if get_verbose(): info(f' => Wrote image from {provider_label} to "{image_path}"') self.images.append(image_path) return image_path def generate_image_nanobanana2(self, prompt: str) -> str: """ Generates an AI Image using Nano Banana 2 API (Gemini image API). Args: prompt (str): Prompt for image generation Returns: path (str): The path to the generated image. """ print(f"Generating Image using Nano Banana 2 API: {prompt}") api_key = get_nanobanana2_api_key() if not api_key: error("nanobanana2_api_key is not configured.") return None base_url = get_nanobanana2_api_base_url().rstrip("/") model = get_nanobanana2_model() aspect_ratio = get_nanobanana2_aspect_ratio() endpoint = f"{base_url}/models/{model}:generateContent" payload = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "responseModalities": ["IMAGE"], "imageConfig": {"aspectRatio": aspect_ratio}, }, } try: response = requests.post( endpoint, headers={"x-goog-api-key": api_key, "Content-Type": "application/json"}, json=payload, timeout=300, ) response.raise_for_status() body = response.json() candidates = body.get("candidates", []) for candidate in candidates: content = candidate.get("content", {}) for part in content.get("parts", []): inline_data = part.get("inlineData") or part.get("inline_data") if not inline_data: continue data = inline_data.get("data") mime_type = inline_data.get("mimeType") or inline_data.get("mime_type", "") if data and str(mime_type).startswith("image/"): image_bytes = base64.b64decode(data) return self._persist_image(image_bytes, "Nano Banana 2 API") if get_verbose(): warning(f"Nano Banana 2 did not return an image payload. Response: {body}") return None except Exception as e: if get_verbose(): warning(f"Failed to generate image with Nano Banana 2 API: {str(e)}") return None def generate_image(self, prompt: str) -> str: """ Generates an AI Image based on the given prompt using Nano Banana 2. Args: prompt (str): Reference for image generation Returns: path (str): The path to the generated image. """ return self.generate_image_nanobanana2(prompt) def generate_script_to_speech(self, tts_instance: TTS) -> str: """ Converts the generated script into Speech using KittenTTS and returns the path to the wav file. Args: tts_instance (tts): Instance of TTS Class. Returns: path_to_wav (str): Path to generated audio (WAV Format). """ path = os.path.join(ROOT_DIR, ".mp", str(uuid4()) + ".wav") # Clean script, remove every character that is not a word character, a space, a period, a question mark, or an exclamation mark. self.script = re.sub(r"[^\w\s.?!]", "", self.script) tts_instance.synthesize(self.script, path) self.tts_path = path if get_verbose(): info(f' => Wrote TTS to "{path}"') return path def add_video(self, video: dict) -> None: """ Adds a video to the cache. Args: video (dict): The video to add Returns: None """ videos = self.get_videos() videos.append(video) cache = get_youtube_cache_path() with open(cache, "r") as file: previous_json = json.loads(file.read()) # Find our account accounts = previous_json["accounts"] for account in accounts: if account["id"] == self._account_uuid: account["videos"].append(video) # Commit changes with open(cache, "w") as f: f.write(json.dumps(previous_json)) def generate_subtitles(self, audio_path: str) -> str: """ Generates subtitles for the audio using the configured STT provider. Args: audio_path (str): The path to the audio file. Returns: path (str): The path to the generated SRT File. """ provider = str(get_stt_provider() or "local_whisper").lower() if provider == "local_whisper": return self.generate_subtitles_local_whisper(audio_path) if provider == "third_party_assemblyai": return self.generate_subtitles_assemblyai(audio_path) warning(f"Unknown stt_provider '{provider}'. Falling back to local_whisper.") return self.generate_subtitles_local_whisper(audio_path) def generate_subtitles_assemblyai(self, audio_path: str) -> str: """ Generates subtitles using AssemblyAI. Args: audio_path (str): Audio file path Returns: path (str): Path to SRT file """ aai.settings.api_key = get_assemblyai_api_key() config = aai.TranscriptionConfig() transcriber = aai.Transcriber(config=config) transcript = transcriber.transcribe(audio_path) subtitles = transcript.export_subtitles_srt() srt_path = os.path.join(ROOT_DIR, ".mp", str(uuid4()) + ".srt") with open(srt_path, "w") as file: file.write(subtitles) return srt_path def _format_srt_timestamp(self, seconds: float) -> str: """ Formats a timestamp in seconds to SRT format. Args: seconds (float): Seconds Returns: ts (str): HH:MM:SS,mmm """ total_millis = max(0, int(round(seconds * 1000))) hours = total_millis // 3600000 minutes = (total_millis % 3600000) // 60000 secs = (total_millis % 60000) // 1000 millis = total_millis % 1000 return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}" def generate_subtitles_local_whisper(self, audio_path: str) -> str: """ Generates subtitles using local Whisper (faster-whisper). Args: audio_path (str): Audio file path Returns: path (str): Path to SRT file """ try: from faster_whisper import WhisperModel except ImportError: error( "Local STT selected but 'faster-whisper' is not installed. " "Install it or switch stt_provider to third_party_assemblyai." ) raise model = WhisperModel( get_whisper_model(), device=get_whisper_device(), compute_type=get_whisper_compute_type(), ) segments, _ = model.transcribe(audio_path, vad_filter=True) lines = [] for idx, segment in enumerate(segments, start=1): start = self._format_srt_timestamp(segment.start) end = self._format_srt_timestamp(segment.end) text = str(segment.text).strip() if not text: continue lines.append(str(idx)) lines.append(f"{start} --> {end}") lines.append(text) lines.append("") subtitles = "\n".join(lines) srt_path = os.path.join(ROOT_DIR, ".mp", str(uuid4()) + ".srt") with open(srt_path, "w", encoding="utf-8") as file: file.write(subtitles) return srt_path def combine(self) -> str: """ Combines everything into the final video. Returns: path (str): The path to the generated MP4 File. """ combined_image_path = os.path.join(ROOT_DIR, ".mp", str(uuid4()) + ".mp4") threads = get_threads() tts_clip = AudioFileClip(self.tts_path) max_duration = tts_clip.duration req_dur = max_duration / len(self.images) # Make a generator that returns a TextClip when called with consecutive generator = lambda txt: TextClip( txt, font=os.path.join(get_fonts_dir(), get_font()), fontsize=100, color="#FFFF00", stroke_color="black", stroke_width=5, size=(1080, 1920), method="caption", ) print(colored("[+] Combining images...", "blue")) clips = [] tot_dur = 0 # Add downloaded clips over and over until the duration of the audio (max_duration) has been reached while tot_dur < max_duration: for image_path in self.images: clip = ImageClip(image_path) clip.duration = req_dur clip = clip.set_fps(30) # Not all images are same size, # so we need to resize them if round((clip.w / clip.h), 4) < 0.5625: if get_verbose(): info(f" => Resizing Image: {image_path} to 1080x1920") clip = crop( clip, width=clip.w, height=round(clip.w / 0.5625), x_center=clip.w / 2, y_center=clip.h / 2, ) else: if get_verbose(): info(f" => Resizing Image: {image_path} to 1920x1080") clip = crop( clip, width=round(0.5625 * clip.h), height=clip.h, x_center=clip.w / 2, y_center=clip.h / 2, ) clip = clip.resize((1080, 1920)) # FX (Fade In) # clip = clip.fadein(2) clips.append(clip) tot_dur += clip.duration final_clip = concatenate_videoclips(clips) final_clip = final_clip.set_fps(30) random_song = choose_random_song() subtitles = None try: subtitles_path = self.generate_subtitles(self.tts_path) equalize_subtitles(subtitles_path, 10) subtitles = SubtitlesClip(subtitles_path, generator) subtitles.set_pos(("center", "center")) except Exception as e: warning(f"Failed to generate subtitles, continuing without subtitles: {e}") random_song_clip = AudioFileClip(random_song).set_fps(44100) # Turn down volume random_song_clip = random_song_clip.fx(afx.volumex, 0.1) comp_audio = CompositeAudioClip([tts_clip.set_fps(44100), random_song_clip]) final_clip = final_clip.set_audio(comp_audio) final_clip = final_clip.set_duration(tts_clip.duration) if subtitles is not None: final_clip = CompositeVideoClip([final_clip, subtitles]) final_clip.write_videofile(combined_image_path, threads=threads) success(f'Wrote Video to "{combined_image_path}"') return combined_image_path def generate_video(self, tts_instance: TTS) -> str: """ Generates a YouTube Short based on the provided niche and language. Args: tts_instance (TTS): Instance of TTS Class. Returns: path (str): The path to the generated MP4 File. """ # Generate the Topic self.generate_topic() # Generate the Script self.generate_script() # Generate the Metadata self.generate_metadata() # Generate the Image Prompts self.generate_prompts() # Generate the Images for prompt in self.image_prompts: self.generate_image(prompt) # Generate the TTS self.generate_script_to_speech(tts_instance) # Combine everything path = self.combine() if get_verbose(): info(f" => Generated Video: {path}") self.video_path = os.path.abspath(path) return path def get_channel_id(self) -> str: """ Gets the Channel ID of the YouTube Account. Returns: channel_id (str): The Channel ID. """ driver = self.browser driver.get("https://studio.youtube.com") time.sleep(2) channel_id = driver.current_url.split("/")[-1] self.channel_id = channel_id return channel_id def upload_video(self) -> bool: """ Uploads the video to YouTube. Returns: success (bool): Whether the upload was successful or not. """ try: self.get_channel_id() driver = self.browser verbose = get_verbose() # Go to youtube.com/upload driver.get("https://www.youtube.com/upload") # Set video file FILE_PICKER_TAG = "ytcp-uploads-file-picker" file_picker = driver.find_element(By.TAG_NAME, FILE_PICKER_TAG) INPUT_TAG = "input" file_input = file_picker.find_element(By.TAG_NAME, INPUT_TAG) file_input.send_keys(self.video_path) # Wait for upload to finish time.sleep(5) # Set title textboxes = driver.find_elements(By.ID, YOUTUBE_TEXTBOX_ID) title_el = textboxes[0] description_el = textboxes[-1] if verbose: info("\t=> Setting title...") title_el.click() time.sleep(1) title_el.clear() title_el.send_keys(self.metadata["title"]) if verbose: info("\t=> Setting description...") # Set description time.sleep(10) description_el.click() time.sleep(0.5) description_el.clear() description_el.send_keys(self.metadata["description"]) time.sleep(0.5) # Set `made for kids` option if verbose: info("\t=> Setting `made for kids` option...") is_for_kids_checkbox = driver.find_element( By.NAME, YOUTUBE_MADE_FOR_KIDS_NAME ) is_not_for_kids_checkbox = driver.find_element( By.NAME, YOUTUBE_NOT_MADE_FOR_KIDS_NAME ) if not get_is_for_kids(): is_not_for_kids_checkbox.click() else: is_for_kids_checkbox.click() time.sleep(0.5) # Click next if verbose: info("\t=> Clicking next...") next_button = driver.find_element(By.ID, YOUTUBE_NEXT_BUTTON_ID) next_button.click() # Click next again if verbose: info("\t=> Clicking next again...") next_button = driver.find_element(By.ID, YOUTUBE_NEXT_BUTTON_ID) next_button.click() # Wait for 2 seconds time.sleep(2) # Click next again if verbose: info("\t=> Clicking next again...") next_button = driver.find_element(By.ID, YOUTUBE_NEXT_BUTTON_ID) next_button.click() # Set as unlisted if verbose: info("\t=> Setting as unlisted...") radio_button = driver.find_elements(By.XPATH, YOUTUBE_RADIO_BUTTON_XPATH) radio_button[2].click() if verbose: info("\t=> Clicking done button...") # Click done button done_button = driver.find_element(By.ID, YOUTUBE_DONE_BUTTON_ID) done_button.click() # Wait for 2 seconds time.sleep(2) # Get latest video if verbose: info("\t=> Getting video URL...") # Get the latest uploaded video URL driver.get( f"https://studio.youtube.com/channel/{self.channel_id}/videos/short" ) time.sleep(2) videos = driver.find_elements(By.TAG_NAME, "ytcp-video-row") first_video = videos[0] anchor_tag = first_video.find_element(By.TAG_NAME, "a") href = anchor_tag.get_attribute("href") if verbose: info(f"\t=> Extracting video ID from URL: {href}") video_id = href.split("/")[-2] # Build URL url = build_url(video_id) self.uploaded_video_url = url if verbose: success(f" => Uploaded Video: {url}") # Add video to cache self.add_video( { "title": self.metadata["title"], "description": self.metadata["description"], "url": url, "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } ) # Close the browser driver.quit() return True except: self.browser.quit() return False def get_videos(self) -> List[dict]: """ Gets the uploaded videos from the YouTube Channel. Returns: videos (List[dict]): The uploaded videos. """ if not os.path.exists(get_youtube_cache_path()): # Create the cache file with open(get_youtube_cache_path(), "w") as file: json.dump({"videos": []}, file, indent=4) return [] videos = [] # Read the cache file with open(get_youtube_cache_path(), "r") as file: previous_json = json.loads(file.read()) # Find our account accounts = previous_json["accounts"] for account in accounts: if account["id"] == self._account_uuid: videos = account["videos"] return videos ================================================ FILE: src/config.py ================================================ import os import sys import json import srt_equalizer from termcolor import colored ROOT_DIR = os.path.dirname(sys.path[0]) def assert_folder_structure() -> None: """ Make sure that the nessecary folder structure is present. Returns: None """ # Create the .mp folder if not os.path.exists(os.path.join(ROOT_DIR, ".mp")): if get_verbose(): print(colored(f"=> Creating .mp folder at {os.path.join(ROOT_DIR, '.mp')}", "green")) os.makedirs(os.path.join(ROOT_DIR, ".mp")) def get_first_time_running() -> bool: """ Checks if the program is running for the first time by checking if .mp folder exists. Returns: exists (bool): True if the program is running for the first time, False otherwise """ return not os.path.exists(os.path.join(ROOT_DIR, ".mp")) def get_email_credentials() -> dict: """ Gets the email credentials from the config file. Returns: credentials (dict): The email credentials """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["email"] def get_verbose() -> bool: """ Gets the verbose flag from the config file. Returns: verbose (bool): The verbose flag """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["verbose"] def get_firefox_profile_path() -> str: """ Gets the path to the Firefox profile. Returns: path (str): The path to the Firefox profile """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["firefox_profile"] def get_headless() -> bool: """ Gets the headless flag from the config file. Returns: headless (bool): The headless flag """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["headless"] def get_ollama_base_url() -> str: """ Gets the Ollama base URL. Returns: url (str): The Ollama base URL """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("ollama_base_url", "http://127.0.0.1:11434") def get_ollama_model() -> str: """ Gets the Ollama model name from the config file. Returns: model (str): The Ollama model name, or empty string if not set. """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("ollama_model", "") def get_twitter_language() -> str: """ Gets the Twitter language from the config file. Returns: language (str): The Twitter language """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["twitter_language"] def get_nanobanana2_api_base_url() -> str: """ Gets the Nano Banana 2 (Gemini image) API base URL. Returns: url (str): API base URL """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get( "nanobanana2_api_base_url", "https://generativelanguage.googleapis.com/v1beta", ) def get_nanobanana2_api_key() -> str: """ Gets the Nano Banana 2 API key. Returns: key (str): API key """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: configured = json.load(file).get("nanobanana2_api_key", "") return configured or os.environ.get("GEMINI_API_KEY", "") def get_nanobanana2_model() -> str: """ Gets the Nano Banana 2 model name. Returns: model (str): Model name """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("nanobanana2_model", "gemini-3.1-flash-image-preview") def get_nanobanana2_aspect_ratio() -> str: """ Gets the aspect ratio for Nano Banana 2 image generation. Returns: ratio (str): Aspect ratio """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("nanobanana2_aspect_ratio", "9:16") def get_threads() -> int: """ Gets the amount of threads to use for example when writing to a file with MoviePy. Returns: threads (int): Amount of threads """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["threads"] def get_zip_url() -> str: """ Gets the URL to the zip file containing the songs. Returns: url (str): The URL to the zip file """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["zip_url"] def get_is_for_kids() -> bool: """ Gets the is for kids flag from the config file. Returns: is_for_kids (bool): The is for kids flag """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["is_for_kids"] def get_google_maps_scraper_zip_url() -> str: """ Gets the URL to the zip file containing the Google Maps scraper. Returns: url (str): The URL to the zip file """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["google_maps_scraper"] def get_google_maps_scraper_niche() -> str: """ Gets the niche for the Google Maps scraper. Returns: niche (str): The niche """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["google_maps_scraper_niche"] def get_scraper_timeout() -> int: """ Gets the timeout for the scraper. Returns: timeout (int): The timeout """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["scraper_timeout"] or 300 def get_outreach_message_subject() -> str: """ Gets the outreach message subject. Returns: subject (str): The outreach message subject """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["outreach_message_subject"] def get_outreach_message_body_file() -> str: """ Gets the outreach message body file. Returns: file (str): The outreach message body file """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["outreach_message_body_file"] def get_tts_voice() -> str: """ Gets the TTS voice from the config file. Returns: voice (str): The TTS voice """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("tts_voice", "Jasper") def get_assemblyai_api_key() -> str: """ Gets the AssemblyAI API key. Returns: key (str): The AssemblyAI API key """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["assembly_ai_api_key"] def get_stt_provider() -> str: """ Gets the configured STT provider. Returns: provider (str): The STT provider """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("stt_provider", "local_whisper") def get_whisper_model() -> str: """ Gets the local Whisper model name. Returns: model (str): Whisper model name """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("whisper_model", "base") def get_whisper_device() -> str: """ Gets the target device for Whisper inference. Returns: device (str): Whisper device """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("whisper_device", "auto") def get_whisper_compute_type() -> str: """ Gets the compute type for Whisper inference. Returns: compute_type (str): Whisper compute type """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file).get("whisper_compute_type", "int8") def equalize_subtitles(srt_path: str, max_chars: int = 10) -> None: """ Equalizes the subtitles in a SRT file. Args: srt_path (str): The path to the SRT file max_chars (int): The maximum amount of characters in a subtitle Returns: None """ srt_equalizer.equalize_srt_file(srt_path, srt_path, max_chars) def get_font() -> str: """ Gets the font from the config file. Returns: font (str): The font """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["font"] def get_fonts_dir() -> str: """ Gets the fonts directory. Returns: dir (str): The fonts directory """ return os.path.join(ROOT_DIR, "fonts") def get_imagemagick_path() -> str: """ Gets the path to ImageMagick. Returns: path (str): The path to ImageMagick """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: return json.load(file)["imagemagick_path"] def get_script_sentence_length() -> int: """ Gets the forced script's sentence length. In case there is no sentence length in config, returns 4 when none Returns: length (int): Length of script's sentence """ with open(os.path.join(ROOT_DIR, "config.json"), "r") as file: config_json = json.load(file) if (config_json.get("script_sentence_length") is not None): return config_json["script_sentence_length"] else: return 4 ================================================ FILE: src/constants.py ================================================ """ This file contains all the constants used in the program. """ TWITTER_TEXTAREA_CLASS = "public-DraftStyleDefault-block public-DraftStyleDefault-ltr" TWITTER_POST_BUTTON_XPATH = "/html/body/div[1]/div/div/div[2]/main/div/div/div/div[1]/div/div[3]/div/div[2]/div[1]/div/div/div/div[2]/div[2]/div[2]/div/div/div/div[3]" OPTIONS = [ "YouTube Shorts Automation", "Twitter Bot", "Affiliate Marketing", "Outreach", "Quit" ] TWITTER_OPTIONS = [ "Post something", "Show all Posts", "Setup CRON Job", "Quit" ] TWITTER_CRON_OPTIONS = [ "Once a day", "Twice a day", "Thrice a day", "Quit" ] YOUTUBE_OPTIONS = [ "Upload Short", "Show all Shorts", "Setup CRON Job", "Quit" ] YOUTUBE_CRON_OPTIONS = [ "Once a day", "Twice a day", "Thrice a day", "Quit" ] # YouTube Section YOUTUBE_TEXTBOX_ID = "textbox" YOUTUBE_MADE_FOR_KIDS_NAME = "VIDEO_MADE_FOR_KIDS_MFK" YOUTUBE_NOT_MADE_FOR_KIDS_NAME = "VIDEO_MADE_FOR_KIDS_NOT_MFK" YOUTUBE_NEXT_BUTTON_ID = "next-button" YOUTUBE_RADIO_BUTTON_XPATH = "//*[@id=\"radioLabel\"]" YOUTUBE_DONE_BUTTON_ID = "done-button" # Amazon Section (AFM)$ AMAZON_PRODUCT_TITLE_ID = "productTitle" AMAZON_FEATURE_BULLETS_ID = "feature-bullets" ================================================ FILE: src/cron.py ================================================ # RUN THIS N AMOUNT OF TIMES import sys from status import * from cache import get_accounts from config import get_verbose from classes.Tts import TTS from classes.Twitter import Twitter from classes.YouTube import YouTube from llm_provider import select_model def main(): """Main function to post content to Twitter or upload videos to YouTube. This function determines its operation based on command-line arguments: - If the purpose is "twitter", it initializes a Twitter account and posts a message. - If the purpose is "youtube", it initializes a YouTube account, generates a video with TTS, and uploads it. Command-line arguments: sys.argv[1]: A string indicating the purpose, either "twitter" or "youtube". sys.argv[2]: A string representing the account UUID. The function also handles verbose output based on user settings and reports success or errors as appropriate. Args: None. The function uses command-line arguments accessed via sys.argv. Returns: None. The function performs operations based on the purpose and account UUID and does not return any value.""" purpose = str(sys.argv[1]) account_id = str(sys.argv[2]) model = str(sys.argv[3]) if len(sys.argv) > 3 else None if model: select_model(model) else: error("No Ollama model specified. Pass model name as third argument.") sys.exit(1) verbose = get_verbose() if purpose == "twitter": accounts = get_accounts("twitter") if not account_id: error("Account UUID cannot be empty.") for acc in accounts: if acc["id"] == account_id: if verbose: info("Initializing Twitter...") twitter = Twitter( acc["id"], acc["nickname"], acc["firefox_profile"], acc["topic"] ) twitter.post() if verbose: success("Done posting.") break elif purpose == "youtube": tts = TTS() accounts = get_accounts("youtube") if not account_id: error("Account UUID cannot be empty.") for acc in accounts: if acc["id"] == account_id: if verbose: info("Initializing YouTube...") youtube = YouTube( acc["id"], acc["nickname"], acc["firefox_profile"], acc["niche"], acc["language"] ) youtube.generate_video(tts) youtube.upload_video() if verbose: success("Uploaded Short.") break else: error("Invalid Purpose, exiting...") sys.exit(1) if __name__ == "__main__": main() ================================================ FILE: src/llm_provider.py ================================================ import ollama from config import get_ollama_base_url _selected_model: str | None = None def _client() -> ollama.Client: return ollama.Client(host=get_ollama_base_url()) def list_models() -> list[str]: """ Lists all models available on the local Ollama server. Returns: models (list[str]): Sorted list of model names. """ response = _client().list() return sorted(m.model for m in response.models) def select_model(model: str) -> None: """ Sets the model to use for all subsequent generate_text calls. Args: model (str): An Ollama model name (must be already pulled). """ global _selected_model _selected_model = model def get_active_model() -> str | None: """ Returns the currently selected model, or None if none has been selected. """ return _selected_model def generate_text(prompt: str, model_name: str = None) -> str: """ Generates text using the local Ollama server. Args: prompt (str): User prompt model_name (str): Optional model name override Returns: response (str): Generated text """ model = model_name or _selected_model if not model: raise RuntimeError( "No Ollama model selected. Call select_model() first or pass model_name." ) response = _client().chat( model=model, messages=[{"role": "user", "content": prompt}], ) return response["message"]["content"].strip() ================================================ FILE: src/main.py ================================================ import schedule import subprocess from art import * from cache import * from utils import * from config import * from status import * from uuid import uuid4 from constants import * from classes.Tts import TTS from termcolor import colored from classes.Twitter import Twitter from classes.YouTube import YouTube from prettytable import PrettyTable from classes.Outreach import Outreach from classes.AFM import AffiliateMarketing from llm_provider import list_models, select_model, get_active_model def main(): """Main entry point for the application, providing a menu-driven interface to manage YouTube, Twitter bots, Affiliate Marketing, and Outreach tasks. This function allows users to: 1. Start the YouTube Shorts Automater to manage YouTube accounts, generate and upload videos, and set up CRON jobs. 2. Start a Twitter Bot to manage Twitter accounts, post tweets, and schedule posts using CRON jobs. 3. Manage Affiliate Marketing by creating pitches and sharing them via Twitter accounts. 4. Initiate an Outreach process for engagement and promotion tasks. 5. Exit the application. The function continuously prompts users for input, validates it, and executes the selected option until the user chooses to quit. Args: None Returns: None""" # Get user input # user_input = int(question("Select an option: ")) valid_input = False while not valid_input: try: # Show user options info("\n============ OPTIONS ============", False) for idx, option in enumerate(OPTIONS): print(colored(f" {idx + 1}. {option}", "cyan")) info("=================================\n", False) user_input = input("Select an option: ").strip() if user_input == '': print("\n" * 100) raise ValueError("Empty input is not allowed.") user_input = int(user_input) valid_input = True except ValueError as e: print("\n" * 100) print(f"Invalid input: {e}") # Start the selected option if user_input == 1: info("Starting YT Shorts Automater...") cached_accounts = get_accounts("youtube") if len(cached_accounts) == 0: warning("No accounts found in cache. Create one now?") user_input = question("Yes/No: ") if user_input.lower() == "yes": generated_uuid = str(uuid4()) success(f" => Generated ID: {generated_uuid}") nickname = question(" => Enter a nickname for this account: ") fp_profile = question(" => Enter the path to the Firefox profile: ") niche = question(" => Enter the account niche: ") language = question(" => Enter the account language: ") account_data = { "id": generated_uuid, "nickname": nickname, "firefox_profile": fp_profile, "niche": niche, "language": language, "videos": [], } add_account("youtube", account_data) success("Account configured successfully!") else: table = PrettyTable() table.field_names = ["ID", "UUID", "Nickname", "Niche"] for account in cached_accounts: table.add_row([cached_accounts.index(account) + 1, colored(account["id"], "cyan"), colored(account["nickname"], "blue"), colored(account["niche"], "green")]) print(table) info("Type 'd' to delete an account.", False) user_input = question("Select an account to start (or 'd' to delete): ").strip() if user_input.lower() == "d": delete_input = question("Enter account number to delete: ").strip() account_to_delete = None for account in cached_accounts: if str(cached_accounts.index(account) + 1) == delete_input: account_to_delete = account break if account_to_delete is None: error("Invalid account selected. Please try again.", "red") else: confirm = question(f"Are you sure you want to delete '{account_to_delete['nickname']}'? (Yes/No): ").strip().lower() if confirm == "yes": remove_account("youtube", account_to_delete["id"]) success("Account removed successfully!") else: warning("Account deletion canceled.", False) return selected_account = None for account in cached_accounts: if str(cached_accounts.index(account) + 1) == user_input: selected_account = account if selected_account is None: error("Invalid account selected. Please try again.", "red") main() else: youtube = YouTube( selected_account["id"], selected_account["nickname"], selected_account["firefox_profile"], selected_account["niche"], selected_account["language"] ) while True: rem_temp_files() info("\n============ OPTIONS ============", False) for idx, youtube_option in enumerate(YOUTUBE_OPTIONS): print(colored(f" {idx + 1}. {youtube_option}", "cyan")) info("=================================\n", False) # Get user input user_input = int(question("Select an option: ")) tts = TTS() if user_input == 1: youtube.generate_video(tts) upload_to_yt = question("Do you want to upload this video to YouTube? (Yes/No): ") if upload_to_yt.lower() == "yes": youtube.upload_video() elif user_input == 2: videos = youtube.get_videos() if len(videos) > 0: videos_table = PrettyTable() videos_table.field_names = ["ID", "Date", "Title"] for video in videos: videos_table.add_row([ videos.index(video) + 1, colored(video["date"], "blue"), colored(video["title"][:60] + "...", "green") ]) print(videos_table) else: warning(" No videos found.") elif user_input == 3: info("How often do you want to upload?") info("\n============ OPTIONS ============", False) for idx, cron_option in enumerate(YOUTUBE_CRON_OPTIONS): print(colored(f" {idx + 1}. {cron_option}", "cyan")) info("=================================\n", False) user_input = int(question("Select an Option: ")) cron_script_path = os.path.join(ROOT_DIR, "src", "cron.py") command = ["python", cron_script_path, "youtube", selected_account['id'], get_active_model()] def job(): subprocess.run(command) if user_input == 1: # Upload Once schedule.every(1).day.do(job) success("Set up CRON Job.") elif user_input == 2: # Upload Twice a day schedule.every().day.at("10:00").do(job) schedule.every().day.at("16:00").do(job) success("Set up CRON Job.") else: break elif user_input == 4: if get_verbose(): info(" => Climbing Options Ladder...", False) break elif user_input == 2: info("Starting Twitter Bot...") cached_accounts = get_accounts("twitter") if len(cached_accounts) == 0: warning("No accounts found in cache. Create one now?") user_input = question("Yes/No: ") if user_input.lower() == "yes": generated_uuid = str(uuid4()) success(f" => Generated ID: {generated_uuid}") nickname = question(" => Enter a nickname for this account: ") fp_profile = question(" => Enter the path to the Firefox profile: ") topic = question(" => Enter the account topic: ") add_account("twitter", { "id": generated_uuid, "nickname": nickname, "firefox_profile": fp_profile, "topic": topic, "posts": [] }) else: table = PrettyTable() table.field_names = ["ID", "UUID", "Nickname", "Account Topic"] for account in cached_accounts: table.add_row([cached_accounts.index(account) + 1, colored(account["id"], "cyan"), colored(account["nickname"], "blue"), colored(account["topic"], "green")]) print(table) info("Type 'd' to delete an account.", False) user_input = question("Select an account to start (or 'd' to delete): ").strip() if user_input.lower() == "d": delete_input = question("Enter account number to delete: ").strip() account_to_delete = None for account in cached_accounts: if str(cached_accounts.index(account) + 1) == delete_input: account_to_delete = account break if account_to_delete is None: error("Invalid account selected. Please try again.", "red") else: confirm = question(f"Are you sure you want to delete '{account_to_delete['nickname']}'? (Yes/No): ").strip().lower() if confirm == "yes": remove_account("twitter", account_to_delete["id"]) success("Account removed successfully!") else: warning("Account deletion canceled.", False) return selected_account = None for account in cached_accounts: if str(cached_accounts.index(account) + 1) == user_input: selected_account = account if selected_account is None: error("Invalid account selected. Please try again.", "red") main() else: twitter = Twitter(selected_account["id"], selected_account["nickname"], selected_account["firefox_profile"], selected_account["topic"]) while True: info("\n============ OPTIONS ============", False) for idx, twitter_option in enumerate(TWITTER_OPTIONS): print(colored(f" {idx + 1}. {twitter_option}", "cyan")) info("=================================\n", False) # Get user input user_input = int(question("Select an option: ")) if user_input == 1: twitter.post() elif user_input == 2: posts = twitter.get_posts() posts_table = PrettyTable() posts_table.field_names = ["ID", "Date", "Content"] for post in posts: posts_table.add_row([ posts.index(post) + 1, colored(post["date"], "blue"), colored(post["content"][:60] + "...", "green") ]) print(posts_table) elif user_input == 3: info("How often do you want to post?") info("\n============ OPTIONS ============", False) for idx, cron_option in enumerate(TWITTER_CRON_OPTIONS): print(colored(f" {idx + 1}. {cron_option}", "cyan")) info("=================================\n", False) user_input = int(question("Select an Option: ")) cron_script_path = os.path.join(ROOT_DIR, "src", "cron.py") command = ["python", cron_script_path, "twitter", selected_account['id'], get_active_model()] def job(): subprocess.run(command) if user_input == 1: # Post Once a day schedule.every(1).day.do(job) success("Set up CRON Job.") elif user_input == 2: # Post twice a day schedule.every().day.at("10:00").do(job) schedule.every().day.at("16:00").do(job) success("Set up CRON Job.") elif user_input == 3: # Post thrice a day schedule.every().day.at("08:00").do(job) schedule.every().day.at("12:00").do(job) schedule.every().day.at("18:00").do(job) success("Set up CRON Job.") else: break elif user_input == 4: if get_verbose(): info(" => Climbing Options Ladder...", False) break elif user_input == 3: info("Starting Affiliate Marketing...") cached_products = get_products() if len(cached_products) == 0: warning("No products found in cache. Create one now?") user_input = question("Yes/No: ") if user_input.lower() == "yes": affiliate_link = question(" => Enter the affiliate link: ") twitter_uuid = question(" => Enter the Twitter Account UUID: ") # Find the account account = None for acc in get_accounts("twitter"): if acc["id"] == twitter_uuid: account = acc add_product({ "id": str(uuid4()), "affiliate_link": affiliate_link, "twitter_uuid": twitter_uuid }) afm = AffiliateMarketing(affiliate_link, account["firefox_profile"], account["id"], account["nickname"], account["topic"]) afm.generate_pitch() afm.share_pitch("twitter") else: table = PrettyTable() table.field_names = ["ID", "Affiliate Link", "Twitter Account UUID"] for product in cached_products: table.add_row([cached_products.index(product) + 1, colored(product["affiliate_link"], "cyan"), colored(product["twitter_uuid"], "blue")]) print(table) user_input = question("Select a product to start: ") selected_product = None for product in cached_products: if str(cached_products.index(product) + 1) == user_input: selected_product = product if selected_product is None: error("Invalid product selected. Please try again.", "red") main() else: # Find the account account = None for acc in get_accounts("twitter"): if acc["id"] == selected_product["twitter_uuid"]: account = acc afm = AffiliateMarketing(selected_product["affiliate_link"], account["firefox_profile"], account["id"], account["nickname"], account["topic"]) afm.generate_pitch() afm.share_pitch("twitter") elif user_input == 4: info("Starting Outreach...") outreach = Outreach() outreach.start() elif user_input == 5: if get_verbose(): print(colored(" => Quitting...", "blue")) sys.exit(0) else: error("Invalid option selected. Please try again.", "red") main() if __name__ == "__main__": # Print ASCII Banner print_banner() first_time = get_first_time_running() if first_time: print(colored("Hey! It looks like you're running MoneyPrinter V2 for the first time. Let's get you setup first!", "yellow")) # Setup file tree assert_folder_structure() # Remove temporary files rem_temp_files() # Fetch MP3 Files fetch_songs() # Select Ollama model — use config value if set, otherwise pick interactively configured_model = get_ollama_model() if configured_model: select_model(configured_model) success(f"Using configured model: {configured_model}") else: try: models = list_models() except Exception as e: error(f"Could not connect to Ollama: {e}") sys.exit(1) if not models: error("No models found on Ollama. Pull a model first (e.g. 'ollama pull llama3.2:3b').") sys.exit(1) info("\n========== OLLAMA MODELS =========", False) for idx, model_name in enumerate(models): print(colored(f" {idx + 1}. {model_name}", "cyan")) info("==================================\n", False) model_choice = None while model_choice is None: raw = input(colored("Select a model: ", "magenta")).strip() try: choice_idx = int(raw) - 1 if 0 <= choice_idx < len(models): model_choice = models[choice_idx] else: warning("Invalid selection. Try again.") except ValueError: warning("Please enter a number.") select_model(model_choice) success(f"Using model: {model_choice}") while True: main() ================================================ FILE: src/status.py ================================================ from termcolor import colored def error(message: str, show_emoji: bool = True) -> None: """ Prints an error message. Args: message (str): The error message show_emoji (bool): Whether to show the emoji Returns: None """ emoji = "❌" if show_emoji else "" print(colored(f"{emoji} {message}", "red")) def success(message: str, show_emoji: bool = True) -> None: """ Prints a success message. Args: message (str): The success message show_emoji (bool): Whether to show the emoji Returns: None """ emoji = "✅" if show_emoji else "" print(colored(f"{emoji} {message}", "green")) def info(message: str, show_emoji: bool = True) -> None: """ Prints an info message. Args: message (str): The info message show_emoji (bool): Whether to show the emoji Returns: None """ emoji = "ℹ️" if show_emoji else "" print(colored(f"{emoji} {message}", "magenta")) def warning(message: str, show_emoji: bool = True) -> None: """ Prints a warning message. Args: message (str): The warning message show_emoji (bool): Whether to show the emoji Returns: None """ emoji = "⚠️" if show_emoji else "" print(colored(f"{emoji} {message}", "yellow")) def question(message: str, show_emoji: bool = True) -> str: """ Prints a question message and returns the user's input. Args: message (str): The question message show_emoji (bool): Whether to show the emoji Returns: user_input (str): The user's input """ emoji = "❓" if show_emoji else "" return input(colored(f"{emoji} {message}", "magenta")) ================================================ FILE: src/utils.py ================================================ import os import random import zipfile import requests import platform from status import * from config import * DEFAULT_SONG_ARCHIVE_URLS = [] def close_running_selenium_instances() -> None: """ Closes any running Selenium instances. Returns: None """ try: info(" => Closing running Selenium instances...") # Kill all running Firefox instances if platform.system() == "Windows": os.system("taskkill /f /im firefox.exe") else: os.system("pkill firefox") success(" => Closed running Selenium instances.") except Exception as e: error(f"Error occurred while closing running Selenium instances: {str(e)}") def build_url(youtube_video_id: str) -> str: """ Builds the URL to the YouTube video. Args: youtube_video_id (str): The YouTube video ID. Returns: url (str): The URL to the YouTube video. """ return f"https://www.youtube.com/watch?v={youtube_video_id}" def rem_temp_files() -> None: """ Removes temporary files in the `.mp` directory. Returns: None """ # Path to the `.mp` directory mp_dir = os.path.join(ROOT_DIR, ".mp") files = os.listdir(mp_dir) for file in files: if not file.endswith(".json"): os.remove(os.path.join(mp_dir, file)) def fetch_songs() -> None: """ Downloads songs into songs/ directory to use with geneated videos. Returns: None """ try: info(f" => Fetching songs...") files_dir = os.path.join(ROOT_DIR, "Songs") if not os.path.exists(files_dir): os.mkdir(files_dir) if get_verbose(): info(f" => Created directory: {files_dir}") else: existing_audio_files = [ name for name in os.listdir(files_dir) if os.path.isfile(os.path.join(files_dir, name)) and name.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")) ] if len(existing_audio_files) > 0: return configured_url = get_zip_url().strip() download_urls = [configured_url] if configured_url else [] download_urls.extend(DEFAULT_SONG_ARCHIVE_URLS) archive_path = os.path.join(files_dir, "songs.zip") downloaded = False for download_url in download_urls: try: response = requests.get(download_url, timeout=60) response.raise_for_status() with open(archive_path, "wb") as file: file.write(response.content) SAFE_EXTENSIONS = (".mp3", ".wav", ".m4a", ".aac", ".ogg", ".flac") with zipfile.ZipFile(archive_path, "r") as zf: for member in zf.namelist(): basename = os.path.basename(member) if not basename or not basename.lower().endswith(SAFE_EXTENSIONS): warning(f"Skipping non-audio file in archive: {member}") continue if ".." in member or member.startswith("/"): warning(f"Skipping suspicious path in archive: {member}") continue zf.extract(member, files_dir) downloaded = True break except Exception as err: warning(f"Failed to fetch songs from {download_url}: {err}") if not downloaded: raise RuntimeError( "Could not download a valid songs archive from any configured URL" ) # Remove the zip file if os.path.exists(archive_path): os.remove(archive_path) success(" => Downloaded Songs to ../Songs.") except Exception as e: error(f"Error occurred while fetching songs: {str(e)}") def choose_random_song() -> str: """ Chooses a random song from the songs/ directory. Returns: str: The path to the chosen song. """ try: songs_dir = os.path.join(ROOT_DIR, "Songs") songs = [ name for name in os.listdir(songs_dir) if os.path.isfile(os.path.join(songs_dir, name)) and name.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")) ] if len(songs) == 0: raise RuntimeError("No audio files found in Songs directory") song = random.choice(songs) success(f" => Chose song: {song}") return os.path.join(ROOT_DIR, "Songs", song) except Exception as e: error(f"Error occurred while choosing random song: {str(e)}") raise