label_script.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. USER_TEXT = """
  2. You are an expert fashion captioner, we are writing descriptions of clothes, look at the image closely and write a caption for it.
  3. Write the following Title, Size, Category, Gender, Type, Description in JSON FORMAT, PLEASE DO NOT FORGET JSON, I WILL BE VERY SAD AND CRY
  4. ALSO START WITH THE JSON AND NOT ANY THING ELSE, FIRST CHAR IN YOUR RESPONSE IS ITS OPENING BRACE, I WILL DRINK CHAI IF YOU FOLLOW THIS
  5. FOLLOW THESE STEPS CLOSELY WHEN WRITING THE CAPTION:
  6. 1. Only start your response with a dictionary like the example below, nothing else, I NEED TO PARSE IT LATER, SO DONT ADD ANYTHING ELSE-IT WILL BREAK MY CODE AND I WILL BE VERY SAD
  7. Remember-DO NOT SAY ANYTHING ELSE ABOUT WHAT IS GOING ON, just the opening brace is the first thing in your response nothing else ok?
  8. 2. REMEMBER TO CLOSE THE DICTIONARY WITH '}'BRACE, IT GOES AFTER THE END OF DESCRIPTION-YOU ALWAYS FORGET IT, THIS WILL CAUSE A FIRE ON A PRODUCTION SERVER BEING USE BY MILLIONS
  9. 3. If you cant tell the size from image, guess it! its okay but dont literally write that you guessed it
  10. 4. Do not make the caption very literal, all of these are product photos, DO NOT CAPTION HOW OR WHERE THEY ARE PLACED, FOCUS ON WRITING ABOUT THE PIECE OF CLOTHING
  11. 5. BE CREATIVE WITH THE DESCRIPTION BUT FOLLOW EVERYTHING CLOSELY FOR STRUCTURE
  12. 6. Return your answer in dictionary format, see the example below
  13. 7. Please do NOT add new lines or tabs in the JSON
  14. 8. I REPEAT DO NOT GIVE ME YOUR EXPLAINATION START WITH THE JSON
  15. {"Title": "Title of item of clothing", "Size": {'S', 'M', 'L', 'XL'}, #select one randomly if you cant tell from the image. DO NOT TELL ME YOU ESTIMATE OR GUESSED IT ONLY THE LETTER IS ENOUGH", Category": {T-Shirt, Shoes, Tops, Pants, Jeans, Shorts, Skirts, Shoes, Footwear}, "Gender": {M, F, U}, "Type": {Casual, Formal, Work Casual, Lounge}, "Description": "Write it here"}
  16. Example: ALWAYS RETURN ANSWERS IN THE DICTIONARY FORMAT BELOW OK?
  17. {"Title": "Casual White pant with logo on it", "size": "L", "Category": "Jeans", "Gender": "U", "Type": "Work Casual", "Description": "Write it here, this is where your stuff goes"}
  18. """
  19. import os
  20. import argparse
  21. import torch
  22. from transformers import MllamaForConditionalGeneration, MllamaProcessor
  23. from tqdm.auto import tqdm
  24. import csv
  25. from PIL import Image
  26. import torch.multiprocessing as mp
  27. from concurrent.futures import ProcessPoolExecutor
  28. import shutil
  29. import time
  30. def is_image_corrupt(image_path):
  31. try:
  32. with Image.open(image_path) as img:
  33. img.verify()
  34. return False
  35. except (IOError, SyntaxError, Image.UnidentifiedImageError):
  36. return True
  37. def find_and_move_corrupt_images(folder_path, corrupt_folder):
  38. image_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path)
  39. if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
  40. num_cores = mp.cpu_count()
  41. with tqdm(total=len(image_files), desc="Checking for corrupt images", unit="file",
  42. bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]") as pbar:
  43. with ProcessPoolExecutor(max_workers=num_cores) as executor:
  44. results = list(executor.map(is_image_corrupt, image_files))
  45. pbar.update(len(image_files))
  46. corrupt_images = [img for img, is_corrupt in zip(image_files, results) if is_corrupt]
  47. os.makedirs(corrupt_folder, exist_ok=True)
  48. for img in tqdm(corrupt_images, desc="Moving corrupt images", unit="file",
  49. bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]"):
  50. shutil.move(img, os.path.join(corrupt_folder, os.path.basename(img)))
  51. print(f"Moved {len(corrupt_images)} corrupt images to {corrupt_folder}")
  52. def get_image(image_path):
  53. return Image.open(image_path).convert('RGB')
  54. def process_images(rank, world_size, args, model_name, input_files, output_csv):
  55. model = MllamaForConditionalGeneration.from_pretrained(model_name, device_map=f"cuda:{rank}", torch_dtype=torch.bfloat16, token=args.hf_token)
  56. processor = MllamaProcessor.from_pretrained(model_name, token=args.hf_token)
  57. chunk_size = len(input_files) // world_size
  58. start_idx = rank * chunk_size
  59. end_idx = start_idx + chunk_size if rank < world_size - 1 else len(input_files)
  60. results = []
  61. pbar = tqdm(input_files[start_idx:end_idx],
  62. desc=f"GPU {rank}",
  63. unit="img",
  64. position=rank,
  65. leave=True,
  66. bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]")
  67. for filename in pbar:
  68. image_path = os.path.join(args.input_path, filename)
  69. image = get_image(image_path)
  70. conversation = [
  71. {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": USER_TEXT}]}
  72. ]
  73. prompt = processor.apply_chat_template(conversation, add_special_tokens=False, add_generation_prompt=True, tokenize=False)
  74. inputs = processor(image, prompt, return_tensors="pt").to(model.device)
  75. output = model.generate(**inputs, temperature=1, top_p=0.9, max_new_tokens=512)
  76. decoded_output = processor.decode(output[0])[len(prompt):]
  77. results.append((filename, decoded_output))
  78. pbar.set_postfix({"Last File": filename})
  79. with open(output_csv, 'w', newline='', encoding='utf-8') as f:
  80. writer = csv.writer(f)
  81. writer.writerow(['Filename', 'Caption'])
  82. writer.writerows(results)
  83. def main():
  84. parser = argparse.ArgumentParser(description="Multi-GPU Image Captioning")
  85. parser.add_argument("--hf_token", required=True, help="Hugging Face API token")
  86. parser.add_argument("--input_path", required=True, help="Path to input image folder")
  87. parser.add_argument("--output_path", required=True, help="Path to output CSV folder")
  88. parser.add_argument("--num_gpus", type=int, required=True, help="Number of GPUs to use")
  89. parser.add_argument("--corrupt_folder", default="corrupt_images", help="Folder to move corrupt images")
  90. args = parser.parse_args()
  91. model_name = "meta-llama/Llama-3.2-11b-Vision-Instruct"
  92. print("Starting image processing pipeline...")
  93. start_time = time.time()
  94. # Find and move corrupt images
  95. corrupt_folder = os.path.join(args.input_path, args.corrupt_folder)
  96. find_and_move_corrupt_images(args.input_path, corrupt_folder)
  97. # Get list of remaining (non-corrupt) image files
  98. input_files = [f for f in os.listdir(args.input_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
  99. print(f"\nProcessing {len(input_files)} images using {args.num_gpus} GPUs...")
  100. mp.set_start_method('spawn', force=True)
  101. processes = []
  102. for rank in range(args.num_gpus):
  103. output_csv = os.path.join(args.output_path, f"captions_gpu_{rank}.csv")
  104. p = mp.Process(target=process_images, args=(rank, args.num_gpus, args, model_name, input_files, output_csv))
  105. p.start()
  106. processes.append(p)
  107. for p in processes:
  108. p.join()
  109. end_time = time.time()
  110. total_time = end_time - start_time
  111. print(f"\nTotal processing time: {total_time:.2f} seconds")
  112. print("Image captioning completed successfully!")
  113. if __name__ == "__main__":
  114. main()