Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
RomanPlusPlus opened this issue Oct 16, 2024 · 0 comments
Open

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

RomanPlusPlus opened this issue Oct 16, 2024 · 0 comments

Comments

@RomanPlusPlus
Copy link

RomanPlusPlus commented Oct 16, 2024

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant