File size: 16,748 Bytes
626eca0
 
 
 
 
9ee75f8
 
 
 
 
 
626eca0
 
 
 
 
3a2d753
 
 
 
 
626eca0
 
 
 
 
 
9ee75f8
 
 
 
 
 
 
626eca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5937143
626eca0
5937143
626eca0
 
 
 
 
 
 
 
 
 
 
 
 
9ee75f8
626eca0
 
9ee75f8
 
626eca0
 
9ee75f8
 
626eca0
8745a5f
 
 
 
9ee75f8
 
 
 
 
 
8745a5f
9ee75f8
8745a5f
1103011
626eca0
 
 
 
 
9ee75f8
 
 
 
 
 
 
 
 
 
 
0b3d36f
 
 
 
 
 
 
 
 
 
 
9ee75f8
 
2e3f491
9ee75f8
 
 
 
7f7fc6a
 
 
 
 
 
 
 
 
 
 
 
 
 
1103011
 
9ee75f8
c047b4f
 
f0bf7d6
c047b4f
 
 
0b3d36f
846aa97
 
c047b4f
 
 
 
0b3d36f
 
846aa97
 
0b3d36f
 
 
 
 
846aa97
 
c047b4f
 
 
0b3d36f
 
846aa97
 
0b3d36f
 
 
c047b4f
129b641
9ee75f8
 
1aaa580
9ee75f8
ecd29a7
1103011
626eca0
 
9ee75f8
d92aa30
9ee75f8
 
 
626eca0
9ee75f8
626eca0
 
 
 
 
 
 
b866469
 
 
f13cbf8
b866469
 
f13cbf8
1aff14a
 
f13cbf8
 
a9b6a2a
b866469
 
 
f13cbf8
b866469
 
 
1aff14a
b866469
626eca0
16f0e9a
0ff3b5f
3a2d753
b866469
 
 
 
0ff3b5f
626eca0
 
 
 
 
d92aa30
626eca0
 
 
 
 
 
c047b4f
 
 
0b3d36f
595b5fb
c047b4f
0b3d36f
b80d07a
c047b4f
c6aa454
0b3d36f
 
 
8c34b62
0b3d36f
 
626eca0
 
 
1a9a3a5
626eca0
fb04667
626eca0
 
 
 
 
 
9ee75f8
 
626eca0
 
 
 
 
 
 
1103011
 
c047b4f
626eca0
e3700f2
 
 
 
 
626eca0
 
1fbbd06
0b3d36f
c047b4f
 
0b3d36f
c94e545
4c778a8
 
 
0b3d36f
c047b4f
626eca0
 
 
 
b95324c
0b3d36f
 
 
 
9ee75f8
1fbbd06
9ee75f8
1fbbd06
 
 
 
 
 
 
 
 
70a5d22
 
 
fd0f289
70a5d22
 
 
fd0f289
70a5d22
e3700f2
70a5d22
e3700f2
6806e2f
e3700f2
b2fefbd
7f7fc6a
b2fefbd
 
 
16f0e9a
7f7fc6a
b2fefbd
ffea8a1
16f0e9a
 
 
 
 
626eca0
 
16f0e9a
 
675daa7
6806e2f
 
 
16f0e9a
6806e2f
 
 
 
 
 
16f0e9a
6806e2f
16f0e9a
 
6806e2f
bbfcd2c
626eca0
 
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import os
import re
import time
from pathlib import Path

from relik.retriever import GoldenRetriever

from relik.retriever.indexers.inmemory import InMemoryDocumentIndex
from relik.retriever.indexers.document import DocumentStore
from relik.retriever import GoldenRetriever
from relik.reader.pytorch_modules.span import RelikReaderForSpanExtraction
import requests
import streamlit as st
from spacy import displacy
from streamlit_extras.badges import badge
from streamlit_extras.stylable_container import stylable_container
import logging

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
logger = logging.getLogger()

