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ding: utf-8 --
|
| 2 |
+
# --- IMPORT LIBRARY UTAMA & INTI ---
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
from diffusers import DiffusionPipeline
|
| 7 |
+
import random
|
| 8 |
+
import time
|
| 9 |
+
import os
|
| 10 |
+
from datetime import datetime, timedelta
|
| 11 |
+
import csv
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import threading
|
| 14 |
+
from PIL import Image, ImageEnhance
|
| 15 |
+
from pathlib import Path # Ditambahkan untuk manajemen path yang lebih baik
|
| 16 |
+
|
| 17 |
+
# --- LIBRARY BARU UNTUK FITUR UPGRADE ---
|
| 18 |
+
try:
|
| 19 |
+
import psutil
|
| 20 |
+
import platform
|
| 21 |
+
from transformers import Swin2SRForImageSuperResolution, Swin2SRImageProcessor
|
| 22 |
+
print("β
Library tambahan (psutil, transformers) berhasil diimpor.")
|
| 23 |
+
except ImportError:
|
| 24 |
+
print("β Peringatan: Library 'psutil' atau 'transformers' tidak ditemukan. Fitur System Monitor & Upscaler tidak akan berfungsi.")
|
| 25 |
+
psutil = None
|
| 26 |
+
platform = None
|
| 27 |
+
Swin2SRForImageSuperResolution = None
|
| 28 |
+
Swin2SRImageProcessor = None
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
import google.generativeai as genai
|
| 32 |
+
print("β
Library 'google-generativeai' berhasil diimpor.")
|
| 33 |
+
except ImportError:
|
| 34 |
+
print("β Peringatan: Library 'google-generativeai' tidak ditemukan. Fitur Chatbot & Prompt Enhancer tidak akan berfungsi.")
|
| 35 |
+
genai = None
|
| 36 |
+
|
| 37 |
+
# --- HEAD HTML & CSS (Tampilan Profesional) ---
|
| 38 |
+
# (Tidak ada perubahan pada HEAD_HTML & CSS, tetap sama seperti yang Anda berikan)
|
| 39 |
+
HEAD_HTML = """
|
| 40 |
+
<head>
|
| 41 |
+
<meta charset="UTF-8">
|
| 42 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 43 |
+
<title>RenXploit's Creative AI Suite</title>
|
| 44 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 45 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 46 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fira+Code:wght@500&display=swap" rel="stylesheet">
|
| 47 |
+
<script>
|
| 48 |
+
function typewriterEffect(element, text, speed) {
|
| 49 |
+
let i = 0;
|
| 50 |
+
element.innerHTML = "";
|
| 51 |
+
const cursor = document.createElement('span');
|
| 52 |
+
cursor.className = 'typewriter-cursor';
|
| 53 |
+
cursor.innerHTML = '|';
|
| 54 |
+
element.appendChild(cursor);
|
| 55 |
+
function type() {
|
| 56 |
+
if (i < text.length) {
|
| 57 |
+
element.insertBefore(document.createTextNode(text.charAt(i)), cursor);
|
| 58 |
+
i++;
|
| 59 |
+
setTimeout(type, speed);
|
| 60 |
+
} else {
|
| 61 |
+
cursor.style.animation = 'blink 1s step-end infinite';
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
type();
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
document.addEventListener("DOMContentLoaded", function(event) {
|
| 68 |
+
const titleElement = document.querySelector('#main-title h1');
|
| 69 |
+
if (titleElement) {
|
| 70 |
+
const titleText = "π RenXploit's Creative AI Suite π";
|
| 71 |
+
titleElement.textContent = "";
|
| 72 |
+
setTimeout(() => typewriterEffect(titleElement, titleText, 50), 500);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
setInterval(() => {
|
| 76 |
+
const triggerButton = document.querySelector('#system-info-trigger-btn button');
|
| 77 |
+
if (triggerButton) {
|
| 78 |
+
triggerButton.click();
|
| 79 |
+
}
|
| 80 |
+
}, 5000);
|
| 81 |
+
});
|
| 82 |
+
</script>
|
| 83 |
+
<style>
|
| 84 |
+
: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); }
|
| 85 |
+
body, .gradio-container { font-family: var(--font-family-main); background-color: var(--background-color) !important; color: var(--text-color); }
|
| 86 |
+
h1, h2, h3 { color: #ffffff; font-weight: 600; }
|
| 87 |
+
#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; }
|
| 88 |
+
#main-title .typewriter-cursor { color: var(--primary-color); font-weight: bold; }
|
| 89 |
+
@keyframes blink { from, to { opacity: 1 } 50% { opacity: 0 } }
|
| 90 |
+
#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; }
|
| 91 |
+
.gradio-tabs { border: none !important; background-color: transparent !important; margin-bottom: 1.5rem; }
|
| 92 |
+
.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; }
|
| 93 |
+
.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; }
|
| 94 |
+
.gradio-tabs > div[role="tablist"] > button:hover { background-color: var(--content-background-color) !important; color: var(--primary-color) !important; }
|
| 95 |
+
.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; }
|
| 96 |
+
.tabitem { background-color: transparent !important; border: none !important; padding: 0 !important; }
|
| 97 |
+
.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); }
|
| 98 |
+
.gradio-accordion { margin-top: 1rem; }
|
| 99 |
+
.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); }
|
| 100 |
+
.gradio-button.primary:hover { transform: translateY(-2px); box-shadow: var(--shadow-strong); }
|
| 101 |
+
.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; }
|
| 102 |
+
.gradio-button.secondary:hover { background-color: var(--primary-color) !important; color: #ffffff !important; }
|
| 103 |
+
.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; }
|
| 104 |
+
.gradio-textbox textarea, .gradio-number input { color: var(--text-color) !important; }
|
| 105 |
+
.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); }
|
| 106 |
+
div.info { color: var(--text-muted-color) !important; font-style: italic; }
|
| 107 |
+
#gallery { border-radius: var(--border-radius) !important; overflow: hidden; border: 1px solid var(--border-color); background-color: #010409; }
|
| 108 |
+
#gallery .gallery-item { transition: transform 0.3s ease, box-shadow 0.3s ease; }
|
| 109 |
+
#gallery .gallery-item:hover { transform: scale(1.03); box-shadow: 0 8px 30px rgba(0, 170, 255, 0.3); }
|
| 110 |
+
.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; }
|
| 111 |
+
.loader-text { font-family: var(--font-family-mono); font-size: 1.1em; color: var(--primary-color); margin-bottom: 20px; }
|
| 112 |
+
.loader-bar-container { height: 8px; background: var(--background-color); border-radius: 4px; overflow: hidden; }
|
| 113 |
+
.loader-bar { width: 100%; height: 100%; background: linear-gradient(90deg, transparent, var(--primary-color), transparent); background-size: 200% 100%; animation: scan 2s linear infinite; }
|
| 114 |
+
@keyframes scan { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
|
| 115 |
+
.gradio-chatbot .message { border-radius: 12px !important; box-shadow: none !important; }
|
| 116 |
+
.gradio-chatbot .user { background-color: var(--primary-color) !important; color: white !important; }
|
| 117 |
+
.gradio-chatbot .bot { background-color: var(--content-background-color) !important; border: 1px solid var(--border-color) !important; }
|
| 118 |
+
.footer { text-align: center; margin: 2rem auto; padding: 1rem; color: var(--text-muted-color); border-top: 1px solid var(--border-color); }
|
| 119 |
+
.footer b { color: var(--primary-color); }
|
| 120 |
+
</style>
|
| 121 |
+
</head>
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
# --- PENGATURAN & LOGIC GLOBAL ---
|
| 125 |
+
VISITOR_LOG_FILE = "visitor_log.csv"
|
| 126 |
+
HISTORY_LOG_FILE = "generation_log.csv" # LOG BARU
|
| 127 |
+
IMAGE_HISTORY_DIR = Path("generated_images") # DIREKTORI BARU
|
| 128 |
+
|
| 129 |
+
file_lock = threading.Lock()
|
| 130 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 131 |
+
print(f"β‘οΈ Menggunakan device: {device.upper()}")
|
| 132 |
+
|
| 133 |
+
# --- Inisialisasi File Log & Direktori ---
|
| 134 |
+
def initialize_environment():
|
| 135 |
+
# Inisialisasi log pengunjung
|
| 136 |
+
if not os.path.exists(VISITOR_LOG_FILE):
|
| 137 |
+
with file_lock:
|
| 138 |
+
if not os.path.exists(VISITOR_LOG_FILE):
|
| 139 |
+
with open(VISITOR_LOG_FILE, mode='w', newline='', encoding='utf-8') as f:
|
| 140 |
+
writer = csv.writer(f)
|
| 141 |
+
writer.writerow(["Timestamp", "IP Address", "User Agent"])
|
| 142 |
+
print(f"β
File log '{VISITOR_LOG_FILE}' berhasil dibuat.")
|
| 143 |
+
|
| 144 |
+
# Inisialisasi log riwayat generasi & direktori gambar (FITUR BARU)
|
| 145 |
+
IMAGE_HISTORY_DIR.mkdir(exist_ok=True)
|
| 146 |
+
if not os.path.exists(HISTORY_LOG_FILE):
|
| 147 |
+
with file_lock:
|
| 148 |
+
if not os.path.exists(HISTORY_LOG_FILE):
|
| 149 |
+
with open(HISTORY_LOG_FILE, mode='w', newline='', encoding='utf-8') as f:
|
| 150 |
+
writer = csv.writer(f)
|
| 151 |
+
writer.writerow(["Timestamp", "Filename", "Prompt", "NegativePrompt", "Seed", "Steps"])
|
| 152 |
+
print(f"β
File log riwayat '{HISTORY_LOG_FILE}' dan direktori '{IMAGE_HISTORY_DIR}' siap.")
|
| 153 |
+
|
| 154 |
+
initialize_environment()
|
| 155 |
+
|
| 156 |
+
# --- PEMUATAN MODEL-MODEL AI ---
|
| 157 |
+
# 1. Model Generator Gambar (Inti)
|
| 158 |
+
print("β‘οΈ Memuat model SDXL-Turbo...")
|
| 159 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 160 |
+
"stabilityai/sdxl-turbo", torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 161 |
+
variant="fp16" if device == "cuda" else None, use_safetensors=True
|
| 162 |
+
).to(device)
|
| 163 |
+
if torch.cuda.is_available(): pipe.enable_xformers_memory_efficient_attention()
|
| 164 |
+
print("β
Model SDXL-Turbo berhasil dimuat.")
|
| 165 |
+
|
| 166 |
+
# 2. Model Peningkatan Resolusi (Fitur Baru)
|
| 167 |
+
upscaler_model = None
|
| 168 |
+
upscaler_processor = None
|
| 169 |
+
if Swin2SRForImageSuperResolution:
|
| 170 |
+
try:
|
| 171 |
+
print("β‘οΈ Memuat model AI Upscaler (Swin2SR)...")
|
| 172 |
+
upscaler_model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2sr-realworld-sr-x4-64-bsrgan-psnr").to(device)
|
| 173 |
+
upscaler_processor = Swin2SRImageProcessor.from_pretrained("caidas/swin2sr-realworld-sr-x4-64-bsrgan-psnr")
|
| 174 |
+
print("β
Model AI Upscaler berhasil dimuat.")
|
| 175 |
+
except Exception as e:
|
| 176 |
+
print(f"β Gagal memuat model Upscaler: {e}. Fitur upscale akan dinonaktifkan.")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# --- KELAS UNTUK CHATBOT GEMINI ---
|
| 180 |
+
class GeminiChat:
|
| 181 |
+
def __init__(self): # Perbaikan: Gunakan __init__
|
| 182 |
+
self.api_keys = []
|
| 183 |
+
self.is_configured = False
|
| 184 |
+
if not genai: return
|
| 185 |
+
|
| 186 |
+
i = 1
|
| 187 |
+
while True:
|
| 188 |
+
key = os.getenv(f"GEMINI_API_KEY_{i}")
|
| 189 |
+
if key:
|
| 190 |
+
self.api_keys.append(key)
|
| 191 |
+
i += 1
|
| 192 |
+
else:
|
| 193 |
+
break
|
| 194 |
+
|
| 195 |
+
if self.api_keys:
|
| 196 |
+
print(f"β
Berhasil memuat {len(self.api_keys)} API Key Gemini. Sistem rotasi aktif.")
|
| 197 |
+
self.is_configured = True
|
| 198 |
+
else:
|
| 199 |
+
print("β PERINGATAN: Tidak ada API Key Gemini yang ditemukan. Fitur AI Chat & Prompt Enhancer tidak akan berfungsi.")
|
| 200 |
+
|
| 201 |
+
def chat(self, message, history, system_prompt=None):
|
| 202 |
+
if not self.is_configured:
|
| 203 |
+
return "Maaf, fitur ini tidak terkonfigurasi karena tidak ada API Key."
|
| 204 |
+
try:
|
| 205 |
+
selected_key = random.choice(self.api_keys)
|
| 206 |
+
genai.configure(api_key=selected_key)
|
| 207 |
+
model = genai.GenerativeModel('gemini-2.5-flash') # Menggunakan model yang lebih baru
|
| 208 |
+
full_prompt = message
|
| 209 |
+
if system_prompt:
|
| 210 |
+
full_prompt = f"{system_prompt}\n\nUser query: {message}"
|
| 211 |
+
response = model.generate_content(full_prompt)
|
| 212 |
+
return response.text
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"β Terjadi error pada API Key Gemini: {e}")
|
| 215 |
+
return "Terjadi kesalahan saat menghubungi API AI. Mungkin salah satu API Key tidak valid atau ada masalah jaringan. Silakan coba lagi."
|
| 216 |
+
|
| 217 |
+
gemini_bot = GeminiChat()
|
| 218 |
+
|
| 219 |
+
# --- FUNGSI-FUNGSI INTI (GENERATOR & LAINNYA) ---
|
| 220 |
+
def log_visitor(request: gr.Request):
|
| 221 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 222 |
+
ip_address = request.client.host if request else "N/A"
|
| 223 |
+
user_agent = request.headers.get("user-agent", "Unknown") if request else "N/A"
|
| 224 |
+
with file_lock:
|
| 225 |
+
with open(VISITOR_LOG_FILE, mode='a', newline='', encoding='utf-8') as f:
|
| 226 |
+
writer = csv.writer(f)
|
| 227 |
+
writer.writerow([timestamp, ip_address, user_agent])
|
| 228 |
+
print(f"β
Pengunjung baru tercatat: IP {ip_address}")
|
| 229 |
+
|
| 230 |
+
def generate_images(prompt, negative_prompt, steps, seed, num_images):
|
| 231 |
+
if not prompt:
|
| 232 |
+
raise gr.Error("Prompt tidak boleh kosong!")
|
| 233 |
+
if seed == -1:
|
| 234 |
+
seed = random.randint(0, 2**32 - 1)
|
| 235 |
+
generator = torch.manual_seed(seed)
|
| 236 |
+
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
|
| 237 |
+
return images, seed
|
| 238 |
+
|
| 239 |
+
def genie_wrapper(prompt, negative_prompt, steps, seed, num_images):
|
| 240 |
+
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)
|
| 241 |
+
|
| 242 |
+
start_time = time.time()
|
| 243 |
+
num_images_int = int(num_images)
|
| 244 |
+
steps_int = int(steps)
|
| 245 |
+
seed_int = int(seed)
|
| 246 |
+
|
| 247 |
+
images, used_seed = generate_images(prompt, negative_prompt, steps_int, seed_int, num_images_int)
|
| 248 |
+
end_time = time.time()
|
| 249 |
+
|
| 250 |
+
# --- UPGRADE: Menyimpan gambar dan log riwayat ---
|
| 251 |
+
timestamp_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 252 |
+
for i, img in enumerate(images):
|
| 253 |
+
filename = f"{int(time.time())}_{i}.png"
|
| 254 |
+
filepath = IMAGE_HISTORY_DIR / filename
|
| 255 |
+
img.save(filepath)
|
| 256 |
+
|
| 257 |
+
with file_lock:
|
| 258 |
+
with open(HISTORY_LOG_FILE, mode='a', newline='', encoding='utf-8') as f:
|
| 259 |
+
writer = csv.writer(f)
|
| 260 |
+
writer.writerow([timestamp_str, filename, prompt, negative_prompt, used_seed, steps_int])
|
| 261 |
+
|
| 262 |
+
generation_time = end_time - start_time
|
| 263 |
+
info_text = f"Seed yang digunakan: {used_seed}\nTotal waktu generasi: {generation_time:.2f} detik"
|
| 264 |
+
yield gr.update(value=images, visible=True), gr.update(visible=False), gr.update(interactive=True), gr.update(value=info_text, visible=True)
|
| 265 |
+
|
| 266 |
+
def submit_report(name, email, message):
|
| 267 |
+
if not name or not message:
|
| 268 |
+
gr.Warning("Nama dan Pesan tidak boleh kosong!")
|
| 269 |
+
return gr.update(visible=False)
|
| 270 |
+
report_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 271 |
+
report_content = f"--- Laporan Baru ({report_time}) ---\nNama: {name}\nEmail: {email}\nPesan: {message}\n\n"
|
| 272 |
+
with open("reports.log", "a", encoding="utf-8") as f:
|
| 273 |
+
f.write(report_content)
|
| 274 |
+
print("β
Laporan baru telah disimpan ke reports.log")
|
| 275 |
+
return gr.update(value="β
Terima kasih! Laporan Anda telah kami terima.", visible=True)
|
| 276 |
+
|
| 277 |
+
def update_visitor_monitor(time_filter: str):
|
| 278 |
+
try:
|
| 279 |
+
with file_lock:
|
| 280 |
+
if not os.path.exists(VISITOR_LOG_FILE) or os.path.getsize(VISITOR_LOG_FILE) < 10:
|
| 281 |
+
return "## π 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
|
| 282 |
+
df = pd.read_csv(VISITOR_LOG_FILE)
|
| 283 |
+
if df.empty: return "## π 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
|
| 284 |
+
|
| 285 |
+
df['Timestamp'] = pd.to_datetime(df['Timestamp'], errors='coerce')
|
| 286 |
+
df.dropna(subset=['Timestamp'], inplace=True)
|
| 287 |
+
if df.empty: return "## π 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
|
| 288 |
+
|
| 289 |
+
total_overall_visitors = len(df)
|
| 290 |
+
total_visitors_formatted = f"## π {total_overall_visitors:,}"
|
| 291 |
+
df['Total Pengunjung'] = np.arange(1, len(df) + 1)
|
| 292 |
+
|
| 293 |
+
now = pd.to_datetime('now', utc=True).tz_localize(None)
|
| 294 |
+
df['Timestamp'] = df['Timestamp'].dt.tz_localize(None)
|
| 295 |
+
|
| 296 |
+
if time_filter == "1 Minggu Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(weeks=1)]
|
| 297 |
+
elif time_filter == "2 Minggu Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(weeks=2)]
|
| 298 |
+
elif time_filter == "3 Bulan Terakhir": df_plot = df[df['Timestamp'] >= now - timedelta(days=90)]
|
| 299 |
+
else: df_plot = df
|
| 300 |
+
|
| 301 |
+
if df_plot.empty: return total_visitors_formatted, pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
|
| 302 |
+
|
| 303 |
+
return total_visitors_formatted, df_plot
|
| 304 |
+
except Exception as e:
|
| 305 |
+
error_message = f"Error saat memperbarui monitor: {e}"
|
| 306 |
+
print(f"β {error_message}")
|
| 307 |
+
return f"## β οΈ Error", pd.DataFrame({"Error": [error_message]})
|
| 308 |
+
|
| 309 |
+
# --- FUNGSI-FUNGSI FITUR BARU ---
|
| 310 |
+
|
| 311 |
+
def enhance_prompt(simple_prompt):
|
| 312 |
+
if not simple_prompt:
|
| 313 |
+
gr.Warning("Tolong masukkan ide Anda terlebih dahulu.")
|
| 314 |
+
return ""
|
| 315 |
+
if not gemini_bot.is_configured:
|
| 316 |
+
gr.Error("Fitur Prompt Enhancer tidak aktif karena API Key Gemini tidak diatur.")
|
| 317 |
+
return "Fitur tidak aktif."
|
| 318 |
+
|
| 319 |
+
system_instruction = (
|
| 320 |
+
"Anda adalah seorang ahli prompt engineering untuk model AI text-to-image seperti Stable Diffusion. "
|
| 321 |
+
"Tugas Anda adalah mengubah ide sederhana dari pengguna menjadi prompt yang kaya, deskriptif, dan artistik. "
|
| 322 |
+
"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). "
|
| 323 |
+
"Hasilkan HANYA prompt-nya saja dalam format teks panjang, tanpa penjelasan atau kalimat pembuka/penutup."
|
| 324 |
+
)
|
| 325 |
+
yield "π§ AI sedang meracik prompt ajaib untuk Anda..."
|
| 326 |
+
enhanced_prompt = gemini_bot.chat(simple_prompt, [], system_prompt=system_instruction)
|
| 327 |
+
yield enhanced_prompt
|
| 328 |
+
|
| 329 |
+
def upscale_image(image_to_upscale, clarity_strength):
|
| 330 |
+
if image_to_upscale is None:
|
| 331 |
+
raise gr.Error("Silakan unggah gambar terlebih dahulu.")
|
| 332 |
+
if upscaler_model is None or upscaler_processor is None:
|
| 333 |
+
raise gr.Error("Fitur Upscaler tidak aktif karena model gagal dimuat. Periksa log saat startup.")
|
| 334 |
+
|
| 335 |
+
yield None, "π Memproses peningkatan resolusi 4x oleh AI..."
|
| 336 |
+
try:
|
| 337 |
+
with torch.no_grad():
|
| 338 |
+
inputs = upscaler_processor(image_to_upscale, return_tensors="pt").to(device)
|
| 339 |
+
outputs = upscaler_model(**inputs)
|
| 340 |
+
output_image = outputs.reconstruction.data.squeeze().float().cpu().clamp_(0, 1).numpy()
|
| 341 |
+
output_image = np.moveaxis(output_image, source=0, destination=-1)
|
| 342 |
+
output_image = (output_image * 255.0).round().astype(np.uint8)
|
| 343 |
+
final_image = Image.fromarray(output_image)
|
| 344 |
+
|
| 345 |
+
if clarity_strength > 1.0:
|
| 346 |
+
yield final_image, f"β¨ Menerapkan peningkatan kejernihan (Strength: {clarity_strength:.2f})..."
|
| 347 |
+
enhancer = ImageEnhance.Sharpness(final_image)
|
| 348 |
+
final_image = enhancer.enhance(clarity_strength)
|
| 349 |
+
|
| 350 |
+
yield final_image, f"β
Gambar berhasil ditingkatkan! Resolusi akhir: {final_image.width}x{final_image.height}px."
|
| 351 |
+
except Exception as e:
|
| 352 |
+
print(f"β Error saat upscaling: {e}")
|
| 353 |
+
yield None, f"β οΈ Terjadi error saat upscaling: {e}"
|
| 354 |
+
|
| 355 |
+
def update_system_info():
|
| 356 |
+
if not psutil or not platform: return "Informasi sistem tidak tersedia (library psutil tidak ditemukan)."
|
| 357 |
+
cpu_percent = psutil.cpu_percent(interval=None)
|
| 358 |
+
ram = psutil.virtual_memory()
|
| 359 |
+
gpu_info = "Tidak terdeteksi (PyTorch tidak menemukan CUDA)"
|
| 360 |
+
if torch.cuda.is_available():
|
| 361 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 362 |
+
gpu_mem_used_gb = torch.cuda.memory_allocated(0) / (1024**3)
|
| 363 |
+
gpu_mem_total_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
|
| 364 |
+
gpu_info = f"**GPU:** `{gpu_name}`\n**VRAM Terpakai:** `{gpu_mem_used_gb:.2f} GB / {gpu_mem_total_gb:.2f} GB`"
|
| 365 |
+
|
| 366 |
+
sys_info = f"**Platform:** `{platform.system()} {platform.release()}`"
|
| 367 |
+
return (f"**CPU Terpakai:** `{cpu_percent:.1f}%`\n"
|
| 368 |
+
f"**RAM Terpakai:** `{ram.percent:.1f}% ({ram.used / (1024**3):.2f} GB / {ram.total / (1024**3):.2f} GB)`\n"
|
| 369 |
+
f"{gpu_info}\n---\n{sys_info}")
|
| 370 |
+
|
| 371 |
+
# --- FUNGSI-FUNGSI UNTUK MENU BARU ---
|
| 372 |
+
|
| 373 |
+
# Fitur: Galeri & Riwayat
|
| 374 |
+
def load_history():
|
| 375 |
+
try:
|
| 376 |
+
with file_lock:
|
| 377 |
+
if not os.path.exists(HISTORY_LOG_FILE):
|
| 378 |
+
return [], pd.DataFrame(), "### π Riwayat Kosong\nBelum ada gambar yang dihasilkan."
|
| 379 |
+
df = pd.read_csv(HISTORY_LOG_FILE)
|
| 380 |
+
|
| 381 |
+
if df.empty:
|
| 382 |
+
return [], df, "### π Riwayat Kosong\nBelum ada gambar yang dihasilkan."
|
| 383 |
+
|
| 384 |
+
df_sorted = df.sort_values(by="Timestamp", ascending=False)
|
| 385 |
+
image_paths = [str(IMAGE_HISTORY_DIR / fname) for fname in df_sorted['Filename']]
|
| 386 |
+
return image_paths, df_sorted, "### β Detail Gambar\nKlik pada sebuah gambar untuk melihat detailnya."
|
| 387 |
+
except Exception as e:
|
| 388 |
+
print(f"β Error memuat riwayat: {e}")
|
| 389 |
+
return [], pd.DataFrame(), f"### β οΈ Error\nTidak dapat memuat riwayat: {e}"
|
| 390 |
+
|
| 391 |
+
def show_history_details(evt: gr.SelectData, history_df: pd.DataFrame):
|
| 392 |
+
if not evt.selected or history_df.empty:
|
| 393 |
+
return "### β Detail Gambar\nKlik pada sebuah gambar untuk melihat detailnya.", gr.update(visible=False)
|
| 394 |
+
|
| 395 |
+
selected_row = history_df.iloc[evt.index]
|
| 396 |
+
details = f"""
|
| 397 |
+
**Prompt:** `{selected_row['Prompt']}`
|
| 398 |
+
**Negative Prompt:** `{selected_row['NegativePrompt']}`
|
| 399 |
+
---
|
| 400 |
+
**Seed:** `{selected_row['Seed']}` | **Steps:** `{selected_row['Steps']}`
|
| 401 |
+
**File:** `{selected_row['Filename']}` | **Dibuat:** `{selected_row['Timestamp']}`
|
| 402 |
+
"""
|
| 403 |
+
return details, gr.update(visible=True)
|
| 404 |
+
|
| 405 |
+
def send_history_to_generator(evt: gr.SelectData, history_df: pd.DataFrame):
|
| 406 |
+
if not evt.selected or history_df.empty:
|
| 407 |
+
return gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 408 |
+
|
| 409 |
+
selected_row = history_df.iloc[evt.index]
|
| 410 |
+
return (
|
| 411 |
+
selected_row['Prompt'],
|
| 412 |
+
selected_row['NegativePrompt'],
|
| 413 |
+
selected_row['Seed'],
|
| 414 |
+
selected_row['Steps'],
|
| 415 |
+
gr.Tabs(selected=0) # Pindah ke tab generator
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def send_history_to_editor(evt: gr.SelectData, history_df: pd.DataFrame):
|
| 419 |
+
if not evt.selected or history_df.empty:
|
| 420 |
+
return gr.update(), gr.update()
|
| 421 |
+
|
| 422 |
+
selected_row = history_df.iloc[evt.index]
|
| 423 |
+
image_path = str(IMAGE_HISTORY_DIR / selected_row['Filename'])
|
| 424 |
+
return Image.open(image_path), gr.Tabs(selected=5) # Pindah ke tab editor
|
| 425 |
+
|
| 426 |
+
# Fitur: Image Editor
|
| 427 |
+
def apply_image_edits(image, brightness, contrast, saturation, sharpness, filter_choice):
|
| 428 |
+
if image is None:
|
| 429 |
+
return None
|
| 430 |
+
|
| 431 |
+
output_image = image.copy()
|
| 432 |
+
|
| 433 |
+
if filter_choice == "Grayscale":
|
| 434 |
+
output_image = output_image.convert("L").convert("RGB") # Convert to grayscale and back to RGB
|
| 435 |
+
elif filter_choice == "Sepia":
|
| 436 |
+
pixels = output_image.load()
|
| 437 |
+
width, height = output_image.size
|
| 438 |
+
for y in range(height):
|
| 439 |
+
for x in range(width):
|
| 440 |
+
r, g, b = output_image.getpixel((x, y))
|
| 441 |
+
tr = int(0.393 * r + 0.769 * g + 0.189 * b)
|
| 442 |
+
tg = int(0.349 * r + 0.686 * g + 0.168 * b)
|
| 443 |
+
tb = int(0.272 * r + 0.534 * g + 0.131 * b)
|
| 444 |
+
pixels[x, y] = (min(255, tr), min(255, tg), min(255, tb))
|
| 445 |
+
|
| 446 |
+
# Terapkan penyesuaian hanya jika bukan filter
|
| 447 |
+
if filter_choice == "None":
|
| 448 |
+
enhancer = ImageEnhance.Brightness(output_image)
|
| 449 |
+
output_image = enhancer.enhance(brightness)
|
| 450 |
+
enhancer = ImageEnhance.Contrast(output_image)
|
| 451 |
+
output_image = enhancer.enhance(contrast)
|
| 452 |
+
enhancer = ImageEnhance.Color(output_image)
|
| 453 |
+
output_image = enhancer.enhance(saturation)
|
| 454 |
+
enhancer = ImageEnhance.Sharpness(output_image)
|
| 455 |
+
output_image = enhancer.enhance(sharpness)
|
| 456 |
+
|
| 457 |
+
return output_image
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# --- ANTARMUKA PENGGUNA (GRADIO UI) ---
|
| 461 |
+
with gr.Blocks(theme=gr.themes.Base(), head=HEAD_HTML) as demo:
|
| 462 |
+
gr.Markdown("# π RenXploit's Creative AI Suite π", elem_id="main-title")
|
| 463 |
+
gr.Markdown("Sebuah platform lengkap untuk kreativitas Anda, ditenagai oleh AI.", elem_id="main-subtitle")
|
| 464 |
+
|
| 465 |
+
with gr.Tabs() as tabs:
|
| 466 |
+
# --- TAB 1: IMAGE GENERATOR (INTI) ---
|
| 467 |
+
with gr.TabItem("π¨ Image Generator", id=0):
|
| 468 |
+
with gr.Row(variant='panel', equal_height=False):
|
| 469 |
+
with gr.Column(scale=1):
|
| 470 |
+
gr.Markdown("### π **Masukan Perintah Anda**")
|
| 471 |
+
prompt_input = gr.Textbox(label="Prompt", placeholder="Contoh: Cinematic photo, seekor rubah merah...", lines=3, info="Jadilah sangat spesifik! Atau gunakan Prompt Enhancer.")
|
| 472 |
+
negative_prompt_input = gr.Textbox(label="Prompt Negatif", placeholder="Contoh: blurry, low quality, bad hands...", lines=2, info="Hal-hal yang TIDAK Anda inginkan.")
|
| 473 |
+
num_images_slider = gr.Slider(minimum=1, maximum=8, value=2, step=1, label="Jumlah Gambar")
|
| 474 |
+
generate_btn = gr.Button("β¨ Hasilkan Gambar!", variant="primary")
|
| 475 |
+
with gr.Accordion("βοΈ Opsi Lanjutan", open=False):
|
| 476 |
+
steps_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Langkah Iterasi (Kualitas vs Kecepatan)")
|
| 477 |
+
with gr.Row():
|
| 478 |
+
seed_input = gr.Number(label="Seed", value=-1, precision=0, info="Gunakan -1 untuk acak.")
|
| 479 |
+
random_seed_btn = gr.Button("π² Acak", variant="secondary")
|
| 480 |
+
with gr.Column(scale=2):
|
| 481 |
+
gr.Markdown("### πΌοΈ **Hasil Generasi**")
|
| 482 |
+
output_gallery = gr.Gallery(label="Hasil Gambar", show_label=False, elem_id="gallery", columns=2, object_fit="contain", height="auto")
|
| 483 |
+
loader_html = gr.HTML(visible=False)
|
| 484 |
+
info_box = gr.Textbox(label="Informasi Generasi", visible=False, interactive=False, lines=2)
|
| 485 |
+
|
| 486 |
+
# --- TAB 2: CHAT WITH AI (INTI) ---
|
| 487 |
+
with gr.TabItem("π¬ Chat with AI", id=1):
|
| 488 |
+
with gr.Row(variant='panel'):
|
| 489 |
+
with gr.Column():
|
| 490 |
+
gr.Markdown("### π€ **Asisten AI Flood**")
|
| 491 |
+
if not gemini_bot.is_configured:
|
| 492 |
+
gr.Warning("Fitur Chatbot dinonaktifkan. API Key Gemini tidak terkonfigurasi.")
|
| 493 |
+
else:
|
| 494 |
+
gr.ChatInterface(
|
| 495 |
+
gemini_bot.chat,
|
| 496 |
+
chatbot=gr.Chatbot(height=500, label="Flood AI", value=[(None, "Halo! Saya adalah asisten AI dari RenXploit. Ada yang bisa saya bantu?")]),
|
| 497 |
+
title=None,
|
| 498 |
+
description="Tanyakan apa saja!",
|
| 499 |
+
examples=["Apa itu SDXL-Turbo?", "Buatkan saya puisi tentang AI", "Jelaskan konsep lubang hitam dengan sederhana"],
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# --- TAB 3: PROMPT ENHANCER (FITUR LAMA) ---
|
| 503 |
+
with gr.TabItem("β¨ Prompt Enhancer", id=2):
|
| 504 |
+
with gr.Row(variant='panel'):
|
| 505 |
+
with gr.Column():
|
| 506 |
+
gr.Markdown("### πͺ **Ubah Ide Jadi Prompt Ajaib**\nCukup tulis ide sederhana, dan biarkan AI menyempurnakannya menjadi prompt yang detail dan artistik.")
|
| 507 |
+
simple_prompt_input = gr.Textbox(label="Ide Sederhana Anda", placeholder="Contoh: seekor astronot di hutan alien", lines=3)
|
| 508 |
+
enhance_btn = gr.Button("Buat Prompt Ajaib!", variant="primary")
|
| 509 |
+
enhanced_prompt_output = gr.Textbox(label="Prompt yang Disempurnakan", lines=5, interactive=True, show_copy_button=True)
|
| 510 |
+
send_to_gen_btn = gr.Button("β‘οΈ Kirim & Pindah ke Generator")
|
| 511 |
+
|
| 512 |
+
# --- TAB 4: AI IMAGE UPSCALER (FITUR LAMA) ---
|
| 513 |
+
with gr.TabItem("π AI Image Upscaler", id=3):
|
| 514 |
+
with gr.Row(variant='panel', equal_height=False):
|
| 515 |
+
with gr.Column():
|
| 516 |
+
gr.Markdown("### **Tingkatkan Resolusi Gambar**\nUnggah gambar untuk meningkatkan kualitas dan ukurannya hingga 4x lipat menggunakan AI.")
|
| 517 |
+
image_to_upscale_input = gr.Image(type="pil", label="Unggah Gambar Anda di Sini")
|
| 518 |
+
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.")
|
| 519 |
+
upscale_btn = gr.Button("Tingkatkan Resolusi!", variant="primary")
|
| 520 |
+
with gr.Column():
|
| 521 |
+
gr.Markdown("### **Hasil Peningkatan Resolusi**")
|
| 522 |
+
upscaled_image_output = gr.Image(label="Gambar Hasil Upscale", interactive=False, show_download_button=True)
|
| 523 |
+
upscale_status_text = gr.Markdown("Status: Menunggu gambar...")
|
| 524 |
+
|
| 525 |
+
# --- TAB 5 (BARU): GALERI & RIWAYAT ---
|
| 526 |
+
with gr.TabItem("πΌοΈ Galeri & Riwayat", id=4):
|
| 527 |
+
with gr.Row(variant='panel'):
|
| 528 |
+
with gr.Column(scale=2):
|
| 529 |
+
gr.Markdown("### **Galeri Hasil Generasi Anda**")
|
| 530 |
+
history_gallery = gr.Gallery(label="Riwayat Gambar", show_label=False, columns=4, object_fit="contain", height="auto")
|
| 531 |
+
history_df_state = gr.State() # State untuk menyimpan dataframe
|
| 532 |
+
with gr.Column(scale=1):
|
| 533 |
+
gr.Markdown("### **Detail & Aksi**")
|
| 534 |
+
history_details_md = gr.Markdown("### β Detail Gambar\nKlik pada sebuah gambar untuk melihat detailnya.")
|
| 535 |
+
refresh_history_btn = gr.Button("π Segarkan Galeri", variant="secondary")
|
| 536 |
+
with gr.Row(visible=False) as history_action_buttons:
|
| 537 |
+
history_to_gen_btn = gr.Button("Kirim ke Generator")
|
| 538 |
+
history_to_editor_btn = gr.Button("Kirim ke Editor")
|
| 539 |
+
|
| 540 |
+
# --- TAB 6 (BARU): IMAGE EDITOR ---
|
| 541 |
+
with gr.TabItem("π¨ Image Editor", id=5):
|
| 542 |
+
with gr.Row(variant='panel'):
|
| 543 |
+
with gr.Column(scale=1):
|
| 544 |
+
gr.Markdown("### **Toolkit Pasca-Produksi**")
|
| 545 |
+
editor_input_image = gr.Image(type="pil", label="Unggah Gambar atau Kirim dari Riwayat")
|
| 546 |
+
with gr.Accordion("Penyesuaian", open=True):
|
| 547 |
+
brightness_slider = gr.Slider(minimum=0.5, maximum=1.5, value=1.0, step=0.05, label="Kecerahan")
|
| 548 |
+
contrast_slider = gr.Slider(minimum=0.5, maximum=1.5, value=1.0, step=0.05, label="Kontras")
|
| 549 |
+
saturation_slider = gr.Slider(minimum=0.0, maximum=2.0, value=1.0, step=0.05, label="Saturasi Warna")
|
| 550 |
+
sharpness_slider = gr.Slider(minimum=0.0, maximum=3.0, value=1.0, step=0.1, label="Ketajaman")
|
| 551 |
+
with gr.Accordion("Filter Cepat", open=True):
|
| 552 |
+
filter_radio = gr.Radio(["None", "Grayscale", "Sepia"], label="Pilih Filter", value="None")
|
| 553 |
+
with gr.Column(scale=1):
|
| 554 |
+
gr.Markdown("### **Hasil Editing**")
|
| 555 |
+
editor_output_image = gr.Image(label="Hasil Akhir", interactive=False, show_download_button=True)
|
| 556 |
+
|
| 557 |
+
# --- TAB 7: VISITOR MONITOR (INTI) ---
|
| 558 |
+
with gr.TabItem("π Visitor Monitor", id=6):
|
| 559 |
+
with gr.Row(variant='panel'):
|
| 560 |
+
with gr.Column():
|
| 561 |
+
gr.Markdown("### π **Live Visitor Monitor**\nPantau jumlah total pengunjung aplikasi Anda secara real-time.")
|
| 562 |
+
with gr.Row():
|
| 563 |
+
with gr.Column(scale=3):
|
| 564 |
+
visitor_count_display = gr.Markdown("## π Memuat data...")
|
| 565 |
+
with gr.Column(scale=2):
|
| 566 |
+
time_filter_radio = gr.Radio(["Semua Waktu", "1 Minggu Terakhir", "2 Minggu Terakhir", "3 Bulan Terakhir"], label="Tampilkan data untuk", value="Semua Waktu")
|
| 567 |
+
refresh_btn = gr.Button("π Segarkan Manual", variant="secondary")
|
| 568 |
+
visitor_plot = gr.LinePlot(x="Timestamp", y="Total Pengunjung", title="Grafik Pertumbuhan Pengunjung", tooltip=['Timestamp', 'Total Pengunjung'], height=500, interactive=True)
|
| 569 |
+
|
| 570 |
+
# --- TAB 8: SYSTEM & SETTINGS (FITUR LAMA) ---
|
| 571 |
+
with gr.TabItem("βοΈ System & Settings", id=7):
|
| 572 |
+
with gr.Row(variant='panel'):
|
| 573 |
+
with gr.Column():
|
| 574 |
+
gr.Markdown("### **Live System Monitor**")
|
| 575 |
+
system_info_md = gr.Markdown("Memuat info sistem...")
|
| 576 |
+
system_info_trigger_btn = gr.Button("Trigger System Info", visible=False, elem_id="system-info-trigger-btn")
|
| 577 |
+
with gr.Column():
|
| 578 |
+
gr.Markdown("### **Pengaturan Aplikasi**")
|
| 579 |
+
with gr.Accordion("Kualitas Model", open=True):
|
| 580 |
+
gr.Radio(["FP16 (Cepat, Kualitas Baik)", "FP32 (Lambat, Kualitas Terbaik)"],
|
| 581 |
+
value="FP16 (Cepat, Kualitas Baik)" if device == "cuda" else "FP32 (Lambat, Kualitas Terbaik)",
|
| 582 |
+
label="Presisi Model Generator",
|
| 583 |
+
interactive=False,
|
| 584 |
+
info="Terkunci. Pengaturan ini ditentukan saat aplikasi dimulai berdasarkan ketersediaan GPU Anda.")
|
| 585 |
+
|
| 586 |
+
# --- TAB-TAB STATIS ---
|
| 587 |
+
with gr.TabItem("π‘ Panduan Prompting", id=8):
|
| 588 |
+
with gr.Row(variant='panel'): gr.Markdown("""## Cara Menjadi "Art Director" yang Hebat untuk AI...\n (Konten panduan Anda di sini)""")
|
| 589 |
+
with gr.TabItem("π Blog & Updates", id=9):
|
| 590 |
+
with gr.Row(variant='panel'): gr.Markdown("""### Perkembangan Terbaru dari RenXploit's AI Suite
|
| 591 |
+
- **v2.5 (Pembaruan Terkini):** Menambahkan **Galeri & Riwayat Generasi** dan **Image Editor** untuk pasca-produksi.
|
| 592 |
+
- **v2.4:** Upscaler di-upgrade dengan kontrol kejernihan, Visitor Monitor diperbaiki, dan UI Settings diperjelas.
|
| 593 |
+
- **v2.3:** Perbaikan bug kritis untuk kompatibilitas dengan berbagai versi Gradio.
|
| 594 |
+
- **v2.2:** Perbaikan bug untuk kompatibilitas Gradio.
|
| 595 |
+
- **v2.1:** Menambahkan **Prompt Enhancer**, **AI Image Upscaler**, dan **Live System Monitor**.
|
| 596 |
+
- **v2.0:** Perombakan Desain Total.
|
| 597 |
+
- **Rencana Berikutnya:** Menjajaki model generator gambar yang berbeda dan fitur Inpainting/Outpainting. Nantikan!""")
|
| 598 |
+
with gr.TabItem("βΉοΈ About & Support", id=10):
|
| 599 |
+
with gr.Row(variant='panel'):
|
| 600 |
+
with gr.Column():
|
| 601 |
+
gr.Markdown("### Tentang Proyek dan Dukungan")
|
| 602 |
+
with gr.Accordion("Tentang RenXploit's Creative AI Suite", open=True):
|
| 603 |
+
gr.Markdown("""
|
| 604 |
+
**RenXploit's Creative AI Suite** adalah proyek pribadi yang dibuat untuk mengeksplorasi kemampuan AI generatif dalam sebuah antarmuka yang mudah digunakan dan profesional.
|
| 605 |
+
Aplikasi ini terus dikembangkan dengan fitur-fitur baru untuk memberdayakan kreativitas Anda.
|
| 606 |
+
|
| 607 |
+
Jika Anda memiliki masukan, menemukan bug, atau ingin berdiskusi, jangan ragu untuk menghubungi saya melalui website portofolio di: **[ngoprek.xyz/contact](https://ngoprek.xyz/contact)**
|
| 608 |
+
""")
|
| 609 |
+
with gr.Accordion("Laporkan Masalah atau Beri Masukan"):
|
| 610 |
+
report_name = gr.Textbox(label="Nama Anda")
|
| 611 |
+
report_email = gr.Textbox(label="Email Anda (Opsional)")
|
| 612 |
+
report_message = gr.Textbox(label="Pesan Anda", lines=5, placeholder="Jelaskan masalah yang Anda temui atau ide yang Anda miliki...")
|
| 613 |
+
report_btn = gr.Button("Kirim Laporan", variant="primary")
|
| 614 |
+
report_status = gr.Markdown(visible=False)
|
| 615 |
+
|
| 616 |
+
gr.Markdown("---\n<div class='footer'><p>Dibuat dengan β€οΈ oleh <b>RenXploit</b>.</p></div>", elem_classes="footer")
|
| 617 |
+
|
| 618 |
+
# --- PENANGANAN EVENT (EVENT HANDLERS) ---
|
| 619 |
+
# 1. Event Inti (Generator & Laporan)
|
| 620 |
+
random_seed_btn.click(lambda: -1, outputs=seed_input)
|
| 621 |
+
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])
|
| 622 |
+
report_btn.click(fn=submit_report, inputs=[report_name, report_email, report_message], outputs=[report_status])
|
| 623 |
+
|
| 624 |
+
# 2. Event Visitor Monitor
|
| 625 |
+
demo.load(log_visitor, inputs=None, outputs=None)
|
| 626 |
+
demo.load(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
|
| 627 |
+
refresh_btn.click(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
|
| 628 |
+
time_filter_radio.change(fn=update_visitor_monitor, inputs=[time_filter_radio], outputs=[visitor_count_display, visitor_plot])
|
| 629 |
+
|
| 630 |
+
# 3. Event Fitur Lainnya (Prompt Enhancer, Upscaler, System)
|
| 631 |
+
enhance_btn.click(fn=enhance_prompt, inputs=[simple_prompt_input], outputs=[enhanced_prompt_output])
|
| 632 |
+
send_to_gen_btn.click(fn=lambda prompt: (prompt, gr.Tabs(selected=0)), inputs=[enhanced_prompt_output], outputs=[prompt_input, tabs])
|
| 633 |
+
upscale_btn.click(fn=upscale_image, inputs=[image_to_upscale_input, clarity_slider], outputs=[upscaled_image_output, upscale_status_text])
|
| 634 |
+
|
| 635 |
+
system_info_trigger_btn.click(fn=update_system_info, inputs=None, outputs=system_info_md)
|
| 636 |
+
demo.load(fn=update_system_info, inputs=None, outputs=system_info_md)
|
| 637 |
+
|
| 638 |
+
# 4. Event untuk Fitur BARU (Galeri & Editor)
|
| 639 |
+
|
| 640 |
+
# Galeri & Riwayat
|
| 641 |
+
# Memuat riwayat saat tab dipilih atau tombol refresh diklik
|
| 642 |
+
history_tab = demo.tabs[4]
|
| 643 |
+
history_tab.select(fn=load_history, inputs=None, outputs=[history_gallery, history_df_state, history_details_md])
|
| 644 |
+
refresh_history_btn.click(fn=load_history, inputs=None, outputs=[history_gallery, history_df_state, history_details_md])
|
| 645 |
+
|
| 646 |
+
# Menampilkan detail saat gambar di galeri dipilih
|
| 647 |
+
history_gallery.select(fn=show_history_details, inputs=[history_df_state], outputs=[history_details_md, history_action_buttons])
|
| 648 |
+
|
| 649 |
+
# Aksi dari tombol di detail riwayat
|
| 650 |
+
history_to_gen_btn.click(
|
| 651 |
+
fn=send_history_to_generator,
|
| 652 |
+
inputs=[history_df_state],
|
| 653 |
+
outputs=[prompt_input, negative_prompt_input, seed_input, steps_slider, tabs]
|
| 654 |
+
)
|
| 655 |
+
history_to_editor_btn.click(
|
| 656 |
+
fn=send_history_to_editor,
|
| 657 |
+
inputs=[history_df_state],
|
| 658 |
+
outputs=[editor_input_image, tabs]
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# Image Editor
|
| 662 |
+
editor_inputs = [editor_input_image, brightness_slider, contrast_slider, saturation_slider, sharpness_slider, filter_radio]
|
| 663 |
+
brightness_slider.release(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 664 |
+
contrast_slider.release(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 665 |
+
saturation_slider.release(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 666 |
+
sharpness_slider.release(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 667 |
+
filter_radio.change(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 668 |
+
editor_input_image.change(fn=apply_image_edits, inputs=editor_inputs, outputs=editor_output_image)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
# --- Menjalankan Aplikasi ---
|
| 672 |
+
if __name__ == "__main__":
|
| 673 |
+
demo.launch(debug=True)
|