-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkov-mashup-lab.html
More file actions
400 lines (343 loc) · 16.5 KB
/
Copy pathmarkov-mashup-lab.html
File metadata and controls
400 lines (343 loc) · 16.5 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Markov Mashup Lab</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="main-nav">
<a href="index.html">Home</a>
<a href="text-reverse-lab.html">Text Reversal</a>
<a href="line-break-lab.html">Line Break Lab</a>
<a href="eraser-lab.html">Eraser Lab</a>
<a href="alphabetizer-lab.html">Alphabetizer Lab</a>
<a href="markov-mashup-lab.html">Markov Mashup Lab</a>
<a href="lipogram-lab.html">Lipogram Lab</a>
<a href="long-tail-lab.html">Long Tail Lab</a>
<a href="grid-it-lab.html">Grid-It Lab</a>
<a href="letter-replacement-lab.html">Letter Swap</a>
<a href="chromacode-lab.html">Chromacode</a>
<a href="about.html">About</a>
</nav>
<!-- Tool content here -->
<div class="container">
<div class="header">
<h1>Markov Mashup Lab</h1>
<p>Upload your text files and generate creative content using Markov chains</p>
</div>
<p style="margin-bottom: 30px; line-height: 1.8; color: #4a4a4a;">
[Add your description here about how the Markov Mashup Lab generates new text and its applications for computational creativity.]
</p>
<div class="content">
<div class="upload-section">
<div class="upload-area" id="uploadArea">
<div class="upload-icon">📁</div>
<div class="upload-text">Drop your .txt files here or click to browse</div>
<div style="font-size: 0.9em; color: #999;">Supports multiple files</div>
<input type="file" id="fileInput" class="file-input" accept=".txt" multiple>
</div>
<div id="fileInfo" class="file-info" style="display: none;">
<h3>📊 Corpus Statistics</h3>
<div class="file-stats" id="fileStats"></div>
</div>
<div class="controls">
<div class="control-group">
<label for="orderInput">Chain Order (1-5)</label>
<input type="number" id="orderInput" min="1" max="5" value="2">
</div>
<div class="control-group">
<label for="lengthInput">Number of Sentences</label>
<input type="number" id="lengthInput" min="1" max="20" value="3">
</div>
<div class="control-group">
<label for="maxWordsInput">Max Words per Sentence</label>
<input type="number" id="maxWordsInput" min="5" max="100" value="25" placeholder="Leave empty for no limit">
</div>
<div class="control-group">
<label for="startInput">Starting Word (optional)</label>
<input type="text" id="startInput" placeholder="Leave empty for random start">
</div>
<button class="generate-btn" id="generateBtn" disabled>
<span id="btnText">Upload text files first</span>
</button>
</div>
</div>
<div class="output-section">
<div class="output-header">
<div class="output-title">🎨 Generated Text</div>
<button class="apply-btn" id="exportBtn">Export TXT</button>
<button class="clear-btn" id="clearBtn">Clear All</button>
</div>
<div class="output-container" id="outputContainer">
<div style="text-align: center; color: #999; padding: 40px;">
Generated text will appear here...
</div>
</div>
</div>
</div>
</div>
<script>
// JavaScript for this specific tool
class MarkovChain {
constructor(order = 2) {
this.order = order;
this.chain = {};
this.starters = [];
}
addText(text) {
const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0);
for (let sentence of sentences) {
const words = sentence.trim().split(/\s+/).filter(w => w.length > 0);
if (words.length < this.order + 1) continue;
// Add sentence starter
if (words.length >= this.order) {
const starter = words.slice(0, this.order).join(' ').toLowerCase();
this.starters.push(starter);
}
// Build the chain
for (let i = 0; i <= words.length - this.order; i++) {
const gram = words.slice(i, i + this.order).join(' ').toLowerCase();
const nextWord = i + this.order < words.length ? words[i + this.order] : null;
if (!this.chain[gram]) {
this.chain[gram] = [];
}
if (nextWord) {
this.chain[gram].push(nextWord);
}
}
}
}
generateSentence(startWord = null, maxWords = null) {
let currentGram;
if (startWord && startWord.trim()) {
// Try to find a gram that starts with the given word
const searchTerm = startWord.toLowerCase();
const matchingGrams = Object.keys(this.chain).filter(gram =>
gram.startsWith(searchTerm)
);
if (matchingGrams.length > 0) {
currentGram = matchingGrams[Math.floor(Math.random() * matchingGrams.length)];
} else {
currentGram = this.starters[Math.floor(Math.random() * this.starters.length)];
}
} else {
currentGram = this.starters[Math.floor(Math.random() * this.starters.length)];
}
if (!currentGram || !this.chain[currentGram]) {
return "Unable to generate text. Please try with different settings.";
}
let result = currentGram.split(' ').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
let attempts = 0;
const maxAttempts = 100;
let wordCount = currentGram.split(' ').length;
while (attempts < maxAttempts) {
const nextWords = this.chain[currentGram];
if (!nextWords || nextWords.length === 0) break;
const nextWord = nextWords[Math.floor(Math.random() * nextWords.length)];
// Check word limit before adding
if (maxWords && wordCount >= maxWords) {
// Force sentence ending if we've hit the limit
break;
}
result += ' ' + nextWord;
wordCount++;
// Stop at sentence endings
if (/[.!?]$/.test(nextWord)) break;
// Update current gram
const words = currentGram.split(' ');
words.shift();
words.push(nextWord.toLowerCase());
currentGram = words.join(' ');
attempts++;
}
// Ensure sentence ends properly
if (!/[.!?]$/.test(result)) {
const endings = ['.', '!', '.', '.', '.'];
result += endings[Math.floor(Math.random() * endings.length)];
}
return result;
}
generateText(numSentences = 3, startWord = null, maxWords = null) {
const sentences = [];
for (let i = 0; i < numSentences; i++) {
const sentence = this.generateSentence(i === 0 ? startWord : null, maxWords);
sentences.push(sentence);
}
return sentences.join(' ');
}
getStats() {
return {
totalGrams: Object.keys(this.chain).length,
totalStarters: this.starters.length,
avgContinuations: Object.values(this.chain).reduce((acc, val) => acc + val.length, 0) / Object.keys(this.chain).length || 0
};
}
}
let markovChain = null;
let totalWords = 0;
let totalFiles = 0;
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const generateBtn = document.getElementById('generateBtn');
const btnText = document.getElementById('btnText');
const outputContainer = document.getElementById('outputContainer');
const clearBtn = document.getElementById('clearBtn');
const fileInfo = document.getElementById('fileInfo');
const fileStats = document.getElementById('fileStats');
// File upload handling
uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', (e) => {
handleFiles(e.target.files);
});
async function handleFiles(files) {
if (files.length === 0) return;
generateBtn.disabled = true;
btnText.innerHTML = '<span class="loading"></span> Processing files...';
const order = parseInt(document.getElementById('orderInput').value) || 2;
markovChain = new MarkovChain(order);
totalWords = 0;
totalFiles = 0;
try {
for (const file of files) {
if (file.type === 'text/plain' || file.name.endsWith('.txt')) {
const text = await readFile(file);
markovChain.addText(text);
totalWords += text.split(/\s+/).length;
totalFiles++;
}
}
if (totalFiles > 0) {
updateFileStats();
generateBtn.disabled = false;
btnText.textContent = 'Generate Text';
} else {
btnText.textContent = 'No valid .txt files found';
setTimeout(() => {
btnText.textContent = 'Upload text files first';
}, 2000);
}
} catch (error) {
console.error('Error processing files:', error);
btnText.textContent = 'Error processing files';
setTimeout(() => {
btnText.textContent = 'Upload text files first';
}, 2000);
}
}
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) => reject(e);
reader.readAsText(file);
});
}
function updateFileStats() {
if (!markovChain) return;
const stats = markovChain.getStats();
fileInfo.style.display = 'block';
fileStats.innerHTML = `
<div class="stat">
<strong>${totalFiles}</strong>
Files
</div>
<div class="stat">
<strong>${totalWords.toLocaleString()}</strong>
Words
</div>
<div class="stat">
<strong>${stats.totalGrams.toLocaleString()}</strong>
Grams
</div>
<div class="stat">
<strong>${Math.round(stats.avgContinuations * 10) / 10}</strong>
Avg Links
</div>
`;
}
// Generate text
generateBtn.addEventListener('click', () => {
if (!markovChain) return;
const numSentences = parseInt(document.getElementById('lengthInput').value) || 3;
const startWord = document.getElementById('startInput').value.trim();
const maxWords = parseInt(document.getElementById('maxWordsInput').value) || null;
const order = parseInt(document.getElementById('orderInput').value) || 2;
// Rebuild chain if order changed
if (markovChain.order !== order) {
generateBtn.disabled = true;
btnText.innerHTML = '<span class="loading"></span> Rebuilding chain...';
// Small delay to show loading state
setTimeout(() => {
// This is a simplified rebuild - in a real app you'd store the original text
btnText.textContent = 'Chain order changed - please re-upload files';
generateBtn.disabled = false;
}, 500);
return;
}
const generatedText = markovChain.generateText(numSentences, startWord, maxWords);
addTextCard(generatedText);
});
function addTextCard(text) {
// Remove placeholder if it exists
const placeholder = outputContainer.querySelector('div[style*="text-align: center"]');
if (placeholder) placeholder.remove();
const card = document.createElement('div');
card.className = 'text-card';
card.innerHTML = `<div class="text-content">${text}</div>`;
// Add with animation
card.style.opacity = '0';
card.style.transform = 'translateY(20px)';
outputContainer.insertBefore(card, outputContainer.firstChild);
setTimeout(() => {
card.style.transition = 'all 0.5s ease';
card.style.opacity = '1';
card.style.transform = 'translateY(0)';
}, 10);
}
// Clear output
clearBtn.addEventListener('click', () => {
outputContainer.innerHTML = `
<div style="text-align: center; color: #999; padding: 40px;">
Generated text will appear here...
</div>
`;
});
document.getElementById('exportBtn').addEventListener('click', function() {
const cards = outputContainer.querySelectorAll('.text-content');
if (!cards.length) return;
const text = Array.from(cards).map(function(c) { return c.textContent.trim(); }).join('\n\n');
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'markov-mashup-output.txt';
a.click();
URL.revokeObjectURL(url);
});
// Update chain order
document.getElementById('orderInput').addEventListener('change', () => {
if (markovChain) {
generateBtn.disabled = true;
btnText.textContent = 'Re-upload files to apply new order';
fileInfo.style.display = 'none';
markovChain = null;
}
});
</script>
</body>
</html>