|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import CloudFlare |
| 6 | + |
| 7 | +def find_call(cf, verbs): |
| 8 | + # So we walk over the @ via a getattr() call. |
| 9 | + # We also have to deal with a . in a verb - that does not work in Python. So sad. |
| 10 | + # Also, the - is actually an _ in this Python library. |
| 11 | + # This is not normally needed for other calls |
| 12 | + m = cf |
| 13 | + for verb in verbs.split('/'): |
| 14 | + m = getattr(m, verb) |
| 15 | + return m |
| 16 | + |
| 17 | +def doit(account_name, prompt_text): |
| 18 | + |
| 19 | + # Or place these in your cloudflare.cfg file |
| 20 | + os.environ['CLOUDFLARE_API_EXTRAS'] = '/accounts/:id/ai/run/@cf/stabilityai/stable-diffusion-xl-base-1.0' |
| 21 | + |
| 22 | + # We set the timeout because these AI calls take longer than normal API calls |
| 23 | + cf = CloudFlare.CloudFlare(global_request_timeout=120) |
| 24 | + |
| 25 | + try: |
| 26 | + params = {'name': account_name, 'per_page': 1} |
| 27 | + accounts = cf.accounts.get(params=params) |
| 28 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 29 | + exit('/accounts %d %s - api call failed' % (e, e)) |
| 30 | + |
| 31 | + account_id = accounts[0]['id'] |
| 32 | + |
| 33 | + image_create_data = { |
| 34 | + 'prompt': prompt_text, |
| 35 | + } |
| 36 | + |
| 37 | + try: |
| 38 | + # This should be easy to call; however, the @ will not work in Python (or many languages) |
| 39 | + # r = [email protected](account_id, data=image_create_data) |
| 40 | + # We find the endpoint via a quick string search |
| 41 | + r = find_call(cf, 'accounts/ai/run/@cf/stabilityai/stable_diffusion_xl_base_1.0').post(account_id, data=image_create_data) |
| 42 | + except CloudFlare.exceptions.CloudFlareAPIError as e: |
| 43 | + exit('/ai.run %d %s - api call failed' % (e, e)) |
| 44 | + |
| 45 | + sys.stdout.buffer.write(r) |
| 46 | + |
| 47 | +def main(): |
| 48 | + account_name = sys.argv[1] |
| 49 | + if len(sys.argv) > 2: |
| 50 | + prompt_text = ' '.join(sys.argv[2:]) |
| 51 | + else: |
| 52 | + prompt_text = "A happy llama running through an orange cloud" |
| 53 | + doit(account_name, prompt_text) |
| 54 | + |
| 55 | +if __name__ == '__main__': |
| 56 | + main() |
0 commit comments