Skip to content

Please add a minimal python script for accessing your API #6

Description

@RomanPlusPlus

Sorry if it's not the right place for this suggestion.

The problem: your API documentation is missing a minimal python script. Something you just run and it works, without installing third-party software etc.

After some experimentation, I've managed to write it myself. Please feel free to add it to the docs (I release it into Public Domain).

import requests
import time
import json
import os

# API endpoint URLs
BASE_URL = "https://api.bfl.ml" 
GENERATE_URL = f"{BASE_URL}/v1/flux-pro-1.1"
RESULT_URL = f"{BASE_URL}/v1/get_result"

# Your API key
API_KEY = "your_key"  # Replace with your actual API key

prompt = "A beautiful landscape with mountains and a lake."


# Headers for authentication
headers = {
    "x-key": API_KEY,
    "Content-Type": "application/json"
}

# Image generation parameters
payload = {
    "prompt": prompt,
    "width": 1024,
    "height": 768,
    "prompt_upsampling": True,
    "safety_tolerance": 2
}

def generate_image():
    # Submit the image generation request
    response = requests.post(GENERATE_URL, json=payload, headers=headers)
    response.raise_for_status()
    task_id = response.json()["id"]
    print(f"Image generation task submitted. Task ID: {task_id}")
    return task_id

def check_result(task_id):
    while True:
        response = requests.get(f"{RESULT_URL}?id={task_id}", headers=headers)
        response.raise_for_status()
        result = response.json()
        
        if result["status"] == "Ready":
            print("Image generation completed!")
            return result["result"]
        elif result["status"] in ["Request Moderated", "Content Moderated", "Error"]:
            print(f"Task failed. Status: {result['status']}")
            return None
        else:
            print(f"Status: {result['status']}. Waiting...")
            time.sleep(5)  # Wait for 5 seconds before checking again

def process_result(result):
    if result is None:
        print("No result to process.")
        return

    print("Result structure:")
    print(json.dumps(result, indent=2))

    if "sample" in result:
        result_img_url = result['sample']
        print(f"Generated image URL: {result_img_url}")
        print(f"Prompt used: {result['prompt']}")
    else:
        print("Image URL not found in the result. Please check the result structure.")
    return result_img_url

def download_image(url):
    response = requests.get(url)
    response.raise_for_status()
    
    filename = f"generated_image_{int(time.time())}.png"

    with open(filename, "wb") as file:
        file.write(response.content)
    
    print(f"Image downloaded successfully as {filename}")
    return filename

def main():
    task_id = generate_image()
    result = check_result(task_id)
    result_img_url = process_result(result)
    
    if result_img_url:
        download_image(result_img_url)

if __name__ == "__main__":
    main()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions