Spaces:
Build error
Build error
Download models.py from mia0601/SmartPhoto: direct link, hf CLI and curl.
- Browser
- Download file 1.04 kB
-
https://huggingface.co/spaces/mia0601/SmartPhoto/resolve/main/models.py
- Command line
-
hf download hf://spaces/mia0601/SmartPhoto/models.py
-
curl -L -o models.py https://huggingface.co/spaces/mia0601/SmartPhoto/resolve/main/models.py
1.04 kB
| from transformers import BlipProcessor, BlipForConditionalGeneration | |
| import torch | |
| import open_clip | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| blip_proc = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base") | |
| blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device) | |
| clip_model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion2b_s34b_b79k') | |
| clip_tokenizer = open_clip.get_tokenizer('ViT-B-32') | |
| clip_model = clip_model.to(device) | |
| def generate_caption(img): | |
| inputs = blip_proc(img, return_tensors="pt").to(device) | |
| out = blip_model.generate(**inputs) | |
| return blip_proc.decode(out[0], skip_special_tokens=True) | |
| def get_img_emb(img): | |
| im = preprocess(img).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| return clip_model.encode_image(im).cpu() | |
| def get_text_emb(text): | |
| tokens = clip_tokenizer([text]).to(device) | |
| with torch.no_grad(): | |
| return clip_model.encode_text(tokens).cpu() |