Spaces:
Build error

ImageToText / app.py
ujembe's picture
Update app.py
66d5ecb verified
Raw History Blame Contribute Delete
1.91 kB
import gradio as gr
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
from PIL import Image
import torch
# Load the image-captioning model and necessary processors
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
processor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
# Ensure model is in evaluation mode to reduce memory usage
model.eval()
# Define the function to convert image to text
def image_to_text(image):
try:
# Check if image is loaded properly
if image is None or not isinstance(image, Image.Image):
return "Error: Invalid image type. Please upload a valid image."
# Preprocess the image with padding and return tensors
pixel_values = processor(images=image, return_tensors="pt", padding=True, truncation=True).pixel_values
# Ensure the tensor is the correct size
if pixel_values.shape[1] == 0:
return "Error: Unable to create tensor. The image might be empty or invalid."
# Generate text caption with padding considered
output_ids = model.generate(pixel_values, max_length=16, num_beams=4, early_stopping=True)
# Decode the output ids to text
caption = tokenizer.decode(output_ids[0], skip_special_tokens=True)
return caption.strip()
except Exception as e:
# Return any error message for debugging
return f"Error: {e}"
# Gradio interface setup
with gr.Blocks() as demo:
with gr.Row():
img_input = gr.Image(type="pil", label="Upload Image")
text_output = gr.Textbox(label="Extracted Text")
img_input.change(image_to_text, inputs=img_input, outputs=text_output)
# Start the Gradio interface
if __name__ == "__main__":
demo.launch()