sk2003 commited on
Commit
a35bb55
·
1 Parent(s): e316093

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -0
app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary packages
2
+ import pandas as pd # pandas for reading csv files
3
+ import matplotlib.pyplot as plt # for creating plots
4
+ from sklearn.model_selection import train_test_split # for splitting the data into train, validation and test sets
5
+ import torch # PyTorch used for executing deep learning functions
6
+ # to store the data and ground truths to be used by the model, loader is an iterable over the Datasets created, the last one is to concatenate Dataset objects
7
+ from torch.utils.data import Dataset, DataLoader, ConcatDataset
8
+ from PIL import Image, ImageTk # to display the image from the encoded pixels
9
+ import gradio as gr
10
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel # importing the TrOCR processor representing the visual feature extrcator and tokenizer of the TrOCR model, and the TrOCR model
11
+
12
+ processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
13
+ # loading and initializing with the pre-trained base trocr model
14
+ model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
15
+ # ADAM optimizer with decaying weights and the learning rate is set to 0.00005
16
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
17
+
18
+ # configuring the model and setting undefined parameters
19
+ # the decoder input_ids require the start and pad tokens, they are created by shifting the input to the right once
20
+ model.config.decoder_start_token_id = processor.tokenizer.cls_token_id # id (=0) of the class token- <s> used as the first token after the inputs are shifted to the right for the decoder
21
+ model.config.pad_token_id = processor.tokenizer.pad_token_id # id (=1) of the pad token- <pad>
22
+ model.config.vocab_size = model.config.decoder.vocab_size # language modelling vocabulary size is set to default value of the decoder of the model (=50625)
23
+ # sequence generation parameters associated with beam search (https://huggingface.co/blog/how-to-generate)
24
+ model.config.eos_token_id = processor.tokenizer.sep_token_id # id (=2) of the separator token- </s> that is used at the end of the string, originally undefined
25
+ model.config.max_length = 32 # maximum length to be used by the text generation function, originally 20
26
+ # for below value- (https://machinelearningmastery.com/beam-search-decoder-natural-language-processing/#:~:text=Common%20beam%20width%20values%20are,better%20matching%20a%20target%20sequence.)
27
+ model.config.num_beams = 5 # number of beams in beam search, beam width - number of sequences to consider while picking the one with the highest probablity, originally 1 (so only greedy search)
28
+ model.config.early_stopping = True # beam search is stopped when 5(num_beams) sentences are done at a time (batch), originally False
29
+ model.config.no_repeat_ngram_size = 3 # ngrams of size 3 can occur only once, to avoid word repetitions
30
+
31
+ data_1 = pd.read_csv('washingtondb-v1.0/ground_truth/lines_truths.csv', header=None)
32
+ images_location_1 = 'washingtondb-v1.0/data/line_images_normalized/'
33
+ data_1.rename(columns={0: "file_name", 1: "text"}, inplace=True)
34
+ data_1['file_name'] = [x + ".png" for x in data_1['file_name']]
35
+
36
+ data_1['text'] = data_1['text'].str.replace('|',' ')
37
+ # all characters in the ground truth have been separated by hyphens (-) so they are removed
38
+ data_1['text'] = data_1['text'].str.replace('-','')
39
+
40
+ data_1.drop(data_1.index[data_1['text'].str.contains('s_sl')], inplace = True)
41
+ data_1.reset_index(drop=True, inplace=True)
42
+
43
+ replace_chars = {'s_pt':'.', 's_qo':':','s_mi':'-', 's_bl':'(', 's_br':')', 's_sq':';', 's_s':'s', 's_cm':',', 's_et':'et', 's_lb':'£', 's_GW':'G.W.', 's_0':'0', 's_1':'1', 's_2':'2', 's_3':'3', 's_4':'4', 's_5':'5', 's_6':'6', 's_7':'7', 's_8':'8', 's_9':'9' }
44
+ # iterating over the dictionary to replace the keys with the values
45
+ for char in replace_chars.keys():
46
+ data_1['text'] = data_1['text'].str.replace(char, replace_chars[char])
47
+
48
+ data_2 = pd.read_excel('Dates/Part I.xlsx')
49
+ images_location_2 = 'Dates/Part I/'
50
+ data_2.drop(['Image_Right', 'City', 'Category'], axis = 1, inplace = True)
51
+ data_2.rename(columns={"Image_Left": "file_name", "Date": "text"}, inplace=True)
52
+ data_2 = data_2.astype({'text': 'str'})
53
+ data_2['file_name'] = [x + ".jpg" for x in data_2['file_name']]
54
+
55
+ train_1, test_1 = train_test_split(data_1, test_size=0.2) # splitting the data_1 dataframe into train and test sets with 80-20 split
56
+ train_1, val_1 = train_test_split(train_1, test_size=0.25) # further splitting the training set using 75-25 split for the validation set
57
+ # the indices of the three data sets are reset in the same dataframe to freshly start from 0 each
58
+ # instead of retaining indices from the original 'data' dataframe and the old indices are avoided being put as another column
59
+ train_1.reset_index(drop=True, inplace=True)
60
+ val_1.reset_index(drop=True, inplace=True)
61
+ test_1.reset_index(drop=True, inplace=True)
62
+ train_2, test_2 = train_test_split(data_2, test_size=0.2) # splitting the data_2 dataframe into train and test datasets
63
+ train_2, val_2 = train_test_split(train_2, test_size=0.25) # further splitting for the validatio set
64
+ # the indices of the three data sets are reset to 0 and old indices are avoided being put as another column
65
+ train_2.reset_index(drop=True, inplace=True)
66
+ val_2.reset_index(drop=True, inplace=True)
67
+ test_2.reset_index(drop=True, inplace=True)
68
+
69
+ class ImageData(Dataset):
70
+ """
71
+ Class representing a custom PyTorch Dataset implementation with the images and their labels
72
+ """
73
+ def __init__(self, data, location):
74
+ """
75
+ Initialization Function
76
+ """
77
+ self.data = data
78
+ self.location = location
79
+ self.processor = processor
80
+
81
+ def __len__(self):
82
+ """
83
+ Function to get the number of samples in the Dataset
84
+ """
85
+ return len(self.data)
86
+
87
+ def __getitem__(self, idx):
88
+ """
89
+ Function/Getter for the contents of a WordData object at index- idx
90
+ Parameter:
91
+ idx - index at which the contents are to be retrieved
92
+ """
93
+ # to get the image file's name
94
+ img_file = self.location + self.data['file_name'][idx]
95
+ # resizing and normalizing the image to 3, 384, 384 (channels, image width and height) after removing the unnecessary 1 dimension bu using squeeze()
96
+ pixels = (self.processor(Image.open(img_file).convert("RGB"), return_tensors="pt").pixel_values).squeeze()
97
+ # encoding the text and getting the input ids or the encoded ground truth values
98
+ # and all values until after the last value 128th one will be made the padding token
99
+ enc_values = self.processor.tokenizer(self.data['text'][idx],
100
+ padding="max_length",
101
+ max_length=32).input_ids
102
+
103
+ # encoded ground truth values are made into a tensor to use in computation
104
+ # while the pad tokens each are set to -100 to be ignored during the computation of the loss
105
+ enc_values = torch.tensor([value if value != self.processor.tokenizer.pad_token_id else -100 for value in enc_values])
106
+
107
+ encodings = {"pixel_values": pixels, "labels": enc_values}
108
+ return encodings
109
+
110
+ # Creating ImageDataset objects for training, validation and testing sets
111
+ train_df_1 = ImageData(data=train_1, location=images_location_1)
112
+ val_df_1 = ImageData(data=val_1, location=images_location_1)
113
+ test_df_1 = ImageData(data=test_1, location=images_location_1)
114
+
115
+ train_df_2 = ImageData(data=train_2, location=images_location_2)
116
+ val_df_2 = ImageData(data=val_2, location=images_location_2)
117
+ test_df_2 = ImageData(data=test_2, location=images_location_2)
118
+
119
+ train_df = ConcatDataset([train_df_1,train_df_2])
120
+ val_df = ConcatDataset([val_df_1,val_df_2])
121
+ test_df = ConcatDataset([test_df_1, test_df_2])
122
+
123
+ # Creating DataLoaders for training, validation and testing data sets, each element is a batch of size 32
124
+ # with data samples and all batches are shuffled at every epoch
125
+ train_dataloader = DataLoader(train_df, batch_size=32, shuffle=True)
126
+ val_dataloader = DataLoader(val_df, batch_size=32, shuffle=True)
127
+ test_dataloader = DataLoader(test_df, batch_size=32, shuffle=True)
128
+
129
+ epochs = 2
130
+ losses = []
131
+
132
+ # Training the model on the training data and validating using the validation set over epochs
133
+ for epoch in range(epochs):
134
+ loss_sum = 0.0 # represents the sum of the loss loss computed after forward propagation of the inputs over each batch
135
+ model.train() # to put in training mode to activate Dropout and BatchNorm layers
136
+
137
+ # iterating all the batches of data in the DataLoader with training data
138
+ # and the pixel values and associated ground truth, keys and values of the WordData objects
139
+ # tqdm is used for displaying the progress bar covering each of the batches
140
+ for batch in train_dataloader:
141
+ # data is used on the same device as the model
142
+ # for key in batch.keys(): # iterating over the keys of the batch dictionary
143
+ # batch[key] = batch[key].to(device)
144
+ optimizer.zero_grad() # resetting the gradients of optimized tensor to 0
145
+ outputs = model(**batch) # the input is passed to the model for forward propagation
146
+ loss = outputs.loss # represents the loss computed after forward propagation of the inputs
147
+ loss.backward() # backward propagation, calculating gradients
148
+ loss_sum += loss.item() # loss is converted into a number and is on the CPU now
149
+ optimizer.step() # optimizer is run, weights are updated
150
+ final_loss = loss_sum/len(train_dataloader)
151
+ losses.append(final_loss)
152
+
153
+ def process_image(image):
154
+ # prepare image
155
+ pixel_values = processor(image, return_tensors="pt").pixel_values
156
+
157
+ # generate
158
+ generated_ids = model.generate(pixel_values)
159
+
160
+ # decode
161
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
162
+
163
+ return generated_text
164
+
165
+ title = "Hist-TrOCR"
166
+ description = "Interactive demo of Hist-TrOCR, a fine-tuned version of Microsoft's TrOCR which is an end-to-end transformer model used for recognition of text from single-line or word images. It has been fine-tuned on historical text images. Upload an image or use one of the sample images below and click 'submit' to get the transcriptions. Results may take a few seconds to show up."
167
+
168
+ # image1 = Image.open(images_location_1 + data_1['file_name'][10])
169
+ # image = Image.open(images_location_1 + data_1['file_name'][11])
170
+ # examples =[image1, image]
171
+
172
+ iface = gr.Interface(fn=process_image,
173
+ inputs=gr.inputs.Image(type="pil"),
174
+ outputs=gr.outputs.Textbox(),
175
+ title=title,
176
+ description=description)
177
+ iface.launch(debug=True)