```
import asyncio
from logging import getLogger
from logging.config import dictConfig
from uuid import uuid4

import flet as ft
from PIL import Image

from configs.logging_config import LOGGING_CONFIG
from configs.path_config import EXAMPLE_IMAGE, OUTPUT_DIR
from utils.clipcrop import CropClip

# ログ設定
dictConfig(LOGGING_CONFIG)
logger = getLogger(__name__)


class AsyncPipeline:
    def __init__(self, clip_cls, num_workers=1):
        self.clip_cls = clip_cls
        self.num_workers = num_workers
        self.queue = asyncio.Queue()
        self.results = {}
        self.task_id_map = {}
        self.futures = {}
        self.workers = []

    async def _worker(self, name: str):
        with self.clip_cls() as cc:
            logger.info(f"Worker {name} initialized.")
            while True:
                try:
                    task = await self.queue.get()
                    if task is None:
                        self.queue.task_done()
                        break  # Shutdown signal
                    task_id, img, prompt = task
                    logger.info(f"{name} started {task_id}")
                    try:
                        result = await asyncio.to_thread(cc.clip_clop, img, prompt)
                        self.results[task_id] = result
                        self.futures[task_id].set_result(result)
                    except Exception as e:
                        logger.exception(f"Exception in {name} for task {task_id}")
                        self.results[task_id] = e
                        self.futures[task_id].set_exception(e)
                    finally:
                        self.queue.task_done()
                except asyncio.CancelledError:
                    break

    async def start_workers(self):
        self.workers = [asyncio.create_task(self._worker(f"worker-{i}")) for i in range(self.num_workers)]

    async def submit_task(self, name, prompt, img_path):
        with Image.open(img_path) as img:
            img.load()
        task_id = str(uuid4())
        self.task_id_map[task_id] = name
        future = asyncio.get_running_loop().create_future()
        self.futures[task_id] = future
        await self.queue.put((task_id, img, prompt))
        return task_id, future

    async def stop(self):
        for _ in self.workers:
            await self.queue.put(None)  # Signal shutdown
        await self.queue.join()
        for w in self.workers:
            w.cancel()
        await asyncio.gather(*self.workers, return_exceptions=True)


# Flet UI 定義
async def main_ui_async(page: ft.Page):
    page.title = "Async Image Pipeline"
    status_list = ft.ListView(expand=True, spacing=5, padding=10)
    pipeline = AsyncPipeline(CropClip, num_workers=2)

    await pipeline.start_workers()

    async def handle_click(e):
        # ボタンがクリックされたらタスクを3つ投入
        tasks = {
            'girl': ('a girl', EXAMPLE_IMAGE),
            'clock': ('a clock on the wall', EXAMPLE_IMAGE),
            'teddy': ('a teddy bear', EXAMPLE_IMAGE),
        }
        for name, (prompt, img_path) in tasks.items():
            task_id, future = await pipeline.submit_task(name, prompt, img_path)
            status_list.controls.append(ft.Text(f"Task {name} ({task_id[:6]}) submitted."))
            page.update()

            async def await_result(task_id=task_id, name=name, future=future):
                try:
                    result = await future
                    if isinstance(result, Image.Image):
                        out_path = OUTPUT_DIR / f"ui_output_{name}_{task_id[:6]}.png"
                        result.save(out_path)
                        status_list.controls.append(ft.Text(f"✅ Task {name} completed. Saved to {out_path}"))
                    else:
                        status_list.controls.append(ft.Text(f"❌ Task {name} failed with error: {result}"))
                except Exception as e:
                    status_list.controls.append(ft.Text(f"❌ Task {name} failed: {e}"))
                page.update()

            # 現在のイベントループでタスクを作成
            asyncio.create_task(await_result())

    run_button = ft.ElevatedButton("Run Tasks", on_click=handle_click)
    page.add(run_button, status_list)


async def main():
    # 重要：ft.app_async を使用する
    await ft.app_async(target=main_ui_async)


if __name__ == "__main__":
    asyncio.run(main())
```

このコードはとりあえず問題なく動作する。 機能や動作を損なわない範囲でリファクタリングして。