Finetuning.aiFinetuning.ai

Python

API examples using Python

Setup

import os
import time
import requests

API_KEY = os.environ["FINETUNING_API_KEY"]
BASE_URL = "https://pub.finetuning.ai"

headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json",
}

Check account info

response = requests.get(f"{BASE_URL}/v1/me", headers=headers)
me = response.json()
print(f"Credits remaining: {me['data']['limits']['totalRemaining']}")

Create a generation

response = requests.post(
    f"{BASE_URL}/v1/generations",
    headers=headers,
    json={
        "tags": "ambient electronic soundscape with deep bass and ethereal pads",
        "duration": 120,
        "bpm": 70,
        "key": "F",
        "scale": "minor",
    },
)

generation = response.json()["data"]
print(f"Generation ID: {generation['id']}")
print(f"Status: {generation['status']}")

Poll for completion

def wait_for_generation(generation_id: str) -> dict:
    while True:
        response = requests.get(
            f"{BASE_URL}/v1/generations/{generation_id}",
            headers=headers,
        )
        gen = response.json()["data"]

        if gen["status"] == "completed":
            print(f"Done! Audio URL: {gen['audioUrl']}")
            return gen

        if gen["status"] == "failed":
            raise Exception(f"Generation failed: {gen.get('errorMessage')}")

        print(f"Status: {gen['status']}... waiting")
        time.sleep(3)

completed = wait_for_generation(generation["id"])

Download the track

audio_response = requests.get(completed["audioUrl"])

with open("output.mp3", "wb") as f:
    f.write(audio_response.content)

print("Saved to output.mp3")

Full example: Generate and download

import os
import time
import requests

API_KEY = os.environ["FINETUNING_API_KEY"]
BASE_URL = "https://pub.finetuning.ai"
headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}


def main():
    # 1. Create generation
    res = requests.post(
        f"{BASE_URL}/v1/generations",
        headers=headers,
        json={
            "tags": "upbeat funk track with slap bass and wah guitar",
            "duration": 60,
            "bpm": 110,
        },
    )
    gen = res.json()["data"]
    print(f"Created: {gen['id']}")

    # 2. Poll until complete
    while True:
        check = requests.get(
            f"{BASE_URL}/v1/generations/{gen['id']}", headers=headers
        )
        result = check.json()["data"]
        print(f"Status: {result['status']}")

        if result["status"] in ("completed", "failed"):
            break
        time.sleep(3)

    if result["status"] == "failed":
        print(f"Failed: {result.get('errorMessage')}")
        return

    # 3. Download
    audio = requests.get(result["audioUrl"])
    with open("funk-track.mp3", "wb") as f:
        f.write(audio.content)
    print("Saved to funk-track.mp3")


if __name__ == "__main__":
    main()

On this page