File size: 3,096 Bytes
7e5dcf1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()