Skip to content
Snippets Groups Projects
user_replacer.py 1.13 KiB
Newer Older
Michał Pogoda's avatar
Michał Pogoda committed
from typing import List, Tuple
from src.annotations import (
    Annotation,
    UserAnnotation,
)
from src.string_replacements import replace_and_update
from src.replacers.interface import ReplacerInterface
from random_username.generate import generate_username

class UserReplacer(ReplacerInterface):
    def __init__(self):
        pass
    
    def replace(self, text: str, detections: List[Tuple[int, int, Annotation]]) -> Tuple[str, List[Tuple[int, int, Annotation]]]:
        replacements = []
        not_processed = []
        
        already_replaced = dict()
        
        for item in detections:
            start, end, detection = item
            
            if isinstance(detection, UserAnnotation):
                if text[start:end] not in already_replaced:
                    username = "@" + generate_username(1)[0]
                    already_replaced[text[start:end]] = username
                    
                replacements.append((start, end, already_replaced[text[start:end]]))
            else:
                not_processed.append(item)
            
        return replace_and_update(text, replacements, not_processed)