Datasets:
Upload sample_usage.py with huggingface_hub
Browse files- sample_usage.py +62 -0
sample_usage.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Sample code for using the Portuguese OCR Dataset
|
2 |
+
|
3 |
+
import h5py
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
from transformers import VisionEncoderDecoderModel, TrOCRProcessor
|
8 |
+
import torch
|
9 |
+
|
10 |
+
# Load the dataset
|
11 |
+
def load_dataset(file_path):
|
12 |
+
with h5py.File(file_path, 'r') as f:
|
13 |
+
images = f['images'][:]
|
14 |
+
texts = [t.decode('utf-8') if isinstance(t, bytes) else t for t in f['texts'][:]]
|
15 |
+
return images, texts
|
16 |
+
|
17 |
+
# Load train dataset
|
18 |
+
train_images, train_texts = load_dataset('train_dataset.h5')
|
19 |
+
print(f"Loaded {len(train_images)} training samples")
|
20 |
+
|
21 |
+
# Display a random sample
|
22 |
+
def display_sample(images, texts, idx=None):
|
23 |
+
if idx is None:
|
24 |
+
idx = np.random.randint(0, len(images))
|
25 |
+
|
26 |
+
print(f"Text: {texts[idx]}")
|
27 |
+
|
28 |
+
plt.figure(figsize=(12, 3))
|
29 |
+
plt.imshow(images[idx])
|
30 |
+
plt.axis('off')
|
31 |
+
plt.title(f"Sample {idx}")
|
32 |
+
plt.show()
|
33 |
+
|
34 |
+
return idx
|
35 |
+
|
36 |
+
# Display a random sample
|
37 |
+
sample_idx = display_sample(train_images, train_texts)
|
38 |
+
|
39 |
+
# Example of using with TrOCR
|
40 |
+
def test_with_trocr(image, model_name="microsoft/trocr-base-printed"):
|
41 |
+
# Load model and processor
|
42 |
+
processor = TrOCRProcessor.from_pretrained(model_name)
|
43 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_name)
|
44 |
+
|
45 |
+
# Convert image to PIL if it's a numpy array
|
46 |
+
if isinstance(image, np.ndarray):
|
47 |
+
image = Image.fromarray(image)
|
48 |
+
|
49 |
+
# Prepare image
|
50 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
51 |
+
|
52 |
+
# Generate prediction
|
53 |
+
generated_ids = model.generate(pixel_values)
|
54 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
55 |
+
|
56 |
+
return generated_text
|
57 |
+
|
58 |
+
# Uncomment to test a sample with a pre-trained TrOCR model
|
59 |
+
# sample_img = train_images[sample_idx]
|
60 |
+
# predicted_text = test_with_trocr(sample_img)
|
61 |
+
# print(f"Original text: {train_texts[sample_idx]}")
|
62 |
+
# print(f"Predicted text: {predicted_text}")
|