File size: 13,633 Bytes
1ffeac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from llm_inference import LLMInferenceNode
import random
from PIL import Image
import io
from themes import IndonesiaTheme  # Pastikan tema ini telah dibuat atau diimpor dengan benar

# Judul aplikasi dalam bentuk HTML
title = """<h1 align="center">💡 Smart Idea Generator 💡</h1>
<p><center>
<a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
<a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
<p align="center">Generate random prompts using powerful LLMs from Hugging Face, Groq, and SambaNova.</p>
</center></p>
"""

# Judul aplikasi dalam bentuk HTML
Footer = """
<p><center>
<a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
<a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
</center></p>
"""

# Fungsi utama untuk membuat antarmuka Gradio
def create_interface():
    llm_node = LLMInferenceNode()  # Node untuk inferensi LLM

    # CSS untuk styling antarmuka
    css = """
    #col-left, #col-mid {
        margin: 20px auto; /* Margin lebih besar untuk pemisahan */
        max-width: 400px;
        padding: 20px; /* Padding lebih besar */
        border-radius: 15px;
        background-color: #ffffff; /* Background blok putih untuk kontras */
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1); /* Bayangan lembut */
        transition: transform 0.2s ease-in-out; /* Animasi saat hover */
    }

    #col-left:hover, #col-mid:hover {
        transform: translateY(-5px); /* Efek naik saat dihover */
    }

    #col-right {
        margin: 20px auto; /* Margin lebih besar untuk pemisahan */
        max-width: 400px;
        padding: 20px; /* Padding lebih besar */
        border-radius: 15px;
        background: linear-gradient(180deg, #0077b6, #0096c7); /* Gradasi biru cerah */
        color: white; /* Teks putih untuk kontras */
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s ease-in-out;
    }

    #col-right:hover {
        transform: translateY(-5px);
    }

    #col-bott {
        margin: 20px auto; /* Margin lebih besar */
        padding: 20px; /* Padding lebih besar */
        border-radius: 15px;
        background-color: rgba(255, 255, 255, 0.85); /* Warna blok transparan */
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
    }

    #banner {
        width: 100%;
        text-align: center;
        margin-bottom: 20px;
        font-weight: 600; /* Lebih tebal */
        color: #0077b6; /* Biru sesuai tema */
    }

    #run-button, #generate-image-button {
        font-weight: bold;
        padding: 15px 30px; /* Padding lebih besar */
        border-radius: 15px;
        cursor: pointer;
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2); /* Bayangan lebih besar */
        transition: all 0.4s ease-in-out; /* Menambahkan animasi untuk semua properti */
    }

    #run-button {
        background-color: #0096c7;
        color: white;
    }

    #run-button:hover {
        background-color: #00b4d8; /* Lebih terang saat hover */
        transform: translateY(-5px); /* Tombol sedikit naik saat hover */
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); /* Bayangan lebih besar saat hover */
    }

    #generate-image-button {
        background-color: #ff69b4; /* Warna pink */
        color: white; /* Teks putih */
    }

    #generate-image-button:hover {
        background-color: #ff85c8; /* Pink lebih terang saat hover */
        transform: translateY(-5px) scale(1.05); /* Membuat tombol sedikit lebih besar dan naik saat hover */
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); /* Bayangan lebih besar saat hover */
    }

    #footer {
        text-align: center;
        margin-top: 20px;
        color: #000; /* Warna netral abu-abu */
        font-style: italic;
    }

    #markdown-silver {
        color: #7a7a7a; /* Mengatur warna font Markdown ke abu-abu netral */
    }

    /* Efek untuk elemen saat difokuskan */
    #col-left:focus, #col-mid:focus, #col-right:focus, #run-button:focus, #generate-image-button:focus {
        outline: 2px solid #0096c7; /* Border biru muda saat fokus */
        outline-offset: 3px;
    }

    /* Responsif untuk perangkat mobile */
    @media (max-width: 768px) {
        #col-left, #col-mid, #col-right {
            max-width: 100%; /* Membuat kolom memenuhi lebar layar */
        }
        #run-button, #generate-image-button {
            width: 100%; /* Tombol menjadi lebar penuh */
            margin-top: 10px; /* Menambahkan margin atas */
        }
    }
    """

    # Membuat antarmuka Gradio dengan tema IndonesiaTheme dan CSS
    with gr.Blocks(theme=IndonesiaTheme(), css=css) as RandomPromptApp:
        
        gr.HTML(title)  # Tampilkan judul aplikasi

        # Baris pertama: Input prompt dan tipe prompt
        with gr.Row():
            with gr.Column(scale=2):
                # Textbox untuk input custom prompt dengan placeholder
                custom = gr.Textbox(
                    label="➡️ Custom Input Prompt (optional)", 
                    lines=3,
                    placeholder="Tulis prompt Anda di sini atau biarkan kosong untuk prompt acak."
                )

                # Dropdown untuk memilih tipe prompt
                prompt_types = ["Random", "Long", "Short", "Medium", "OnlyObjects", "NoFigure", "Landscape", "Fantasy"]
                prompt_type = gr.Dropdown(
                    choices=prompt_types,
                    label="Prompt Type",
                    value="Random",
                    interactive=True
                )
                
                # Menyimpan tipe prompt yang dipilih dalam sebuah State
                prompt_type_state = gr.State("Random")

                # Fungsi untuk mengupdate tipe prompt ketika "Random" dipilih
                def update_prompt_type(value, state):
                    if value == "Random":
                        new_value = random.choice([t for t in prompt_types if t != "Random"])
                        print(f"[-] Random prompt type selected: {new_value}")
                        return value, new_value
                    print(f"[-] Updated prompt type: {value}")
                    return value, value
                
                # Menghubungkan dropdown tipe prompt dengan fungsi update
                prompt_type.change(update_prompt_type, inputs=[prompt_type, prompt_type_state], outputs=[prompt_type, prompt_type_state])

            with gr.Column(scale=2):
                # Accordion untuk parameter terkait generasi prompt LLM
                with gr.Accordion("➡️ LLM Prompt Generation", open=False):
                    long_talk = gr.Checkbox(label="Long Talk", value=True)
                    compress = gr.Checkbox(label="Compress", value=True)
                    compression_level = gr.Dropdown(
                        choices=["soft", "medium", "hard"],
                        label="Compression Level",
                        value="hard"
                    )
                    custom_base_prompt = gr.Textbox(label="➡️ Custom Base Prompt", lines=5)

                # Dropdown untuk memilih provider LLM
                llm_provider = gr.Dropdown(
                    choices=["Hugging Face", "Groq", "SambaNova"],
                    label="LLM Provider",
                    value="Groq"
                )
                # Textbox untuk API key (disembunyikan)
                api_key = gr.Textbox(label="API Key", type="password", visible=False)
                # Dropdown untuk memilih model LLM
                model = gr.Dropdown(label="Model", choices=["llama-3.1-70b-versatile", "mixtral-8x7b-32768", "llama-3.2-90b-text-preview"], value="llama-3.2-90b-text-preview")
        
        with gr.Row():
            # Tombol untuk mengenerate prompt dan teks
            generate_button = gr.Button("✅ Generate Prompt", elem_id="run-button")
        
        with gr.Row():
            # Output teks hasil generasi LLM dan gambar yang dihasilkan
            text_output = gr.Textbox(label="➡️ LLM Generated Text", lines=10, show_copy_button=True)
            image_output = gr.Image(label="➡️ Generated Image", type="filepath")

        with gr.Row():
            # Tambahkan footer di bagian bawah
            gr.HTML("""
                <footer id="footer">
                Transfer Energi Semesta Digital © 2024 __drat. | 🇮🇩 Untuk Indonesia Jaya!
                </footer>
                """)

        # Fungsi untuk mengupdate model LLM berdasarkan provider yang dipilih
        def update_model_choices(provider):
            provider_models = {
                "Hugging Face": [
                    "Qwen/Qwen2.5-72B-Instruct",
                    "meta-llama/Meta-Llama-3.1-70B-Instruct",
                    "mistralai/Mixtral-8x7B-Instruct-v0.1",
                    "mistralai/Mistral-7B-Instruct-v0.3"
                ],
                "Groq": [
                    "llama-3.1-70b-versatile",
                    "mixtral-8x7b-32768",
                    "llama-3.2-90b-text-preview"
                ],
                "SambaNova": [
                    "Meta-Llama-3.1-70B-Instruct",
                    "Meta-Llama-3.1-405B-Instruct",
                    "Meta-Llama-3.1-8B-Instruct"
                ],
            }
            models = provider_models.get(provider, [])
            return gr.Dropdown(choices=models, value=models[0] if models else "")
        
        # Fungsi untuk menyembunyikan textbox API key jika tidak dibutuhkan
        def update_api_key_visibility(provider):
            return gr.update(visible=False)  # API key tidak dibutuhkan untuk provider yang dipilih

        # Menghubungkan perubahan provider LLM dengan fungsi untuk mengupdate model dan visibilitas API key
        llm_provider.change(
            update_model_choices, 
            inputs=[llm_provider], 
            outputs=[model]
        )
        llm_provider.change(
            update_api_key_visibility, 
            inputs=[llm_provider], 
            outputs=[api_key]
        )

        # Fungsi untuk mengenerate prompt dan teks dengan LLM
        def generate_random_prompt_with_llm(custom_input, prompt_type, long_talk, compress, compression_level, custom_base_prompt, provider, api_key, model_selected, prompt_type_state):
            try:
                # Langkah 1: Mengenerate prompt
                dynamic_seed = random.randint(0, 1000000)
                
                # Jika prompt_type adalah "Random", pilih tipe prompt acak
                if prompt_type == "Random":
                    prompt_type = random.choice([t for t in prompt_types if t != "Random"])
                    print(f"[-] Random prompt type selected: {prompt_type}")
                
                # Jika ada custom input, gunakan sebagai prompt
                if custom_input and custom_input.strip():
                    prompt = llm_node.generate_prompt(dynamic_seed, prompt_type, custom_input)
                    print(f"[-] Using Custom Input Prompt.")
                else:
                    prompt = llm_node.generate_prompt(dynamic_seed, prompt_type, f"Create a random prompt based on the '{prompt_type}' type.")
                    print(f"[-] No Custom Input Prompt provided. Generated prompt based on prompt_type: {prompt_type}")

                print(f"[-] Generated Prompt: {prompt}")

                # Langkah 2: Mengenerate teks dengan LLM
                poster = False  # Nilai default
                result = llm_node.generate(
                    input_text=prompt,
                    long_talk=long_talk,
                    compress=compress,
                    compression_level=compression_level,
                    poster=poster,
                    prompt_type=prompt_type,
                    custom_base_prompt=custom_base_prompt,
                    provider=provider,
                    api_key=api_key,
                    model=model_selected
                )
                print(f"Generated Text: {result}")

                return result

            except Exception as e:
                print(f"[-] An error occurred: {e}")
                return f"[-] Error occurred while processing the request: {str(e)}"

        # Menghubungkan tombol generate dengan fungsi untuk mengenerate prompt dan teks
        generate_button.click(
            generate_random_prompt_with_llm,
            inputs=[custom, prompt_type, long_talk, compress, compression_level, custom_base_prompt, llm_provider, api_key, model, prompt_type_state],
            outputs=[text_output],
            api_name="generate_random_prompt_with_llm"
        )

        # Tambahkan tombol untuk mengenerate gambar
        generate_image_button = gr.Button("🔥 Generate Image", elem_id="generate-image-button")

        # Fungsi untuk mengenerate gambar
        def generate_image(text):
            try:
                seed = random.randint(0, 1000000)
                image_path = llm_node.generate_image(text, seed=seed)
                print(f"[-] Image generated: {image_path}")
                return image_path
            except Exception as e:
                print(f"[-] An error occurred while generating the image: {e}")
                return None

        # Menghubungkan tombol generate gambar dengan fungsi untuk mengenerate gambar
        generate_image_button.click(
            generate_image,
            inputs=[text_output],
            outputs=[image_output]
        )

    return RandomPromptApp

# Meluncurkan aplikasi Gradio
if __name__ == "__main__":
    RandomPromptApp = create_interface()
    RandomPromptApp.launch()