Certainly! Below is the fixed and improved version of your script. I've replaced the usage of yt_dlp with the TikTokApi library (since pyktok is not a commonly recognized library for downloading TikTok content). This script will download the MP3 from the input TikTok URL and convert it to MIDI using the Basic Pitch model.
Please make sure to install the required packages before running the script:
pip install TikTokApi requests basic-pitch
Here's the updated script:
import os
import sys
import requests
from TikTokApi import TikTokApi
from basic_pitch.inference import predict_and_save, Model
from basic_pitch import ICASSP_2022_MODEL_PATH
# Initialize the Basic Pitch model
basic_pitch_model = Model(ICASSP_2022_MODEL_PATH)
def download_mp3(tiktok_url, output_dir):
"""
Download audio from a TikTok video and save it as an MP3.
Args:
tiktok_url (str): The URL of the TikTok video.
output_dir (str): The directory to save the downloaded MP3 file.
"""
try:
# Initialize TikTokApi
with TikTokApi() as api:
# Get the TikTok video object
video = api.video(url=tiktok_url)
# Get video info
video_info = video.info()
# Extract the music play URL
music_url = video_info.get('music', {}).get('playUrl', None)
if not music_url:
print("No music URL found in the TikTok video.")
sys.exit(1)
# Download the music
response = requests.get(music_url)
response.raise_for_status() # Raise an error for bad status codes
# Save the audio as an MP3 file
mp3_filename = os.path.join(output_dir, 'audio.mp3')
with open(mp3_filename, 'wb') as f:
f.write(response.content)
print("Audio downloaded successfully.")
except Exception as e:
print(f"Failed to download audio: {e}")
sys.exit(1)
def convert_mp3_to_midi(mp3_file, output_dir):
"""
Convert an MP3 file to MIDI using the Basic Pitch model.
Args:
mp3_file (str): The path to the MP3 file.
output_dir (str): The directory to save the generated MIDI file.
"""
audio_paths = [mp3_file]
try:
predict_and_save(
audio_paths,
output_directory=output_dir,
save_midi=True,
save_model_outputs=False,
sonify_midi=False,
save_notes=False,
model=basic_pitch_model,
)
print(f"MIDI file successfully saved in folder: {output_dir}")
except Exception as e:
print(f"Failed to convert MP3 to MIDI: {e}")
sys.exit(1)
def main():
"""
Main function to execute the script logic.
"""
# Get the current script directory
script_dir = os.path.dirname(os.path.abspath(__file__))
# Create an output folder in the script directory
output_dir = os.path.join(script_dir, 'output')
os.makedirs(output_dir, exist_ok=True)
# Prompt the user for a TikTok video link
tiktok_url = input("Enter TikTok video URL: ").strip()
# Download the MP3 from the TikTok video
print("Downloading audio from TikTok...")
download_mp3(tiktok_url, output_dir)
# Verify the MP3 file was downloaded
mp3_file = os.path.join(output_dir, 'audio.mp3')
if not os.path.isfile(mp3_file):
print("No MP3 file found in the output folder.")
sys.exit(1)
# Convert the MP3 file to MIDI
print(f"Converting {os.path.basename(mp3_file)} to MIDI...")
convert_mp3_to_midi(mp3_file, output_dir)
if __name__ == '__main__':
main()
Explanation of the Changes:
-
Replaced yt_dlp with TikTokApi: The download_mp3 function now uses the TikTokApi library to obtain the music URL from the TikTok video and downloads the audio using requests.
-
Improved Error Handling: Added more specific error messages and used response.raise_for_status() to handle HTTP errors.
-
Code Cleanup and Comments: Added comments and docstrings to explain the purpose of functions and code blocks, improving readability.
-
Used exist_ok in os.makedirs: Simplified directory creation by using exist_ok=True to avoid needing to check if the directory exists.
-
Simplified MP3 File Handling: Assumed that the MP3 file will be named audio.mp3, simplifying file path handling.
Note:
-
TikTokApi Configuration: The TikTokApi library may require additional configuration due to TikTok's anti-bot measures. You might need to set up custom request headers, cookies, or use a proxy to avoid being blocked by TikTok. Refer to the TikTokApi documentation for detailed setup instructions.
-
Legal Considerations: Ensure that downloading content from TikTok complies with their terms of service and local laws. This script is intended for educational purposes.
Dependencies:
requests: For making HTTP requests to download the audio file.
TikTokApi: For interacting with TikTok's API to get video and music information.
basic_pitch: For converting audio to MIDI using Spotify's Basic Pitch model.
Installation Instructions:
Before running the script, install the required libraries:
pip install requests TikTokApi basic-pitch
Usage:
Run the script using Python:
python script_name.py
When prompted, enter the TikTok video URL you wish to process. The script will download the audio, convert it to MIDI, and save the output in the output folder.
I hope this helps! Let me know if you have any questions or need further assistance.