Hug0endob commited on
Commit
d914e3a
Β·
verified Β·
1 Parent(s): 68de2f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -20
app.py CHANGED
@@ -6,20 +6,16 @@ import re
6
  import torch
7
  from transformers import BlipForConditionalGeneration, BlipProcessor, T5ForConditionalGeneration, T5Tokenizer
8
 
9
- # Device: CPU-only
10
  device = torch.device("cpu")
11
 
12
- # Load caption model (small, CPU-friendly)
13
- # HF model: Salesforce/blip-image-captioning-base
14
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
15
- model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
16
- model.to(device)
17
 
18
- # Lightweight rewriter model (T5-small) to improve fluency/detail without big cost
19
  rewriter_tokenizer = T5Tokenizer.from_pretrained("t5-small")
20
  rewriter = T5ForConditionalGeneration.from_pretrained("t5-small").to(device)
21
 
22
- # Simple safety patterns (non-bypass)
23
  SENSITIVE_PATTERNS = [
24
  r"\b(nude|naked|porn|sex|sexual|explicit|hardcore)\b",
25
  r"\b(blood|gore|mutilat|disembowel|organs)\b",
@@ -41,15 +37,12 @@ def is_caption_allowed(text: str):
41
  return SENSITIVE_RE.search(text) is None
42
 
43
  def generate_caption(img: Image.Image, max_len:int=30):
44
- # prepare inputs
45
  inputs = processor(images=img, return_tensors="pt").to(device)
46
- # generate with small beams to balance speed/quality
47
  out = model.generate(**inputs, max_length=max_len, num_beams=3, early_stopping=True)
48
  caption = processor.decode(out[0], skip_special_tokens=True).strip()
49
  return caption
50
 
51
  def rewrite_caption(caption: str, max_len:int=64):
52
- # Use T5-small to expand/clean the caption. Prefix "paraphrase:" helps instruct T5.
53
  input_text = "paraphrase: " + caption
54
  tok = rewriter_tokenizer(input_text, return_tensors="pt", truncation=True).to(device)
55
  out = rewriter.generate(**tok, max_length=max_len, num_beams=2, early_stopping=True)
@@ -59,28 +52,42 @@ def rewrite_caption(caption: str, max_len:int=64):
59
  def describe_image(url: str, max_caption_len: int = 30, expand: bool = True):
60
  img, err = load_image_from_url(url)
61
  if err:
62
- return None, err
63
  caption = generate_caption(img, max_len=max_caption_len)
64
  if not is_caption_allowed(caption):
65
- return img, "Caption omitted for safety."
 
 
 
66
  if expand:
67
  try:
68
  caption = rewrite_caption(caption, max_len=64)
69
  if not is_caption_allowed(caption):
70
- return img, "Caption omitted for safety."
 
 
71
  except Exception:
72
  pass
 
 
 
 
73
  return img, caption
74
 
 
75
  with gr.Blocks() as demo:
76
- gr.Markdown("## CPU-optimized Image Captioning (BLIP-base + T5-small rewriter)")
77
  with gr.Row():
78
- url_in = gr.Textbox(label="Image URL", placeholder="https://example.com/photo.jpg")
79
- max_len = gr.Slider(minimum=10, maximum=60, value=30, label="Max caption token length")
80
- expand_chk = gr.Checkbox(label="Expand/rewite caption (slower, more natural)", value=True)
81
- img_out = gr.Image(type="pil", label="Image")
82
- caption_out = gr.Textbox(label="Caption")
83
- go = gr.Button("Load & Describe")
 
 
 
 
84
  go.click(fn=describe_image, inputs=[url_in, max_len, expand_chk], outputs=[img_out, caption_out])
85
 
86
  if __name__ == "__main__":
 
6
  import torch
7
  from transformers import BlipForConditionalGeneration, BlipProcessor, T5ForConditionalGeneration, T5Tokenizer
8
 
 
9
  device = torch.device("cpu")
10
 
11
+ # Load models (CPU-friendly)
 
12
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
13
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device)
 
14
 
 
15
  rewriter_tokenizer = T5Tokenizer.from_pretrained("t5-small")
16
  rewriter = T5ForConditionalGeneration.from_pretrained("t5-small").to(device)
17
 
18
+ # Safety patterns (simple filter)
19
  SENSITIVE_PATTERNS = [
20
  r"\b(nude|naked|porn|sex|sexual|explicit|hardcore)\b",
21
  r"\b(blood|gore|mutilat|disembowel|organs)\b",
 
37
  return SENSITIVE_RE.search(text) is None
38
 
39
  def generate_caption(img: Image.Image, max_len:int=30):
 
40
  inputs = processor(images=img, return_tensors="pt").to(device)
 
41
  out = model.generate(**inputs, max_length=max_len, num_beams=3, early_stopping=True)
42
  caption = processor.decode(out[0], skip_special_tokens=True).strip()
43
  return caption
44
 
45
  def rewrite_caption(caption: str, max_len:int=64):
 
46
  input_text = "paraphrase: " + caption
47
  tok = rewriter_tokenizer(input_text, return_tensors="pt", truncation=True).to(device)
48
  out = rewriter.generate(**tok, max_length=max_len, num_beams=2, early_stopping=True)
 
52
  def describe_image(url: str, max_caption_len: int = 30, expand: bool = True):
53
  img, err = load_image_from_url(url)
54
  if err:
55
+ return None, f"Error: {err}"
56
  caption = generate_caption(img, max_len=max_caption_len)
57
  if not is_caption_allowed(caption):
58
+ # Provide a neutral, respectful safety message with next steps
59
+ safety_msg = ("A descriptive caption was not provided because the image may contain explicit or graphic content. "
60
+ "If this is unexpected, try a different image or upload a cropped/edited version that removes sensitive content.")
61
+ return img, safety_msg
62
  if expand:
63
  try:
64
  caption = rewrite_caption(caption, max_len=64)
65
  if not is_caption_allowed(caption):
66
+ safety_msg = ("A descriptive caption was not provided because the generated text may describe explicit or graphic content. "
67
+ "Try a different image or disable the expansion option.")
68
+ return img, safety_msg
69
  except Exception:
70
  pass
71
+ # Make caption more descriptive by appending structural cues (objects, colors, setting)
72
+ # Quick heuristic: if short, expand with a simple template
73
+ if len(caption.split()) < 6:
74
+ caption = f"{caption}. The scene appears to contain: {caption.lower()}."
75
  return img, caption
76
 
77
+ # Gradio UI: image left, caption right
78
  with gr.Blocks() as demo:
79
+ gr.Markdown("## Image captioning β€” image on the left, descriptive caption on the right (CPU-optimized)")
80
  with gr.Row():
81
+ with gr.Column(scale=1):
82
+ url_in = gr.Textbox(label="Image URL", placeholder="https://example.com/photo.jpg")
83
+ max_len = gr.Slider(minimum=10, maximum=60, value=30, label="Max caption length")
84
+ expand_chk = gr.Checkbox(label="Expand/rewite caption (slower, more natural)", value=True)
85
+ go = gr.Button("Load & Describe")
86
+ with gr.Column(scale=1):
87
+ img_out = gr.Image(type="pil", label="Image")
88
+ with gr.Column(scale=1):
89
+ caption_out = gr.Textbox(label="Descriptive caption", lines=6)
90
+
91
  go.click(fn=describe_image, inputs=[url_in, max_len, expand_chk], outputs=[img_out, caption_out])
92
 
93
  if __name__ == "__main__":