Spaces:
Sleeping
Sleeping
Create inference.py
Browse files- inference.py +42 -0
inference.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import re
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 4 |
+
|
| 5 |
+
MODEL_NAME = "imelia13/t5-indosum-summarizer"
|
| 6 |
+
|
| 7 |
+
device = torch.device("cpu")
|
| 8 |
+
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 10 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
|
| 11 |
+
model.to(device)
|
| 12 |
+
model.eval()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def clean_text(text: str) -> str:
|
| 16 |
+
text = text.replace("\n", " ")
|
| 17 |
+
text = text.replace("\t", " ")
|
| 18 |
+
text = re.sub(r"\s+", " ", text)
|
| 19 |
+
return text.strip()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def summarize_text(text: str) -> str:
|
| 23 |
+
text = clean_text(text)
|
| 24 |
+
|
| 25 |
+
inputs = tokenizer(
|
| 26 |
+
"ringkas: " + text,
|
| 27 |
+
return_tensors="pt",
|
| 28 |
+
truncation=True,
|
| 29 |
+
max_length=512
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model.generate(
|
| 36 |
+
**inputs,
|
| 37 |
+
max_length=128,
|
| 38 |
+
num_beams=4,
|
| 39 |
+
early_stopping=True
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|