File size: 1,932 Bytes
6391da0
 
 
 
 
265ddde
6391da0
265ddde
a007769
265ddde
6391da0
 
683c2c6
6391da0
683c2c6
6391da0
 
a007769
265ddde
 
a007769
265ddde
6391da0
265ddde
6391da0
 
 
 
 
a007769
 
6391da0
265ddde
 
a007769
 
265ddde
6391da0
 
 
a007769
683c2c6
6391da0
 
 
 
 
 
265ddde
 
 
 
6391da0
265ddde
a007769
265ddde
 
6391da0
265ddde
 
 
6391da0
265ddde
 
 
 
 
6391da0
 
265ddde
6391da0
 
265ddde
 
 
 
 
683c2c6
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
import torch
from PIL import Image
from transformers import BlipProcessor, BlipForConditionalGeneration
import gradio as gr
from gtts import gTTS
import os

# -------------------------------
# Load Model
# -------------------------------
device = "cuda" if torch.cuda.is_available() else "cpu"

processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained(
    "Salesforce/blip-image-captioning-base"
).to(device)

print("Model loaded successfully!")

# -------------------------------
# Caption + Text-to-Speech Function
# -------------------------------
def generate_caption(image):

    if image is None:
        return "Please upload an image first.", None

    image = image.convert("RGB")

    #  Correct way (NO prompt)
    inputs = processor(images=image, return_tensors="pt").to(device)

    output = model.generate(
        **inputs,
        max_length=100,
        num_beams=5
    )

    caption = processor.decode(output[0], skip_special_tokens=True)

    #  Convert text to speech
    audio_path = "caption_audio.mp3"
    tts = gTTS(text=caption, lang='en')
    tts.save(audio_path)

    return caption, audio_path


# -------------------------------
# Gradio UI
# -------------------------------
with gr.Blocks(theme=gr.themes.Soft()) as demo:

    gr.Markdown("""
    # Image Caption Generator
    ### Generate detailed captions + Voice Output
    """)

    with gr.Row():
        image_input = gr.Image(type="pil", label="Upload Image")
        output_text = gr.Textbox(label="Detailed Caption", lines=4)

    audio_output = gr.Audio(label="🔊 Listen to Caption")

    generate_btn = gr.Button("Generate Caption")

    generate_btn.click(
        fn=generate_caption,
        inputs=image_input,
        outputs=[output_text, audio_output]
    )



# -------------------------------
# Launch
# -------------------------------
demo.launch()