To accomplish your goal, you will need to adjust the entity recognition process to recognize overlapping entities, such as both "Diabetes" and "Diabetes Mellitus" in the same sentence. However, by default, the EntityRuler and the NER pipeline components in spaCy are designed to avoid such overlaps, as they aim to provide unique, best-match entities rather than all possible matches.
One straightforward approach to get around this limitation is by ensuring that your pattern matching pipeline (EntityRuler) does not immediately replace the ner component but rather is added beforehand. This way, you can have the EntityRuler add its findings to the Doc object first, followed by the NER model's predictions. It's crucial, however, to set the overwrite_ents parameter of the EntityRuler to False, so it doesn't overwrite entities that might have been recognized by the model but adds to them instead. This approach may help in catching both "Diabetes" and "Diabetes Mellitus" as separate entities, assuming the model itself can recognize such entities distinctively.
Here's an adjusted version of your example to reflect this approach:
import spacy
from spacy.pipeline import EntityRuler
from negspacy.negation import Negex
nlp = spacy.load('en_ner_bc5cdr_md')
# Create an EntityRuler
ruler = EntityRuler(nlp, overwrite_ents=False)
patterns = [{"label": "DISEASE", "pattern": "Diabetes Mellitus"},
{"label": "DISEASE", "pattern": "Diabetes"},
{"label": "DISEASE", "pattern": "Typhoid"},
{"label": "DISEASE", "pattern": "Cancer"},
{"label": "DISEASE", "pattern": "Banana Cedar"}]
ruler.add_patterns(patterns)
# Add the EntityRuler before the NER component
nlp.add_pipe("entity_ruler", before="ner", config={"overwrite_ents": False})
# Configure and add the Negex pipeline to handle negations after entity recognition
nlp.add_pipe("negex", config={"ent_types":["DISEASE"]})
doc = nlp("The patient was diagnosed with Diabetes Mellitus but not Banana Cedar.")
# Output entities and their negation status
for ent in doc.ents:
negation_status = "Not Present" if ent._.negex else "Present"
print(f"{ent.text}: {negation_status}")
Note: This approach depends on your NER model and how it's trained. If "Diabetes" and "Diabetes Mellitus" are very close in the context, your model may still opt to select only the most specific match ("Diabetes Mellitus") based on its training and the inherent preferences built into the model for longer, more specific entities over shorter, possibly more ambiguous ones.
Additionally, since the adjustments involve both pattern-based and model-based entity recognition strategies, the effectiveness of identifying such closely overlapping entities can vary. If the built-in NER model consistently favors longer matches and thus ignores "Diabetes" when "Diabetes Mellitus" is present, further customization or a more complex approach involving retraining the model might be required to achieve the exact behavior you're looking for.