
Webpage Singer 🎶
Under maintenance
Pricing
Pay per event
Go to Store

Webpage Singer 🎶
Under maintenance
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.
5.0 (1)
Pricing
Pay per event
9
Total users
45
Monthly users
5
Runs succeeded
0%
Last modified
a month ago
.dockerignore
.git.mise.toml.nvim.luastorage
# The rest is copied from https://github.com/github/gitignore/blob/main/Python.gitignore
# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:.python-version
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder..idea/
.gitignore
.mise.toml.nvim.luastorage
# The rest is copied from https://github.com/github/gitignore/blob/main/Python.gitignore
# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:.python-version
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder..idea/
# Added by Apify CLInode_modules
LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2023 Apify Technologies s.r.o.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
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.05openai == 1.63.*6requests
.actor/Dockerfile
# First, specify the base Docker image.# You can see the Docker images from Apify at https://hub.docker.com/r/apify/.# You can also use any other image from Docker Hub.FROM apify/actor-python:3.13
# Second, copy just requirements.txt into the Actor image,# since it should be the only file that affects the dependency install in the next step,# in order to speed up the buildCOPY requirements.txt ./
# Install the packages specified in requirements.txt,# Print the installed Python version, pip version# and all installed packages with their versions for debuggingRUN echo "Python version:" \ && python --version \ && echo "Pip version:" \ && pip --version \ && echo "Installing dependencies:" \ && pip install -r requirements.txt \ && echo "All installed Python packages:" \ && pip freeze
# Next, copy the remaining files and directories with the source code.# Since we do this after installing the dependencies, quick build will be really fast# for most source file changes.COPY . ./
# Use compileall to ensure the runnability of the Actor Python code.RUN python3 -m compileall -q .
# Specify how to launch the source code of your Actor.# By default, the "python3 -m src" command is runCMD ["python3", "-m", "src"]
.actor/actor.json
{ "actorSpecification": 1, "name": "webpage-singer", "title": "Webpage Singer", "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.", "version": "0.0", "buildTag": "latest", "meta": { "templateId": "python-start" }, "input": "./input_schema.json", "dockerfile": "./Dockerfile", "storages": { "dataset": "./dataset_schema.json" }}
.actor/dataset_schema.json
{ "actorSpecification": 1, "views": { "overview": { "title": "Overview", "transformation": { "fields": [ "variant", "download url", "play url", "lyrics" ] }, "display": { "component": "table", "properties": { "variant": { "label": "variant", "format": "text" }, "play url": { "label": "play url", "format": "link" }, "download url": { "label": "download url", "format": "link" }, "lyrics": { "label": "lyrics", "format": "text" } } } } }}
.actor/input_schema.json
{ "title": "Scrape data from a web page", "type": "object", "schemaVersion": 1, "properties": { "url": { "title": "Page URL", "type": "string", "description": "Just enter the URL of a web page and it will be used to generate lyrics for the song.", "editor": "textfield", "prefill": "https://apify.com/about" }, "topmediai_api_key": { "title": "API key for TopMediai", "type": "string", "isSecret": true, "description": "If you provide your own TopMediai API key, you will be charged less.", "editor": "textfield" }, "song_genre": { "title": "Song genre", "type": "string", "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.", "editor": "textfield", "prefill": "Hip Hop" }
}, "required": ["url"]}
src/__init__.py
1
src/__main__.py
1import asyncio2
3from .main import main4
5# Execute the Actor entry point.6asyncio.run(main())
src/fetch_content.py
1from apify import Actor2
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_MODEL2
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 os2
3from apify import Actor4
5from src.fetch_content import fetch_content6from src.music_generation import get_song, generate_songs7from src.lyrics_generation import generate_lyrics8from src.open_ai import truncate_to_max_content_length9from src.suggest_music_genre import suggest_music_genre10
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 visualisation17
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_content41 )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 used88 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 getLogger2
3import requests4import json5
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 songs36
37
38def get_song(link: str) -> bytes:39 """Get song from link."""40 return requests.request("GET", link).content
src/open_ai.py
1import os2
3from apify import Actor4from openai import AsyncOpenAI5
6OPENAI_MODEL = "gpt-4o"7
8# Max content length as supported by OpenAI API and the gpt-4o model9OPENAI_MAX_CONTENT_LENGTH_TOKENS = 12800010
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
src/suggest_music_genre.py
1from src.open_ai import get_open_api_client2
3from src.open_ai import truncate_to_max_content_length, OPENAI_MODEL4
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