Spaces:
Sleeping
Sleeping
Tim Zhang commited on
Commit ·
b8d244d
1
Parent(s): fbfaa18
inference added
Browse filesFiles changed (2)
- app.py+8-15
- clip_styler.py+14-105
66 unmodified lines676869707172737475767778798081828384857 unmodified lines9394959697989915 unmodified lines11511611711811912012112212312412512612712812913013113266 unmodified linestransforms.ToTensor()])def edit_image(image, style_choice, num_steps):if image is None: return Noneweights_map = {"Sketch": "model_sketch.pth","Van Gogh": "model_painting.pth","Cyberpunk": "model_cyberpunk.pth"}detail_prompt = {"Sketch": "charcoal sketch","Van Gogh": "Van Gogh painting","Cyberpunk": "neon cyberpunk",}'''try:style_net.load_state_dict(torch.load(weights_map.get(style_choice), map_location=DEVICE))7 unmodified linesoutput_img = transforms.ToPILImage()(output_tensor.squeeze().cpu())return output_img'''return style_transfer(image, detail_prompt[style_choice], num_steps=num_steps)# --- THE UI ---with gr.Blocks() as demo:15 unmodified lineswith gr.Row():im_in = gr.Image(type="pil", label="Input Image")style = gr.Dropdown(["Sketch", "Van Gogh", "Cyberpunk"], label="Choose Style")steps_slider = gr.Slider(minimum=50,maximum=200,value=100,step=10,label="Number of Steps (more = better quality but slower)")btn_edit = gr.Button("Apply")im_out = gr.Image(label="Result")btn_edit.click(edit_image, inputs=[im_in, style, steps_slider], outputs=im_out)if __name__ == "__main__":demo.launch(share=True)66 unmodified lines676869707172737475767778798081828384857 unmodified lines9394959697989915 unmodified lines11511611711811912012112212312412566 unmodified linestransforms.ToTensor()])def edit_image(image, style_choice):if image is None: return Nonedetail_prompt = {"Sketch": "charcoal sketch","Van Gogh": "Van Gogh painting","Cyberpunk": "neon cyberpunk",}WEIGHTS_MAP = {"Sketch": "unet_charcoal-sketch.pth","Van Gogh": "unet_van-gogh-painting.pth","Cyberpunk": "unet_neon-cyberpunk.pth"}'''try:style_net.load_state_dict(torch.load(weights_map.get(style_choice), map_location=DEVICE))7 unmodified linesoutput_img = transforms.ToPILImage()(output_tensor.squeeze().cpu())return output_img'''return style_transfer(image, detail_prompt[style_choice], weights_path=WEIGHTS_MAP[style_choice])# --- THE UI ---with gr.Blocks() as demo:15 unmodified lineswith gr.Row():im_in = gr.Image(type="pil", label="Input Image")style = gr.Dropdown(["Sketch", "Van Gogh", "Cyberpunk"], label="Choose Style")btn_edit = gr.Button("Apply")im_out = gr.Image(label="Result")btn_edit.click(edit_image, inputs=[im_in, style], outputs=im_out)if __name__ == "__main__":demo.launch(share=True)
4 unmodified lines567891011121314151617181920212223242526272829303132338 unmodified lines4243444546474811 unmodified lines6061626364656667686970717273747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571584 unmodified linesfrom cnn1 import UNetfrom transformers import CLIPModel, AutoTokenizerfrom torchvision.transforms.functional import adjust_contrastclip_model = Nonetokenizer = Nonevgg19 = Nonecnn_model = Nonedef load_models():"""Load models once and cache them"""global clip_model, tokenizer, vgg19, cnn_modelif clip_model is None:clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(DEVICE)if tokenizer is None:tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")if vgg19 is None:vgg19 = models.vgg19(pretrained=True).features.to(DEVICE)for param in vgg19.parameters():param.requires_grad_(False)if cnn_model is None:cnn_model = UNet(text_dim=512).to(DEVICE)return clip_model, tokenizer, vgg19, cnn_model8 unmodified linesif layer.bias is not None:torch.nn.init.zeros_(layer.bias)def style_transfer(img, prompt, num_steps=NUM_EPOCHS, source="a Photo"):"""Apply style transfer to an uploaded image11 unmodified linesimg = load_image(img).to(DEVICE)# Load modelsclip_model, tokenizer, vgg19, cnn_model = load_models()# Reset CNN model for fresh start on each imagereset_cnn_model()# image featuresfeatures = get_features(normalize(img), vgg19)# cnn model#cnn_model = UNet().to(DEVICE)# load ADAMoptimizer = optim.Adam(cnn_model.parameters(), lr=LR)scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.5)# data augmentationcrop = transforms.Compose([transforms.RandomCrop(CROP_SIZE)])augment = transforms.Compose([transforms.RandomPerspective(fill=0, p=1, distortion_scale=0.5), transforms.Resize(RESIZE)])# initialize variablescontent_loss_epoch = []style_loss_epoch = []total_loss_epoch = []output_image = imgmean_img = torch.mean(img, dim=(2, 3), keepdim=False).squeeze(0)mean_img = [mean_img[0].item(), mean_img[1].item(), mean_img[2].item()]target = img.clone().requires_grad_(True).to(DEVICE)with torch.no_grad():edited_text = prompt_ensemble(prompt)1 unmodified linetext_features = clip_model.get_text_features(**text_tokens)text_features = text_features.mean(axis=0, keepdim=True)text_features /= text_features.norm(dim=-1, keepdim=True)edited_source = prompt_ensemble(source)source_tokens = tokenizer(edited_source, padding=True, return_tensors="pt").to(DEVICE)source_features = clip_model.get_text_features(**source_tokens)source_features = source_features.mean(axis=0, keepdim=True)source_features /= source_features.norm(dim=-1, keepdim=True)img_features = clip_model.get_image_features(pixel_values=clip_normalize(img))img_features /= (img_features.clone().norm(dim=-1, keepdim=True))for epoch in range(num_steps + 1):scheduler.step()#target = cnn_model(img).requires_grad_(True).to(DEVICE)target = cnn_model(img, text_embedding=text_features).to(DEVICE)target_features = get_features(normalize(target), vgg19)content_loss = 0.0content_loss += torch.mean((target_features['conv4_2'] - features['conv4_2']) ** 2)content_loss += torch.mean((target_features['conv5_2'] - features['conv5_2']) ** 2)loss_patch = 0img_proc = []for n in range(NUM_CROPS):target_crop = crop(target)target_crop = augment(target_crop)img_proc.append(target_crop)img_proc = torch.cat(img_proc, dim=0)img_aug = img_procimg_aug_features = clip_model.get_image_features(pixel_values=clip_normalize(img_aug))img_aug_features /= (img_aug_features.clone().norm(dim=-1, keepdim=True))img_direction = img_aug_features - img_featuresimg_direction /= img_direction.clone().norm(dim=-1, keepdim=True)text_direction = (text_features - source_features).repeat(img_aug_features.size(0), 1)text_direction /= text_direction.norm(dim=-1, keepdim=True)loss_calc = (1 - torch.cosine_similarity(img_direction, text_direction, dim=1))loss_calc[loss_calc < PATCH_THRESHOLD] = 0.0loss_patch += loss_calc.mean()glob_features = clip_model.get_image_features(pixel_values=clip_normalize(target))glob_features /= (glob_features.clone().norm(dim=-1, keepdim=True))glob_direction = glob_features - img_featuresglob_direction /= glob_direction.clone().norm(dim=-1, keepdim=True)loss_glob = (1 - torch.cosine_similarity(glob_direction, text_direction, dim=1)).mean()loss_tv = L_TV * get_image_prior_losses(target)total_loss = (L_PATCH * loss_patch) + (L_DIR * loss_glob) + (L_CONTENT * content_loss) + loss_tvtotal_loss_epoch.append(total_loss)optimizer.zero_grad()total_loss.backward()optimizer.step()# Post-process outputoutput_image = target.clone().detach()4 unmodified lines56789101112131415161718192021228 unmodified lines3132333435363711 unmodified lines4950515253545556571 unmodified line5960616263646566674 unmodified linesfrom cnn1 import UNetfrom transformers import CLIPModel, AutoTokenizerfrom torchvision.transforms.functional import adjust_contrastimport torch.nn.functional as Fdef load_models(weights_path):clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(DEVICE)tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")vgg19 = models.vgg19(pretrained=True).features.to(DEVICE)for param in vgg19.parameters():param.requires_grad_(False)cnn_model = UNet(text_dim=512).to(DEVICE)cnn_model.load_state_dict(torch.load(weights_path, map_location=DEVICE))return clip_model, tokenizer, vgg19, cnn_model8 unmodified linesif layer.bias is not None:torch.nn.init.zeros_(layer.bias)def style_transfer(img, prompt, weights_path, source="a Photo"):"""Apply style transfer to an uploaded image11 unmodified linesimg = load_image(img).to(DEVICE)# Load modelsclip_model, tokenizer, vgg19, cnn_model = load_models(weights_path)cnn_model.eval()with torch.no_grad():edited_text = prompt_ensemble(prompt)1 unmodified linetext_features = clip_model.get_text_features(**text_tokens)text_features = text_features.mean(axis=0, keepdim=True)text_features /= text_features.norm(dim=-1, keepdim=True)with torch.inference_mode():target = cnn_model(img, text_embedding=text_features).to(DEVICE)# Post-process outputoutput_image = target.clone().detach()
app.py+8-15
clip_styler.py+14-105