tabnation

python mass image renamer

Mar 26th, 2026
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1.  
  2. # pip install transformers torch pillow
  3.  
  4. import os
  5. import re
  6. from PIL import Image
  7. from transformers import BlipProcessor, BlipForConditionalGeneration
  8.  
  9. folder = r"C:\Users\thoma\OneDrive\Desktop\openmoji-618x618-color" # change to your folder
  10.  
  11. processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
  12. model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
  13.  
  14. stop_words = [
  15. "a","an","the","image","photo","picture","of","with",
  16. "and","on","in","there","is"
  17. ]
  18.  
  19. def simplify_caption(text):
  20.  
  21. text = text.lower()
  22.  
  23. words = re.findall(r"[a-z]+", text)
  24.  
  25. words = [w for w in words if w not in stop_words]
  26.  
  27. words = words[:3] # limit to 3 words
  28.  
  29. return "-".join(words)
  30.  
  31.  
  32. for file in os.listdir(folder):
  33.  
  34. if file.lower().endswith((".png",".jpg",".jpeg",".webp")):
  35.  
  36. path = os.path.join(folder,file)
  37.  
  38. try:
  39.  
  40. image = Image.open(path).convert("RGB")
  41.  
  42. inputs = processor(image, return_tensors="pt")
  43. output = model.generate(**inputs)
  44.  
  45. caption = processor.decode(output[0], skip_special_tokens=True)
  46.  
  47. name = simplify_caption(caption)
  48.  
  49. ext = os.path.splitext(file)[1]
  50.  
  51. new_path = os.path.join(folder,name + ext)
  52.  
  53. counter = 1
  54. while os.path.exists(new_path):
  55. new_path = os.path.join(folder,f"{name}-{counter}{ext}")
  56. counter += 1
  57.  
  58. os.rename(path,new_path)
  59.  
  60. print(file,"->",os.path.basename(new_path))
  61.  
  62. except Exception as e:
  63. print("error:",file,e)
Advertisement
Add Comment
Please, Sign In to add comment