-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse-fragments.js
More file actions
342 lines (292 loc) · 9.53 KB
/
parse-fragments.js
File metadata and controls
342 lines (292 loc) · 9.53 KB
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
/**
* Parse Word document and populate fragment files
* Extracts sections from the book and creates properly formatted markdown files
*/
import mammoth from 'mammoth';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const WORD_FILE = path.join(__dirname, 'draft', 'One Chooses the Title of a Book Only at the End.docx');
const FRAGMENTS_DIR = path.join(__dirname, 'fragments');
// Section markers to identify different parts
const SECTION_PATTERNS = {
prologue: /^Prologue\s*$/i,
cycle1: /^Cycle 1[:\-\s]*(.+)?$/i,
cycle2: /^Cycle 2[:\-\s]*(.+)?$/i,
cycle3: /^Cycle 3[:\-\s]*(.+)?$/i,
epilogue: /^Epilogue\s*$/i,
};
// Character markers
const CHARACTER_PATTERNS = {
cassandra: /^Cassandra\s*$/i,
stephane: /^St[eé]phane\s*$/i,
reader: /^Reader\s*$/i,
witness: /^The\s+Witness\s*$/i,
};
/**
* Parse the Word document
*/
async function parseWordDocument() {
console.log('Reading Word document...');
try {
const result = await mammoth.extractRawText({ path: WORD_FILE });
if (!result || !result.value) {
throw new Error('Failed to extract text from document');
}
const text = result.value;
console.log(`Extracted ${text.length} characters\n`);
return text;
} catch (error) {
console.error('Error reading Word document:', error);
throw error;
}
}
/**
* Split text into sections and fragments
*/
function splitIntoSections(text) {
const lines = text.split('\n');
const sections = {
prologue: [],
cycle1: [],
cycle2: [],
cycle3: [],
epilogue: [],
};
let currentSection = null;
let currentCharacter = null;
let currentTitle = '';
let currentContent = [];
let startedContent = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Look for "Prologue" header in the content (not TOC)
if (!startedContent && line.match(/^Prologue\s*$/i)) {
// Check if there's actual content following
for (let j = i + 1; j < Math.min(i + 20, lines.length); j++) {
if (lines[j].trim().length > 100) {
startedContent = true;
currentSection = 'prologue';
currentCharacter = 'Prologue';
currentTitle = 'Prologue';
console.log('Found Prologue section');
break;
}
}
if (startedContent) continue;
}
// Skip until we've started content
if (!startedContent) continue;
// Detect cycle sections
if (line.match(/^Cycle 1[:\-\s]/i)) {
// Save any current fragment
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
currentContent = [];
currentCharacter = null;
currentTitle = '';
}
currentSection = 'cycle1';
console.log('Found Cycle 1');
continue;
}
if (line.match(/^Cycle 2[:\-\s]/i)) {
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
currentContent = [];
currentCharacter = null;
currentTitle = '';
}
currentSection = 'cycle2';
console.log('Found Cycle 2');
continue;
}
if (line.match(/^Cycle 3[:\-\s]/i)) {
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
currentContent = [];
currentCharacter = null;
currentTitle = '';
}
currentSection = 'cycle3';
console.log('Found Cycle 3');
continue;
}
if (line.match(/^Epilogue[:\-\s]/i)) {
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
currentContent = [];
}
currentSection = 'epilogue';
currentCharacter = 'Epilogue';
currentTitle = 'The Return';
console.log('Found Epilogue');
continue;
}
// Detect character headers with titles: (Character): Title
const characterMatch = line.match(/^\((Cassandra|Reader|Stephane|Stéphane)\):\s*(.+)$/i);
if (characterMatch) {
// Save previous fragment
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
}
currentCharacter = characterMatch[1].replace('é', 'e'); // Normalize Stéphane to Stephane
currentCharacter = currentCharacter.charAt(0).toUpperCase() + currentCharacter.slice(1).toLowerCase();
currentTitle = characterMatch[2].trim();
currentContent = [];
console.log(` Found fragment in ${currentSection}: ${currentCharacter} - ${currentTitle}`);
continue;
}
// Detect "Acknowledgments" - this marks end of main content
if (line.match(/^Acknowledgments/i)) {
// Save final fragment
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
}
break;
}
// Add content to current fragment
if (currentSection && currentCharacter) {
// For Prologue and Epilogue, collect all content until next section
if (currentCharacter === 'Prologue' || currentCharacter === 'Epilogue') {
if (line) {
currentContent.push(line);
}
} else {
// For regular fragments, add content
if (currentContent.length > 0 || line) {
currentContent.push(line);
}
}
}
}
// Save final fragment if not already saved
if (currentContent.length > 0 && currentSection) {
sections[currentSection].push({
title: currentTitle || 'Untitled',
character: currentCharacter || 'Unknown',
content: currentContent.join('\n').trim()
});
}
return sections;
}
/**
* Create filename from title and character
*/
function createFilename(index, character, title) {
const num = String(index + 1).padStart(2, '0');
const char = character.toLowerCase();
const slug = title
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.substring(0, 50);
return `${num}-${char}-${slug}.md`;
}
/**
* Create markdown content
*/
function createMarkdown(fragment) {
// Clean up content - add line breaks where sentences run together
let content = fragment.content;
// Fix common issues where sentences are joined
content = content.replace(/([.!?])([A-Z])/g, '$1\n\n$2');
content = content.replace(/([.!?])(\s*)Love,/g, '$1\n\nLove,');
// Clean up excessive whitespace
content = content.replace(/\n{3,}/g, '\n\n');
return `# ${fragment.title}
**Character:** ${fragment.character}
**Cycle:** ${fragment.cycle}
---
${content.trim()}
`;
}
/**
* Save fragments to files
*/
function saveFragments(sections) {
const cycleNames = {
prologue: 'Prologue',
cycle1: 'Cycle 1',
cycle2: 'Cycle 2',
cycle3: 'Cycle 3',
epilogue: 'Epilogue',
};
for (const [sectionKey, fragments] of Object.entries(sections)) {
if (fragments.length === 0) continue;
const sectionDir = path.join(FRAGMENTS_DIR, sectionKey);
// Ensure directory exists
if (!fs.existsSync(sectionDir)) {
fs.mkdirSync(sectionDir, { recursive: true });
}
console.log(`\nProcessing ${sectionKey}: ${fragments.length} fragments`);
fragments.forEach((fragment, index) => {
const filename = createFilename(index, fragment.character, fragment.title);
const filePath = path.join(sectionDir, filename);
const fragmentWithCycle = {
...fragment,
cycle: cycleNames[sectionKey]
};
const markdown = createMarkdown(fragmentWithCycle);
fs.writeFileSync(filePath, markdown, 'utf-8');
console.log(` ✓ ${filename}`);
});
}
}
/**
* Main execution
*/
async function main() {
try {
console.log('Starting fragment extraction...\n');
// Check if Word file exists
if (!fs.existsSync(WORD_FILE)) {
console.error(`Error: Word file not found at ${WORD_FILE}`);
console.log('Please ensure "One Chooses the Title of a Book Only at the End.docx" is in the project root.');
process.exit(1);
}
// Parse document
const text = await parseWordDocument();
// Split into sections
const sections = splitIntoSections(text);
// Show summary
console.log('\nExtracted sections:');
for (const [section, fragments] of Object.entries(sections)) {
console.log(` ${section}: ${fragments.length} fragments`);
}
// Save fragments
console.log('\nSaving fragments...');
saveFragments(sections);
console.log('\n✅ Fragment extraction complete!');
} catch (error) {
console.error('Error:', error);
process.exit(1);
}
}
main();