-
Notifications
You must be signed in to change notification settings - Fork 0
/
BanglaT5-test.py
143 lines (101 loc) · 4.13 KB
/
BanglaT5-test.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import json
import pandas as pd
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
from normalizer import normalize
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from transformers import (
AdamW, AutoModelForSeq2SeqLM,AutoTokenizer as Tokenizer)
MODEL_NAME = 'csebuetnlp/banglat5'
tokenizer = Tokenizer.from_pretrained(MODEL_NAME,use_fast=False)
LModel = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME,return_dict=True)
"""## **DataLoader**"""
class BengaliSummaryModel(pl.LightningModule):
def __init__(self):
super().__init__()
self.model = LModel
def forward(self,input_ids,attention_mask,decoder_attention_mask, labels=None):
output = self.model(
input_ids,
attention_mask = attention_mask,
labels = labels
)
return output.loss, output.logits
def training_step(self, batch, batch_idx):
input_ids = batch["text_input_ids"]
attention_mask = batch["text_attention_mask"]
labels = batch["labels"]
labels_attention_mask = batch["labels_attention_mask"]
loss, outputs = self(
input_ids = input_ids,
attention_mask = attention_mask,
decoder_attention_mask = labels_attention_mask,
labels = labels
)
self.log("train_loss",loss,prog_bar=True,logger=True)
return loss
def validation_step(self, batch, batch_idx):
input_ids = batch["text_input_ids"]
attention_mask = batch["text_attention_mask"]
labels = batch["labels"]
labels_attention_mask = batch["labels_attention_mask"]
loss, outputs = self(
input_ids = input_ids,
attention_mask = attention_mask,
decoder_attention_mask = labels_attention_mask,
labels = labels
)
self.log("val_loss",loss,prog_bar=True,logger=True)
return loss
def test_step(self, batch, batch_idx):
input_ids = batch["text_input_ids"]
attention_mask = batch["text_attention_mask"]
labels = batch["labels"]
labels_attention_mask = batch["labels_attention_mask"]
loss, outputs = self(
input_ids = input_ids,
attention_mask = attention_mask,
decoder_attention_mask = labels_attention_mask,
labels = labels
)
self.log("test_loss",loss,prog_bar=True,logger=True)
return loss
def configure_optimizers(self):
return AdamW(self.parameters(),lr = 0.0001)
cppath = 'BanglaT5.ckpt'
trained_model = BengaliSummaryModel.load_from_checkpoint(cppath)
trained_model.freeze()
def summarize_text(text):
text_encoding = tokenizer(
normalize(text),
max_length = 512,
padding = 'max_length',
truncation = True,
return_attention_mask = True,
return_tensors = "pt")
generated_ids = trained_model.model.generate(
input_ids = text_encoding["input_ids"],
max_length=100,
num_beams=2,
repetition_penalty=2.5,
length_penalty=1.0,
early_stopping=True
)
preds = [tokenizer.decode(gen_id,skip_special_tokens=True,clean_up_tokenization_spaces=True)
for gen_id in generated_ids]
return " ".join(preds)
with open('input.txt', 'r') as f:
text = f.read()
model_summary = summarize_text(text)
with open('output.txt', 'a') as f:
f.write('\n==========================================================\n')
f.write("Actual Text : {}\n".format(text))
f.write('----------------------------------------------------------\n')
#f.write("Actual : {}\n".format(sample_row["summary"]))
#f.write("----------------------------------------------------------\n")
f.write("Predicted : {}\n".format(model_summary))
f.write('==========================================================\n')