Valeriy Sinyukov
commited on
Commit
·
4b079b8
1
Parent(s):
283e838
Add scibert model
Browse files
category_classification/models/HibiscusMaximus__scibert_paper_classification/model.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as tp
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from transformers import pipeline, Pipeline, AutoModelForSequenceClassification
|
5 |
+
from transformers.pipelines import PIPELINE_REGISTRY
|
6 |
+
|
7 |
+
name = "HibiscusMaximus/scibert_paper_classification"
|
8 |
+
|
9 |
+
|
10 |
+
class SciBertPaperClassifierPipeline(Pipeline):
|
11 |
+
def _sanitize_parameters(self, **kwargs):
|
12 |
+
return {}, {}, {}
|
13 |
+
|
14 |
+
def preprocess(self, inputs):
|
15 |
+
if not isinstance(inputs, tp.Iterable):
|
16 |
+
inputs = [inputs]
|
17 |
+
texts = [
|
18 |
+
f"AUTHORS: {' '.join(paper.authors) if isinstance(paper.authors, list) else paper.authors} "
|
19 |
+
f"TITLE: {paper.title} ABSTRACT: {paper.abstract}"
|
20 |
+
for paper in inputs
|
21 |
+
]
|
22 |
+
inputs = self.tokenizer(
|
23 |
+
texts, truncation=True, padding=True, max_length=256, return_tensors="pt"
|
24 |
+
).to(self.device)
|
25 |
+
return inputs
|
26 |
+
|
27 |
+
def _forward(self, model_inputs):
|
28 |
+
with torch.no_grad():
|
29 |
+
outputs = self.model(**model_inputs)
|
30 |
+
return outputs
|
31 |
+
|
32 |
+
def postprocess(self, model_outputs):
|
33 |
+
probs = torch.nn.functional.softmax(model_outputs.logits, dim=-1)
|
34 |
+
results = []
|
35 |
+
for prob in probs:
|
36 |
+
result = [
|
37 |
+
{"label": self.model.config.id2label[label_idx], "score": score.item()}
|
38 |
+
for label_idx, score in enumerate(prob)
|
39 |
+
]
|
40 |
+
results.append(result)
|
41 |
+
if 1 == len(results):
|
42 |
+
return results[0]
|
43 |
+
return results
|
44 |
+
|
45 |
+
|
46 |
+
PIPELINE_REGISTRY.register_pipeline(
|
47 |
+
"paper-classification",
|
48 |
+
pipeline_class=SciBertPaperClassifierPipeline,
|
49 |
+
pt_model=AutoModelForSequenceClassification,
|
50 |
+
)
|
51 |
+
|
52 |
+
|
53 |
+
class SciBertPaperClassifier:
|
54 |
+
def __init__(self):
|
55 |
+
self.pipeline = pipeline("paper-classification", model=name)
|
56 |
+
|
57 |
+
def __call__(self, input):
|
58 |
+
return self.pipeline(input)
|
59 |
+
|
60 |
+
|
61 |
+
def get_model():
|
62 |
+
return SciBertPaperClassifier()
|
63 |
+
|
64 |
+
|
65 |
+
supported_langs = ["en"]
|