-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1580 lines (1371 loc) · 53.9 KB
/
app.py
File metadata and controls
1580 lines (1371 loc) · 53.9 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 requests
import cloudscraper
import base64
import time
import random
from datetime import datetime
import json
import os
import hashlib
from openai import OpenAI
# --- 1. 页面基础配置 ---
st.set_page_config(
page_title="ShowImageWeb - AI图像生成器",
page_icon="✨",
layout="wide",
initial_sidebar_state="expanded"
)
# 强制页面从顶部开始 - 在最开始执行
st.markdown("""
<script>
// 页面顶部强制执行
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
window.scrollTo(0, 0);
</script>
<style>
html {
scroll-behavior: auto !important;
scroll-padding-top: 0 !important;
}
body {
scroll-behavior: auto !important;
}
</style>
""", unsafe_allow_html=True)
# --- 2. 高级CSS样式系统 ---
st.markdown("""
<style>
/* CSS变量定义 */
:root {
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
--success-gradient: linear-gradient(135deg, #13B497 0%, #59D4A8 100%);
--warning-gradient: linear-gradient(135deg, #FFA500 0%, #FF6347 100%);
--glass-bg: rgba(255, 255, 255, 0.25);
--glass-border: rgba(255, 255, 255, 0.18);
--shadow-sm: 0 2px 4px rgba(0,0,0,0.1);
--shadow-md: 0 4px 6px rgba(0,0,0,0.1);
--shadow-lg: 0 10px 25px rgba(0,0,0,0.1);
--shadow-xl: 0 20px 40px rgba(0,0,0,0.15);
--border-radius-sm: 12px;
--border-radius-md: 16px;
--border-radius-lg: 24px;
--transition-fast: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
--transition-normal: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
--transition-slow: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
/* 全局背景设计 */
.stApp {
background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
background-attachment: fixed;
min-height: 100vh;
position: relative;
}
/* 动态背景粒子效果 */
.stApp::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background:
radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.2) 0%, transparent 50%);
z-index: -1;
animation: floatGradient 20s ease infinite;
}
@keyframes floatGradient {
0%, 100% { transform: translate(0, 0) rotate(0deg); }
33% { transform: translate(-20px, -20px) rotate(1deg); }
66% { transform: translate(20px, -10px) rotate(-1deg); }
}
/* 玻璃态容器 */
.glass-container {
background: var(--glass-bg);
backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: var(--border-radius-lg);
box-shadow: var(--shadow-xl);
padding: 1.5rem;
margin-bottom: 1rem;
position: relative;
overflow: hidden;
transition: var(--transition-normal);
}
.glass-container::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.6s;
}
.glass-container:hover::before {
left: 100%;
}
.glass-container:hover {
transform: translateY(-5px);
box-shadow: 0 30px 60px rgba(0,0,0,0.25);
}
/* 侧边栏超现代化设计 */
section[data-testid="stSidebar"] {
background: linear-gradient(180deg, #1a1a2e 0%, #0f0f23 100%);
backdrop-filter: blur(20px);
border-right: 1px solid rgba(255,255,255,0.1);
box-shadow: 4px 0 20px rgba(0,0,0,0.3);
}
section[data-testid="stSidebar"] > div:first-child {
padding: 2rem 1.5rem !important;
}
/* 侧边栏标题发光效果 */
section[data-testid="stSidebar"] h1 {
background: linear-gradient(135deg, #667eea, #764ba2, #f093fb);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
text-align: center;
font-size: 2.5rem !important;
font-weight: 800 !important;
text-shadow: 0 0 30px rgba(102, 126, 234, 0.5);
animation: glow 3s ease-in-out infinite alternate;
margin-bottom: 2rem !important;
}
@keyframes glow {
from { filter: drop-shadow(0 0 20px rgba(102, 126, 234, 0.3)); }
to { filter: drop-shadow(0 0 30px rgba(240, 147, 251, 0.5)); }
}
/* 侧边栏组件样式 */
section[data-testid="stSidebar"] h2,
section[data-testid="stSidebar"] h3,
section[data-testid="stSidebar"] h4 {
color: #ffffff !important;
font-weight: 600 !important;
margin-bottom: 1rem !important;
text-transform: uppercase;
letter-spacing: 1px;
font-size: 1.1rem !important;
}
section[data-testid="stSidebar"] label,
section[data-testid="stSidebar"] span,
section[data-testid="stSidebar"] p {
color: #e5e7eb !important;
font-weight: 400 !important;
}
/* 输入框样式重设计 */
.stTextArea > div > textarea {
background: rgba(255, 255, 255, 0.1) !important;
border: 2px solid rgba(102, 126, 234, 0.3) !important;
border-radius: var(--border-radius-md) !important;
color: #ffffff !important;
backdrop-filter: blur(10px);
transition: var(--transition-normal) !important;
font-size: 1rem !important;
padding: 1rem !important;
}
.stTextArea > div > textarea:focus {
background: rgba(255, 255, 255, 0.15) !important;
border-color: rgba(102, 126, 234, 0.8) !important;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2) !important;
outline: none !important;
}
.stTextInput > div > input {
background: rgba(255, 255, 255, 0.1) !important;
border: 2px solid rgba(102, 126, 234, 0.3) !important;
border-radius: var(--border-radius-sm) !important;
color: #ffffff !important;
backdrop-filter: blur(10px);
transition: var(--transition-normal) !important;
}
.stTextInput > div > input:focus {
background: rgba(255, 255, 255, 0.15) !important;
border-color: rgba(102, 126, 234, 0.8) !important;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2) !important;
outline: none !important;
}
/* 按钮系统重设计 */
div.stButton > button {
background: var(--primary-gradient) !important;
color: white !important;
border: none !important;
border-radius: var(--border-radius-sm) !important;
font-weight: 700 !important;
font-size: 1.1rem !important;
padding: 1rem 2rem !important;
transition: var(--transition-normal) !important;
box-shadow: var(--shadow-md) !important;
position: relative;
overflow: hidden;
text-transform: uppercase;
letter-spacing: 1px;
}
div.stButton > button::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
transition: left 0.5s;
}
div.stButton > button:hover::before {
left: 100%;
}
div.stButton > button:hover {
transform: translateY(-3px) scale(1.02) !important;
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3) !important;
}
div.stButton > button:active {
transform: translateY(-1px) scale(0.98) !important;
}
/* Primary按钮特殊样式 */
div.stButton > button[kind="primary"] {
background: linear-gradient(135deg, #FF6B6B, #FFE66D, #4ECDC4, #667eea) !important;
background-size: 300% 300% !important;
animation: gradientShift 3s ease infinite !important;
}
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
/* 下载按钮样式 */
div.stDownloadButton > button {
background: var(--success-gradient) !important;
border-radius: var(--border-radius-sm) !important;
font-weight: 600 !important;
padding: 0.75rem 1.5rem !important;
transition: var(--transition-normal) !important;
}
div.stDownloadButton > button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 8px 20px rgba(19, 180, 151, 0.3) !important;
}
/* 主标题区域 */
.main-header {
text-align: center;
margin-bottom: 3rem;
position: relative;
}
.main-header h1 {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
font-size: 4rem !important;
font-weight: 900 !important;
background: linear-gradient(135deg, #ffffff, #f0f0f0, #ffffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
text-shadow: 0 0 50px rgba(255,255,255,0.3);
margin-bottom: 1rem !important;
animation: titleFloat 6s ease-in-out infinite;
}
@keyframes titleFloat {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
.main-header p {
font-size: 1.3rem !important;
color: rgba(255,255,255,0.9) !important;
font-weight: 400 !important;
margin: 0 !important;
}
/* 输入区域高级容器 */
.input-section {
background: var(--glass-bg);
backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: var(--border-radius-lg);
padding: 2rem;
margin-bottom: 2rem;
box-shadow: var(--shadow-xl);
position: relative;
}
/* 图片画廊卡片系统 */
.gallery-card {
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(15px);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: var(--border-radius-md);
overflow: hidden;
transition: var(--transition-normal);
position: relative;
box-shadow: var(--shadow-md);
margin-bottom: 1rem;
/* 正方形画框容器 */
aspect-ratio: 1/1;
}
.gallery-card:hover {
transform: translateY(-8px) scale(1.02);
box-shadow: 0 25px 50px rgba(0,0,0,0.3);
background: rgba(255, 255, 255, 0.25);
}
.gallery-card img {
width: 100%;
height: 100%;
object-fit: cover;
transition: var(--transition-slow);
background: rgba(0,0,0,0.1);
/* 确保图片填满正方形容器 */
border-radius: var(--border-radius-md);
}
.gallery-card:hover img {
transform: scale(1.05);
}
/* 图片信息标签 */
.image-info {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
color: white;
padding: 1rem;
opacity: 0;
transform: translateY(20px);
transition: var(--transition-normal);
}
.gallery-card:hover .image-info {
opacity: 1;
transform: translateY(0);
}
/* 状态指示器美化 */
.stStatus .stAlert {
background: rgba(255, 255, 255, 0.1) !important;
backdrop-filter: blur(20px) !important;
border: 1px solid rgba(255, 255, 255, 0.2) !important;
border-radius: var(--border-radius-md) !important;
color: white !important;
font-weight: 500 !important;
}
/* 滑块样式 */
.stSlider {
margin: 1.5rem 0 !important;
}
.stSlider [data-testid="stSliderHandle"] {
background: var(--primary-gradient) !important;
border: 2px solid white !important;
box-shadow: var(--shadow-md) !important;
}
.stSlider [data-testid="stSliderTrack"] {
background: rgba(102, 126, 234, 0.3) !important;
border-radius: 10px !important;
}
/* 开关按钮美化 */
.stCheckbox [data-testid="stMarkdownContainer"] {
background: rgba(255, 255, 255, 0.1) !important;
border-radius: var(--border-radius-sm) !important;
padding: 1rem !important;
transition: var(--transition-normal) !important;
}
.stCheckbox:hover [data-testid="stMarkdownContainer"] {
background: rgba(255, 255, 255, 0.15) !important;
}
/* 度量卡片美化 */
.stMetric {
background: rgba(255, 255, 255, 0.15) !important;
backdrop-filter: blur(15px) !important;
border: 1px solid rgba(255, 255, 255, 0.2) !important;
border-radius: var(--border-radius-md) !important;
padding: 1.5rem !important;
box-shadow: var(--shadow-lg) !important;
transition: var(--transition-normal) !important;
}
.stMetric:hover {
transform: translateY(-3px);
box-shadow: 0 15px 35px rgba(0,0,0,0.2);
background: rgba(255, 255, 255, 0.2);
}
/* 信息提示美化 */
.stInfo {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.2), rgba(240, 147, 251, 0.2)) !important;
backdrop-filter: blur(20px) !important;
border: 1px solid rgba(255, 255, 255, 0.3) !important;
border-radius: var(--border-radius-lg) !important;
color: white !important;
font-weight: 500 !important;
padding: 1.5rem !important;
}
/* 加载动画美化 */
.stSpinner > div {
border-top-color: #667eea !important;
border-radius: 50% !important;
animation: spin 1s linear infinite !important;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 滚动条美化 */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: var(--primary-gradient);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--secondary-gradient);
}
/* 禁用平滑滚动 */
html {
scroll-behavior: auto !important;
scroll-padding-top: 0 !important;
}
body {
scroll-behavior: auto !important;
overflow-x: hidden;
}
/* 确保主内容区域可见 */
.stApp {
scroll-margin-top: 0 !important;
min-height: 100vh;
}
/* 防止固定定位元素影响滚动 */
.stSidebar {
position: sticky !important;
top: 0;
height: 100vh;
}
/* 响应式设计 */
@media (max-width: 768px) {
.main-header h1 {
font-size: 2.5rem !important;
}
.glass-container {
padding: 1.5rem;
margin-bottom: 1.5rem;
}
.input-section {
padding: 1.5rem;
}
/* 保持正方形比例,但调整画框的缩放效果 */
.gallery-card:hover img {
transform: scale(1.03);
}
}
@media (max-width: 480px) {
/* 小屏幕下略微减小悬停缩放效果 */
.gallery-card:hover img {
transform: scale(1.02);
}
/* 优化小屏幕下的卡片间距 */
.gallery-card {
margin-bottom: 0.75rem;
}
}
/* 特殊效果:霓虹发光 */
.neon-glow {
box-shadow: 0 0 20px rgba(102, 126, 234, 0.5),
0 0 40px rgba(102, 126, 234, 0.3),
0 0 60px rgba(102, 126, 234, 0.1);
}
/* 悬浮动画 */
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-20px); }
}
.floating {
animation: float 6s ease-in-out infinite;
}
</style>
""", unsafe_allow_html=True)
# --- 3. 状态管理 ---
# 初始化历史记录
if 'history' not in st.session_state:
st.session_state.history = []
# 初始化生成状态(用于控制按钮变灰)
if 'is_generating' not in st.session_state:
st.session_state.is_generating = False
# --- 持久化存储功能 ---
def get_image_hash(image_bytes):
"""生成图片的唯一哈希值"""
return hashlib.md5(image_bytes).hexdigest()
def load_saved_gallery():
"""从文件加载保存的画廊"""
gallery_file = "saved_gallery/gallery.json"
if os.path.exists(gallery_file):
try:
with open(gallery_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
st.error(f"加载保存的画廊失败: {e}")
return []
return []
def save_gallery_to_file():
"""将画廊保存到文件"""
gallery_file = "saved_gallery/gallery.json"
os.makedirs("saved_gallery", exist_ok=True)
try:
with open(gallery_file, 'w', encoding='utf-8') as f:
json.dump(st.session_state.saved_gallery, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
st.error(f"保存画廊失败: {e}")
return False
def save_image_to_file(image_bytes, image_id):
"""保存图片文件到磁盘"""
image_dir = "saved_gallery/images"
os.makedirs(image_dir, exist_ok=True)
image_path = f"{image_dir}/{image_id}.png"
try:
with open(image_path, 'wb') as f:
f.write(image_bytes)
return image_path
except Exception as e:
st.error(f"保存图片失败: {e}")
return None
def save_temp_to_gallery(temp_item_id):
"""将临时作品保存到永久画廊"""
# 在历史记录中找到对应的临时作品
for i, item in enumerate(st.session_state.history):
if item["id"] == temp_item_id:
temp_item = item
break
else:
st.toast("❌ 未找到对应的临时作品", icon="❌")
return False
# 检查是否已经在永久画廊中
image_bytes = base64.b64decode(temp_item['base64_image'])
image_hash = get_image_hash(image_bytes)
for item in st.session_state.saved_gallery:
if item.get('hash') == image_hash:
st.toast("🎨 该作品已在画廊中", icon="✅")
return False
# 保存图片文件
image_path = save_image_to_file(image_bytes, temp_item['id'])
if not image_path:
return False
# 创建永久作品记录(保持相同的时间戳)
gallery_item = {
"id": temp_item['id'],
"prompt": temp_item['prompt'],
"image_path": image_path,
"hash": image_hash,
"seed": temp_item['seed'],
"time": temp_item['time'],
"duration": temp_item['duration'],
"saved_at": time.time()
}
st.session_state.saved_gallery.insert(0, gallery_item)
# 从临时历史中移除
st.session_state.history.pop(i)
# 保存到文件
if save_gallery_to_file():
st.toast("🎉 作品已保存到画廊!", icon="✅")
return True
return False
def remove_from_saved_gallery(image_id):
"""从保存的画廊中移除图片"""
for i, item in enumerate(st.session_state.saved_gallery):
if item["id"] == image_id:
# 删除图片文件
try:
if os.path.exists(item["image_path"]):
os.remove(item["image_path"])
except Exception as e:
st.warning(f"删除图片文件失败: {e}")
# 从列表中移除
st.session_state.saved_gallery.pop(i)
# 保存更新后的画廊
save_gallery_to_file()
st.toast("🗑️ 作品已从画廊移除", icon="✅")
return True
return False
# --- 3. 状态管理 ---
# 初始化历史记录
if 'history' not in st.session_state:
st.session_state.history = []
# 初始化生成状态(用于控制按钮变灰)
if 'is_generating' not in st.session_state:
st.session_state.is_generating = False
# 初始化填充提示状态
if 'filled_prompt' not in st.session_state:
st.session_state.filled_prompt = ""
# 初始化保存的输入内容
if 'saved_prompt' not in st.session_state:
st.session_state.saved_prompt = ""
# 初始化生成记录状态
if 'has_generated' not in st.session_state:
st.session_state.has_generated = False
# 初始化保存的画廊状态
if 'saved_gallery' not in st.session_state:
st.session_state.saved_gallery = load_saved_gallery()
# 初始化API Key保存状态
if 'save_api_key' not in st.session_state:
st.session_state.save_api_key = False
def save_api_key_to_local(key):
"""将API Key保存到本地文件"""
try:
with open('api_key.txt', 'w') as f:
f.write(key)
return True
except Exception as e:
st.error(f"保存API Key失败: {e}")
return False
def load_saved_api_key():
"""从本地文件加载保存的API Key"""
try:
if os.path.exists('api_key.txt'):
with open('api_key.txt', 'r') as f:
return f.read().strip()
except Exception:
pass
return None
def add_to_history(prompt, image_bytes, seed, duration):
"""将生成的图片添加到历史记录的最前面"""
timestamp = datetime.now().strftime("%H:%M:%S")
# 只存储base64编码,节省内存
base64_image = base64.b64encode(image_bytes).decode()
st.session_state.history.insert(0, {
"id": f"{int(time.time())}",
"prompt": prompt,
"base64_image": base64_image, # 只存储base64
"seed": seed,
"time": timestamp,
"duration": f"{duration:.2f}s"
})
# 标记已有生成记录
st.session_state.has_generated = True
def clear_history():
st.session_state.history = []
st.session_state.has_generated = False
def start_generating():
"""点击按钮时的回调:设置状态为生成中"""
st.session_state.is_generating = True
# --- 4. 超现代化侧边栏控制台 ---
with st.sidebar:
# 动态装饰分隔线
st.markdown("""
<div style="text-align: center; margin-bottom: 2rem;">
<div style="height: 3px; background: linear-gradient(90deg, #667eea, #764ba2, #f093fb); border-radius: 5px; margin-bottom: 1rem;"></div>
</div>
""", unsafe_allow_html=True)
# 控制台标题
st.markdown('<h1 style="text-align: center; font-size: 2rem; margin-bottom: 1.5rem;">控制台</h1>', unsafe_allow_html=True)
# API配置区域
st.markdown('<h4 style="color: #667eea; margin-bottom: 0.5rem; font-size: 0.9rem;">🔑 API 配置</h4>', unsafe_allow_html=True)
# API类型选择
api_type = st.selectbox(
"🔧 API 类型",
options=["L站Lazy佬API", "OpenAI格式API"],
index=1,
help="选择API调用格式"
)
# 根据API类型显示不同的配置
if api_type == "L站Lazy佬API":
api_base_url = st.text_input(
"🌐 API Endpoint",
value="https://z-api.aioec.tech/proxy/generate",
help="完整的API接口地址",
label_visibility="visible"
)
else: # OpenAI格式API
api_base_url = st.text_input(
"🌐 API Base URL",
value="https://ai.gitee.com/v1",
help="OpenAI格式的API基础地址",
label_visibility="visible"
)
# --- 默认 Key ---
DEFAULT_API_KEY = "sk-zKTGcw8llBFZLpXAAsxTmMSmCfY8DNfe"
# 尝试加载本地保存的API Key
saved_key = load_saved_api_key()
# 如果有保存的key,使用保存的;否则显示默认key
if saved_key:
api_key = st.text_input(
"🔐 API Key",
value=saved_key,
type="password",
placeholder="sk-...",
help="已加载本地保存的API Key"
)
else:
api_key = st.text_input(
"🔐 API Key",
value=DEFAULT_API_KEY,
type="password",
placeholder="sk-...",
help="已预置默认密钥,您也可以修改为自己的密钥"
)
# 添加保存API Key的勾选框
# 如果有保存的key,默认勾选;否则使用session状态
default_checkbox_value = st.session_state.save_api_key or bool(saved_key)
save_key = st.checkbox(
"💾保存Key",
value=default_checkbox_value,
help="勾选后将API Key保存到本地文件,下次启动时自动加载"
)
# 更新保存状态
st.session_state.save_api_key = save_key
# 如果用户勾选了保存且API Key发生变化,则保存到本地
if save_key and api_key and api_key != saved_key:
if save_api_key_to_local(api_key):
st.success("✅ API Key已保存到本地")
# 如果用户取消勾选,删除本地保存的文件
if not save_key and os.path.exists('api_key.txt'):
try:
os.remove('api_key.txt')
st.info("🗑️ 已删除本地保存的API Key")
except Exception:
pass
# 为OpenAI格式API添加额外配置
if api_type == "OpenAI格式API":
# 模型选择
model_name = st.selectbox(
"🤖 模型",
options=["z-image-turbo"],
index=0,
help="选择图像生成模型"
)
# 图像尺寸
image_size = st.selectbox(
"📐 图像尺寸",
options=["1024x1024", "2048x2048"],
index=0,
help="选择生成的图像尺寸"
)
# 推理步数
inference_steps = st.slider(
"🔢 推理步数",
min_value=1,
max_value=50,
value=9,
step=1,
help="推理步数,影响生成质量"
)
# 提示此为OpenAI格式的额外参数
st.info("💡 OpenAI格式API将使用模型、尺寸等参数进行生成")
# 分隔线
st.markdown('<div style="height: 1px; background: linear-gradient(90deg, rgba(102, 126, 234, 0.3), rgba(102, 126, 234, 0.1), transparent); margin: 1rem 0;"></div>', unsafe_allow_html=True)
# 生成参数区域
st.markdown('<h4 style="color: #764ba2; margin-bottom: 0.5rem; font-size: 0.9rem;">⚙️ 生成参数</h4>', unsafe_allow_html=True)
seed_input = st.number_input(
"🎲 随机种子",
value=42,
step=1,
help="控制生成结果的随机性"
)
use_random = st.toggle("🎯 随机种子模式", value=True, help="每次生成使用不同的随机种子")
# 分隔线
st.markdown('<div style="height: 1px; background: linear-gradient(90deg, rgba(118, 75, 162, 0.3), rgba(118, 75, 162, 0.1), transparent); margin: 1rem 0;"></div>', unsafe_allow_html=True)
# 界面设置区域
st.markdown('<h4 style="color: #f093fb; margin-bottom: 0.5rem; font-size: 0.9rem;">🎨 界面设置</h4>', unsafe_allow_html=True)
gallery_cols = st.slider(
"📐 画廊列数",
min_value=1,
max_value=4,
value=2,
help="列数越少,单张图片显示越大"
)
# 分隔线
st.markdown('<div style="height: 1px; background: linear-gradient(90deg, rgba(240, 147, 251, 0.3), rgba(240, 147, 251, 0.1), transparent); margin: 1rem 0;"></div>', unsafe_allow_html=True)
# 统计信息区域
st.markdown('<h4 style="color: #13B497; margin-bottom: 0.5rem; font-size: 0.9rem;">📊 统计信息</h4>', unsafe_allow_html=True)
history_count = len(st.session_state.history)
# 高级统计卡片
col1, col2 = st.columns(2)
with col1:
st.metric(
"🖼️ 已生成",
f"{history_count}",
delta=None,
help="本次会话生成的图片总数"
)
with col2:
if history_count > 0:
avg_duration = sum(float(item['duration'].rstrip('s')) for item in st.session_state.history[:5]) / min(5, history_count)
st.metric(
"⚡ 平均耗时",
f"{avg_duration:.1f}s",
help="最近5张图片的平均生成时间"
)
# 操作按钮
if history_count > 0:
st.markdown('<div style="margin-top: 1rem;">', unsafe_allow_html=True)
if st.button(
"🗑️ 清空历史记录",
use_container_width=True,
type="secondary",
help="删除所有生成的历史图片"
):
clear_history()
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
# 临时作品管理
temp_count = len(st.session_state.history)
if temp_count > 0:
st.markdown('<div style="margin-top: 1rem;">', unsafe_allow_html=True)
if st.button(
f"💾 保存所有临时作品 ({temp_count})",
use_container_width=True,
type="secondary",
help="将所有临时作品永久保存"
):
saved_count = 0
for item in st.session_state.history[:]: # 使用切片避免修改正在迭代的列表
if save_temp_to_gallery(item["id"]):
saved_count += 1
if saved_count > 0:
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
# 保存画廊管理
saved_count = len(st.session_state.saved_gallery)
if saved_count > 0:
st.markdown('<div style="margin-top: 1rem;">', unsafe_allow_html=True)
if st.button(
f"🗑️ 清空保存的画廊 ({saved_count})",
use_container_width=True,
type="secondary",
help="删除所有永久保存的图片"
):
if st.session_state.saved_gallery:
# 删除所有保存的图片文件
for item in st.session_state.saved_gallery:
try:
if os.path.exists(item["image_path"]):
os.remove(item["image_path"])
except Exception as e:
st.warning(f"删除图片文件失败: {e}")
# 清空保存的画廊
st.session_state.saved_gallery = []
save_gallery_to_file()
st.toast("🗑️ 保存的画廊已清空", icon="✅")
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
# 底部装饰 - 减小间距
st.markdown("""
<div style="text-align: center; margin-top: 1rem;">
<div style="height: 2px; background: linear-gradient(90deg, transparent, #667eea, transparent); border-radius: 5px;"></div>
<p style="color: #e5e7eb; font-size: 0.8rem; margin-top: 0.5rem;">✨ Powered by AI</p>
</div>
""", unsafe_allow_html=True)
# --- 5. 超现代化主工作区 ---
# 顶部锚点 - 强制页面从这里开始
st.markdown('<div id="top" style="height: 1px; width: 1px; visibility: hidden;"></div>', unsafe_allow_html=True)
# 主标题区域
st.markdown("""
<div class="main-header floating">
<h1>ShowImageWeb</h1>
<p>🎨 AI图像生成 - 将您的想象力转化为视觉艺术</p>
</div>
""", unsafe_allow_html=True)
# 输入区域布局
st.markdown('<div style="max-width: 900px; margin: 0 auto 2rem auto;">', unsafe_allow_html=True)
# 主输入区域 - 调整列比例
col1, col2, col3 = st.columns([8, 0.5, 3])
with col1: