Spaces:
Running
Running
Upload 4 files
Browse files- app.py +331 -0
- llm_inference.py +260 -0
- requirements.txt +2 -0
- themes.py +55 -0
app.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from llm_inference import LLMInferenceNode
|
3 |
+
import random
|
4 |
+
from PIL import Image
|
5 |
+
import io
|
6 |
+
from themes import IndonesiaTheme # Pastikan tema ini telah dibuat atau diimpor dengan benar
|
7 |
+
|
8 |
+
# Judul aplikasi dalam bentuk HTML
|
9 |
+
title = """<h1 align="center">💡 Smart Idea Generator 💡</h1>
|
10 |
+
<p><center>
|
11 |
+
<a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
|
12 |
+
<a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
|
13 |
+
<p align="center">Generate random prompts using powerful LLMs from Hugging Face, Groq, and SambaNova.</p>
|
14 |
+
</center></p>
|
15 |
+
"""
|
16 |
+
|
17 |
+
# Judul aplikasi dalam bentuk HTML
|
18 |
+
Footer = """
|
19 |
+
<p><center>
|
20 |
+
<a href="https://x.com/gokayfem" target="_blank">[X gokaygokay]</a>
|
21 |
+
<a href="https://github.com/gokayfem" target="_blank">[Github gokayfem]</a>
|
22 |
+
</center></p>
|
23 |
+
"""
|
24 |
+
|
25 |
+
# Fungsi utama untuk membuat antarmuka Gradio
|
26 |
+
def create_interface():
|
27 |
+
llm_node = LLMInferenceNode() # Node untuk inferensi LLM
|
28 |
+
|
29 |
+
# CSS untuk styling antarmuka
|
30 |
+
css = """
|
31 |
+
#col-left, #col-mid {
|
32 |
+
margin: 20px auto; /* Margin lebih besar untuk pemisahan */
|
33 |
+
max-width: 400px;
|
34 |
+
padding: 20px; /* Padding lebih besar */
|
35 |
+
border-radius: 15px;
|
36 |
+
background-color: #ffffff; /* Background blok putih untuk kontras */
|
37 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1); /* Bayangan lembut */
|
38 |
+
transition: transform 0.2s ease-in-out; /* Animasi saat hover */
|
39 |
+
}
|
40 |
+
|
41 |
+
#col-left:hover, #col-mid:hover {
|
42 |
+
transform: translateY(-5px); /* Efek naik saat dihover */
|
43 |
+
}
|
44 |
+
|
45 |
+
#col-right {
|
46 |
+
margin: 20px auto; /* Margin lebih besar untuk pemisahan */
|
47 |
+
max-width: 400px;
|
48 |
+
padding: 20px; /* Padding lebih besar */
|
49 |
+
border-radius: 15px;
|
50 |
+
background: linear-gradient(180deg, #0077b6, #0096c7); /* Gradasi biru cerah */
|
51 |
+
color: white; /* Teks putih untuk kontras */
|
52 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
|
53 |
+
transition: transform 0.2s ease-in-out;
|
54 |
+
}
|
55 |
+
|
56 |
+
#col-right:hover {
|
57 |
+
transform: translateY(-5px);
|
58 |
+
}
|
59 |
+
|
60 |
+
#col-bott {
|
61 |
+
margin: 20px auto; /* Margin lebih besar */
|
62 |
+
padding: 20px; /* Padding lebih besar */
|
63 |
+
border-radius: 15px;
|
64 |
+
background-color: rgba(255, 255, 255, 0.85); /* Warna blok transparan */
|
65 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
|
66 |
+
}
|
67 |
+
|
68 |
+
#banner {
|
69 |
+
width: 100%;
|
70 |
+
text-align: center;
|
71 |
+
margin-bottom: 20px;
|
72 |
+
font-weight: 600; /* Lebih tebal */
|
73 |
+
color: #0077b6; /* Biru sesuai tema */
|
74 |
+
}
|
75 |
+
|
76 |
+
#run-button, #generate-image-button {
|
77 |
+
font-weight: bold;
|
78 |
+
padding: 15px 30px; /* Padding lebih besar */
|
79 |
+
border-radius: 15px;
|
80 |
+
cursor: pointer;
|
81 |
+
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2); /* Bayangan lebih besar */
|
82 |
+
transition: all 0.4s ease-in-out; /* Menambahkan animasi untuk semua properti */
|
83 |
+
}
|
84 |
+
|
85 |
+
#run-button {
|
86 |
+
background-color: #0096c7;
|
87 |
+
color: white;
|
88 |
+
}
|
89 |
+
|
90 |
+
#run-button:hover {
|
91 |
+
background-color: #00b4d8; /* Lebih terang saat hover */
|
92 |
+
transform: translateY(-5px); /* Tombol sedikit naik saat hover */
|
93 |
+
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); /* Bayangan lebih besar saat hover */
|
94 |
+
}
|
95 |
+
|
96 |
+
#generate-image-button {
|
97 |
+
background-color: #ff69b4; /* Warna pink */
|
98 |
+
color: white; /* Teks putih */
|
99 |
+
}
|
100 |
+
|
101 |
+
#generate-image-button:hover {
|
102 |
+
background-color: #ff85c8; /* Pink lebih terang saat hover */
|
103 |
+
transform: translateY(-5px) scale(1.05); /* Membuat tombol sedikit lebih besar dan naik saat hover */
|
104 |
+
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); /* Bayangan lebih besar saat hover */
|
105 |
+
}
|
106 |
+
|
107 |
+
#footer {
|
108 |
+
text-align: center;
|
109 |
+
margin-top: 20px;
|
110 |
+
color: #000; /* Warna netral abu-abu */
|
111 |
+
font-style: italic;
|
112 |
+
}
|
113 |
+
|
114 |
+
#markdown-silver {
|
115 |
+
color: #7a7a7a; /* Mengatur warna font Markdown ke abu-abu netral */
|
116 |
+
}
|
117 |
+
|
118 |
+
/* Efek untuk elemen saat difokuskan */
|
119 |
+
#col-left:focus, #col-mid:focus, #col-right:focus, #run-button:focus, #generate-image-button:focus {
|
120 |
+
outline: 2px solid #0096c7; /* Border biru muda saat fokus */
|
121 |
+
outline-offset: 3px;
|
122 |
+
}
|
123 |
+
|
124 |
+
/* Responsif untuk perangkat mobile */
|
125 |
+
@media (max-width: 768px) {
|
126 |
+
#col-left, #col-mid, #col-right {
|
127 |
+
max-width: 100%; /* Membuat kolom memenuhi lebar layar */
|
128 |
+
}
|
129 |
+
#run-button, #generate-image-button {
|
130 |
+
width: 100%; /* Tombol menjadi lebar penuh */
|
131 |
+
margin-top: 10px; /* Menambahkan margin atas */
|
132 |
+
}
|
133 |
+
}
|
134 |
+
"""
|
135 |
+
|
136 |
+
# Membuat antarmuka Gradio dengan tema IndonesiaTheme dan CSS
|
137 |
+
with gr.Blocks(theme=IndonesiaTheme(), css=css) as RandomPromptApp:
|
138 |
+
|
139 |
+
gr.HTML(title) # Tampilkan judul aplikasi
|
140 |
+
|
141 |
+
# Baris pertama: Input prompt dan tipe prompt
|
142 |
+
with gr.Row():
|
143 |
+
with gr.Column(scale=2):
|
144 |
+
# Textbox untuk input custom prompt dengan placeholder
|
145 |
+
custom = gr.Textbox(
|
146 |
+
label="➡️ Custom Input Prompt (optional)",
|
147 |
+
lines=3,
|
148 |
+
placeholder="Tulis prompt Anda di sini atau biarkan kosong untuk prompt acak."
|
149 |
+
)
|
150 |
+
|
151 |
+
# Dropdown untuk memilih tipe prompt
|
152 |
+
prompt_types = ["Random", "Long", "Short", "Medium", "OnlyObjects", "NoFigure", "Landscape", "Fantasy"]
|
153 |
+
prompt_type = gr.Dropdown(
|
154 |
+
choices=prompt_types,
|
155 |
+
label="Prompt Type",
|
156 |
+
value="Random",
|
157 |
+
interactive=True
|
158 |
+
)
|
159 |
+
|
160 |
+
# Menyimpan tipe prompt yang dipilih dalam sebuah State
|
161 |
+
prompt_type_state = gr.State("Random")
|
162 |
+
|
163 |
+
# Fungsi untuk mengupdate tipe prompt ketika "Random" dipilih
|
164 |
+
def update_prompt_type(value, state):
|
165 |
+
if value == "Random":
|
166 |
+
new_value = random.choice([t for t in prompt_types if t != "Random"])
|
167 |
+
print(f"[-] Random prompt type selected: {new_value}")
|
168 |
+
return value, new_value
|
169 |
+
print(f"[-] Updated prompt type: {value}")
|
170 |
+
return value, value
|
171 |
+
|
172 |
+
# Menghubungkan dropdown tipe prompt dengan fungsi update
|
173 |
+
prompt_type.change(update_prompt_type, inputs=[prompt_type, prompt_type_state], outputs=[prompt_type, prompt_type_state])
|
174 |
+
|
175 |
+
with gr.Column(scale=2):
|
176 |
+
# Accordion untuk parameter terkait generasi prompt LLM
|
177 |
+
with gr.Accordion("➡️ LLM Prompt Generation", open=False):
|
178 |
+
long_talk = gr.Checkbox(label="Long Talk", value=True)
|
179 |
+
compress = gr.Checkbox(label="Compress", value=True)
|
180 |
+
compression_level = gr.Dropdown(
|
181 |
+
choices=["soft", "medium", "hard"],
|
182 |
+
label="Compression Level",
|
183 |
+
value="hard"
|
184 |
+
)
|
185 |
+
custom_base_prompt = gr.Textbox(label="➡️ Custom Base Prompt", lines=5)
|
186 |
+
|
187 |
+
# Dropdown untuk memilih provider LLM
|
188 |
+
llm_provider = gr.Dropdown(
|
189 |
+
choices=["Hugging Face", "Groq", "SambaNova"],
|
190 |
+
label="LLM Provider",
|
191 |
+
value="Groq"
|
192 |
+
)
|
193 |
+
# Textbox untuk API key (disembunyikan)
|
194 |
+
api_key = gr.Textbox(label="API Key", type="password", visible=False)
|
195 |
+
# Dropdown untuk memilih model LLM
|
196 |
+
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")
|
197 |
+
|
198 |
+
with gr.Row():
|
199 |
+
# Tombol untuk mengenerate prompt dan teks
|
200 |
+
generate_button = gr.Button("✅ Generate Prompt", elem_id="run-button")
|
201 |
+
|
202 |
+
with gr.Row():
|
203 |
+
# Output teks hasil generasi LLM dan gambar yang dihasilkan
|
204 |
+
text_output = gr.Textbox(label="➡️ LLM Generated Text", lines=10, show_copy_button=True)
|
205 |
+
image_output = gr.Image(label="➡️ Generated Image", type="filepath")
|
206 |
+
|
207 |
+
with gr.Row():
|
208 |
+
# Tambahkan footer di bagian bawah
|
209 |
+
gr.HTML("""
|
210 |
+
<footer id="footer">
|
211 |
+
Transfer Energi Semesta Digital © 2024 __drat. | 🇮🇩 Untuk Indonesia Jaya!
|
212 |
+
</footer>
|
213 |
+
""")
|
214 |
+
|
215 |
+
# Fungsi untuk mengupdate model LLM berdasarkan provider yang dipilih
|
216 |
+
def update_model_choices(provider):
|
217 |
+
provider_models = {
|
218 |
+
"Hugging Face": [
|
219 |
+
"Qwen/Qwen2.5-72B-Instruct",
|
220 |
+
"meta-llama/Meta-Llama-3.1-70B-Instruct",
|
221 |
+
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
222 |
+
"mistralai/Mistral-7B-Instruct-v0.3"
|
223 |
+
],
|
224 |
+
"Groq": [
|
225 |
+
"llama-3.1-70b-versatile",
|
226 |
+
"mixtral-8x7b-32768",
|
227 |
+
"llama-3.2-90b-text-preview"
|
228 |
+
],
|
229 |
+
"SambaNova": [
|
230 |
+
"Meta-Llama-3.1-70B-Instruct",
|
231 |
+
"Meta-Llama-3.1-405B-Instruct",
|
232 |
+
"Meta-Llama-3.1-8B-Instruct"
|
233 |
+
],
|
234 |
+
}
|
235 |
+
models = provider_models.get(provider, [])
|
236 |
+
return gr.Dropdown(choices=models, value=models[0] if models else "")
|
237 |
+
|
238 |
+
# Fungsi untuk menyembunyikan textbox API key jika tidak dibutuhkan
|
239 |
+
def update_api_key_visibility(provider):
|
240 |
+
return gr.update(visible=False) # API key tidak dibutuhkan untuk provider yang dipilih
|
241 |
+
|
242 |
+
# Menghubungkan perubahan provider LLM dengan fungsi untuk mengupdate model dan visibilitas API key
|
243 |
+
llm_provider.change(
|
244 |
+
update_model_choices,
|
245 |
+
inputs=[llm_provider],
|
246 |
+
outputs=[model]
|
247 |
+
)
|
248 |
+
llm_provider.change(
|
249 |
+
update_api_key_visibility,
|
250 |
+
inputs=[llm_provider],
|
251 |
+
outputs=[api_key]
|
252 |
+
)
|
253 |
+
|
254 |
+
# Fungsi untuk mengenerate prompt dan teks dengan LLM
|
255 |
+
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):
|
256 |
+
try:
|
257 |
+
# Langkah 1: Mengenerate prompt
|
258 |
+
dynamic_seed = random.randint(0, 1000000)
|
259 |
+
|
260 |
+
# Jika prompt_type adalah "Random", pilih tipe prompt acak
|
261 |
+
if prompt_type == "Random":
|
262 |
+
prompt_type = random.choice([t for t in prompt_types if t != "Random"])
|
263 |
+
print(f"[-] Random prompt type selected: {prompt_type}")
|
264 |
+
|
265 |
+
# Jika ada custom input, gunakan sebagai prompt
|
266 |
+
if custom_input and custom_input.strip():
|
267 |
+
prompt = llm_node.generate_prompt(dynamic_seed, prompt_type, custom_input)
|
268 |
+
print(f"[-] Using Custom Input Prompt.")
|
269 |
+
else:
|
270 |
+
prompt = llm_node.generate_prompt(dynamic_seed, prompt_type, f"Create a random prompt based on the '{prompt_type}' type.")
|
271 |
+
print(f"[-] No Custom Input Prompt provided. Generated prompt based on prompt_type: {prompt_type}")
|
272 |
+
|
273 |
+
print(f"[-] Generated Prompt: {prompt}")
|
274 |
+
|
275 |
+
# Langkah 2: Mengenerate teks dengan LLM
|
276 |
+
poster = False # Nilai default
|
277 |
+
result = llm_node.generate(
|
278 |
+
input_text=prompt,
|
279 |
+
long_talk=long_talk,
|
280 |
+
compress=compress,
|
281 |
+
compression_level=compression_level,
|
282 |
+
poster=poster,
|
283 |
+
prompt_type=prompt_type,
|
284 |
+
custom_base_prompt=custom_base_prompt,
|
285 |
+
provider=provider,
|
286 |
+
api_key=api_key,
|
287 |
+
model=model_selected
|
288 |
+
)
|
289 |
+
print(f"Generated Text: {result}")
|
290 |
+
|
291 |
+
return result
|
292 |
+
|
293 |
+
except Exception as e:
|
294 |
+
print(f"[-] An error occurred: {e}")
|
295 |
+
return f"[-] Error occurred while processing the request: {str(e)}"
|
296 |
+
|
297 |
+
# Menghubungkan tombol generate dengan fungsi untuk mengenerate prompt dan teks
|
298 |
+
generate_button.click(
|
299 |
+
generate_random_prompt_with_llm,
|
300 |
+
inputs=[custom, prompt_type, long_talk, compress, compression_level, custom_base_prompt, llm_provider, api_key, model, prompt_type_state],
|
301 |
+
outputs=[text_output],
|
302 |
+
api_name="generate_random_prompt_with_llm"
|
303 |
+
)
|
304 |
+
|
305 |
+
# Tambahkan tombol untuk mengenerate gambar
|
306 |
+
generate_image_button = gr.Button("🔥 Generate Image", elem_id="generate-image-button")
|
307 |
+
|
308 |
+
# Fungsi untuk mengenerate gambar
|
309 |
+
def generate_image(text):
|
310 |
+
try:
|
311 |
+
seed = random.randint(0, 1000000)
|
312 |
+
image_path = llm_node.generate_image(text, seed=seed)
|
313 |
+
print(f"[-] Image generated: {image_path}")
|
314 |
+
return image_path
|
315 |
+
except Exception as e:
|
316 |
+
print(f"[-] An error occurred while generating the image: {e}")
|
317 |
+
return None
|
318 |
+
|
319 |
+
# Menghubungkan tombol generate gambar dengan fungsi untuk mengenerate gambar
|
320 |
+
generate_image_button.click(
|
321 |
+
generate_image,
|
322 |
+
inputs=[text_output],
|
323 |
+
outputs=[image_output]
|
324 |
+
)
|
325 |
+
|
326 |
+
return RandomPromptApp
|
327 |
+
|
328 |
+
# Meluncurkan aplikasi Gradio
|
329 |
+
if __name__ == "__main__":
|
330 |
+
RandomPromptApp = create_interface()
|
331 |
+
RandomPromptApp.launch()
|
llm_inference.py
ADDED
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random # Import the random module
|
3 |
+
from groq import Groq
|
4 |
+
from openai import OpenAI
|
5 |
+
import requests
|
6 |
+
from PIL import Image
|
7 |
+
import io
|
8 |
+
from gradio_client import Client
|
9 |
+
|
10 |
+
class LLMInferenceNode:
|
11 |
+
def __init__(self):
|
12 |
+
self.huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
|
13 |
+
self.groq_api_key = os.getenv("GROQ_API_KEY")
|
14 |
+
self.sambanova_api_key = os.getenv("SAMBANOVA_API_KEY")
|
15 |
+
|
16 |
+
self.huggingface_client = OpenAI(
|
17 |
+
base_url="https://api-inference.huggingface.co/v1/",
|
18 |
+
api_key=self.huggingface_token,
|
19 |
+
)
|
20 |
+
self.groq_client = Groq(api_key=self.groq_api_key)
|
21 |
+
self.sambanova_client = OpenAI(
|
22 |
+
api_key=self.sambanova_api_key,
|
23 |
+
base_url="https://api.sambanova.ai/v1",
|
24 |
+
)
|
25 |
+
self.flux_client = Client("KingNish/Realtime-FLUX", hf_token=self.huggingface_token)
|
26 |
+
|
27 |
+
def generate_prompt(self, dynamic_seed, prompt_type, custom_input):
|
28 |
+
"""
|
29 |
+
Generates a prompt based on the provided seed, prompt type, and custom input.
|
30 |
+
"""
|
31 |
+
random.seed(dynamic_seed)
|
32 |
+
if custom_input and custom_input.strip():
|
33 |
+
prompt = custom_input
|
34 |
+
else:
|
35 |
+
prompt = f"Create a random prompt based on the '{prompt_type}' type."
|
36 |
+
|
37 |
+
# Additional logic can be added here if needed
|
38 |
+
print(f"Generated prompt: {prompt}") # Debug statement
|
39 |
+
return prompt
|
40 |
+
|
41 |
+
def generate(
|
42 |
+
self,
|
43 |
+
input_text,
|
44 |
+
long_talk,
|
45 |
+
compress,
|
46 |
+
compression_level,
|
47 |
+
poster,
|
48 |
+
prompt_type,
|
49 |
+
custom_base_prompt="",
|
50 |
+
provider="Hugging Face",
|
51 |
+
api_key=None,
|
52 |
+
model=None,
|
53 |
+
):
|
54 |
+
try:
|
55 |
+
# Define prompts
|
56 |
+
default_long_prompt = """Create a detailed visually descriptive caption of this description,
|
57 |
+
which will be used as a prompt for a text to image AI system (caption only, no instructions like "create an image").
|
58 |
+
Remove any mention of digital artwork or artwork style. Give detailed visual descriptions of the character(s), including ethnicity, skin tone, expression etc.
|
59 |
+
Imagine using keywords for a still for someone who has aphantasia. Describe the image style, e.g., any photographic or art styles/techniques utilized.
|
60 |
+
Make sure to fully describe all aspects of the cinematography, with abundant technical details and visual descriptions.
|
61 |
+
If there is more than one image, combine the elements and characters from all of the images creatively into a single
|
62 |
+
cohesive composition with a single background, inventing an interaction between the characters.
|
63 |
+
Be creative in combining the characters into a single cohesive scene.
|
64 |
+
Focus on two primary characters (or one) and describe an interesting interaction between them, such as a hug, a kiss, a fight, giving an object,
|
65 |
+
an emotional reaction/interaction. If there is more than one background in the images, pick the most appropriate one.
|
66 |
+
Your output is only the caption itself, no comments or extra formatting.
|
67 |
+
The caption is in a single long paragraph.
|
68 |
+
If you feel the images are inappropriate, invent a new scene/characters inspired by these.
|
69 |
+
Additionally, incorporate a specific movie director's visual style and describe the lighting setup in detail,
|
70 |
+
including the type, color, and placement of light sources to create the desired mood and atmosphere.
|
71 |
+
Always frame the scene, including details about the film grain, color grading, and any artifacts or characteristics specific."""
|
72 |
+
|
73 |
+
default_simple_prompt = """Create a brief, straightforward caption for this description, suitable for a text-to-image AI system.
|
74 |
+
Focus on the main elements, key characters, and overall scene without elaborate details.
|
75 |
+
Provide a clear and concise description in one or two sentences. Your output is only the caption itself, no comments or extra formatting.
|
76 |
+
The caption is in a single long paragraph."""
|
77 |
+
|
78 |
+
poster_prompt = """Analyze the provided description and extract key information to create a movie poster style description. Format the output as follows:
|
79 |
+
Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
|
80 |
+
Main character: Give a description of the main character.
|
81 |
+
Background: Describe the background in detail.
|
82 |
+
Supporting characters: Describe the supporting characters.
|
83 |
+
Branding type: Describe the branding type.
|
84 |
+
Tagline: Include a tagline that captures the essence of the movie.
|
85 |
+
Visual style: Ensure that the visual style fits the branding type and tagline.
|
86 |
+
You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters.
|
87 |
+
Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph."""
|
88 |
+
|
89 |
+
only_objects_prompt = """Create a highly detailed and visually rich description focusing solely on inanimate objects,
|
90 |
+
without including any human or animal figures. Describe the objects' shapes, sizes, colors, textures, and materials in great detail.
|
91 |
+
Pay attention to their arrangement, positioning, and how they interact with light and shadow. Include information about the setting
|
92 |
+
or environment these objects are in, such as indoor/outdoor, time of day, weather conditions, and any atmospheric effects.
|
93 |
+
Mention any unique features, patterns, or imperfections on the objects. Describe the overall composition, perspective, and
|
94 |
+
any artistic techniques that might be employed to render these objects (e.g., photorealism, impressionistic style, etc.).
|
95 |
+
Your description should paint a vivid picture that allows someone to imagine the scene without seeing it, focusing on the beauty,
|
96 |
+
complexity, or significance of everyday objects. Your output is only the caption itself, no comments or extra formatting.
|
97 |
+
The caption is in a single long paragraph."""
|
98 |
+
|
99 |
+
no_figure_prompt = """Generate a comprehensive and visually evocative description of a scene
|
100 |
+
or landscape without including any human or animal figures. Focus on the environment, natural elements, and man-made structures if present.
|
101 |
+
Describe the topography, vegetation, weather conditions, and time of day in great detail.
|
102 |
+
Pay attention to colors, textures, and how light interacts with different elements of the scene.
|
103 |
+
If there are buildings or other structures, describe their architecture, condition, and how they fit into the landscape.
|
104 |
+
Include sensory details beyond just visual elements - mention sounds, smells, and the overall atmosphere or mood of the scene.
|
105 |
+
Describe any notable features like bodies of water, geological formations, or sky phenomena.
|
106 |
+
Consider the perspective from which the scene is viewed and how this affects the composition.
|
107 |
+
Your description should transport the reader to this location, allowing them to vividly imagine the scene without any living subjects present.
|
108 |
+
Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph."""
|
109 |
+
|
110 |
+
landscape_prompt = """Create an immersive and detailed description of a landscape,
|
111 |
+
focusing on its natural beauty and geographical features.
|
112 |
+
Begin with the overall topography - is it mountainous, coastal, forested, desert, or a combination?
|
113 |
+
Describe the horizon and how land meets sky. Detail the vegetation, noting types of trees, flowers, or grass,
|
114 |
+
and how they're distributed across the landscape. Include information about any water features -
|
115 |
+
rivers, lakes, oceans - and how they interact with the land. Describe the sky, including cloud formations,
|
116 |
+
color gradients, and any celestial bodies visible.
|
117 |
+
Pay attention to the quality of light, time of day, and season, explaining how these factors affect the colors and shadows in the scene.
|
118 |
+
Include details about weather conditions and how they impact the landscape.
|
119 |
+
Mention any geological features like rock formations, cliffs, or unique land patterns.
|
120 |
+
If there are any distant man-made elements, describe how they integrate with the natural setting.
|
121 |
+
Your description should capture the grandeur and mood of the landscape,
|
122 |
+
allowing the reader to feel as if they're standing within this awe-inspiring natural scene.
|
123 |
+
Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph."""
|
124 |
+
|
125 |
+
fantasy_prompt = """Craft an extraordinarily detailed and imaginative description of a fantasy scene,
|
126 |
+
blending elements of magic, otherworldly creatures, and fantastical environments. Begin by setting the overall tone -
|
127 |
+
is this a dark and foreboding realm, a whimsical fairytale setting, or an epic high-fantasy world?
|
128 |
+
Describe the landscape, including any impossible or magical geographical features like floating islands,
|
129 |
+
crystal forests, or rivers of starlight. Detail the flora and fauna,
|
130 |
+
focusing on fantastical plants and creatures that don't exist in our world.
|
131 |
+
Include descriptions of any structures or ruins, emphasizing their otherworldly architecture and magical properties.
|
132 |
+
Describe the sky and any celestial bodies, considering how they might differ from our reality.
|
133 |
+
Include details about the presence of magic - how it manifests visually,
|
134 |
+
its effects on the environment, and any magical phenomena occurring in the scene.
|
135 |
+
If there are characters present, describe their appearance, focusing on non-human features, magical auras, or
|
136 |
+
fantastical clothing and accessories. Pay attention to colors, textures, and light sources,
|
137 |
+
especially those that couldn't exist in the real world. Your description should transport the
|
138 |
+
reader to a realm of pure imagination, where the laws of physics and nature as we know them don't apply.
|
139 |
+
Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph."""
|
140 |
+
|
141 |
+
prompt_types = {
|
142 |
+
"Long": default_long_prompt,
|
143 |
+
"Short": default_simple_prompt,
|
144 |
+
"Medium": poster_prompt,
|
145 |
+
"OnlyObjects": only_objects_prompt,
|
146 |
+
"NoFigure": no_figure_prompt,
|
147 |
+
"Landscape": landscape_prompt,
|
148 |
+
"Fantasy": fantasy_prompt,
|
149 |
+
}
|
150 |
+
|
151 |
+
# Determine the base prompt
|
152 |
+
print(f"Received prompt_type: '{prompt_type}'") # Debug print
|
153 |
+
if prompt_type == "Random":
|
154 |
+
prompt_type = random.choice(list(prompt_types.keys()))
|
155 |
+
print(f"Randomly selected prompt type: {prompt_type}")
|
156 |
+
|
157 |
+
if prompt_type and prompt_type.strip() and prompt_type in prompt_types:
|
158 |
+
base_prompt = prompt_types[prompt_type]
|
159 |
+
print(f"Using {prompt_type} prompt")
|
160 |
+
elif custom_base_prompt.strip():
|
161 |
+
base_prompt = custom_base_prompt
|
162 |
+
print("Using custom base prompt")
|
163 |
+
else:
|
164 |
+
base_prompt = default_long_prompt
|
165 |
+
print(f"Warning: Unknown or empty prompt type '{prompt_type}'. Using default long prompt.")
|
166 |
+
|
167 |
+
# Handle compression if applicable
|
168 |
+
if compress and not poster:
|
169 |
+
compression_chars = {
|
170 |
+
"soft": 600 if long_talk else 300,
|
171 |
+
"medium": 400 if long_talk else 200,
|
172 |
+
"hard": 200 if long_talk else 100,
|
173 |
+
}
|
174 |
+
char_limit = compression_chars.get(compression_level, 200)
|
175 |
+
base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
|
176 |
+
|
177 |
+
# Construct messages for the LLM
|
178 |
+
system_message = "You are a helpful assistant. Try your best to give the best response possible to the user."
|
179 |
+
|
180 |
+
if input_text.startswith("Create a random prompt based on"):
|
181 |
+
user_message = f"Create a random description based on this\nInstructions: {base_prompt}"
|
182 |
+
else:
|
183 |
+
user_message = f"{base_prompt}\nDescription: {input_text}"
|
184 |
+
|
185 |
+
# Generate a random seed
|
186 |
+
seed = random.randint(0, 10000)
|
187 |
+
print(f"Generated seed: {seed}") # Debug print
|
188 |
+
|
189 |
+
# Select the appropriate provider
|
190 |
+
if provider == "Hugging Face":
|
191 |
+
response = self.huggingface_client.chat.completions.create(
|
192 |
+
model=model or "meta-llama/Meta-Llama-3.1-70B-Instruct",
|
193 |
+
max_tokens=1024,
|
194 |
+
temperature=1.0,
|
195 |
+
top_p=0.95,
|
196 |
+
messages=[
|
197 |
+
{"role": "system", "content": system_message},
|
198 |
+
{"role": "user", "content": user_message},
|
199 |
+
],
|
200 |
+
seed=seed # Pass the seed parameter
|
201 |
+
)
|
202 |
+
output = response.choices[0].message.content.strip()
|
203 |
+
|
204 |
+
elif provider == "Groq":
|
205 |
+
response = self.groq_client.chat.completions.create(
|
206 |
+
model=model or "llama-3.1-70b-versatile",
|
207 |
+
max_tokens=1024,
|
208 |
+
temperature=1.0,
|
209 |
+
messages=[
|
210 |
+
{"role": "system", "content": system_message},
|
211 |
+
{"role": "user", "content": user_message},
|
212 |
+
],
|
213 |
+
seed=seed # Pass the seed parameter
|
214 |
+
)
|
215 |
+
output = response.choices[0].message.content.strip()
|
216 |
+
|
217 |
+
elif provider == "SambaNova":
|
218 |
+
response = self.sambanova_client.chat.completions.create(
|
219 |
+
model=model or "Meta-Llama-3.1-70B-Instruct",
|
220 |
+
max_tokens=1024,
|
221 |
+
temperature=1.0,
|
222 |
+
messages=[
|
223 |
+
{"role": "system", "content": system_message},
|
224 |
+
{"role": "user", "content": user_message},
|
225 |
+
],
|
226 |
+
seed=seed # Pass the seed parameter
|
227 |
+
)
|
228 |
+
output = response.choices[0].message.content.strip()
|
229 |
+
|
230 |
+
else:
|
231 |
+
raise ValueError(f"Unsupported provider: {provider}")
|
232 |
+
|
233 |
+
# Clean up the output if necessary
|
234 |
+
if ": " in output:
|
235 |
+
output = output.split(": ", 1)[1].strip()
|
236 |
+
elif output.lower().startswith("here"):
|
237 |
+
sentences = output.split(". ")
|
238 |
+
if len(sentences) > 1:
|
239 |
+
output = ". ".join(sentences[1:]).strip()
|
240 |
+
|
241 |
+
return output
|
242 |
+
|
243 |
+
except Exception as e:
|
244 |
+
print(f"An error occurred: {e}")
|
245 |
+
return f"Error occurred while processing the request: {str(e)}"
|
246 |
+
|
247 |
+
def generate_image(self, prompt, seed=42, width=1024, height=1024):
|
248 |
+
try:
|
249 |
+
result = self.flux_client.predict(
|
250 |
+
prompt=prompt,
|
251 |
+
seed=seed,
|
252 |
+
width=width,
|
253 |
+
height=height,
|
254 |
+
api_name="/generate_image"
|
255 |
+
)
|
256 |
+
# Extract the image path from the result tuple
|
257 |
+
image_path = result[0]
|
258 |
+
return image_path
|
259 |
+
except Exception as e:
|
260 |
+
raise Exception(f"Error generating image: {str(e)}")
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
openai
|
2 |
+
groq
|
themes.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from typing import Iterable
|
3 |
+
from gradio.themes.base import Base
|
4 |
+
from gradio.themes.utils import colors, fonts, sizes
|
5 |
+
|
6 |
+
class IndonesiaTheme(Base):
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
*,
|
10 |
+
primary_hue: colors.Color | str = colors.red,
|
11 |
+
secondary_hue: colors.Color | str = colors.gray,
|
12 |
+
neutral_hue: colors.Color | str = colors.gray,
|
13 |
+
spacing_size: sizes.Size | str = sizes.spacing_md,
|
14 |
+
radius_size: sizes.Size | str = sizes.radius_md,
|
15 |
+
text_size: sizes.Size | str = sizes.text_lg,
|
16 |
+
font: fonts.Font
|
17 |
+
| str
|
18 |
+
| Iterable[fonts.Font | str] = (
|
19 |
+
fonts.GoogleFont("Quicksand"),
|
20 |
+
"ui-sans-serif",
|
21 |
+
"sans-serif",
|
22 |
+
),
|
23 |
+
font_mono: fonts.Font
|
24 |
+
| str
|
25 |
+
| Iterable[fonts.Font | str] = (
|
26 |
+
fonts.GoogleFont("IBM Plex Mono"),
|
27 |
+
"ui-monospace",
|
28 |
+
"monospace",
|
29 |
+
),
|
30 |
+
):
|
31 |
+
super().__init__(
|
32 |
+
primary_hue=primary_hue,
|
33 |
+
secondary_hue=secondary_hue,
|
34 |
+
neutral_hue=neutral_hue,
|
35 |
+
spacing_size=spacing_size,
|
36 |
+
radius_size=radius_size,
|
37 |
+
text_size=text_size,
|
38 |
+
font=font,
|
39 |
+
font_mono=font_mono,
|
40 |
+
)
|
41 |
+
super().set(
|
42 |
+
body_background_fill="linear-gradient(to bottom, #e0e0e0, #7d7d7d)", # Gradasi abu-abu muda ke abu-abu tua
|
43 |
+
body_background_fill_dark="linear-gradient(to bottom, #7d7d7d, #4a4a4a)", # Gradasi abu-abu tua ke lebih gelap untuk dark mode
|
44 |
+
button_primary_background_fill="linear-gradient(90deg, #d84a4a, #b33030)", # Merah ke merah tua
|
45 |
+
button_primary_background_fill_hover="linear-gradient(90deg, #e85b5b, #cc4b4b)", # Merah lebih terang untuk hover
|
46 |
+
button_primary_text_color="white",
|
47 |
+
button_primary_background_fill_dark="linear-gradient(90deg, #b33030, #8f1f1f)", # Merah tua untuk dark mode
|
48 |
+
slider_color="*secondary_300",
|
49 |
+
slider_color_dark="*secondary_600",
|
50 |
+
block_title_text_weight="600",
|
51 |
+
block_border_width="3px",
|
52 |
+
block_shadow="*shadow_drop_lg",
|
53 |
+
button_shadow="*shadow_drop_lg",
|
54 |
+
button_large_padding="32px",
|
55 |
+
)
|