File size: 19,276 Bytes
78d7e62
 
 
 
352825c
78d7e62
 
 
 
 
 
 
 
 
 
352825c
78d7e62
c7838e5
352825c
 
 
 
78d7e62
 
352825c
78d7e62
 
c7838e5
0d986e2
 
 
 
 
 
 
 
 
 
 
 
 
59ca737
c7838e5
78d7e62
352825c
 
78d7e62
 
 
352825c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352825c
78d7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7838e5
78d7e62
2a2cc4e
352825c
 
 
2a2cc4e
352825c
2a2cc4e
78d7e62
2a2cc4e
352825c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a2cc4e
352825c
 
 
 
59ca737
2a2cc4e
 
 
352825c
 
 
 
 
 
 
 
 
2a2cc4e
 
 
 
 
 
 
 
 
 
 
78d7e62
 
 
352825c
 
78d7e62
352825c
 
 
 
78d7e62
 
 
 
 
 
 
 
352825c
2a2cc4e
 
e3d832d
2a2cc4e
e3d832d
2a2cc4e
328779b
78d7e62
 
 
 
 
 
 
352825c
 
 
 
78d7e62
0d986e2
78d7e62
 
 
352825c
 
 
 
 
 
 
c7838e5
 
 
 
 
 
 
 
 
2a2cc4e
352825c
 
 
 
 
 
 
c7838e5
352825c
 
 
 
 
 
c7838e5
352825c
 
c7838e5
 
352825c
 
2a2cc4e
 
352825c
2a2cc4e
 
 
 
 
 
 
352825c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a2cc4e
 
 
c7838e5
352825c
 
 
78d7e62
352825c
 
 
78d7e62
352825c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d7e62
352825c
 
 
 
 
 
78d7e62
352825c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d7e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

"""Streamlit app for Presidio + Privy-trained PII models."""

import spacy
import en_spacy_pii_distilbert
from spacy_recognizer import CustomSpacyRecognizer
from presidio_analyzer.nlp_engine import NlpEngineProvider
from presidio_anonymizer import AnonymizerEngine
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry
import pandas as pd
from annotated_text import annotated_text
from json import JSONEncoder
import json
import warnings
import streamlit as st
# from streamlit import logger as _logger
import os
import csv
import json
from chatgpt_wrapper import ChatGPT
import time

os.environ["TOKENIZERS_PARALLELISM"] = "false"
warnings.filterwarnings('ignore')

# from flair_recognizer import FlairRecognizer

def load_data(file_location):
    unpacked_string_data = []
    unpacked_url_data = []
    unpacked_json_data = []
    # Read the data back from the CSV file and unpack it
    with open(file_location, mode='r') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            unpacked_string_data.append(row[0])
            unpacked_url_data.append(row[1])
            unpacked_json_data.append(json.loads(row[2]))
            # print("Unpacked string data:", unpacked_string_data)
            # print("Unpacked url data:", unpacked_url_data)
            # print("Unpacked JSON data:", unpacked_json_data)
    return unpacked_string_data, dict(zip(unpacked_string_data, unpacked_json_data))

# Helper methods
@st.cache_resource #(allow_output_mutation=True)
def analyzer_engine(use_local=None):
    """Return AnalyzerEngine."""

    spacy_recognizer = CustomSpacyRecognizer()
    if use_local:
        # !pip
        # install
        # https: // huggingface.co / beki / en_spacy_pii_distilbert / resolve / main / en_spacy_pii_distilbert - any - py3 - none - any.whl

        # Using spacy.load().
        nlp = spacy.load("en_spacy_pii_distilbert")

        # Importing as module.
        nlp_engine = en_spacy_pii_distilbert.load()
    else:
        configuration = {
            # print("ENALBEE MODELES")
            "nlp_engine_name": "spacy",
            "models": [
                {"lang_code": "en", "model_name": "en_spacy_pii_distilbert"}],
        }

        # Create NLP engine based on configuration
        provider = NlpEngineProvider(nlp_configuration=configuration)
        nlp_engine = provider.create_engine()

    registry = RecognizerRegistry()
    # add rule-based recognizers
    registry.load_predefined_recognizers(nlp_engine=nlp_engine)
    registry.add_recognizer(spacy_recognizer)
    # remove the nlp engine we passed, to use custom label mappings
    registry.remove_recognizer("SpacyRecognizer")

    analyzer = AnalyzerEngine(nlp_engine=nlp_engine,
                              registry=registry, supported_languages=["en"])

    # uncomment for flair-based NLP recognizer
    # flair_recognizer = FlairRecognizer()
    # registry.load_predefined_recognizers()
    # registry.add_recognizer(flair_recognizer)
    # analyzer = AnalyzerEngine(registry=registry, supported_languages=["en"])
    return analyzer


