-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
1505 lines (1292 loc) · 48.5 KB
/
Copy pathweb_server.py
File metadata and controls
1505 lines (1292 loc) · 48.5 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
"""
VoxAI Web Server - Remote Access Interface
This creates a web-accessible version of VoxAI that you can access from anywhere.
Features:
- Password protected access
- Chat with LLM (streaming)
- Image generation with model selection
- Model hot-swapping via keyboard shortcuts
- Mobile-friendly responsive UI
Usage:
python web_server.py --port 7860 --password yourpassword
Then access from anywhere: http://your-ip:7860
"""
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
import sys
import json
import asyncio
import hashlib
import secrets
import argparse
import threading
import time
from pathlib import Path
from datetime import datetime, timedelta
from functools import wraps
# Add parent directory to path for imports
APP_DIR = Path(__file__).parent.absolute()
sys.path.insert(0, str(APP_DIR))
from backend.image_generator import GenerationConfig
# Add engine to path
VOX_API_DIR = APP_DIR / "engine"
if VOX_API_DIR.exists():
sys.path.insert(0, str(VOX_API_DIR))
# =========================================================
# BACKEND SETUP (CRITICAL FOR LOCAL LLAMA.CPP)
# =========================================================
def _setup_vox_backend():
"""Set up custom backend environment variables and DLLs."""
import ctypes
print("[VoxAI Server] Setting up custom backend...")
if not VOX_API_DIR.exists():
return False
vox_str = str(VOX_API_DIR)
llama_dll = VOX_API_DIR / "llama.dll"
ggml_dll = VOX_API_DIR / "ggml.dll"
# 1. Set LLAMA_CPP_LIB to point to our custom DLL
if llama_dll.exists():
os.environ["LLAMA_CPP_LIB"] = str(llama_dll)
print(f"[VoxAI Server] LLAMA_CPP_LIB = {llama_dll}")
# 2. Set Backend Search Path
os.environ["GGML_BACKEND_SEARCH_PATH"] = vox_str
# 3. Add to PATH
os.environ["PATH"] = vox_str + os.pathsep + os.environ.get("PATH", "")
# 4. Windows DLL Directories
if hasattr(os, 'add_dll_directory'):
try:
os.add_dll_directory(vox_str)
except Exception as e:
print(f"[VoxAI Server] DLL dir warning: {e}")
# 5. Pre-load ggml.dll and Backends
if ggml_dll.exists():
try:
ggml = ctypes.CDLL(str(ggml_dll))
if hasattr(ggml, 'ggml_backend_load_all'):
ggml.ggml_backend_load_all()
print("[VoxAI Server] Backends loaded (ggml_backend_load_all)")
except Exception as e:
print(f"[VoxAI Server] Backend load error: {e}")
return False
return True
# EXECUTE SETUP IMMEDIATELY
_setup_vox_backend()
# Flask imports
try:
from flask import Flask, request, jsonify, Response, render_template_string, session, redirect, url_for, send_file
from flask_cors import CORS
except ImportError:
print("[WebServer] Installing Flask...")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "flask", "flask-cors", "--quiet"])
from flask import Flask, request, jsonify, Response, render_template_string, session, redirect, url_for, send_file
from flask_cors import CORS
# ============================================
# CONFIGURATION
# ============================================
class ServerConfig:
HOST = "0.0.0.0"
PORT = 7860
PASSWORD = None # Set via command line or config
SECRET_KEY = secrets.token_hex(32)
SESSION_TIMEOUT = 24 * 60 * 60 # 24 hours
# Paths
MODELS_DIR = APP_DIR / "models" / "llm"
OUTPUT_DIR = APP_DIR / "outputs" / "images"
CHECKPOINTS_DIR = APP_DIR / "models" / "checkpoints"
# Image generation presets
IMAGE_PRESETS = {
"0": {
"name": "SDXL (Balanced)",
"checkpoint": "sd_xl_base_1.0.safetensors",
"width": 1024, "height": 1024,
"steps": 25, "cfg": 7.0,
"sampler": "euler_ancestral"
},
"1": {
"name": "SDXL (Quality)",
"checkpoint": "sd_xl_base_1.0.safetensors",
"width": 1024, "height": 1024,
"steps": 40, "cfg": 7.5,
"sampler": "dpmpp_2m"
},
"2": {
"name": "Flux (Fast)",
"checkpoint": "flux1-schnell.safetensors",
"width": 1024, "height": 1024,
"steps": 4, "cfg": 1.0,
"sampler": "euler"
},
"3": {
"name": "Flux (Dev)",
"checkpoint": "flux1-dev.safetensors",
"width": 1024, "height": 1024,
"steps": 25, "cfg": 3.5,
"sampler": "euler"
}
}
config = ServerConfig()
# ============================================
# FLASK APP
# ============================================
app = Flask(__name__)
app.secret_key = config.SECRET_KEY
CORS(app)
# Global state
class AppState:
vox_api = None
image_generator = None
current_llm_model = None
current_image_preset = "0"
is_generating = False
chat_history = []
state = AppState()
# ============================================
# AUTHENTICATION
# ============================================
def hash_password(password: str) -> str:
return hashlib.sha256(password.encode()).hexdigest()
def require_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if config.PASSWORD:
if 'authenticated' not in session or not session['authenticated']:
if request.is_json:
return jsonify({"error": "Not authenticated"}), 401
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
password = request.form.get('password') or request.json.get('password')
if password and hash_password(password) == hash_password(config.PASSWORD):
session['authenticated'] = True
session['login_time'] = datetime.now().isoformat()
if request.is_json:
return jsonify({"success": True})
return redirect(url_for('index'))
else:
if request.is_json:
return jsonify({"error": "Invalid password"}), 401
return render_template_string(LOGIN_HTML, error="Invalid password")
return render_template_string(LOGIN_HTML, error=None)
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login'))
# ============================================
# API ENDPOINTS
# ============================================
@app.route('/')
@require_auth
def index():
return render_template_string(MAIN_HTML)
@app.route('/api/status')
@require_auth
def api_status():
"""Get current server status."""
return jsonify({
"status": "online",
"current_llm": state.current_llm_model,
"current_image_preset": state.current_image_preset,
"is_generating": state.is_generating,
"available_llm_models": get_available_llm_models(),
"image_presets": config.IMAGE_PRESETS
})
@app.route('/api/models/llm')
@require_auth
def api_llm_models():
"""List available LLM models."""
models = get_available_llm_models()
return jsonify({"models": models, "current": state.current_llm_model})
@app.route('/api/models/llm/load', methods=['POST'])
@require_auth
def api_load_llm():
"""Load a specific LLM model."""
data = request.json
model_name = data.get('model')
if not model_name:
return jsonify({"error": "No model specified"}), 400
try:
success = load_llm_model(model_name)
if success:
return jsonify({"success": True, "model": model_name})
else:
return jsonify({"error": "Failed to load model"}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/chat', methods=['POST'])
@require_auth
def api_chat():
"""Send a chat message and get streaming response."""
data = request.json
message = data.get('message', '')
if not message:
return jsonify({"error": "No message provided"}), 400
# Add to history
state.chat_history.append({"role": "user", "content": message})
def generate():
try:
response_text = ""
for chunk in chat_stream(message):
response_text += chunk
yield f"data: {json.dumps({'chunk': chunk})}\n\n"
# Add assistant response to history
state.chat_history.append({"role": "assistant", "content": response_text})
yield f"data: {json.dumps({'done': True})}\n\n"
except Exception as e:
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return Response(generate(), mimetype='text/event-stream')
@app.route('/api/chat/clear', methods=['POST'])
@require_auth
def api_clear_chat():
"""Clear chat history."""
state.chat_history = []
if state.vox_api:
try:
state.vox_api.reset_context()
except Exception:
pass
return jsonify({"success": True})
@app.route('/api/image/presets')
@require_auth
def api_image_presets():
"""Get available image generation presets."""
return jsonify({
"presets": config.IMAGE_PRESETS,
"current": state.current_image_preset
})
@app.route('/api/image/preset', methods=['POST'])
@require_auth
def api_set_image_preset():
"""Set image generation preset."""
data = request.json
preset_id = str(data.get('preset', '0'))
if preset_id in config.IMAGE_PRESETS:
state.current_image_preset = preset_id
return jsonify({"success": True, "preset": config.IMAGE_PRESETS[preset_id]})
else:
return jsonify({"error": "Invalid preset"}), 400
@app.route('/api/image/generate', methods=['POST'])
@require_auth
def api_generate_image():
"""Generate an image from prompt."""
if state.is_generating:
return jsonify({"error": "Generation already in progress"}), 429
data = request.json
prompt = data.get('prompt', '')
negative_prompt = data.get('negative_prompt', '')
preset_id = data.get('preset', state.current_image_preset)
if not prompt:
return jsonify({"error": "No prompt provided"}), 400
preset = config.IMAGE_PRESETS.get(str(preset_id), config.IMAGE_PRESETS["0"])
def generate():
state.is_generating = True
try:
yield f"data: {json.dumps({'status': 'starting', 'preset': preset['name']})}\n\n"
result = generate_image(
prompt=prompt,
negative_prompt=negative_prompt,
checkpoint=preset.get('checkpoint'),
**{k: v for k, v in preset.items() if k not in ['name', 'checkpoint']}
)
if result and 'path' in result:
yield f"data: {json.dumps({'status': 'complete', 'image': result['path'], 'filename': result['filename']})}\n\n"
elif result and 'error' in result:
yield f"data: {json.dumps({'status': 'error', 'error': result['error']})}\n\n"
else:
yield f"data: {json.dumps({'status': 'error', 'error': 'Unknown generation failure'})}\n\n"
except Exception as e:
yield f"data: {json.dumps({'status': 'error', 'error': str(e)})}\n\n"
finally:
state.is_generating = False
return Response(generate(), mimetype='text/event-stream')
@app.route('/api/image/output/<filename>')
@require_auth
def api_get_image(filename):
"""Serve generated images."""
image_path = config.OUTPUT_DIR / filename
if image_path.exists():
return send_file(image_path, mimetype='image/png')
return jsonify({"error": "Image not found"}), 404
@app.route('/api/history')
@require_auth
def api_history():
"""Get chat history."""
return jsonify({"history": state.chat_history})
# ============================================
# BACKEND INTEGRATION
# ============================================
def get_available_llm_models():
"""Get list of available GGUF models."""
models = []
if config.MODELS_DIR.exists():
for f in config.MODELS_DIR.glob("*.gguf"):
models.append({
"name": f.stem,
"path": str(f),
"size_gb": f.stat().st_size / (1024**3)
})
return sorted(models, key=lambda x: x['name'])
def load_llm_model(model_name: str) -> bool:
"""Load an LLM model."""
global state
try:
# Find model file
model_path = None
for f in config.MODELS_DIR.glob("*.gguf"):
if f.stem == model_name or model_name in f.name:
model_path = f
break
if not model_path:
print(f"[WebServer] Model not found: {model_name}")
return False
# Unload existing model first
if state.vox_api is not None:
try:
state.vox_api.shutdown()
except Exception:
pass
state.vox_api = None
# Import and initialize VoxAPI with the new model
try:
# Try direct import first (if engine is in path)
from vox_api import VoxAPI
except ImportError:
try:
# Try as submodule
from engine.vox_api import VoxAPI
except ImportError:
print("[WebServer] VoxAPI not available")
print(f"[WebServer] Looked in: {VOX_API_DIR}")
return False
# Create new VoxAPI instance with the model
state.vox_api = VoxAPI(
model_path=str(model_path),
verbose=True
)
state.current_llm_model = model_name
print(f"[WebServer] Loaded model: {model_name}")
return True
except Exception as e:
print(f"[WebServer] Error loading model: {e}")
import traceback
traceback.print_exc()
return False
def chat_stream(message: str):
"""Stream chat response from LLM."""
if state.vox_api is None:
# Try to initialize with first available model
try:
# Try direct import first
try:
from vox_api import VoxAPI
except ImportError:
from engine.vox_api import VoxAPI
models = get_available_llm_models()
if models:
model_path = models[0]['path']
state.vox_api = VoxAPI(
model_path=model_path,
verbose=True
)
state.current_llm_model = models[0]['name']
print(f"[WebServer] Auto-loaded model: {state.current_llm_model}")
else:
yield "Error: No models found in models directory."
return
except ImportError as e:
yield f"Error: VoxAPI not available. Make sure engine/ is set up. ({e})"
return
except Exception as e:
yield f"Error: Could not initialize LLM backend. ({e})"
return
if state.vox_api is None:
yield "Error: Could not initialize LLM backend."
return
try:
for token in state.vox_api.chat(message, stream=True):
yield token
except Exception as e:
yield f"Error: {str(e)}"
def generate_image(prompt: str, negative_prompt: str = "", **kwargs):
"""Generate an image using the image generator."""
try:
print("[WebServer] Request received: generate_image")
# Lazy load image generator
if state.image_generator is None:
print("[WebServer] Lazy loading ImageGenerator...")
try:
from backend.image_generator import ImageGenerator
print("[WebServer] Imported ImageGenerator class.")
state.image_generator = ImageGenerator()
print("[WebServer] Instantiated ImageGenerator.")
except ImportError as e:
print(f"[WebServer] ImageGenerator import failed: {e}")
import traceback
traceback.print_exc()
return {"error": f"Failed to import ImageGenerator: {e}"}
except Exception as e:
print(f"[WebServer] ImageGenerator init failed: {e}")
import traceback
traceback.print_exc()
return {"error": f"Failed to initialize ImageGenerator: {e}"}
# 1. Parse Args to GenerationConfig
# 1. Parse Args to GenerationConfig
# Map web args to config
width = int(kwargs.get('width', 1024))
height = int(kwargs.get('height', 1024))
steps = int(kwargs.get('steps', 20))
cfg_scale = float(kwargs.get('cfg', 7.0))
sampler = kwargs.get('sampler', "euler")
gen_config = GenerationConfig(
prompt=prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
steps=steps,
cfg_scale=cfg_scale,
sampler=sampler
)
# 2. Check/Load Model
checkpoint = kwargs.get('checkpoint')
if checkpoint:
if state.image_generator.current_model != checkpoint:
print(f"[WebServer] Switching model to {checkpoint}")
# We need to find the full path or just pass name if manager handles it
# ImageGenerator.load_model takes model_id (filename)
try:
state.image_generator.load_model(checkpoint)
except Exception as e:
print(f"[WebServer] Model load failed: {e}")
import traceback
traceback.print_exc()
return {"error": f"Failed to load model {checkpoint}: {e}"}
elif not state.image_generator.current_model:
# Try to load a default if nothing loaded
print("[WebServer] No model loaded, trying default...")
# This might fail if user has no models, but better than crash
# 3. Generate
# Use generate_and_save to get a file path
output_path_str = state.image_generator.generate_and_save(gen_config)
if output_path_str:
filename = os.path.basename(output_path_str)
return {
"path": f"/api/image/output/{filename}",
"filename": filename,
"full_path": output_path_str
}
except Exception as e:
import traceback
trace = traceback.format_exc()
print(f"[WebServer] Image generation error: {e}")
print(trace)
return {"error": str(e)}
return {"error": "Unknown error (silent failure)"}
# ============================================
# HTML TEMPLATES
# ============================================
LOGIN_HTML = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VoxAI - Login</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
.login-box {
background: rgba(30, 30, 46, 0.95);
padding: 40px;
border-radius: 16px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 400px;
border: 1px solid rgba(0, 128, 128, 0.3);
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #00b4b4;
font-size: 28px;
}
.logo {
text-align: center;
font-size: 48px;
margin-bottom: 10px;
}
input[type="password"] {
width: 100%;
padding: 14px 16px;
background: #252536;
border: 1px solid #444;
border-radius: 8px;
color: #fff;
font-size: 16px;
margin-bottom: 20px;
}
input:focus {
outline: none;
border-color: #008080;
}
button {
width: 100%;
padding: 14px;
background: linear-gradient(135deg, #008080, #006666);
border: none;
border-radius: 8px;
color: #fff;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 128, 128, 0.4);
}
.error {
background: rgba(255, 82, 82, 0.2);
border: 1px solid #ff5252;
color: #ff8a8a;
padding: 12px;
border-radius: 8px;
margin-bottom: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="login-box">
<div class="logo">🤖</div>
<h1>VoxAI Remote</h1>
{% if error %}
<div class="error">{{ error }}</div>
{% endif %}
<form method="POST">
<input type="password" name="password" placeholder="Enter password..." autofocus required>
<button type="submit">Access VoxAI</button>
</form>
</div>
</body>
</html>
'''
MAIN_HTML = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VoxAI Remote</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg-primary: #1a1a2e;
--bg-secondary: #1e1e2e;
--bg-tertiary: #252536;
--accent: #008080;
--accent-light: #00b4b4;
--text-primary: #e0e0e0;
--text-secondary: #888;
--border: #333;
--user-msg: #006666;
--assistant-msg: #2d2d44;
}
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
display: flex;
flex-direction: column;
}
/* Header */
.header {
background: var(--bg-secondary);
padding: 12px 20px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 100;
}
.header h1 {
font-size: 20px;
color: var(--accent-light);
display: flex;
align-items: center;
gap: 10px;
}
.header-actions {
display: flex;
gap: 10px;
}
.btn {
padding: 8px 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
.btn:hover {
background: var(--accent);
border-color: var(--accent);
}
.btn-primary {
background: var(--accent);
border-color: var(--accent);
}
/* Mode Tabs */
.mode-tabs {
display: flex;
background: var(--bg-secondary);
padding: 0 20px;
border-bottom: 1px solid var(--border);
}
.mode-tab {
padding: 12px 24px;
cursor: pointer;
border-bottom: 2px solid transparent;
color: var(--text-secondary);
transition: all 0.2s;
}
.mode-tab:hover {
color: var(--text-primary);
}
.mode-tab.active {
color: var(--accent-light);
border-bottom-color: var(--accent-light);
}
/* Main Content */
.main-content {
flex: 1;
display: flex;
flex-direction: column;
max-width: 900px;
margin: 0 auto;
width: 100%;
padding: 20px;
}
/* Chat Container */
.chat-container {
flex: 1;
overflow-y: auto;
padding-bottom: 20px;
}
.message {
margin-bottom: 16px;
display: flex;
flex-direction: column;
}
.message.user {
align-items: flex-end;
}
.message-content {
max-width: 80%;
padding: 12px 16px;
border-radius: 12px;
line-height: 1.5;
white-space: pre-wrap;
}
.message.user .message-content {
background: var(--user-msg);
border-bottom-right-radius: 4px;
}
.message.assistant .message-content {
background: var(--assistant-msg);
border-bottom-left-radius: 4px;
}
.message-label {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 4px;
}
/* Input Area */
.input-area {
background: var(--bg-secondary);
padding: 16px;
border-radius: 12px;
border: 1px solid var(--border);
}
.input-row {
display: flex;
gap: 10px;
}
#message-input {
flex: 1;
padding: 16px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-size: 16px;
resize: vertical;
min-height: 80px;
max-height: 300px;
line-height: 1.5;
font-family: inherit;
}
#message-input:focus {
outline: none;
border-color: var(--accent);
}
#send-btn {
padding: 12px 24px;
background: var(--accent);
border: none;
border-radius: 8px;
color: #fff;
font-weight: bold;
cursor: pointer;
transition: all 0.2s;
}
#send-btn:hover {
background: var(--accent-light);
}
#send-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Model Selector */
.model-selector {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border);
}
.model-selector label {
color: var(--text-secondary);
font-size: 13px;
}
.model-selector select {
flex: 1;
padding: 8px 12px;
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text-primary);
font-size: 14px;
}
/* Image Generation */
.image-section {
display: none;
}
.image-section.active {
display: block;
}
.preset-cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 12px;
margin-bottom: 20px;
}
.preset-card {
padding: 16px;
background: var(--bg-tertiary);
border: 2px solid var(--border);
border-radius: 10px;
cursor: pointer;
transition: all 0.2s;
}
.preset-card:hover {
border-color: var(--accent);
}
.preset-card.selected {
border-color: var(--accent-light);
background: rgba(0, 128, 128, 0.1);
}
.preset-card h3 {
margin-bottom: 8px;
color: var(--accent-light);
}
.preset-card p {
font-size: 12px;
color: var(--text-secondary);
}
.image-preview {
margin-top: 20px;
text-align: center;
}
.image-preview img {
max-width: 100%;
max-height: 512px;
border-radius: 8px;
border: 1px solid var(--border);
}
.status-text {
color: var(--accent-light);
margin: 10px 0;
}
/* Modal */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
z-index: 1000;
align-items: center;
justify-content: center;
}
.modal-overlay.active {
display: flex;
}
.modal {
background: var(--bg-secondary);
padding: 24px;
border-radius: 12px;
max-width: 500px;
width: 90%;
border: 1px solid var(--border);
}
.modal h2 {
margin-bottom: 16px;
color: var(--accent-light);
}
.model-list {
max-height: 300px;