Untitled conversation
- Usercode
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 csv
import logging
from pathlib import Path
import flet as ft
from configs.path_config import TAGS_CSV_DIR
# ロガー設定
logger_local = logging.getLogger(__name__)
logger_local.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
logger_local.addHandler(handler)
def load_suggestions_from_csv(filepath: Path):
suggestions = []
try:
with open(filepath, newline='', encoding='cp932') as csvfile:
reader = csv.reader(csvfile) # ← カンマ区切りに修正
for i, row in enumerate(reader):
logger_local.debug(f"Row {i}: {row}")
if len(row) < 1 or not row[0].strip():
logger_local.warning(f"Skipping empty or invalid row {i}")
continue
value = row[0].strip()
# キーとして value のみを使用
key = value
suggestion = ft.AutoCompleteSuggestion(key=key, value=value)
logger_local.debug(f"Suggestion added: key='{key}', value='{value}'")
suggestions.append(suggestion)
except Exception as e:
logger_local.error(f"Failed to load suggestions: {e}")
return suggestions
def main(page: ft.Page):
logger_local.info("Initializing page and loading suggestions...")
suggestions = load_suggestions_from_csv(TAGS_CSV_DIR)
logger_local.info(f"Total suggestions loaded: {len(suggestions)}")
ac = ft.AutoComplete(
suggestions=suggestions,
on_select=lambda e: logger_local.info(f"Selected: index={e.control.selected_index}, value={e.selection}"),
)
page.add(
ac,
ft.Text("タグ名またはエイリアスを入力してください。"),
)
ft.app(target=main)
以下に要件を満たす修正コードを示します。主な変更点は以下の通りです:
import csv
import logging
from pathlib import Path
import asyncio # 非同期処理用に追加
import flet as ft
from configs.path_config import TAGS_CSV_DIR
# ロガー設定
logger_local = logging.getLogger(__name__)
logger_local.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
logger_local.addHandler(handler)
def load_suggestions_from_csv(filepath: Path):
suggestions = []
try:
with open(filepath, newline='', encoding='cp932') as csvfile:
reader = csv.reader(csvfile)
for i, row in enumerate(reader):
if len(row) < 1 or not row[0].strip():
logger_local.warning(f"Skipping empty or invalid row {i}")
continue
value = row[0].strip()
key = value
suggestion = ft.AutoCompleteSuggestion(key=key, value=value)
suggestions.append(suggestion)
except Exception as e:
logger_local.error(f"Failed to load suggestions: {e}")
return suggestions
async def main(page: ft.Page):
logger_local.info("Initializing page...")
# プログレスインジケータの作成
progress_ring = ft.ProgressRing(width=50, height=50, visible=True)
loading_text = ft.Text("タグデータを読み込み中...", size=16)
loading_column = ft.Column(
[progress_ring, loading_text],
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
expand=True
)
# メインUIコンテナ(初期状態ではローディング表示のみ)
main_container = ft.Container(
content=loading_column,
alignment=ft.alignment.center,
expand=True
)
page.add(main_container)
await page.update_async()
# 非同期でCSV読み込みを実行
logger_local.info("Starting CSV loading in background...")
suggestions = []
try:
# バックグラウンドスレッドでCSV読み込み
suggestions = await asyncio.to_thread(load_suggestions_from_csv, TAGS_CSV_DIR)
logger_local.info(f"Total suggestions loaded: {len(suggestions)}")
except Exception as e:
logger_local.error(f"Error during CSV loading: {e}")
loading_text.value = "タグデータの読み込みに失敗しました"
await page.update_async()
return
# 読み込み完了後のUI作成
ac = ft.AutoComplete(
suggestions=suggestions,
on_select=lambda e: logger_local.info(f"Selected: index={e.control.selected_index}, value={e.selection}"),
width=400
)
# タグ表示用テキストフィールド
textfield_tags = ft.TextField(
label="選択されたタグ",
multiline=True,
min_lines=3,
max_lines=5,
read_only=True,
expand=True
)
# オートコンプリート選択時の処理
def handle_tag_select(e):
new_tag = e.selection.value
current_tags = textfield_tags.value or ""
# 重複チェック(同じタグが既にあれば追加しない)
if new_tag in current_tags.split():
logger_local.info(f"タグ '{new_tag}' は既に追加されています")
return
# スペース区切りで追加
updated_tags = f"{current_tags} {new_tag}".strip()
textfield_tags.value = updated_tags
textfield_tags.update()
logger_local.info(f"タグ追加: {new_tag} -> 現在のタグ: {updated_tags}")
# イベントハンドラを設定
ac.on_select = handle_tag_select
# メインUIをローディングからコンテンツに置き換え
main_container.content = ft.Column(
[
ft.Text("タグ名またはエイリアスを入力してください。"),
ac,
ft.Divider(height=20),
ft.Text("選択済みタグ:"),
textfield_tags
],
spacing=10,
expand=True
)
# ローディング表示を非表示にして更新
progress_ring.visible = False
loading_text.visible = False
await page.update_async()
# 非同期アプリとして起動
ft.app(target=main)
非同期処理の実装:
main 関数を async に変更asyncio.to_thread() でバックグラウンド実行update_async() で非同期処理ローディング表示:
タグ管理機能:
textfield_tags)エラーハンドリング:
この実装により、10秒かかるCSV読み込み処理中もUIがフリーズせず、ユーザーに進行状況を表示できます。またタグ管理機能も要件通りに実装されています。