@st.cache_resource#(allow_output_mutation=True)
def anonymizer_engine():
    """Return AnonymizerEngine."""
    return AnonymizerEngine()


def get_supported_entities():
    """Return supported entities from the Analyzer Engine."""
    return analyzer_engine().get_supported_entities()


def analyze(**kwargs):
    """Analyze input using Analyzer engine and input arguments (kwargs)."""
    if "entities" not in kwargs or "All" in kwargs["entities"]:
        kwargs["entities"] = None
    return analyzer_engine().analyze(**kwargs)


def anonymize(text, analyze_results):
    """Anonymize identified input using Presidio Abonymizer."""
    if not text:
        return
    res = anonymizer_engine().anonymize(text, analyze_results)
    return res.text


def annotate(text, st_analyze_results, st_entities):
    tokens = []
    # sort by start index
    results = sorted(st_analyze_results, key=lambda x: x.start)
    for i, res in enumerate(results):
        if i == 0:
            tokens.append(text[:res.start])

        # append entity text and entity type
        tokens.append((text[res.start: res.end], res.entity_type))

        # if another entity coming i.e. we're not at the last results element, add text up to next entity
        if i != len(results) - 1:
            tokens.append(text[res.end:results[i+1].start])
        # if no more entities coming, add all remaining text
        else:
            tokens.append(text[res.end:])
    return tokens


st.set_page_config(page_title="Bitahoy demo", layout="wide")

# Side bar -------------------------------------------
# add picture with
st.sidebar.image("structured-data-anonymizer/assets/bitahoy-logo.png", width=200)

st.sidebar.markdown(
"""Detect and anonymize PII in structured text such as protocol traces (JSON, SQL, XML etc.)"""
)

# dropdown
# titles, json_dict = load_data("structured-data-anonymizer/assets/data_s_short.csv")
# option_list = titles
# option = st.sidebar.selectbox(
#     'Choose an existing structured input?',
#     option_list)

# dropdown df
# Title,Url,Dict,Prompt,Result
dataframe = pd.read_csv("structured-data-anonymizer/assets/df_data_short.csv")
# select only the third column of the data frame
# select only first column of the data frame
titles = dataframe['Title']
# conver it to a list
titles = titles.values.tolist()
# print(dataframe.iloc[0])
# select first row from dataframe
option_list = titles
# for i in option_list:
#     if (dataframe[dataframe['Title'] == i]['Result'].empty):
#         i = i + "*"
# print(option_list)
option = st.sidebar.selectbox(
    'Choose an existing structured input?',
    option_list)

# # st.sidebar.write('You selected:', option)
# json_dict = dataframe['Dict']
# json_dict = json_dict.values.tolist()
sidebar_text = 'Use small icon-button in right corner to copy input to clipboard'
st.sidebar.write(sidebar_text)
json_dict_option = dataframe[dataframe['Title'] == option]['Dict'].values[0]

st.sidebar.code (json_dict_option)

#romans complex dropdown
# st.checkbox("Enable/Disable input of existing data", key="disabled")
#
#     option = st.selectbox(
#         "Choose an existing structured input?",
#         option_list,
#         # label_visibility=st.session_state.visibility,
#         disabled=st.session_state.disabled,
#     )
#     st.write('You selected:', option)

