| |
| |
| |
|
|
| import numpy as np |
| import pandas as pd |
|
|
| |
| |
|
|
| import os |
| for dirname, _, filenames in os.walk('/kaggle/input'): |
| for filename in filenames: |
| print(os.path.join(dirname, filename)) |
|
|
| |
| |
|
|
|
|
| get_ipython().getoutput("pip install nltk") |
|
|
|
|
| import torch |
| from transformers import BlipProcessor, BlipForConditionalGeneration |
| from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction |
| from tqdm import tqdm |
|
|
|
|
| device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
| model_name = "utkarshpise/blip-ucm-captioning" |
|
|
| processor = BlipProcessor.from_pretrained(model_name) |
| model = BlipForConditionalGeneration.from_pretrained(model_name) |
|
|
| model.to(device) |
| model.eval() |
|
|
| print(" Model loaded") |
|
|
|
|
| smooth = SmoothingFunction().method1 |
|
|
| def evaluate_model(model, loader, processor, device): |
| model.eval() |
|
|
| total_loss = 0 |
| preds = [] |
| refs = [] |
|
|
| with torch.no_grad(): |
| for batch in tqdm(loader, desc="Evaluating"): |
| batch = {k: v.to(device) for k, v in batch.items()} |
|
|
| |
| outputs = model(**batch) |
| loss = outputs.loss |
| total_loss += loss.item() |
|
|
| |
| generated_ids = model.generate( |
| pixel_values=batch["pixel_values"], |
| max_length=50, |
| num_beams=5 |
| ) |
|
|
| pred = processor.batch_decode(generated_ids, skip_special_tokens=True) |
| ref = processor.batch_decode(batch["labels"], skip_special_tokens=True) |
|
|
| preds.extend(pred) |
| refs.extend(refs if False else ref) |
|
|
| avg_loss = total_loss / len(loader) |
|
|
| bleu_scores = [] |
| for p, r in zip(preds, refs): |
| score = sentence_bleu([r.split()], p.split(), smoothing_function=smooth) |
| bleu_scores.append(score) |
|
|
| bleu = sum(bleu_scores) / len(bleu_scores) |
|
|
| return avg_loss, bleu |
|
|
|
|
| import kagglehub |
| import os |
| import json |
|
|
| path = kagglehub.dataset_download("sumanpaul14/ucm-captioning-dataset") |
|
|
| print("Dataset path:", path) |
| print("Files:", os.listdir(path)) |
|
|
|
|
| from torch.utils.data import Dataset, DataLoader, random_split |
| from PIL import Image |
| import json |
| import os |
|
|
| BASE_PATH = "/kaggle/input/datasets/sumanpaul14/ucm-captioning-dataset" |
| DATA_JSON = os.path.join(BASE_PATH, "dataset.json") |
| IMG_DIR = os.path.join(BASE_PATH, "imgs", "imgs") |
|
|
| |
| with open(DATA_JSON) as f: |
| data = json.load(f) |
|
|
| samples = [] |
| for item in data["images"]: |
| img_path = os.path.join(IMG_DIR, item["filename"]) |
|
|
| if os.path.exists(img_path): |
| for sent in item["sentences"]: |
| samples.append({ |
| "image": img_path, |
| "caption": sent["raw"] |
| }) |
|
|
|
|
| class UCMCaptionDataset(Dataset): |
| def __init__(self, samples, processor): |
| self.samples = samples |
| self.processor = processor |
|
|
| def __len__(self): |
| return len(self.samples) |
|
|
| def __getitem__(self, idx): |
| item = self.samples[idx] |
|
|
| image = Image.open(item["image"]).convert("RGB") |
| caption = item["caption"] |
|
|
| encoding = self.processor( |
| images=image, |
| text=caption, |
| padding="max_length", |
| truncation=True, |
| return_tensors="pt" |
| ) |
|
|
| encoding = {k: v.squeeze(0) for k, v in encoding.items()} |
| encoding["labels"] = encoding["input_ids"] |
|
|
| return encoding |
|
|
|
|
| dataset = UCMCaptionDataset(samples, processor) |
|
|
| train_size = int(0.8 * len(dataset)) |
| test_size = len(dataset) - train_size |
|
|
| _, test_dataset = random_split(dataset, [train_size, test_size]) |
|
|
| test_loader = DataLoader(test_dataset, batch_size=8) |
|
|
|
|
| loss, bleu = evaluate_model(model, test_loader, processor, device) |
|
|
| print(f"\nLM Loss: {loss}") |
| print(f" BLEU Score: {bleu}") |
|
|
|
|
| import os |
| print(os.listdir("/kaggle/working")) |
|
|
|
|
| from huggingface_hub import login |
|
|
| login() |
|
|
|
|
|
|
|
|
| from huggingface_hub import upload_file |
|
|
| repo_id = "utkarshpise/blip-ucm-captioning" |
|
|
| upload_file( |
| path_or_fileobj="/kaggle/working/.virtual_documents/__notebook_source__.ipynb", |
| path_in_repo="inference.py", |
| repo_id=repo_id, |
| repo_type="model" |
| ) |
|
|
| print(" Code uploaded!") |
|
|
|
|
| Evaluating: 100%|ββββββββββ| 263/263 [09:11<00:00, 2.10s/it] |
|
|
| LM Loss: 0.43680915043834495 |
| BLEU Score: 0.09948045741442776 |
|
|