File size: 31,452 Bytes
c062e09
7088d92
c062e09
15f1331
 
 
 
 
 
 
 
 
 
 
4901939
c062e09
4901939
c062e09
 
 
 
 
 
 
 
 
 
 
15f1331
8c6ef54
 
 
 
c062e09
8c6ef54
 
4901939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062e09
 
15f1331
 
c062e09
 
15f1331
c062e09
15f1331
 
 
 
 
 
 
 
 
 
 
4901939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15f1331
4901939
15f1331
 
 
 
8c6ef54
15f1331
 
 
8c6ef54
 
15f1331
c062e09
15f1331
 
0d4c15d
8c6ef54
c062e09
4901939
15f1331
 
 
7088d92
c062e09
 
 
15f1331
 
c062e09
4901939
15f1331
 
 
4901939
 
 
 
 
 
 
 
 
 
c062e09
15f1331
4901939
 
 
 
 
15f1331
 
 
0d4c15d
15f1331
4901939
15f1331
 
8c6ef54
0d4c15d
15f1331
 
c062e09
 
 
8c6ef54
 
4901939
 
8c6ef54
15f1331
 
4901939
c062e09
 
 
4901939
 
c062e09
4901939
 
 
 
 
 
 
c062e09
4901939
c062e09
4901939
 
 
 
 
c062e09
 
 
 
4901939
c062e09
4901939
c062e09
 
4901939
 
 
 
15f1331
4901939
c062e09
0d4c15d
4901939
 
0d4c15d
4901939
 
 
 
 
 
 
 
 
 
c062e09
4901939
c062e09
4901939
c062e09
0d4c15d
 
 
4901939
 
c062e09
 
4901939
c062e09
 
 
 
4901939
 
c062e09
4901939
 
c062e09
 
4901939
 
 
c062e09
0d4c15d
 
4901939
c062e09
 
4901939
c062e09
 
4901939
c062e09
4901939
 
 
 
 
 
 
 
 
c062e09
0d4c15d
4901939
 
 
 
 
c062e09
4901939
 
c062e09
15f1331
4901939
 
 
8c6ef54
4901939
 
 
8c6ef54
 
4901939
15f1331
4901939
8c6ef54
4901939
c062e09
4901939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062e09
 
4901939
7088d92
0d4c15d
4901939
 
 
7088d92
4901939
 
 
 
 
 
 
 
 
 
 
 
c062e09
 
8c6ef54
c062e09
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
# -*- 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
import csv
import pandas as pd
import threading
from PIL import Image, ImageEnhance # Ditambahkan untuk fitur kejernihan gambar

# --- 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) ---
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);
            }
            
            // --- JAVASCRIPT UNTUK TRIGGER PERIODIK YANG KOMPATIBEL ---
            setInterval(() => {
                const triggerButton = document.querySelector('#system-info-trigger-btn button');
                if (triggerButton) {
                    triggerButton.click();
                }
            }, 5000); // Interval 5000 milidetik = 5 detik
        });
    </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 { 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 { border-radius: var(--border-radius) !important; overflow: hidden; border: 1px solid var(--border-color); background-color: #010409; }
        #gallery .gallery-item { transition: transform 0.3s ease, box-shadow 0.3s ease; }
        #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; } }
        .gradio-chatbot .message { border-radius: 12px !important; box-shadow: none !important; }
        .gradio-chatbot .user { background-color: var(--primary-color) !important; color: white !important; }
        .gradio-chatbot .bot { background-color: var(--content-background-color) !important; border: 1px solid var(--border-color) !important; }
        .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"
file_lock = threading.Lock()
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"➑️ Menggunakan device: {device.upper()}")

# --- Inisialisasi File Log Pengunjung ---
def initialize_log_file():
    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.")

initialize_log_file()

# --- PEMUATAN MODEL-MODEL AI ---
# 1. Model Generator Gambar (Inti)
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.")

# 2. Model Peningkatan Resolusi (Fitur Baru)
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 dinonaktifkan.")

# --- 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')
            full_prompt = message
            if system_prompt: full_prompt = f"{system_prompt}\n\nUser query: {message}"
            response = model.generate_content(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), gr.update(interactive=False), gr.update(visible=False)
    start_time = time.time()
    images, used_seed = generate_images(prompt, negative_prompt, steps, int(seed), int(num_images))
    end_time = time.time()
    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)

# --- PERBAIKAN: Fungsi Visitor Monitor yang lebih robust ---
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) < 10: # Check for header
                return "## πŸ“ˆ 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
            df = pd.read_csv(VISITOR_LOG_FILE)
            if df.empty: return "## πŸ“ˆ 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
        
        # Konversi ke datetime dan tangani error dengan mengubahnya menjadi NaT (Not a Time)
        df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
        df.dropna(subset=['Timestamp'], inplace=True) # Hapus baris yang gagal dikonversi
        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)
        
        # Membuat semua data waktu menjadi timezone-naive untuk perbandingan yang konsisten
        now = pd.to_datetime('now', utc=True).tz_localize(None)
        df['Timestamp'] = df['Timestamp'].dt.tz_localize(None)

        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", 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 (cinematic lighting, soft light, dll), gaya seni (photorealistic, anime style, oil painting, dll), komposisi, dan kualitas (hyperdetailed, 4K, masterpiece, trending on artstation). "
        "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

