├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── examples ├── advanced_example.py ├── basic_example.py └── copyright_detection.py ├── requirements.txt ├── setup.py └── src └── twitch_highlights ├── __init__.py ├── acr_cloud.py ├── clip_edit.py └── twitch_api.py /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distribution 📦 to PyPI and inform the Discord community 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | build-n-publish: 9 | name: Build and publish Python 🐍 distributions 📦 to PyPI 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: '3.x' 17 | - name: Install dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | pip install setuptools wheel 21 | - name: Build distributions 22 | run: | 23 | python setup.py sdist bdist_wheel 24 | - name: Publish distribution 📦 to PyPI 25 | uses: pypa/gh-action-pypi-publish@master 26 | with: 27 | password: ${{ secrets.PYPI_API_TOKEN }} 28 | 29 | discord-notification: 30 | name: Send an announcement to the Discord community channel 💬 31 | runs-on: ubuntu-latest 32 | steps: 33 | - name: Discord notification 34 | env: 35 | DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} 36 | uses: Ilshidur/action-discord@master 37 | with: 38 | args: |+ 39 | :loudspeaker: **Release Alert!** :loudspeaker: 40 | Hi everyone! A new version of the twitch-highlights package has been released: ${{ github.event.release.tag_name }} 📦 41 | 42 | Take a look at the new features and the updated documentation at: https://github.com/pelledrijver/highlights-bot 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/python 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=python 4 | 5 | ### Python ### 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | pip-wheel-metadata/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | pytestdebug.log 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | doc/_build/ 78 | 79 | # PyBuilder 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | #poetry.lock 101 | 102 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 103 | __pypackages__/ 104 | 105 | # Celery stuff 106 | celerybeat-schedule 107 | celerybeat.pid 108 | 109 | # SageMath parsed files 110 | *.sage.py 111 | 112 | # Environments 113 | # .env 114 | .env/ 115 | .venv/ 116 | env/ 117 | venv/ 118 | ENV/ 119 | env.bak/ 120 | venv.bak/ 121 | pythonenv* 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # operating system-related files 145 | *.DS_Store #file properties cache/storage on macOS 146 | Thumbs.db #thumbnail cache on Windows 147 | 148 | # profiling data 149 | .prof 150 | 151 | .idea/ 152 | 153 | 154 | # End of https://www.toptal.com/developers/gitignore/api/python -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DIhttps://requests.readthedocs.io/en/master/user/advanced/STRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Pelle Drijver 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | include LICENSE 3 | 4 | # added by check-manifest 5 | recursive-include examples *.py 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # twitch-highlights 2 | [![GitHub](https://img.shields.io/github/license/pelledrijver/twitch-highlights)](https://github.com/pelledrijver/twitch-highlights/blob/master/LICENSE) 3 | [![PyPI Project](https://img.shields.io/pypi/v/twitch-highlights)](https://pypi.org/project/twitch-highlights/) 4 | [![PyPI Downloads](https://img.shields.io/pypi/dm/twitch-highlights)](https://pypi.org/project/twitch-highlights/) 5 | [![Discord](https://img.shields.io/discord/829297778324537384?color=%237289da&label=discord)](https://discord.gg/SPCj7TURj7) 6 | 7 | An OS-independent and easy-to-use module for creating highlight videos from trending Twitch clips. Twitch highlight videos can be created by either specifying a category or a list of streamer names. 8 | 9 | ## Getting started 10 | ### Installing 11 | ```bash 12 | pip install twitch-highlights 13 | ``` 14 | ### Import 15 | ```python 16 | import twitch_highlights 17 | ``` 18 | 19 | 20 | ## Examples 21 | This section will describe the functions and methods provided by the package. If you would like to get started with some example code, make sure to take a look at the *examples* directory. 22 | 23 | ### TwitchHighlights 24 | The class used to interact with the Twitch API and collect trending clips. By passing *twitch_credentials* and/or *acr_credentials* to the constructor, the proper authentication steps are performed to interact with the APIs. The object returned can be used to generate highlight videos. 25 | ```python 26 | twitch_credentials = { 27 | "client_id": "1at6pyf0lvjk48san9j7fjak6hue2i", 28 | "client_secret": "5i2c7weuz1qmvtahrok6agi7nbqo7d" 29 | } 30 | 31 | acr_credentials = { 32 | "access_key": "m73k42t5v1jttq2h4h1r41v450lgqdpl", 33 | "secret_key": "1haPnq6StnU6S4FqoqzOvNAzLkapbaFeG7Pj945U", 34 | "host": "identify-eu-west-1.acrcloud.com" 35 | } 36 | 37 | TwitchHighlights(twitch_credentials=twitch_credentials, acr_credentials=acr_credentials) 38 | ``` 39 | Arguments: 40 | - **twitch_credentials**: Dictionary storing the *client_id* and *client_secret* keys. Information on how to obtain these credentials can be found [here](https://dev.twitch.tv/docs/authentication#registration). 41 | - **acr_credentials**: *(optional)* Dictionary storing the *access_key*, *secret_key* and, *host* keys. ACR is used for copyright music detection. Information on how to obtain these credentials can be found [here](https://www.acrcloud.com/music-recognition/). 42 | 43 | ### make_video_by_category 44 | Creates a highlight video consisting of trending clip from the provided category in the current directory. 45 | ```python 46 | highlight_generator.make_video_by_category(category = "Just Chatting", language = "en", video_length = 500) 47 | ``` 48 | Arguments: 49 | - **category**: Name of the category from which the clips are gathered (case-insensitive). 50 | - **output_name**: Name of the generated output mp4 file. Defaults to *"output_video"*. 51 | - **language**: Preferred language of the clips to be included in the video. Note that the clip's language tag might not actually match the language spoken in the clip. Defaults to *None*, which means that no clips are removed. 52 | - **video_length**: Minimum length of the video to be created in seconds. Clips are added to the combined video until this length is reached. Defaults to *300*. 53 | - **started_at**: Starting date/time for included clips as a datetime object in the UTC standard. Defaults to exactly one day before the time at which the method is called. 54 | - **ended_at**: Ending date/time for included clips as a datetime object in the UTC standard. Defaults to the time at which the method is called. 55 | - **render_settings**: Dictionary containing information used for rendering and combining the clips. More information [here](#render_settings). Defaults to *None*. 56 | - **sort_by**: Preferred ordering of clips (*"popularity", "chronologically", or "random"*). Defaults to *"popularity"*. 57 | - **filter_copyright**: If set to True, clips containing copyrighted music are not included in the video. Defaults to False. 58 | 59 | 60 | ### make_video_by_streamer 61 | Creates a highlight video consisting of trending clip from the provided category in the current directory. 62 | ```python 63 | highlight_generator.make_video_by_streamer(streamers = ["Ninja", "Myth"]) 64 | ``` 65 | Arguments: 66 | - **streamers**: List of streamer names to gather clips from. 67 | - **output_name**: Name of the generated output mp4 file. Defaults to *"output_video"*. 68 | - **language**: Preferred language of the clips to be included in the video. Note that the clip's language tag might not actually match the language spoken in the clip. Defaults to *None*, which means that no clips are removed. 69 | - **video_length**: Minimum length of the video to be created in seconds. Clips are added to the combined video until this length is reached. Defaults to *300*. 70 | - **started_at**: Starting date/time for included clips as a datetime object in the UTC standard. Defaults to exactly one day before the time at which the method is called. 71 | - **ended_at**: Ending date/time for included clips as a datetime object in the UTC standard. Defaults to the time at which the method is called. 72 | - **render_settings**: Dictionary containing information used for rendering and combining the clips. More information [here](#render_settings). Defaults to *None*. 73 | - **sort_by**: Preferred ordering of clips (*"popularity", "chronologically", or "random"*). Defaults to *"popularity"*. 74 | - **filter_copyright**: If set to True, clips containing copyrighted music are not included in the video. Defaults to False. 75 | 76 | 77 | ### get_top_categories 78 | Returns a list of the names of the most trending categories on Twitch at the moment of invocation. 79 | ```python 80 | highlight_generator.get_top_categories(5) 81 | ``` 82 | Arguments: 83 | - **amount**: Maximum number of categories to return. Maximum: 100. Defaults to *20*. 84 | 85 | 86 | ### render_settings 87 | Dictionary containing information used for rendering and combining the clips. When *None* is passed or if any of the keys is missing, the default values are used. 88 | 89 | Keys: 90 | - **intro_path**: Path to the file containing the intro video that has to be added to the start of the generated video. If not specified, no intro is added. 91 | - **transition_path**: Path to the file containing the transition video that has to be added between each of the clips in the generated video. If not specified, no transitions are added. 92 | - **outro_path**: Path to the file containing the outro video that has to be added to the end of the generated video. If not specified, no outro is added. 93 | - **target_resolution**: Tuple containing (desired_height, desired_width) to which the resolution is resized. Defaults to *(1080, 1920)*. 94 | - **fps**: Number of frames per second. Defaults to *60*. 95 | 96 | ## License 97 | [Apache-2.0](https://github.com/pelledrijver/twitch-highlights/blob/dev/LICENSE) 98 | 99 | ## Contributing 100 | So far, I have been the only one who has worked on the project, and it would be great if I could get an extra pair of hands. Feel free to contact me if you have any great ideas and would like to contribute to this project. New features I'm currently working on are: 101 | - Uploading the created video directly to YouTube 102 | - The option to have a small animation with the name of the streamer at the start of each clip -------------------------------------------------------------------------------- /examples/advanced_example.py: -------------------------------------------------------------------------------- 1 | from twitch_highlights import TwitchHighlights 2 | from datetime import datetime, timedelta 3 | 4 | twitch_credentials = { 5 | "client_id": "##############################", # Your client id here 6 | "client_secret": "##############################" # Your client secret here 7 | } 8 | 9 | render_settings = { 10 | 'intro_path': "##############################", # Path to intro video file 11 | 'outro_path': "##############################", # Path to outro video file 12 | 'transition_path': "##############################" # Path to transition video file 13 | } 14 | 15 | started_at = datetime.utcnow() - timedelta(days=7) # Starting date/time for included clips. Currently set to one week ago. 16 | ended_at = datetime.utcnow() - timedelta(days=1) # Ending date/time for included clips. Currently set to one week ago. 17 | 18 | highlight_generator = TwitchHighlights(twitch_credentials=twitch_credentials) 19 | 20 | highlight_generator.make_video_by_category(category="Fortnite", output_name="epic_highlight_video", 21 | language="fr", video_length=100, started_at=started_at, 22 | ended_at=ended_at, render_settings=render_settings, 23 | sort_by="chronologically") 24 | -------------------------------------------------------------------------------- /examples/basic_example.py: -------------------------------------------------------------------------------- 1 | from twitch_highlights import TwitchHighlights 2 | 3 | twitch_credentials = { 4 | "client_id": "##############################", # Your client id here 5 | "client_secret": "##############################" # Your client secret here 6 | } 7 | 8 | highlight_generator = TwitchHighlights(twitch_credentials=twitch_credentials) 9 | 10 | highlight_generator.make_video_by_category(category="Fortnite") 11 | -------------------------------------------------------------------------------- /examples/copyright_detection.py: -------------------------------------------------------------------------------- 1 | from twitch_highlights import TwitchHighlights 2 | 3 | twitch_credentials = { 4 | "client_id": "##############################", # Your client id here 5 | "client_secret": "##############################" # Your client secret here 6 | } 7 | 8 | acr_credentials = { 9 | "access_key": "################################", # Your access key here 10 | "secret_key": "########################################", # Your secret key here 11 | "host": "###############################" # Your host here 12 | } 13 | 14 | highlight_generator = TwitchHighlights(twitch_credentials=twitch_credentials, acr_credentials=acr_credentials) 15 | 16 | highlight_generator.make_video_by_category(category="Music", filter_copyright=True) 17 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | DateTime==4.3 2 | moviepy==1.0.3 3 | requests==2.25.1 4 | python-slugify==4.0.1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setup( 7 | author='Pelle Drijver', 8 | author_email='pelledrijver@gmail.com', 9 | url='https://github.com/pelledrijver/twitch-highlights', 10 | name='twitch-highlights', 11 | version='1.1.1', 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | description="An OS-independent and easy-to-use module for creating highlight videos from trending Twitch clips. " 15 | "Twitch highlight videos can be created by either specifying a category or a list of streamer " 16 | "names.", 17 | keywords="twitch, twitch highlights, twitch clips, twitch compilation", 18 | install_requires=[ 19 | 'requests', 20 | 'datetime', 21 | 'moviepy>=1.0.3', 22 | 'python-slugify>=4.0' 23 | ], 24 | package_dir={'': 'src'}, 25 | packages=['twitch_highlights'], 26 | license='Apache License 2.0', 27 | classifiers=[ 28 | 'Programming Language :: Python :: 3', 29 | 'Programming Language :: Python :: 3.6', 30 | 'Programming Language :: Python :: 3.7', 31 | 'Programming Language :: Python :: 3.8', 32 | 'License :: OSI Approved :: Apache Software License', 33 | 'Operating System :: OS Independent' 34 | ] 35 | ) 36 | -------------------------------------------------------------------------------- /src/twitch_highlights/__init__.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from . import twitch_api 3 | from . import clip_edit 4 | from . import acr_cloud 5 | 6 | 7 | class TwitchHighlights: 8 | def __init__(self, twitch_credentials, acr_credentials=None): 9 | self.twitch_oauth_header = twitch_api.login(twitch_credentials) 10 | 11 | if acr_credentials: 12 | self.acr_credentials = acr_cloud.login(acr_credentials) 13 | 14 | def get_top_categories(self, amount=20): 15 | return twitch_api.get_top_categories(self.twitch_oauth_header, amount) 16 | 17 | def make_video_by_category(self, category, output_name="output_video", language=None, video_length=300, 18 | started_at=datetime.utcnow() - timedelta(days=1), ended_at=datetime.utcnow(), 19 | render_settings=None, sort_by="popularity", filter_copyright=False): 20 | acr_credentials = None 21 | if filter_copyright: 22 | self.check_acr_cloud_credentials() 23 | acr_credentials = self.acr_credentials 24 | 25 | clips = twitch_api.get_clips_by_category(self.twitch_oauth_header, category, started_at, ended_at) 26 | clip_edit.create_video_from_json(clips, output_name, language, video_length, render_settings, sort_by, 27 | filter_copyright, acr_credentials) 28 | 29 | def make_video_by_streamer(self, streamers, output_name="output_video", language=None, video_length=300, 30 | started_at=datetime.utcnow() - timedelta(days=1), ended_at=datetime.utcnow(), 31 | render_settings=None, sort_by="popularity", filter_copyright=False): 32 | acr_credentials = None 33 | if filter_copyright: 34 | self.check_acr_cloud_credentials() 35 | acr_credentials = self.acr_credentials 36 | 37 | clips = [] 38 | for streamer in streamers: 39 | clips.extend(twitch_api.get_clips_by_streamer(self.twitch_oauth_header, streamer, started_at, ended_at)) 40 | 41 | clip_edit.create_video_from_json(clips, output_name, language, video_length, render_settings, sort_by, 42 | filter_copyright, acr_credentials) 43 | 44 | def check_acr_cloud_credentials(self): 45 | if not hasattr(self, "acr_credentials"): 46 | raise Exception("No ACRCloud credentials have been found. Please make sure to pass the ACR credentials " 47 | "to the TwitchHighlights constructor.") 48 | -------------------------------------------------------------------------------- /src/twitch_highlights/acr_cloud.py: -------------------------------------------------------------------------------- 1 | from moviepy.editor import VideoFileClip 2 | import os 3 | import base64 4 | import hmac 5 | import hashlib 6 | import time 7 | import requests 8 | 9 | 10 | # https://docs.acrcloud.com/reference/identification-api 11 | 12 | def login(acr_credentials): 13 | access_key = acr_credentials["access_key"] 14 | access_secret = acr_credentials["secret_key"] 15 | 16 | requrl = f'https://{acr_credentials["host"]}/v1/identify' 17 | timestamp = time.time() 18 | 19 | string_to_sign = f'POST\n/v1/identify\n{access_key}\naudio\n1\n{str(timestamp)}' 20 | sign = base64.b64encode(hmac.new(bytes(access_secret, encoding="utf8"), bytes(string_to_sign, encoding="utf8"), 21 | digestmod=hashlib.sha1).digest()) 22 | 23 | data = {'access_key': access_key, 24 | 'sample_bytes': 0, 25 | 'timestamp': str(timestamp), 26 | 'signature': sign, 27 | 'data_type': "audio", 28 | "signature_version": "1"} 29 | 30 | response = requests.post(requrl, files=None, data=data) 31 | 32 | if response.status_code != 200: 33 | raise Exception(f'An error occured while authenticating ACRCloud: {response.json()}') 34 | 35 | if response.json()["status"]["code"] != 3006: 36 | raise Exception("An error occured while authenticating ACRCloud: invalid credentials", 37 | response.json()["status"]["msg"]) 38 | 39 | return acr_credentials 40 | 41 | 42 | def is_copyright(file_path, acr_credentials): 43 | access_key = acr_credentials["access_key"] 44 | access_secret = acr_credentials["secret_key"] 45 | requrl = f'https://{acr_credentials["host"]}/v1/identify' 46 | 47 | temp_dir = os.path.dirname(os.path.realpath(file_path)) 48 | audio_file_path = os.path.join(temp_dir, 'temp.mp3') 49 | 50 | video = VideoFileClip(file_path) 51 | audio = video.audio 52 | audio.write_audiofile(audio_file_path, logger=None) 53 | audio.close() 54 | video.close() 55 | 56 | timestamp = time.time() 57 | 58 | string_to_sign = f'POST\n/v1/identify\n{access_key}\naudio\n1\n{str(timestamp)}' 59 | sign = base64.b64encode(hmac.new(bytes(access_secret, encoding="utf8"), bytes(string_to_sign, encoding="utf8"), 60 | digestmod=hashlib.sha1).digest()) 61 | 62 | f = open(audio_file_path, "rb") 63 | sample_bytes = os.path.getsize(audio_file_path) 64 | 65 | files = [ 66 | ('sample', ('temp.mp3', f, 'audio/mpeg')) 67 | ] 68 | data = {'access_key': access_key, 69 | 'sample_bytes': sample_bytes, 70 | 'timestamp': str(timestamp), 71 | 'signature': sign, 72 | 'data_type': "audio", 73 | "signature_version": "1"} 74 | 75 | response = requests.post(requrl, files=files, data=data) 76 | response.encoding = "utf-8" 77 | 78 | f.close() 79 | os.remove(audio_file_path) 80 | 81 | if response.status_code != 200: 82 | raise Exception(response.json()) 83 | 84 | error_code = response.json()["status"]["code"] 85 | 86 | if error_code != 0 and error_code != 1001: 87 | raise Exception(response.json()["status"]["msg"]) 88 | 89 | return error_code == 0 90 | -------------------------------------------------------------------------------- /src/twitch_highlights/clip_edit.py: -------------------------------------------------------------------------------- 1 | from moviepy.editor import VideoFileClip, concatenate_videoclips 2 | from slugify import slugify 3 | from tqdm import tqdm 4 | import tempfile 5 | import random 6 | import proglog 7 | import requests 8 | import os 9 | import shutil 10 | from . import acr_cloud 11 | 12 | 13 | def sort_clips_chronologically(clips): 14 | clips.sort(key=lambda k: k["created_at"]) 15 | 16 | 17 | def sort_clips_popularity(clips): 18 | clips.sort(key=lambda k: k["view_count"], reverse=True) 19 | 20 | 21 | def sort_clips_randomly(clips): 22 | clips.sort(random.shuffle(clips)) 23 | 24 | 25 | def add_clip(clip_list, file_path, render_settings): 26 | if len(clip_list) == 0 and 'intro_path' in render_settings: 27 | clip_list.append( 28 | VideoFileClip(render_settings['intro_path'], target_resolution=render_settings["target_resolution"])) 29 | 30 | if 'transition_path' in render_settings and len(clip_list) != 0: 31 | clip_list.append( 32 | VideoFileClip(render_settings['transition_path'], target_resolution=render_settings["target_resolution"])) 33 | 34 | clip_list.append(VideoFileClip(file_path, target_resolution=render_settings["target_resolution"])) 35 | 36 | 37 | def download_clip(session, clip, file_path): 38 | video_url = clip["video_url"] 39 | 40 | response = session.get(video_url, stream=True) 41 | total_size_in_bytes = int(response.headers.get('content-length', 0)) 42 | progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True) 43 | 44 | f = open(file_path, 'wb') 45 | for chunk in response.iter_content(chunk_size=1024 * 1024): 46 | if chunk: 47 | progress_bar.update(len(chunk)) 48 | f.write(chunk) 49 | f.close() 50 | progress_bar.close() 51 | 52 | 53 | def get_combined_video_length(clip_list): 54 | sum = 0 55 | for clip in clip_list: 56 | sum += clip.duration 57 | return sum 58 | 59 | 60 | def check_render_settings(render_settings): 61 | if render_settings is None: 62 | render_settings = dict() 63 | render_settings["fps"] = 60 64 | render_settings["target_resolution"] = (1080, 1920) 65 | return render_settings 66 | 67 | if 'fps' not in render_settings: 68 | render_settings['fps'] = 60 69 | 70 | if 'target_resolution' not in render_settings: 71 | render_settings['target_resolution'] = (1080, 1920) 72 | 73 | if 'intro_path' in render_settings: 74 | temp = VideoFileClip(render_settings['intro_path'], target_resolution=render_settings["target_resolution"]) 75 | temp.close() 76 | 77 | if 'outro_path' in render_settings: 78 | temp = VideoFileClip(render_settings['outro_path'], target_resolution=render_settings["target_resolution"]) 79 | temp.close() 80 | 81 | if 'transition_path' in render_settings: 82 | temp = VideoFileClip(render_settings['transition_path'], target_resolution=render_settings["target_resolution"]) 83 | temp.close() 84 | 85 | return render_settings 86 | 87 | 88 | def merge_videos(clip_list, output_name, render_settings): 89 | if len(clip_list) == 0: 90 | raise Exception("No clips have been found with the specified preferences. " 91 | "Try different preferences instead.") 92 | 93 | if 'outro_path' in render_settings: 94 | clip_list.append( 95 | VideoFileClip(render_settings['outro_path'], target_resolution=render_settings["target_resolution"])) 96 | 97 | merged_video = concatenate_videoclips(clip_list, method="compose") 98 | temp_dir_path = get_temp_dir() 99 | print(f"Writing video file to {output_name}.mp4") 100 | 101 | merged_video.write_videofile( 102 | f"{output_name}.mp4", 103 | codec="libx264", 104 | fps=render_settings['fps'], 105 | temp_audiofile=os.path.join(temp_dir_path, "temp-audio.m4a"), 106 | remove_temp=True, 107 | audio_codec="aac", 108 | logger=proglog.TqdmProgressBarLogger(print_messages=False)) 109 | 110 | merged_video.close() 111 | for clip in clip_list: 112 | clip.close() 113 | 114 | print(f'Successfully generated highlight video "{output_name}"!') 115 | 116 | 117 | def preprocess_clips(clips, language): 118 | for clip in clips: 119 | video_url = clip["thumbnail_url"].split("-preview")[0] + ".mp4" 120 | clip["video_url"] = video_url 121 | 122 | if language is not None: 123 | return [clip for clip in clips if language in clip["language"]] 124 | 125 | return clips 126 | 127 | 128 | def create_video_from_json(clips, output_name, language, video_length, render_settings, sort_by, filter_copyright, 129 | acr_credentials=None): 130 | print("Successfully fetched clip data") 131 | 132 | remove_tmp_content() 133 | temp_dir_path = get_temp_dir() 134 | clips = preprocess_clips(clips, language) 135 | render_settings = check_render_settings(render_settings) 136 | 137 | if sort_by == "random": 138 | sort_clips_randomly(clips) 139 | elif sort_by == "popularity": 140 | sort_clips_popularity(clips) 141 | elif sort_by == "chronologically": 142 | sort_clips_chronologically(clips) 143 | else: 144 | Exception(f'Sorting method {sort_by} not recognized.') 145 | 146 | clip_list = [] 147 | 148 | with requests.Session() as s: 149 | for clip in clips: 150 | if get_combined_video_length(clip_list) >= video_length: 151 | break 152 | 153 | print(f'Downloading clip: {clip["broadcaster_name"]} - {clip["title"]}') 154 | file_name = slugify(f'{clip["title"]} - {clip["video_id"]}') 155 | file_path = os.path.join(temp_dir_path, f'{file_name}.mp4') 156 | download_clip(s, clip, file_path) 157 | 158 | if filter_copyright: 159 | print("Checking for copyrighted music...") 160 | 161 | if acr_cloud.is_copyright(file_path, acr_credentials): 162 | print("Copyrighted music has been detected in clip. Clip removed!") 163 | os.remove(file_path) 164 | continue 165 | else: 166 | print("No copyrighted music has been found!") 167 | 168 | add_clip(clip_list, file_path, render_settings) 169 | 170 | merge_videos(clip_list, output_name, render_settings) 171 | 172 | shutil.rmtree(temp_dir_path) 173 | 174 | 175 | def remove_tmp_content(): 176 | temp_dir_path = get_temp_dir() 177 | 178 | if os.path.isdir(temp_dir_path): 179 | shutil.rmtree(temp_dir_path) 180 | os.mkdir(temp_dir_path) 181 | 182 | 183 | def get_temp_dir(): 184 | temp_dir_path = os.path.join(tempfile.gettempdir(), "twitch_highlights") 185 | return temp_dir_path 186 | -------------------------------------------------------------------------------- /src/twitch_highlights/twitch_api.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | TWITCH_OAUTH_ENDPOINT = "https://id.twitch.tv/oauth2/token" 4 | TWITCH_CLIPS_ENDPOINT = "https://api.twitch.tv/helix/clips" 5 | TWITCH_CATEGORY_ENDPOINT = "https://api.twitch.tv/helix/search/categories" 6 | TWITCH_TOP_GAMES_ENDPOINT = "https://api.twitch.tv/helix/games/top" 7 | TWITCH_BROADCASTER_ENDPOINT = "https://api.twitch.tv/helix/users" 8 | 9 | 10 | def login(twitch_credentials): 11 | twitch_client_id = twitch_credentials["client_id"] 12 | twitch_client_secret = twitch_credentials["client_secret"] 13 | query_parameters = f'?client_id={twitch_client_id}&client_secret={twitch_client_secret}&grant_type=client_credentials' 14 | 15 | response = requests.post(TWITCH_OAUTH_ENDPOINT + query_parameters) 16 | if response.status_code != 200: 17 | raise Exception(f'An error occured while authenticating Twitch: {response.json()["message"]}') 18 | 19 | twitch_token = response.json()['access_token'] 20 | twitch_oauth_header = {"Client-ID": twitch_client_id, 21 | "Authorization": f"Bearer {twitch_token}"} 22 | 23 | return twitch_oauth_header 24 | 25 | 26 | def get_request(twitch_oauth_header, endpoint_url, query_parameters, error_message="An error occurred"): 27 | response = requests.get(endpoint_url + query_parameters, headers=twitch_oauth_header) 28 | 29 | if response.status_code != 200: 30 | raise Exception(response.json()) 31 | 32 | if response.json()["data"] is None: 33 | raise Exception(error_message) 34 | 35 | return response.json()["data"] 36 | 37 | 38 | def get_top_categories(twitch_oauth_header, amount=20): 39 | categories_json = get_request(twitch_oauth_header, TWITCH_TOP_GAMES_ENDPOINT, f"?first={amount}") 40 | categories = [] 41 | 42 | for category in categories_json: 43 | categories.append(category['name']) 44 | 45 | return categories 46 | 47 | 48 | def get_category_id(twitch_credentials, category_name): 49 | query_parameters = f'?query={category_name}' 50 | error_message = f'Twitch category not found: "{category_name}"' 51 | category_list = get_request(twitch_credentials, TWITCH_CATEGORY_ENDPOINT, query_parameters, error_message) 52 | found_category = next((category for category in category_list if category["name"].lower() == category_name.lower()), 53 | None) 54 | 55 | if found_category is None: 56 | raise Exception(f'Category with name "{category_name}" not found.') 57 | 58 | return found_category["id"] 59 | 60 | 61 | def get_broadcaster_id(twitch_credentials, broadcaster_name): 62 | query_parameters = f'?login={broadcaster_name}' 63 | broadcaster_data = get_request(twitch_credentials, TWITCH_BROADCASTER_ENDPOINT, query_parameters) 64 | if len(broadcaster_data) == 0: 65 | raise Exception(f'Broadcaster with name "{broadcaster_name}" not found.') 66 | 67 | return broadcaster_data[0]["id"] 68 | 69 | 70 | def get_clips_by_category(twitch_credentials, category_name, started_at, ended_at): 71 | started_at = started_at.isoformat("T") + "Z" 72 | ended_at = ended_at.isoformat("T") + "Z" 73 | category_id = get_category_id(twitch_credentials, category_name) 74 | query_parameters = f'?game_id={category_id}&first=100&started_at={started_at}&ended_at={ended_at}' 75 | return get_request(twitch_credentials, TWITCH_CLIPS_ENDPOINT, query_parameters) 76 | 77 | 78 | def get_clips_by_streamer(twitch_credentials, streamer_name, started_at, ended_at): 79 | started_at = started_at.isoformat("T") + "Z" 80 | ended_at = ended_at.isoformat("T") + "Z" 81 | broadcaster_id = get_broadcaster_id(twitch_credentials, streamer_name) 82 | query_parameters = f'?broadcaster_id={broadcaster_id}&first=100&started_at={started_at}&ended_at={ended_at}' 83 | 84 | return get_request(twitch_credentials, TWITCH_CLIPS_ENDPOINT, query_parameters) 85 | --------------------------------------------------------------------------------