# RELIK = os.getenv("RELIK", "localhost:8000/api/entities")

import random

from relik.inference.annotator import Relik
from relik.inference.data.objects import (
    AnnotationType,
    RelikOutput,
    Span,
    TaskType,
    Triples,
)

def get_random_color(ents):
    colors = {}
    random_colors = generate_pastel_colors(len(ents))
    for ent in ents:
        colors[ent] = random_colors.pop(random.randint(0, len(random_colors) - 1))
    return colors


def floatrange(start, stop, steps):
    if int(steps) == 1:
        return [stop]
    return [
        start + float(i) * (stop - start) / (float(steps) - 1) for i in range(steps)
    ]


def hsl_to_rgb(h, s, l):
    def hue_2_rgb(v1, v2, v_h):
        while v_h < 0.0:
            v_h += 1.0
        while v_h > 1.0:
            v_h -= 1.0
        if 6 * v_h < 1.0:
            return v1 + (v2 - v1) * 6.0 * v_h
        if 2 * v_h < 1.0:
            return v2
        if 3 * v_h < 2.0:
            return v1 + (v2 - v1) * ((2.0 / 3.0) - v_h) * 6.0
        return v1

    # if not (0 <= s <= 1): raise ValueError, "s (saturation) parameter must be between 0 and 1."
    # if not (0 <= l <= 1): raise ValueError, "l (lightness) parameter must be between 0 and 1."

    r, b, g = (l * 255,) * 3
    if s != 0.0:
        if l < 0.5:
            var_2 = l * (1.0 + s)
        else:
            var_2 = (l + s) - (s * l)
        var_1 = 2.0 * l - var_2
        r = 255 * hue_2_rgb(var_1, var_2, h + (1.0 / 3.0))
        g = 255 * hue_2_rgb(var_1, var_2, h)
        b = 255 * hue_2_rgb(var_1, var_2, h - (1.0 / 3.0))

    return int(round(r)), int(round(g)), int(round(b))


def generate_pastel_colors(n):
    """Return different pastel colours.

    Input:
        n (integer) : The number of colors to return

    Output:
        A list of colors in HTML notation (eg.['#cce0ff', '#ffcccc', '#ccffe0', '#f5ccff', '#f5ffcc'])

    Example:
        >>> print generate_pastel_colors(5)
        ['#cce0ff', '#f5ccff', '#ffcccc', '#f5ffcc', '#ccffe0']
    """
    if n == 0:
        return []

    # To generate colors, we use the HSL colorspace (see http://en.wikipedia.org/wiki/HSL_color_space)
    start_hue = 0.0  # 0=red    1/3=0.333=green   2/3=0.666=blue
    saturation = 1.0
    lightness = 0.9
    # We take points around the chromatic circle (hue):
    # (Note: we generate n+1 colors, then drop the last one ([:-1]) because
    # it equals the first one (hue 0 = hue 1))
    return [
        "#%02x%02x%02x" % hsl_to_rgb(hue, saturation, lightness)
        for hue in floatrange(start_hue, start_hue + 1, n + 1)
    ][:-1]


def set_sidebar(css):
    with st.sidebar:
        st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)
        st.image(
            "https://upload.wikimedia.org/wikipedia/commons/8/87/The_World_Bank_logo.svg",
            use_column_width=True,
        )
        st.markdown("### World Bank")
        st.markdown("### DIME")