# --- PERBAIKAN: Fungsi Upscaler dengan kontrol kejernihan ---
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. Periksa log saat startup.")
    
    yield None, "πŸš€ Memproses peningkatan resolusi 4x oleh AI..."
    try:
        # Langkah 1: Upscale dengan AI
        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)
        
        # Langkah 2: Terapkan peningkatan kejernihan jika diminta
        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}`\n**VRAM 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}")


# --- 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")
    
    with gr.Tabs() as tabs:
        # --- TAB 1: IMAGE GENERATOR (INTI) ---
        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)
        
        # --- TAB 2: CHAT WITH AI (INTI) ---
        with gr.TabItem("πŸ’¬ Chat with AI", id=1):
            with gr.Row(variant='panel'):
                with gr.Column():
                    gr.Markdown("### πŸ€– **Asisten AI Flood**")
                    if not gemini_bot.is_configured:
                        gr.Warning("Fitur Chatbot dinonaktifkan. API Key Gemini tidak terkonfigurasi.")
                    else:
                        gr.ChatInterface(
                            gemini_bot.chat,
                            chatbot=gr.Chatbot(height=500, label="Flood AI", value=[(None, "Halo! Saya adalah asisten AI dari RenXploit. Ada yang bisa saya bantu?")]),
                            title=None,
                            description="Tanyakan apa saja!",
                            examples=["Apa itu SDXL-Turbo?", "Buatkan saya puisi tentang AI", "Jelaskan konsep lubang hitam dengan sederhana"],
                        )

        # --- TAB 3: PROMPT ENHANCER (FITUR BARU) ---
        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)
                    with gr.Row():
                        send_to_gen_btn = gr.Button("➑️ Kirim & Pindah ke Generator")

        # --- TAB 4: AI IMAGE UPSCALER (FITUR BARU & DIPERBAIKI) ---
        with gr.TabItem("πŸš€ AI Image Upscaler", id=3):
            with gr.Row(variant='panel', equal_height=False): # Ubah equal_height agar slider tidak meregang
                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")
                    # --- PERBAIKAN: Menambahkan slider untuk kontrol kejernihan ---
                    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)
                    upscale_status_text = gr.Markdown("Status: Menunggu gambar...")

        # --- TAB 5: VISITOR MONITOR (INTI & DIPERBAIKI) ---
        with gr.TabItem("πŸ“Š Visitor Monitor", id=4):
             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)

        # --- TAB 6: SYSTEM & SETTINGS (FITUR BARU & DIPERBAIKI) ---
        with gr.TabItem("βš™οΈ System & Settings", id=5):
            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):
                         # --- PERBAIKAN: Mengubah teks info agar lebih jelas ---
                         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. Pengaturan ini ditentukan saat aplikasi dimulai berdasarkan ketersediaan GPU Anda.")

        # --- TAB-TAB STATIS ---
        # (Tidak ada perubahan di sini, konten tetap sama)
        with gr.TabItem("πŸ’‘ Panduan Prompting", id=6):
            with gr.Row(variant='panel'): gr.Markdown("""## Cara Menjadi "Art Director" yang Hebat untuk AI...""")
        with gr.TabItem("πŸ“– Blog & Updates", id=7):
            with gr.Row(variant='panel'): gr.Markdown("""### Perkembangan Terbaru dari RenXploit's AI Suite\n- **v2.4 (Pembaruan Terkini):** Upscaler di-upgrade dengan kontrol kejernihan, Visitor Monitor diperbaiki, dan UI Settings diperjelas.\n- **v2.3:** Perbaikan bug kritis untuk kompatibilitas dengan berbagai versi Gradio.\n- **v2.2:** Perbaikan bug untuk kompatibilitas Gradio.\n- **v2.1:** Menambahkan **Prompt Enhancer**, **AI Image Upscaler**, dan **Live System Monitor**.\n- **v2.0:** Perombakan Desain Total.\n- **Rencana Berikutnya:** Menjajaki model generator gambar yang berbeda dan fitur Inpainting/Outpainting. Nantikan!""")
        with gr.TabItem("ℹ️ About & Support", id=8):
            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 yang dibuat untuk mengeksplorasi kemampuan AI generatif dalam sebuah antarmuka yang mudah digunakan.\n **Bagian ini belum saya kerjakan dengan selesai** jadi jika anda ingin komplain atau ada hal apapun itu bisa report ke saya lewat website portofolio saya dengan url: https://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 yang Anda temui atau ide yang Anda miliki...")
                        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) ---
    # 1. Event Inti
    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])
    report_btn.click(fn=submit_report, inputs=[report_name, report_email, report_message], outputs=[report_status])

    # 2. Event Visitor Monitor
    demo.load(log_visitor, inputs=None, outputs=None)
    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])

    # 3. Event Fitur Baru
    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]) # Input diperbarui
    
    system_info_trigger_btn.click(fn=update_system_info, inputs=None, outputs=system_info_md)
    demo.load(fn=update_system_info, inputs=None, outputs=system_info_md) # Jalankan sekali saat dimuat


# --- Menjalankan Aplikasi ---
if __name__ == "__main__":
    demo.launch(debug=True)