Spaces:
Build error
Build error
File size: 1,913 Bytes
420f2a2 b37f538 75083b9 420f2a2 75083b9 5edb59b b37f538 a7fe715 420f2a2 96c8cef 420f2a2 b37f538 75083b9 66d5ecb 96c8cef b37f538 96c8cef 4f36eca b37f538 96c8cef b37f538 420f2a2 5edb59b f241f2a a6a0b8d f241f2a a6a0b8d f241f2a 5edb59b f241f2a | 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 | 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()
|