File size: 50,664 Bytes
12da16b
 
a9ac993
12da16b
 
 
 
 
 
 
7d1a1c6
12da16b
 
 
 
 
810d769
7d1a1c6
810d769
 
12da16b
ddd798a
 
 
 
 
 
 
 
810d769
ddd798a
 
 
 
 
 
 
 
 
 
 
a9ac993
810d769
ddd798a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810d769
a9ac993
 
 
810d769
a9ac993
12da16b
 
 
 
a9ac993
810d769
12da16b
da6819a
 
a9ac993
810d769
 
 
 
 
 
7d1a1c6
da6819a
 
a9ac993
810d769
 
 
 
a9ac993
12da16b
 
ddd798a
12da16b
a9ac993
 
 
 
12da16b
 
a9ac993
 
 
12da16b
 
 
 
 
 
a9ac993
2aeb5a1
7d1a1c6
810d769
12da16b
 
a9ac993
 
12da16b
810d769
a9ac993
12da16b
a9ac993
810d769
 
 
 
 
 
 
 
 
 
 
 
a9ac993
810d769
 
12da16b
a9ac993
 
b125d48
810d769
 
 
 
 
 
2aeb5a1
810d769
a9ac993
810d769
 
 
a9ac993
12da16b
810d769
 
 
ddd798a
810d769
7d1a1c6
810d769
12da16b
810d769
 
 
12da16b
a9ac993
810d769
 
 
 
a9ac993
810d769
 
 
 
a9ac993
810d769
 
 
12da16b
810d769
 
a9ac993
 
 
810d769
a9ac993
12da16b
810d769
 
 
 
12da16b
a9ac993
810d769
 
 
a9ac993
810d769
a9ac993
810d769
 
 
 
 
 
 
 
 
 
 
7d1a1c6
810d769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d1a1c6
810d769
a9ac993
810d769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d1a1c6
 
 
 
 
 
 
810d769
 
 
 
 
 
 
 
 
 
7d1a1c6
810d769
 
 
 
7d1a1c6
810d769
7d1a1c6
810d769
 
 
 
 
 
 
 
 
 
7d1a1c6
810d769
 
 
 
7d1a1c6
810d769
7d1a1c6
810d769
 
 
7d1a1c6
 
810d769
da6819a
a9ac993
 
810d769
 
a9ac993
810d769
 
 
 
a9ac993
 
810d769
 
 
 
 
a9ac993
810d769
 
 
 
 
 
 
 
 
 
 
 
ddd798a
810d769
77fc15d
 
 
a9ac993
ce2e3bd
810d769
 
 
 
 
ce2e3bd
810d769
 
 
 
 
 
 
 
 
 
 
 
a9ac993
810d769
 
 
 
 
a9ac993
810d769
 
 
 
 
 
a9ac993
810d769
 
a9ac993
810d769
a9ac993
810d769
a9ac993
810d769
a9ac993
810d769
 
 
 
a9ac993
810d769
 
 
 
 
 
ce2e3bd
a9ac993
810d769
a9ac993
810d769
2aeb5a1
810d769
 
 
a9ac993
ddd798a
a9ac993
 
810d769
a9ac993
 
810d769
 
 
 
 
 
a9ac993
 
12da16b
 
810d769
ddd798a
12da16b
810d769
a9ac993
 
 
77fc15d
810d769
12da16b
 
810d769
a9ac993
810d769
 
 
 
a9ac993
 
810d769
a9ac993
810d769
a9ac993
 
810d769
 
a9ac993
810d769
a9ac993
 
21b45a1
810d769
a9ac993
 
2aeb5a1
a9ac993
 
 
810d769
 
21b45a1
a9ac993
810d769
 
a9ac993
 
 
 
810d769
a9ac993
77fc15d
a9ac993
 
 
810d769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12da16b
 
a9ac993
810d769
 
 
a9ac993
810d769
 
 
ddd798a
810d769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ac993
7d1a1c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810d769
 
a9ac993
 
 
810d769
a9ac993
810d769
77fc15d
 
 
810d769
77fc15d
810d769
a9ac993
 
810d769
 
a9ac993
 
810d769
 
77fc15d
810d769
 
ddd798a
a9ac993
810d769
 
 
 
 
 
 
 
 
 
 
 
 
 
12da16b
810d769
12da16b
a9ac993
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
# -- coding: utf-8 --
# --- IMPORT LIBRARY UTAMA & INTI ---

import gradio as gr
import torch
import numpy as np
from diffusers import DiffusionPipeline
import random
import time
import os
from datetime import datetime, timedelta # <-- KESALAHAN SUDAH DIPERBAIKI DI SINI
import csv
import pandas as pd
import threading
from PIL import Image, ImageEnhance
from pathlib import Path
import uuid # Library untuk ID unik chat
import urllib.parse
import json # Library baru untuk menyimpan data share
import string # Library baru untuk generate ID random

# --- LIBRARY BARU UNTUK FITUR UPGRADE ---

try:
    import psutil
    import platform
    from transformers import Swin2SRForImageSuperResolution, Swin2SRImageProcessor
    print("βœ… Library tambahan (psutil, transformers) berhasil diimpor.")
except ImportError:
    print("❌ Peringatan: Library 'psutil' atau 'transformers' tidak ditemukan. Fitur System Monitor & Upscaler tidak akan berfungsi.")
    psutil = None
    platform = None
    Swin2SRForImageSuperResolution = None
    Swin2SRImageProcessor = None

try:
    import google.generativeai as genai
    print("βœ… Library 'google-generativeai' berhasil diimpor.")
except ImportError:
    print("❌ Peringatan: Library 'google-generativeai' tidak ditemukan. Fitur Chatbot & Prompt Enhancer tidak akan berfungsi.")
    genai = None

# --- HEAD HTML & CSS (Tampilan Profesional dengan Upgrade untuk Chat) ---
HEAD_HTML = """
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RenXploit's Creative AI Suite</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fira+Code:wght@500&display=swap" rel="stylesheet">
    <script>
        function typewriterEffect(element, text, speed) {
            let i = 0;
            element.innerHTML = ""; 
            const cursor = document.createElement('span');
            cursor.className = 'typewriter-cursor';
            cursor.innerHTML = '|';
            element.appendChild(cursor);
            function type() {
                if (i < text.length) {
                    element.insertBefore(document.createTextNode(text.charAt(i)), cursor);
                    i++;
                    setTimeout(type, speed);
                } else {
                    cursor.style.animation = 'blink 1s step-end infinite';
                }
            }
            type();
        }

        document.addEventListener("DOMContentLoaded", function(event) {
            const titleElement = document.querySelector('#main-title h1');
            if (titleElement) {
                const titleText = "πŸš€ RenXploit's Creative AI Suite 🌌";
                titleElement.textContent = "";
                setTimeout(() => typewriterEffect(titleElement, titleText, 50), 500);
            }
            
            setInterval(() => {
                const triggerButton = document.querySelector('#system-info-trigger-btn button');
                if (triggerButton) {
                    triggerButton.click();
                }
            }, 5000);
        });
    </script>
    <style>
        :root { --primary-color: #00aaff; --primary-hover-color: #0088cc; --background-color: #0d1117; --content-background-color: #161b22; --border-color: #30363d; --text-color: #c9d1d9; --text-muted-color: #8b949e; --font-family-main: 'Inter', sans-serif; --font-family-mono: 'Fira Code', monospace; --border-radius: 12px; --shadow-light: 0 4px 14px 0 rgba(0, 170, 255, 0.1); --shadow-strong: 0 6px 20px 0 rgba(0, 170, 255, 0.15); }
        body, .gradio-container { font-family: var(--font-family-main); background-color: var(--background-color) !important; color: var(--text-color); }
        h1, h2, h3 { color: #ffffff; font-weight: 600; }
        #main-title h1 { font-size: 2.5em !important; font-weight: 700 !important; text-align: center; padding: 2rem 1rem; color: #ffffff; background: linear-gradient(90deg, #00aaff, #00ffaa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; display: inline-block; }
        #main-title .typewriter-cursor { color: var(--primary-color); font-weight: bold; }
        @keyframes blink { from, to { opacity: 1 } 50% { opacity: 0 } }
        #main-subtitle p { font-size: 1.2em !important; text-align: center; color: var(--text-muted-color); margin-top: -1.5rem !important; margin-bottom: 2rem !important; }
        .gradio-tabs { border: none !important; background-color: transparent !important; margin-bottom: 1.5rem; }
        .gradio-tabs > div[role="tablist"] { display: flex; justify-content: center; flex-wrap: wrap; gap: 10px; border-bottom: 2px solid var(--border-color); padding-bottom: 10px; }
        .gradio-tabs > div[role="tablist"] > button { background-color: transparent !important; color: var(--text-muted-color) !important; border: none !important; border-bottom: 3px solid transparent !important; font-size: 1.1em !important; font-weight: 600 !important; padding: 12px 20px !important; border-radius: 8px 8px 0 0 !important; transition: all 0.3s ease; }
        .gradio-tabs > div[role="tablist"] > button:hover { background-color: var(--content-background-color) !important; color: var(--primary-color) !important; }
        .gradio-tabs > div[role="tablist"] > button.selected { color: var(--primary-color) !important; border-bottom: 3px solid var(--primary-color) !important; background-color: var(--content-background-color) !important; }
        .tabitem { background-color: transparent !important; border: none !important; padding: 0 !important; }
        .gradio-row.panel, .gradio-accordion, .gradio-group { background-color: var(--content-background-color) !important; border: 1px solid var(--border-color) !important; border-radius: var(--border-radius) !important; padding: 24px !important; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .gradio-accordion { margin-top: 1rem; }
        .gradio-button.primary { background: linear-gradient(90deg, var(--primary-color), #00c6ff) !important; color: #ffffff !important; font-weight: 600 !important; font-size: 1.1em !important; border-radius: 8px !important; border: none !important; padding: 12px 24px !important; transition: all 0.3s ease; box-shadow: var(--shadow-light); }
        .gradio-button.primary:hover { transform: translateY(-2px); box-shadow: var(--shadow-strong); }
        .gradio-button.secondary { background-color: var(--content-background-color) !important; border: 1px solid var(--primary-color) !important; color: var(--primary-color) !important; transition: all 0.3s ease; }
        .gradio-button.secondary:hover { background-color: var(--primary-color) !important; color: #ffffff !important; }
        .gradio-textbox, .gradio-number, .gradio-image { background-color: var(--background-color) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px !important; }
        .gradio-textbox textarea, .gradio-number input { color: var(--text-color) !important; }
        .gradio-textbox:focus-within, .gradio-number:focus-within { border-color: var(--primary-color) !important; box-shadow: 0 0 0 2px rgba(0, 170, 255, 0.3); }
        div.info { color: var(--text-muted-color) !important; font-style: italic; }
        #gallery, #history_gallery { border-radius: var(--border-radius) !important; overflow: hidden; border: 1px solid var(--border-color); background-color: #010409; }
        #gallery .gallery-item, #history_gallery .gallery-item { transition: transform 0.3s ease, box-shadow 0.3s ease; }
        #gallery .gallery-item:hover, #history_gallery .gallery-item:hover { transform: scale(1.03); box-shadow: 0 8px 30px rgba(0, 170, 255, 0.3); }
        .loader-container { border: 1px solid var(--border-color); border-radius: var(--border-radius); padding: 30px; background: var(--content-background-color); text-align: center; overflow: hidden; }
        .loader-text { font-family: var(--font-family-mono); font-size: 1.1em; color: var(--primary-color); margin-bottom: 20px; }
        .loader-bar-container { height: 8px; background: var(--background-color); border-radius: 4px; overflow: hidden; }
        .loader-bar { width: 100%; height: 100%; background: linear-gradient(90deg, transparent, var(--primary-color), transparent); background-size: 200% 100%; animation: scan 2s linear infinite; }
        @keyframes scan { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
        #chatbot-container { display: flex; flex-direction: column; height: 70vh; max-height: 750px; }
        #chatbot-display { flex-grow: 1; overflow-y: auto; padding: 10px; border-bottom: 1px solid var(--border-color); }
        #chatbot-display .message { border-radius: 18px !important; padding: 12px 18px !important; box-shadow: none !important; max-width: 80%; }
        #chatbot-display .user { background-color: var(--primary-color) !important; color: white !important; align-self: flex-end; border-bottom-right-radius: 5px !important; }
        #chatbot-display .bot { background-color: var(--content-background-color) !important; border: 1px solid var(--border-color) !important; align-self: flex-start; border-bottom-left-radius: 5px !important; }
        #chat-history-sidebar { background-color: transparent !important; border: none !important; padding: 0 !important; box-shadow: none !important; }
        #chat-history-sidebar .gradio-radio > div { display: flex; flex-direction: column; gap: 8px; }
        #chat-history-sidebar .gradio-radio label { width: 100%; text-align: left; padding: 10px; border: 1px solid var(--border-color); border-radius: 8px; transition: all 0.2s ease; }
        #chat-history-sidebar .gradio-radio input:checked + label { border-color: var(--primary-color); background-color: rgba(0, 170, 255, 0.1); color: var(--primary-color); font-weight: 600; }
        .footer { text-align: center; margin: 2rem auto; padding: 1rem; color: var(--text-muted-color); border-top: 1px solid var(--border-color); }
        .footer b { color: var(--primary-color); }
    </style>
</head>
"""

# --- PENGATURAN & LOGIC GLOBAL ---

VISITOR_LOG_FILE = "visitor_log.csv"
HISTORY_LOG_FILE = "generation_log.csv"
IMAGE_HISTORY_DIR = Path("generated_images")
SHARE_DATA_DIR = Path("shared_data")

file_lock = threading.Lock()
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"➑️ Menggunakan device: {device.upper()}")

# --- Inisialisasi File Log & Direktori ---

def initialize_environment():
    if not os.path.exists(VISITOR_LOG_FILE):
        with file_lock:
            if not os.path.exists(VISITOR_LOG_FILE):
                with open(VISITOR_LOG_FILE, mode='w', newline='', encoding='utf-8') as f:
                    writer = csv.writer(f)
                    writer.writerow(["Timestamp", "IP Address", "User Agent"])
                print(f"βœ… File log '{VISITOR_LOG_FILE}' berhasil dibuat.")

    IMAGE_HISTORY_DIR.mkdir(exist_ok=True)
    SHARE_DATA_DIR.mkdir(exist_ok=True) 
    if not os.path.exists(HISTORY_LOG_FILE):
        with file_lock:
            if not os.path.exists(HISTORY_LOG_FILE):
                with open(HISTORY_LOG_FILE, mode='w', newline='', encoding='utf-8') as f:
                    writer = csv.writer(f)
                    writer.writerow(["Timestamp", "Filename", "Prompt", "NegativePrompt", "Seed", "Steps"])
                print(f"βœ… File log riwayat '{HISTORY_LOG_FILE}' dan direktori '{IMAGE_HISTORY_DIR}' siap.")

initialize_environment()

# --- PEMUATAN MODEL-MODEL AI ---
print("➑️ Memuat model SDXL-Turbo...")
pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/sdxl-turbo", torch_dtype=torch.float16 if device == "cuda" else torch.float32,
    variant="fp16" if device == "cuda" else None, use_safetensors=True
).to(device)
if torch.cuda.is_available(): pipe.enable_xformers_memory_efficient_attention()
print("βœ… Model SDXL-Turbo berhasil dimuat.")

upscaler_model = None
upscaler_processor = None
if Swin2SRForImageSuperResolution:
    try:
        print("➑️ Memuat model AI Upscaler (Swin2SR)...")
        upscaler_model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2sr-realworld-sr-x4-64-bsrgan-psnr").to(device)
        upscaler_processor = Swin2SRImageProcessor.from_pretrained("caidas/swin2sr-realworld-sr-x4-64-bsrgan-psnr")
        print("βœ… Model AI Upscaler berhasil dimuat.")
    except Exception as e:
        print(f"❌ Gagal memuat model Upscaler: {e}. Fitur upscale akan dinaktifkan.")

# --- KELAS UNTUK CHATBOT GEMINI ---
class GeminiChat:
    def __init__(self):
        self.api_keys = []
        self.is_configured = False
        if not genai: return

        i = 1
        while True:
            key = os.getenv(f"GEMINI_API_KEY_{i}")
            if key:
                self.api_keys.append(key)
                i += 1
            else:
                break
        
        if self.api_keys:
            print(f"βœ… Berhasil memuat {len(self.api_keys)} API Key Gemini. Sistem rotasi aktif.")
            self.is_configured = True
        else:
            print("❌ PERINGATAN: Tidak ada API Key Gemini yang ditemukan. Fitur AI Chat & Prompt Enhancer tidak akan berfungsi.")

    def chat(self, message, history, system_prompt=None):
        if not self.is_configured:
            return "Maaf, fitur ini tidak terkonfigurasi karena tidak ada API Key."
        try:
            selected_key = random.choice(self.api_keys)
            genai.configure(api_key=selected_key)
            model = genai.GenerativeModel('gemini-2.5-flash')
            
            chat_history_for_api = []
            for user_msg, model_msg in history:
                if user_msg: chat_history_for_api.append({"role": "user", "parts": [user_msg]})
                if model_msg: chat_history_for_api.append({"role": "model", "parts": [model_msg]})
            
            chat_session = model.start_chat(history=chat_history_for_api)
            
            full_prompt = message
            if system_prompt and not history:
                full_prompt = f"{system_prompt}\n\nUser query: {message}"
                
            response = chat_session.send_message(full_prompt)
            return response.text
        except Exception as e:
            print(f"❌ Terjadi error pada API Key Gemini: {e}")
            return "Terjadi kesalahan saat menghubungi API AI. Mungkin salah satu API Key tidak valid atau ada masalah jaringan. Silakan coba lagi."

gemini_bot = GeminiChat()

# --- FUNGSI-FUNGSI INTI (GENERATOR & LAINNYA) ---
def log_visitor(request: gr.Request):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    ip_address = request.client.host if request else "N/A"
    user_agent = request.headers.get("user-agent", "Unknown") if request else "N/A"
    with file_lock:
        with open(VISITOR_LOG_FILE, mode='a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow([timestamp, ip_address, user_agent])
    print(f"βœ… Pengunjung baru tercatat: IP {ip_address}")

def generate_images(prompt, negative_prompt, steps, seed, num_images):
    if not prompt:
        raise gr.Error("Prompt tidak boleh kosong!")
    if seed == -1:
        seed = random.randint(0, 2**32 - 1)
    generator = torch.manual_seed(seed)
    images = pipe(prompt=prompt, negative_prompt=negative_prompt, generator=generator, num_inference_steps=steps, guidance_scale=0.0, num_images_per_prompt=num_images).images
    return images, seed

def genie_wrapper(prompt, negative_prompt, steps, seed, num_images):
    yield gr.update(visible=False), gr.update(visible=True, value="<div class='loader-container'><div class='loader-text'>AI sedang melukis mahakarya Anda...</div><div class='loader-bar-container'><div class='loader-bar'></div></div></div>"), gr.update(interactive=False), gr.update(visible=False)

    start_time = time.time()
    images, used_seed = generate_images(prompt, negative_prompt, int(steps), int(seed), int(num_images))
    end_time = time.time()

    timestamp_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for i, img in enumerate(images):
        filename = f"{int(time.time())}_{used_seed}_{i}.png"
        filepath = IMAGE_HISTORY_DIR / filename
        img.save(filepath)
        
        with file_lock:
            with open(HISTORY_LOG_FILE, mode='a', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerow([timestamp_str, filename, prompt, negative_prompt, used_seed, int(steps)])

    generation_time = end_time - start_time
    info_text = f"Seed yang digunakan: {used_seed}\nTotal waktu generasi: {generation_time:.2f} detik"
    yield gr.update(value=images, visible=True), gr.update(visible=False), gr.update(interactive=True), gr.update(value=info_text, visible=True)

def submit_report(name, email, message):
    if not name or not message:
        gr.Warning("Nama dan Pesan tidak boleh kosong!")
        return gr.update(visible=False)
    report_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    report_content = f"--- Laporan Baru ({report_time}) ---\nNama: {name}\nEmail: {email}\nPesan: {message}\n\n"
    with open("reports.log", "a", encoding="utf-8") as f:
        f.write(report_content)
    print("βœ… Laporan baru telah disimpan ke reports.log")
    return gr.update(value="βœ… Terima kasih! Laporan Anda telah kami terima.", visible=True)

# --- FUNGSI VISITOR MONITOR ---
def update_visitor_monitor(time_filter: str):
    try:
        with file_lock:
            if not os.path.exists(VISITOR_LOG_FILE) or os.path.getsize(VISITOR_LOG_FILE) == 0:
                return "## πŸ“ˆ 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
            
            column_names = ["Timestamp", "IP Address", "User Agent"]
            df = pd.read_csv(VISITOR_LOG_FILE, header=None, names=column_names)

            if not df.empty and df.iloc[0]['Timestamp'] == 'Timestamp':
                df = df.iloc[1:].reset_index(drop=True)
        
        if df.empty: return "## πŸ“ˆ 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
        
        df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
        df.dropna(subset=['Timestamp'], inplace=True)
        if df.empty: return "## πŸ“ˆ 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})

        total_overall_visitors = len(df)
        total_visitors_formatted = f"## πŸ“ˆ {total_overall_visitors:,}"
        df['Total Pengunjung'] = np.arange(1, len(df) + 1)
        
        now = datetime.now()

        if time_filter == "1 Minggu Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(weeks=1)]
        elif time_filter == "2 Minggu Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(weeks=2)]
        elif time_filter == "3 Bulan Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(days=90)]
        else: df_plot = df
        
        if df_plot.empty: return total_visitors_formatted, pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
        
        return total_visitors_formatted, df_plot
    except Exception as e:
        error_message = f"Error saat memperbarui monitor: {e}"
        print(f"❌ {error_message}")
        return f"## ⚠️ Error: {e}", pd.DataFrame({"Error": [error_message]})

# --- FUNGSI-FUNGSI FITUR BARU ---
def enhance_prompt(simple_prompt):
    if not simple_prompt:
        gr.Warning("Tolong masukkan ide Anda terlebih dahulu.")
        return ""
    if not gemini_bot.is_configured:
        gr.Error("Fitur Prompt Enhancer tidak aktif karena API Key Gemini tidak diatur.")
        return "Fitur tidak aktif."
    
    system_instruction = (
        "Anda adalah seorang ahli prompt engineering untuk model AI text-to-image seperti Stable Diffusion. "
        "Tugas Anda adalah mengubah ide sederhana dari pengguna menjadi prompt yang kaya, deskriptif, dan artistik. "
        "Fokus pada detail visual: subjek, setting, pencahayaan, gaya seni, komposisi, dan kualitas. "
        "Hasilkan HANYA prompt-nya saja dalam format teks panjang, tanpa penjelasan atau kalimat pembuka/penutup."
    )
    yield "🧠 AI sedang meracik prompt ajaib untuk Anda..."
    enhanced_prompt = gemini_bot.chat(simple_prompt, [], system_prompt=system_instruction)
    yield enhanced_prompt

def upscale_image(image_to_upscale, clarity_strength):
    if image_to_upscale is None: raise gr.Error("Silakan unggah gambar terlebih dahulu.")
    if upscaler_model is None or upscaler_processor is None: raise gr.Error("Fitur Upscaler tidak aktif karena model gagal dimuat.")
    
    yield None, "πŸš€ Memproses peningkatan resolusi 4x oleh AI..."
    try:
        with torch.no_grad():
            inputs = upscaler_processor(image_to_upscale, return_tensors="pt").to(device)
            outputs = upscaler_model(**inputs)
            output_image = outputs.reconstruction.data.squeeze().float().cpu().clamp_(0, 1).numpy()
            output_image = np.moveaxis(output_image, source=0, destination=-1)
            output_image = (output_image * 255.0).round().astype(np.uint8)
            final_image = Image.fromarray(output_image)
        
        if clarity_strength > 1.0:
            yield final_image, f"✨ Menerapkan peningkatan kejernihan (Strength: {clarity_strength:.2f})..."
            enhancer = ImageEnhance.Sharpness(final_image)
            final_image = enhancer.enhance(clarity_strength)

        yield final_image, f"βœ… Gambar berhasil ditingkatkan! Resolusi akhir: {final_image.width}x{final_image.height}px."
    except Exception as e:
        print(f"❌ Error saat upscaling: {e}")
        yield None, f"⚠️ Terjadi error saat upscaling: {e}"

def update_system_info():
    if not psutil or not platform: return "Informasi sistem tidak tersedia (library psutil tidak ditemukan)."
    cpu_percent = psutil.cpu_percent(interval=None)
    ram = psutil.virtual_memory()
    gpu_info = "Tidak terdeteksi (PyTorch tidak menemukan CUDA)"
    if torch.cuda.is_available():
        gpu_name = torch.cuda.get_device_name(0)
        gpu_mem_used_gb = torch.cuda.memory_allocated(0) / (1024**3)
        gpu_mem_total_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
        gpu_info = f"GPU: {gpu_name}\nVRAM Terpakai: {gpu_mem_used_gb:.2f} GB / {gpu_mem_total_gb:.2f} GB"

    sys_info = f"**Platform:** `{platform.system()} {platform.release()}`"
    return (f"**CPU Terpakai:** `{cpu_percent:.1f}%`\n"
            f"**RAM Terpakai:** `{ram.percent:.1f}% ({ram.used / (1024**3):.2f} GB / {ram.total / (1024**3):.2f} GB)`\n"
            f"{gpu_info}\n---\n{sys_info}")

# --- FUNGSI-FUNGSI UNTUK MENU BARU & FITUR SHARE (DIPERBAIKI TOTAL) ---

def generate_random_id(length=10):
    """Menghasilkan ID acak dari huruf dan angka."""
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))

def share_image_history(selected_index: int, history_df: pd.DataFrame, request: gr.Request):
    """Membuat URL share untuk detail gambar."""
    if selected_index is None or history_df.empty:
        gr.Warning("Pilih gambar terlebih dahulu sebelum membagikan.")
        return gr.update(visible=False)

    try:
        selected_row = history_df.iloc[selected_index]
        base_url = "https://floodd-ai2.hf.space/" 

        share_data = {
            'prompt': selected_row['Prompt'],
            'neg': selected_row.get('NegativePrompt', ''),
            'seed': int(selected_row['Seed']),
            'steps': int(selected_row['Steps'])
        }
        
        share_id = generate_random_id()
        with open(SHARE_DATA_DIR / f"image_{share_id}.json", 'w') as f:
            json.dump(share_data, f)
            
        share_url = f"{base_url}?share_image_id={share_id}"
        
        share_content = f"βœ… **URL Share Berhasil Dibuat!**\nBagikan link ini untuk mengisi ulang generator:\n\n`{share_url}`"
        return gr.update(value=share_content, visible=True)

    except Exception as e:
        print(f"❌ Error saat membuat URL share gambar: {e}")
        return gr.update(value=f"⚠️ Gagal membuat URL: {e}", visible=True)


def share_chat_history(chat_id, all_chats_history, request: gr.Request):
    """Membuat URL share untuk riwayat obrolan."""
    if not chat_id or chat_id not in all_chats_history:
        gr.Warning("Pilih obrolan yang valid untuk dibagikan.")
        return gr.update(visible=False)

    try:
        chat_to_share = all_chats_history[chat_id]
        if not chat_to_share.get('history'):
            gr.Warning("Obrolan ini kosong dan tidak bisa dibagikan.")
            return gr.update(visible=False)
            
        base_url = "https://floodd-ai2.hf.space/" 

        with open(SHARE_DATA_DIR / f"chat_{chat_id}.json", 'w') as f:
            json.dump(chat_to_share, f)
            
        share_url = f"{base_url}?share_chat_id={chat_id}"
        
        share_content = f"βœ… **URL Share Berhasil Dibuat!**\nBagikan link ini untuk melihat obrolan:\n\n`{share_url}`"
        return gr.update(value=share_content, visible=True)
    except Exception as e:
        print(f"❌ Error saat membuat URL share chat: {e}")
        return gr.update(value=f"⚠️ Gagal membuat URL: {e}", visible=True)
        
def handle_shared_url(request: gr.Request):
    """Fungsi ini berjalan saat aplikasi dimuat untuk memeriksa parameter URL."""
    # Mengembalikan tuple dengan panjang yang konsisten untuk semua return path
    default_chat_return = (gr.State.IDENTITY, None, [], gr.update(), gr.update())
    default_image_return = (gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY, gr.update())

    if not request:
        return default_chat_return, default_image_return

    params = request.query_params
    
    if 'share_chat_id' in params:
        chat_id = params['share_chat_id']
        filepath = SHARE_DATA_DIR / f"chat_{chat_id}.json"
        if filepath.exists():
            print(f"βœ… Memuat chat dari URL share: {chat_id}")
            with open(filepath, 'r') as f:
                shared_chat_data = json.load(f)
            initial_chat_state = {chat_id: shared_chat_data}
            chat_return = (
                initial_chat_state, 
                chat_id, 
                shared_chat_data.get('history', []), 
                gr.update(choices=[shared_chat_data.get('title', 'Obrolan Dibagikan')], value=shared_chat_data.get('title', 'Obrolan Dibagikan')),
                gr.Tabs(selected=1)
            )
            return chat_return, default_image_return
        else:
            print(f"⚠️ ID share chat tidak ditemukan: {chat_id}")

    elif 'share_image_id' in params:
        image_id = params['share_image_id']
        filepath = SHARE_DATA_DIR / f"image_{image_id}.json"
        if filepath.exists():
            print(f"βœ… Memuat detail gambar dari URL share: {image_id}")
            with open(filepath, 'r') as f:
                shared_image_data = json.load(f)
            image_return = (
                shared_image_data.get('prompt', ''),
                shared_image_data.get('neg', ''),
                shared_image_data.get('seed', -1),
                shared_image_data.get('steps', 2),
                gr.Tabs(selected=0)
            )
            return default_chat_return, image_return
        else:
            print(f"⚠️ ID share gambar tidak ditemukan: {image_id}")

    return default_chat_return, default_image_return


def load_history():
    try:
        with file_lock:
            if not os.path.exists(HISTORY_LOG_FILE):
                return [], pd.DataFrame(), "### πŸ“‚ Riwayat Kosong\nBelum ada gambar yang dihasilkan."
            df = pd.read_csv(HISTORY_LOG_FILE)

        if df.empty:
            return [], df, "### πŸ“‚ Riwayat Kosong\nBelum ada gambar yang dihasilkan."

        df_sorted = df.sort_values(by="Timestamp", ascending=False)
        image_paths = [str(IMAGE_HISTORY_DIR / fname) for fname in df_sorted['Filename'] if (IMAGE_HISTORY_DIR / fname).exists()]
        return image_paths, df_sorted, "### β“˜ Detail Gambar\nKlik pada sebuah gambar untuk melihat detailnya."
    except Exception as e:
        print(f"❌ Error memuat riwayat: {e}")
        return [], pd.DataFrame(), f"### ⚠️ Error\nTidak dapat memuat riwayat: {e}"

def show_history_details(evt: gr.SelectData, history_df: pd.DataFrame):
    if not evt.selected or history_df.empty:
        return "### β“˜ Detail Gambar\nKlik gambar untuk melihat detailnya.", gr.update(visible=False), gr.update(visible=False), None

    selected_index = evt.index
    selected_row = history_df.iloc[selected_index]
    details = f"""
    **Prompt:** `{selected_row['Prompt']}`
    **Negative Prompt:** `{selected_row.get('NegativePrompt', 'N/A')}`
    ---
    **Seed:** `{selected_row['Seed']}` | **Steps:** `{selected_row['Steps']}`
    **File:** `{selected_row['Filename']}` | **Dibuat:** `{selected_row['Timestamp']}`
    """
    return details, gr.update(visible=True), gr.update(visible=False), selected_index

def send_history_to_generator(selected_index: int, history_df: pd.DataFrame):
    if selected_index is None or history_df.empty: return gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
    selected_row = history_df.iloc[selected_index]
    return ( selected_row['Prompt'], selected_row.get('NegativePrompt', ''), selected_row['Seed'], selected_row['Steps'], gr.Tabs(selected=0) )

def send_history_to_editor(selected_index: int, history_df: pd.DataFrame):
    if selected_index is None or history_df.empty: return gr.update(), gr.update()
    selected_row = history_df.iloc[selected_index]
    image_path = str(IMAGE_HISTORY_DIR / selected_row['Filename'])
    return Image.open(image_path), gr.Tabs(selected=5)

