-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_sleep.py
More file actions
1799 lines (1547 loc) · 61.4 KB
/
main_sleep.py
File metadata and controls
1799 lines (1547 loc) · 61.4 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
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime, timedelta
import pymysql
import os
from dotenv import load_dotenv
# .env 파일 로드
load_dotenv()
# ==================== 페이지 설정 ====================
st.set_page_config(
page_title="FISAGRAM",
page_icon="🍪",
layout="wide"
)
# ==================== 데이터베이스 연결 함수 (MySQL) ====================
def get_db_connection():
"""MySQL 데이터베이스 연결"""
try:
connection = pymysql.connect(
host='118.67.131.22',
port=3306,
user='fisaai6',
passwd=os.getenv('FISADB_PASSWORD'),
db='fisagram',
charset='utf8mb4'
)
return connection
except Exception as e:
st.error(f"❌ 데이터베이스 연결 실패: {str(e)}")
return None
def get_db_connection_dict():
"""딕셔너리 커서용 연결 (일반 쿼리용)"""
try:
connection = pymysql.connect(
host='118.67.131.22',
port=3306,
user='fisaai6',
passwd=os.getenv('FISADB_PASSWORD'),
db='fisagram',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
return connection
except Exception as e:
st.error(f"❌ 데이터베이스 연결 실패: {str(e)}")
return None
# ==================== 수면 데이터 관련 함수 ====================
def load_sleep_data():
"""DB에서 모든 수면 기록 불러오기"""
conn = get_db_connection()
if conn is None:
return pd.DataFrame()
try:
query = """
SELECT
log_id,
user_id,
sleep_date,
sleep_hours
FROM sleep_logs
ORDER BY sleep_date DESC
"""
df = pd.read_sql(query, conn)
if not df.empty:
df['date'] = pd.to_datetime(df['sleep_date'])
df = df.drop(columns=['sleep_date'])
df['sleep_hours'] = pd.to_numeric(df['sleep_hours'], errors='coerce')
df = df.dropna(subset=['date', 'sleep_hours'])
return df
except Exception as e:
st.error(f"❌ 데이터 로드 실패: {str(e)}")
return pd.DataFrame()
finally:
conn.close()
def get_user_list():
"""사용자 목록 가져오기"""
conn = get_db_connection_dict()
if conn is None:
return []
try:
cursor = conn.cursor()
cursor.execute("SELECT DISTINCT user_id FROM users_study_flat ORDER BY user_id")
users = [row['user_id'] for row in cursor.fetchall()]
return users
except Exception as e:
st.error(f"❌ 사용자 목록 로드 실패: {str(e)}")
return []
finally:
conn.close()
def save_sleep_record(user_id, sleep_date, sleep_hours):
"""새 수면 기록 저장"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
delete_query = """
DELETE FROM sleep_logs
WHERE user_id = %s AND sleep_date = %s
"""
cursor.execute(delete_query, (user_id, sleep_date))
insert_query = """
INSERT INTO sleep_logs (user_id, sleep_date, sleep_hours)
VALUES (%s, %s, %s)
"""
cursor.execute(insert_query, (user_id, sleep_date, sleep_hours))
conn.commit()
return True
except Exception as e:
st.error(f"❌ 데이터 저장 실패: {str(e)}")
conn.rollback()
return False
finally:
conn.close()
# ==================== 커뮤니티 팁 관련 함수 ====================
def create_tips_table_if_not_exists():
"""커뮤니티 팁 테이블 생성"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS community_tips (
tip_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
tip_content TEXT NOT NULL,
likes INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
cursor.execute(create_table_query)
conn.commit()
return True
except Exception as e:
st.warning(f"⚠️ 테이블 생성 실패: {str(e)}")
return False
finally:
conn.close()
def load_community_tips():
"""커뮤니티 팁 불러오기"""
conn = get_db_connection_dict()
if conn is None:
return []
try:
cursor = conn.cursor()
cursor.execute("""
SELECT tip_id, username, tip_content, likes, created_at
FROM community_tips
ORDER BY likes DESC, created_at DESC
""")
tips = cursor.fetchall()
return tips
except Exception as e:
create_tips_table_if_not_exists()
return []
finally:
conn.close()
def save_community_tip(username, tip_content):
"""새 커뮤니티 팁 저장"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
insert_query = """
INSERT INTO community_tips (username, tip_content, likes)
VALUES (%s, %s, 0)
"""
cursor.execute(insert_query, (username, tip_content))
conn.commit()
return True
except Exception as e:
st.error(f"❌ 팁 저장 실패: {str(e)}")
return False
finally:
conn.close()
def update_tip_likes(tip_id, new_likes):
"""팁 좋아요 수 업데이트"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
cursor.execute("""
UPDATE community_tips
SET likes = %s
WHERE tip_id = %s
""", (new_likes, tip_id))
conn.commit()
return True
except Exception as e:
st.error(f"❌ 좋아요 업데이트 실패: {str(e)}")
return False
finally:
conn.close()
def delete_community_tip(tip_id):
"""커뮤니티 팁 삭제"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
cursor.execute("DELETE FROM community_tips WHERE tip_id = %s", (tip_id,))
conn.commit()
return True
except Exception as e:
st.error(f"❌ 삭제 실패: {str(e)}")
return False
finally:
conn.close()
# ==================== 좌석표 관련 함수 (MySQL 연동) ====================
def create_seating_table_if_not_exists():
"""좌석 배치 테이블 생성"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
create_table_query = """
CREATE TABLE IF NOT EXISTS seating_arrangement (
id INT AUTO_INCREMENT PRIMARY KEY,
section VARCHAR(20) NOT NULL,
row_num INT NOT NULL,
col_num INT NOT NULL,
user_id INT NOT NULL,
UNIQUE KEY unique_seat (section, row_num, col_num),
FOREIGN KEY (user_id) REFERENCES users_study_flat(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
cursor.execute(create_table_query)
conn.commit()
return True
except Exception as e:
st.warning(f"⚠️ 테이블 생성 실패: {str(e)}")
return False
finally:
conn.close()
def get_all_users_from_mysql():
"""MySQL에서 모든 사용자 정보 가져오기"""
conn = get_db_connection_dict()
if conn is None:
return []
try:
cursor = conn.cursor()
cursor.execute("""
SELECT user_id, user_name, birth_year, major, mbti,
region, interests, intro, study_name
FROM users_study_flat
ORDER BY user_name
""")
users = cursor.fetchall()
return users
except Exception as e:
st.error(f"❌ 사용자 목록 로드 실패: {str(e)}")
return []
finally:
conn.close()
def get_user_by_id_mysql(user_id):
"""MySQL에서 특정 사용자 정보 가져오기"""
conn = get_db_connection_dict()
if conn is None:
return None
try:
cursor = conn.cursor()
cursor.execute("""
SELECT user_id, user_name, birth_year, major, mbti,
region, interests, intro, study_name
FROM users_study_flat
WHERE user_id = %s
""", (user_id,))
user = cursor.fetchone()
return user
except Exception as e:
st.error(f"❌ 사용자 정보 로드 실패: {str(e)}")
return None
finally:
conn.close()
def save_seating_arrangement(seating_data):
"""좌석 배치 저장 (MySQL)"""
conn = get_db_connection_dict()
if conn is None:
return False
try:
cursor = conn.cursor()
# 기존 좌석 배치 삭제
cursor.execute("DELETE FROM seating_arrangement")
# 새 좌석 배치 저장
for seat in seating_data:
cursor.execute("""
INSERT INTO seating_arrangement (section, row_num, col_num, user_id)
VALUES (%s, %s, %s, %s)
""", (seat['section'], seat['row'], seat['col'], seat['user_id']))
conn.commit()
return True
except Exception as e:
st.error(f"❌ 좌석 배치 저장 실패: {str(e)}")
conn.rollback()
return False
finally:
conn.close()
def load_seating_arrangement():
"""저장된 좌석 배치 불러오기 (MySQL)"""
conn = get_db_connection_dict()
if conn is None:
return {}
try:
cursor = conn.cursor()
cursor.execute("SELECT section, row_num, col_num, user_id FROM seating_arrangement")
seats = cursor.fetchall()
seating = {}
for seat in seats:
key = f"{seat['section']}_{seat['row_num']}_{seat['col_num']}"
seating[key] = seat['user_id']
return seating
except Exception as e:
# 테이블이 없으면 생성 시도
create_seating_table_if_not_exists()
return {}
finally:
conn.close()
# ==================== 세션 상태 초기화 ====================
if "current_page" not in st.session_state:
st.session_state.current_page = "main"
if "selected_user" not in st.session_state:
st.session_state.selected_user = 1
if 'seating' not in st.session_state:
st.session_state.seating = load_seating_arrangement()
if 'selected_user_info' not in st.session_state:
st.session_state.selected_user_info = None
if 'sleep_tips' not in st.session_state:
st.session_state.sleep_tips = []
if 'tip_counter' not in st.session_state:
st.session_state.tip_counter = 1
if 'user_liked_tips' not in st.session_state:
st.session_state.user_liked_tips = set()
if 'sleep_data' not in st.session_state:
# 초기 데이터 로드
with st.spinner("📊 데이터 로딩 중..."):
st.session_state.sleep_data = load_sleep_data()
# ==================== Instagram 스타일 CSS ====================
st.markdown("""
<style>
/* 전체 배경 */
.main {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
/* 메인 헤더 - Instagram 느낌 */
.main-header {
font-size: 2.8rem;
font-weight: 800;
text-align: center;
margin-bottom: 2rem;
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: -1px;
}
/* 통계 카드 - 4가지 색상 그라데이션 */
.stat-card-purple {
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
padding: 2rem;
border-radius: 20px;
color: white;
text-align: center;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
transition: transform 0.3s ease;
}
.stat-card-pink {
background: linear-gradient(135deg, #F093FB 0%, #F5576C 100%);
padding: 2rem;
border-radius: 20px;
color: white;
text-align: center;
box-shadow: 0 10px 30px rgba(245, 87, 108, 0.3);
transition: transform 0.3s ease;
}
.stat-card-blue {
background: linear-gradient(135deg, #4FACFE 0%, #00F2FE 100%);
padding: 2rem;
border-radius: 20px;
color: white;
text-align: center;
box-shadow: 0 10px 30px rgba(79, 172, 254, 0.3);
transition: transform 0.3s ease;
}
.stat-card-teal {
background: linear-gradient(135deg, #43E97B 0%, #38F9D7 100%);
padding: 2rem;
border-radius: 20px;
color: white;
text-align: center;
box-shadow: 0 10px 30px rgba(67, 233, 123, 0.3);
transition: transform 0.3s ease;
}
.stat-card-purple:hover, .stat-card-pink:hover,
.stat-card-blue:hover, .stat-card-teal:hover {
transform: translateY(-5px);
}
.stat-label {
font-size: 0.95rem;
font-weight: 600;
opacity: 0.95;
margin-bottom: 0.5rem;
letter-spacing: 0.5px;
}
.stat-value {
font-size: 2.5rem;
font-weight: 800;
text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* 학습 진행도 게이지 컨테이너 */
.progress-container {
background: white;
border-radius: 20px;
padding: 2.5rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.08);
margin: 2rem 0;
}
.progress-title {
font-size: 1.8rem;
font-weight: 700;
color: #333;
text-align: center;
margin-bottom: 1.5rem;
}
/* 카드 스타일 */
.instagram-card {
background: white;
border-radius: 20px;
padding: 2rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.08);
margin-bottom: 1.5rem;
transition: transform 0.3s ease;
}
.instagram-card:hover {
transform: translateY(-3px);
box-shadow: 0 15px 50px rgba(0,0,0,0.12);
}
/* 수면 팁 카드 */
.sleep-tip {
background: linear-gradient(135deg, #E8F4F8 0%, #D4E7F0 100%);
padding: 1.2rem;
border-radius: 15px;
border-left: 5px solid #4FACFE;
margin-bottom: 0.8rem;
font-weight: 500;
transition: all 0.3s ease;
}
.sleep-tip:hover {
transform: translateX(5px);
box-shadow: 0 5px 15px rgba(79, 172, 254, 0.2);
}
/* 커뮤니티 팁 */
.community-tip {
background: linear-gradient(135deg, #FFF9E6 0%, #FFF0CC 100%);
padding: 1.5rem;
border-radius: 15px;
margin-bottom: 1.2rem;
border: 2px solid #FFE4A3;
box-shadow: 0 5px 20px rgba(0,0,0,0.05);
}
.tip-header {
font-weight: 700;
color: #333;
margin-bottom: 0.7rem;
font-size: 1.05rem;
}
.tip-content {
color: #555;
line-height: 1.7;
margin: 0.8rem 0;
}
.tip-footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.8rem;
font-size: 0.9rem;
color: #999;
}
.tip-likes {
color: #FF6B6B;
font-size: 1rem;
font-weight: 600;
}
/* DB 연결 상태 */
.db-status {
background: linear-gradient(135deg, #E8F5E9 0%, #C8E6C9 100%);
padding: 1rem;
border-radius: 15px;
border-left: 5px solid #4CAF50;
margin-bottom: 1.5rem;
font-weight: 600;
}
/* 정보 카드 */
.info-card {
background: white;
border-radius: 20px;
padding: 2rem;
box-shadow: 0 10px 40px rgba(0,0,0,0.08);
margin-bottom: 1.5rem;
}
.info-header {
font-size: 1.8rem;
font-weight: 700;
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 1.5rem;
}
.info-item {
margin: 12px 0;
padding: 12px;
background: linear-gradient(135deg, #F8F9FA 0%, #E9ECEF 100%);
border-radius: 10px;
font-size: 0.95rem;
font-weight: 500;
}
/* 섹션 타이틀 */
.section-title {
font-size: 1.5rem;
font-weight: 700;
color: #333;
margin-bottom: 1.2rem;
text-align: center;
}
/* 사이드바 메뉴 버튼 스타일 */
[data-testid="stSidebar"] .stButton>button {
background: white;
color: #555;
border-radius: 12px;
border: 2px solid #E9ECEF;
font-weight: 600;
padding: 0.75rem 1.5rem;
transition: all 0.3s ease;
box-shadow: none;
width: 100%;
text-align: left;
}
[data-testid="stSidebar"] .stButton>button:hover {
background: #F8F9FA;
border-color: #667EEA;
color: #667EEA;
transform: translateX(5px);
}
/* 메인 페이지 버튼은 그라데이션 유지 */
.main .stButton>button {
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
color: white;
border-radius: 12px;
border: none;
font-weight: 700;
padding: 0.75rem 1.5rem;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
.main .stButton>button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
/* 좌석 버튼 - 하늘색 그라데이션 */
div[data-testid="column"] .stButton>button {
background: linear-gradient(135deg, #89CFF0 0%, #4FC3F7 100%);
color: white;
border-radius: 12px;
border: none;
font-weight: 700;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(79, 195, 247, 0.3);
font-size: 0.95rem;
padding: 1rem;
}
div[data-testid="column"] .stButton>button:hover {
transform: translateY(-3px);
box-shadow: 0 8px 25px rgba(79, 195, 247, 0.4);
background: linear-gradient(135deg, #4FC3F7 0%, #29B6F6 100%);
}
/* 빈 자리 버튼 */
div[data-testid="column"] .stButton>button:disabled {
background: #F0F0F0 !important;
color: #999 !important;
border: 2px dashed #DDD !important;
box-shadow: none !important;
}
/* 폼 입력 스타일 */
.stTextInput>div>div>input,
.stTextArea>div>div>textarea,
.stSelectbox>div>div>select {
border-radius: 10px;
border: 2px solid #E9ECEF;
transition: all 0.3s ease;
}
.stTextInput>div>div>input:focus,
.stTextArea>div>div>textarea:focus {
border-color: #667EEA;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
/* 네비게이션 배너 */
.nav-banner {
background: white;
padding: 1rem;
border-radius: 15px;
box-shadow: 0 4px 15px rgba(0,0,0,0.08);
margin-bottom: 2rem;
display: flex;
gap: 0.8rem;
flex-wrap: wrap;
justify-content: center;
}
.nav-button {
display: inline-block;
padding: 0.6rem 1.2rem;
background: linear-gradient(135deg, #F8F9FA 0%, #E9ECEF 100%);
color: #555;
text-decoration: none;
border-radius: 10px;
font-weight: 600;
font-size: 0.9rem;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.nav-button:hover {
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
color: white;
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
/* 통계 카드 */
.stat-card {
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
padding: 1.5rem;
border-radius: 15px;
color: white;
text-align: center;
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}
.stat-card .stat-label {
font-size: 0.9rem;
font-weight: 600;
opacity: 0.95;
margin-bottom: 0.5rem;
}
.stat-card .stat-value {
font-size: 2rem;
font-weight: 800;
text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
""", unsafe_allow_html=True)
# ==================== 메인 페이지 ====================
def show_main_page():
st.markdown('<div class="main-header"><span style="-webkit-text-fill-color: initial;">🍪</span> FISAGRAM</div>', unsafe_allow_html=True)
# 학습 진행도 계산 (총 960시간, 주 5일 하루 9시간씩)
total_hours = 960
start_date = datetime(2025, 12, 30) # 시작일
end_date = datetime(2026, 6, 25) # 수료일 (6월 25일)
current_date = datetime.now()
# 현재까지 경과한 영업일 수 계산 (주 5일 기준)
days_elapsed = (current_date - start_date).days
weeks_elapsed = days_elapsed // 7
remaining_days_in_week = days_elapsed % 7
# 주말 제외하고 실제 학습일 수 계산 (간단 계산: 주 5일 기준)
study_days = weeks_elapsed * 5 + min(remaining_days_in_week, 5)
elapsed_hours = study_days * 9 # 하루 9시간
# 최소값 보정 (음수 방지)
elapsed_hours = max(0, elapsed_hours)
remaining_hours = max(0, total_hours - elapsed_hours)
progress_percent = min(100, (elapsed_hours / total_hours) * 100)
# 수료일까지 남은 일수
days_until_completion = (end_date - current_date).days
# 4개 통계 카드 (Instagram 색상)
c1, c2, c3, c4 = st.columns(4)
with c1:
st.markdown(f"""
<div class="stat-card-purple">
<div class="stat-label">🌙 진행률</div>
<div class="stat-value">{progress_percent:.1f}%</div>
</div>
""", unsafe_allow_html=True)
with c2:
st.markdown(f"""
<div class="stat-card-pink">
<div class="stat-label">⏱️ 경과 시간</div>
<div class="stat-value">{elapsed_hours}h</div>
</div>
""", unsafe_allow_html=True)
with c3:
st.markdown(f"""
<div class="stat-card-blue">
<div class="stat-label">🎯 남은 시간</div>
<div class="stat-value">{remaining_hours}h</div>
</div>
""", unsafe_allow_html=True)
with c4:
st.markdown(f"""
<div class="stat-card-teal">
<div class="stat-label">📚 전체 시간</div>
<div class="stat-value">{total_hours}h</div>
</div>
""", unsafe_allow_html=True)
# 학습 진행도 게이지 차트
st.markdown("---")
st.markdown('<div class="progress-title">📊 부트캠프 진행도</div>', unsafe_allow_html=True)
fig = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=progress_percent,
delta={'reference': 0, 'increasing': {'color': "#43E97B"}},
title={'text': f"<b>{elapsed_hours}/{total_hours} 시간</b>", 'font': {'size': 24}},
number={'suffix': "%", 'font': {'size': 50, 'color': '#667EEA'}},
gauge={
'axis': {'range': [None, 100], 'tickwidth': 2, 'tickcolor': "#667EEA"},
'bar': {'color': "#667EEA", 'thickness': 0.8},
'bgcolor': "white",
'borderwidth': 3,
'bordercolor': "#E9ECEF",
'steps': [
{'range': [0, 33.3], 'color': '#FFE5E5'},
{'range': [33.3, 66.6], 'color': '#FFF5E5'},
{'range': [66.6, 100], 'color': '#E5F5E5'}
],
'threshold': {
'line': {'color': "#F5576C", 'width': 4},
'thickness': 0.75,
'value': progress_percent
}
}
))
fig.update_layout(
height=350,
margin=dict(l=20, r=20, t=50, b=20),
paper_bgcolor='rgba(0,0,0,0)',
font={'family': "Arial, sans-serif"}
)
st.plotly_chart(fig, use_container_width=True)
# 진행도 상세 정보
col_info1, col_info2 = st.columns(2)
with col_info1:
avg_hours_per_day = elapsed_hours / max(1, study_days)
st.markdown(f"""
<div class="instagram-card">
<h4>⚡ 현재 진행 속도</h4>
<p style="font-size: 1.2rem; color: #667EEA; font-weight: 700;">
평균 {avg_hours_per_day:.1f}시간/일 (주 5일 기준)
</p>
</div>
""", unsafe_allow_html=True)
with col_info2:
st.markdown(f"""
<div class="instagram-card">
<h4>🎓 예상 수료일</h4>
<p style="font-size: 1.2rem; color: #F5576C; font-weight: 700;">
2025년 6월 25일 (D-{days_until_completion})
</p>
</div>
""", unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("---")
# 메뉴 카드
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div class="instagram-card">
<h3>😴 수면 기록</h3>
<p style="color: #666; margin: 1rem 0;">수면 시간을 기록하고 분석하세요</p>
</div>
""", unsafe_allow_html=True)
if st.button("수면 기록 페이지로 이동 →", use_container_width=True, key="goto_sleep"):
st.session_state.current_page = "sleep"
st.rerun()
with col2:
st.markdown("""
<div class="instagram-card">
<h3>🪑 좌석표</h3>
<p style="color: #666; margin: 1rem 0;">우리 반 좌석 배치를 확인하세요</p>
</div>
""", unsafe_allow_html=True)
if st.button("좌석표 페이지로 이동 →", use_container_width=True, key="goto_seating"):
st.session_state.current_page = "seating"
st.rerun()
# ==================== 수면 기록 페이지 ====================
def show_sleep_page():
st.markdown('<div class="main-header">💤 수면 기록 관리</div>', unsafe_allow_html=True)
if st.button("⬅️ 메인으로"):
st.session_state.current_page = "main"
st.rerun()
df_all = st.session_state.sleep_data
if df_all.empty:
st.warning("⚠️ 수면 기록이 없습니다.")
return
# MySQL에서 사용자 이름 가져오기
conn = get_db_connection_dict()
user_map = {} # {user_id: user_name}
if conn:
try:
cursor = conn.cursor()
cursor.execute("SELECT user_id, user_name FROM users_study_flat")
for row in cursor.fetchall():
user_map[row['user_id']] = row['user_name']
conn.close()
except:
conn.close()
users = sorted(df_all["user_id"].unique())
if st.session_state.selected_user not in users:
st.session_state.selected_user = users[0]
# 사용자 이름으로 표시
user_display_options = [f"{user_map.get(uid, f'사용자 {uid}')}" for uid in users]
selected_display = st.selectbox(
"👤 사용자 선택",
user_display_options,
index=users.index(st.session_state.selected_user)
)
# 선택된 표시 옵션에서 실제 user_id 추출
selected_user = users[user_display_options.index(selected_display)]
st.session_state.selected_user = selected_user
# ==================== 배너와 오늘의 수면 기록을 양옆에 배치 ====================
col_banner, col_record = st.columns([1, 1])
with col_banner:
st.markdown("""
<style>
.nav-banner-large {
background: white;
padding: 1.5rem;
border-radius: 20px;
box-shadow: 0 8px 25px rgba(0,0,0,0.12);
margin-bottom: 2.5rem;
}
.nav-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
}
.nav-button-large {
display: flex;
align-items: center;
justify-content: center;
padding: 1.2rem 1.5rem;
background: linear-gradient(135deg, #8B9FE8 0%, #9B8FCA 100%);
color: white !important;
text-decoration: none !important;
border-radius: 15px;
font-weight: 700;
font-size: 1.05rem;
transition: all 0.3s ease;
border: none;
box-shadow: 0 4px 15px rgba(139, 159, 232, 0.3);
white-space: nowrap;
}
.nav-button-large:hover {
transform: translateY(-3px);
box-shadow: 0 8px 25px rgba(139, 159, 232, 0.4);
color: white !important;
background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
}
.emoji-icon {
font-size: 1.4rem;
margin-right: 0.6rem;
flex-shrink: 0;
text-decoration: none !important;
}
.tip-delete-btn {
background: #FF6B6B;
color: white;
border: none;
padding: 0.3rem 0.8rem;
border-radius: 8px;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.3s ease;