-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-real-conversion.js
More file actions
472 lines (392 loc) · 14.4 KB
/
Copy pathtest-real-conversion.js
File metadata and controls
472 lines (392 loc) · 14.4 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/**
* Teste real de conversão com FileForge
* Este arquivo demonstra conversões reais que geram arquivos válidos
*/
const fs = require('fs');
const path = require('path');
// Importar as bibliotecas diretamente para testes reais
const sharp = require('sharp');
const { PDFDocument, rgb } = require('pdf-lib');
const { marked } = require('marked');
async function createTestFiles() {
console.log('🔥 Criando arquivos de teste reais...\n');
// Criar diretório de teste
const testDir = './test-files';
if (!fs.existsSync(testDir)) {
fs.mkdirSync(testDir);
}
// 1. Criar uma imagem de teste
console.log('📸 Gerando imagem de teste...');
await sharp({
create: {
width: 800,
height: 600,
channels: 3,
background: { r: 100, g: 150, b: 200 }
}
})
.png()
.composite([
{
input: Buffer.from(`
<svg width="800" height="600">
<rect width="800" height="600" fill="rgb(100,150,200)"/>
<text x="400" y="250" text-anchor="middle" font-size="48" fill="white" font-family="Arial">
FileForge Test Image
</text>
<text x="400" y="320" text-anchor="middle" font-size="24" fill="white" font-family="Arial">
Generated with Sharp
</text>
<circle cx="400" cy="400" r="50" fill="rgba(255,255,255,0.3)"/>
</svg>
`),
top: 0,
left: 0
}
])
.toFile(path.join(testDir, 'test-image.png'));
console.log('✅ Imagem criada: test-files/test-image.png');
// 2. Criar um PDF de teste
console.log('📄 Gerando PDF de teste...');
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]); // A4 size
const { width, height } = page.getSize();
page.drawText('FileForge - Framework de Conversão', {
x: 50,
y: height - 100,
size: 24,
color: rgb(0, 0, 0),
});
page.drawText('Este é um PDF de teste gerado pelo FileForge.', {
x: 50,
y: height - 150,
size: 14,
color: rgb(0.2, 0.2, 0.2),
});
page.drawText('Características do FileForge:', {
x: 50,
y: height - 200,
size: 16,
color: rgb(0, 0, 0),
});
const features = [
'• Conversão multi-formato',
'• OCR integrado',
'• Extração de metadados',
'• Streaming para arquivos grandes',
'• Batch conversion',
'• Sistema de plugins extensível'
];
features.forEach((feature, index) => {
page.drawText(feature, {
x: 70,
y: height - 240 - (index * 25),
size: 12,
color: rgb(0.1, 0.1, 0.1),
});
});
// Adicionar uma forma geométrica
page.drawRectangle({
x: 400,
y: height - 400,
width: 150,
height: 100,
borderColor: rgb(0.4, 0.6, 0.8),
borderWidth: 2,
color: rgb(0.9, 0.95, 1),
});
page.drawText('FileForge', {
x: 430,
y: height - 360,
size: 16,
color: rgb(0.4, 0.6, 0.8),
});
const pdfBytes = await pdfDoc.save();
fs.writeFileSync(path.join(testDir, 'test-document.pdf'), pdfBytes);
console.log('✅ PDF criado: test-files/test-document.pdf');
// 3. Criar um arquivo de texto
console.log('📝 Gerando arquivo de texto...');
const textContent = `FileForge - Framework de Conversão de Arquivos
Este é um arquivo de texto de exemplo para demonstrar as capacidades do FileForge.
CARACTERÍSTICAS:
- Suporte a 15+ formatos de arquivo
- Conversões inteligentes entre diferentes tipos de mídia
- OCR (Reconhecimento Ótico de Caracteres) integrado
- Extração automática de metadados
- Processamento em streaming para arquivos grandes
- Conversão em lote com controle de concorrência
- Sistema de plugins extensível
- CLI poderoso e intuitivo
- Otimizado para ambientes serverless
FORMATOS SUPORTADOS:
Documentos: PDF, DOCX, TXT, HTML, Markdown
Imagens: JPG, PNG, SVG, WebP
Dados: XLSX, CSV, JSON, XML
Mídia: MP3, WAV, MP4, AVI (estrutura implementada)
EXEMPLOS DE USO:
1. Converter PDF para texto com OCR
2. Extrair texto de imagens digitalizadas
3. Converter documentos Word para Markdown
4. Processar milhares de arquivos em lote
5. Extrair metadados EXIF de fotos
Desenvolvido por Julio Amorim
GitHub: https://github.com/julioamorimdev/FileForge
Email: contato@julioamorim.com.br
`;
fs.writeFileSync(path.join(testDir, 'test-document.txt'), textContent, 'utf8');
console.log('✅ Texto criado: test-files/test-document.txt');
// 4. Criar um arquivo Markdown
console.log('📋 Gerando arquivo Markdown...');
const markdownContent = `# FileForge - Framework de Conversão
## 🔥 Visão Geral
O **FileForge** é um framework avançado para conversão de arquivos multi-formato, desenvolvido para ser:
- **Simples**: API unificada \`convert(input, output_format, options)\`
- **Poderoso**: Suporte a 15+ formatos com conversões inteligentes
- **Extensível**: Sistema de plugins para funcionalidades customizadas
## 📦 Instalação
### JavaScript/Node.js
\`\`\`bash
npm install fileforge
\`\`\`
### Python
\`\`\`bash
pip install fileforge
\`\`\`
## 🚀 Uso Rápido
### JavaScript
\`\`\`javascript
const { FileForge } = require('fileforge');
const forge = new FileForge();
// Conversão simples
await forge.convert('documento.pdf', 'txt');
// Com OCR
await forge.convert('imagem.jpg', 'txt', { ocr: true });
\`\`\`
### Python
\`\`\`python
from fileforge import FileForge
forge = FileForge()
# Conversão simples
await forge.convert('documento.pdf', 'txt')
\`\`\`
## 🎯 Recursos Principais
| Recurso | Descrição |
|---------|-----------|
| **Multi-formato** | 15+ formatos suportados |
| **OCR** | Extração de texto de imagens |
| **Metadados** | EXIF, propriedades de documentos |
| **Streaming** | Arquivos grandes sem sobrecarregar memória |
| **Batch** | Conversão em massa |
| **Plugins** | Sistema extensível |
## 🔧 Conversões Suportadas
- **PDF** ↔ TXT, Markdown, HTML, Imagens
- **DOCX** ↔ PDF, TXT, HTML, Markdown
- **Imagens** ↔ PDF, diferentes formatos
- **Dados** ↔ JSON, CSV, XLSX
## 📊 Performance
O FileForge foi otimizado para:
- ⚡ Processamento rápido
- 💾 Uso eficiente de memória
- ☁️ Ambientes serverless
- 🔄 Processamento paralelo
---
*Desenvolvido com ❤️ por [Julio Amorim](https://github.com/julioamorimdev)*
`;
fs.writeFileSync(path.join(testDir, 'test-document.md'), markdownContent, 'utf8');
console.log('✅ Markdown criado: test-files/test-document.md');
}
async function testRealConversions() {
console.log('\n🧪 Testando conversões reais...\n');
const testDir = './test-files';
const outputDir = './converted-files';
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
try {
// 1. Converter PNG para JPG
console.log('🔄 Convertendo PNG → JPG...');
await sharp(path.join(testDir, 'test-image.png'))
.jpeg({ quality: 90 })
.toFile(path.join(outputDir, 'converted-image.jpg'));
console.log('✅ Conversão PNG → JPG concluída');
// 2. Redimensionar imagem
console.log('🔄 Redimensionando imagem...');
await sharp(path.join(testDir, 'test-image.png'))
.resize(400, 300)
.png()
.toFile(path.join(outputDir, 'resized-image.png'));
console.log('✅ Redimensionamento concluído');
// 3. Converter Markdown para HTML
console.log('🔄 Convertendo Markdown → HTML...');
const markdownContent = fs.readFileSync(path.join(testDir, 'test-document.md'), 'utf8');
const htmlContent = `<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FileForge Documentation</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
code {
background: #f4f4f4;
padding: 2px 4px;
border-radius: 3px;
}
pre {
background: #f4f4f4;
padding: 10px;
border-radius: 5px;
overflow-x: auto;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
blockquote {
border-left: 4px solid #ddd;
margin: 0;
padding-left: 20px;
}
</style>
</head>
<body>
${marked(markdownContent)}
</body>
</html>`;
fs.writeFileSync(path.join(outputDir, 'converted-document.html'), htmlContent, 'utf8');
console.log('✅ Conversão Markdown → HTML concluída');
// 4. Converter texto para PDF
console.log('🔄 Convertendo TXT → PDF...');
const textContent = fs.readFileSync(path.join(testDir, 'test-document.txt'), 'utf8');
const textPdfDoc = await PDFDocument.create();
const textPage = textPdfDoc.addPage([595, 842]);
const { width: pageWidth, height: pageHeight } = textPage.getSize();
const fontSize = 12;
const margin = 50;
const lineHeight = fontSize * 1.4;
const maxWidth = pageWidth - (margin * 2);
// Quebrar texto em linhas
const lines = [];
const paragraphs = textContent.split('\n');
for (const paragraph of paragraphs) {
if (paragraph.trim() === '') {
lines.push('');
continue;
}
const words = paragraph.split(' ');
let currentLine = '';
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
// Estimativa simples de largura (6 pixels por caractere)
if (testLine.length * 6 <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
}
if (currentLine) lines.push(currentLine);
}
let y = pageHeight - margin;
let currentPage = textPage;
for (const line of lines) {
if (y < margin + lineHeight) {
// Nova página
currentPage = textPdfDoc.addPage([595, 842]);
y = pageHeight - margin;
}
if (line.trim() !== '') {
currentPage.drawText(line, {
x: margin,
y,
size: fontSize,
color: rgb(0, 0, 0),
});
}
y -= lineHeight;
}
const textPdfBytes = await textPdfDoc.save();
fs.writeFileSync(path.join(outputDir, 'converted-text.pdf'), textPdfBytes);
console.log('✅ Conversão TXT → PDF concluída');
// 5. Criar JSON de exemplo e converter para CSV
console.log('🔄 Convertendo JSON → CSV...');
const jsonData = [
{ id: 1, nome: 'FileForge', tipo: 'Framework', linguagem: 'JavaScript/Python' },
{ id: 2, nome: 'Sharp', tipo: 'Biblioteca', linguagem: 'JavaScript' },
{ id: 3, nome: 'PDF-lib', tipo: 'Biblioteca', linguagem: 'JavaScript' },
{ id: 4, nome: 'Tesseract.js', tipo: 'OCR', linguagem: 'JavaScript' },
{ id: 5, nome: 'Pillow', tipo: 'Biblioteca', linguagem: 'Python' }
];
// Salvar JSON
fs.writeFileSync(path.join(testDir, 'test-data.json'), JSON.stringify(jsonData, null, 2), 'utf8');
// Converter para CSV
const headers = Object.keys(jsonData[0]);
const csvLines = [headers.join(',')];
for (const item of jsonData) {
const values = headers.map(header => {
const value = item[header];
// Escapar vírgulas e aspas
if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
});
csvLines.push(values.join(','));
}
const csvContent = csvLines.join('\n');
fs.writeFileSync(path.join(outputDir, 'converted-data.csv'), csvContent, 'utf8');
console.log('✅ Conversão JSON → CSV concluída');
} catch (error) {
console.error('❌ Erro durante a conversão:', error.message);
}
}
async function showResults() {
console.log('\n📊 Resultados das Conversões:\n');
const outputDir = './converted-files';
if (fs.existsSync(outputDir)) {
const files = fs.readdirSync(outputDir);
for (const file of files) {
const filePath = path.join(outputDir, file);
const stats = fs.statSync(filePath);
const sizeKB = (stats.size / 1024).toFixed(2);
console.log(`📄 ${file} - ${sizeKB} KB`);
}
console.log(`\n✅ Total: ${files.length} arquivos convertidos`);
console.log(`📁 Localização: ${path.resolve(outputDir)}`);
} else {
console.log('❌ Diretório de saída não encontrado');
}
}
// Executar os testes
async function main() {
try {
await createTestFiles();
await testRealConversions();
await showResults();
console.log('\n🎉 Todos os testes de conversão foram executados com sucesso!');
console.log('🔍 Verifique os arquivos gerados nas pastas test-files/ e converted-files/');
console.log('\n💡 Para usar no seu código:');
console.log('const { FileForge } = require("./dist/index.js");');
} catch (error) {
console.error('❌ Erro durante a execução:', error);
}
}
// Executar se chamado diretamente
if (require.main === module) {
main();
}
module.exports = { createTestFiles, testRealConversions, showResults };