Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create HuggingFaceTransformer.py #35

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions ariadne/contrib/HuggingFaceTransformer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
@author: Ghadeer Mobasher
"""
from cassis import Cas
from ariadne.contrib.inception_util import create_prediction, SENTENCE_TYPE
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForTokenClassification
import pandas as pd
from ariadne.classifier import Classifier

class HuggingFaceClassifier(Classifier):
'''As an example, to use it HuggingFace models for token classification
HuggingFaceClassifier(model_name="ghadeermobasher/BC5CDR-Chemical-Disease-balanced-pubmedbert")'''
def __init__(self, model_name: str):
super().__init__()
self._model = model_name
def predict(self, cas: Cas, layer: str, feature: str, project_id: str, document_id: str, user_id: str):
tokenizer = AutoTokenizer.from_pretrained(self._model)
model = AutoModelForTokenClassification.from_pretrained(self._model)
nlp_ner = pipeline("ner", model=model, tokenizer=tokenizer,aggregation_strategy="max")
for c, sentence in enumerate(cas.select(SENTENCE_TYPE)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't see the c being used. If it is not needed, I guess the enumerate is not needed either?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, true. I was using them for other purposes and forgot to remove them.

columns = {'word', 'start', 'end', 'entity_group', 'score'}
df = pd.DataFrame(columns=columns)
s=nlp_ner(sentence.get_covered_text())
for item in s:
df = df.append(item, ignore_index= True)
for i in range(len(df)):
prediction = create_prediction(cas, layer, feature,df.loc[i, "start"]+sentence.__getattribute__("begin"),df.loc[i, "end"]+sentence.__getattribute__("begin"),df.loc[i, "entity_group"])
mobashgr marked this conversation as resolved.
Show resolved Hide resolved
cas.add_annotation(prediction)