Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
import nltk
|
| 4 |
+
import random
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import T5ForConditionalGeneration,T5Tokenizer
|
| 8 |
+
summary_model = T5ForConditionalGeneration.from_pretrained('t5-base')
|
| 9 |
+
summary_tokenizer = T5Tokenizer.from_pretrained('t5-base')
|
| 10 |
+
|
| 11 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 12 |
+
summary_model = summary_model.to(device)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
nltk.download('punkt')
|
| 16 |
+
nltk.download('brown')
|
| 17 |
+
nltk.download('wordnet')
|
| 18 |
+
from nltk.corpus import wordnet as wn
|
| 19 |
+
from nltk.tokenize import sent_tokenize
|
| 20 |
+
|
| 21 |
+
def set_seed(seed: int):
|
| 22 |
+
random.seed(seed)
|
| 23 |
+
np.random.seed(seed)
|
| 24 |
+
torch.manual_seed(seed)
|
| 25 |
+
torch.cuda.manual_seed_all(seed)
|
| 26 |
+
|
| 27 |
+
set_seed(42)
|
| 28 |
+
|
| 29 |
+
def postprocesstext (content):
|
| 30 |
+
final=""
|
| 31 |
+
for sent in sent_tokenize(content):
|
| 32 |
+
sent = sent.capitalize()
|
| 33 |
+
final = final +" "+sent
|
| 34 |
+
return final
|
| 35 |
+
|
| 36 |
+
def summarizer(text,model,tokenizer):
|
| 37 |
+
text = text.strip().replace("\n"," ")
|
| 38 |
+
text = "summarize: "+text
|
| 39 |
+
# print (text)
|
| 40 |
+
max_len = 512
|
| 41 |
+
encoding = tokenizer.encode_plus(text,max_length=max_len, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
|
| 42 |
+
|
| 43 |
+
input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
|
| 44 |
+
|
| 45 |
+
outs = model.generate(input_ids=input_ids,
|
| 46 |
+
attention_mask=attention_mask,
|
| 47 |
+
early_stopping=True,
|
| 48 |
+
num_beams=3,
|
| 49 |
+
num_return_sequences=1,
|
| 50 |
+
no_repeat_ngram_size=2,
|
| 51 |
+
min_length = 75,
|
| 52 |
+
max_length=300)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
|
| 56 |
+
summary = dec[0]
|
| 57 |
+
summary = postprocesstext(summary)
|
| 58 |
+
summary= summary.strip()
|
| 59 |
+
|
| 60 |
+
return summary
|
| 61 |
+
|
| 62 |
+
demo = gr.Interface(fn=summarizer, inputs="text", outputs="text")
|
| 63 |
+
demo.launch()
|