Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # pip install transformers torch pillow
- import os
- import re
- from PIL import Image
- from transformers import BlipProcessor, BlipForConditionalGeneration
- folder = r"C:\Users\thoma\OneDrive\Desktop\openmoji-618x618-color" # change to your folder
- processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
- model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
- stop_words = [
- "a","an","the","image","photo","picture","of","with",
- "and","on","in","there","is"
- ]
- def simplify_caption(text):
- text = text.lower()
- words = re.findall(r"[a-z]+", text)
- words = [w for w in words if w not in stop_words]
- words = words[:3] # limit to 3 words
- return "-".join(words)
- for file in os.listdir(folder):
- if file.lower().endswith((".png",".jpg",".jpeg",".webp")):
- path = os.path.join(folder,file)
- try:
- image = Image.open(path).convert("RGB")
- inputs = processor(image, return_tensors="pt")
- output = model.generate(**inputs)
- caption = processor.decode(output[0], skip_special_tokens=True)
- name = simplify_caption(caption)
- ext = os.path.splitext(file)[1]
- new_path = os.path.join(folder,name + ext)
- counter = 1
- while os.path.exists(new_path):
- new_path = os.path.join(folder,f"{name}-{counter}{ext}")
- counter += 1
- os.rename(path,new_path)
- print(file,"->",os.path.basename(new_path))
- except Exception as e:
- print("error:",file,e)
Advertisement
Add Comment
Please, Sign In to add comment