-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
349 lines (308 loc) · 8.59 KB
/
index.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
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
const path = require("path");
const fs = require("fs-extra");
const { JSDOM } = require("jsdom");
const moment = require("moment");
const he = require("he");
const ID_START = 1;
const ID_END = 50000;
const outputDir = path.join(__dirname, "films");
String.prototype.replaceAll = function(search, replacement) {
let target = this;
return target.replace(new RegExp(search, "g"), replacement);
};
function extractDate(str) {
return moment(str, "YYYY.MM.DD").format("YYYY-MM-DD");
}
const patches = {
"001924": {
"Argumento/roteiro": {
Roteiro: ["Diegues, Carlos"]
}
},
"002174": {
"Argumento/roteiro": {
Roteiro: ["Omar, Arthur"]
}
},
"003250": {
"Argumento/roteiro": {
Roteiro: ["Diegues, Carlos"]
}
},
"003309": {
"Argumento/roteiro": {
Roteiro: ["Miziara, José"]
}
},
"003333": {
Estória: ["Morgantini, Araldo"]
},
"003333": {
"Argumento/roteiro": {
Roteiro: ["Paula, Francisco de", "Motta, Nelson"],
Argumento: ["Paula, Francisco de", "Motta, Nelson"]
}
},
"009335": {
"Argumento/roteiro": {
Roteiro: ["Cotrim, Costa"]
}
}
};
const sectionsInBackOrder = [
"Observações",
"Fontes consultadas",
"Fontes utilizadas",
"Conteúdo examinado",
"Identidades/elenco:",
"Narração",
"Participação especial",
"Ator(es) Convidado(s)",
"Identidades/elenco:",
"Locação:",
"Canção",
"Dados adicionais de música",
"Música",
"Dados adicionais de direção de arte",
"Direção de arte",
"Dados adicionais de montagem",
"Montagem",
"Dados adicionais de som",
"Som",
"Dados adicionais de fotografia",
"Fotografia",
"Direção",
"Estória",
"Argumento/roteiro",
"Distribuição",
"Produção - Dados adicionais",
"Produção",
"Prêmios",
"Termos geográficos",
"Descritores secundários",
"Termos descritores",
"Gênero",
"Sinopse",
"Circuito exibidor",
"Data e local de lançamento",
"Certificados",
"Data e local de produção",
"Versão",
"Material original",
"Categorias",
"Outras remetências de título",
"Título atribuído ao episódio"
];
const sectionNamesWithColon = [
"Ator(es) Convidado(s)",
"Conteúdo examinado",
"Estória",
"Fontes consultadas",
"Fontes utilizadas",
"Narração",
"Observações",
"Outras remetências de título",
"Participação especial"
];
const onelineSections = ["Conteúdo examinado", "Estória"];
const semicolonSeparatedArray = [
"Termos geográficos",
"Descritores secundários",
"Termos descritores",
"Gênero"
];
const commaSeparatedArray = ["Material original"];
const dashSeparatedArray = ["Categorias"];
const sourceSections = ["Fontes consultadas", "Fontes utilizadas"];
function parseIdentity(line) {
let [person, identity] = line.split("(");
person = person.trim();
return identity
? {
person,
identity: identity.replace(")", "")
}
: {
person
};
}
function parseAndRemoveSection(accumulator, sectionId) {
const pageId = accumulator.id;
let lines;
try {
let sectionSeparator;
if (sectionNamesWithColon.includes(sectionId)) {
sectionSeparator = `\n${sectionId}:`;
} else {
sectionSeparator = `section:${sectionId}`;
}
if (accumulator.remainingText.indexOf(sectionSeparator) > -1) {
const data = {};
const sectionText = accumulator.remainingText
.split(sectionSeparator)
.pop();
// Remove section from remaining text
const sectionStartIndex = accumulator.remainingText.lastIndexOf(
sectionSeparator
);
const remainingText = accumulator.remainingText.substring(
0,
sectionStartIndex
);
// Check if section has patch
if (patches[pageId] && patches[pageId][sectionId]) {
return {
remainingText,
data: Object.assign({}, accumulator.data, patches[pageId])
};
}
// FULL-TEXT SECTIONS
if (
[
"Argumento/roteiro",
"Canção",
"Certificados",
"Circuito exibidor",
"Dados adicionais de música",
"Observações",
"Prêmios",
"Sinopse",
"Título atribuído ao episódio"
].includes(sectionId)
) {
data[sectionId] = he.decode(sectionText);
} else {
// Parse section
lines = sectionText
.split("\n")
.map(n => n.trim())
.filter(n => n); // discard empty lines
if (lines.length == 0)
return {
remainingText,
data: accumulator.data
};
if (sourceSections.includes(sectionId)) {
data[sectionId] = parseSources(lines);
} else if (onelineSections.includes(sectionId)) {
data[sectionId] = lines.pop();
} else if (sectionId === "Locação:") {
data["Locação"] = lines.pop();
} else if (sectionId === "Narração") {
data["Narração"] = lines;
} else if (sectionId === "Identidades/elenco:") {
data["Identidades/elenco"] = lines.map(parseIdentity);
} else if (sectionId === "Ator(es) Convidado(s)") {
data["Ator(es) Convidado(s)"] = lines.map(parseIdentity);
} else if (sectionId === "Participação especial") {
data["Participação especial"] = lines.map(parseIdentity);
} else if (
semicolonSeparatedArray
.concat("Outras remetências de título")
.includes(sectionId)
) {
data[sectionId] = lines
.pop()
.split(";")
.map(i => i.trim());
} else if (commaSeparatedArray.includes(sectionId)) {
data[sectionId] = lines
.pop()
.split(",")
.map(i => i.trim());
} else if (dashSeparatedArray.includes(sectionId)) {
data[sectionId] = lines
.pop()
.split("/")
.map(i => i.trim());
} else {
data[sectionId] = {};
lines.forEach(line => {
const [key, value] = line.split(":");
const entries = value.split(";").map(i => i.trim());
data[sectionId][key] = entries.length == 1 ? entries[0] : entries;
});
}
}
// Return modified accumulator
return {
id: pageId,
remainingText,
data: Object.assign({}, accumulator.data, data)
};
} else {
return accumulator;
}
} catch (error) {
throw new Error(`${pageId} (${sectionId}): ${error.message}`);
}
}
function parseSources(lines) {
return lines.map(i => {
if (i.indexOf("<a") > -1) {
const anchorDom = new JSDOM(i);
const result = {
id: i
.replace(`<a href="#" onclick="return( showFonte('`, "")
.split("'")[0]
};
const text = anchorDom.window.document.body.textContent;
if (text != result.id) result.text = text;
return result;
} else {
return { text: i };
}
});
}
async function parseFile(movieId) {
const data = await fs.readFile(`./html/${movieId}.html`, "utf8");
let page = { id: movieId, data: {} };
const dom = new JSDOM(data);
const tableNode = dom.window.document.querySelector(
".middle > form:nth-child(2) > center:nth-child(32) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2)"
);
if (!tableNode) {
console.log(`${movieId}: empty`);
return;
}
// MOVIE TITLE
const titleDiv = tableNode.querySelector("div");
if (!titleDiv) return;
tableNode.removeChild(titleDiv);
page.data["Título"] = titleDiv.textContent;
let html = tableNode.innerHTML;
page.remainingText = html
.trim()
.replace("<!-- formato de apresentacao da base -->", "")
.replaceAll("<br>", "\n")
.replaceAll("<b>", "")
.replaceAll("</b>", "")
.replaceAll("<blockquote>", "\n")
.replaceAll("</blockquote>", "\n")
.replaceAll('<b class="label">', "section:");
page = sectionsInBackOrder.reduce(parseAndRemoveSection, page);
const outputFilename = path.join(outputDir, `${movieId}.json`);
// Try to remove the file if it exists.
try {
await fs.remove(outputFilename);
} catch (error) {
// Nothing to do
}
const jsonOutput = JSON.stringify(page.data, null, 2);
await fs.writeFile(outputFilename, jsonOutput);
console.log(`${movieId}: ok`);
}
async function start() {
try {
// Ensure output dir exists.
await fs.ensureDir(outputDir);
let i = ID_START;
while (i < ID_END) {
await parseFile(i.toString().padStart(6, "0"));
i++;
}
} catch (error) {
console.log("Fatal error:", error);
}
}
start();