Untitled conversation
- User
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())このコードはとりあえず問題なく動作する。 機能や動作を損なわない範囲でリファクタリングして。
Assistant
このコードは、非同期タスクを管理するための
AsyncPipelineクラスと、Flet を使用した UI を定義しています。以下は、機能や動作を損なわない範囲でのリファクタリング後のコードです。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.task_results = {} self.task_futures = {} async def _worker(self, name: str): with self.clip_cls() as cc: logger.info(f"Worker {name} initialized.") while True: 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._set_task_result(task_id, result) except Exception as e: logger.exception(f"Exception in {name} for task {task_id}") self._set_task_result(task_id, e, is_exception=True) finally: self.queue.task_done() def _set_task_result(self, task_id, result, is_exception=False): self.task_results[task_id] = result future = self.task_futures.pop(task_id) if is_exception: future.set_exception(result) else: future.set_result(result) async def start_workers(self, num_workers=None): num_workers = num_workers or self.num_workers self.workers = [asyncio.create_task(self._worker(f"worker-{i}")) for i in range(num_workers)] async def submit_task(self, img, prompt): task_id = str(uuid4()) future = asyncio.get_running_loop().create_future() self.task_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) class AsyncImagePipelineApp: def __init__(self, page: ft.Page): self.page = page self.pipeline = AsyncPipeline(CropClip, num_workers=2) self.status_list = ft.ListView(expand=True, spacing=5, padding=10) self._setup_ui() def _setup_ui(self): self.page.title = "Async Image Pipeline" run_button = ft.ElevatedButton("Run Tasks", on_click=self.handle_click) self.page.add(run_button, self.status_list) async def handle_click(self, e): await self.pipeline.start_workers() 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(): with Image.open(img_path) as img: img.load() task_id, future = await self.pipeline.submit_task(img, prompt) self.status_list.controls.append(ft.Text(f"Task {name} ({task_id[:6]}) submitted.")) self.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) self.status_list.controls.append(ft.Text(f"✅ Task {name} completed. Saved to {out_path}")) else: self.status_list.controls.append(ft.Text(f"❌ Task {name} failed with error: {result}")) except Exception as e: self.status_list.controls.append(ft.Text(f"❌ Task {name} failed: {e}")) self.page.update() asyncio.create_task(await_result()) async def run(self): await ft.app_async(target=self._main_ui_async) async def _main_ui_async(self, page: ft.Page): self.__init__(page) async def main(): app = AsyncImagePipelineApp(ft.Page()) await app.run() if __name__ == "__main__": asyncio.run(main())主な変更点は以下の通りです。
AsyncPipelineクラス:_set_task_resultメソッドを追加して、タスクの結果を設定する処理を共通化しました。AsyncImagePipelineAppクラス: UI 関連の処理をこのクラスにまとめました。_setup_uiメソッドで UI を初期化し、handle_clickメソッドでボタンクリック時の処理を定義しています。main_ui_async関数:AsyncImagePipelineAppクラスに置き換えました。main関数:AsyncImagePipelineAppクラスを使用してアプリを実行するように変更しました。
これらの変更により、コードの構造が整理され、可読性が向上しています。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.