Spaces:
Sleeping
Sleeping
File size: 8,256 Bytes
7594e45 cae1719 7594e45 |
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 |
import gradio as gr
import torch
import numpy as np
from diffusers import DiffusionPipeline
import random
import time
import os
try:
import google.generativeai as genai
print("β
Library 'google-generativeai' berhasil diimpor.")
except ImportError:
print("β Peringatan: Library 'google-generativeai' tidak ditemukan.")
genai = None
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. Sistem rotasi aktif.")
self.is_configured = True
else:
print("β PERINGATAN: Tidak ada API Key Gemini yang ditemukan di Secrets.")
def chat(self, message, history):
if not self.is_configured: return "Maaf, chatbot tidak terkonfigurasi."
try:
selected_key = random.choice(self.api_keys)
genai.configure(api_key=selected_key)
model = genai.GenerativeModel('gemini-2.5-flash')
chat_session = model.start_chat(history=[])
response = chat_session.send_message(message)
return response.text
except Exception as e:
print(f"β Terjadi error pada salah satu API Key: {e}")
return "Terjadi kesalahan saat menghubungi API Gemini. Silakan coba lagi."
gemini_bot = GeminiChat()
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"β‘οΈ Menggunakan device untuk generator gambar: {device.upper()}")
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()
def generate_images(prompt, negative_prompt, steps, seed, num_images):
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()
for i in range(20): # Loop singkat untuk animasi awal
elapsed_time = time.time() - start_time
loader_html_content = f"""
<div class="loader-container">
<div class="loader-bar"></div>
<p class="loader-text">Mempersiapkan model... Waktu berlalu: {elapsed_time:.2f} detik</p>
</div>
"""
yield gr.update(), gr.update(value=loader_html_content), gr.update(), gr.update()
time.sleep(0.1) # Jeda kecil untuk membuat animasi terlihat
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):
print(f"Laporan Diterima:\nNama: {name}\nEmail: {email}\nPesan: {message}")
return gr.update(value="β
Terima kasih! Laporan Anda telah kami terima.", visible=True)
CUSTOM_CSS = """
.loader-container { border: 1px solid #333; border-radius: 8px; padding: 20px; background-color: #1a1a1a; text-align: center; overflow: hidden; position: relative; }
.loader-text { font-family: 'monospace'; font-size: 1.1em; color: #00ff99; text-shadow: 0 0 5px #00ff99; }
.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; }
@keyframes scan { 0% { left: -10%; } 100% { left: 100%; } }
.footer { text-align: center; margin: 2rem auto; }
"""
with gr.Blocks(theme=gr.themes.Monochrome(), css=CUSTOM_CSS) as demo:
gr.Markdown("# π RenXploit's Creative AI Suite π\nSebuah platform lengkap untuk kreativitas Anda, ditenagai oleh AI.")
with gr.Tabs():
with gr.TabItem("π¨ Image Generator", id=0):
with gr.Row(variant='panel'):
with gr.Column(scale=1):
gr.Markdown("### π Masukkan Perintah Anda")
prompt_input = gr.Textbox(label="Prompt", placeholder="Contoh: Cinematic photo, seekor rubah merah...", lines=3, info="Jadilah sangat spesifik! Semakin detail, semakin akurat hasilnya.")
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.")
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")
with gr.Row():
seed_input = gr.Number(label="Seed", value=-1, precision=0, info="Gunakan -1 untuk acak.")
random_seed_btn = gr.Button("π² Acak")
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)
with gr.TabItem("π‘ Panduan Prompting", id=1):
gr.Markdown("## Cara Menjadi \"Art Director\" yang Hebat untuk AI\n...")
with gr.TabItem("π¬ Chat with AI", id=2):
gr.Markdown("### π€ Asisten AI Flood\nTanyakan apa saja!")
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, bubble_full_width=False, value=[[None, "Halo! Saya adalah asisten AI dari RenXploit. Ada yang bisa saya bantu?"]]))
with gr.TabItem("π Blog & Updates", id=3):
gr.Markdown("### Perkembangan Terbaru dari RenXploit's AI Suite\n...")
with gr.TabItem("βΉοΈ About & Support", id=4):
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 ...")
with gr.Accordion("Laporkan Masalah atau Beri Masukan"):
report_name = gr.Textbox(label="Nama Anda")
report_email = gr.Textbox(label="Email Anda")
report_message = gr.Textbox(label="Pesan Anda", lines=5)
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")
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])
demo.launch()
|