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
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
/* CONSTANTS */
const maxSelectedFrames = 3;

/* VUE APP */
const SocioFillmoreDemo = {
    data() {
        return {
            interactiveModeEnabled: false,
            showIntroductionBox: true,
            showExplanationText: true,

            // examples
            selectedExampleId: -1,

            // event types
            eventTypeName: "",
            eventTypeDescr: "",
            eventTypeTextExample: "",

            // frames
            primaryFrames: Array(maxSelectedFrames).fill(null),
            perspectivizingFrames: Array(maxSelectedFrames).fill(Array(2).fill(null)),

            frameToAdd: "",
            showInvalidFrameWarning: false,

            // keywords (for frame selection)
            keywordAreaShown: false,
            showInvalidKeywordWarning: false,
            keywordToAdd: "",
            selectedKeywords: [],
            keywordSuggestedFrames: [],

            // text analysis
            textToAnalyze: "",
            analyzedSentences: [],
            analyzingTextBusy: false,
            analysisLanguage: "it"
        }
    },

    mounted() {
    },

    // methods listed in order as shown in UI
    methods: {

        // mode 1: interactive mode
        startInteractiveMode() {
            this.interactiveModeEnabled = true;
            console.log(this.$refs);
            setTimeout(() => {
                this.$refs.interactiveModeHeading.scrollIntoView({ behavior: "smooth" });
            }, 100)
        },


        // 1A: define event type
        showEventExample() {

            let numExamples = 1;
            let randNum = Math.floor(Math.random() * numExamples);

            const names = [
                "Traffic crash",
            ];
            const descriptions = [
                "An accident happens in which a driver hits a pedestrian with their car. Typically, this kind of event is framed with a strong focus on the victim and their actions, and less focus on the driver"
            ]
            const textExamples = [
                "Typical newspaper headline (from https://www.irishexaminer.com/news/arid-40791657.html): Cyclist, 70s, seriously injured following collision in Dublin.\nAlternative way of framing: Driver hits pedestrian with his car, sending the 70-year old man to hospital with heavy injuries."
            ];

            this.selectedExampleId = randNum;
            this.eventTypeName = names[randNum];
            this.eventTypeDescr = descriptions[randNum];
            this.eventTypeTextExample = textExamples[randNum];
        },

        // 1B: defining frames
        showFrameExample() {
            let selectedExample = this.selectedExampleId;
            if (selectedExample === -1) {
                selectedExample = Math.floor(Math.random() * 3);
                this.selectedExample = selectedExample;
            }

            this.primaryFrames = this.primaryFrames.map(_ => null);
            switch (selectedExample) {
                case 0: // measles
                    this.switchFrame(0, "Impact");
                    setTimeout(() => {this.switchFrame(1, "Experience_bodily_harm")}, 50);
                    setTimeout(() => {this.switchFrame(2, "Catastrophe")}, 100);
                    break;
//                case 1:
//                    this.switchFrame(0, "Win_prize");
//                    this.switchFrame(1, "Self_motion");
//                    this.switchFrame(2, "Motion_directional");
//                    break;
//                case 2:
//                    this.switchFrame(0, "Win_prize");
//                    this.switchFrame(1, "Self_motion");
//                    this.switchFrame(2, "Motion_directional");
//                    break;
            }

        },

        addFrame(frmName) {
            this.frameToAdd = "";

            let numSelectedFrames = this.primaryFrames.filter((fr) => fr !== null).length;
            if (numSelectedFrames >= maxSelectedFrames) {
                return;
            }

            let newFrameIdx = numSelectedFrames;
            this.switchFrame(newFrameIdx, frmName);

        },

        switchFrame(targetIdx, frmName) {
            getFrameInfo(frmName,
                // success    
                (data) => {
                    this.showInvalidFrameWarning = false;
                    console.log(data);

                    this.primaryFrames[targetIdx] = {
                        "name": frmName,
                        "description": data["description"],
                        "altPerspectives": [],
                        "typicalExemplar": data["typicalExemplar"]
                    };

                    data["altPerspectives"].forEach((persp) => {
                        getFrameInfo(persp["frame"],
                            // success
                            (perspData) => {
                                this.primaryFrames[targetIdx].altPerspectives.push({
                                    "name": persp["frame"],
                                    "type": persp["type"][0].toUpperCase() + persp["type"].substring(1),
                                    "description": perspData["description"],
                                    "typicalExemplar": perspData["typicalExemplar"]
                                });
                                // this.analyzeText(this.textToAnalyze);
                            });
                    });
                },
                // failure
                () => {
                    this.showInvalidFrameWarning = true;
                });
        },

        removeFrame(frmName) {
            this.primaryFrames = this.primaryFrames.filter((frm) => frm === null || frm.name !== frmName);
            for (let i = this.primaryFrames.length; i < maxSelectedFrames; i++) {
                this.primaryFrames.push(null);
            }
        },


        // 1C: keyword-assisted frame selection
        showKeywords() {
            this.keywordAreaShown = true;
            setTimeout(() => {
                this.$refs.keywordHeading.scrollIntoView({ behavior: "smooth" });
            }, 100)
        },

        addKeyword() {
            this.selectedKeywords.push({ "text": this.keywordToAdd });
            this.keywordToAdd = "";
            this.updateKeywordSuggestedFrames();
        },

        updateKeywordSuggestedFrames() {
            this.keywordSuggestedFrames = [];
            $.get(
                "similar_frames",
                { "words_in": this.selectedKeywords.map((kwd) => kwd.text).join("+") }
            ).done((data) => {
                if (data.result === "FAIL") {
                    this.showInvalidKeywordWarning = true;
                } else {
                    this.showInvalidKeywordWarning = false;
                    data["frames"].slice(0, 5).forEach((frm) => {
                        getFrameInfo(frm, (frameInfo) => {
                            console.log(frameInfo);
                            this.keywordSuggestedFrames.push({
                                text: frm,
                                description: frameInfo["description"],
                                exemplars: frameInfo["exemplars"],
                                altPerspectives: frameInfo["altPerspectives"],
                            })
                        });
                    });
                }
            });
        },

        removeKeyword(event) {
            this.selectedKeywords = this.selectedKeywords.filter((kwd) => kwd.text !== event.target.attributes["title"].value);
            this.updateKeywordSuggestedFrames();
        },

        // 1D: on-the-fly text analysis
        analyzeText(text, language) {
            this.analyzedSentences = [];
            this.analyzingTextBusy = true;

            $.get("sociofillmore", { "text": text, "language": language },
                // success
                (data) => {
                    data.forEach((sentenceData) => {
                        console.log(sentenceData);
                        let textParts = [];
                        sentenceData["sentence"].forEach((token, tokenIdx) => {
                            let targets = sentenceData["fn_structures"].filter(struct => struct["target"]["tokens_idx"].includes(tokenIdx));
                            if (targets.length === 0) {
                                textParts.push({ "text": token, "type": "nonTarget" });
                            } else {

                                // frame & perspective
                                let target = targets[0];
                                let perspectiveType = "Main";
                                let perspectiveOn = target["frame"];
                                let subType = "otherTarget";
                                if (this.primaryFrames.filter(pf => pf !== null).map(pf => pf.name).includes(target["frame"])) {
                                    subType = "primaryTarget";
                                } else if (this.primaryFrames.filter(pf => pf !== null).flatMap(pf => pf.altPerspectives.map(ap => ap.name)).includes(target["frame"])) {
                                    let primary = this.primaryFrames.filter(pf => pf !== null && pf.altPerspectives.map(ap => ap.name).includes(target["frame"]))[0];
                                    let alternate = primary.altPerspectives.filter(ap => ap.name === target["frame"])[0];
                                    subType = "altTarget";
                                    perspectiveType = alternate.type;
                                    perspectiveOn = primary.name;
                                }

                                // grammar info
                                let syntax = sentenceData["syntax"][tokenIdx][0];
                                let grammarInfo = getGrammarInfo(syntax);

                                // FEs
                                let roles = [];
                                target["roles"].forEach(role => {
                                    let roleName = role[0];
                                    let roleSpanIdx = role[1]["tokens_idx"];
                                    let roleSpanTxt = role[1]["tokens_str"].join(" ");
                                    roles.push({
                                        "name": roleName,
                                        "spanIdx": roleSpanIdx,
                                        "spanTxt": roleSpanTxt,
                                        "spanTxtClipped": roleSpanTxt.length > 50 ? roleSpanTxt.substring(0, 50) + "...": roleSpanTxt
                                    })
                                });

                                console.log(roles);
                                textParts.push({
                                    "text": token,
                                    "type": "target",
                                    "subType": subType,
                                    "frame": target["frame"],
                                    "perspectiveType": perspectiveType,
                                    "perspectiveOn": perspectiveOn,
                                    "grammarInfo": grammarInfo,
                                    "roles": roles
                                });
                            }
                        });

                        this.analyzedSentences.push({
                            "text": sentenceData["sentence"].join(" "),
                            "textParts": textParts,
                            "relevantTargets": textParts.filter(tp => (tp.type === "target" && tp.subType !== "otherTarget"))
                        });
                        console.log(this.analyzedSentences);
                        this.analyzingTextBusy = false;
                    });
                });
        },

        showTextExample() {
            this.analysisLanguage = "en";
            this.textToAnalyze = this.eventTypeTextExample;
        }


    },

    delimiters: ['@{', '}']
}

