import base64 import requests import os from dotenv import load_dotenv load_dotenv() ACCOUNT_ID = os.environ["CLOUDFLARE_ACCOUNT_ID"] API_TOKEN = os.environ["CLOUDFLARE_API_TOKEN"] def text_to_image_cloudflare(prompt, output_path): MODEL = "@cf/black-forest-labs/flux-1-schnell" URL = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/{MODEL}" payload = { "prompt": prompt, } headers = { "Authorization": f"Bearer {API_TOKEN}", "Content-Type": "application/json", } resp = requests.post(URL, json=payload, headers=headers, timeout=60) resp.raise_for_status() data = resp.json() b64 = data["result"]["image"] if not b64: raise RuntimeError(f"Unexpected response structure: {data}") img_bytes = base64.b64decode(b64) with open(output_path, "wb") as f: f.write(img_bytes) return True def refine_text_prompt(prompt): MODEL = "@cf/meta/llama-3.2-3b-instruct" URL = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/{MODEL}" instructions = """ User is talking about some object. Your task is to generate a short and concise description of it. Use only user's own words, keep it as short as possible. Example: User: 'Umm, okay, I would like a really cool sword, with for example a bright orange crossguard. And also it should be slightly curved.' You: 'a slightly curved sword with bright orange crossguard' """ response = requests.post(URL, headers={"Authorization": f"Bearer {API_TOKEN}"}, json={ "messages": [ {"role": "system", "content": instructions}, {"role": "user", "content": prompt} ] } ) data = response.json() return data["result"]["response"]