File size: 15,883 Bytes
1376fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b195a06
 
1376fd4
 
1ba6579
1376fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c36f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1376fd4
81c36f4
 
1376fd4
81c36f4
1376fd4
 
 
81c36f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1376fd4
81c36f4
 
f8fcf26
81c36f4
 
1376fd4
 
 
81c36f4
1376fd4
81c36f4
 
 
 
1376fd4
81c36f4
1376fd4
81c36f4
 
 
 
 
 
 
 
 
 
 
 
1376fd4
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import boto3
import os
import json
import re
import gradio as gr
from typing import List, Dict, Tuple, Optional, Union, Any

# โ”€โ”€ S3 CONFIG โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
s3 = boto3.client(
    "s3",
    aws_access_key_id     = os.getenv("AWS_ACCESS_KEY_ID"),
    aws_secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY"),
    region_name           = os.getenv("AWS_DEFAULT_REGION", "ap-southeast-2"),
)

# ai4data/datause-annotation
# S3 bucket and keys
BUCKET       = "doccano-processed"
#INIT_KEY     = "gradio/initial_data_train.json"
INIT_KEY = "gradio/refugee_train_initial_data_v2.json"
#VALID_PREFIX = "validated_records/"
VALID_PREFIX = "refugee_train_validated/"

# โ”€โ”€ Helpers to load & save from S3 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def load_initial_data() -> List[Dict]:
    obj = s3.get_object(Bucket=BUCKET, Key=INIT_KEY)
    return json.loads(obj['Body'].read())

def load_all_validations() -> Dict[int, Dict]:
    records = {}
    pages = s3.get_paginator("list_objects_v2").paginate(
        Bucket=BUCKET, Prefix=VALID_PREFIX
    )
    for page in pages:
        for obj in page.get("Contents", []):
            key = obj["Key"]
            idx = int(os.path.splitext(os.path.basename(key))[0])
            data = s3.get_object(Bucket=BUCKET, Key=key)["Body"].read()
            records[idx] = json.loads(data)
    return records

def save_single_validation(idx: int, record: Dict):
    key = f"{VALID_PREFIX}{idx}.json"
    s3.put_object(
        Bucket      = BUCKET,
        Key         = key,
        Body        = json.dumps(record, indent=2).encode('utf-8'),
        ContentType = 'application/json'
    )

class DynamicDataset:
    def __init__(self, data: List[Dict]):
        self.data    = data
        self.len     = len(data)
        self.current = 0
        for ex in self.data:
            ex.setdefault("validated", False)

    def example(self, idx: int) -> Dict:
        self.current = max(0, min(self.len - 1, idx))
        return self.data[self.current]

    def next(self) -> Dict:
        if self.current < self.len - 1:
            self.current += 1
        return self.data[self.current]

    def prev(self) -> Dict:
        if self.current > 0:
            self.current -= 1
        return self.data[self.current]

    def jump_next_unvalidated(self) -> Dict:
        for i in range(self.current + 1, self.len):
            if not self.data[i]["validated"]:
                self.current = i
                break
        return self.data[self.current]

    def jump_prev_unvalidated(self) -> Dict:
        for i in range(self.current - 1, -1, -1):
            if not self.data[i]["validated"]:
                self.current = i
                break
        return self.data[self.current]

    def validate(self):
        self.data[self.current]["validated"] = True

def tokenize_text(text: str) -> List[str]:
    return re.findall(r"\w+(?:[-_]\w+)*|[^\s\w]", text)

