openfree commited on
Commit
b6d7423
·
verified ·
1 Parent(s): 32ceba2

Delete app-backup1.py

Browse files
Files changed (1) hide show
  1. app-backup1.py +0 -510
app-backup1.py DELETED
@@ -1,510 +0,0 @@
1
- import os
2
- import subprocess
3
- from typing import Union
4
- 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
37
- import uuid
38
- import shutil
39
- 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)
131
-
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,
195
- concept_sentence,
196
- which_model,
197
- steps,
198
- lr,
199
- rank,
200
- dataset_folder,
201
- sample_1,
202
- sample_2,
203
- sample_3,
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
-
210
- try:
211
- username = whoami()["name"]
212
- except:
213
- raise gr.Error("Failed to get username. Please check your HF_TOKEN.")
214
-
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)
248
- if sample_2:
249
- config["config"]["process"][0]["sample"]["prompts"].append(sample_2)
250
- if sample_3:
251
- config["config"]["process"][0]["sample"]["prompts"].append(sample_3)
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
- theme = gr.themes.Monochrome(
337
- text_size=gr.themes.Size(lg="18px", md="15px", sm="13px", xl="22px", xs="12px", xxl="24px", xxs="9px"),
338
- font=[gr.themes.GoogleFont("Source Sans Pro"), "ui-sans-serif", "system-ui", "sans-serif"],
339
- )
340
-
341
-
342
- css = """
343
- h1{font-size: 2em}
344
- h3{margin-top: 0}
345
- #component-1{text-align:center}
346
- .tabitem{border: 0px}
347
- .group_padding{padding: .55em}
348
- """
349
-
350
- with gr.Blocks(theme=theme, css=css) as demo:
351
- gr.Markdown(
352
- """# 🆔 Gini LoRA 학습
353
- ### 이미지들(최대 150장 미만)을 업로드하세요. """
354
- )
355
-
356
- with gr.Tab("Train"): # 탭 이름 변경
357
- with gr.Column(): # main_ui 대신 직접 Column 사용
358
- with gr.Group():
359
- with gr.Row():
360
- lora_name = gr.Textbox(
361
- label="The name of your LoRA",
362
- info="This has to be a unique name",
363
- placeholder="e.g.: Persian Miniature Painting style, Cat Toy",
364
- )
365
- concept_sentence = gr.Textbox(
366
- label="Trigger word/sentence",
367
- info="Trigger word or sentence to be used",
368
- placeholder="uncommon word like p3rs0n or trtcrd, or sentence like 'in the style of CNSTLL'",
369
- interactive=True,
370
- )
371
- # model_warning 변수 추가
372
- model_warning = gr.Markdown(visible=False)
373
-
374
- which_model = gr.Radio(
375
- ["[dev] (high quality model)"],
376
- label="Base model",
377
- value="[dev] (high quality model)"
378
- )
379
-
380
-
381
-
382
- with gr.Group(visible=True) as image_upload:
383
- with gr.Row():
384
- images = gr.File(
385
- file_types=["image", ".txt"],
386
- label="Upload your images",
387
- file_count="multiple",
388
- interactive=True,
389
- visible=True,
390
- scale=1,
391
- )
392
- with gr.Column(scale=3, visible=False) as captioning_area:
393
- with gr.Column():
394
- gr.Markdown(
395
- """# 이미지 라벨링
396
- <p style="margin-top:0"> 비전인식 LLM이 이미지를 인식하여 자동으로 라벨링(이미지 인식을 위한 필수 설명). [trigger] '트리거 워드'는 학습한 모델을 실행하는 고유 키값 /trigger word.</p>
397
- """, elem_classes="group_padding")
398
- do_captioning = gr.Button("비전 인식 LLM 자동 라벨���")
399
- output_components = [captioning_area]
400
- caption_list = []
401
- for i in range(1, MAX_IMAGES + 1):
402
- locals()[f"captioning_row_{i}"] = gr.Row(visible=False)
403
- with locals()[f"captioning_row_{i}"]:
404
- locals()[f"image_{i}"] = gr.Image(
405
- type="filepath",
406
- width=111,
407
- height=111,
408
- min_width=111,
409
- interactive=False,
410
- scale=2,
411
- show_label=False,
412
- show_share_button=False,
413
- show_download_button=False,
414
- )
415
- locals()[f"caption_{i}"] = gr.Textbox(
416
- label=f"Caption {i}", scale=15, interactive=True
417
- )
418
-
419
- output_components.append(locals()[f"captioning_row_{i}"])
420
- output_components.append(locals()[f"image_{i}"])
421
- output_components.append(locals()[f"caption_{i}"])
422
- caption_list.append(locals()[f"caption_{i}"])
423
-
424
- with gr.Accordion("Advanced options", open=False):
425
- steps = gr.Number(label="Steps", value=1000, minimum=1, maximum=10000, step=1)
426
- lr = gr.Number(label="Learning Rate", value=4e-4, minimum=1e-6, maximum=1e-3, step=1e-6)
427
- rank = gr.Number(label="LoRA Rank", value=16, minimum=4, maximum=128, step=4)
428
- with gr.Accordion("Even more advanced options", open=False):
429
- if(is_spaces):
430
- 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")
431
- use_more_advanced_options = gr.Checkbox(label="Use more advanced options", value=False)
432
- more_advanced_options = gr.Code(config_yaml, language="yaml")
433
-
434
- with gr.Accordion("Sample prompts (optional)", visible=False) as sample:
435
- gr.Markdown(
436
- "Include sample prompts to test out your trained model. Don't forget to include your trigger word/sentence (optional)"
437
- )
438
- sample_1 = gr.Textbox(label="Test prompt 1")
439
- sample_2 = gr.Textbox(label="Test prompt 2")
440
- sample_3 = gr.Textbox(label="Test prompt 3")
441
- with gr.Group(visible=False) as cost_preview:
442
- cost_preview_info = gr.Markdown(elem_id="cost_preview_info", elem_classes="group_padding")
443
- payment_update = gr.Button("I have set up a payment method", visible=False)
444
- output_components.append(sample)
445
- output_components.append(sample_1)
446
- output_components.append(sample_2)
447
- output_components.append(sample_3)
448
- start = gr.Button("Start training", visible=False)
449
- progress_area = gr.Markdown("")
450
-
451
-
452
-
453
- dataset_folder = gr.State()
454
-
455
- images.upload(
456
- load_captioning,
457
- inputs=[images, concept_sentence],
458
- outputs=output_components
459
- ).then(
460
- update_pricing,
461
- inputs=[steps],
462
- outputs=[cost_preview, cost_preview_info, payment_update, start]
463
- )
464
-
465
- images.clear(
466
- hide_captioning,
467
- outputs=[captioning_area, cost_preview, sample, start]
468
- )
469
-
470
- images.delete(
471
- load_captioning,
472
- inputs=[images, concept_sentence],
473
- outputs=output_components
474
- ).then(
475
- update_pricing,
476
- inputs=[steps],
477
- outputs=[cost_preview, cost_preview_info, payment_update, start]
478
- )
479
-
480
- gr.on(
481
- triggers=[steps.change],
482
- fn=update_pricing,
483
- inputs=[steps],
484
- outputs=[cost_preview, cost_preview_info, payment_update, start]
485
- )
486
-
487
- start.click(fn=create_dataset, inputs=[images] + caption_list, outputs=dataset_folder).then(
488
- fn=start_training,
489
- inputs=[
490
- lora_name,
491
- concept_sentence,
492
- which_model,
493
- steps,
494
- lr,
495
- rank,
496
- dataset_folder,
497
- sample_1,
498
- sample_2,
499
- sample_3,
500
- use_more_advanced_options,
501
- more_advanced_options
502
- ],
503
- outputs=progress_area,
504
- )
505
-
506
- do_captioning.click(fn=run_captioning, inputs=[images, concept_sentence] + caption_list, outputs=caption_list)
507
-
508
-
509
- if __name__ == "__main__":
510
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)