Spaces:
Runtime error
Runtime error
File size: 1,664 Bytes
fb2f0a7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import fal_client
from PIL import Image
from typing import Dict, Any
import requests
from io import BytesIO
from weave_prompt import ImageGenerator
from dotenv import load_dotenv
load_dotenv()
class FalImageGenerator(ImageGenerator):
"""Handles image generation using fal_client."""
def __init__(self, model_name: str = "fal-ai/flux-pro"):
self.model_name = model_name
def _on_queue_update(self, update):
"""Handle queue updates during image generation."""
if isinstance(update, fal_client.InProgress):
for log in update.logs:
print(log["message"])
def generate(self, prompt: str, **kwargs) -> Image.Image:
"""Generate an image from a text prompt using fal_client."""
result = fal_client.subscribe(
self.model_name,
arguments={
"prompt": prompt,
**kwargs
},
with_logs=True,
on_queue_update=self._on_queue_update,
)
print(result)
return self._extract_image_from_result(result)
def _extract_image_from_result(self, result: Dict[str, Any]) -> Image.Image:
"""Extract and download image from fal_client result."""
if result and 'images' in result and len(result['images']) > 0:
image_url = result['images'][0]['url']
response = requests.get(image_url)
response.raise_for_status() # Raise an exception for bad status codes
image = Image.open(BytesIO(response.content))
return image
else:
raise ValueError("No image found in the result") |