Spaces:
Running
on
Zero
Running
on
Zero
File size: 2,084 Bytes
44342ba fd11c5a 194e156 3fa52bd fb1de0f 44342ba d4bf218 44342ba 194e156 fb1de0f 44342ba 817e54c fd11c5a 194e156 fd11c5a 3fa52bd 194e156 3fa52bd fd11c5a 194e156 fd11c5a 817e54c fd11c5a 817e54c fd11c5a 817e54c 44342ba 817e54c |
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 |
import gradio as gr
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
from PIL import Image
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
import spaces
# Load TrOCR model
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-large-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-large-handwritten")
def preprocess_image(image):
# Convert image to RGB
image = image.convert("RGB")
# Resize and normalize the image to [0, 1]
transform = transforms.Compose([
transforms.Resize((384, 384)), # Resize to the expected input size
transforms.ToTensor(), # Convert to tensor and scale to [0, 1]
])
pixel_values = transform(image).unsqueeze(0) # Add batch dimension
return pixel_values
def visualize_image(pixel_values):
# Convert tensor to numpy array and permute dimensions for visualization
image = pixel_values.squeeze().permute(1, 2, 0).numpy()
plt.imshow(image)
plt.title("Preprocessed Image")
plt.show()
@spaces.GPU
def recognize_text(image):
try:
# Preprocess the image
pixel_values = preprocess_image(image)
print("Image preprocessed. Pixel values shape:", pixel_values.shape)
# Visualize preprocessed image
visualize_image(pixel_values)
# Generate text from the image
with torch.no_grad():
generated_ids = model.generate(pixel_values)
print("Generated IDs:", generated_ids)
# Decode the generated IDs to text
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print("Decoded text:", text)
return text
except Exception as e:
print(f"Error: {str(e)}")
return f"Error: {str(e)}"
# Gradio UI
note = gr.Interface(
fn=recognize_text,
inputs=gr.Image(type="pil"),
outputs="text",
title="Handwritten Note to Digital Text",
description="Upload an image of handwritten text, and the AI will convert it to digital text."
)
note.launch() |