Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 3 |
+
from gtts import gTTS
|
| 4 |
+
import tempfile
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# Load the 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 |
+
def generate_description(image):
|
| 12 |
+
"""Generates a textual description of the given image using a pre-trained BLIP model."""
|
| 13 |
+
inputs = processor(image, return_tensors="pt").to(model.device)
|
| 14 |
+
output = model.generate(**inputs)
|
| 15 |
+
description = processor.decode(output[0], skip_special_tokens=True)
|
| 16 |
+
return description
|
| 17 |
+
|
| 18 |
+
def text_to_speech(text):
|
| 19 |
+
"""Converts text to speech using gTTS and returns the audio file path."""
|
| 20 |
+
tts = gTTS(text=text, lang='en')
|
| 21 |
+
temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 22 |
+
tts.save(temp_audio.name)
|
| 23 |
+
return temp_audio.name
|
| 24 |
+
|
| 25 |
+
def process_image(image):
|
| 26 |
+
"""Processes the uploaded image to generate description and return audio file."""
|
| 27 |
+
description = generate_description(image)
|
| 28 |
+
return description
|
| 29 |
+
|
| 30 |
+
def get_audio(description):
|
| 31 |
+
"""Generates the audio file for the given description."""
|
| 32 |
+
return text_to_speech(description)
|
| 33 |
+
|
| 34 |
+
# Build Gradio Interface
|
| 35 |
+
with gr.Blocks() as demo:
|
| 36 |
+
gr.Markdown("# Image Description and Audio Transcript App")
|
| 37 |
+
gr.Markdown("Upload an image to get an AI-generated description. Click the button to hear the description.")
|
| 38 |
+
|
| 39 |
+
with gr.Row():
|
| 40 |
+
image_input = gr.Image(type="pil")
|
| 41 |
+
text_output = gr.Textbox(label="Generated Description")
|
| 42 |
+
|
| 43 |
+
generate_btn = gr.Button("Generate Description")
|
| 44 |
+
audio_btn = gr.Button("Click here for an audio transcript")
|
| 45 |
+
audio_output = gr.Audio()
|
| 46 |
+
|
| 47 |
+
generate_btn.click(process_image, inputs=[image_input], outputs=[text_output])
|
| 48 |
+
audio_btn.click(get_audio, inputs=[text_output], outputs=[audio_output])
|
| 49 |
+
|
| 50 |
+
# Launch the Gradio app
|
| 51 |
+
demo.launch()
|