def apply_image_edits(image, brightness, contrast, saturation, sharpness, filter_choice):
    if image is None: return None
    output_image = image.copy()
    if filter_choice == "Grayscale": output_image = output_image.convert("L").convert("RGB")
    elif filter_choice == "Sepia":
        pixels = output_image.load()
        width, height = output_image.size
        for y in range(height):
            for x in range(width):
                r, g, b = output_image.getpixel((x, y))
                tr, tg, tb = int(0.393*r + 0.769*g + 0.189*b), int(0.349*r + 0.686*g + 0.168*b), int(0.272*r + 0.534*g + 0.131*b)
                pixels[x, y] = (min(255, tr), min(255, tg), min(255, tb))
    
    enhancer = ImageEnhance.Brightness(output_image); output_image = enhancer.enhance(brightness)
    enhancer = ImageEnhance.Contrast(output_image); output_image = enhancer.enhance(contrast)
    enhancer = ImageEnhance.Color(output_image); output_image = enhancer.enhance(saturation)
    enhancer = ImageEnhance.Sharpness(output_image); output_image = enhancer.enhance(sharpness)
    return output_image
    
# --- FUNGSI LOGIC CHATBOT BARU ---
def add_new_chat(all_chats_history):
    new_chat_id = str(uuid.uuid4())
    all_chats_history[new_chat_id] = {
        "title": "Percakapan Baru",
        "history": [(None, "Halo! Saya Flood, asisten AI dari RenXploit. Ada yang bisa saya bantu?")]
    }
    history_titles = [info['title'] for info in all_chats_history.values()]
    new_title = all_chats_history[new_chat_id]['title']
    
    return all_chats_history, new_chat_id, all_chats_history[new_chat_id]['history'], gr.update(choices=history_titles, value=new_title)

def handle_user_message(user_message, chat_id, all_chats_history):
    if not chat_id or chat_id not in all_chats_history:
        all_chats_history, chat_id, current_history, _ = add_new_chat({})
    
    current_history = all_chats_history[chat_id]['history']
    
    if len(current_history) == 1 and current_history[0][0] is None:
        current_history = []
        
    current_history.append((user_message, None))
    all_chats_history[chat_id]['history'] = current_history
    
    if len(current_history) == 1:
        new_title = user_message[:30] + '...' if len(user_message) > 30 else user_message
        all_chats_history[chat_id]['title'] = new_title
    
    history_titles = [info['title'] for info in all_chats_history.values()]
    
    yield all_chats_history, current_history, gr.update(choices=history_titles, value=all_chats_history[chat_id]['title']), gr.update(value=""), gr.update(visible=False)

    bot_response = gemini_bot.chat(user_message, [h for h in current_history if h[0] is not None])
    current_history[-1] = (user_message, bot_response)
    all_chats_history[chat_id]['history'] = current_history
    
    yield all_chats_history, current_history, gr.update(), gr.update(), gr.update(visible=True)

def switch_chat(selected_title, all_chats_history):
    if not selected_title: return None, [], gr.update(visible=False)
    
    selected_id = None
    for chat_id, info in all_chats_history.items():
        if info['title'] == selected_title:
            selected_id = chat_id
            break
            
    if selected_id:
        return selected_id, all_chats_history[selected_id]['history'], gr.update(visible=True)
    return None, [], gr.update(visible=False)
    

# --- ANTARMUKA PENGGUNA (GRADIO UI) ---

