|
| 1 | +from transformers import pipeline |
| 2 | +from request import ModelRequest |
| 3 | + |
| 4 | +class Model(): |
| 5 | + def __new__(cls, context): |
| 6 | + cls.context = context |
| 7 | + if not hasattr(cls, 'instance'): |
| 8 | + cls.instance = super(Model, cls).__new__(cls) |
| 9 | + cls.nlp_ner = pipeline("ner", model="GautamR/akai_ner", tokenizer="GautamR/akai_ner") |
| 10 | + return cls.instance |
| 11 | + |
| 12 | + async def inference(self, request: ModelRequest): |
| 13 | + entities = self.nlp_ner(request.text) |
| 14 | + return self.aggregate_entities(request.text, entities) |
| 15 | + |
| 16 | + @staticmethod |
| 17 | + def aggregate_entities(sentence, entity_outputs): |
| 18 | + aggregated_entities = [] |
| 19 | + current_entity = None |
| 20 | + |
| 21 | + for entity in entity_outputs: |
| 22 | + entity_type = entity["entity"].split("-")[-1] |
| 23 | + |
| 24 | + # Handle subwords |
| 25 | + if entity["word"].startswith("##"): |
| 26 | + # If we encounter an I-PEST or any other I- entity |
| 27 | + if "I-" in entity["entity"]: |
| 28 | + if current_entity: # Add previous entity |
| 29 | + aggregated_entities.append(current_entity) |
| 30 | + |
| 31 | + word_start = sentence.rfind(" ", 0, entity["start"]) + 1 |
| 32 | + word_end = sentence.find(" ", entity["end"]) |
| 33 | + if word_end == -1: |
| 34 | + word_end = len(sentence) |
| 35 | + |
| 36 | + current_entity = { |
| 37 | + "entity_group": entity_type, |
| 38 | + "score": float(entity["score"]), |
| 39 | + "word": sentence[word_start:word_end].replace('.','').replace('?',''), |
| 40 | + "start": float(word_start), |
| 41 | + "end": float(word_end) |
| 42 | + } |
| 43 | + aggregated_entities.append(current_entity) |
| 44 | + current_entity = None |
| 45 | + |
| 46 | + else: |
| 47 | + # If it's a subword but not an I- entity |
| 48 | + current_entity["word"] += entity["word"][2:] |
| 49 | + current_entity["end"] = entity["end"] |
| 50 | + current_entity["score"] = float((current_entity["score"] + entity["score"]) / 2) # averaging scores |
| 51 | + |
| 52 | + # Handle full words |
| 53 | + else: |
| 54 | + if current_entity: |
| 55 | + aggregated_entities.append(current_entity) |
| 56 | + |
| 57 | + current_entity = { |
| 58 | + "entity_group": entity_type, |
| 59 | + "score": float(entity["score"]), |
| 60 | + "word": entity["word"], |
| 61 | + "start": float(entity["start"]), |
| 62 | + "end": float(entity["end"]) |
| 63 | + } |
| 64 | + |
| 65 | + if current_entity: |
| 66 | + aggregated_entities.append(current_entity) |
| 67 | + |
| 68 | + return aggregated_entities |
0 commit comments