Manuel Torres
Add image captioning functionality from URL
7e5dcf1
Raw History Blame Contribute Delete
3.1 kB
import gradio as gr
import requests
from PIL import Image
from io import BytesIO
from bs4 import BeautifulSoup
from transformers import AutoProcessor, BlipForConditionalGeneration
# Load the pretrained processor and model
processor = AutoProcessor.from_pretrained(
"Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained(
"Salesforce/blip-image-captioning-base")
def process_images_from_url(url):
if not url.startswith('http://') and not url.startswith('https://'):
return "Invalid URL. Please enter a valid URL starting with http:// or https://"
# Download the page
response = requests.get(url)
# Parse the page with BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# Find all img elements
img_elements = soup.find_all('img')
captions = []
for img_element in img_elements:
img_url = img_element.get('src')
# Skip if the image is an SVG or too small (likely an icon)
if 'svg' in img_url or '1x1' in img_url:
continue
# Correct the URL if it's malformed
if img_url.startswith('//'):
img_url = 'https:' + img_url
elif not img_url.startswith('http://') and not img_url.startswith('https://'):
continue # Skip URLs that don't start with http:// or https://
try:
# Download the image
response = requests.get(img_url)
# Convert the image data to a PIL Image
raw_image = Image.open(BytesIO(response.content))
if raw_image.size[0] * raw_image.size[1] < 400: # Skip very small images
continue
raw_image = raw_image.convert('RGB')
# Process the image
inputs = processor(raw_image, return_tensors="pt")
# Generate a caption for the image
out = model.generate(**inputs, max_new_tokens=50)
# Decode the generated tokens to text
caption = processor.decode(out[0], skip_special_tokens=True)
# Append the image URL and caption
captions.append(f"Image URL: {img_url}\n Caption: {caption} \n\n")
except Exception as e:
captions.append(f"Error processing image {img_url}: {e}\n\n")
continue
return "\n".join(captions)
# Gradio interface
def gradio_interface(url):
captions = process_images_from_url(url)
return captions
# Create the Gradio app
# Create the Gradio app with a better layout
with gr.Blocks() as iface:
with gr.Column():
gr.Markdown("### Image Captioning from URL\n\nEnter a URL and this app will extract images from the web page and generate captions using a BLIP model.")
url_input = gr.Textbox(
label="Enter URL", placeholder="https://example.com", lines=1, max_lines=1)
captions_output = gr.Textbox(label="Image Captions", lines=10)
submit_button = gr.Button("Submit")
submit_button.click(
gradio_interface, inputs=url_input, outputs=captions_output)
# Launch the app
iface.launch()