with gr.Blocks(theme=gr.themes.Base(), head=HEAD_HTML) as demo:
    gr.Markdown("# πŸš€ RenXploit's Creative AI Suite 🌌", elem_id="main-title")
    gr.Markdown("Sebuah platform lengkap untuk kreativitas Anda, ditenagai oleh AI.", elem_id="main-subtitle")

    chat_history_state = gr.State({})
    current_chat_id_state = gr.State(None)
    selected_history_index_state = gr.State(None)
    
    with gr.Tabs() as tabs:
        with gr.TabItem("🎨 Image Generator", id=0):
            with gr.Row(variant='panel', equal_height=False):
                with gr.Column(scale=1):
                    gr.Markdown("### πŸ“ **Masukan Perintah Anda**")
                    prompt_input = gr.Textbox(label="Prompt", placeholder="Contoh: Cinematic photo, seekor rubah merah...", lines=3, info="Jadilah sangat spesifik! Atau gunakan Prompt Enhancer.")
                    negative_prompt_input = gr.Textbox(label="Prompt Negatif", placeholder="Contoh: blurry, low quality, bad hands...", lines=2, info="Hal-hal yang TIDAK Anda inginkan.")
                    num_images_slider = gr.Slider(minimum=1, maximum=8, value=2, step=1, label="Jumlah Gambar")
                    generate_btn = gr.Button("✨ Hasilkan Gambar!", variant="primary")
                    with gr.Accordion("βš™οΈ Opsi Lanjutan", open=False):
                        steps_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Langkah Iterasi (Kualitas vs Kecepatan)")
                        with gr.Row():
                            seed_input = gr.Number(label="Seed", value=-1, precision=0, info="Gunakan -1 untuk acak.")
                            random_seed_btn = gr.Button("🎲 Acak", variant="secondary")
                with gr.Column(scale=2):
                    gr.Markdown("### πŸ–ΌοΈ **Hasil Generasi**")
                    output_gallery = gr.Gallery(label="Hasil Gambar", show_label=False, elem_id="gallery", columns=2, object_fit="contain", height="auto")
                    loader_html = gr.HTML(visible=False)
                    info_box = gr.Textbox(label="Informasi Generasi", visible=False, interactive=False, lines=2)
        
        with gr.TabItem("πŸ’¬ Chat with AI", id=1):
            with gr.Row(variant='panel'):
                with gr.Column(scale=1, min_width=250) as sidebar:
                    gr.Markdown("### πŸ—‚οΈ Riwayat Chat")
                    new_chat_btn = gr.Button("βž• Obrolan Baru", variant="primary")
                    with gr.Group(elem_id="chat-history-sidebar"):
                        chat_history_list = gr.Radio(label="Pilih Obrolan", choices=[], interactive=True)
                    with gr.Row(visible=False) as chat_action_buttons:
                         share_chat_btn = gr.Button("πŸ”— Bagikan Chat")
                    share_chat_output = gr.Textbox(label="URL untuk Dibagikan", lines=4, interactive=True, show_copy_button=True, visible=False)

                with gr.Column(scale=3):
                    gr.Markdown("### πŸ€– **Asisten AI Flood**")
                    if not gemini_bot.is_configured:
                        gr.Warning("Fitur Chatbot dinonaktifkan. API Key Gemini tidak terkonfigurasi.")
                    else:
                        with gr.Column(elem_id="chatbot-container"):
                            chatbot_display = gr.Chatbot(elem_id="chatbot-display", label="Flood AI", bubble_full_width=False)
                            with gr.Row():
                                user_chat_input = gr.Textbox(show_label=False, placeholder="Ketik pesan Anda di sini...", scale=5)
                                send_chat_btn = gr.Button("Kirim", variant="secondary", scale=1)
        
        with gr.TabItem("✨ Prompt Enhancer", id=2):
            with gr.Row(variant='panel'):
                with gr.Column():
                    gr.Markdown("### πŸͺ„ **Ubah Ide Jadi Prompt Ajaib**\nCukup tulis ide sederhana, dan biarkan AI menyempurnakannya menjadi prompt yang detail dan artistik.")
                    simple_prompt_input = gr.Textbox(label="Ide Sederhana Anda", placeholder="Contoh: seekor astronot di hutan alien", lines=3)
                    enhance_btn = gr.Button("Buat Prompt Ajaib!", variant="primary")
                    enhanced_prompt_output = gr.Textbox(label="Prompt yang Disempurnakan", lines=5, interactive=True, show_copy_button=True)
                    send_to_gen_btn = gr.Button("➑️ Kirim & Pindah ke Generator")

        with gr.TabItem("πŸš€ AI Image Upscaler", id=3):
            with gr.Row(variant='panel', equal_height=False):
                with gr.Column():
                    gr.Markdown("### **Tingkatkan Resolusi Gambar**\nUnggah gambar untuk meningkatkan kualitas dan ukurannya hingga 4x lipat menggunakan AI.")
                    image_to_upscale_input = gr.Image(type="pil", label="Unggah Gambar Anda di Sini")
                    clarity_slider = gr.Slider(minimum=1.0, maximum=3.0, value=1.0, step=0.1, label="Tingkat Peningkatan Kejernihan", info="Setelah di-upscale 4x, atur kejernihan gambar di sini. 1.0 = Tanpa efek.")
                    upscale_btn = gr.Button("Tingkatkan Resolusi!", variant="primary")
                with gr.Column():
                    gr.Markdown("### **Hasil Peningkatan Resolusi**")
                    upscaled_image_output = gr.Image(label="Gambar Hasil Upscale", interactive=False, show_download_button=True)
                    upscale_status_text = gr.Markdown("Status: Menunggu gambar...")

        with gr.TabItem("πŸ–ΌοΈ Galeri & Riwayat", id=4) as history_tab:
            with gr.Row(variant='panel'):
                with gr.Column(scale=2):
                    gr.Markdown("### **Galeri Hasil Generasi Anda**")
                    history_gallery = gr.Gallery(label="Riwayat Gambar", show_label=False, columns=4, object_fit="contain", height="auto", elem_id="history_gallery")
                    history_df_state = gr.State()
                with gr.Column(scale=1):
                    gr.Markdown("### **Detail & Aksi**")
                    history_details_md = gr.Markdown("### β“˜ Detail Gambar\nKlik pada sebuah gambar untuk melihat detailnya.")
                    refresh_history_btn = gr.Button("πŸ”„ Segarkan Galeri", variant="secondary")
                    with gr.Row(visible=False) as history_action_buttons:
                        history_to_gen_btn = gr.Button("Kirim ke Generator")
                        history_to_editor_btn = gr.Button("Kirim ke Editor")
                        share_history_btn = gr.Button("πŸ”— Bagikan Detail")
                    share_history_output = gr.Textbox(label="URL untuk Dibagikan", lines=4, interactive=True, show_copy_button=True, visible=False)

        with gr.TabItem("🎨 Image Editor", id=5):
            with gr.Row(variant='panel'):
                with gr.Column(scale=1):
                    gr.Markdown("### **Toolkit Pasca-Produksi**")
                    editor_input_image = gr.Image(type="pil", label="Unggah Gambar atau Kirim dari Riwayat")
                    with gr.Accordion("Penyesuaian", open=True):
                        brightness_slider = gr.Slider(minimum=0.5, maximum=1.5, value=1.0, step=0.05, label="Kecerahan")
                        contrast_slider = gr.Slider(minimum=0.5, maximum=1.5, value=1.0, step=0.05, label="Kontras")
                        saturation_slider = gr.Slider(minimum=0.0, maximum=2.0, value=1.0, step=0.05, label="Saturasi Warna")
                        sharpness_slider = gr.Slider(minimum=0.0, maximum=3.0, value=1.0, step=0.1, label="Ketajaman")
                    with gr.Accordion("Filter Cepat", open=True):
                         filter_radio = gr.Radio(["None", "Grayscale", "Sepia"], label="Pilih Filter", value="None")
                with gr.Column(scale=1):
                    gr.Markdown("### **Hasil Editing**")
                    editor_output_image = gr.Image(label="Hasil Akhir", interactive=False, show_download_button=True)

        with gr.TabItem("πŸ“Š Visitor Monitor", id=6):
            with gr.Row(variant='panel'):
                with gr.Column():
                    gr.Markdown("### πŸ“ˆ **Live Visitor Monitor**\nPantau jumlah total pengunjung aplikasi Anda secara real-time.")
                    with gr.Row():
                        with gr.Column(scale=3): visitor_count_display = gr.Markdown("## πŸ“ˆ Memuat data...")
                        with gr.Column(scale=2):
                            time_filter_radio = gr.Radio(["Semua Waktu", "1 Minggu Terakhir", "2 Minggu Terakhir", "3 Bulan Terakhir"], label="Tampilkan data untuk", value="Semua Waktu")
                            refresh_btn = gr.Button("πŸ”„ Segarkan Manual", variant="secondary")
                    visitor_plot = gr.LinePlot(x="Timestamp", y="Total Pengunjung", title="Grafik Pertumbuhan Pengunjung", tooltip=['Timestamp', 'Total Pengunjung'], height=500, interactive=True)

        with gr.TabItem("βš™οΈ System & Settings", id=7):
            with gr.Row(variant='panel'):
                with gr.Column():
                    gr.Markdown("### **Live System Monitor**")
                    system_info_md = gr.Markdown("Memuat info sistem...")
                    system_info_trigger_btn = gr.Button("Trigger System Info", visible=False, elem_id="system-info-trigger-btn")
                with gr.Column():
                    gr.Markdown("### **Pengaturan Aplikasi**")
                    with gr.Accordion("Kualitas Model", open=True):
                        gr.Radio(["FP16 (Cepat, Kualitas Baik)", "FP32 (Lambat, Kualitas Terbaik)"], 
                                 value="FP16 (Cepat, Kualitas Baik)" if device == "cuda" else "FP32 (Lambat, Kualitas Terbaik)",
                                 label="Presisi Model Generator", interactive=False, info="Terkunci. Ditentukan saat aplikasi dimulai.")

        with gr.TabItem("πŸ’‘ Panduan Prompting", id=8):
            with gr.Row(variant='panel'): gr.Markdown("""## Cara Menjadi "Art Director" yang Hebat untuk AI...\n (Konten panduan Anda di sini)""")
        with gr.TabItem("πŸ“– Blog & Updates", id=9):
            with gr.Row(variant='panel'): gr.Markdown("""### Perkembangan Terbaru dari RenXploit's AI Suite
v3.1 (Perbaikan Share URL): Mengimplementasikan sistem share berbasis URL Query Parameter yang fungsional. Kini URL share untuk chat dan gambar dapat dibuka dan menampilkan konten yang sesuai.
v3.0 (Perbaikan Kritis): Memperbaiki bug pada fitur Share URL dan Share Detail Galeri yang disebabkan oleh perbedaan versi Gradio dan logika event yang salah.
v2.8: Mengganti komponen `gr.Box` dengan `gr.Group` untuk kompatibilitas.
v2.7: Perombakan total UI Chatbot dengan fitur riwayat, new chat, dan share.""")
        with gr.TabItem("ℹ️ About & Support", id=10):
            with gr.Row(variant='panel'):
                with gr.Column():
                    gr.Markdown("### Tentang Proyek dan Dukungan")
                    with gr.Accordion("Tentang RenXploit's Creative AI Suite", open=True):
                        gr.Markdown("""
                        RenXploit's Creative AI Suite adalah proyek pribadi untuk mengeksplorasi AI generatif.
                        Hubungi saya melalui: ngoprek.xyz/contact
                        """)
                    with gr.Accordion("Laporkan Masalah atau Beri Masukan"):
                        report_name = gr.Textbox(label="Nama Anda")
                        report_email = gr.Textbox(label="Email Anda (Opsional)")
                        report_message = gr.Textbox(label="Pesan Anda", lines=5, placeholder="Jelaskan masalah atau ide Anda...")
                        report_btn = gr.Button("Kirim Laporan", variant="primary")
                        report_status = gr.Markdown(visible=False)

    gr.Markdown("---\n<div class='footer'><p>Dibuat dengan ❀️ oleh <b>RenXploit</b>.</p></div>", elem_classes="footer")

    # --- PENANGANAN EVENT (EVENT HANDLERS DENGAN PERBAIKAN) ---
    
    # Kumpulan output untuk URL handler
    shared_chat_outputs = [chat_history_state, current_chat_id_state, chatbot_display, chat_history_list, tabs]
    shared_image_outputs = [prompt_input, negative_prompt_input, seed_input, steps_slider, tabs]

    @demo.load
    def process_url_and_init(request: gr.Request, current_chat_state):
        chat_return, image_return = handle_shared_url(request)

        # Cek apakah URL share chat diproses
        if chat_return[1] is not None: # Cek chat_id
            # Nilai-nilai ini akan mengisi komponen chat
            return chat_return + (gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY, gr.update())
        
        # Cek apakah URL share image diproses
        elif image_return[0] != gr.State.IDENTITY: # Cek prompt
            # Jika tidak ada share chat, inisialisasi chat default
            new_chat_state, new_chat_id, new_history, chat_list_update = add_new_chat({})
            return (new_chat_state, new_chat_id, new_history, chat_list_update, image_return[4]) + image_return[:-1]

        # Jika tidak ada URL share sama sekali, inisialisasi chat
        elif not current_chat_state:
            new_chat_state, new_chat_id, new_history, chat_list_update = add_new_chat({})
            return (new_chat_state, new_chat_id, new_history, chat_list_update, gr.update()) + (gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY, gr.State.IDENTITY)

        # Jika state sudah ada dan tidak ada URL, jangan lakukan apa-apa
        return (gr.State.IDENTITY,) * len(shared_chat_outputs + shared_image_outputs)

    demo.load(log_visitor, inputs=None, outputs=None)
    demo.load(fn=update_system_info, inputs=None, outputs=system_info_md)
    
    random_seed_btn.click(lambda: -1, outputs=seed_input)
    generate_btn.click(fn=genie_wrapper, inputs=[prompt_input, negative_prompt_input, steps_slider, seed_input, num_images_slider], outputs=[output_gallery, loader_html, generate_btn, info_box])
    
    new_chat_btn.click(fn=add_new_chat, inputs=[chat_history_state], outputs=[chat_history_state, current_chat_id_state, chatbot_display, chat_history_list])
    
    send_chat_btn.click(fn=handle_user_message, inputs=[user_chat_input, current_chat_id_state, chat_history_state], outputs=[chat_history_state, chatbot_display, chat_history_list, user_chat_input, chat_action_buttons])
    user_chat_input.submit(fn=handle_user_message, inputs=[user_chat_input, current_chat_id_state, chat_history_state], outputs=[chat_history_state, chatbot_display, chat_history_list, user_chat_input, chat_action_buttons])
    chat_history_list.change(fn=switch_chat, inputs=[chat_history_list, chat_history_state], outputs=[current_chat_id_state, chatbot_display, chat_action_buttons])
    
    share_chat_btn.click(fn=share_chat_history, inputs=[current_chat_id_state, chat_history_state], outputs=[share_chat_output])

    enhance_btn.click(fn=enhance_prompt, inputs=[simple_prompt_input], outputs=[enhanced_prompt_output])
    send_to_gen_btn.click(fn=lambda prompt: (prompt, gr.Tabs(selected=0)), inputs=[enhanced_prompt_output], outputs=[prompt_input, tabs])
    upscale_btn.click(fn=upscale_image, inputs=[image_to_upscale_input, clarity_slider], outputs=[upscaled_image_output, upscale_status_text])
    
    history_tab.select(fn=load_history, inputs=None, outputs=[history_gallery, history_df_state, history_details_md])
    refresh_history_btn.click(fn=load_history, inputs=None, outputs=[history_gallery, history_df_state, history_details_md])
    
    history_gallery.select(fn=show_history_details, inputs=[history_df_state], outputs=[history_details_md, history_action_buttons, share_history_output, selected_history_index_state])
    history_to_gen_btn.click(fn=send_history_to_generator, inputs=[selected_history_index_state, history_df_state], outputs=[prompt_input, negative_prompt_input, seed_input, steps_slider, tabs])
    history_to_editor_btn.click(fn=send_history_to_editor, inputs=[selected_history_index_state, history_df_state], outputs=[editor_input_image, tabs])
    
    share_history_btn.click(fn=share_image_history, inputs=[selected_history_index_state, history_df_state], outputs=[share_history_output])

    editor_inputs = [editor_input_image, brightness_slider, contrast_slider, saturation_slider, sharpness_slider, filter_radio]
    for slider in [brightness_slider, contrast_slider, saturation_slider, sharpness_slider]:
        slider.release(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
    filter_radio.change(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
    editor_input_image.change(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)

    demo.load(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
    refresh_btn.click(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
    time_filter_radio.change(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
    
    system_info_trigger_btn.click(fn=update_system_info, inputs=None, outputs=system_info_md)
    
    report_btn.click(fn=submit_report, inputs=[report_name, report_email, report_message], outputs=[report_status])

# --- Menjalankan Aplikasi ---

if __name__ == "__main__":
    demo.launch(debug=True)