openfree commited on
Commit
b79c514
ยท
verified ยท
1 Parent(s): ce47142

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +409 -390
app.py CHANGED
@@ -5,32 +5,6 @@ from huggingface_hub import whoami, HfApi
5
  from fastapi import FastAPI
6
  from starlette.middleware.sessions import SessionMiddleware
7
  import sys
8
-
9
- # ai-toolkit์ด ์—†์œผ๋ฉด ์„ค์น˜
10
- if not os.path.exists("ai-toolkit"):
11
- subprocess.run("git clone https://github.com/ostris/ai-toolkit.git", shell=True)
12
- subprocess.run("cd ai-toolkit && git submodule update --init --recursive", shell=True)
13
-
14
- # ai-toolkit ๊ฒฝ๋กœ ์ถ”๊ฐ€
15
- toolkit_path = os.path.join(os.getcwd(), "ai-toolkit")
16
- sys.path.append(toolkit_path)
17
-
18
- # ํ•„์š”ํ•œ ํŒจํ‚ค์ง€ ์„ค์น˜
19
- subprocess.run("pip install -r ai-toolkit/requirements.txt", shell=True)
20
-
21
-
22
- is_spaces = True if os.environ.get("SPACE_ID") else False
23
-
24
- os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
25
- import sys
26
-
27
- from dotenv import load_dotenv
28
-
29
- load_dotenv()
30
-
31
- # Add the current working directory to the Python path
32
- sys.path.insert(0, os.getcwd())
33
-
34
  import gradio as gr
35
  from PIL import Image
36
  import torch
@@ -40,91 +14,129 @@ import json
40
  import yaml
41
  from slugify import slugify
42
  from transformers import AutoProcessor, AutoModelForCausalLM
 
 
 
 
 
 
 
43
 
44
- # Gradio app ์„ค์ •
45
  app = FastAPI()
46
  app.add_middleware(SessionMiddleware, secret_key="your-secret-key")
47
 
48
- if not is_spaces:
49
- sys.path.insert(0, "ai-toolkit")
50
- from toolkit.job import get_job
51
- gr.OAuthProfile = None
52
- gr.OAuthToken = None
53
-
54
-
55
  MAX_IMAGES = 150
56
 
57
-
58
- # Hugging Face ํ† ํฐ ์„ค์ •
59
  HF_TOKEN = os.getenv("HF_TOKEN")
60
  if not HF_TOKEN:
61
  raise ValueError("HF_TOKEN environment variable is not set")
62
 
63
-
64
- if is_spaces:
65
- subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
66
- import spaces
67
-
68
- os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
69
  os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
70
 
71
- # HF API ์ดˆ๊ธฐํ™”
72
  api = HfApi(token=HF_TOKEN)
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def load_captioning(uploaded_files, concept_sentence):
 
75
  uploaded_images = [file for file in uploaded_files if not file.endswith('.txt')]
76
  txt_files = [file for file in uploaded_files if file.endswith('.txt')]
77
  txt_files_dict = {os.path.splitext(os.path.basename(txt_file))[0]: txt_file for txt_file in txt_files}
78
  updates = []
 
79
  if len(uploaded_images) <= 1:
80
  raise gr.Error(
81
- "Please upload at least 2 images to train your model (the ideal number with default settings is between 4-30)"
82
  )
83
  elif len(uploaded_images) > MAX_IMAGES:
84
  raise gr.Error(f"For now, only {MAX_IMAGES} or less images are allowed for training")
85
- # Update for the captioning_area
86
- # for _ in range(3):
87
  updates.append(gr.update(visible=True))
88
- # Update visibility and image for each captioning row and image
 
89
  for i in range(1, MAX_IMAGES + 1):
90
- # Determine if the current row and image should be visible
91
  visible = i <= len(uploaded_images)
92
 
93
- # Update visibility of the captioning row
94
  updates.append(gr.update(visible=visible))
95
-
96
- # Update for image component - display image if available, otherwise hide
97
  image_value = uploaded_images[i - 1] if visible else None
98
  updates.append(gr.update(value=image_value, visible=visible))
99
 
100
  corresponding_caption = False
101
- if(image_value):
102
  base_name = os.path.splitext(os.path.basename(image_value))[0]
103
- print(base_name)
104
- print(image_value)
105
  if base_name in txt_files_dict:
106
- print("entrou")
107
  with open(txt_files_dict[base_name], 'r') as file:
108
  corresponding_caption = file.read()
109
 
110
- # Update value of captioning area
111
  text_value = corresponding_caption if visible and corresponding_caption else "[trigger]" if visible and concept_sentence else None
112
  updates.append(gr.update(value=text_value, visible=visible))
113
 
114
- # Update for the sample caption area
115
  updates.append(gr.update(visible=True))
116
- # Update prompt samples
117
  updates.append(gr.update(placeholder=f'A portrait of person in a bustling cafe {concept_sentence}', value=f'A person in a bustling cafe {concept_sentence}'))
118
  updates.append(gr.update(placeholder=f"A mountainous landscape in the style of {concept_sentence}"))
119
  updates.append(gr.update(placeholder=f"A {concept_sentence} in a mall"))
 
120
  return updates
121
 
122
  def hide_captioning():
 
123
  return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
124
 
125
- def create_dataset(*inputs):
126
- print("Creating dataset")
127
- images = inputs[0]
128
  destination_folder = str(f"datasets/{uuid.uuid4()}")
129
  if not os.path.exists(destination_folder):
130
  os.makedirs(destination_folder)
@@ -132,63 +144,225 @@ def create_dataset(*inputs):
132
  jsonl_file_path = os.path.join(destination_folder, "metadata.jsonl")
133
  with open(jsonl_file_path, "a") as jsonl_file:
134
  for index, image in enumerate(images):
135
- new_image_path = shutil.copy(image, destination_folder)
136
-
137
- original_caption = inputs[index + 1]
138
- file_name = os.path.basename(new_image_path)
139
-
140
- data = {"file_name": file_name, "prompt": original_caption}
141
-
142
- jsonl_file.write(json.dumps(data) + "\n")
143
 
144
  return destination_folder
145
 
146
-
147
  def run_captioning(images, concept_sentence, *captions):
148
- device = "cuda" if torch.cuda.is_available() else "cpu"
149
- torch_dtype = torch.float16
150
- model = AutoModelForCausalLM.from_pretrained(
151
- "microsoft/Florence-2-large", torch_dtype=torch_dtype, trust_remote_code=True
152
- ).to(device)
153
- processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- captions = list(captions)
156
- for i, image_path in enumerate(images):
157
- print(captions[i])
158
- if isinstance(image_path, str): # If image is a file path
159
- image = Image.open(image_path).convert("RGB")
 
 
 
 
 
 
 
160
 
