Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,28 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import torch
|
| 3 |
import spaces
|
| 4 |
import gradio as gr
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
| 13 |
|
| 14 |
-
# This is 100% standard Gradio code, so the ZeroGPU scanner will perfectly detect it!
|
| 15 |
@spaces.GPU
|
| 16 |
def predict(image):
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
-
model.to(device)
|
| 22 |
-
|
| 23 |
pixel_values = processor(image, return_tensors="pt").pixel_values.to(device)
|
| 24 |
generated_ids = model.generate(pixel_values)
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
-
#
|
| 28 |
demo = gr.Interface(
|
| 29 |
fn=predict,
|
| 30 |
inputs=gr.Image(type="pil"),
|
| 31 |
-
outputs="text",
|
| 32 |
title="TrOCR Hub Backend"
|
| 33 |
)
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 1 |
import spaces
|
| 2 |
import gradio as gr
|
| 3 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 4 |
+
import torch
|
| 5 |
|
| 6 |
+
# Load models
|
| 7 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 8 |
+
processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-handwritten')
|
| 9 |
+
model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-handwritten').to(device)
|
|
|
|
| 10 |
|
|
|
|
| 11 |
@spaces.GPU
|
| 12 |
def predict(image):
|
| 13 |
+
if image is None:
|
| 14 |
+
return ""
|
| 15 |
+
# Process the image directly on the ZeroGPU
|
|
|
|
|
|
|
|
|
|
| 16 |
pixel_values = processor(image, return_tensors="pt").pixel_values.to(device)
|
| 17 |
generated_ids = model.generate(pixel_values)
|
| 18 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 19 |
+
return generated_text
|
| 20 |
|
| 21 |
+
# The real interface that perfectly matches v5.0.3!
|
| 22 |
demo = gr.Interface(
|
| 23 |
fn=predict,
|
| 24 |
inputs=gr.Image(type="pil"),
|
| 25 |
+
outputs="text",
|
| 26 |
title="TrOCR Hub Backend"
|
| 27 |
)
|
| 28 |
|