Spaces:
Sleeping
Sleeping
File size: 13,133 Bytes
ae66859 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | """
model_utils.py β Model loading and caption generation utilities
for the Cartoon Image Captioning App.
"""
import os
# Block TF/Flax before any transformers import to prevent libmetal_plugin crash
os.environ["TRANSFORMERS_NO_TF"] = "1"
os.environ["TRANSFORMERS_NO_FLAX"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
from typing import List, Tuple, Optional
import warnings
warnings.filterwarnings("ignore")
# ββ Safe torch import βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
try:
import torch
_TORCH_OK = True
DEVICE = (
"cuda" if torch.cuda.is_available()
else "mps" if (hasattr(torch.backends, "mps") and torch.backends.mps.is_available())
else "cpu"
)
except Exception as _e:
torch = None # type: ignore
_TORCH_OK = False
DEVICE = "cpu"
warnings.warn(
f"PyTorch could not be imported ({_e}). "
"Model inference will be unavailable until torch is fixed.\n"
"Fix with: conda install pytorch torchvision torchaudio -c pytorch --force-reinstall",
RuntimeWarning
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Preprocessing
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def preprocess_cartoon(image: Image.Image, target_size: int = 224) -> Image.Image:
"""
Apply cartoon-specific preprocessing:
- Convert to RGB
- Resize to target_size x target_size
- Mild sharpening to enhance cartoon edges
- Normalize brightness/contrast
"""
if image.mode != "RGB":
image = image.convert("RGB")
# Resize with high-quality Lanczos resampling
image = image.resize((target_size, target_size), Image.LANCZOS)
# Mild edge enhancement for cartoon-style images
enhancer = ImageEnhance.Sharpness(image)
image = enhancer.enhance(1.4)
# Slight contrast boost
contrast_enhancer = ImageEnhance.Contrast(image)
image = contrast_enhancer.enhance(1.1)
return image
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ViT-GPT2 Model
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_vit_gpt2():
"""Load and return ViT-GPT2 image captioning model."""
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
model_name = "nlpconnect/vit-gpt2-image-captioning"
processor = ViTImageProcessor.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = VisionEncoderDecoderModel.from_pretrained(model_name)
model = model.to(DEVICE)
model.eval()
return model, processor, tokenizer
def generate_vit_gpt2(
model, processor, tokenizer,
image: Image.Image,
num_captions: int = 3,
max_length: int = 60
) -> List[Tuple[str, float]]:
"""
Generate multiple diverse captions using ViT-GPT2.
Returns list of (caption, score) tuples.
"""
img = preprocess_cartoon(image)
pixel_values = processor(images=img, return_tensors="pt").pixel_values.to(DEVICE)
results = []
with torch.no_grad():
# Beam search for best caption
output_ids = model.generate(
pixel_values,
max_length=max_length,
num_beams=5,
num_return_sequences=num_captions,
early_stopping=True,
return_dict_in_generate=True,
output_scores=True,
do_sample=True,
temperature=1.2,
top_p=0.9,
repetition_penalty=1.2,
)
sequences = output_ids.sequences if hasattr(output_ids, "sequences") else output_ids
if hasattr(sequences, "shape") and sequences.dim() == 2:
for i, seq in enumerate(sequences):
caption = tokenizer.decode(seq, skip_special_tokens=True).strip()
# Compute approximate confidence from sequence length
score = max(0.3, 1.0 - i * 0.12)
if caption:
results.append((caption, round(score, 3)))
else:
caption = tokenizer.decode(sequences, skip_special_tokens=True).strip()
results.append((caption, 0.85))
# Ensure we return num_captions results
while len(results) < num_captions:
if results:
results.append((results[0][0], max(0.1, results[0][1] - 0.1)))
else:
results.append(("A cartoon scene.", 0.5))
return results[:num_captions]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLIP-2 Model
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_blip2():
"""Load and return BLIP-2 model."""
from transformers import Blip2Processor, Blip2ForConditionalGeneration
model_name = "Salesforce/blip2-opt-2.7b"
dtype = torch.float16 if DEVICE != "cpu" else torch.float32
processor = Blip2Processor.from_pretrained(model_name)
model = Blip2ForConditionalGeneration.from_pretrained(
model_name, torch_dtype=dtype, device_map="auto"
)
model.eval()
return model, processor
BLIP2_CARTOON_PROMPTS = [
"Write a witty, sarcastic, and funny punchline for this cartoon:",
"A humorous and clever New Yorker comic caption:",
"Question: What is the funniest possible joke to describe this scene? Answer:",
]
def generate_blip2(
model, processor,
image: Image.Image,
num_captions: int = 3,
max_new_tokens: int = 60
) -> List[Tuple[str, float]]:
"""
Generate captions using BLIP-2 with multiple prompts.
Returns list of (caption, score) tuples.
"""
img = preprocess_cartoon(image)
dtype = torch.float16 if DEVICE != "cpu" else torch.float32
results = []
prompts_to_use = BLIP2_CARTOON_PROMPTS[:num_captions]
if len(prompts_to_use) < num_captions:
prompts_to_use += [None] * (num_captions - len(prompts_to_use))
for i, prompt in enumerate(prompts_to_use):
try:
if prompt:
inputs = processor(
img, text=prompt, return_tensors="pt"
).to(DEVICE, dtype)
else:
inputs = processor(img, return_tensors="pt").to(DEVICE, dtype)
with torch.no_grad():
generated_ids = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
num_beams=4,
repetition_penalty=1.3,
temperature=1.1,
do_sample=True,
top_p=0.9,
)
caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
# Remove the prompt echo if present
if prompt and caption.startswith(prompt):
caption = caption[len(prompt):].strip()
score = round(0.92 - i * 0.08, 3)
results.append((caption or "Caption generation failed.", score))
except Exception as e:
results.append((f"[Generation error: {str(e)[:40]}]", 0.1))
return results[:num_captions]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BLIP-1 (Lightweight fallback β faster for CPU)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_blip():
"""Load lightweight BLIP model (good CPU fallback)."""
from transformers import BlipProcessor, BlipForConditionalGeneration
model_name = "Salesforce/blip-image-captioning-large"
processor = BlipProcessor.from_pretrained(model_name)
model = BlipForConditionalGeneration.from_pretrained(model_name).to(DEVICE)
model.eval()
return model, processor
def generate_blip(
model, processor,
image: Image.Image,
num_captions: int = 3,
max_new_tokens: int = 60
) -> List[Tuple[str, float]]:
"""Generate captions using BLIP with conditional prompts."""
img = preprocess_cartoon(image)
prompts = [
"a witty, humorous, and funny cartoon punchline:",
"a sarcastic joke about this image:",
"a clever and funny New Yorker caption:",
][:num_captions]
results = []
for i, prompt in enumerate(prompts):
try:
inputs = processor(img, text=prompt, return_tensors="pt").to(DEVICE)
with torch.no_grad():
out = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
num_beams=4,
temperature=1.1,
do_sample=True,
top_p=0.9,
repetition_penalty=1.2
)
caption = processor.decode(out[0], skip_special_tokens=True).strip()
if caption.lower().startswith(prompt.lower()):
caption = caption[len(prompt):].strip()
score = round(0.88 - i * 0.06, 3)
results.append((caption or "No caption generated.", score))
except Exception as e:
results.append((f"Error: {str(e)[:40]}", 0.1))
return results[:num_captions]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Humor Scorer (lightweight approx. using perplexity + lexical cues)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
HUMOR_KEYWORDS = {
"positive": [
"irony", "twist", "surprise", "unexpected", "ironic",
"sarcastic", "absurd", "bizarre", "ridiculous", "clever",
"witty", "irony", "pun", "joke", "funny", "laugh", "hilarious",
"bizarre", "awkward", "ridiculous", "paradox"
],
"structural": [
"but", "however", "except", "unless", "despite", "although",
"even though", "turns out", "actually", "wait", "suddenly"
]
}
def score_humor(caption: str) -> float:
"""
Lightweight humor scoring based on:
- Lexical humor markers
- Caption length (good captions are medium length)
- Structural incongruity markers
Returns score in [0, 1].
"""
caption_lower = caption.lower()
words = caption_lower.split()
n_words = len(words)
# Base score
score = 0.3
# Keyword score
kw_hits = sum(1 for kw in HUMOR_KEYWORDS["positive"] if kw in caption_lower)
struct_hits = sum(1 for kw in HUMOR_KEYWORDS["structural"] if kw in caption_lower)
score += min(kw_hits * 0.08, 0.24)
score += min(struct_hits * 0.06, 0.18)
# Length penalty: too short or too long is bad
if 5 <= n_words <= 20:
score += 0.15
elif n_words < 3:
score -= 0.1
# Punctuation markers (question marks, exclamation for humor)
if "?" in caption:
score += 0.05
if "!" in caption:
score += 0.03
# Clip to [0, 1]
return round(min(max(score, 0.0), 1.0), 3)
def analyze_captions(captions: List[Tuple[str, float]]) -> List[dict]:
"""
Full analysis of generated captions.
Returns list of dicts with caption, confidence, humor_score, word_count.
"""
results = []
for caption, confidence in captions:
humor = score_humor(caption)
results.append({
"caption": caption,
"confidence": confidence,
"humor_score": humor,
"word_count": len(caption.split()),
"char_count": len(caption),
})
return results
|