def prepare_for_highlight(data: Dict) -> List[Tuple[str, Optional[str]]]:
    tokens = data["tokenized_text"]
    ner    = data["ner"]
    highlighted, curr_ent, ent_buf, norm_buf = [], None, [], []
    for idx, tok in enumerate(tokens):
        if curr_ent is None or idx > curr_ent[1]:
            if ent_buf:
                highlighted.append((" ".join(ent_buf), curr_ent[2]))
                ent_buf = []
            curr_ent = next((e for e in ner if e[0] == idx), None)
        if curr_ent and curr_ent[0] <= idx <= curr_ent[1]:
            if norm_buf:
                highlighted.append((" ".join(norm_buf), None))
                norm_buf = []
            ent_buf.append(tok)
        else:
            if ent_buf:
                highlighted.append((" ".join(ent_buf), curr_ent[2]))
                ent_buf = []
            norm_buf.append(tok)
    if ent_buf:
        highlighted.append((" ".join(ent_buf), curr_ent[2]))
    if norm_buf:
        highlighted.append((" ".join(norm_buf), None))
    return [(re.sub(r"\s(?=[,\.!?โ€ฆ:;])", "", txt), lbl) for txt, lbl in highlighted]


def extract_tokens_and_labels(highlighted: List[Dict[str, Union[str, None]]]
                            ) -> Tuple[List[str], List[Tuple[int,int,str]]]:
    tokens, ner = [], []
    token_idx = 0

    for entry in highlighted:
        text  = entry['token']
        label = entry.get('class_or_confidence') or entry.get('class') or entry.get('label')
        # split into real tokens
        toks = tokenize_text(text)
        start = token_idx
        end   = token_idx + len(toks) - 1

        tokens.extend(toks)
        if label:
            ner.append((start, end, label))

        token_idx = end + 1

    return tokens, ner


# โ”€โ”€ App factory โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# def create_demo() -> gr.Blocks:
#     data             = load_initial_data()
#     validated_store  = load_all_validations()

#     for idx in validated_store:
#         if 0 <= idx < len(data):
#             data[idx]["validated"] = True
#     dynamic_dataset  = DynamicDataset(data)
#     with gr.Blocks() as demo:
#         prog      = gr.Slider(0, dynamic_dataset.len-1, value=0, step=1, label="Example #", interactive=False)
#         inp_box   = gr.HighlightedText(label="Sentence", interactive=True)
#         status    = gr.Checkbox(label="Validated?", value=False, interactive=False)
#         filename_disp = gr.Markdown(label="Filename")    # NEW: shows current filename
#         page_disp     = gr.Markdown(label="Page")        # NEW: shows current page number
#         gr.Markdown(
#             "[๐Ÿ“– Entity Tag Guide](https://huggingface.co/spaces/rafmacalaba/datause-annotation/blob/main/guidelines.md)"
#         )
        
#         with gr.Row():
#             prev_btn  = gr.Button("โ—€๏ธ Previous")
#             apply_btn = gr.Button("๐Ÿ“ Apply Changes")
#             next_btn  = gr.Button("Next โ–ถ๏ธ")
#         with gr.Row():
#             skip_prev = gr.Button("โฎ๏ธ Prev Unvalidated")
#             validate_btn = gr.Button("โœ… Validate")
#             skip_next = gr.Button("โญ๏ธ Next Unvalidated")

#         # def load_example(idx):
#         #     rec  = validated_store.get(idx, dynamic_dataset.example(idx))
#         #     segs = prepare_for_highlight(rec)
#         #     return segs, rec.get("validated", False), idx

#         def load_example(idx):
#             rec  = validated_store.get(idx, dynamic_dataset.example(idx))
#             segs = prepare_for_highlight(rec)
#             return (
#                 segs,
#                 rec.get("validated", False),
#                 idx,
#                 rec.get("filename", ""),    # <-- returns filename for filename_disp
#                 f"Page {rec.get('page', '')}"  # <-- returns page for page_disp
#             )

#         def update_example(highlighted, idx: int):
#             # grab the record
#             rec = dynamic_dataset.data[idx]

#             # reโ€tokenize from the raw text (same as do_validate)
#             orig_tokens = tokenize_text(rec["text"])

#             # realign the user's highlights back to those tokens
#             new_ner = align_spans_to_tokens(highlighted, orig_tokens)

#             # overwrite both token list and span list (and mark unโ€validated)
#             rec["tokenized_text"] = orig_tokens
#             rec["ner"]            = new_ner
#             rec["validated"]      = False

