Hug0endob commited on
Commit
36cfd26
Β·
verified Β·
1 Parent(s): 4462cb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -20
app.py CHANGED
@@ -10,23 +10,37 @@ from transformers import (
10
  T5ForConditionalGeneration,
11
  T5Tokenizer,
12
  )
13
- import re
14
 
15
  device = torch.device("cpu")
16
 
17
- # Image captioning model (nlpconnect/vit-gpt2-image-captioning)
18
- processor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
19
- tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
20
- model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning").to(device)
 
21
  model.eval()
22
 
23
- # Rewriter (T5)
24
  rewriter_tokenizer = T5Tokenizer.from_pretrained("t5-small")
25
  rewriter = T5ForConditionalGeneration.from_pretrained("t5-small").to(device)
26
  rewriter.eval()
27
 
28
  def load_image_from_url(url: str, timeout=10):
29
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  resp = requests.get(url, timeout=timeout, headers={"User-Agent": "huggingface-space/1.0"})
31
  resp.raise_for_status()
32
  img = Image.open(BytesIO(resp.content)).convert("RGB")
@@ -34,49 +48,68 @@ def load_image_from_url(url: str, timeout=10):
34
  except Exception as e:
35
  return None, f"Error loading image: {e}"
36
 
37
- def generate_caption(img: Image.Image, max_len: int = 30):
 
38
  inputs = processor(images=img, return_tensors="pt")
39
  pixel_values = inputs.pixel_values.to(device)
40
- out = model.generate(pixel_values, max_length=max_len, num_beams=2, early_stopping=True)
 
 
 
 
 
 
 
 
 
41
  caption = tokenizer.decode(out[0], skip_special_tokens=True).strip()
42
  return caption
43
 
44
- def rewrite_caption(caption: str, max_len: int = 64):
45
- input_text = "paraphrase: " + caption
 
 
 
 
46
  tok = rewriter_tokenizer(input_text, return_tensors="pt", truncation=True).to(device)
47
  out = rewriter.generate(**tok, max_length=max_len, num_beams=2, early_stopping=True)
48
  rewritten = rewriter_tokenizer.decode(out[0], skip_special_tokens=True).strip()
49
  return rewritten
50
 
51
- def describe_image(url: str, max_caption_len: int = 30, expand: bool = True):
52
  img, err = load_image_from_url(url)
53
  if err:
54
  return None, f"Error: {err}"
55
- caption = generate_caption(img, max_len=max_caption_len)
56
  if expand:
57
  try:
58
- caption = rewrite_caption(caption, max_len=64)
59
  except Exception:
60
  pass
61
  if len(caption.split()) < 6:
62
  caption = f"{caption}. The scene appears to contain: {caption.lower()}."
63
  return img, caption
64
 
65
- # Gradio UI: image left, caption right
66
- with gr.Blocks() as demo:
67
- gr.Markdown("## Image captioning β€” image on the left, descriptive caption on the right (CPU-optimized, uncensored)")
 
 
 
68
  with gr.Row():
69
  with gr.Column(scale=1):
70
- url_in = gr.Textbox(label="Image URL", placeholder="https://example.com/photo.jpg")
71
- max_len = gr.Slider(minimum=10, maximum=60, value=30, label="Max caption length")
72
- expand_chk = gr.Checkbox(label="Expand/rewite caption (slower, more natural)", value=True)
 
 
73
  go = gr.Button("Load & Describe")
74
  with gr.Column(scale=1):
75
  img_out = gr.Image(type="pil", label="Image")
76
  with gr.Column(scale=1):
77
  caption_out = gr.Textbox(label="Descriptive caption", lines=6)
78
 
79
- go.click(fn=describe_image, inputs=[url_in, max_len, expand_chk], outputs=[img_out, caption_out])
80
 
81
  if __name__ == "__main__":
82
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
10
  T5ForConditionalGeneration,
11
  T5Tokenizer,
12
  )
13
+ import urllib.parse
14
 
15
  device = torch.device("cpu")
16
 
17
+ # Models
18
+ PROCESSOR_NAME = "nlpconnect/vit-gpt2-image-captioning"
19
+ processor = ViTImageProcessor.from_pretrained(PROCESSOR_NAME)
20
+ tokenizer = AutoTokenizer.from_pretrained(PROCESSOR_NAME)
21
+ model = VisionEncoderDecoderModel.from_pretrained(PROCESSOR_NAME).to(device)
22
  model.eval()
23
 
24
+ # Optional rewriter (T5-small) to make captions more natural / respond to prompt
25
  rewriter_tokenizer = T5Tokenizer.from_pretrained("t5-small")
26
  rewriter = T5ForConditionalGeneration.from_pretrained("t5-small").to(device)
27
  rewriter.eval()
28
 
29
  def load_image_from_url(url: str, timeout=10):
30
  try:
31
+ # allow string that is data URL or direct URL
32
+ url = url.strip()
33
+ if url.startswith("data:"):
34
+ # let PIL handle data URLs via BytesIO after splitting
35
+ header, encoded = url.split(",", 1)
36
+ import base64
37
+ data = base64.b64decode(encoded)
38
+ img = Image.open(BytesIO(data)).convert("RGB")
39
+ return img, None
40
+ # ensure proper URL encoding
41
+ parsed = urllib.parse.urlsplit(url)
42
+ if parsed.scheme == "":
43
+ return None, "Invalid URL (missing scheme: http/https)."
44
  resp = requests.get(url, timeout=timeout, headers={"User-Agent": "huggingface-space/1.0"})
45
  resp.raise_for_status()
46
  img = Image.open(BytesIO(resp.content)).convert("RGB")
 
48
  except Exception as e:
49
  return None, f"Error loading image: {e}"
50
 
51
+ def generate_caption(img: Image.Image, prompt: str = None, max_len: int = 30, num_beams: int = 2):
52
+ # Prepare encoder inputs
53
  inputs = processor(images=img, return_tensors="pt")
54
  pixel_values = inputs.pixel_values.to(device)
55
+
56
+ # If a prompt is provided, prepend it to the decoder start tokens via tokenizer (prefix)
57
+ # This is a lightweight way to bias output by using the tokenizer's bos/tokenizer decoding prefix.
58
+ gen_kwargs = {"max_length": max_len, "num_beams": num_beams, "early_stopping": True}
59
+ if prompt:
60
+ # For vit-gpt2 model, we can try to use forced_decoder_input_ids or prefix decoding
61
+ # Simpler approach: generate normally and then rely on rewriter to apply prompt.
62
+ pass
63
+
64
+ out = model.generate(pixel_values, **gen_kwargs)
65
  caption = tokenizer.decode(out[0], skip_special_tokens=True).strip()
66
  return caption
67
 
68
+ def rewrite_caption_with_prompt(caption: str, prompt: str = None, max_len: int = 64):
69
+ # If prompt provided, use it to instruct T5; otherwise paraphrase
70
+ if prompt:
71
+ input_text = f"paraphrase: {caption} prompt: {prompt}"
72
+ else:
73
+ input_text = "paraphrase: " + caption
74
  tok = rewriter_tokenizer(input_text, return_tensors="pt", truncation=True).to(device)
75
  out = rewriter.generate(**tok, max_length=max_len, num_beams=2, early_stopping=True)
76
  rewritten = rewriter_tokenizer.decode(out[0], skip_special_tokens=True).strip()
77
  return rewritten
78
 
79
+ def describe_image(url: str, prompt: str, max_caption_len: int = 30, expand: bool = True, beams: int = 2):
80
  img, err = load_image_from_url(url)
81
  if err:
82
  return None, f"Error: {err}"
83
+ caption = generate_caption(img, prompt=prompt, max_len=max_caption_len, num_beams=beams)
84
  if expand:
85
  try:
86
+ caption = rewrite_caption_with_prompt(caption, prompt=prompt, max_len=64)
87
  except Exception:
88
  pass
89
  if len(caption.split()) < 6:
90
  caption = f"{caption}. The scene appears to contain: {caption.lower()}."
91
  return img, caption
92
 
93
+ css = """
94
+ footer {display: none !important;}
95
+ """
96
+
97
+ with gr.Blocks(css=css, title="Image Describer (vit-gpt2, uncensored, promptable)") as demo:
98
+ gr.Markdown("## Image Describer β€” uncensored captions, optional prompt to bias description")
99
  with gr.Row():
100
  with gr.Column(scale=1):
101
+ url_in = gr.Textbox(label="Image URL or data URL", placeholder="https://example.com/photo.jpg")
102
+ prompt_in = gr.Textbox(label="Optional prompt (e.g. 'Describe people and actions')", placeholder="Focus on people, actions, or colors.")
103
+ max_len = gr.Slider(minimum=8, maximum=60, value=30, label="Max caption length")
104
+ beams = gr.Slider(minimum=1, maximum=4, value=2, step=1, label="Num beams (higher = better quality, slower)")
105
+ expand_chk = gr.Checkbox(label="Rewrite/Paraphrase with prompt (slower)", value=True)
106
  go = gr.Button("Load & Describe")
107
  with gr.Column(scale=1):
108
  img_out = gr.Image(type="pil", label="Image")
109
  with gr.Column(scale=1):
110
  caption_out = gr.Textbox(label="Descriptive caption", lines=6)
111
 
112
+ go.click(fn=describe_image, inputs=[url_in, prompt_in, max_len, expand_chk, beams], outputs=[img_out, caption_out])
113
 
114
  if __name__ == "__main__":
115
  demo.launch(server_name="0.0.0.0", server_port=7860)