scmlewis commited on
Commit
93c50ef
·
verified ·
1 Parent(s): fc7316d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -25
app.py CHANGED
@@ -1,51 +1,79 @@
1
  from transformers import BlipProcessor, BlipForConditionalGeneration, pipeline
2
  import gradio as gr
3
  from PIL import Image
 
 
4
 
5
  # Load the main image captioning model
6
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
7
  model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
8
 
9
- # Load a small language model pipeline for polishing (can change model to a better LLM as needed)
10
  text_generator = pipeline("text-generation", model="gpt2")
11
 
12
  def preprocess_image(image):
13
- # Example: convert to RGB if needed, resize if you want consistent input size
14
  if image.mode != "RGB":
15
  image = image.convert("RGB")
16
  return image
17
 
18
  def postprocess_caption(raw_caption):
19
- # Use language model to polish and expand the caption slightly
20
- # Limit max new tokens to keep the output concise
21
- polished = text_generator(f"Describe this image in more detail: {raw_caption}", max_length=50, num_return_sequences=1)
22
- # Extract generated text, remove prompt part
23
- polished_caption = polished[0]['generated_text'].replace(f"Describe this image in more detail: ", "").strip()
24
  return polished_caption
25
 
26
  def generate_caption(image, max_length=30, num_beams=5):
27
  image = preprocess_image(image)
28
  inputs = processor(image, return_tensors="pt")
29
- # Generate caption with adjustable parameters for length and quality
30
  out = model.generate(**inputs, max_length=max_length, num_beams=num_beams, early_stopping=True)
31
  raw_caption = processor.decode(out[0], skip_special_tokens=True)
32
  polished_caption = postprocess_caption(raw_caption)
33
  return polished_caption
34
 
35
- # Gradio interface with sliders for max_length and num_beams parameters and descriptions
36
- iface = gr.Interface(
37
- fn=generate_caption,
38
- inputs=[
39
- gr.Image(type="pil", label="Upload Image"),
40
- gr.Slider(10, 50, value=30, step=5, label="Caption Max Length",
41
- info="Controls the length of the caption (higher means longer captions)"),
42
- gr.Slider(1, 10, value=5, step=1, label="Beam Search Width",
43
- info="Controls how many caption options the model considers before picking the best")
44
- ],
45
- outputs="text",
46
- title="Enhanced Image Captioning App",
47
- description="Upload an image and get a polished, detailed description. Adjust sliders to control caption length and quality."
48
- )
49
-
50
- if __name__ == "__main__":
51
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from transformers import BlipProcessor, BlipForConditionalGeneration, pipeline
2
  import gradio as gr
3
  from PIL import Image
4
+ import requests
5
+ from io import BytesIO
6
 
7
  # Load the main image captioning model
8
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
9
  model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
10
 
 
11
  text_generator = pipeline("text-generation", model="gpt2")
12
 
13
  def preprocess_image(image):
 
14
  if image.mode != "RGB":
15
  image = image.convert("RGB")
16
  return image
17
 
18
  def postprocess_caption(raw_caption):
19
+ prompt = f"Rewrite this caption more clearly and concisely: {raw_caption}"
20
+ polished = text_generator(prompt, max_length=50, num_return_sequences=1)
21
+ polished_caption = polished[0]['generated_text'].replace(prompt, "").strip()
22
+ polished_caption = polished_caption.split(".")[0] + "."
 
23
  return polished_caption
24
 
25
  def generate_caption(image, max_length=30, num_beams=5):
26
  image = preprocess_image(image)
27
  inputs = processor(image, return_tensors="pt")
 
28
  out = model.generate(**inputs, max_length=max_length, num_beams=num_beams, early_stopping=True)
29
  raw_caption = processor.decode(out[0], skip_special_tokens=True)
30
  polished_caption = postprocess_caption(raw_caption)
31
  return polished_caption
32
 
33
+ def load_sample_image():
34
+ # A sample cat image URL from Wikimedia Commons
35
+ url = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/320px-Cat03.jpg"
36
+ response = requests.get(url)
37
+ img = Image.open(BytesIO(response.content))
38
+ return img
39
+
40
+ with gr.Blocks(theme=gr.themes.Default()) as iface:
41
+ gr.Markdown("# Enhanced Image Captioning App")
42
+ gr.Markdown(
43
+ "Upload an image and get a polished, detailed caption. Adjust the sliders to control caption length and quality."
44
+ )
45
+
46
+ with gr.Row():
47
+ with gr.Column(scale=1):
48
+ image_input = gr.Image(type="pil", label="Upload Image")
49
+ sample_btn = gr.Button("Load Sample Image")
50
+ with gr.Column(scale=1):
51
+ caption_output = gr.Textbox(label="Generated Caption", interactive=False, lines=3)
52
+
53
+ with gr.Accordion("Advanced Options", open=False):
54
+ max_len_slider = gr.Slider(10, 50, value=30, step=5, label="Caption Max Length",
55
+ info="Controls how long the caption is (higher means longer).")
56
+ num_beams_slider = gr.Slider(1, 10, value=5, step=1, label="Beam Width",
57
+ info="Controls how many caption options the model considers for better quality.")
58
+
59
+ sample_btn.click(fn=load_sample_image, inputs=None, outputs=image_input)
60
+
61
+ image_input.change(
62
+ fn=generate_caption,
63
+ inputs=[image_input, max_len_slider, num_beams_slider],
64
+ outputs=caption_output
65
+ )
66
+
67
+ max_len_slider.change(
68
+ fn=generate_caption,
69
+ inputs=[image_input, max_len_slider, num_beams_slider],
70
+ outputs=caption_output
71
+ )
72
+
73
+ num_beams_slider.change(
74
+ fn=generate_caption,
75
+ inputs=[image_input, max_len_slider, num_beams_slider],
76
+ outputs=caption_output
77
+ )
78
+
79
+ iface.launch()