def get_el_annotations(response):
    i_link_wrapper = "<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css'><a href='https://developmentevidence.3ieimpact.org/taxonomy-search-detail/intervention/disaggregated-intervention/{}' style='color: #414141'> <span style='font-size: 1.0em; font-family: monospace'> Intervention {}</span></a>"
    o_link_wrapper = "<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css'><a href='https://developmentevidence.3ieimpact.org/taxonomy-search-detail/intervention/disaggregated-outcome/{}' style='color: #414141'><span style='font-size: 1.0em; font-family: monospace'> Outcome: {}</span></a>"
    # swap labels key with ents
    ents = [
        {
            "start": l.start,
            "end": l.end,
            "label": i_link_wrapper.format(l.label[0].upper() + l.label[1:].replace("/", "%2").replace(" ", "%20").replace("&","%26"), l.label),
        } if io_map[l.label] == "intervention" else 
        {
            "start": l.start,
            "end": l.end,
            "label": o_link_wrapper.format(l.label[0].upper() + l.label[1:].replace("/", "%2").replace(" ", "%20").replace("&","%26"), l.label), 
        }
        for l in response.spans
    ]
    dict_of_ents = {"text": response.text, "ents": ents}
    label_in_text = set(l["label"] for l in dict_of_ents["ents"])
    options = {"ents": label_in_text, "colors": get_random_color(label_in_text)}
    return dict_of_ents, options



def get_retriever_annotations(response):
    el_link_wrapper = "<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css'><a href='https://en.wikipedia.org/wiki/{}' style='color: #414141'><i class='fa-brands fa-wikipedia-w fa-xs'></i> <span style='font-size: 1.0em; font-family: monospace'> {}</span></a>"
    # swap labels key with ents
    ents = [l.text
        for l in response.candidates[TaskType.SPAN]
    ]
    dict_of_ents = {"text": response.text, "ents": ents}
    label_in_text = set(l for l in dict_of_ents["ents"])
    options = {"ents": label_in_text, "colors": get_random_color(label_in_text)}
    return dict_of_ents, options
    

def get_retriever_annotations_candidates(text, ents):
    el_link_wrapper = "<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css'><a href='https://en.wikipedia.org/wiki/{}' style='color: #414141'><i class='fa-brands fa-wikipedia-w fa-xs'></i> <span style='font-size: 1.0em; font-family: monospace'> {}</span></a>"
    # swap labels key with ents
    dict_of_ents = {"text": text, "ents": ents}
    label_in_text = set(l for l in dict_of_ents["ents"])
    options = {"ents": label_in_text, "colors": get_random_color(label_in_text)}
    return dict_of_ents, options

    
import json
io_map = {}
with open("/home/user/app/models/retriever/document_index/documents.jsonl", "r") as r:
    for line in r:
        element = json.loads(line)
        io_map[element["text"]] = element["metadata"]["type"]

            
import json
db_set = set()
with open("models/retriever/intervention/gpt/db/document_index/documents.jsonl", "r") as r:
    for line in r:
        element = json.loads(line)
        db_set.add(element["text"])

with open("models/retriever/outcome/gpt/db/document_index/documents.jsonl", "r") as r:
    for line in r:
        element = json.loads(line)
        db_set.add(element["text"])


@st.cache_resource()
def load_model():

    retriever_question = GoldenRetriever(
        question_encoder="/home/user/app/models/retriever/question_encoder",
        document_index="/home/user/app/models/retriever/document_index/questions"

    )

    retriever_intervention_gpt_taxonomy = GoldenRetriever(
        question_encoder="models/retriever/intervention/gpt+llama/taxonomy/question_encoder",
        document_index="models/retriever/intervention/gpt+llama/taxonomy/document_index"

    )


    
    retriever_intervention_gpt_db = GoldenRetriever(
        question_encoder="models/retriever/intervention/gpt+llama/db/question_encoder",
        document_index="models/retriever/intervention/gpt+llama/db/document_index"

    )

    
    retriever_outcome_gpt_taxonomy = GoldenRetriever(
        question_encoder="models/retriever/outcome/gpt+llama/taxonomy/question_encoder",
        document_index="models/retriever/outcome/gpt+llama/taxonomy/document_index"

    )

    
    retriever_outcome_gpt_db = GoldenRetriever(
        question_encoder="models/retriever/outcome/gpt+llama/db/question_encoder",
        document_index="models/retriever/outcome/gpt+llama/db/document_index"

    )


    reader = RelikReaderForSpanExtraction("/home/user/app/models/small-extended-large-batch",
                                        dataset_kwargs={"use_nme": True})

    relik_question = Relik(reader=reader, retriever=retriever_question, window_size="none", top_k=100, task="span", device="cpu", document_index_device="cpu")

    return [relik_question, retriever_intervention_gpt_db, retriever_outcome_gpt_db, retriever_intervention_gpt_taxonomy, retriever_outcome_gpt_taxonomy]

