-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1429 lines (1214 loc) · 56.2 KB
/
app.py
File metadata and controls
1429 lines (1214 loc) · 56.2 KB
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Dict, Any, Optional
import streamlit as st
import sys
import os
# 🚀 Streamlit Cloud用 高速起動モード - 検出ロジック改善
def detect_cloud_mode():
"""Streamlit Cloud環境を検出"""
cloud_indicators = [
os.environ.get('STREAMLIT_SHARING_MODE') == '1',
'streamlit.io' in os.environ.get('URL', ''),
'streamlitapp.com' in os.environ.get('URL', ''),
'/mount/src/' in os.getcwd(), # Streamlit Cloudの典型的なパス
os.environ.get('HOSTNAME', '').startswith('streamlit-'),
'STREAMLIT_SERVER_HEADLESS' in os.environ,
'/app/' in os.getcwd(), # Docker環境
]
return any(cloud_indicators)
CLOUD_MODE = detect_cloud_mode()
# プロジェクトパスの設定(本番環境対応強化)
import sys
import os
from typing import Dict
# より堅牢なパス設定
project_root = os.path.dirname(os.path.abspath(__file__))
webui_dir = os.path.basename(project_root)
# webuiフォルダ内にいる場合は親ディレクトリに移動
if webui_dir == 'webui':
project_root = os.path.dirname(project_root)
src_path = os.path.join(project_root, 'src')
# パスの追加(重複チェック付き)
for path in [project_root, src_path]:
if path not in sys.path:
sys.path.insert(0, path)
# Streamlit自動リロード対応: キャッシュクリア(CLOUD_MODEでは軽量化)
if not CLOUD_MODE:
# 設定関連モジュールの強制リロード
modules_to_clear = [
'unified_config', 'unified_auth', 'api_config',
'src.unified_config', 'src.unified_auth', 'src.api_config'
]
for module in modules_to_clear:
if module in sys.modules:
del sys.modules[module]
# 統一設定とセキュリティ(エラーハンドリング付き・リロード対応)
CONFIG_AVAILABLE = False
UserLevel = None
UnifiedConfig = None
UnifiedAuth = None
APIConfig = None
def initialize_config_modules():
"""設定モジュールの初期化(リロード対応)"""
global CONFIG_AVAILABLE, UserLevel, UnifiedConfig, UnifiedAuth, APIConfig
try:
# 複数のインポート方法を試行
try:
from src.unified_config import UnifiedConfig as UC, UserLevel as UL
from src.unified_auth import UnifiedAuth as UA
from src.api_config import APIConfig as AC
except ImportError:
try:
from unified_config import UnifiedConfig as UC, UserLevel as UL
from unified_auth import UnifiedAuth as UA
from api_config import APIConfig as AC
except ImportError:
# 最後の手段として直接パス指定
sys.path.insert(0, os.path.join(project_root, 'src'))
from unified_config import UnifiedConfig as UC, UserLevel as UL
from unified_auth import UnifiedAuth as UA
from api_config import APIConfig as AC
# 成功時に変数に代入
UnifiedConfig = UC
UserLevel = UL
APIConfig = AC
UnifiedAuth = UA
CONFIG_AVAILABLE = True
return True
except Exception as e:
print(f"⚠️ 設定モジュールの読み込みに失敗: {e}")
# フォールバック設定
class FallbackUserLevel:
PUBLIC = "public"
OWNER = "owner"
class FallbackUnifiedConfig:
@staticmethod
def get_user_level(session_state):
return session_state.get('user_level', FallbackUserLevel.PUBLIC)
@staticmethod
def get_ui_config(user_level):
return {"title": "AITuber ルリ", "theme": "default"}
@staticmethod
def get_available_features(user_level):
if user_level == FallbackUserLevel.OWNER:
return {
"character_status": False, # 未実装のため無効化
"ai_conversation": True,
"image_analysis": False, # 未実装のため無効化
"streaming_integration": False, # 未実装のため無効化
"system_settings": False, # 未実装のため無効化
"analytics": False # 未実装のため無効化
}
return {"ai_conversation": True, "character_status": False}
class FallbackUnifiedAuth:
@staticmethod
def show_auth_interface():
pass
@staticmethod
def authenticate(username, password, session_state):
"""将来的な拡張用のユーザー名・パスワード認証"""
try:
# 統一設定から認証情報を取得
owner_password = UnifiedConfig.OWNER_PASSWORD if hasattr(UnifiedConfig, 'OWNER_PASSWORD') else os.environ.get('OWNER_PASSWORD', 'ruri2024')
owner_username = UnifiedConfig.OWNER_USERNAME if hasattr(UnifiedConfig, 'OWNER_USERNAME') else os.environ.get('OWNER_USERNAME', 'owner')
except:
# フォールバック
owner_password = os.environ.get('OWNER_PASSWORD', 'ruri2024')
owner_username = os.environ.get('OWNER_USERNAME', 'owner')
# 現在はパスワードメインだが、将来的にユーザー名も考慮可能
if password == owner_password:
session_state.user_level = FallbackUserLevel.OWNER
session_state.authenticated = True
session_state.authenticated_username = username
return True
return False
@staticmethod
def authenticate_user(password):
"""現在の認証方式(パスワードのみ)"""
try:
# 統一設定から認証情報を取得
owner_password = UnifiedConfig.OWNER_PASSWORD if hasattr(UnifiedConfig, 'OWNER_PASSWORD') else os.environ.get('OWNER_PASSWORD', 'ruri2024')
except:
# フォールバック
owner_password = os.environ.get('OWNER_PASSWORD', 'ruri2024')
if password == owner_password:
return FallbackUserLevel.OWNER
return None
@staticmethod
def logout(session_state):
session_state.user_level = FallbackUserLevel.PUBLIC
session_state.authenticated = False
session_state.authenticated_username = None
# 初期化フラグもリセット
session_state.initialization_complete = False
UserLevel = FallbackUserLevel
UnifiedConfig = FallbackUnifiedConfig
UnifiedAuth = FallbackUnifiedAuth
CONFIG_AVAILABLE = False
return False
# 初期化実行
initialize_config_modules()
# 基本機能のインポート(エラーハンドリング付き)
AI_AVAILABLE = False
IMAGE_PROCESSING_AVAILABLE = False
PLOTTING_AVAILABLE = False
# 軽量インポート: 必要時のみ読み込み
def lazy_import_ai():
"""AI機能の遅延インポート"""
global AI_AVAILABLE
if not AI_AVAILABLE:
try:
from src.character_ai import RuriCharacter
AI_AVAILABLE = True
return True
except ImportError as e:
print(f"⚠️ AI機能の読み込みに失敗: {e}")
return False
return True
def get_ruri_character():
"""ルリキャラクターインスタンスの取得(フォールバック付き)"""
if lazy_import_ai():
try:
from src.character_ai import RuriCharacter
return RuriCharacter()
except Exception as e:
print(f"⚠️ ルリキャラクター初期化失敗: {e}")
# フォールバック用ダミークラス
class DummyRuriCharacter:
def generate_response(self, message, image=None):
return "AI機能が利用できません。システム管理者にお問い合わせください。"
return DummyRuriCharacter()
# オプション機能の初期化(一度だけ実行)
if 'optional_features_initialized' not in st.session_state:
st.session_state.optional_features_initialized = True
try:
import cv2
import numpy as np
IMAGE_PROCESSING_AVAILABLE = True
if not CLOUD_MODE:
print("✅ 画像処理機能: 利用可能")
except ImportError as e:
if not CLOUD_MODE:
print(f"⚠️ 画像処理機能の読み込みに失敗: {e}")
IMAGE_PROCESSING_AVAILABLE = False
try:
import plotly.graph_objects as go
PLOTTING_AVAILABLE = True
if not CLOUD_MODE:
print("✅ Plotly機能: 利用可能")
except ImportError:
if not CLOUD_MODE:
print("⚠️ Plotly機能は無効です")
PLOTTING_AVAILABLE = False
else:
# 既に初期化済みの場合はデフォルト値を設定
IMAGE_PROCESSING_AVAILABLE = False
PLOTTING_AVAILABLE = False
def main():
"""統一WebUIメイン関数"""
# ナビゲーション用ユニークID生成(最優先で初期化)
if 'nav_session_id' not in st.session_state:
import time
st.session_state.nav_session_id = str(int(time.time() * 1000000))
try:
# 設定モジュールの再初期化(リロード対応)
initialize_config_modules()
# ホットリロード対応: セッション状態の保護
if 'hot_reload_protection' not in st.session_state:
st.session_state.hot_reload_protection = True
# 既存の認証状態があればそれを維持
if 'authenticated' not in st.session_state:
st.session_state.authenticated = False
if 'user_level' not in st.session_state:
st.session_state.user_level = UserLevel.PUBLIC if hasattr(UserLevel, 'PUBLIC') else "public"
# アプリケーション初期化ログ(一度だけ表示)
if 'app_initialized' not in st.session_state:
st.session_state.app_initialized = True
if not CLOUD_MODE:
print("🚀 アプリケーション初期化開始...")
# レスポンシブデザインのセットアップ(安全実行)
try:
setup_responsive_design()
if not CLOUD_MODE and not st.session_state.get('design_setup_logged', False):
print("✅ レスポンシブデザイン: 設定完了")
st.session_state.design_setup_logged = True
except Exception as e:
if not CLOUD_MODE:
print(f"⚠️ レスポンシブデザイン設定エラー: {e}")
# デザインエラーでもアプリ続行
# セッション状態の初期化(ホットリロード対応強化)
if 'current_page' not in st.session_state:
st.session_state.current_page = 'home'
if 'initialization_complete' not in st.session_state or not st.session_state.initialization_complete:
# 初期化が完了していない場合のみ実行
if 'authenticated' not in st.session_state:
st.session_state.authenticated = False
if 'user_level' not in st.session_state:
st.session_state.user_level = UserLevel.PUBLIC if hasattr(UserLevel, 'PUBLIC') else "public"
# チャット履歴の安定した初期化
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if not CLOUD_MODE:
print("💬 チャット履歴を初期化しました")
# セッションからチャット履歴を復元(オプション)
try:
load_chat_history_from_session()
except Exception as e:
if not CLOUD_MODE:
print(f"⚠️ チャット履歴復元エラー: {e}")
# 初期化完了フラグを設定
st.session_state.initialization_complete = True
# 設定取得ログ(一度だけ表示)
if not CLOUD_MODE and not st.session_state.get('config_fetch_logged', False):
print("🎯 設定取得中...")
st.session_state.config_fetch_logged = True
# 設定の取得(エラーハンドリング強化)
try:
user_level = UnifiedConfig.get_user_level(st.session_state) if UnifiedConfig else "public"
ui_config = UnifiedConfig.get_ui_config(user_level) if UnifiedConfig else {"title": "AITuber ルリ", "theme": "default"}
features = UnifiedConfig.get_available_features(user_level) if UnifiedConfig else {
"ai_conversation": True,
"character_status": False,
"basic_image_analysis": False
}
except Exception as e:
if not CLOUD_MODE:
print(f"⚠️ 設定取得エラー: {e}")
# フォールバック設定
user_level = "public"
ui_config = {"title": "AITuber ルリ", "theme": "default"}
features = {
"ai_conversation": True,
"character_status": False,
"basic_image_analysis": False
}
# ユーザー情報ログ(一度だけ表示)
if not CLOUD_MODE and not st.session_state.get('user_info_logged', False):
print(f"👤 ユーザーレベル: {user_level}")
print(f"🔧 利用可能機能: {list(features.keys())}")
st.session_state.user_info_logged = True
# レスポンシブサイドバーの設定(一度だけ実行)
# setup_responsive_sidebar(user_level, features, ui_config) # 重複削除
# 認証画面の表示判定
current_page = st.session_state.get('current_page', 'home')
is_owner = (hasattr(UserLevel, 'OWNER') and user_level == UserLevel.OWNER) or user_level == "owner"
# ホーム、AI会話は常にアクセス可能
public_pages = ['home', 'ai_conversation', 'character']
# 明示的に認証画面を要求された場合は最優先
if st.session_state.get('show_auth', False):
show_auth_page()
return
elif current_page in public_pages or is_owner:
# アクセス許可 - 通常処理を継続
pass
else:
# 認証が必要なページにアクセスしようとした場合のみ認証画面表示
if current_page not in public_pages:
show_auth_page()
return
# ページ表示ログ(一度だけ、または変更時のみ)
if not CLOUD_MODE and st.session_state.get('last_logged_page') != current_page:
print(f"📄 ページ表示: {current_page}")
st.session_state.last_logged_page = current_page
# 完了ログ(一度だけ表示)
if not CLOUD_MODE and not st.session_state.get('app_complete_logged', False):
print("✅ アプリケーション表示完了")
st.session_state.app_complete_logged = True
except Exception as e:
if not CLOUD_MODE:
print(f"💥 致命的エラー: {e}")
st.error(f"アプリケーションの初期化に失敗しました: {e}")
st.markdown("### 🚨 緊急フォールバックモード")
st.markdown("基本的な機能のみ利用可能です")
# 最小限のUI表示
st.title("🌟 AITuber ルリ")
st.info("現在、軽量モードで動作しています")
# 基本的なチャット機能のみ提供
chat_input = st.text_input("ルリにメッセージを送信:")
if st.button("送信") and chat_input:
st.write(f"**あなた**: {chat_input}")
st.write("**ルリ**: ありがとうございます!現在システムを調整中です...")
# 初期化プロセスの表示(認証済みの場合はスキップ)
if 'initialization_complete' not in st.session_state or not st.session_state.get('authenticated', False):
with st.spinner('Connecting pupa system...'):
# 既存の認証状態を確認
current_user_level = st.session_state.get('user_level', UserLevel.PUBLIC if UserLevel else "public")
# ユーザーレベルの取得(既存の状態を優先)
try:
if not st.session_state.get('authenticated', False):
user_level = UnifiedConfig.get_user_level(st.session_state)
else:
user_level = current_user_level
except:
user_level = current_user_level
try:
ui_config = UnifiedConfig.get_ui_config(user_level)
except:
ui_config = {"title": "AITuber ルリ", "theme": "default"}
try:
features = UnifiedConfig.get_available_features(user_level)
except:
# 認証状態に応じてフィーチャーを設定
if st.session_state.get('authenticated', False) or user_level in ["owner", getattr(UserLevel, 'OWNER', None)]:
features = {
"character_status": False, # 未実装のため無効化
"ai_conversation": True,
"basic_image_analysis": False, # 未実装のため無効化
"streaming_integration": False, # 未実装のため無効化
"system_settings": False, # 未実装のため無効化
"analytics": False # 未実装のため無効化
}
else:
features = {
"ai_conversation": True,
"character_status": False,
"basic_image_analysis": False
}
# 初期化完了フラグを設定(認証状態を保持)
st.session_state.initialization_complete = True
st.session_state.user_level = user_level
st.session_state.ui_config = ui_config
st.session_state.features = features
# 初期化完了後は無限ループを防ぐためrerunしない
# (認証関連でのrerunは別途適切な場所で実行)
# セッションから設定を取得(フォールバック)
user_level = st.session_state.get('user_level', UserLevel.PUBLIC if UserLevel else "public")
ui_config = st.session_state.get('ui_config', {"title": "AITuber ルリ", "theme": "default"})
features = st.session_state.get('features', {
"ai_conversation": True,
"character_status": False,
"basic_image_analysis": False
})
# レスポンシブ対応の初期設定
setup_responsive_design()
# 認証状態の確認(改良版・リロード対応)
try:
auth_handler = UnifiedAuth()
except:
auth_handler = None
# サイドバーメニュー(レスポンシブ対応)
setup_responsive_sidebar(user_level, features, ui_config)
# 認証ダイアログの表示チェック(メインエリアに表示)
if st.session_state.get('show_auth', False):
show_auth_page()
return
# パブリックユーザー以外で認証が必要な場合の処理(改良版・ホットリロード対応)
is_owner = False
if hasattr(UserLevel, 'OWNER') and user_level == UserLevel.OWNER:
is_owner = True
elif user_level == "owner":
is_owner = True
elif st.session_state.get('authenticated', False):
is_owner = True
# 認証が必要なページかどうかチェック
current_page = st.session_state.get('current_page', 'home')
# ホーム、AI会話は常にアクセス可能
public_pages = ['home', 'ai_conversation', 'character']
if current_page in public_pages or is_owner:
# アクセス許可 - 通常処理を継続
pass
elif st.session_state.get('show_auth', False):
# 明示的に認証画面を要求された場合
show_auth_page()
return
else:
# 認証が必要なページにアクセスしようとした場合のみ認証画面表示
if current_page not in public_pages:
show_auth_page()
return
# メインページの表示
page = st.session_state.get('current_page', 'home')
if page == 'home':
show_home_page(user_level, features, ui_config)
elif page == 'character' and features.get('character_status'):
show_character_page(user_level, features)
elif page == 'ai_conversation' and features.get('ai_conversation'):
show_ai_conversation_page(user_level, features)
elif page == 'image_analysis' and features.get('basic_image_analysis'):
show_image_analysis_page(user_level, features)
elif page == 'streaming' and features.get('streaming_integration'):
show_streaming_page(user_level, features)
elif page == 'settings' and features.get('system_settings'):
show_settings_page(user_level, features)
elif page == 'analytics' and features.get('analytics'):
show_analytics_page(user_level, features)
else:
st.error(f"ページ '{page}' は利用できません")
def setup_responsive_design():
"""レスポンシブデザインの設定(アクセシビリティ強化版)"""
# アクセシビリティ重視のレスポンシブCSS
st.markdown("""
<style>
/* 基本レスポンシブ設定 - 戯曲『あいのいろ』の世界観 */
.main > div {
padding-top: 2rem;
}
/* 会話関連スタイル - 個別ボックス設計 */
.chat-container {
max-width: 100%;
padding: 1rem;
margin: 0.5rem 0;
}
/* ユーザーメッセージボックス */
.user-message {
background: linear-gradient(135deg, #e0f2fe 0%, #b3e5fc 100%);
padding: 1rem 1.25rem;
margin: 0.75rem 0;
border-radius: 1rem 1rem 0.25rem 1rem;
border-left: 4px solid #0288d1;
color: #01579b;
box-shadow: 0 3px 12px rgba(2, 136, 209, 0.2);
max-width: 85%;
margin-left: auto;
margin-right: 0;
animation: slideInRight 0.3s ease-out;
}
/* ルリメッセージボックス */
.ruri-message {
background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
padding: 1rem 1.25rem;
margin: 0.75rem 0;
border-radius: 1rem 1rem 1rem 0.25rem;
border-left: 4px solid #8e24aa;
color: #4a148c;
box-shadow: 0 3px 12px rgba(142, 36, 170, 0.2);
max-width: 85%;
margin-left: 0;
margin-right: auto;
animation: slideInLeft 0.3s ease-out;
}
/* タイピング効果 */
.typing-indicator {
background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
padding: 1rem 1.25rem;
margin: 0.75rem 0;
border-radius: 1rem 1rem 1rem 0.25rem;
border-left: 4px solid #8e24aa;
color: #4a148c;
box-shadow: 0 3px 12px rgba(142, 36, 170, 0.2);
max-width: 85%;
margin-left: 0;
margin-right: auto;
/* 無限アニメーションを無効化 - 定期リロード防止 */
/* animation: pulse 1.5s infinite; */
}
.typing-dots {
display: inline-block;
position: relative;
}
.typing-dots span {
opacity: 1; /* 固定表示に変更 */
/* 無限アニメーションを無効化 - 定期リロード防止 */
/* animation: typingDots 1.4s infinite; */
}
/* アニメーション遅延も無効化 */
.typing-dots span:nth-child(1) { /* animation-delay: 0s; */ }
.typing-dots span:nth-child(2) { /* animation-delay: 0.2s; */ }
.typing-dots span:nth-child(3) { /* animation-delay: 0.4s; */ }
/* アニメーション定義 */
@keyframes slideInRight {
from { opacity: 0; transform: translateX(30px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slideInLeft {
from { opacity: 0; transform: translateX(-30px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}
@keyframes typingDots {
0%, 60%, 100% { opacity: 0; }
30% { opacity: 1; }
}
/* タイムスタンプスタイル */
.message-timestamp {
font-size: 0.75rem;
color: rgba(0, 0, 0, 0.5);
margin-bottom: 0.5rem;
text-align: center;
}
/* ラベルスタイル */
.message-label {
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 0.25rem;
opacity: 0.8;
}
.message-content {
font-size: 1rem;
line-height: 1.5;
margin: 0;
}
.chat-input-section {
background: transparent;
padding: 1rem 0;
border-radius: 0;
margin-top: 0.5rem;
border: none;
box-shadow: none;
}
/* 画像レスポンシブ - 感情学習をイメージした枠(コンパクト版) */
.ruri-image-container {
display: flex;
justify-content: center;
margin: 1rem 0;
position: relative;
}
.ruri-image-container img {
max-width: 100%;
max-height: 300px;
height: auto;
border-radius: 1.5rem;
box-shadow: 0 8px 32px rgba(99, 102, 241, 0.2);
border: 3px solid #e2e8f0;
transition: all 0.3s ease;
object-fit: contain;
}
.ruri-image-container img:hover {
transform: scale(1.02);
box-shadow: 0 12px 48px rgba(99, 102, 241, 0.3);
}
/* 画像コンテナのレスポンシブ対応 */
div[data-testid="column"]:first-child {
display: flex;
flex-direction: column;
align-items: center;
padding: 0 1rem;
}
div[data-testid="column"]:first-child img {
max-width: min(300px, 90vw);
height: auto;
border-radius: 1rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
border: 3px solid #e2e8f0;
margin: 0 auto;
}
/* カラーパレット - 戯曲『あいのいろ』テーマ */
:root {
--primary-color: #6366f1; /* 感情学習の青 */
--secondary-color: #8b5cf6; /* 成長の紫 */
--accent-color: #06b6d4; /* 変化の水色 */
--success-color: #10b981; /* 学習完了の緑 */
--text-primary: #1e293b; /* 高コントラスト黒 */
--text-secondary: #475569; /* 読みやすいグレー */
--background-light: #f8fafc; /* 明るい背景 */
--border-light: #e2e8f0; /* 優しいボーダー */
}
/* モバイル対応 */
@media (max-width: 768px) {
.chat-container {
padding: 0.75rem;
margin: 0.5rem 0;
}
.user-message, .ruri-message, .typing-indicator {
padding: 0.75rem 1rem;
font-size: 0.95rem;
margin: 0.5rem 0;
max-width: 90%;
border-radius: 0.75rem 0.75rem 0.25rem 0.75rem;
}
.ruri-message, .typing-indicator {
border-radius: 0.75rem 0.75rem 0.75rem 0.25rem;
}
.message-content {
font-size: 0.9rem;
}
.message-timestamp {
font-size: 0.7rem;
}
.chat-input-section {
padding: 0.5rem 0;
border-radius: 0;
}
.ruri-image-container img {
max-width: 80%;
max-height: 200px;
border-radius: 1rem;
}
.main > div {
padding-top: 1rem;
}
/* モバイルでのボタン配置 */
.stColumns > div {
min-width: 0 !important;
flex: 1 !important;
}
.stButton > button {
width: 100% !important;
font-size: 0.9rem !important;
padding: 0.5rem !important;
}
/* モバイルでのカラム幅調整とレスポンシブ画像 */
div[data-testid="column"]:nth-child(1) {
flex: 1 !important;
padding: 0.5rem !important;
text-align: center;
}
div[data-testid="column"]:nth-child(1) img {
max-width: min(250px, 85vw) !important;
margin: 0 auto !important;
}
div[data-testid="column"]:nth-child(2) {
flex: 1 !important;
padding: 0.5rem !important;
}
}
/* タブレット対応 */
@media (min-width: 769px) and (max-width: 1024px) {
.chat-container {
padding: 1.25rem;
}
.ruri-image-container img {
max-width: 85%;
}
/* タブレットでの画像調整 */
div[data-testid="column"]:first-child img {
max-width: min(280px, 80vw);
}
}
/* デスクトップ対応 */
@media (min-width: 1025px) {
/* デスクトップでの画像調整 */
div[data-testid="column"]:first-child img {
max-width: min(300px, 25vw);
}
}
/* 高コントラストアクセシビリティ */
@media (prefers-contrast: high) {
.chat-message {
border-left-width: 6px;
border-color: #000000;
}
.chat-container {
border-color: #475569;
border-width: 3px;
}
}
/* 視覚的な強調 */
.highlight-text {
color: var(--primary-color);
font-weight: 600;
}
.status-indicator {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.875rem;
font-weight: 500;
}
.status-active {
background-color: #dcfce7;
color: #166534;
border: 1px solid #22c55e;
}
.status-limited {
background-color: #fef3c7;
color: #92400e;
border: 1px solid #f59e0b;
}
/* expanderのスタイル改善 */
.streamlit-expander {
background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
border: 1px solid #cbd5e1;
border-radius: 0.5rem;
margin: 0.5rem 0;
}
/* レスポンシブ対応:モバイル */
@media (max-width: 768px) {
/* モバイルでは縦並び */
div[data-testid="column"] {
margin-bottom: 1rem;
}
}
</style>
""", unsafe_allow_html=True)
def setup_responsive_sidebar(user_level: Any, features: Dict[str, bool], ui_config: Dict):
"""レスポンシブ対応サイドバーの設定(シンプル版)"""
with st.sidebar:
st.title("🌟 メニュー")
# 認証状態表示(改良版・ホットリロード対応)
is_authenticated = st.session_state.get('authenticated', False)
if (hasattr(UserLevel, 'OWNER') and user_level == UserLevel.OWNER) or user_level == "owner" or is_authenticated:
st.success("🔓 所有者認証済み")
else:
st.info("🔒 パブリックモード")
# ナビゲーションメニュー(キー重複防止)
import time
import random
# 毎回新しいユニークIDを生成(セッション状態依存を排除)
unique_id = f"{int(time.time() * 1000000)}_{random.randint(10000, 99999)}"
# Streamlit Cloud デバッグ情報(一時的)
if st.session_state.get('show_debug', False):
st.write("🔍 デバッグ情報:")
st.write(f"- user_level: {user_level}")
st.write(f"- features: {features}")
st.write(f"- character_status: {features.get('character_status', False)}")
st.write(f"- basic_image_analysis: {features.get('basic_image_analysis', False)}")
# 強制的に無効化設定を適用(Streamlit Cloud対策)
menu_items = [
("home", "🏠 ホーム", True),
("character", "👤 キャラクター状態", False), # 強制無効化
("ai_conversation", "💬 ルリと話す", False), # ボタンを無効化
("image_analysis", "🖼️ 画像分析", False), # 強制無効化
("streaming", "📺 配信管理", False), # 強制無効化
("settings", "⚙️ 設定", False), # 強制無効化
("analytics", "📊 分析", False) # 強制無効化
]
for page_key, page_name, enabled in menu_items:
# すべてのボタンを表示(非活性の場合はdisabled=True)
button_clicked = st.button(
page_name,
key=f"nav_{page_key}_{unique_id}",
disabled=not enabled,
help="この機能は開発中です" if not enabled else None
)
if enabled and button_clicked:
current_page = st.session_state.get('current_page', 'home')
if current_page != page_key: # 異なるページの場合のみ遷移
st.session_state.current_page = page_key
# 会話処理中でない場合のみrerunを実行
if not st.session_state.get('chat_processing', False):
st.rerun()
# 認証関連(改良版・ホットリロード対応)
st.markdown("---")
# デバッグ情報切り替え(開発用)
if st.button("🔍 デバッグ情報", key=f"debug_toggle_{unique_id}"):
st.session_state.show_debug = not st.session_state.get('show_debug', False)
st.rerun()
is_authenticated = st.session_state.get('authenticated', False)
is_public = (hasattr(UserLevel, 'PUBLIC') and user_level == UserLevel.PUBLIC) or user_level == "public"
if (is_public and not is_authenticated):
auth_clicked = st.button("🔐 所有者認証", key="sidebar_auth_button")
if auth_clicked:
st.session_state.show_auth = True
st.rerun()
else:
logout_clicked = st.button("🚪 ログアウト", key="sidebar_logout_button")
if logout_clicked:
try:
UnifiedAuth().logout(st.session_state)
except:
# フォールバック時のログアウト
st.session_state.user_level = UserLevel.PUBLIC if hasattr(UserLevel, 'PUBLIC') else "public"
st.session_state.authenticated = False
# 初期化フラグもリセット
st.session_state.initialization_complete = False
# ログアウト時のみrerunが必要
st.rerun()
def show_home_page(user_level: Any, features: Dict[str, bool], ui_config: Dict):
"""ホームページ - レスポンシブ対応チャット機能付き"""
# チャット履歴の安定した初期化(確実に実行)
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# メイン画像とタイトル
st.markdown("""
<div style="text-align: center; margin-bottom: 1.5rem;">
<h1 style="color: #4a90e2; margin-bottom: 0.5rem;">🌟 pupa: ルリ</h1>
<p style="color: #666; font-size: 1.1rem;">戯曲『あいのいろ』から生まれた感情学習型AI</p>
</div>
""", unsafe_allow_html=True)
# レスポンシブ対応:画像とキャラクター設定の配置
image_path = os.path.join(project_root, "assets", "ruri_imageboard.png")
# レスポンシブレイアウト(強化版)
st.markdown("""
<style>
.main-content-container {
max-width: 1000px !important;
margin: 0 auto !important;
padding: 1rem !important;
}
.stColumn {
padding: 0 1rem !important;
}
.stImage > img {
max-width: 100% !important;
height: auto !important;
}
</style>
<div class="main-content-container">
""", unsafe_allow_html=True)
col1, col2 = st.columns([1, 1], gap="medium")
with col1:
st.markdown("#### 🎭 ルリ")
if os.path.exists(image_path):
# シンプルな画像表示(最新のStreamlit推奨方法)
st.image(image_path, caption="")
else:
st.info("🎭 ルリの画像を読み込み中...")
with col2:
# キャラクター設定ブロック(シンプルなStreamlitコンポーネント)
st.markdown("#### 📖 キャラクター設定")
# 情報カード風の表示
with st.expander("📋 基本情報", expanded=True):
st.markdown("**名前**: ルリ")
st.markdown("**特徴**: 感情を学習して段階的に色づいていくAI")
with st.expander("🎯 現在の状態", expanded=True):
st.markdown("**学習段階**: 🖤 Monochrome (学習開始段階)")
st.markdown("**感情学習進度**: 5%")
# プログレスバー
progress = 0.05
st.progress(progress)
with st.expander("📚 原作情報", expanded=True):
st.markdown("**原作**: 戯曲『あいのいろ』")
st.markdown("**作者**: 尾崎太祐 / Otty")
st.markdown("**キャラクターデザイン**: まつはち")