/* HELPER FUNCTIONS */
function getFrameInfo(frm, successCallback, failureCallback) {

    $.get("frame_info", { "frame": frm }).done((data) => {

        if (data["result"] !== "OK") {
            failureCallback();
            return;
        }

        let descriptionClipped = clipFrameDescription(data["frameDefinition"]);
        let url = "https://framenet2.icsi.berkeley.edu/fnReports/data/frameIndex.xml?frame=" + frm;
        descriptionClipped += ' <a href="' + url + '">(read more)</a>';

        let sampledExemplars = sampleExemplars(data["exemplars"]);
        let exemplarsClipped = clipExemplars(sampledExemplars);

        let frameInfo = {
            "description": descriptionClipped,
            "exemplars": exemplarsClipped,
            "altPerspectives": data["altPerspectives"],
            "typicalExemplar": data["typicalExemplar"]
        };
        successCallback(frameInfo);
    })
}


function clipFrameDescription(descriptionParts) {
    console.log(descriptionParts);
    let descriptionClipped = "";
    for (let i = 0; i < descriptionParts.length; i++) {
        let remainingLength = 300 - descriptionClipped.length;
        if (remainingLength >= 0) {
            let newPart = descriptionParts[i];
            if (newPart.length > remainingLength) {
                descriptionClipped += newPart.substring(0, remainingLength) + "...";
            } else {
                descriptionClipped += newPart;
            }
        }
    }
    return descriptionClipped;
}

