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__)
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)
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)
以下は、非同期でCSVを読み込みながらプログレスインジケーターを表示し、読み込み完了後にオートコンプリートを有効化するように変更したコードです。また、タグを選択すると別のテキストフィールドにスペース区切りで追加される機能を実装しています。
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__)
async 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()
key = value
suggestion = ft.AutoCompleteSuggestion(key=key, value=value)
suggestions.append(suggestion)
# 大量のデータを読み込む場合にUIがフリーズしないように少し待機
if i % 100 == 0:
await asyncio.sleep(0)
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...")
# タグを保持するリスト
selected_tags = []
# タグ表示用テキストフィールド
textfield_tags = ft.TextField(
label="選択されたタグ",
multiline=True,
min_lines=3,
max_lines=5,
read_only=True,
expand=True,
)
# オートコンプリート用テキストフィールド(初期状態は無効)
ac = ft.AutoComplete(
suggestions=[],
on_select=lambda e: on_tag_select(e, selected_tags, textfield_tags),
disabled=True,
label="タグをロード中です...",
)
# プログレスインジケーター
progress_ring = ft.ProgressRing(width=20, height=20, visible=True)
loading_row = ft.Row([progress_ring, ft.Text("タグを読み込んでいます...")], visible=True)
page.add(
loading_row,
ac,
ft.Text("タグ名またはエイリアスを入力してください。"),
textfield_tags,
)
# 非同期でCSVを読み込み
async def load_suggestions():
logger_local.info("Loading suggestions from CSV...")
suggestions = await load_suggestions_from_csv(TAGS_CSV_DIR)
logger_local.info(f"Total suggestions loaded: {len(suggestions)}")
# UIを更新
ac.suggestions = suggestions
ac.disabled = False
ac.label = "タグを入力"
loading_row.visible = False
page.update()
# バックグラウンドで読み込みを開始
page.run_task(load_suggestions)
def on_tag_select(e, selected_tags, textfield_tags):
selected_tag = e.selection.value
logger_local.info(f"Selected tag: {selected_tag}")
# 既に選択済みでないかチェック
if selected_tag not in selected_tags:
selected_tags.append(selected_tag)
textfield_tags.value = " ".join(selected_tags)
textfield_tags.update()
ft.app(target=main)
非同期処理の追加:
load_suggestions_from_csv を非同期関数に変更await asyncio.sleep(0) を挿入ローディングUIの追加:
タグ追加機能:
textfield_tags を追加バックグラウンド処理:
page.run_task() を使用してCSV読み込みをバックグラウンドで実行この実装により、ユーザーはCSVの読み込みが完了するまでの間、プログレスインジケーターを見ながら待つことができ、読み込み完了後はスムーズにタグを選択して追加できるようになります。