Spaces:
Sleeping
Sleeping
Download app.py from kanimozhi-2103/Image_Captioning: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/kanimozhi-2103/Image_Captioning/resolve/main/app.py
- Command line
-
hf download hf://spaces/kanimozhi-2103/Image_Captioning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kanimozhi-2103/Image_Captioning/resolve/main/app.py
1.93 kB
| 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() |