
Webpage Singer 🎶
Try for free
This Actor is paid per event
Go to Store

Webpage Singer 🎶
josef.prochazka/webpage-singer
Try for free
This Actor is paid per event
Ever wondered what a website would sound like as a song? This Actor takes any webpage, turns its content into lyrics, and transforms it into a track in your favorite genre. Just drop in a URL, pick a style, and let the AI do the rest.
Developer
Maintained by Community
Actor Metrics
17 Monthly users
5.0 / 5 (1)
5 bookmarks
84% runs succeeded
Created in Feb 2025
Modified a day ago
Categories
.dockerignore
1.git
2.mise.toml
3.nvim.lua
4storage
5
6# The rest is copied from https://github.com/github/gitignore/blob/main/Python.gitignore
7
8# Byte-compiled / optimized / DLL files
9__pycache__/
10*.py[cod]
11*$py.class
12
13# C extensions
14*.so
15
16# Distribution / packaging
17.Python
18build/
19develop-eggs/
20dist/
21downloads/
22eggs/
23.eggs/
24lib/
25lib64/
26parts/
27sdist/
28var/
29wheels/
30share/python-wheels/
31*.egg-info/
32.installed.cfg
33*.egg
34MANIFEST
35
36# PyInstaller
37# Usually these files are written by a python script from a template
38# before PyInstaller builds the exe, so as to inject date/other infos into it.
39*.manifest
40*.spec
41
42# Installer logs
43pip-log.txt
44pip-delete-this-directory.txt
45
46# Unit test / coverage reports
47htmlcov/
48.tox/
49.nox/
50.coverage
51.coverage.*
52.cache
53nosetests.xml
54coverage.xml
55*.cover
56*.py,cover
57.hypothesis/
58.pytest_cache/
59cover/
60
61# Translations
62*.mo
63*.pot
64
65# Django stuff:
66*.log
67local_settings.py
68db.sqlite3
69db.sqlite3-journal
70
71# Flask stuff:
72instance/
73.webassets-cache
74
75# Scrapy stuff:
76.scrapy
77
78# Sphinx documentation
79docs/_build/
80
81# PyBuilder
82.pybuilder/
83target/
84
85# Jupyter Notebook
86.ipynb_checkpoints
87
88# IPython
89profile_default/
90ipython_config.py
91
92# pyenv
93# For a library or package, you might want to ignore these files since the code is
94# intended to run in multiple environments; otherwise, check them in:
95.python-version
96
97# pdm
98# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
99#pdm.lock
100# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
101# in version control.
102# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
103.pdm.toml
104.pdm-python
105.pdm-build/
106
107# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
108__pypackages__/
109
110# Celery stuff
111celerybeat-schedule
112celerybeat.pid
113
114# SageMath parsed files
115*.sage.py
116
117# Environments
118.env
119.venv
120env/
121venv/
122ENV/
123env.bak/
124venv.bak/
125
126# Spyder project settings
127.spyderproject
128.spyproject
129
130# Rope project settings
131.ropeproject
132
133# mkdocs documentation
134/site
135
136# mypy
137.mypy_cache/
138.dmypy.json
139dmypy.json
140
141# Pyre type checker
142.pyre/
143
144# pytype static type analyzer
145.pytype/
146
147# Cython debug symbols
148cython_debug/
149
150# PyCharm
151# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
152# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
153# and can be added to the global gitignore or merged into this file. For a more nuclear
154# option (not recommended) you can uncomment the following to ignore the entire idea folder.
155.idea/
.gitignore
1.mise.toml
2.nvim.lua
3storage
4
5# The rest is copied from https://github.com/github/gitignore/blob/main/Python.gitignore
6
7# Byte-compiled / optimized / DLL files
8__pycache__/
9*.py[cod]
10*$py.class
11
12# C extensions
13*.so
14
15# Distribution / packaging
16.Python
17build/
18develop-eggs/
19dist/
20downloads/
21eggs/
22.eggs/
23lib/
24lib64/
25parts/
26sdist/
27var/
28wheels/
29share/python-wheels/
30*.egg-info/
31.installed.cfg
32*.egg
33MANIFEST
34
35# PyInstaller
36# Usually these files are written by a python script from a template
37# before PyInstaller builds the exe, so as to inject date/other infos into it.
38*.manifest
39*.spec
40
41# Installer logs
42pip-log.txt
43pip-delete-this-directory.txt
44
45# Unit test / coverage reports
46htmlcov/
47.tox/
48.nox/
49.coverage
50.coverage.*
51.cache
52nosetests.xml
53coverage.xml
54*.cover
55*.py,cover
56.hypothesis/
57.pytest_cache/
58cover/
59
60# Translations
61*.mo
62*.pot
63
64# Django stuff:
65*.log
66local_settings.py
67db.sqlite3
68db.sqlite3-journal
69
70# Flask stuff:
71instance/
72.webassets-cache
73
74# Scrapy stuff:
75.scrapy
76
77# Sphinx documentation
78docs/_build/
79
80# PyBuilder
81.pybuilder/
82target/
83
84# Jupyter Notebook
85.ipynb_checkpoints
86
87# IPython
88profile_default/
89ipython_config.py
90
91# pyenv
92# For a library or package, you might want to ignore these files since the code is
93# intended to run in multiple environments; otherwise, check them in:
94.python-version
95
96# pdm
97# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
98#pdm.lock
99# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
100# in version control.
101# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
102.pdm.toml
103.pdm-python
104.pdm-build/
105
106# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
107__pypackages__/
108
109# Celery stuff
110celerybeat-schedule
111celerybeat.pid
112
113# SageMath parsed files
114*.sage.py
115
116# Environments
117.env
118.venv
119env/
120venv/
121ENV/
122env.bak/
123venv.bak/
124
125# Spyder project settings
126.spyderproject
127.spyproject
128
129# Rope project settings
130.ropeproject
131
132# mkdocs documentation
133/site
134
135# mypy
136.mypy_cache/
137.dmypy.json
138dmypy.json
139
140# Pyre type checker
141.pyre/
142
143# pytype static type analyzer
144.pytype/
145
146# Cython debug symbols
147cython_debug/
148
149# PyCharm
150# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
151# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
152# and can be added to the global gitignore or merged into this file. For a more nuclear
153# option (not recommended) you can uncomment the following to ignore the entire idea folder.
154.idea/
155
156# Added by Apify CLI
157node_modules
LICENSE
1Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
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 2023 Apify Technologies s.r.o.
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.
requirements.txt
1# Feel free to add your Python dependencies below. For formatting guidelines, see:
2# https://pip.pypa.io/en/latest/reference/requirements-file-format/
3
4apify < 3.0
5openai == 1.63.*
6requests
.actor/Dockerfile
1# First, specify the base Docker image.
2# You can see the Docker images from Apify at https://hub.docker.com/r/apify/.
3# You can also use any other image from Docker Hub.
4FROM apify/actor-python:3.13
5
6# Second, copy just requirements.txt into the Actor image,
7# since it should be the only file that affects the dependency install in the next step,
8# in order to speed up the build
9COPY requirements.txt ./
10
11# Install the packages specified in requirements.txt,
12# Print the installed Python version, pip version
13# and all installed packages with their versions for debugging
14RUN echo "Python version:" \
15 && python --version \
16 && echo "Pip version:" \
17 && pip --version \
18 && echo "Installing dependencies:" \
19 && pip install -r requirements.txt \
20 && echo "All installed Python packages:" \
21 && pip freeze
22
23# Next, copy the remaining files and directories with the source code.
24# Since we do this after installing the dependencies, quick build will be really fast
25# for most source file changes.
26COPY . ./
27
28# Use compileall to ensure the runnability of the Actor Python code.
29RUN python3 -m compileall -q .
30
31# Specify how to launch the source code of your Actor.
32# By default, the "python3 -m src" command is run
33CMD ["python3", "-m", "src"]
.actor/actor.json
1{
2 "actorSpecification": 1,
3 "name": "webpage-singer",
4 "title": "Webpage Singer",
5 "description": "Ever wondered what a website would sound like as a song? This Actor takes any webpage, turns its content into lyrics, and transforms it into a track in your favorite genre. Just drop in a URL, pick a style, and let the AI do the rest.",
6 "version": "0.0",
7 "buildTag": "latest",
8 "meta": {
9 "templateId": "python-start"
10 },
11 "input": "./input_schema.json",
12 "dockerfile": "./Dockerfile",
13 "storages": {
14 "dataset": "./dataset_schema.json"
15 }
16}
.actor/dataset_schema.json
1{
2 "actorSpecification": 1,
3 "views": {
4 "overview": {
5 "title": "Overview",
6 "transformation": {
7 "fields": [
8 "variant", "download url", "play url", "lyrics"
9 ]
10 },
11 "display": {
12 "component": "table",
13 "properties": {
14 "variant": {
15 "label": "variant",
16 "format": "text"
17 },
18 "play url": {
19 "label": "play url",
20 "format": "link"
21 },
22 "download url": {
23 "label": "download url",
24 "format": "link"
25 },
26 "lyrics": {
27 "label": "lyrics",
28 "format": "text"
29 }
30 }
31 }
32 }
33 }
34}
.actor/input_schema.json
1{
2 "title": "Scrape data from a web page",
3 "type": "object",
4 "schemaVersion": 1,
5 "properties": {
6 "url": {
7 "title": "Page URL",
8 "type": "string",
9 "description": "Just enter the URL of a web page and it will be used to generate lyrics for the song.",
10 "editor": "textfield",
11 "prefill": "https://apify.com/about"
12 },
13 "topmediai_api_key": {
14 "title": "API key for TopMediai",
15 "type": "string",
16 "isSecret": true,
17 "description": "If you provide your own TopMediai API key, you will be charged less.",
18 "editor": "textfield"
19 },
20 "song_genre": {
21 "title": "Song genre",
22 "type": "string",
23 "description": "Song genre used to generate the song. If you don't provide a genre, the AI will suggest one based on the page content.",
24 "editor": "textfield",
25 "prefill": "Hip Hop"
26 }
27
28 },
29 "required": ["url"]
30}
src/__init__.py
src/__main__.py
1import asyncio
2
3from .main import main
4
5# Execute the Actor entry point.
6asyncio.run(main())
src/fetch_content.py
1from apify import Actor
2
3
4async def fetch_content(url):
5 run = await Actor.call(
6 actor_id="apify/website-content-crawler",
7 run_input={
8 "startUrls": [{"url": url}],
9 "maxCrawlPages": 1,
10 "crawlerType": "playwright:adaptive",
11 "proxyConfiguration": {
12 "useApifyProxy": True,
13 },
14 },
15 memory_mbytes=4096, # Reduce memory so that it can run on free accounts.
16 )
17
18 if run is None or run.status != "SUCCEEDED":
19 raise RuntimeError("Website Content Crawler failed to scrape the page")
20
21 page = await Actor.apify_client.dataset(run.default_dataset_id).list_items(limit=1)
22
23 if not page.items:
24 raise ValueError("No content scraped")
25
26 return page.items[0].get("markdown")
src/lyrics_generation.py
1from src.open_ai import get_open_api_client, OPENAI_MODEL
2
3SYSTEM_PROMPT = """
4You are a helpful, analytical assistant that can summarize text. You try to be non-biased and sticking to facts.
5"""
6
7USER_PROMPT = """
8Summarize the following text into a song-like structure.
9
10 - It should consist of max 4 verses, each around 30 words, all of the roughly same length.
11 - Don't rhyme it, unless the text is in English.
12 - The text remains understandable, clear and factual.
13 - Don't change the meaning, the story should stay as is.
14 - Stick to the original order of information.
15 - Stick to the original language.
16 - Don't print headlines like "Verse 1".
17 - Spell out numbers, as in never produce numerical symbols. Instead of 35, write thirty-five.
18"""
19
20
21async def generate_lyrics(content):
22 chat_completion = await get_open_api_client().chat.completions.create(
23 messages=[
24 {"role": "system", "content": SYSTEM_PROMPT},
25 {"role": "user", "content": f"{USER_PROMPT}\n\n```{content}```"},
26 ],
27 model=OPENAI_MODEL,
28 )
29
30 return chat_completion.choices[0].message.content
src/main.py
1import os
2
3from apify import Actor
4
5from src.fetch_content import fetch_content
6from src.music_generation import get_song, generate_songs
7from src.lyrics_generation import generate_lyrics
8from src.open_ai import truncate_to_max_content_length
9from src.suggest_music_genre import suggest_music_genre
10
11
12async def main() -> None:
13 async with Actor:
14 actor_input = await Actor.get_input()
15 kvs = await Actor.open_key_value_store()
16 dataset = await Actor.open_dataset() # Alternative visualisation
17
18 url = actor_input.get("url")
19 if not url:
20 raise ValueError('Missing "url" attribute in input!')
21
22 # Fetch page content.
23 try:
24 await Actor.set_status_message("Fetching page content")
25 Actor.log.info("Fetching page content", extra={"url": url})
26 page_content = truncate_to_max_content_length(await fetch_content(url))
27 except Exception as e:
28 await Actor.fail(
29 exception=e, status_message="Fetching page content failed."
30 )
31
32 # Generate song lyrics + determine genre.
33 try:
34 await Actor.set_status_message("Generating lyrics using AI")
35 Actor.log.info(
36 "Generating lyrics using AI", extra={"page_content": page_content}
37 )
38 lyrics = await generate_lyrics(page_content)
39 song_genre = actor_input.get("song_genre") or await suggest_music_genre(
40 page_content
41 )
42 await kvs.set_value(
43 key="lyrics.txt", value=lyrics, content_type="text/plain"
44 )
45 except Exception as e:
46 await Actor.fail(
47 exception=e, status_message="Generating lyrics using AI failed."
48 )
49
50 # Generate song.
51 try:
52 await Actor.set_status_message(
53 "Generating the song (this might take a few minutes)"
54 )
55 Actor.log.info(
56 "Generating the song", extra={"lyrics": lyrics, "genre": song_genre}
57 )
58 topmediai_api_key = actor_input.get("topmediai_api_key") or os.environ.get(
59 "TOPMEDIAI_API_KEY"
60 )
61
62 song_links = generate_songs(
63 lyrics=lyrics,
64 api_key=topmediai_api_key,
65 genre=song_genre,
66 logger=Actor.log,
67 )
68 for variant, song_link in enumerate(song_links, start=1):
69 await kvs.set_value(
70 key=f"song_variant_{variant}",
71 value=get_song(song_link),
72 content_type="audio/mpeg",
73 )
74 await dataset.push_data(
75 {
76 "variant": variant,
77 "download url": song_link,
78 "play url": await kvs.get_public_url(f"song_variant_{variant}"),
79 "lyrics": lyrics,
80 }
81 )
82 except Exception as e:
83 await Actor.fail(
84 exception=e, status_message="Generating song using TopMediaAI failed."
85 )
86
87 # Charge user based on the resources used
88 if actor_input.get("topmediai_api_key"):
89 await Actor.charge(event_name="song_with_user_api_key", count=1)
90 else:
91 await Actor.charge(event_name="song_with_actor_api_key", count=1)
src/music_generation.py
1from logging import getLogger
2
3import requests
4import json
5
6
7def generate_songs(
8 lyrics: str, api_key: str, genre: str = "Hip Hop", logger=getLogger(__name__)
9) -> [str]:
10 """Generate song and return generated song link."""
11 api_url = "https://api.topmediai.com/v1/music"
12
13 payload = {"is_auto": 0, "prompt": genre, "lyrics": lyrics}
14 headers = {"x-api-key": api_key, "Content-Type": "application/json"}
15
16 response = requests.request("POST", api_url, json=payload, headers=headers)
17 if response.status_code != 200:
18 raise RuntimeError(response.text)
19
20 response_text = json.loads(response.text)
21
22 if response_text.get("status", None) != 200:
23 raise RuntimeError(
24 f"TopMediai song generation temporarily out of order. Please try again later."
25 f" Details in response: {response.text}"
26 )
27
28 songs = [song["audio_file"] for song in response_text.get("data", [])]
29
30 if not songs:
31 raise RuntimeError(
32 "TopMediai song generation temporarily out of order. Please try again later."
33 )
34
35 return songs
36
37
38def get_song(link: str) -> bytes:
39 """Get song from link."""
40 return requests.request("GET", link).content
src/open_ai.py
1import os
2
3from apify import Actor
4from openai import AsyncOpenAI
5
6OPENAI_MODEL = "gpt-4o"
7
8# Max content length as supported by OpenAI API and the gpt-4o model
9OPENAI_MAX_CONTENT_LENGTH_TOKENS = 128000
10
11
12def get_open_api_client():
13 return AsyncOpenAI(
14 api_key=os.environ.get("OPENAI_API_KEY"),
15 )
16
17
18def truncate_to_max_content_length(content):
19 # Simple heuristic: 1 word = 4 tokens. This is a pessimistic conversion, which should be safe for most languages.
20 truncated_content = " ".join(
21 content.split()[: OPENAI_MAX_CONTENT_LENGTH_TOKENS // 4]
22 )
23
24 if len(truncated_content) < len(content):
25 Actor.log.warning(
26 "Fetched page was too long for OpenAI API and was truncated",
27 extra={
28 "original_length": len(content),
29 "truncated_length": len(truncated_content),
30 },
31 )
32
33 return truncated_content
src/py.typed
1
src/suggest_music_genre.py
1from src.open_ai import get_open_api_client
2
3from src.open_ai import truncate_to_max_content_length, OPENAI_MODEL
4
5SYSTEM_PROMPT = """
6You are a helpful, sensitive and empathetic assistant that understands nuances and emotions in text.
7"""
8
9USER_PROMPT = """
10The following text will be turned into a song. Please suggest a music genre that fits the text.
11
12Take into account the mood, tone, severity, topic etc.
13
14Return just the genre and nothing else.
15
16Sample outputs: "indie britpop", "experimental rock", "opera".
17"""
18
19
20async def suggest_music_genre(content):
21 chat_completion = await get_open_api_client().chat.completions.create(
22 messages=[
23 {"role": "system", "content": SYSTEM_PROMPT},
24 {"role": "user", "content": f"{USER_PROMPT}\n\n```{content}```"},
25 ],
26 model=OPENAI_MODEL,
27 )
28
29 return chat_completion.choices[0].message.content