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
以下に、あなたのコードのリファクタリング案を提示します。以下の目標に基づいて整理しました:
- 可読性の向上(関数・変数名の明確化、定数の整理)
- 責務の分離(UIロジックとバックエンド処理の分離)
- 冗長なコードの削減
- 潜在的なバグの回避(例:クロージャ内での変数キャプチャ)
- 型ヒントの追加による保守性の向上(必要に応じて)
✅ 主な改善点一覧
項目 改善内容 関数分割 await_resultを外に出し、明示的な引数渡しに変更クロージャ修正 クロージャでの task_id,futureのキャプチャバグ対策命名改善 run_button→run_tasks_buttonなど意味のある名前に構造改善 UI部品の初期化を関数に分離 ( setup_ui)型ヒント追加 関数シグネチャに型注釈を付ける ロギング強化 タスク完了時のログも追加 不要な with 文削除 Image.open(...).load()の load は不要な場合あり※
Image.load()は多くの場合自動で呼ばれるため、明示的に呼ぶ必要は通常ありません。
🛠️ リファクタリング後のコード
import asyncio from logging import getLogger 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.futures = {} self.task_id_map = {} self.workers = [] 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.results[task_id] = result self.futures[task_id].set_result(result) logger.info(f"{name} completed {task_id}") 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() 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: str, prompt: str, img_path: str): with Image.open(img_path) as img: # .load() は多くの場合不要 pass # Pillow は open 後に自動的に 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) await self.queue.join() for w in self.workers: w.cancel() await asyncio.gather(*self.workers, return_exceptions=True) def create_status_text(text: str) -> ft.Text: return ft.Text(text, size=12) async def process_task_result(task_id: str, name: str, future: asyncio.Future, status_list: ft.ListView) -> None: try: result: Image.Image | Exception = 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(create_status_text(f"✅ Task '{name}' completed. Saved to {out_path}")) else: status_list.controls.append(create_status_text(f"❌ Task '{name}' failed with error: {result}")) except Exception as e: status_list.controls.append(create_status_text(f"❌ Task '{name}' raised exception: {e}")) finally: # UI更新 status_list.update() async def on_run_tasks_click(e: ft.ControlEvent, pipeline: AsyncPipeline, status_list: ft.ListView) -> None: 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(create_status_text(f"Task '{name}' ({task_id[:6]}) submitted.")) # 非同期処理を個別に実行 asyncio.create_task(process_task_result(task_id, name, future, status_list)) status_list.update() def setup_ui(page: ft.Page, pipeline: AsyncPipeline) -> None: page.title = "Async Image Pipeline" status_list = ft.ListView(expand=True, spacing=5, padding=10) run_tasks_button = ft.ElevatedButton("Run Tasks", on_click=lambda e: on_run_tasks_click(e, pipeline, status_list)) page.add(run_tasks_button, status_list) async def main_ui_async(page: ft.Page): pipeline = AsyncPipeline(CropClip, num_workers=2) await pipeline.start_workers() setup_ui(page, pipeline) async def main(): await ft.app_async(target=main_ui_async) if __name__ == "__main__": asyncio.run(main())
🔍 注意点・補足
❗
Image.load()について- Pillow の
Image.open()後に.load()を呼ぶ必要は基本的にありません。内部的に自動で読み込まれます。 - もし特別な理由があるなら残しても良いですが、コメントを入れておくべきです。
❗ クロージャの修正
- 元のコードでは
async def await_result(...)の中でtask_id,futureをクロージャで参照していましたが、これはイベントループが進むと意図しない値になる可能性があります。 - そのため、引数で明示的に渡す形にリファクタリングしました。
🧪 テスト推奨事項
- 並列数 (
num_workers) を変えて安定性を確認 - エラーを返すプロンプトや画像パスを渡して例外処理が正しく動くか確認
ご希望であれば、以下の追加改善も可能です:
- タスクごとの進捗表示(ProgressBar)
- キャンセルボタンの追加
- ログ出力を UI にも表示
- ファイル削除・再実行機能
お気軽にお申し付けください!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.