Spaces:
Runtime error
Runtime error
File size: 20,037 Bytes
a73fa4e 8fb43ea a73fa4e a4a73a4 025c015 a73fa4e 04b10e3 a73fa4e 04b10e3 a73fa4e 04b10e3 a73fa4e 025c015 a73fa4e a41399d a73fa4e 8fb43ea a73fa4e 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea c64cc64 8fb43ea a73fa4e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
"""
ポチ(犬)アシスタントコンポーネント
画面右下に固定配置され、本音表示機能を提供する
"""
import streamlit as st
import logging
import time
logger = logging.getLogger(__name__)
class DogAssistant:
"""ポチ(犬)アシスタントクラス"""
def __init__(self):
"""初期化"""
self.default_message = "ポチは麻理の本音を察知したようだ・・・"
self.active_message = "ワンワン!本音が見えてるワン!"
def render_dog_component(self, tutorial_manager=None):
"""画面右下に固定配置される犬のコンポーネントを描画"""
try:
# 現在の状態を取得
current_show_all_hidden = st.session_state.get('show_all_hidden', False)
# 犬のコンポーネントのCSS(レスポンシブ対応)
dog_css = """
<style>
.dog-assistant-container {
position: fixed;
bottom: 120px;
right: 20px;
z-index: 1000;
display: flex;
flex-direction: column;
align-items: flex-start;
pointer-events: none;
transform: translateX(-50px);
}
.dog-speech-bubble {
background-color: rgba(255, 255, 255, 0.95);
color: #333;
padding: 10px 15px;
border-radius: 20px;
font-size: 13px;
margin-bottom: 10px;
position: relative;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
backdrop-filter: blur(10px);
border: 1px solid rgba(0,0,0,0.1);
max-width: 200px;
word-wrap: break-word;
animation: bubbleFloat 3s ease-in-out infinite;
pointer-events: auto;
}
.dog-speech-bubble::after {
content: '';
position: absolute;
bottom: -8px;
left: 20px;
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid rgba(255, 255, 255, 0.95);
}
.dog-button {
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%);
border: none;
border-radius: 50%;
width: 70px;
height: 70px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(255, 154, 158, 0.4);
display: flex;
align-items: center;
justify-content: center;
font-size: 35px;
pointer-events: auto;
animation: dogBounce 2s ease-in-out infinite;
}
.dog-button:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px rgba(255, 154, 158, 0.6);
background: linear-gradient(135deg, #ff6b6b 0%, #feca57 50%, #ff9ff3 100%);
}
.dog-button:active {
transform: scale(0.95);
}
.dog-button.active {
background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
animation: dogActive 1s ease-in-out infinite;
}
@keyframes bubbleFloat {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-5px); }
}
@keyframes dogBounce {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-3px); }
}
@keyframes dogActive {
0%, 100% { transform: scale(1) rotate(0deg); }
25% { transform: scale(1.05) rotate(-2deg); }
75% { transform: scale(1.05) rotate(2deg); }
}
/* レスポンシブ対応 */
@media (max-width: 768px) {
.dog-assistant-container {
bottom: 110px;
right: 15px;
transform: translateX(-40px);
}
.dog-speech-bubble {
max-width: 150px;
font-size: 12px;
padding: 8px 12px;
}
.dog-button {
width: 60px;
height: 60px;
font-size: 30px;
}
}
@media (max-width: 480px) {
.dog-assistant-container {
bottom: 100px;
right: 10px;
transform: translateX(-30px);
}
.dog-speech-bubble {
max-width: 120px;
font-size: 11px;
padding: 6px 10px;
}
.dog-button {
width: 50px;
height: 50px;
font-size: 25px;
}
}
/* 画面が非常に小さい場合は吹き出しを非表示 */
@media (max-width: 320px) {
.dog-speech-bubble {
display: none;
}
}
</style>
"""
# 現在の状態を使用(関数開始時に取得済み)
is_active = current_show_all_hidden
bubble_text = self.active_message if is_active else self.default_message
button_class = "dog-button active" if is_active else "dog-button"
# JavaScriptでクリックイベントを処理
dog_js = f"""
<script>
function toggleDogMode() {{
// Streamlitのセッション状態を更新するためのトリガー
const event = new CustomEvent('dogButtonClick', {{
detail: {{ active: {str(is_active).lower()} }}
}});
window.dispatchEvent(event);
// ボタンの状態を即座に更新
const button = document.querySelector('.dog-button');
const bubble = document.querySelector('.dog-speech-bubble');
if (button && bubble) {{
if ({str(is_active).lower()}) {{
button.classList.remove('active');
bubble.textContent = '{self.default_message}';
}} else {{
button.classList.add('active');
bubble.textContent = '{self.active_message}';
}}
}}
}}
// ページ読み込み時にイベントリスナーを設定
document.addEventListener('DOMContentLoaded', function() {{
const button = document.querySelector('.dog-button');
if (button) {{
button.addEventListener('click', toggleDogMode);
}}
}});
// Streamlitの再描画後にもイベントリスナーを再設定
setTimeout(function() {{
const button = document.querySelector('.dog-button');
if (button) {{
button.addEventListener('click', toggleDogMode);
}}
}}, 100);
</script>
"""
# HTMLコンポーネント
dog_html = f"""
<div class="dog-assistant-container">
<div class="dog-speech-bubble">
{bubble_text}
</div>
<button class="{button_class}" title="ポチが麻理の本音を察知します" onclick="toggleDogMode()">
🐕
</button>
</div>
"""
# HTMLコンポーネント(ボタン以外)を表示
dog_display_html = f"""
<div class="dog-assistant-container">
<div class="dog-speech-bubble">
{bubble_text}
</div>
<div style="width: 70px; height: 70px; display: flex; align-items: center; justify-content: center;">
<!-- Streamlitボタンがここに配置される -->
</div>
</div>
"""
st.markdown(dog_css + dog_display_html, unsafe_allow_html=True)
# Streamlitボタンを固定位置に配置
button_css = """
<style>
.dog-button-overlay {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1001;
pointer-events: auto;
}
.dog-button-overlay .stButton > button {
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
border: none;
border-radius: 50%;
width: 70px;
height: 70px;
font-size: 35px;
color: white;
box-shadow: 0 4px 15px rgba(255, 154, 158, 0.4);
transition: all 0.3s ease;
animation: dogBounce 2s ease-in-out infinite;
}
.dog-button-overlay .stButton > button:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px rgba(255, 154, 158, 0.6);
}
@keyframes dogBounce {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-3px); }
}
@media (max-width: 768px) {
.dog-button-overlay {
bottom: 15px;
right: 15px;
}
.dog-button-overlay .stButton > button {
width: 60px;
height: 60px;
font-size: 30px;
}
}
@media (max-width: 480px) {
.dog-button-overlay {
bottom: 10px;
right: 10px;
}
.dog-button-overlay .stButton > button {
width: 50px;
height: 50px;
font-size: 25px;
}
}
</style>
"""
st.markdown(button_css, unsafe_allow_html=True)
st.markdown('<div class="dog-button-overlay">', unsafe_allow_html=True)
# ボタンクリック処理(キーを固定して状態変更の問題を解決)
button_key = "dog_fixed_button" # 固定キー
button_help = "本音を隠す" if is_active else "本音を見る"
# ボタンの状態を視覚的に反映するためのスタイル
button_style = """
<style>
div[data-testid="stButton"] > button[kind="primary"] {
background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%) !important;
animation: dogActive 1s ease-in-out infinite !important;
}
</style>
""" if is_active else ""
if button_style:
st.markdown(button_style, unsafe_allow_html=True)
if st.button("🐕", key=button_key, help=button_help, type="primary" if is_active else "secondary"):
self.handle_dog_button_click(tutorial_manager)
logger.info("右下の犬のボタンがクリックされました")
st.markdown('</div>', unsafe_allow_html=True)
logger.debug(f"犬のコンポーネントを描画しました (active: {is_active})")
except Exception as e:
logger.error(f"犬のコンポーネント描画エラー: {e}")
def handle_dog_button_click(self, tutorial_manager=None):
"""犬のボタンクリック処理(1回クリック対応版)"""
try:
# 重複クリック防止(短時間での連続クリックを防ぐ)
current_time = time.time()
last_click_time = st.session_state.get('dog_button_last_click', 0)
if current_time - last_click_time < 0.5: # 0.5秒以内の連続クリックを防ぐ
logger.debug("犬のボタン連続クリックを防止しました")
return
st.session_state.dog_button_last_click = current_time
# 本音表示機能のトリガー
if 'show_all_hidden' not in st.session_state:
st.session_state.show_all_hidden = False
# 現在の状態を確実に取得
current_state = st.session_state.get('show_all_hidden', False)
new_state = not current_state
# 状態を即座に更新(複数のフラグを同時に設定)
st.session_state.show_all_hidden = new_state
st.session_state.show_all_hidden_changed = True # チャット履歴の強制再表示フラグ
st.session_state.dog_button_clicked = True # UI更新フラグ
st.session_state.force_chat_rerender = True # 強制再描画フラグ
logger.info(f"🐕 ポチボタンクリック: {current_state} → {new_state}")
# 全メッセージのフリップ状態を即座に更新
if 'message_flip_states' not in st.session_state:
st.session_state.message_flip_states = {}
# 現在のメッセージに対してフリップ状態を設定
if 'chat' in st.session_state and 'messages' in st.session_state.chat:
# 初期メッセージが存在することを確認
messages = st.session_state.chat['messages']
if not any(msg.get('is_initial', False) for msg in messages):
logger.warning("犬のボタン押下時に初期メッセージが見つかりません - 復元します")
initial_message = {"role": "assistant", "content": "何の用?遊びに来たの?", "is_initial": True}
st.session_state.chat['messages'].insert(0, initial_message)
logger.info("犬のボタン押下時に初期メッセージを復元しました")
# 全てのアシスタントメッセージのフリップ状態を更新
for i, message in enumerate(st.session_state.chat['messages']):
if message['role'] == 'assistant':
message_id = f"msg_{i}"
st.session_state.message_flip_states[message_id] = new_state
logger.debug(f"メッセージ {message_id} のフリップ状態を {new_state} に設定")
else:
logger.warning("犬のボタン押下時にチャットセッションが存在しません - 初期化します")
# チャットセッションが存在しない場合は初期化
initial_message = {"role": "assistant", "content": "何の用?遊びに来たの?", "is_initial": True}
if 'chat' not in st.session_state:
st.session_state.chat = {
"messages": [initial_message],
"affection": 30,
"scene_params": {"theme": "default"},
"limiter_state": {},
"scene_change_pending": None,
"ura_mode": False
}
else:
st.session_state.chat['messages'] = [initial_message]
logger.info("犬のボタン押下時にチャットセッションを初期化しました")
# チュートリアルステップ2を完了(tutorial_managerが渡された場合)
if tutorial_manager:
tutorial_manager.check_step_completion(2, True)
# 通知メッセージ(一度だけ表示)
if new_state:
st.success("🐕 ポチが麻理の本音を察知しました!")
else:
st.info("🐕 ポチが通常モードに戻りました。")
logger.info(f"犬のボタン状態変更完了: {current_state} → {new_state}")
# 状態変更を即座に反映するため再描画を実行
st.rerun()
except Exception as e:
logger.error(f"犬のボタンクリック処理エラー: {e}")
import traceback
logger.error(f"犬のボタンクリック処理エラーの詳細: {traceback.format_exc()}")
def render_with_streamlit_button(self):
"""Streamlitのボタンを使用した代替実装(フォールバック用)"""
try:
# 固定位置のCSS
fallback_css = """
<style>
.dog-fallback-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
background: rgba(255, 255, 255, 0.9);
border-radius: 15px;
padding: 10px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
backdrop-filter: blur(10px);
}
@media (max-width: 768px) {
.dog-fallback-container {
bottom: 15px;
right: 15px;
padding: 8px;
}
}
</style>
"""
st.markdown(fallback_css, unsafe_allow_html=True)
# コンテナの開始
st.markdown('<div class="dog-fallback-container">', unsafe_allow_html=True)
# 状態表示
is_active = st.session_state.get('show_all_hidden', False)
status_text = "本音モード中" if is_active else "通常モード"
st.caption(f"🐕 {status_text}")
# ボタン
button_text = "🔄 戻す" if is_active else "🐕 本音を見る"
if st.button(button_text, key="dog_assistant_btn"):
# チュートリアルマネージャーを取得(可能な場合)
tutorial_manager = None
try:
# セッション状態からチュートリアルマネージャーを取得する試み
# (完全ではないが、フォールバック用)
pass
except:
pass
self.handle_dog_button_click(tutorial_manager)
# コンテナの終了
st.markdown('</div>', unsafe_allow_html=True)
except Exception as e:
logger.error(f"犬のフォールバック描画エラー: {e}")
def get_current_state(self):
"""現在の犬の状態を取得"""
return {
'is_active': st.session_state.get('show_all_hidden', False),
'message': self.active_message if st.session_state.get('show_all_hidden', False) else self.default_message
} |