#             # reโ€render
#             return prepare_for_highlight(rec)

#         def align_spans_to_tokens(
#             highlighted: List[Dict[str, Union[str, None]]],
#             tokens: List[str]
#         ) -> List[Tuple[int,int,str]]:
#             """
#             Align each highlighted chunk to the next matching tokens in the list,
#             advancing a pointer so repeated tokens map in the order you clicked them.
#             """
#             spans = []
#             search_start = 0

#             for entry in highlighted:
#                 text  = entry["token"]
#                 label = entry.get("class_or_confidence") or entry.get("label") or entry.get("class")
#                 if not label:
#                     continue

#                 chunk_toks = tokenize_text(text)
#                 # scan only from the end of the last match
#                 for i in range(search_start, len(tokens) - len(chunk_toks) + 1):
#                     if tokens[i:i+len(chunk_toks)] == chunk_toks:
#                         spans.append((i, i + len(chunk_toks) - 1, label))
#                         search_start = i + len(chunk_toks)
#                         break
#                 else:
#                     print(f"โš ๏ธ Couldnโ€™t align chunk: {text!r}")

#             return spans

#         def do_validate(highlighted, idx: int):
#             # mark validated in memory
#             dynamic_dataset.validate()

#             # grab the record
#             rec = dynamic_dataset.data[idx]

#             # re-tokenize from the original text
#             orig_tokens = tokenize_text(rec["text"])

#             # realign the user's highlighted segments to those tokens
#             new_ner = align_spans_to_tokens(highlighted, orig_tokens)

#             # overwrite both token list and span list
#             rec["tokenized_text"] = orig_tokens
#             rec["ner"]            = new_ner

#             # persist
#             save_single_validation(idx, rec)

#             # re-render and show checkbox checked
#             return prepare_for_highlight(rec), True


#         def nav(fn):
#             rec  = fn()
#             segs = prepare_for_highlight(rec)
#             return segs, rec.get("validated", False), dynamic_dataset.current

#         demo.load(load_example, inputs=prog, outputs=[inp_box, status, prog])
#         apply_btn.click(
#             fn=update_example,
#             inputs=[inp_box, prog],     # pass both the highlights *and* the example idx
#             outputs=inp_box
#         )
#         #apply_btn.click(update_spans, inputs=inp_box, outputs=inp_box)
#         prev_btn.click(lambda: nav(dynamic_dataset.prev), inputs=None, outputs=[inp_box, status, prog])
#         validate_btn.click(do_validate, inputs=[inp_box, prog], outputs=[inp_box, status])
#         next_btn.click(lambda: nav(dynamic_dataset.next), inputs=None, outputs=[inp_box, status, prog])
#         skip_prev.click(lambda: nav(dynamic_dataset.jump_prev_unvalidated), inputs=None, outputs=[inp_box, status, prog])
#         skip_next.click(lambda: nav(dynamic_dataset.jump_next_unvalidated), inputs=None, outputs=[inp_box, status, prog])

#     return demo