def set_intro(css):
    # intro

    st.markdown("# ImpactAI")
    st.image(
    "http://35.237.102.64/public/logo.png",
)
    st.markdown(
        "### 3ie taxonomy level 4 Intervention/Outcome candidate retriever with Entity Linking"
    )
    # st.markdown(
    #     "This is a front-end for the paper [Universal Semantic Annotator: the First Unified API "
    #     "for WSD, SRL and Semantic Parsing](https://www.researchgate.net/publication/360671045_Universal_Semantic_Annotator_the_First_Unified_API_for_WSD_SRL_and_Semantic_Parsing), which will be presented at LREC 2022 by "
    #     "[Riccardo Orlando](https://riccorl.github.io), [Simone Conia](https://c-simone.github.io/), "
    #     "[Stefano Faralli](https://corsidilaurea.uniroma1.it/it/users/stefanofaralliuniroma1it), and [Roberto Navigli](https://www.diag.uniroma1.it/navigli/)."
    # )
    
from datetime import datetime
from pathlib import Path
from huggingface_hub import HfApi, CommitScheduler
from uuid import uuid4

# Access token from environment variable
# api = HfApi()
# api.set_access_token(os.getenv("HF_TOKEN"))

JSON_DATASET_DIR = Path("json_demo_selected_io")
JSON_DATASET_DIR.mkdir(parents=True, exist_ok=True)
JSON_DATASET_PATH = JSON_DATASET_DIR / f"train-{uuid4()}.json"

scheduler = CommitScheduler(
    repo_id="demo-retriever",
    repo_type="dataset",
    folder_path=JSON_DATASET_DIR,
    path_in_repo="data",
    token=os.getenv("HF_TOKEN")
)


def write_candidates_to_file(text, candidates, selected_candidates):
    logger.info(f"Text: {text}\tCandidates: {str(candidates)}\tSelected Candidates: {str(selected_candidates)}\n")
    with scheduler.lock:
        with JSON_DATASET_PATH.open("a") as f:
            json.dump({"text": text, "Candidates": [candidate for candidate in candidates], "Selected Candidates": [candidate for candidate in selected_candidates], "datetime": datetime.now().isoformat()}, f)
            f.write("\n")