st_entities = st.sidebar.multiselect(
    label="Which entities to look for?",
    options=get_supported_entities(),
    default=['PHONE_NUMBER', 'CREDIT_CARD', 'DATE_TIME', 'MEDICAL_LICENSE', 'US_BANK_NUMBER', 'IP_ADDRESS', 'IBAN_CODE', 'LOCATION', 'EMAIL_ADDRESS']
#     default=list(get_supported_entities()),
)
# ['PHONE_NUMBER', 'PERSON', 'CRYPTO', 'AU_TFN', 'ORGANIZATION', 'UK_NHS', 'CREDIT_CARD', 'US_DRIVER_LICENSE',
# 'US_SSN', 'URL', 'AU_MEDICARE', 'DATE_TIME', 'NRP', 'US_PASSPORT', 'MEDICAL_LICENSE', 'US_BANK_NUMBER',
# 'IP_ADDRESS', 'IBAN_CODE', 'US_ITIN', 'AU_ACN', 'SG_NRIC_FIN', 'LOCATION', 'AU_ABN', 'EMAIL_ADDRESS']
# st.sidebar.text(list(get_supported_entities()))

st_threshold = st.sidebar.slider(
    label="Acceptance threshold", min_value=0.0, max_value=1.0, value=0.35
)

st_return_decision_process = st.sidebar.checkbox(
    "Add analysis explanations in json")

api_togg = st.sidebar.checkbox(label='API toggle', value=True)

# vertical space
st.sidebar.text("")
# vertical space
st.sidebar.text("")


st.sidebar.info(
    "Privy is an open source framework for synthetic data generation in protocol trace formats (json, sql, html etc). Presidio is an open source framework for PII detection and anonymization. "
    "For more info visit [privy](https://github.com/pixie-io/pixie/tree/main/src/datagen/pii/privy) and [aka.ms/presidio](https://aka.ms/presidio)"
)


# Main panel
if 'first_load' not in st.session_state:
    st.session_state['first_load'] = True


analyzer_load_state = st.info(
    "Starting analyzer and loading model...")
engine = analyzer_engine()
analyzer_load_state.empty()

# Initialization
# if 'bot' not in st.session_state:
#     st.sidebar.text("init...")
#     st.session_state['bot'] = ChatGPT()
#     init_prompt = "i'd like you to act like a snobby AI and tell me what you think of my structured data"
#     init_answer = st.session_state['bot'].ask(init_prompt)

# col?
# Store the initial value of widgets in session state
if "visibility" not in st.session_state:
    st.session_state.visibility = "visible"
    st.session_state.disabled = False

col1, col2 = st.columns(2)

with col1:
    st.subheader("Input")

    sys_name = st.text_area(
        label="Name of the system in question",
        value=option,
        height=1,
    )

    st_text = st.text_area(
        label= "Structured text used as input",
        value = """{ "@timestamp":"2022-06-08T16:54:58.849Z", "alienOTX":{ "firewall":{ "action":"Deny", "category":"AlienVaultFirewallNetworkRule", "icmp":{ "request":{ "code":"8" } }, "operation_name":"AzureFirewallNetworkRuleLog", "path": "http://www.example.com/ab001.zip", }, "resource":{ "group":"TEST-FW-RG", "id":"/SUBSCRIPTIONS/23103928-B2CF-472A-8CDB-FR7630006000011234567890189/RESOURCEGROUPS/TEST-FW-RG/PROVIDERS/MICROSOFT.NETWORK/AZUREFIREWALLS/TEST-FW01", "address":"172.24.0.4", "provider":"SonicWall", "number":"040084913373", "sentto": "[email protected]" }, "subscription_id":"4012888888881881-23103928-B2CF-472A-8CDB-0146E2849129" } }""",
        # value="SELECT shipping FROM users WHERE shipping = '201 Thayer St Providence RI 02912'"
        # "\n\n"
        # "{user: Willie Porter, ip: 192.168.2.80, email: [email protected]}",
        height=300,
    )
    button = st.button("Detect and replace PII")
    st.text("""""")