161
- prompt = "<DETAILED_CAPTION>"
162
- inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- generated_ids = model.generate(
165
- input_ids=inputs["input_ids"], pixel_values=inputs["pixel_values"], max_new_tokens=1024, num_beams=3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
- generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
169
- parsed_answer = processor.post_process_generation(
170
- generated_text, task=prompt, image_size=(image.width, image.height)
171
- )
172
- caption_text = parsed_answer["<DETAILED_CAPTION>"].replace("The image shows ", "")
173
- if concept_sentence:
174
- caption_text = f"{caption_text} [trigger]"
175
- captions[i] = caption_text
176
-
177
- yield captions
178
- model.to("cpu")
179
- del model
180
- del processor
181
-
182
- if is_spaces:
183
- run_captioning = spaces.GPU()(run_captioning)
184
-
185
- def recursive_update(d, u):
186
- for k, v in u.items():
187
- if isinstance(v, dict) and v:
188
- d[k] = recursive_update(d.get(k, {}), v)
189
- else:
190
- d[k] = v
191
- return d
192
 
193
  def start_training(
194
  lora_name,
@@ -204,6 +378,7 @@ def start_training(
204
  use_more_advanced_options,
205
  more_advanced_options,
206
  ):
 
207
  if not lora_name:
208
  raise gr.Error("You forgot to insert your LoRA name! This name has to be unique.")
209
 
@@ -215,33 +390,18 @@ def start_training(
215
  print("Started training")
216
  slugged_lora_name = slugify(lora_name)
217
 
218
- # Load the default config
219
- with open("train_lora_flux_24gb.yaml", "r") as f:
220
- config = yaml.safe_load(f)
221
-
222
- # dev ๋ชจ๋ธ ์„ค์ •
223
- config["config"]["name"] = slugged_lora_name
224
- config["config"]["process"][0]["model"]["name_or_path"] = "black-forest-labs/FLUX.1-dev"
225
- config["config"]["process"][0]["model"]["assistant_lora_path"] = None # adapter ์—†์ด ์„ค์ •
226
- config["config"]["process"][0]["model"]["low_vram"] = False
227
- config["config"]["process"][0]["train"]["skip_first_sample"] = True
228
  config["config"]["process"][0]["train"]["steps"] = int(steps)
229
  config["config"]["process"][0]["train"]["lr"] = float(lr)
230
  config["config"]["process"][0]["network"]["linear"] = int(rank)
231
  config["config"]["process"][0]["network"]["linear_alpha"] = int(rank)
232
  config["config"]["process"][0]["datasets"][0]["folder_path"] = dataset_folder
233
- config["config"]["process"][0]["save"]["push_to_hub"] = True
234
- config["config"]["process"][0]["save"]["hf_repo_id"] = f"{username}/{slugged_lora_name}"
235
- config["config"]["process"][0]["save"]["hf_private"] = True
236
- config["config"]["process"][0]["save"]["hf_token"] = HF_TOKEN
237
- config["config"]["process"][0]["sample"]["sample_steps"] = 28
238
-
239
- if concept_sentence:
240
- config["config"]["process"][0]["trigger_word"] = concept_sentence
241
 
 
242
  if sample_1 or sample_2 or sample_3:
243
- config["config"]["process"][0]["train"]["disable_sampling"] = False
244
- config["config"]["process"][0]["sample"]["sample_every"] = steps
245
  config["config"]["process"][0]["sample"]["prompts"] = []
246
  if sample_1:
247
  config["config"]["process"][0]["sample"]["prompts"].append(sample_1)
@@ -252,100 +412,46 @@ def start_training(
252
  else:
253
  config["config"]["process"][0]["train"]["disable_sampling"] = True
254
 
255
- if(use_more_advanced_options):
256
- more_advanced_options_dict = yaml.safe_load(more_advanced_options)
257
- config["config"]["process"][0] = recursive_update(config["config"]["process"][0], more_advanced_options_dict)
258
- print(config)
 
 
 
 
 
 
 
 
 
 
259
 
260
  try:
261
- # Save the updated config
262
- random_config_name = str(uuid.uuid4())
263
  os.makedirs("tmp", exist_ok=True)
264
- config_path = f"tmp/{random_config_name}-{slugged_lora_name}.yaml"
265
  with open(config_path, "w") as f:
266
  yaml.dump(config, f)
267
 
268
- # ์ง์ ‘ ๋กœ์ปฌ GPU์—์„œ ํ•™์Šต ์‹คํ–‰
269
- from toolkit.job import get_job
270
- job = get_job(config_path)
271
- job.run()
272
- job.cleanup()
273
  except Exception as e:
274
  raise gr.Error(f"Training failed: {str(e)}")
275
 
276
- return f"""# Training completed successfully!
277
- ## Your model is available at: <a href='https://huggingface.co/{username}/{slugged_lora_name}'>{username}/{slugged_lora_name}</a>"""
278
-
279
-
280
- def update_pricing(steps):
281
- try:
282
- seconds_per_iteration = 7.54
283
- total_seconds = (steps * seconds_per_iteration) + 240
284
- cost_per_second = 0.80/60/60
285
- cost = round(cost_per_second * total_seconds, 2)
286
- cost_preview = f'''To train this LoRA, a paid L4 GPU will be hooked under the hood during training and then removed once finished.
287
- ### Estimated to cost <b>< US$ {str(cost)}</b> for {round(int(total_seconds)/60, 2)} minutes with your current train settings <small>({int(steps)} iterations at {seconds_per_iteration}s/it)</small>'''
288
- return gr.update(visible=True), cost_preview, gr.update(visible=False), gr.update(visible=True)
289
- except:
290
- return gr.update(visible=False), "", gr.update(visible=False), gr.update(visible=True)
291
-
292
-
293
-
294
- def swap_base_model(model):
295
- return gr.update(visible=True) if model == "[dev] (high quality model, non-commercial license)" else gr.update(visible=False)
296
-
297
- config_yaml = '''
298
- device: cuda:0
299
- model:
300
- is_flux: true
301
- quantize: true
302
- network:
303
- linear: 16 #it will overcome the 'rank' parameter
304
- linear_alpha: 16 #you can have an alpha different than the ranking if you'd like
305
- type: lora
306
- sample:
307
- guidance_scale: 3.5
308
- height: 1024
309
- neg: '' #doesn't work for FLUX
310
- sample_every: 1000
311
- sample_steps: 28
312
- sampler: flowmatch
313
- seed: 42
314
- walk_seed: true
315
- width: 1024
316
- save:
317
- dtype: float16
318
- hf_private: true
319
- max_step_saves_to_keep: 4
320
- push_to_hub: true
321
- save_every: 10000
322
- train:
323
- batch_size: 1
324
- dtype: bf16
325
- ema_config:
326
- ema_decay: 0.99
327
- use_ema: true
328
- gradient_accumulation_steps: 1
329
- gradient_checkpointing: true
330
- noise_scheduler: flowmatch
331
- optimizer: adamw8bit #options: prodigy, dadaptation, adamw, adamw8bit, lion, lion8bit
332
- train_text_encoder: false #probably doesn't work for flux
333
- train_unet: true
334
- '''
335
-
336
-
337
-
338
  custom_theme = gr.themes.Base(
339
  primary_hue="indigo",
340
  secondary_hue="slate",
341
  neutral_hue="slate",
342
  ).set(
343
- # ๊ธฐ๋ณธ ๋ฐฐ๊ฒฝ ๋ฐ ๋ณด๋”
344
  background_fill_primary="#1a1a1a",
345
  background_fill_secondary="#2d2d2d",
346
  border_color_primary="#404040",
347
 
348
- # ๋ฒ„ํŠผ ์Šคํƒ€์ผ
349
  button_primary_background_fill="#4F46E5",
350
  button_primary_background_fill_dark="#4338CA",
351
  button_primary_background_fill_hover="#6366F1",
@@ -360,7 +466,6 @@ custom_theme = gr.themes.Base(
360
  button_secondary_text_color="white",
361
  button_secondary_text_color_dark="white",
362
 
363
- # ๋ธ”๋ก ์Šคํƒ€์ผ
364
  block_background_fill="#2d2d2d",
365
  block_background_fill_dark="#1F2937",
366
  block_label_background_fill="#4F46E5",
@@ -370,31 +475,18 @@ custom_theme = gr.themes.Base(
370
  block_title_text_color="white",
371
  block_title_text_color_dark="white",
372
 
373
- # ์ž…๋ ฅ ํ•„๋“œ ์Šคํƒ€์ผ
374
  input_background_fill="#374151",
375
  input_background_fill_dark="#1F2937",
376
  input_border_color="#4B5563",
377
  input_border_color_dark="#374151",
378
  input_placeholder_color="#9CA3AF",
379
  input_placeholder_color_dark="#6B7280",
380
-
381
- # ๊ทธ๋ฆผ์ž ํšจ๊ณผ
382
- shadow_spread="8px",
383
- shadow_inset="0px 2px 4px 0px rgba(0,0,0,0.1)",
384
-
385
- # ์ปจํ…Œ์ด๋„ˆ ์Šคํƒ€์ผ
386
- panel_background_fill="#2d2d2d",
387
- panel_background_fill_dark="#1F2937",
388
-
389
- # ๋ณด๋” ์Šคํƒ€์ผ
390
- border_color_accent="#4F46E5",
391
- border_color_accent_dark="#4338CA"
392
  )
393
 
394
- css='''
395
- /* ๊ธฐ๋ณธ ์Šคํƒ€์ผ */
396
  h1 {
397
- font-size: 3em;
398
  text-align: center;
399
  margin-bottom: 0.5em;
400
  color: white !important;
@@ -406,193 +498,67 @@ h3 {
406
  color: white !important;
407
  }
408
 
409
- /* Markdown ํ…์ŠคํŠธ ์Šคํƒ€์ผ */
410
- .markdown {
 
 
 
 
411
  color: white !important;
412
  }
413
 
414
- .markdown h1,
415
- .markdown h2,
416
- .markdown h3,
417
- .markdown h4,
418
- .markdown h5,
419
- .markdown h6,
420
- .markdown p {
421
- color: white !important;
422
- }
423
-
424
- /* ์ปดํฌ๋„ŒํŠธ ์Šคํƒ€์ผ */
425
- .container {
426
- max-width: 1200px;
427
- margin: 0 auto;
428
- padding: 20px;
429
- }
430
-
431
- /* ์ž…๋ ฅ ํ•„๋“œ ์Šคํƒ€์ผ */
432
- .input-group {
433
- background: var(--block-background-fill);
434
- padding: 15px;
435
- border-radius: 12px;
436
- margin-bottom: 20px;
437
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
438
- }
439
-
440
- /* ๋ชจ๋“  ์ž…๋ ฅ ํ•„๋“œ ํ…์ŠคํŠธ ์ƒ‰์ƒ */
441
- input, textarea, .gradio-textbox input, .gradio-textbox textarea, .gradio-number input {
442
  color: white !important;
443
  }
444
 
445
- /* ๋ผ๋ฒจ ํ…์ŠคํŠธ ์Šคํƒ€์ผ */
446
- label, .label-text {
447
- color: white !important;
448
- }
449
-
450
- /* ๋ผ๋””์˜ค ๋ฒ„ํŠผ ํ…์ŠคํŠธ */
451
- .gradio-radio label span {
452
- color: white !important;
453
- }
454
-
455
- /* ์ฒดํฌ๋ฐ•์Šค ํ…์ŠคํŠธ */
456
- .gradio-checkbox label span {
457
- color: white !important;
458
- }
459
-
460
- /* ๋ฒ„ํŠผ ์Šคํƒ€์ผ */
461
- .button {
462
- height: 40px;
463
- border-radius: 8px;
464
  transition: all 0.3s ease;
465
- color: white !important;
466
  }
467
 
468
- .button:hover {
469
  transform: translateY(-2px);
470
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
471
  }
472
 
473
- /* ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์˜์—ญ */
474
  .image-upload-area {
475
- border: 2px dashed var(--input-border-color);
476
  border-radius: 12px;
477
  padding: 20px;
478
  text-align: center;
479
  margin-bottom: 20px;
480
- color: white !important;
481
- }
482
-
483
- /* ์บก์…˜ ์˜์—ญ */
484
- .caption-area {
485
- background: var(--block-background-fill);
486
- padding: 15px;
487
- border-radius: 12px;
488
- margin-top: 20px;
489
- color: white !important;
490
  }
491
 
 
492
  .caption-row {
493
  display: flex;
494
  align-items: center;
495
  margin-bottom: 10px;
496
  gap: 10px;
497
  }
498
-
499
- /* ๊ณ ๊ธ‰ ์˜ต์…˜ ์˜์—ญ */
500
- .advanced-options {
501
- background: var(--block-background-fill);
502
- padding: 15px;
503
- border-radius: 12px;
504
- margin-top: 20px;
505
- color: white !important;
506
- }
507
-
508
- /* ์ง„ํ–‰ ์ƒํƒœ ํ‘œ์‹œ */
509
- .progress-area {
510
- background: var(--block-background-fill);
511
- padding: 15px;
512
- border-radius: 12px;
513
- margin-top: 20px;
514
- text-align: center;
515
- color: white !important;
516
- }
517
-
518
- /* ํ”Œ๋ ˆ์ด์Šคํ™€๋” ํ…์ŠคํŠธ */
519
- ::placeholder {
520
- color: rgba(255, 255, 255, 0.5) !important;
521
- }
522
-
523
- /* ์ฝ”๋“œ ์—๋””ํ„ฐ ํ…์ŠคํŠธ */
524
- .gradio-code {
525
- color: white !important;
526
- }
527
-
528
- /* ์•„์ฝ”๋””์–ธ ํ…์ŠคํŠธ */
529
- .gradio-accordion .label-wrap {
530
- color: white !important;
531
- }
532
-
533
- /* ๋ฐ˜์‘ํ˜• ๋””์ž์ธ */
534
- @media (max-width: 768px) {
535
- .caption-row {
536
- flex-direction: column;
537
- }
538
- }
539
-
540
- /* ์Šคํฌ๋กค๋ฐ” ์Šคํƒ€์ผ */
541
- ::-webkit-scrollbar {
542
- width: 8px;
543
- }
544
-
545
- ::-webkit-scrollbar-track {
546
- background: var(--background-fill-primary);
547
- border-radius: 4px;
548
- }
549
-
550
- ::-webkit-scrollbar-thumb {
551
- background: var(--primary-500);
552
- border-radius: 4px;
553
- }
554
-
555
- ::-webkit-scrollbar-thumb:hover {
556
- background: var(--primary-600);
557
- }
558
-
559
- /* ๋ชจ๋“  ํ…์ŠคํŠธ ์ž…๋ ฅ ์š”์†Œ */
560
- .gradio-container input[type="text"],
561
- .gradio-container textarea,
562
- .gradio-container .input-text,
563
- .gradio-container .input-textarea {
564
- color: white !important;
565
- }
566
-
567
- /* ๋“œ๋กญ๋‹ค์šด ํ…์ŠคํŠธ */
568
- select, option {
569
- color: white !important;
570
- }
571
-
572
- /* ๋ฒ„ํŠผ ํ…์ŠคํŠธ */
573
- button {
574
- color: white !important;
575
- }
576
  '''
577
 
578
- # Gradio ์•ฑ ์ˆ˜์ •
579
  with gr.Blocks(theme=custom_theme, css=css) as demo:
580
-
581
  gr.Markdown(
582
- """# ๐Ÿ†” Gini LoRA ํ•™์Šต
583
- ### 1)LoRA ์ด๋ฆ„ ์˜์–ด๋กœ '์ž…๋ ฅ' 2)ํŠธ๋ฆฌ๊ฑฐ ๋‹จ์–ด ์˜์–ด๋กœ '์ž…๋ ฅ' 3)๊ธฐ๋ณธ ๋ชจ๋ธ 'ํด๋ฆญ' 4)์ด๋ฏธ์ง€(์ตœ์†Œ 2์žฅ~์ตœ๋Œ€ 150์žฅ ๋ฏธ๋งŒ) '์—…๋กœ๋“œ' 5)๋น„์ „ ์ธ์‹ LLM ๋ผ๋ฒจ๋ง 'ํด๋ฆญ' 6)START ํด๋ฆญ""",
584
- elem_classes=["markdown"]
585
- )
586
 
587
  with gr.Tab("Train"):
588
- with gr.Column(elem_classes="container"):
589
- # LoRA ์„ค์ • ๊ทธ๋ฃน
590
- with gr.Group(elem_classes="input-group"):
591
  with gr.Row():
592
  lora_name = gr.Textbox(
593
  label="LoRA ์ด๋ฆ„",
594
  info="๊ณ ์œ ํ•œ ์ด๋ฆ„์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค",
595
- placeholder="์˜ˆ: Persian Miniature Painting style, Cat Toy"
596
  )
597
  concept_sentence = gr.Textbox(
598
  label="ํŠธ๋ฆฌ๊ฑฐ ๋‹จ์–ด/๋ฌธ์žฅ",
@@ -604,12 +570,11 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
604
  which_model = gr.Radio(
605
  ["๊ณ ํ€„๋ฆฌํ‹ฐ ๋งž์ถค ํ•™์Šต ๋ชจ๋ธ"],
606
  label="๊ธฐ๋ณธ ๋ชจ๋ธ",
607
- value="[dev] (high quality model)"
608
  )
609
 
610
- # ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ ์˜์—ญ
611
  with gr.Group(visible=True, elem_classes="image-upload-area") as image_upload:
612
-
613
  with gr.Row():
614
  images = gr.File(
615
  file_types=["image", ".txt"],
@@ -623,8 +588,8 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
623
  with gr.Column():
624
  gr.Markdown(
625
  """# ์ด๋ฏธ์ง€ ๋ผ๋ฒจ๋ง
626
- <p style="margin-top:0"> ๋น„์ „์ธ์‹ LLM์ด ์ด๋ฏธ์ง€๋ฅผ ์ธ์‹ํ•˜์—ฌ ์ž๋™์œผ๋กœ ๋ผ๋ฒจ๋ง(์ด๋ฏธ์ง€ ์ธ์‹์„ ์œ„ํ•œ ํ•„์ˆ˜ ์„ค๋ช…). [trigger] 'ํŠธ๋ฆฌ๊ฑฐ ์›Œ๋“œ'๋Š” ํ•™์Šตํ•œ ๋ชจ๋ธ์„ ์‹คํ–‰ํ•˜๋Š” ๊ณ ์œ  ํ‚ค๊ฐ’ /trigger word.</p>
627
- """, elem_classes="group_padding")
628
  do_captioning = gr.Button("๋น„์ „ ์ธ์‹ LLM ์ž๋™ ๋ผ๋ฒจ๋ง")
629
  output_components = [captioning_area]
630
  caption_list = []
@@ -651,16 +616,55 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
651
  output_components.append(locals()[f"caption_{i}"])
652
  caption_list.append(locals()[f"caption_{i}"])
653
 
 
654
  with gr.Accordion("Advanced options", open=False):
655
  steps = gr.Number(label="Steps", value=1000, minimum=1, maximum=10000, step=1)
656
  lr = gr.Number(label="Learning Rate", value=4e-4, minimum=1e-6, maximum=1e-3, step=1e-6)
657
  rank = gr.Number(label="LoRA Rank", value=16, minimum=4, maximum=128, step=4)
658
  with gr.Accordion("Even more advanced options", open=False):
659
- if(is_spaces):
660
- gr.Markdown("Attention: changing this parameters may make your training fail or go out-of-memory if training on Spaces. Only change settings here it if you know what you are doing. Beware that training is done in an L4 GPU with 24GB of RAM")
661
  use_more_advanced_options = gr.Checkbox(label="Use more advanced options", value=False)
662
- more_advanced_options = gr.Code(config_yaml, language="yaml")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
 
 
664
  with gr.Accordion("Sample prompts (optional)", visible=False) as sample:
665
  gr.Markdown(
666
  "Include sample prompts to test out your trained model. Don't forget to include your trigger word/sentence (optional)"
@@ -668,20 +672,28 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
668
  sample_1 = gr.Textbox(label="Test prompt 1")
669
  sample_2 = gr.Textbox(label="Test prompt 2")
670
  sample_3 = gr.Textbox(label="Test prompt 3")
 
 
671
  with gr.Group(visible=False) as cost_preview:
672
  cost_preview_info = gr.Markdown(elem_id="cost_preview_info", elem_classes="group_padding")
673
  payment_update = gr.Button("I have set up a payment method", visible=False)
 
 
674
  output_components.append(sample)
675
  output_components.append(sample_1)
676
  output_components.append(sample_2)
677
  output_components.append(sample_3)
678
- start = gr.Button("START ํด๋ฆญ('์•ฝ 25~30๋ถ„ ํ›„ ํ•™์Šต์ด ์ข…๋ฃŒ๋˜๊ณ  ์™„๋ฃŒ ๋ฉ”์‹œ์ง€๊ฐ€ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.)'", visible=False)
 
 
 
 
679
  progress_area = gr.Markdown("")
680
 
681
-
682
-
683
  dataset_folder = gr.State()
684
 
 
685
  images.upload(
686
  load_captioning,
687
  inputs=[images, concept_sentence],
@@ -707,14 +719,17 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
707
  outputs=[cost_preview, cost_preview_info, payment_update, start]
708
  )
709
 
710
- gr.on(
711
- triggers=[steps.change],
712
- fn=update_pricing,
713
  inputs=[steps],
714
  outputs=[cost_preview, cost_preview_info, payment_update, start]
715
  )
716
 
717
- start.click(fn=create_dataset, inputs=[images] + caption_list, outputs=dataset_folder).then(
 
 
 
 
718
  fn=start_training,
719
  inputs=[
720
  lora_name,
@@ -733,8 +748,12 @@ with gr.Blocks(theme=custom_theme, css=css) as demo:
733
  outputs=progress_area,
734
  )
735
 
736
- do_captioning.click(fn=run_captioning, inputs=[images, concept_sentence] + caption_list, outputs=caption_list)
737
-
 
 
 
738
 
 
739
  if __name__ == "__main__":
740
  demo.launch(server_name="0.0.0.0", server_port=7860, auth=("gini", "pick"), show_error=True)
 
5
  from fastapi import FastAPI
6
  from starlette.middleware.sessions import SessionMiddleware
7
  import sys
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import gradio as gr
9
  from PIL import Image
10
  import torch
 
14
  import yaml
15
  from slugify import slugify
16
  from transformers import AutoProcessor, AutoModelForCausalLM
17
+ import numpy as np
18
+
19
+ # Set environment variables
20
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
21
+
22
+ # Check if we're running on HF Spaces
23
+ is_spaces = True if os.environ.get("SPACE_ID") else False
24
 
25
+ # FastAPI app setup
26
  app = FastAPI()
27
  app.add_middleware(SessionMiddleware, secret_key="your-secret-key")
28
 
29
+ # Constants
 
 
 
 
 
 
30
  MAX_IMAGES = 150
31
 
32
+ # Hugging Face token setup
 
33
  HF_TOKEN = os.getenv("HF_TOKEN")
34
  if not HF_TOKEN:
35
  raise ValueError("HF_TOKEN environment variable is not set")
36
 
 
 
 
 
 
 
37
  os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
38
 
39
+ # Initialize HF API
40
  api = HfApi(token=HF_TOKEN)
41
 
42
+ # Create default train config
43
+ def get_default_train_config(lora_name, username, trigger_word=None):
44
+ """Generate a default training configuration"""
45
+ slugged_lora_name = slugify(lora_name)
46
+
47
+ config = {
48
+ "config": {
49
+ "name": slugged_lora_name,
50
+ "process": [{
51
+ "model": {
52
+ "name_or_path": "black-forest-labs/FLUX.1-dev",
53
+ "assistant_lora_path": None,
54
+ "low_vram": False,
55
+ },
56
+ "network": {
57
+ "linear": 16,
58
+ "linear_alpha": 16
59
+ },
60
+ "train": {
61
+ "skip_first_sample": True,
62
+ "steps": 1000,
63
+ "lr": 4e-4,
64
+ "disable_sampling": False
65
+ },
66
+ "datasets": [{
67
+ "folder_path": "", # Will be filled later
68
+ }],
69
+ "save": {
70
+ "push_to_hub": True,
71
+ "hf_repo_id": f"{username}/{slugged_lora_name}",
72
+ "hf_private": True,
73
+ "hf_token": HF_TOKEN
74
+ },
75
+ "sample": {
76
+ "sample_steps": 28,
77
+ "sample_every": 1000,
78
+ "prompts": []
79
+ }
80
+ }]
81
+ }
82
+ }
83
+
84
+ if trigger_word:
85
+ config["config"]["process"][0]["trigger_word"] = trigger_word
86
+
87
+ return config
88
+
89
+ # Helper functions
90
  def load_captioning(uploaded_files, concept_sentence):
91
+ """Load images and prepare captioning UI"""
92
  uploaded_images = [file for file in uploaded_files if not file.endswith('.txt')]
93
  txt_files = [file for file in uploaded_files if file.endswith('.txt')]
94
  txt_files_dict = {os.path.splitext(os.path.basename(txt_file))[0]: txt_file for txt_file in txt_files}
95
  updates = []
96
+
97
  if len(uploaded_images) <= 1:
98
  raise gr.Error(
99
+ "Please upload at least 2 images to train your model (the ideal number is between 4-30)"
100
  )
101
  elif len(uploaded_images) > MAX_IMAGES:
102
  raise gr.Error(f"For now, only {MAX_IMAGES} or less images are allowed for training")
103
+
104
+ # Update captioning area visibility
105
  updates.append(gr.update(visible=True))
106
+
107
+ # Update individual captioning rows
108
  for i in range(1, MAX_IMAGES + 1):
 
109
  visible = i <= len(uploaded_images)
110
 
 
111
  updates.append(gr.update(visible=visible))
112
+
 
113
  image_value = uploaded_images[i - 1] if visible else None
114
  updates.append(gr.update(value=image_value, visible=visible))
115
 
116
  corresponding_caption = False
117
+ if image_value:
118
  base_name = os.path.splitext(os.path.basename(image_value))[0]
 
 
119
  if base_name in txt_files_dict:
 
120
  with open(txt_files_dict[base_name], 'r') as file:
121
  corresponding_caption = file.read()
122
 
 
123
  text_value = corresponding_caption if visible and corresponding_caption else "[trigger]" if visible and concept_sentence else None
124
  updates.append(gr.update(value=text_value, visible=visible))
125
 
126
+ # Update sample caption area
127
  updates.append(gr.update(visible=True))
 
128
  updates.append(gr.update(placeholder=f'A portrait of person in a bustling cafe {concept_sentence}', value=f'A person in a bustling cafe {concept_sentence}'))
129
  updates.append(gr.update(placeholder=f"A mountainous landscape in the style of {concept_sentence}"))
130
  updates.append(gr.update(placeholder=f"A {concept_sentence} in a mall"))
131
+
132
  return updates
133
 
134
  def hide_captioning():
135
+ """Hide captioning UI elements"""
136
  return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
137
 
138
+ def create_dataset(images, *captions):
139
+ """Create dataset directory with images and captions"""
 
140
  destination_folder = str(f"datasets/{uuid.uuid4()}")
141
  if not os.path.exists(destination_folder):
142
  os.makedirs(destination_folder)
 
144
  jsonl_file_path = os.path.join(destination_folder, "metadata.jsonl")
145
  with open(jsonl_file_path, "a") as jsonl_file:
146
  for index, image in enumerate(images):
147
+ if image: # Skip None values
148
+ new_image_path = shutil.copy(image, destination_folder)
149
+ caption = captions[index]
150
+ file_name = os.path.basename(new_image_path)
151
+ data = {"file_name": file_name, "prompt": caption}
152
+ jsonl_file.write(json.dumps(data) + "\n")
 
 
153
 
154
  return destination_folder
155
 
 
156
  def run_captioning(images, concept_sentence, *captions):
157
+ """Run automatic captioning using Microsoft Florence model"""
158
+ try:
159
+ device = "cuda" if torch.cuda.is_available() else "cpu"
160
+ torch_dtype = torch.float16
161
+
162
+ # Load model and processor
163
+ model = AutoModelForCausalLM.from_pretrained(
164
+ "microsoft/Florence-2-large", torch_dtype=torch_dtype, trust_remote_code=True
165
+ ).to(device)
166
+ processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)
167
+
168
+ captions = list(captions)
169
+ for i, image_path in enumerate(images):
170
+ if not image_path: # Skip None values
171
+ continue
172
+
173
+ if isinstance(image_path, str): # If image is a file path
174
+ try:
175
+ image = Image.open(image_path).convert("RGB")
176
+ except Exception as e:
177
+ print(f"Error opening image {image_path}: {e}")
178
+ continue
179
+
180
+ prompt = "<DETAILED_CAPTION>"
181
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to(device, torch_dtype)
182
+
183
+ generated_ids = model.generate(
184
+ input_ids=inputs["input_ids"],
185
+ pixel_values=inputs["pixel_values"],
186
+ max_new_tokens=1024,
187
+ num_beams=3
188
+ )
189
+
190
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
191
+ parsed_answer = processor.post_process_generation(
192
+ generated_text, task=prompt, image_size=(image.width, image.height)
193
+ )
194
+ caption_text = parsed_answer["<DETAILED_CAPTION>"].replace("The image shows ", "")
195
+ if concept_sentence:
196
+ caption_text = f"{caption_text} [trigger]"
197
+
198
+ captions[i] = caption_text
199
+ yield captions
200
+
201
+ # Clean up to free memory
202
+ model.to("cpu")
203
+ del model
204
+ del processor
205
+ torch.cuda.empty_cache()
206
+
207
+ except Exception as e:
208
+ print(f"Error in captioning: {e}")
209
+ raise gr.Error(f"Captioning failed: {str(e)}")
210
 
211
+ def update_pricing(steps):
212
+ """Update estimated cost based on training steps"""
213
+ try:
214
+ seconds_per_iteration = 7.54
215
+ total_seconds = (steps * seconds_per_iteration) + 240
216
+ cost_per_second = 0.80/60/60
217
+ cost = round(cost_per_second * total_seconds, 2)
218
+ cost_preview = f'''To train this LoRA, a paid L4 GPU will be used during training.
219
+ ### Estimated to take <b>~{round(int(total_seconds)/60, 2)} minutes</b> with your current settings <small>({int(steps)} iterations)</small>'''
220
+ return gr.update(visible=True), cost_preview, gr.update(visible=False), gr.update(visible=True)
221
+ except:
222
+ return gr.update(visible=False), "", gr.update(visible=False), gr.update(visible=True)
223
 
224
+ def run_training_process(config_path):
225
+ """Run the actual training process"""
226
+ try:
227
+ # This is a simplified placeholder for the actual training code
228
+ # Instead of using the ai-toolkit which is causing errors, we'll implement our own training logic
229
+
230
+ # Call to a direct training script that doesn't require the problematic dependencies
231
+ script_path = os.path.join(os.getcwd(), "direct_train_lora.py")
232
+ with open(script_path, "w") as f:
233
+ f.write("""
234
+ import os
235
+ import sys
236
+ import yaml
237
+ import torch
238
+ from peft import LoraConfig, get_peft_model
239
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
240
+ from datasets import load_dataset
241
+ import json
242
 
243
+ def train_lora(config_path):
244
+ # Load config
245
+ with open(config_path, 'r') as f:
246
+ config = yaml.safe_load(f)
247
+
248
+ process_config = config['config']['process'][0]
249
+
250
+ # Get basic parameters
251
+ model_name = process_config['model']['name_or_path']
252
+ lora_rank = process_config['network']['linear']
253
+ steps = process_config['train']['steps']
254
+ lr = process_config['train']['lr']
255
+ dataset_path = process_config['datasets'][0]['folder_path']
256
+ repo_id = process_config['save']['hf_repo_id']
257
+ hf_token = process_config['save']['hf_token']
258
+
259
+ # Load dataset
260
+ dataset = []
261
+ with open(os.path.join(dataset_path, "metadata.jsonl"), 'r') as f:
262
+ for line in f:
263
+ data = json.loads(line)
264
+ image_path = os.path.join(dataset_path, data['file_name'])
265
+ prompt = data['prompt']
266
+ dataset.append({"image_path": image_path, "text": prompt})
267
+
268
+ # Load base model
269
+ print(f"Loading model {model_name}")
270
+ model = AutoModelForCausalLM.from_pretrained(
271
+ model_name,
272
+ torch_dtype=torch.float16,
273
+ device_map="auto",
274
+ trust_remote_code=True,
275
+ use_auth_token=hf_token
276
+ )
277
+
278
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=hf_token)
279
+
280
+ # Configure LoRA
281
+ lora_config = LoraConfig(
282
+ r=lora_rank,
283
+ lora_alpha=lora_rank,
284
+ target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
285
+ lora_dropout=0.05,
286
+ bias="none",
287
+ task_type="CAUSAL_LM"
288
+ )
289
+
290
+ # Apply LoRA
291
+ model = get_peft_model(model, lora_config)
292
+
293
+ # Training parameters
294
+ training_args = TrainingArguments(
295
+ output_dir=f"./lora_train/{repo_id.split('/')[-1]}",
296
+ num_train_epochs=3,
297
+ per_device_train_batch_size=1,
298
+ gradient_accumulation_steps=4,
299
+ learning_rate=lr,
300
+ max_steps=steps,
301
+ fp16=True,
302
+ logging_steps=10,
303
+ save_steps=steps // 2,
304
+ push_to_hub=True,
305
+ hub_model_id=repo_id,
306
+ hub_token=hf_token,
307
+ )
308
+
309
+ # Simple dataset preparation
310
+ def process_batch(examples):
311
+ return tokenizer(
312
+ examples["text"],
313
+ padding="max_length",
314
+ truncation=True,
315
+ max_length=256
316
  )
317
+
318
+ # Convert dataset to huggingface format
319
+ train_dataset = load_dataset('json', data_files={'train': dataset_path + '/metadata.jsonl'})['train']
320
+
321
+ # Set up trainer
322
+ trainer = Trainer(
323
+ model=model,
324
+ args=training_args,
325
+ train_dataset=train_dataset,
326
+ data_collator=lambda data: {'input_ids': torch.stack([f['input_ids'] for f in data]),
327
+ 'attention_mask': torch.stack([f['attention_mask'] for f in data])},
328
+ )
329
+
330
+ # Train
331
+ print("Starting training...")
332
+ trainer.train()
333
+
334
+ # Save and push to hub
335
+ model.save_pretrained(f"./lora_final/{repo_id.split('/')[-1]}")
336
+ tokenizer.save_pretrained(f"./lora_final/{repo_id.split('/')[-1]}")
337
+
338
+ if process_config['save']['push_to_hub']:
339
+ model.push_to_hub(repo_id, use_auth_token=hf_token)
340
+ tokenizer.push_to_hub(repo_id, use_auth_token=hf_token)
341
+
342
+ print(f"Training completed! Model saved to {repo_id}")
343
+ return repo_id
344
 
345
+ if __name__ == "__main__":
346
+ if len(sys.argv) > 1:
347
+ train_lora(sys.argv[1])
348
+ else:
349
+ print("Please provide config path")
350
+ """)
351
+
352
+ result = subprocess.run([sys.executable, script_path, config_path],
353
+ capture_output=True, text=True, check=True)
354
+ print(result.stdout)
355
+ if result.returncode != 0:
356
+ raise Exception(f"Training script failed: {result.stderr}")
357
+
358
+ # Extract repo ID from config
359
+ with open(config_path, "r") as f:
360
+ config = yaml.safe_load(f)
361
+ repo_id = config["config"]["process"][0]["save"]["hf_repo_id"]
362
+
363
+ return repo_id
364
+ except Exception as e:
365
+ raise Exception(f"Training process failed: {str(e)}")
 
 
 
366
 
367
  def start_training(
368
  lora_name,
 
378
  use_more_advanced_options,
379
  more_advanced_options,
380
  ):
381
+ """Start the LoRA training process"""
382
  if not lora_name:
383
  raise gr.Error("You forgot to insert your LoRA name! This name has to be unique.")
384
 
 
390
  print("Started training")
391
  slugged_lora_name = slugify(lora_name)
392
 
393
+ # Get base config
394
+ config = get_default_train_config(lora_name, username, concept_sentence)
395
+
396
+ # Update config with form values
 
 
 
 
 
 
397
  config["config"]["process"][0]["train"]["steps"] = int(steps)
398
  config["config"]["process"][0]["train"]["lr"] = float(lr)
399
  config["config"]["process"][0]["network"]["linear"] = int(rank)
400
  config["config"]["process"][0]["network"]["linear_alpha"] = int(rank)
401
  config["config"]["process"][0]["datasets"][0]["folder_path"] = dataset_folder
 
 
 
 
 
 
 
 
402
 
403
+ # Add sample prompts if provided
404
  if sample_1 or sample_2 or sample_3:
 
 
405
  config["config"]["process"][0]["sample"]["prompts"] = []
406
  if sample_1:
407
  config["config"]["process"][0]["sample"]["prompts"].append(sample_1)
 
412
  else:
413
  config["config"]["process"][0]["train"]["disable_sampling"] = True
414
 
415
+ # Apply advanced options if enabled
416
+ if use_more_advanced_options:
417
+ try:
418
+ more_advanced_options_dict = yaml.safe_load(more_advanced_options)
419
+ def recursive_update(d, u):
420
+ for k, v in u.items():
421
+ if isinstance(v, dict) and v:
422
+ d[k] = recursive_update(d.get(k, {}), v)
423
+ else:
424
+ d[k] = v
425
+ return d
426
+ config["config"]["process"][0] = recursive_update(config["config"]["process"][0], more_advanced_options_dict)
427
+ except Exception as e:
428
+ raise gr.Error(f"Error in advanced options: {str(e)}")
429
 
430
  try:
431
+ # Save the config
 
432
  os.makedirs("tmp", exist_ok=True)
433
+ config_path = f"tmp/{uuid.uuid4()}-{slugged_lora_name}.yaml"
434
  with open(config_path, "w") as f:
435
  yaml.dump(config, f)
436
 
437
+ # Run training process
438
+ repo_id = run_training_process(config_path)
439
+
440
+ return f"""# Training completed successfully!
441
+ ## Your model is available at: <a href='https://huggingface.co/{repo_id}'>{repo_id}</a>"""
442
  except Exception as e:
443
  raise gr.Error(f"Training failed: {str(e)}")
444
 
445
+ # UI Theme and CSS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  custom_theme = gr.themes.Base(
447
  primary_hue="indigo",
448
  secondary_hue="slate",
449
  neutral_hue="slate",
450
  ).set(
 
451
  background_fill_primary="#1a1a1a",
452
  background_fill_secondary="#2d2d2d",
453
  border_color_primary="#404040",
454
 
 
455
  button_primary_background_fill="#4F46E5",
456
  button_primary_background_fill_dark="#4338CA",
457
  button_primary_background_fill_hover="#6366F1",
 
466
  button_secondary_text_color="white",
467
  button_secondary_text_color_dark="white",
468
 
 
469
  block_background_fill="#2d2d2d",
470
  block_background_fill_dark="#1F2937",
471
  block_label_background_fill="#4F46E5",
 
475
  block_title_text_color="white",
476
  block_title_text_color_dark="white",
477
 
 
478
  input_background_fill="#374151",
479
  input_background_fill_dark="#1F2937",
480
  input_border_color="#4B5563",
481
  input_border_color_dark="#374151",
482
  input_placeholder_color="#9CA3AF",
483
  input_placeholder_color_dark="#6B7280",
 
 
 
 
 
 
 
 
 
 
 
 
484
  )
485
 
486
+ css = '''
487
+ /* Base styles */
488
  h1 {
489
+ font-size: 2.5em;
490
  text-align: center;
491
  margin-bottom: 0.5em;
492
  color: white !important;
 
498
  color: white !important;
499
  }
500
 
501
+ /* Ensure all text is white */
502
+ .markdown, .markdown h1, .markdown h2, .markdown h3,
503
+ .markdown h4, .markdown h5, .markdown h6, .markdown p,
504
+ label, .label-text, .gradio-radio label span, .gradio-checkbox label span,
505
+ input, textarea, .gradio-textbox input, .gradio-textbox textarea,
506
+ .gradio-number input, select, option, button {
507
  color: white !important;
508
  }
509
 
510
+ /* Input style improvements */
511
+ input[type="text"], textarea, .input-text, .input-textarea {
512
+ background-color: #374151 !important;
513
+ border-color: #4B5563 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
  color: white !important;
515
  }
516
 
517
+ /* Button styling */
518
+ button {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  transition: all 0.3s ease;
 
520
  }
521
 
522
+ button:hover {
523
  transform: translateY(-2px);
524
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
525
  }
526
 
527
+ /* Image area */
528
  .image-upload-area {
529
+ border: 2px dashed #4B5563;
530
  border-radius: 12px;
531
  padding: 20px;
532
  text-align: center;
533
  margin-bottom: 20px;
 
 
 
 
 
 
 
 
 
 
534
  }
535
 
536
+ /* Caption rows */
537
  .caption-row {
538
  display: flex;
539
  align-items: center;
540
  margin-bottom: 10px;
541
  gap: 10px;
542
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  '''
544
 
545
+ # Gradio UI
546
  with gr.Blocks(theme=custom_theme, css=css) as demo:
 
547
  gr.Markdown(
548
+ """# ๐Ÿ†” Gini LoRA ํ•™์Šต
549
+ ### 1) LoRA ์ด๋ฆ„ ์ž…๋ ฅ 2) ํŠธ๋ฆฌ๊ฑฐ ๋‹จ์–ด ์ž…๋ ฅ 3) ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ(2-30์žฅ ๊ถŒ์žฅ) 4) ๋น„์ „ ์ธ์‹ LLM ๋ผ๋ฒจ๋ง 5) START ํด๋ฆญ""",
550
+ elem_classes=["markdown"]
551
+ )
552
 
553
  with gr.Tab("Train"):
554
+ with gr.Column():
555
+ # LoRA ์„ค์ •
556
+ with gr.Group():
557
  with gr.Row():
558
  lora_name = gr.Textbox(
559
  label="LoRA ์ด๋ฆ„",
560
  info="๊ณ ์œ ํ•œ ์ด๋ฆ„์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค",
561
+ placeholder="์˜ˆ: Persian Miniature Style, Cat Toy"
562
  )
563
  concept_sentence = gr.Textbox(
564
  label="ํŠธ๋ฆฌ๊ฑฐ ๋‹จ์–ด/๋ฌธ์žฅ",
 
570
  which_model = gr.Radio(
571
  ["๊ณ ํ€„๋ฆฌํ‹ฐ ๋งž์ถค ํ•™์Šต ๋ชจ๋ธ"],
572
  label="๊ธฐ๋ณธ ๋ชจ๋ธ",
573
+ value="๊ณ ํ€„๋ฆฌํ‹ฐ ๋งž์ถค ํ•™์Šต ๋ชจ๋ธ"
574
  )
575
 
576
+ # ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ
577
  with gr.Group(visible=True, elem_classes="image-upload-area") as image_upload:
 
578
  with gr.Row():
579
  images = gr.File(
580
  file_types=["image", ".txt"],
 
588
  with gr.Column():
589
  gr.Markdown(
590
  """# ์ด๋ฏธ์ง€ ๋ผ๋ฒจ๋ง
591
+ <p style="margin-top:0"> ๋น„์ „์ธ์‹ LLM์ด ์ด๋ฏธ์ง€๋ฅผ ์ธ์‹ํ•˜์—ฌ ์ž๋™์œผ๋กœ ๋ผ๋ฒจ๋ง(์ด๋ฏธ์ง€ ์ธ์‹์„ ์œ„ํ•œ ํ•„์ˆ˜ ์„ค๋ช…). [trigger] 'ํŠธ๋ฆฌ๊ฑฐ ์›Œ๋“œ'๋Š” ํ•™์Šตํ•œ ๋ชจ๋ธ์„ ์‹คํ–‰ํ•˜๋Š” ๊ณ ์œ  ํ‚ค๊ฐ’</p>
592
+ """, elem_classes="group_padding")
593
  do_captioning = gr.Button("๋น„์ „ ์ธ์‹ LLM ์ž๋™ ๋ผ๋ฒจ๋ง")
594
  output_components = [captioning_area]
595
  caption_list = []
 
616
  output_components.append(locals()[f"caption_{i}"])
617
  caption_list.append(locals()[f"caption_{i}"])
618
 
619
+ # ๊ณ ๊ธ‰ ์„ค์ •
620
  with gr.Accordion("Advanced options", open=False):
621
  steps = gr.Number(label="Steps", value=1000, minimum=1, maximum=10000, step=1)
622
  lr = gr.Number(label="Learning Rate", value=4e-4, minimum=1e-6, maximum=1e-3, step=1e-6)
623
  rank = gr.Number(label="LoRA Rank", value=16, minimum=4, maximum=128, step=4)
624
  with gr.Accordion("Even more advanced options", open=False):
 
 
625
  use_more_advanced_options = gr.Checkbox(label="Use more advanced options", value=False)
626
+ more_advanced_options = gr.Code(
627
+ value="""
628
+ device: cuda:0
629
+ model:
630
+ is_flux: true
631
+ quantize: true
632
+ network:
633
+ linear: 16
634
+ linear_alpha: 16
635
+ type: lora
636
+ sample:
637
+ guidance_scale: 3.5
638
+ height: 1024
639
+ neg: ''
640
+ sample_steps: 28
641
+ sampler: flowmatch
642
+ seed: 42
643
+ walk_seed: true
644
+ width: 1024
645
+ save:
646
+ dtype: float16
647
+ hf_private: true
648
+ max_step_saves_to_keep: 4
649
+ push_to_hub: true
650
+ save_every: 10000
651
+ train:
652
+ batch_size: 1
653
+ dtype: bf16
654
+ ema_config:
655
+ ema_decay: 0.99
656
+ use_ema: true
657
+ gradient_accumulation_steps: 1
658
+ gradient_checkpointing: true
659
+ noise_scheduler: flowmatch
660
+ optimizer: adamw8bit
661
+ train_text_encoder: false
662
+ train_unet: true
663
+ """,
664
+ language="yaml"
665
+ )
666
 
667
+ # ์ƒ˜ํ”Œ ํ”„๋กฌํ”„ํŠธ
668
  with gr.Accordion("Sample prompts (optional)", visible=False) as sample:
669
  gr.Markdown(
670
  "Include sample prompts to test out your trained model. Don't forget to include your trigger word/sentence (optional)"
 
672
  sample_1 = gr.Textbox(label="Test prompt 1")
673
  sample_2 = gr.Textbox(label="Test prompt 2")
674
  sample_3 = gr.Textbox(label="Test prompt 3")
675
+
676
+ # ๋น„์šฉ ์•ˆ๋‚ด
677
  with gr.Group(visible=False) as cost_preview:
678
  cost_preview_info = gr.Markdown(elem_id="cost_preview_info", elem_classes="group_padding")
679
  payment_update = gr.Button("I have set up a payment method", visible=False)
680
+
681
+ # ์กฐํ•ฉ ๋ณ€์ˆ˜
682
  output_components.append(sample)
683
  output_components.append(sample_1)
684
  output_components.append(sample_2)
685
  output_components.append(sample_3)
686
+
687
+ # ์‹œ์ž‘ ๋ฒ„ํŠผ
688
+ start = gr.Button("START ํด๋ฆญ ('์•ฝ 15-20๋ถ„ ํ›„ ํ•™์Šต์ด ์ข…๋ฃŒ๋˜๊ณ  ์™„๋ฃŒ ๋ฉ”์‹œ์ง€๊ฐ€ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค')", visible=False)
689
+
690
+ # ์ง„ํ–‰ ์ƒํƒœ
691
  progress_area = gr.Markdown("")
692
 
693
+ # ์ƒํƒœ ๋ณ€์ˆ˜
 
694
  dataset_folder = gr.State()
695
 
696
+ # ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ
697
  images.upload(
698
  load_captioning,
699
  inputs=[images, concept_sentence],
 
719
  outputs=[cost_preview, cost_preview_info, payment_update, start]
720
  )
721
 
722
+ steps.change(
723
+ update_pricing,
 
724
  inputs=[steps],
725
  outputs=[cost_preview, cost_preview_info, payment_update, start]
726
  )
727
 
728
+ start.click(
729
+ fn=create_dataset,
730
+ inputs=[images] + caption_list,
731
+ outputs=dataset_folder
732
+ ).then(
733
  fn=start_training,
734
  inputs=[
735
  lora_name,
 
748
  outputs=progress_area,
749
  )
750
 
751
+ do_captioning.click(
752
+ fn=run_captioning,
753
+ inputs=[images, concept_sentence] + caption_list,
754
+ outputs=caption_list
755
+ )
756
 
757
+ # Launch the app
758
  if __name__ == "__main__":
759
  demo.launch(server_name="0.0.0.0", server_port=7860, auth=("gini", "pick"), show_error=True)