File size: 39,211 Bytes
7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e c41d113 7919c5e |
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 |
# -- 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
from pathlib import Path # Ditambahkan untuk manajemen path yang lebih baik
# --- 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) ---
# (Tidak ada perubahan pada HEAD_HTML & CSS, tetap sama seperti yang Anda berikan)
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 { 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"
HISTORY_LOG_FILE = "generation_log.csv"
IMAGE_HISTORY_DIR = Path("generated_images")
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)
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 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, 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" # Add seed to filename
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)
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:
return "## π 0", pd.DataFrame({"Timestamp": [], "Total Pengunjung": []})
df = pd.read_csv(VISITOR_LOG_FILE)
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 = 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
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:
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}`\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}")
# --- FUNGSI-FUNGSI UNTUK MENU BARU ---
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 pada sebuah gambar untuk melihat detailnya.", gr.update(visible=False)
selected_row = history_df.iloc[evt.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)
def send_history_to_generator(evt: gr.SelectData, history_df: pd.DataFrame):
if not evt.selected or history_df.empty:
return gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
selected_row = history_df.iloc[evt.index]
return (
selected_row['Prompt'],
selected_row.get('NegativePrompt', ''),
selected_row['Seed'],
selected_row['Steps'],
gr.Tabs(selected=0)
)
def send_history_to_editor(evt: gr.SelectData, history_df: pd.DataFrame):
if not evt.selected or history_df.empty:
return gr.update(), gr.update()
selected_row = history_df.iloc[evt.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
# --- 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 ---
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")
# --- TAB 4: AI IMAGE UPSCALER ---
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...")
# --- TAB 5 (BARU): GALERI & RIWAYAT (DENGAN PERBAIKAN) ---
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")
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")
# --- TAB 6 (BARU): IMAGE EDITOR ---
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)
# --- TAB 7: VISITOR MONITOR ---
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)
# --- TAB 8: SYSTEM & SETTINGS ---
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. Pengaturan ini ditentukan saat aplikasi dimulai berdasarkan ketersediaan GPU Anda.")
# --- TAB-TAB STATIS ---
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
- **v2.5 (Pembaruan Terkini):** Menambahkan **Galeri & Riwayat Generasi** dan **Image Editor** untuk pasca-produksi.
- **v2.4:** Upscaler di-upgrade dengan kontrol kejernihan, Visitor Monitor diperbaiki, dan UI Settings diperjelas.
- **v2.3:** Perbaikan bug kritis untuk kompatibilitas dengan berbagai versi Gradio.
- **v2.2:** Perbaikan bug untuk kompatibilitas Gradio.
- **v2.1:** Menambahkan **Prompt Enhancer**, **AI Image Upscaler**, dan **Live System Monitor**.
- **v2.0:** Perombakan Desain Total.
- **Rencana Berikutnya:** Menjajaki model generator gambar yang berbeda dan fitur Inpainting/Outpainting. Nantikan!""")
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 yang dibuat untuk mengeksplorasi kemampuan AI generatif dalam sebuah antarmuka yang mudah digunakan dan profesional.
Aplikasi ini terus dikembangkan dengan fitur-fitur baru untuk memberdayakan kreativitas Anda.
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)**
""")
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 Lainnya
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])
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)
# 4. Event untuk Fitur BARU (Galeri & Editor)
# Galeri & Riwayat
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])
history_to_gen_btn.click(fn=send_history_to_generator, inputs=[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=[history_df_state], outputs=[editor_input_image, tabs])
# Image Editor
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)
# --- Menjalankan Aplikasi ---
if __name__ == "__main__":
demo.launch(debug=True) |