with col2:
    st.subheader("Analyzed results with detected entities highlighted")
    # st.text("Output text with detected entities highlighted")
    with st.spinner("Analyzing..."):
        if button or st.session_state.first_load:
            option = sys_name
            st_analyze_results = analyze(
                text=st_text,
                entities=st_entities,
                language="en",
                score_threshold=st_threshold,
                return_decision_process=st_return_decision_process,
            )
            # """
            # Ugly hack that checks if last 2 chars as Z" and changes the end of the last entity to -1
            # This is done to prevent the anotation to inlcude the quotes for the date4 and breka the json donwtheroad
            # ### TODO: make this less hacky?
            # """
            for i in st_analyze_results:
                # st.write(i)
                # st.write(st_text[i.end - 2:i.end])
                if st_text[i.end-2:i.end] == 'Z"':# and i.type == "DATE_TIME":
                    i.end = i.end-1
                    continue
                if st_text[i.end-2:i.end] == "Z'":# and i.type == "DATE_TIME":
                    i.end = i.end-1
                    continue
                # if "'" in st_text[i.start:i.end]:
                #     st_analyze_results.remove(i)
                #     continue
                # if "," in st_text[i.start:i.end]:
                #     st_analyze_results.remove(i)
                #     continue


            annotated_tokens = annotate(st_text, st_analyze_results, st_entities)
            # annotated_tokens
            annotated_text(*annotated_tokens)

    # vertical space
    st.text("")
    st.text("")

    with st.expander("Show results with replaced PII and detailed results"):
        # st.subheader("Final results with tokens instead if PII")
        # vertical space

        if button or st.session_state.first_load:
            st_anonymize_results = anonymize(st_text, st_analyze_results)
            st.write(st_anonymize_results)
            # st.write(st_anonymize_results)
            # try:
            #     # st_anonymize_results = ast.literal_eval(st_anonymize_results)
            #     st.json(st_anonymize_results) #.replace("'", '"'))
            # except Json Parse Error as e:
            #     st.write(st_anonymize_results)
        # vertical space
        st.text("")
        st.subheader("Detailed Findings")
        if st_analyze_results:
            res_dicts = [r.to_dict() for r in st_analyze_results]
            for d in res_dicts:
                d['Value'] = st_text[d['start']:d['end']]
            df = pd.DataFrame.from_records(res_dicts)
            df = df[["entity_type", "Value", "score", "start", "end"]].rename(
                {
                    "entity_type": "Entity type",
                    "start": "Start",
                    "end": "End",
                    "score": "Confidence",
                },
                axis=1,
            )

            st.dataframe(df, width=1000)  # , height=500)
        else:
            st.text("No findings")

# st_analyze_results
# end of col

# After the columns

col5, col6 = st.columns(2)
prompt = "Write a summary for a {} event log, based on the given structured JSON input. Start with an executive summary with a short general description of what is a {}, and then focus on the Key Findings, Monitoring Summary,  Incident Summary, Threat Summary and Recommendations. Replace any random " \
            "strings and tokens in angular-brackets with an approximations to make it more human readable: \"{}\" ".format(
        option, option,
        st_anonymize_results)

with col5:
    st.subheader("Formatting")

    button_create = st.button("Create summary")
    st.markdown(
        "Start with an executive summary and describe what system the log came from, then focus on the Key Findings, Monitoring Summary,  Incident Summary, Threat Summary and Recommendations.")
    st.text("""""")

    with st.expander("Additional inputs"):
        st_prompt = st.text_area(
            label="Tokenized input with the formatted prompt",
            value=prompt,
            height=200,
        )

        write_results = ""
        st_output = st.text_area(
            label="Record results for later use",
            value=write_results,
            height=100,
        )
        button_save = st.button("Save summary to file?")
        st.text("""""")

        placeholder_table = st.empty()
        placeholder_table.write("")

        init_prompt = """I want you to act as a cyber security analyst expert. I will provide some specific information about concrete incidents, and it will be your job to come up with a coherent summery of the event, described in this log I give you. You can give a short description and then give strategies for protecting this system from malicious actors, based on the incident data I give you. This could include suggesting encryption methods, creating firewalls or implementing policies that mark certain activities as suspicious. Your summery would be used by decision makers to manage the situation, therefore make informed predictions and formulate them precisely in relation to the event I present to you."""
        st_init_prompt = st.text_area(
            label="Initial promopt to focus model",
            value=init_prompt,
            height=100,
        )
        button_reset = st.button("Reset model setup")

