File size: 5,233 Bytes
c7a7d1a
d7cc84c
8469a31
c7a7d1a
5c17079
 
ff5bde8
b80c049
4d50659
1ab9990
5c17079
4ed16e0
 
1ab9990
 
 
4ed16e0
 
 
 
5c17079
 
4ed16e0
 
 
467849f
1ab9990
5c17079
1ab9990
6d41dac
 
c79210f
6d41dac
4ed16e0
 
6d41dac
 
14993ed
5c17079
4ed16e0
 
 
 
6d41dac
5c17079
6d41dac
 
14993ed
5c17079
4ed16e0
 
5c17079
4ed16e0
1ab9990
 
4ed16e0
 
 
 
 
c79210f
 
5c17079
4ed16e0
 
5c17079
4ed16e0
1ab9990
 
4ed16e0
 
 
 
 
5c17079
 
 
 
 
 
4ed16e0
 
 
 
 
5c17079
4ed16e0
5c17079
4ed16e0
 
2f38ad4
5c17079
4ed16e0
5c17079
4ed16e0
1ab9990
 
c79210f
4ed16e0
2f38ad4
ff5bde8
c20dc93
1ab9990
5c17079
1ab9990
 
 
 
 
5c17079
1ab9990
5c17079
1ab9990
 
 
 
 
 
5c17079
1ab9990
5c17079
 
1ab9990
 
 
 
 
 
 
 
 
 
 
 
 
5c17079
1ab9990
 
5c17079
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ab9990
5c17079
 
ff5bde8
5c17079
 
 
 
 
1ab9990
 
 
 
e20eb5a
5c17079
 
ff5bde8
5c17079
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import re
import gradio as gr
from entity_dictionary import ENTITY_DICTIONARY


# tokenize
def tokenize(text):
    return re.findall(r"\w+|[.!?]", text)


# dictionary matching
def find_dictionary_match(tokens, start):
    for category, phrases in ENTITY_DICTIONARY.items():
        if category == "REGEX_PATTERNS":
            continue

        for phrase in phrases:
            p_tokens = phrase.split()
            span = tokens[start:start + len(p_tokens)]

            if len(span) == len(p_tokens) and \
               [t.lower() for t in span] == [p.lower() for p in p_tokens]:
                return category, len(p_tokens), " ".join(span)

    return None


# dictionary entity detection
def detect_dictionary_entities(text):
    tokens = tokenize(text)
    entities = []

    i = 0
    sentence_start = True

    while i < len(tokens):
        token = tokens[i]

        if token in ".!?":
            sentence_start = True
            i += 1
            continue

        if not token.isalpha():
            sentence_start = False
            i += 1
            continue

        # sentence start
        if sentence_start:
            match = find_dictionary_match(tokens, i)

            if match:
                cat, length, value = match
                entities.append({"text": value, "type": cat})
                i += length
            else:
                i += 1

            sentence_start = False
            continue

        # capitalized groups
        if token[0].isupper():
            match = find_dictionary_match(tokens, i)

            if match:
                cat, length, value = match
                entities.append({"text": value, "type": cat})
                i += length
                continue

            phrase = [token]
            j = i + 1

            while (
                j < len(tokens)
                and tokens[j].isalpha()
                and tokens[j][0].isupper()
            ):
                phrase.append(tokens[j])
                j += 1

            entities.append({
                "text": " ".join(phrase),
                "type": "CAP_GROUP"
            })

            i = j
            continue

        # normal dictionary matching
        match = find_dictionary_match(tokens, i)

        if match:
            cat, _, value = match
            entities.append({"text": value, "type": cat})

        i += 1

    return entities


# regex detection
def detect_regex_entities(text, existing_entities):
    if "REGEX_PATTERNS" not in ENTITY_DICTIONARY:
        return []

    occupied = set()

    for e in existing_entities:
        for m in re.finditer(re.escape(e["text"]), text, re.IGNORECASE):
            occupied.update(range(m.start(), m.end()))

    matches = []

    for category, pattern in ENTITY_DICTIONARY["REGEX_PATTERNS"].items():
        for m in re.finditer(pattern, text):

            span = set(range(m.start(), m.end()))

            # avoid overlap
            if span & occupied:
                continue

            matches.append({
                "text": m.group(),
                "type": category,
                "start": m.start(),
                "end": m.end(),
                "length": m.end() - m.start()
            })

    matches.sort(key=lambda x: x["length"], reverse=True)

    return [{"text": m["text"], "type": m["type"]} for m in matches]


# masking
def mask_text(text, entities):
    masked = text
    entity_map = {}
    counter = 1

    for e in sorted(entities, key=lambda x: len(x["text"]), reverse=True):

        ph = f"z{counter}"
        counter += 1

        masked = re.sub(
            rf"\b{re.escape(e['text'])}\b",
            ph,
            masked,
            flags=re.IGNORECASE
        )

        entity_map[ph] = e["text"]

    return masked, entity_map


# main function
def detect_and_mask(text):

    if not text.strip():
        return "", "", ""

    # option B entity detection
    dict_entities = detect_dictionary_entities(text)
    regex_entities = detect_regex_entities(text, dict_entities)

    entities = dict_entities + regex_entities

    # remove duplicates
    unique = {}
    for e in entities:
        key = e["text"].lower()

        if key not in unique:
            unique[key] = e

    entities = list(unique.values())

    # mask
    masked_text, entity_map = mask_text(text, entities)

    # format entities
    if entities:
        entity_output = "\n".join(
            [f"{e['text']} --> {e['type']}" for e in entities]
        )
    else:
        entity_output = "No entities detected."

    # format placeholders
    mapping_output = "\n".join(
        [f"{k} --> {v}" for k, v in entity_map.items()]
    )

    return entity_output, masked_text, mapping_output


# gradio interface
iface = gr.Interface(
    fn=detect_and_mask,
    inputs=gr.Textbox(
        lines=4,
        placeholder="Enter sentence..."
    ),
    outputs=[
        gr.Textbox(lines=10, label="Detected Entities"),
        gr.Textbox(lines=4, label="Masked Sentence"),
        gr.Textbox(lines=10, label="Placeholder Mapping")
    ],
    title="Entity Detection and Masking",
    description="Detects entities and generates masked sentence",
    api_name="detect_entities"
)

iface.launch()