def run_client():
    with open(Path(__file__).parent / "style.css") as f:
        css = f.read()

    st.set_page_config(
        page_title="ImpactAI",
        page_icon="🦮",
        layout="wide",
    )
    set_sidebar(css)
    set_intro(css)

        # Radio button selection
    analysis_type = st.radio(
        "Choose analysis type:",
        options=["Retriever", "Entity Linking"],
        index=0  # Default to 'question'
    )

    selection_options = ["DB Intervention", "DB Outcome", "Taxonomy Intervention", "Taxonomy Outcome", "Top-k DB in Taxonomy Intervention", "Top-k DB in Taxonmy Outcome", ]
    
    if analysis_type == "Retriever":
        # Selection list using selectbox
        selection_list = st.selectbox(
            "Select an option:",
            options=selection_options
        )

    # text input
    text = st.text_area(
        "Enter Text Below:",
        value="",
        height=200,
        max_chars=1500,
    )

    with stylable_container(
        key="annotate_button",
        css_styles="""
            button {
                background-color: #a8ebff;
                color: black;
                border-radius: 25px;
            }
            """,
    ):
        submit = st.button("Annotate")
    # submit = st.button("Run")

    if "relik_model" not in st.session_state.keys():
        st.session_state["relik_model"] = load_model()
    relik_model = st.session_state["relik_model"][0]

    if 'candidates' not in st.session_state:
        st.session_state['candidates'] = []
    if 'selected_candidates' not in st.session_state:
        st.session_state['selected_candidates'] = []

    # ReLik API call
    if submit:

        if analysis_type == "Entity Linking":
            relik_model = st.session_state["relik_model"][0]
        else:
            model_idx = selection_options.index(selection_list)
            if selection_list == "Top-k DB in Taxonomy Intervention" or selection_list == "Top-k DB in Taxonmy Outcome":
                relik_model = st.session_state["relik_model"][model_idx-1]
            else:
                relik_model = st.session_state["relik_model"][model_idx+1]
            
            
        text = text.strip()
        if text:
            st.markdown("####")
            with st.spinner(text="In progress"):
                if analysis_type == "Entity Linking":
                    response = relik_model(text)
                    
                    dict_of_ents, options = get_el_annotations(response=response)
                    dict_of_ents_candidates, options_candidates = get_retriever_annotations(response=response)

                    st.markdown("#### Entity Linking")

                    display = displacy.render(
                        dict_of_ents, manual=True, style="ent", options=options
                    )
    
    
                    display = display.replace("\n", " ")
    
                    # heurstic, prevents split of annotation decorations
                    display = display.replace("border-radius: 0.35em;", "border-radius: 0.35em; white-space: nowrap;")
    
                    with st.container():
                        st.write(display, unsafe_allow_html=True)
                    candidate_text = "".join(f"<li style='color: black;'>Intervention: {candidate}</li>" if io_map[candidate] == "intervention" else f"<li style='color: black;'>Outcome: {candidate}</li>" for candidate in dict_of_ents_candidates["ents"][0:10])
                    text = """
                    <h2 style='color: black;'>Possible Candidates:</h2>
                    <ul style='color: black;'>
                    """ + candidate_text + "</ul>"
    
                    st.markdown(text, unsafe_allow_html=True)    
                else:
                    if selection_list == "Top-k DB in Taxonomy Intervention" or selection_list == "Top-k DB in Taxonomy Outcome":
                        response = relik_model.retrieve(text, k=50, batch_size=400, progress_bar=False)
                        candidates_text = [pred.document.text for pred in response[0] if pred.document.text in db_set]
                        candidates_text = candidates_text[:10]
                    else:
                        response = relik_model.retrieve(text, k=20, batch_size=400, progress_bar=False)
                        candidates_text = [pred.document.text for pred in response[0]] 
                        
        
                    if candidates_text:
                        st.session_state.candidates = candidates_text

                    else:
                        st.session_state.candidates = []
                        st.session_state.selected_candidates = []
                        st.markdown("<h2 style='color: black;'>No Candidates Found</h2>", unsafe_allow_html=True)
         
        else:
            st.error("Please enter some text.")
    
    # Ensure the candidates list is displayed even after interactions
    if st.session_state.candidates and analysis_type != "Entity Linking":
        dict_of_ents_candidates, options_candidates = get_retriever_annotations_candidates(text, st.session_state.candidates)
        st.markdown("<h2 style='color: black;'>Possible Candidates:</h2>", unsafe_allow_html=True)
        for candidate in dict_of_ents_candidates["ents"]:
            checked = candidate in st.session_state.selected_candidates
            if st.checkbox(candidate, key=candidate, value=checked):
                if candidate not in st.session_state.selected_candidates:
                    st.session_state.selected_candidates.append(candidate)
            else:
                if candidate in st.session_state.selected_candidates:
                    st.session_state.selected_candidates.remove(candidate)
    
        if st.button("Save Selected Candidates"):
            if write_candidates_to_file(text, dict_of_ents_candidates["ents"], st.session_state.selected_candidates):
                st.success("Selected candidates have been saved to file.")

 
if __name__ == "__main__":
    run_client()