-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
277 lines (231 loc) · 9.13 KB
/
app.js
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
import { extract } from "https://esm.sh/@extractus/article-extractor";
import { extractInformationFromHTML } from "./extractor.js";
function saveKey() {
const openaiKey = document.getElementById("openai-key").value;
if (openaiKey) {
// Check if the input is not empty
localStorage.setItem("openaiKey", openaiKey);
alert("OpenAI Key saved successfully.");
} else {
alert("Please enter an OpenAI Key.");
}
}
$(`#save-key`).click(saveKey);
$(document).ready(function () {
// Load the OpenAI Key from local storage
const savedKey = localStorage.getItem("openaiKey");
if (savedKey) {
// Set the input value to the saved key
$(`#openai-key`).val(savedKey);
}
// Function to add a new field input along with a description input
function addInputField(name = "", input_type = "", description = "") {
const fieldHtml = $(`
<div class="flex flex-wrap items-center mb-4 fieldItem">
<input required type="text" value ='${name}' placeholder="Field name (e.g., Author)" class="field-name shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mr-2" style="flex-grow: 1;">
<select required class="field-type shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mr-2" style="flex-grow: 1;">
<option value="" ${
input_type === "" ? "selected" : ""
}>Select Type</option>
<option value="string" ${
input_type === "string" ? "selected" : ""
}>String</option>
<option value="number" ${
input_type === "number" ? "selected" : ""
}>Number</option>
<option value="boolean" ${
input_type === "boolean" ? "selected" : ""
}>Boolean</option>
</select>
<input required type="text" value ='${description}' placeholder="Description (e.g., Article author)" class="field-description shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mr-2" style="flex-grow: 4;">
<button class="remove-field bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded focus:outline-none focus:shadow-outline">-</button>
</div>
`);
$("#fields-container").append(fieldHtml);
fieldHtml.find(".remove-field").click(function () {
$(this).parent().remove();
});
}
// Initially add one input field
addInputField();
// Add button event to add more input fields
$("#add-field").click(function (e) {
e.preventDefault();
addInputField();
});
// Function to read and process the uploaded file
$("#template-upload").change(function (e) {
// Delete all divs with class fieldItem
$(".fieldItem").remove();
const fileReader = new FileReader();
fileReader.onload = function (e) {
const fields = JSON.parse(e.target.result);
fields.forEach((field) => {
addInputField(field.name, field.input_type, field.description);
});
};
fileReader.readAsText(e.target.files[0]);
});
// Function to export fields as a template
$("#export-template").click(function () {
const fields = $(".field-name")
.map(function () {
return {
name: $(this).val(),
input_type: $(this).next(".field-type").val(),
description: $(this)
.next(".field-type")
.next(".field-description")
.val(),
};
})
.get();
const dataStr =
"data:text/json;charset=utf-8," +
encodeURIComponent(JSON.stringify(fields));
const dlAnchorElem = document.createElement("a");
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "template.json");
dlAnchorElem.click();
});
// Handle form submission
$("#article-form").submit(async function (e) {
e.preventDefault();
$("#extracted-article").html("<p>Loading...</p>");
$("#extraction-results").html("<p>Loading...</p>");
const articleUrl = $("#article-url").val();
const fieldsToExtract = $(".field-name")
.map(function () {
return $(this).val();
})
.get();
const fieldsTypes = $(".field-type")
.map(function () {
return $(this).val();
})
.get();
const fieldsDescriptions = $(".field-description")
.map(function () {
return $(this).val();
})
.get();
if (!articleUrl) {
alert("Please enter a URL.");
return;
}
// AJAX request to fetch article content
const fetchUrl =
"https://api.allorigins.win/get?url=" + encodeURIComponent(articleUrl);
try {
const article = await extract(fetchUrl);
const cleanedHTML = displayArticle(article.content);
const extractedInformation = await extractInformationFromHTML(
cleanedHTML,
fieldsToExtract,
fieldsTypes,
fieldsDescriptions
);
displayResults(extractedInformation);
} catch (err) {
alert("Failed to retrieve the article. Please try again.");
$("#result-container").html("<p>Could not retrieve the article.</p>");
console.error(err);
}
});
function cleanAndTransformHTML(htmlString) {
// Remove all newline characters from the HTML string to simplify processing
let preCleanedString = htmlString
.replace(/\n+/g, "")
.replace(/\s{2,}/g, " ");
// Create a new DOM parser
const parser = new DOMParser();
// Parse the pre-cleaned string of HTML into a document object
const doc = parser.parseFromString(preCleanedString, "text/html");
// Function to recursively clean nodes in the DOM
function cleanNode(node) {
// Iterate over all child nodes of the current node
let child = node.firstChild;
while (child) {
const nextChild = child.nextSibling;
// Clean text nodes by trimming whitespace
if (child.nodeType === 3) {
// Text node
child.nodeValue = child.nodeValue.replace(/\\n/g, "");
if (child.nodeValue === "") {
child.parentNode.removeChild(child);
}
}
// Recursively clean element nodes
else if (child.nodeType === 1) {
// Element node
cleanNode(child);
}
child = nextChild;
}
// More aggressive removal of empty elements including <p> tags filled with spaces or non-breaking spaces
if (
node.nodeType === 1 &&
(node.childNodes.length === 0 || /^\s*$/.test(node.innerHTML))
) {
node.parentNode.removeChild(node);
}
}
// Start cleaning from the document's body
cleanNode(doc.body);
// Return the cleaned HTML content
return doc.body.innerHTML;
}
// Function to parse and display extracted information along with descriptions
function displayArticle(htmlData) {
// Replace multiple line breaks and spaces with a single space
const cleanedContent = cleanAndTransformHTML(htmlData);
// Insert the cleaned content into the specified div
document.getElementById("extracted-article").innerHTML = cleanedContent;
return cleanedContent;
}
function displayResults(results) {
// Get a reference to the container
var container = document.getElementById("extraction-results");
// Clear previous contents (if any)
container.innerHTML = "";
// Specify options for the JSONEditor
var options = {
mode: "tree", // set to 'code' to allow code editing, 'tree' for visual editor, or 'view' to just view
modes: ["code", "form", "text", "tree", "view"], // can be adjusted according to what you want to allow
onError: function (err) {
alert(err.toString());
},
onModeChange: function (newMode, oldMode) {
console.log("Mode switched from", oldMode, "to", newMode);
},
};
// Create the editor
var editor = new JSONEditor(container, options);
// Set JSON data
editor.set(results);
window.editor = editor;
}
// If you want to get updated JSON data by the user, you can use editor.get()
$("#save-json").click(function () {
// If window.editor is not defined, then the editor has not been created
if (!window.editor) {
alert("Please extract information from an article first.");
return;
}
// Retrieve JSON data from the editor
var json = editor.get();
// Serialize JSON data to a string
var jsonString = JSON.stringify(json, null, 2); // Pretty print with 2 spaces indentation
// Create a Blob object representing the JSON data
var blob = new Blob([jsonString], { type: "application/json" });
// Create a URL for the blob object
var url = URL.createObjectURL(blob);
// Create a temporary anchor element and trigger the download
var a = document.createElement("a");
a.href = url;
a.download = "extracted-data.json"; // File name for the download
document.body.appendChild(a); // Append to the document
a.click(); // Trigger the download
document.body.removeChild(a); // Clean up
});
});