function sampleExemplars(exemplars) {
    let sampledExemplars = [];
    let sampleSize = Math.min(10, exemplars.length);

    for (let i = 0; i < sampleSize; i++) {
        let filteredExemplars = exemplars.filter(((ex) => !sampledExemplars.includes(ex)));
        let randIdx = Math.floor(Math.random() * filteredExemplars.length);
        sampledExemplars.push(filteredExemplars[randIdx]);
    }
    return sampledExemplars;
}

function clipExemplars(exemplars) {
    // clip exemplars to show the target + some context before and after
    return exemplars.map((ex) => {

        // target +/- N characters
        const maxContextChars = 35;

        let tgtStartIdx = ex["target_idx"][0];
        let fragmentStartIdx = Math.max(0, tgtStartIdx - maxContextChars);
        let tgtEndIdx = ex["target_idx"][1];
        let fragmentEndIdx = Math.min(ex["text"].length, tgtEndIdx + maxContextChars);

        // adjust for word boundaries
        let textWithCapitalizedTarget =
            ex["text"].substring(0, tgtStartIdx) +
            ex["text"].substring(tgtStartIdx, tgtEndIdx).toUpperCase() +
            ex["text"].substring(tgtEndIdx, ex["text"].length);
        ;

        let clippedText = textWithCapitalizedTarget.split(" ").filter((_, idx, arr) => {
            let prevChars = arr.slice(0, idx).join(" ").length;
            if (prevChars >= fragmentStartIdx && prevChars <= fragmentEndIdx) {
                return true;
            } else {
                return false;
            }
        }).join(" ");

        return { "text": clippedText };
    })
}

function getGrammarInfo(syntax) {
    let grammarInfo = "other";
    if (syntax["syn_category"].startsWith("v:")) {
        switch (syntax["syn_construction"]) {
            case "verbal:active":
                grammarInfo = "active";
                break;
            case "verbal:passive":
                grammarInfo = "passive";
                break;
            case "verbal:unaccusative":
                grammarInfo = "intransitive";
                break;
            case "verbal:impersonal":
                grammarInfo = "impersonal";
                break;
            case "verbal:reflexive":
                grammarInfo = "reflexive";
                break;
        }
    } else if (syntax["syn_category"] == "n") {
        grammarInfo = "noun";
    } else if (syntax["syn_category"] == "adj") {
        grammarInfo = "adjective";
    }
    return grammarInfo;
}


/* MAIN LOOP */
Vue.createApp(SocioFillmoreDemo).mount("#sociofillmore-demo");