import random

with col6:
    st.subheader("Output incident summary")

# effect button_create(button2)
# with st.spinner("button_create..."):
if button_create:
    # load existing promp and results
    if (not api_togg):
        saved_prompt = dataframe[dataframe['Title'] == option]['Prompt'].values[0]
        saved_result = dataframe[dataframe['Title'] == option]['Result'].values[0]
    else:
        saved_prompt = ""
        saved_result = ""
    # check if match to current prompt
    # if re.sub(r"[\n\t\s]*", "", saved_prompt) == re.sub(r"[\n\t\s]*", "", st_prompt):
    md_results = ""
    with col6:
        x = st.empty()
        x.markdown("")

    # check if saved_prompt is not of a type float
    if (not isinstance(saved_prompt, float)) and (not api_togg):
        # st.write(saved_prompt)
        with col6:
            with st.spinner('Fetching results...'):
                time.sleep(random.uniform(2.1, 5.8))
                # st.write("Prompt already queried in the past, loading result from database")
                md_results = saved_result
                words = md_results.split()
                num_words = len(words)
                chunk_size = int(random.uniform(2, 6))
                str_placeholder = ""

                for i in range(0, num_words, chunk_size):
                    chunk = ' '.join(words[i:i + chunk_size])
                    str_placeholder = str_placeholder + " " + chunk
                    x.markdown(str_placeholder)
                    # x.markdown(chunk)
                    time.sleep(random.uniform(0.1, 0.6))
                x.markdown(saved_result)
    else:
        # st.write("New prompt, need GPT")
        with col6:
            with st.spinner('Generating, please wait...'):
                bot = ChatGPT()
                # init_answer = bot.ask(init_prompt)

                init_points = ""
                for chunk in bot.ask_stream(init_prompt):
                    init_points = init_points + "."
                    x.markdown(init_points)

                x.markdown("")

                # st_prompt = "tell me two facts about yourself"
                for chunk in bot.ask_stream(st_prompt):
                    md_results = md_results + chunk
                    x.markdown(md_results)
                    #check if last char of chunk is a new line
                    # if "\n" in chunk:
                    #     x.markdown(md_results)
                    # st.markdown(chunk)
                x.markdown(md_results)
                bot._cleanup()
                # md_results = bot.ask(st_prompt) #"Hello, could you tell what is {}?".format(option))
                # print(md_results)  # prints the response from chatGPT

                # st.write(st_prompt)
                # st.write(saved_prompt)
            # md_results = """No result found""" ##here GPT
    # with col6:
    #     # st.subheader("Output incident summary")
    #     st.markdown(md_results)
    placeholder_table.write((dataframe.loc[dataframe['Title'] == option]))

# if button_reset:
#     bot = ChatGPT()
#     bot._cleanup()

if button_save:
    # dataframe = pd.read_csv("structured-data-anonymizer/assets/df_data_short.csv")
    # save st_prompt and st_output to dataframe in row for Title = json_dict_option
    dataframe.loc[dataframe['Title'] == option, 'Prompt'] = st_prompt
    dataframe.loc[dataframe['Title'] == option, 'Result'] = md_results #st_output
    # st.write(json_dict_option)
    # write dataframe back to the csv file
    dataframe.to_csv("structured-data-anonymizer/assets/df_data_short.csv", index=False)
    st.write("Saved to file")
    st.write(dataframe.loc[dataframe['Title'] == option])

# end of document
st.session_state['first_load'] = True



class ToDictListEncoder(JSONEncoder):
    """Encode dict to json."""

    def default(self, o):
        """Encode to JSON using to_dict."""
        if o:
            return o.to_dict()
        return []


if st_return_decision_process:
    st.json(json.dumps(st_analyze_results, cls=ToDictListEncoder))