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r
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
from diffusers import DiffusionPipeline
|
| 6 |
+
import random
|
| 7 |
+
import time
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
import google.generativeai as genai
|
| 12 |
+
print("✅ Library 'google-generativeai' berhasil diimpor.")
|
| 13 |
+
except ImportError:
|
| 14 |
+
print("❌ Peringatan: Library 'google-generativeai' tidak ditemukan.")
|
| 15 |
+
genai = None
|
| 16 |
+
|
| 17 |
+
class GeminiChat:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.api_keys = []
|
| 20 |
+
self.is_configured = False
|
| 21 |
+
if not genai: return
|
| 22 |
+
i = 1
|
| 23 |
+
while True:
|
| 24 |
+
key = os.getenv(f"GEMINI_API_KEY_{i}")
|
| 25 |
+
if key: self.api_keys.append(key); i += 1
|
| 26 |
+
else: break
|
| 27 |
+
if self.api_keys:
|
| 28 |
+
print(f"✅ Berhasil memuat {len(self.api_keys)} API Key. Sistem rotasi aktif.")
|
| 29 |
+
self.is_configured = True
|
| 30 |
+
else:
|
| 31 |
+
print("❌ PERINGATAN: Tidak ada API Key Gemini yang ditemukan di Secrets.")
|
| 32 |
+
|
| 33 |
+
def chat(self, message, history):
|
| 34 |
+
if not self.is_configured: return "Maaf, chatbot tidak terkonfigurasi."
|
| 35 |
+
try:
|
| 36 |
+
selected_key = random.choice(self.api_keys)
|
| 37 |
+
genai.configure(api_key=selected_key)
|
| 38 |
+
model = genai.GenerativeModel('gemini-2.5-flash')
|
| 39 |
+
chat_session = model.start_chat(history=[])
|
| 40 |
+
response = chat_session.send_message(message)
|
| 41 |
+
return response.text
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"❌ Terjadi error pada salah satu API Key: {e}")
|
| 44 |
+
return "Terjadi kesalahan saat menghubungi API Gemini. Silakan coba lagi."
|
| 45 |
+
|
| 46 |
+
gemini_bot = GeminiChat()
|
| 47 |
+
|
| 48 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 49 |
+
print(f"➡️ Menggunakan device untuk generator gambar: {device.upper()}")
|
| 50 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 51 |
+
"stabilityai/sdxl-turbo", torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 52 |
+
variant="fp16" if device == "cuda" else None, use_safetensors=True
|
| 53 |
+
).to(device)
|
| 54 |
+
if torch.cuda.is_available(): pipe.enable_xformers_memory_efficient_attention()
|
| 55 |
+
|
| 56 |
+
def generate_images(prompt, negative_prompt, steps, seed, num_images):
|
| 57 |
+
if seed == -1: seed = random.randint(0, 2**32 - 1)
|
| 58 |
+
generator = torch.manual_seed(seed)
|
| 59 |
+
images = pipe(
|
| 60 |
+
prompt=prompt, negative_prompt=negative_prompt, generator=generator,
|
| 61 |
+
num_inference_steps=steps, guidance_scale=0.0, num_images_per_prompt=num_images
|
| 62 |
+
).images
|
| 63 |
+
return images, seed
|
| 64 |
+
|
| 65 |
+
def genie_wrapper(prompt, negative_prompt, steps, seed, num_images):
|
| 66 |
+
yield gr.update(visible=False), gr.update(visible=True), gr.update(interactive=False), gr.update(visible=False)
|
| 67 |
+
|
| 68 |
+
start_time = time.time()
|
| 69 |
+
|
| 70 |
+
for i in range(20): # Loop singkat untuk animasi awal
|
| 71 |
+
elapsed_time = time.time() - start_time
|
| 72 |
+
loader_html_content = f"""
|
| 73 |
+
<div class="loader-container">
|
| 74 |
+
<div class="loader-bar"></div>
|
| 75 |
+
<p class="loader-text">Mempersiapkan model... Waktu berlalu: {elapsed_time:.2f} detik</p>
|
| 76 |
+
</div>
|
| 77 |
+
"""
|
| 78 |
+
yield gr.update(), gr.update(value=loader_html_content), gr.update(), gr.update()
|
| 79 |
+
time.sleep(0.1) # Jeda kecil untuk membuat animasi terlihat
|
| 80 |
+
|
| 81 |
+
images, used_seed = generate_images(prompt, negative_prompt, steps, int(seed), int(num_images))
|
| 82 |
+
end_time = time.time()
|
| 83 |
+
|
| 84 |
+
generation_time = end_time - start_time
|
| 85 |
+
info_text = f"Seed yang digunakan: {used_seed}\nTotal waktu generasi: {generation_time:.2f} detik"
|
| 86 |
+
|
| 87 |
+
yield gr.update(value=images, visible=True), gr.update(visible=False), gr.update(interactive=True), gr.update(value=info_text, visible=True)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def submit_report(name, email, message):
|
| 91 |
+
print(f"Laporan Diterima:\nNama: {name}\nEmail: {email}\nPesan: {message}")
|
| 92 |
+
return gr.update(value="✅ Terima kasih! Laporan Anda telah kami terima.", visible=True)
|
| 93 |
+
|
| 94 |
+
CUSTOM_CSS = """
|
| 95 |
+
.loader-container { border: 1px solid #333; border-radius: 8px; padding: 20px; background-color: #1a1a1a; text-align: center; overflow: hidden; position: relative; }
|
| 96 |
+
.loader-text { font-family: 'monospace'; font-size: 1.1em; color: #00ff99; text-shadow: 0 0 5px #00ff99; }
|
| 97 |
+
.loader-bar { position: absolute; top: 0; left: -10%; width: 10%; height: 100%; background: linear-gradient(90deg, transparent, rgba(0, 255, 153, 0.5), transparent); animation: scan 2s linear infinite; }
|
| 98 |
+
@keyframes scan { 0% { left: -10%; } 100% { left: 100%; } }
|
| 99 |
+
.footer { text-align: center; margin: 2rem auto; }
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
with gr.Blocks(theme=gr.themes.Monochrome(), css=CUSTOM_CSS) as demo:
|
| 103 |
+
gr.Markdown("# 🚀 RenXploit's Creative AI Suite 🌌\nSebuah platform lengkap untuk kreativitas Anda, ditenagai oleh AI.")
|
| 104 |
+
|
| 105 |
+
with gr.Tabs():
|
| 106 |
+
with gr.TabItem("🎨 Image Generator", id=0):
|
| 107 |
+
with gr.Row(variant='panel'):
|
| 108 |
+
with gr.Column(scale=1):
|
| 109 |
+
gr.Markdown("### 📝 Masukkan Perintah Anda")
|
| 110 |
+
prompt_input = gr.Textbox(label="Prompt", placeholder="Contoh: Cinematic photo, seekor rubah merah...", lines=3, info="Jadilah sangat spesifik! Semakin detail, semakin akurat hasilnya.")
|
| 111 |
+
negative_prompt_input = gr.Textbox(label="Prompt Negatif", placeholder="Contoh: blurry, low quality...", lines=2, info="Masukkan hal-hal yang TIDAK Anda inginkan di gambar.")
|
| 112 |
+
num_images_slider = gr.Slider(minimum=1, maximum=8, value=2, step=1, label="Jumlah Gambar")
|
| 113 |
+
generate_btn = gr.Button("✨ Hasilkan Gambar!", variant="primary")
|
| 114 |
+
with gr.Accordion("⚙️ Opsi Lanjutan", open=False):
|
| 115 |
+
steps_slider = gr.Slider(minimum=1, maximum=5, value=2, step=1, label="Langkah Iterasi")
|
| 116 |
+
with gr.Row():
|
| 117 |
+
seed_input = gr.Number(label="Seed", value=-1, precision=0, info="Gunakan -1 untuk acak.")
|
| 118 |
+
random_seed_btn = gr.Button("🎲 Acak")
|
| 119 |
+
with gr.Column(scale=2):
|
| 120 |
+
gr.Markdown("### 🖼️ Hasil Generasi")
|
| 121 |
+
output_gallery = gr.Gallery(label="Hasil Gambar", show_label=False, elem_id="gallery", columns=2, object_fit="contain", height="auto")
|
| 122 |
+
loader_html = gr.HTML(visible=False)
|
| 123 |
+
info_box = gr.Textbox(label="Informasi Generasi", visible=False, interactive=False)
|
| 124 |
+
|
| 125 |
+
with gr.TabItem("💡 Panduan Prompting", id=1):
|
| 126 |
+
gr.Markdown("## Cara Menjadi \"Art Director\" yang Hebat untuk AI\n...")
|
| 127 |
+
with gr.TabItem("💬 Chat with AI", id=2):
|
| 128 |
+
gr.Markdown("### 🤖 Asisten AI Flood\nTanyakan apa saja!")
|
| 129 |
+
if not gemini_bot.is_configured:
|
| 130 |
+
gr.Warning("Fitur Chatbot dinonaktifkan. API Key Gemini tidak terkonfigurasi.")
|
| 131 |
+
else:
|
| 132 |
+
gr.ChatInterface(gemini_bot.chat, chatbot=gr.Chatbot(height=500, bubble_full_width=False, value=[[None, "Halo! Saya adalah asisten AI dari RenXploit. Ada yang bisa saya bantu?"]]))
|
| 133 |
+
with gr.TabItem("📖 Blog & Updates", id=3):
|
| 134 |
+
gr.Markdown("### Perkembangan Terbaru dari RenXploit's AI Suite\n...")
|
| 135 |
+
with gr.TabItem("ℹ️ About & Support", id=4):
|
| 136 |
+
gr.Markdown("### Tentang Proyek dan Dukungan")
|
| 137 |
+
with gr.Accordion("Tentang RenXploit's Creative AI Suite", open=True):
|
| 138 |
+
gr.Markdown("**RenXploit's Creative AI Suite** adalah ...")
|
| 139 |
+
with gr.Accordion("Laporkan Masalah atau Beri Masukan"):
|
| 140 |
+
report_name = gr.Textbox(label="Nama Anda")
|
| 141 |
+
report_email = gr.Textbox(label="Email Anda")
|
| 142 |
+
report_message = gr.Textbox(label="Pesan Anda", lines=5)
|
| 143 |
+
report_btn = gr.Button("Kirim Laporan", variant="primary")
|
| 144 |
+
report_status = gr.Markdown(visible=False)
|
| 145 |
+
|
| 146 |
+
gr.Markdown("---\n<div class='footer'><p>Dibuat dengan ❤️ oleh <a href="https://ngoprek.xyz">RenXploit</a>.</div>", elem_classes="footer")
|
| 147 |
+
|
| 148 |
+
random_seed_btn.click(lambda: -1, outputs=seed_input)
|
| 149 |
+
generate_btn.click(
|
| 150 |
+
fn=genie_wrapper,
|
| 151 |
+
inputs=[prompt_input, negative_prompt_input, steps_slider, seed_input, num_images_slider],
|
| 152 |
+
outputs=[output_gallery, loader_html, generate_btn, info_box]
|
| 153 |
+
)
|
| 154 |
+
report_btn.click(fn=submit_report, inputs=[report_name, report_email, report_message], outputs=[report_status])
|
| 155 |
+
|
| 156 |
+
demo.launch()
|