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.
# src/tabs/main_tab_explorer.py
import os
import platform
import subprocess
from pathlib import Path
from src.debug.timer import timer
import flet as ft
from configs.path_config import IMAGES_DIR
from utils.thumbnails import get_thumbnail
def create_subdir_card(item_path: Path, on_click: callable) -> ft.Card:
return ft.Card(
content=ft.Container(
content=ft.Column([
ft.Icon(
ft.Icons.FOLDER,
size=60,
color=ft.Colors.BLUE_400
),
ft.Text(
item_path.name,
size=14,
text_align=ft.TextAlign.CENTER,
overflow=ft.TextOverflow.ELLIPSIS
)
],
alignment=ft.MainAxisAlignment.CENTER,
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
spacing=10
),
padding=10,
on_click=on_click,
),
elevation=2
)
def create_image_card(item_path: Path, on_click: callable) -> ft.Card:
return ft.Card(
content=ft.Container(
content=ft.Stack([
ft.Image(
src=str(get_thumbnail(item_path)),
fit=ft.ImageFit.COVER,
border_radius=8,
left=0, right=0, top=0, bottom=0,
),
ft.Container( # タイトル部分に透明背景をつける
height=28,
bgcolor=ft.Colors.with_opacity(0.6, ft.Colors.BLACK),
border_radius=8,
left=0, right=0, bottom=0,
),
ft.Container(
content=ft.Text(
item_path.name,
size=14,
color=ft.Colors.WHITE,
weight=ft.FontWeight.BOLD,
text_align=ft.TextAlign.CENTER,
overflow=ft.TextOverflow.ELLIPSIS,
),
alignment=ft.alignment.bottom_center, # 下中央配置
padding=4,
# 横方向最大幅制限(親から10px余白)
margin=ft.margin.symmetric(horizontal=10),
# 角丸処理
border_radius=8,
)
]),
on_click=on_click,
),
elevation=2,
shape=ft.RoundedRectangleBorder(radius=8),
)
class ImageBrowser:
def __init__(self):
self.root_dir = IMAGES_DIR
self.current_dir = self.root_dir
self.history = []
# サポートする画像拡張子
self.image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
def is_image(self, path):
return path.suffix.lower() in self.image_extensions
@staticmethod
def open_image(image_path):
"""OSのデフォルトアプリケーションで画像を開く"""
system = platform.system()
if system == 'Darwin': # macOS
subprocess.run(['open', str(image_path)])
elif system == 'Windows':
os.startfile(str(image_path))
else: # Linux
subprocess.run(['xdg-open', str(image_path)])
def get_items(self):
"""現在のディレクトリのサブディレクトリと画像を取得"""
items = []
try:
for item in sorted(self.current_dir.iterdir()):
if item.is_dir() and not item.name.startswith('.'):
items.append(('dir', item))
elif item.is_file() and self.is_image(item):
items.append(('image', item))
except PermissionError:
pass
return items
def navigate_to(self, path):
"""指定されたパスに移動"""
if path.is_dir():
self.history.append(self.current_dir)
self.current_dir = path
def go_back(self):
"""前のディレクトリに戻る"""
if self.history:
self.current_dir = self.history.pop()
def go_to_root(self):
"""ルートディレクトリに戻る"""
self.history.clear()
self.current_dir = self.root_dir
def build_tab(self, page: ft.Page):
"""ImageBrowserのUIをタブとして構築して返す"""
browser = self
# パスを表示するテキスト
path_text = ft.Text(
value=str(browser.current_dir),
size=16,
weight=ft.FontWeight.BOLD
)
# カードを表示するグリッド
grid = ft.GridView(
expand=True,
runs_count=5,
max_extent=200,
child_aspect_ratio=1.0,
spacing=10,
run_spacing=10,
)
def update_view():
"""ビューを更新"""
path_text.value = str(browser.current_dir)
grid.controls.clear()
items = browser.get_items()
for item_type, item_path in items:
if item_type == 'dir':
# ディレクトリカード
card = create_subdir_card(item_path=item_path, on_click=lambda e, p=item_path: navigate_to_dir(p))
else:
# 画像カード
card = create_image_card(item_path=item_path, on_click=lambda e, p=item_path: open_image(p))
grid.controls.append(card)
# ナビゲーションボタンの表示/非表示
back_button.disabled = browser.current_dir == browser.root_dir
root_button.disabled = browser.current_dir == browser.root_dir
page.update()
def navigate_to_dir(path):
"""ディレクトリに移動"""
browser.navigate_to(path)
with timer(prefix=f"navigate to {path}: "):
update_view()
def open_image(path):
"""画像を開く"""
ImageBrowser.open_image(path)
def go_back(e):
"""前に戻る"""
browser.go_back()
update_view()
def go_to_root(e):
"""ルートに戻る"""
browser.go_to_root()
update_view()
# ナビゲーションボタン
back_button = ft.IconButton(
icon=ft.Icons.ARROW_BACK,
on_click=go_back,
tooltip="前に戻る",
disabled=True
)
root_button = ft.IconButton(
icon=ft.Icons.HOME,
on_click=go_to_root,
tooltip="ルートに戻る",
disabled=True
)
# ヘッダー
header = ft.Row([
back_button,
root_button,
path_text
])
# タブの内容
tab_content = ft.Column([
header,
grid
], expand=True)
# 初期表示
update_view()
return ft.Tab(
text="Browser",
content=tab_content
)
def main(page: ft.Page):
page.title = "タブ付き画像ブラウザ"
page.padding = 20
# ImageBrowserのインスタンスを作成
image_browser = ImageBrowser()
# タブを作成
tabs = ft.Tabs(
selected_index=0,
animation_duration=300,
tabs=[
image_browser.build_tab(page),
],
expand=True
)
# ページにタブを追加
page.add(tabs)
if __name__ == "__main__":
ft.app(target=main)
2025-06-17 00:31:08,002 flet:240 on_session_created [INFO]: App session started
2025-06-17 00:31:08,011 utils.async_task_manager:51 start_worker [INFO]: Worker task started.
2025-06-17 00:31:10,209 src.debug.timer:26 timer [INFO]: navigate to C:\Users\faker\Desktop\lora_test\images\midori_2: 111.26 ms
2025-06-17 00:31:12,678 utils.async_task_manager:98 _worker [INFO]: Worker task cancelled
2025-06-17 00:31:12,679 utils.async_task_manager:102 _worker [INFO]: Worker task finished
2025-06-17 00:31:12,682 watchcat:60 watch_images [INFO]: Observer stopped
Python 3.12, Flet 0.28.3.
このコードは完全に動作する画像ブラウザである。画像が100枚あるタブに移動したとき、111msの遅延が生じている。
これは100枚のサムネイルのキャッシュをロードしている時間で、その間はGUIの動作がブロックされている。
ページが遷移してから、ページの上からサムネイルを順次ロードするにはどうしたらいい?
なお、get_thumbnail_asyncは用意してある。
コードを書く場合、コード全体を省略なしに単一のコードブロックに含めること。コードの「変更点」をコメントに記載しないこと。既存のコメントを消さないこと。
# src/tabs/main_tab_explorer.py
import os
import platform
import subprocess
from pathlib import Path
from src.debug.timer import timer
import flet as ft
import asyncio # 非同期処理のために必要
from configs.path_config import IMAGES_DIR
# from utils.thumbnails import get_thumbnail # 元の同期関数
# get_thumbnail_async が utils.thumbnails に存在すると仮定する
# 実際の環境では `from utils.thumbnails import get_thumbnail_async` のようにインポートしてください。
# 以下は、utils.thumbnails.py が存在しない場合の仮の定義です。
# もし utils.thumbnails.py に非同期関数が実装されている場合は、この仮定義は不要です。
try:
from utils.thumbnails import get_thumbnail_async
except ImportError:
# utils.thumbnails モジュールまたは get_thumbnail_async が存在しない場合のダミー実装
async def get_thumbnail_async(image_path: Path) -> str:
"""
非同期でサムネイルを生成し、そのパスを返す関数 (仮実装)。
実際のサムネイル生成処理(ディスクI/O、画像処理など)を含む想定。
完了まで待機が発生するため非同期で実行する。
"""
# print(f"Generating thumbnail for: {image_path}") # デバッグ用
# ここに実際の非同期サムネイル生成ロジックを記述する
# 例: Pillowを使ったリサイズ、キャッシュへの保存など
# サムネイル生成に時間がかかることをシミュレートするために await asyncio.sleep を使用
await asyncio.sleep(0.02) # 20ms の遅延をシミュレート (実際の処理時間に応じて調整)
# サムネイル生成後にキャッシュされたファイルパスを返す
# 元の get_thumbnail 関数がキャッシュパスを返すロジックを持っていると仮定
try:
from utils.thumbnails import get_thumbnail
return get_thumbnail(image_path) # 元の関数が返すパスを返す (実際はサムネイル生成後のパス)
except ImportError:
# utils.thumbnails モジュール自体がない場合、元のファイルパスを返す(実際はサムネイルパスが必要)
# この場合、サムネイルは表示されず、元の画像が表示されるか、エラーになる可能性があります。
print(f"Warning: utils.thumbnails module not found. Cannot generate real thumbnails.")
# return str(image_path) # サムネイルとして元のパスを返す(機能しない)
return None # サムネイルがないことを示す
def create_subdir_card(item_path: Path, on_click: callable) -> ft.Card:
"""サブディレクトリを表示するカードを作成する"""
return ft.Card(
content=ft.Container(
content=ft.Column([
ft.Icon(
ft.Icons.FOLDER,
size=60,
color=ft.Colors.BLUE_400
),
ft.Text(
item_path.name,
size=14,
text_align=ft.TextAlign.CENTER,
overflow=ft.TextOverflow.ELLIPSIS
)
],
alignment=ft.MainAxisAlignment.CENTER,
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
spacing=10
),
padding=10,
on_click=on_click,
),
elevation=2
)
def create_image_card_with_placeholder(item_path: Path, on_click: callable) -> tuple[ft.Card, ft.Image]:
"""
サムネイルロード用のプレースホルダーを持つ画像カードと、
サムネイルを更新するためのft.Imageコントロールへの参照を返す関数。
"""
# プレースホルダーとなるImageコントロール
# 初期状態ではsrc=Noneとし、ロード後に更新される。
placeholder_img_control = ft.Image(
src=None, # 初期状態は空(またはプレースホルダー画像パス)
fit=ft.ImageFit.COVER,
border_radius=8,
left=0, right=0, top=0, bottom=0,
# error_content=ft.Icon(ft.Icons.BROKEN_IMAGE) # エラー時の表示オプション
)
card = ft.Card(
content=ft.Container(
content=ft.Stack([
placeholder_img_control, # ここにプレースホルダー画像が表示される(初期は空)
ft.Container( # タイトル部分に透明背景をつける
height=28,
bgcolor=ft.Colors.with_opacity(0.6, ft.Colors.BLACK),
border_radius=8,
left=0, right=0, bottom=0,
),
ft.Container(
content=ft.Text(
item_path.name,
size=14,
color=ft.Colors.WHITE,
weight=ft.FontWeight.BOLD,
text_align=ft.TextAlign.CENTER,
overflow=ft.TextOverflow.ELLIPSIS,
),
alignment=ft.alignment.bottom_center, # 下中央配置
padding=4,
margin=ft.margin.symmetric(horizontal=10),
border_radius=8,
)
]),
on_click=on_click, # 画像クリック時のイベントハンドラ
),
elevation=2,
shape=ft.RoundedRectangleBorder(radius=8),
)
return card, placeholder_img_control
class ImageBrowser:
def __init__(self):
self.root_dir = IMAGES_DIR
self.current_dir = self.root_dir
self.history = []
# サポートする画像拡張子
self.image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
def is_image(self, path: Path) -> bool:
"""指定されたパスがサポートされている画像ファイルか判定する"""
return path.suffix.lower() in self.image_extensions
@staticmethod
def open_image(image_path: Path):
"""OSのデフォルトアプリケーションで画像を開く"""
system = platform.system()
if system == 'Darwin': # macOS
subprocess.run(['open', str(image_path)])
elif system == 'Windows':
os.startfile(str(image_path))
else: # Linux
subprocess.run(['xdg-open', str(image_path)])
def get_items(self) -> list[tuple[str, Path]]:
"""現在のディレクトリのサブディレクトリと画像ファイルを取得する"""
items = []
try:
# ディレクトリ内のアイテムをソートして取得
# .DS_Storeなどの隠しファイルを除外
for item in sorted(self.current_dir.iterdir()):
if item.is_dir() and not item.name.startswith('.'):
items.append(('dir', item))
elif item.is_file() and self.is_image(item):
items.append(('image', item))
except PermissionError:
# アクセス権がないディレクトリはスキップ
pass
return items
def navigate_to(self, path: Path):
"""指定されたパスに移動し、履歴を記録する"""
if path.is_dir():
self.history.append(self.current_dir)
self.current_dir = path
def go_back(self):
"""前のディレクトリに戻る"""
if self.history:
self.current_dir = self.history.pop()
def go_to_root(self):
"""ルートディレクトリに戻る"""
self.history.clear()
self.current_dir = self.root_dir
def build_tab(self, page: ft.Page) -> ft.Tab:
"""ImageBrowserのUIをタブとして構築して返す"""
browser = self
# パスを表示するテキストコントロール
path_text = ft.Text(
value=str(browser.current_dir),
size=16,
weight=ft.FontWeight.BOLD,
overflow=ft.TextOverflow.ELLIPSIS, # パスが長い場合のエリプシス対応
)
# カードを表示するためのGridViewコントロール
grid = ft.GridView(
expand=True,
runs_count=5, # グリッドの列数 (必要に応じて画面幅に合わせて調整)
max_extent=200, # 各アイテムの最大幅
child_aspect_ratio=1.0, # カードのアスペクト比 (正方形)
spacing=10, # カード間の水平・垂直スペース
run_spacing=10, # グリッドの行間スペース
)
# 非同期サムネイルロードのために、ロードが必要な画像コントロールとパスを保持するリスト
# 各要素は {'card': ft.Card, 'image_control': ft.Image, 'path': Path} の形式
self.image_controls_to_update: list[dict] = []
def update_view():
"""
ビューを更新します(ディレクトリ構造とプレースホルダー表示)。
更新後、バックグラウンドでサムネイルの非同期ロードを開始します。
"""
self.image_controls_to_update.clear() # 前回の更新情報をクリア
path_text.value = str(browser.current_dir)
grid.controls.clear()
items = browser.get_items()
for item_type, item_path in items:
if item_type == 'dir':
# ディレクトリカードを作成し、グリッドに追加
card = create_subdir_card(item_path=item_path, on_click=lambda e, p=item_path: navigate_to_dir(p))
grid.controls.append(card)
else:
# 画像カード(プレースホルダー付き)を作成
card, placeholder_image_control = create_image_card_with_placeholder(item_path=item_path, on_click=lambda e, p=item_path: open_image(p))
grid.controls.append(card)
# 後でサムネイルをロードするために、画像コントロールとパスをリストに追加
self.image_controls_to_update.append({
'card': card,
'image_control': placeholder_image_control,
'path': item_path
})
# ナビゲーションボタンの状態を更新
back_button.disabled = not browser.history # historyが空なら無効
root_button.disabled = browser.current_dir == browser.root_dir
page.update() # まず現在のビュー(ディレクトリ名とプレースホルダー)を表示
# ビュー更新後、バックグラウンドでサムネイルロードを開始
# page.run_thread を使って非同期関数を実行する
# asyncio.create_task はコルーチンをタスク化する
page.run_thread(
asyncio.create_task,
kwargs={'coro': load_thumbnails_in_background(self.image_controls_to_update, page)}
)
async def load_thumbnails_in_background(items_data: list[dict], page: ft.Page):
"""
バックグラウンドでサムネイルを非同期にロードし、UIを更新する関数。
"""
tasks = []
for item_info in items_data:
image_control = item_info['image_control']
img_path = item_info['path']
# 各サムネイルロードに対するコルーチンを作成
async def load_single_thumbnail(ctrl: ft.Image, path: Path, pg: ft.Page):
try:
# 非同期サムネイル生成関数を呼び出す
# `get_thumbnail_async` はサムネイルファイルのパスを返す想定
thumbnail_path = await get_thumbnail_async(path)
if thumbnail_path:
# FletのImageコントロールのsrcを更新
ctrl.src = str(thumbnail_path)
# 各サムネイルがロードされるたびにページを更新
# 大量にある場合はまとめて更新した方がパフォーマンスが良い場合もあるが、逐次ロードの視覚効果のため
pg.update()
except Exception as e:
print(f"Error loading thumbnail for {path}: {e}")
# エラー発生時の表示 (例: エラーアイコン)
ctrl.error_content = ft.Icon(ft.Icons.BROKEN_IMAGE, color=ft.Colors.RED_ACCENT_700)
pg.update() # エラー表示も更新
# 各画像のロードタスクを作成
tasks.append(load_single_thumbnail(image_control, img_path, page))
# 全てのサムネイルロードタスクを並列実行
await asyncio.gather(*tasks)
print("All thumbnails loaded.") # 全てのサムネイルロード完了のログ
def navigate_to_dir(path: Path):
"""指定されたディレクトリに移動する"""
browser.navigate_to(path)
with timer(prefix=f"navigate to {path}: "):
update_view() # ここでビューを更新し、非同期ロードを開始する
def open_image(path: Path):
"""画像ファイルを開く"""
ImageBrowser.open_image(path)
def go_back(e):
"""前のディレクトリに戻る"""
browser.go_back()
update_view()
def go_to_root(e):
"""ルートディレクトリに戻る"""
browser.go_to_root()
update_view()
# ナビゲーションボタン
back_button = ft.IconButton(
icon=ft.Icons.ARROW_BACK,
on_click=go_back,
tooltip="前に戻る",
disabled=True # 初期状態では無効
)
root_button = ft.IconButton(
icon=ft.Icons.HOME,
on_click=go_to_root,
tooltip="ルートに戻る",
disabled=True # 初期状態では無効
)
# ヘッダー: ナビゲーションボタンとパス表示テキスト
header = ft.Row([
back_button,
root_button,
# Path Text を Row に含め、水平方向にスペースを均等に配分
ft.Container(content=path_text, expand=True, alignment=ft.alignment.center_left, padding=ft.padding.only(left=10))
], alignment=ft.MainAxisAlignment.START)
# タブの内容: ヘッダー、区切り線、グリッド
tab_content = ft.Column([
header,
ft.Divider(), # ヘッダーとグリッドの間に追加
grid
], expand=True)
# 初期表示: ディレクトリの内容とプレースホルダーを表示し、非同期ロードを開始
update_view()
return ft.Tab(
text="Browser",
content=tab_content
)
def main(page: ft.Page):
"""Fletアプリケーションのエントリーポイント"""
page.title = "タブ付き画像ブラウザ"
page.padding = 20
# ImageBrowserのインスタンスを作成
image_browser = ImageBrowser()
# タブコントロールを作成し、ImageBrowserのタブを追加
tabs = ft.Tabs(
selected_index=0,
animation_duration=300,
tabs=[
image_browser.build_tab(page),
],
expand=True
)
# ページにタブコントロールを追加
page.add(tabs)
if __name__ == "__main__":
# Fletアプリケーションを実行
ft.app(target=main)