Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import asyncio
from logging import getLogger
from uuid import uuid4
from PIL import Image
import flet as ft
from utils.clipcrop import CropClip
from configs.path_config import EXAMPLE_IMAGE, OUTPUT_DIR
from configs.logging_config import LOGGING_CONFIG
from logging.config import dictConfig
# ログ設定
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())
このコードはとりあえず完全に動作する。リファクタリングして。コメントは不要。
import asyncio
from uuid import uuid4
from pathlib import Path
from typing import Dict, Optional, Callable, Any
from PIL import Image
import flet as ft
from utils.clipcrop import CropClip
from configs.path_config import EXAMPLE_IMAGE, OUTPUT_DIR
class AsyncPipeline:
def __init__(self, processor_cls: type, num_workers: int = 1):
self.processor_cls = processor_cls
self.num_workers = num_workers
self.queue: asyncio.Queue = asyncio.Queue()
self.workers: list[asyncio.Task] = []
self._running = False
async def start(self):
if self._running:
return
self._running = True
self.workers = [
asyncio.create_task(self._worker(f"worker-{i}"))
for i in range(self.num_workers)
]
async def stop(self):
if not self._running:
return
self._running = False
for _ in self.workers:
await self.queue.put(None)
await asyncio.gather(*self.workers, return_exceptions=True)
self.workers.clear()
async def _worker(self, name: str):
with self.processor_cls() as processor:
while self._running:
task = await self.queue.get()
if task is None:
break
callback, args = task
try:
result = await asyncio.to_thread(processor.clip_clop, *args)
await callback(result, None)
except Exception as e:
await callback(None, e)
async def submit(self, img_path: Path, prompt: str, callback: Callable):
with Image.open(img_path) as img:
img.load()
await self.queue.put((callback, (img, prompt)))
class ImagePipelineUI:
def __init__(self, page: ft.Page):
self.page = page
self.page.title = "Async Image Pipeline"
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):
run_button = ft.ElevatedButton("Run Tasks", on_click=self.handle_run)
self.page.add(run_button, self.status_list)
async def handle_run(self, e):
await self.pipeline.start()
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:
task_id = str(uuid4())[:6]
self.add_status(f"Task {name} ({task_id}) submitted.")
async def process_callback(result, error, name=name, task_id=task_id):
if error:
self.add_status(f"❌ Task {name} failed: {error}")
elif isinstance(result, Image.Image):
out_path = OUTPUT_DIR / f"ui_output_{name}_{task_id}.png"
result.save(out_path)
self.add_status(f"✅ Task {name} completed. Saved to {out_path}")
else:
self.add_status(f"❌ Task {name} failed with unexpected result")
await self.pipeline.submit(img_path, prompt, process_callback)
def add_status(self, message: str):
self.status_list.controls.append(ft.Text(message))
self.page.update()
async def cleanup(self):
await self.pipeline.stop()
async def main():
async def app(page: ft.Page):
ui = ImagePipelineUI(page)
page.on_disconnect = lambda _: asyncio.create_task(ui.cleanup())
await ft.app_async(target=app)
if __name__ == "__main__":
asyncio.run(main())