def create_demo() -> gr.Blocks:
    data            = load_initial_data()
    validated_store = load_all_validations()

    # mark any pre-validated examples
    for idx in validated_store:
        if 0 <= idx < len(data):
            data[idx]["validated"] = True

    dynamic_dataset = DynamicDataset(data)

    def make_info(rec):
        fn = rec.get("filename", "โ€”")
        pg = rec.get("page", "โ€”")
        # Markdown with line break for Gradio
        return f"**File:** `{fn}`  \n**Page:** `{pg}`"

    def align_spans_to_tokens(
        highlighted: List[Dict[str, Union[str, None]]],
        tokens: List[str]
    ) -> List[Tuple[int, int, str]]:
        """
        Align each highlighted chunk to the next matching tokens in the list,
        advancing a pointer so repeated tokens map in the order you clicked them.
        """
        spans = []
        search_start = 0

        for entry in highlighted:
            text  = entry["token"]
            label = entry.get("class_or_confidence") or entry.get("label") or entry.get("class")
            if not label:
                continue

            chunk_toks = tokenize_text(text)
            # scan only from the end of the last match
            for i in range(search_start, len(tokens) - len(chunk_toks) + 1):
                if tokens[i:i + len(chunk_toks)] == chunk_toks:
                    spans.append((i, i + len(chunk_toks) - 1, label))
                    search_start = i + len(chunk_toks)
                    break
            else:
                print(f"โš ๏ธ Couldnโ€™t align chunk: {text!r}")

        return spans

    def load_example(idx):
        rec  = validated_store.get(idx, dynamic_dataset.example(idx))
        segs = prepare_for_highlight(rec)
        return segs, rec.get("validated", False), idx, make_info(rec)

    def update_example(highlighted, idx: int):
        rec = dynamic_dataset.data[idx]
        # reโ€tokenize
        orig_tokens = tokenize_text(rec["text"])
        # realign highlights
        new_ner = align_spans_to_tokens(highlighted, orig_tokens)
        # overwrite & mark un-validated
        rec["tokenized_text"] = orig_tokens
        rec["ner"]            = new_ner
        rec["validated"]      = False
        return prepare_for_highlight(rec), rec["validated"], idx, make_info(rec)

    def do_validate(highlighted, idx: int):
        # in-memory mark
        dynamic_dataset.validate()
        rec = dynamic_dataset.data[idx]
        orig_tokens = tokenize_text(rec["text"])
        new_ner = align_spans_to_tokens(highlighted, orig_tokens)
        rec["tokenized_text"] = orig_tokens
        rec["ner"]            = new_ner
        # persist to disk/store
        save_single_validation(idx, rec)
        return prepare_for_highlight(rec), True, make_info(rec)

    def nav(fn):
        rec  = fn()
        segs = prepare_for_highlight(rec)
        return segs, rec.get("validated", False), dynamic_dataset.current, make_info(rec)

    with gr.Blocks() as demo:
        prog        = gr.Slider(0, dynamic_dataset.len-1, value=0, step=1, label="Example #", interactive=False)
        inp_box     = gr.HighlightedText(label="Sentence", interactive=True)
        info_md     = gr.Markdown(label="Source")      # โ† shows filename & page
        status      = gr.Checkbox(label="Validated?", value=False, interactive=False)

        gr.Markdown(
            "[๐Ÿ“– Entity Tag Guide](https://huggingface.co/spaces/rafmacalaba/datause-annotation/blob/main/guidelines.md)"
        )

        with gr.Row():
            prev_btn    = gr.Button("โ—€๏ธ Previous")
            apply_btn   = gr.Button("๐Ÿ“ Apply Changes")
            next_btn    = gr.Button("Next โ–ถ๏ธ")

        with gr.Row():
            skip_prev     = gr.Button("โฎ๏ธ Prev Unvalidated")
            validate_btn = gr.Button("โœ… Validate")
            skip_next     = gr.Button("โญ๏ธ Next Unvalidated")

        # initial load
        demo.load(load_example, inputs=prog, outputs=[inp_box, status, prog, info_md])

        # wire up actions (all now also update info_md)
        apply_btn.click(update_example, inputs=[inp_box, prog], outputs=[inp_box, status, prog, info_md])
        prev_btn.click(lambda: nav(dynamic_dataset.prev), inputs=None, outputs=[inp_box, status, prog, info_md])
        next_btn.click(lambda: nav(dynamic_dataset.next), inputs=None, outputs=[inp_box, status, prog, info_md])
        skip_prev.click(lambda: nav(dynamic_dataset.jump_prev_unvalidated), inputs=None, outputs=[inp_box, status, prog, info_md])
        skip_next.click(lambda: nav(dynamic_dataset.jump_next_unvalidated), inputs=None, outputs=[inp_box, status, prog, info_md])
        validate_btn.click(do_validate, inputs=[inp_box, prog], outputs=[inp_box, status, info_md])

    return demo

if __name__ == "__main__":
    demo = create_demo()
    demo.launch(share=True, inline=True, debug=True)