feat: comprehensive import progress tracking for all 7 formats
Add real-time progress reporting throughout the entire import pipeline
with a standardized API that works across all supported formats.
Workshop Team Feature Request:
- Eliminates "0% complete" hangs during AI extraction
- Shows continuous progress with entities/sec, throughput, ETA
- Reports contextual messages ("Processing page 5 of 23")
- Standardized progress API for CSV, PDF, Excel, JSON, Markdown, YAML, DOCX
Core Changes:
- Add FormatHandlerProgressHooks interface for extensible progress
- Wire up all 3 binary format handlers (CSV, PDF, Excel) with 7+ progress points
- Wire up all 4 text format importers (JSON, Markdown, YAML, DOCX)
- Add ImportProgress interface with stage, message, counts, throughput, ETA
- ImportCoordinator normalizes all format progress to standard interface
CLI Improvements:
- Import command now uses brain.import() directly with full progress
- Add --include-vfs flag to find command (v4.4.0 compatibility)
- Add --confidence and --weight options to add command
Documentation:
- docs/guides/standard-import-progress.md - Universal API guide
- docs/guides/import-progress-implementation.md - Developer guide
- docs/guides/import-progress-examples.md - Practical examples
- JSDoc on brain.import() with universal handler examples
Result: ONE progress handler works for ALL 7 formats with zero format-specific code!
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
e7ea9c4e4b
commit
d5576ffb56
20 changed files with 3967 additions and 52 deletions
370
docs/guides/import-progress-examples.md
Normal file
370
docs/guides/import-progress-examples.md
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
# Import Progress - Usage Examples
|
||||
|
||||
**How to Use Progress Tracking in Your Applications**
|
||||
|
||||
Brainy v4.5.0+ provides real-time progress tracking for **all 7 supported file formats** (CSV, PDF, Excel, JSON, Markdown, YAML, DOCX).
|
||||
|
||||
> **⚠️ KEY FEATURE:** The progress API is **100% standardized**. Write your progress handler ONCE and it works for ALL formats with zero format-specific code! See [Standard Import Progress API](./standard-import-progress.md) for the complete interface documentation.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Basic Progress Tracking
|
||||
|
||||
```typescript
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
import * as fs from 'fs'
|
||||
|
||||
const brain = await Brainy.create()
|
||||
|
||||
// Import with progress tracking
|
||||
const result = await brain.import(fs.readFileSync('large-file.xlsx'), {
|
||||
onProgress: (progress) => {
|
||||
console.log(`Progress: ${progress.stage}`)
|
||||
console.log(` Message: ${progress.message}`)
|
||||
console.log(` Entities: ${progress.entities || 0}`)
|
||||
console.log(` Relationships: ${progress.relationships || 0}`)
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Import complete: ${result.entities.length} entities created`)
|
||||
```
|
||||
|
||||
**Expected Output:**
|
||||
```
|
||||
Progress: detecting
|
||||
Message: Detecting format...
|
||||
Entities: 0
|
||||
Relationships: 0
|
||||
Progress: extracting
|
||||
Message: Loading Excel workbook...
|
||||
Entities: 0
|
||||
Relationships: 0
|
||||
Progress: extracting
|
||||
Message: Reading sheet: Sales (1/3)
|
||||
Entities: 0
|
||||
Relationships: 0
|
||||
Progress: extracting
|
||||
Message: Parsing Excel (33%)
|
||||
Entities: 0
|
||||
Relationships: 0
|
||||
Progress: extracting
|
||||
Message: Reading sheet: Products (2/3)
|
||||
Entities: 0
|
||||
Relationships: 0
|
||||
... (more progress updates)
|
||||
Progress: complete
|
||||
Message: Import complete
|
||||
Entities: 1523
|
||||
Relationships: 892
|
||||
Import complete: 1523 entities created
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Universal Progress Handler (Works for ALL Formats)
|
||||
|
||||
The examples below show format-specific messages, but **you don't need format-specific code**! The `ImportProgress` interface is the same for all formats:
|
||||
|
||||
```typescript
|
||||
// ONE HANDLER FOR ALL FORMATS!
|
||||
function universalProgressHandler(progress) {
|
||||
console.log(`[${progress.stage}] ${progress.message}`)
|
||||
|
||||
if (progress.processed && progress.total) {
|
||||
console.log(` Progress: ${progress.processed}/${progress.total}`)
|
||||
}
|
||||
|
||||
if (progress.entities || progress.relationships) {
|
||||
console.log(` Extracted: ${progress.entities || 0} entities, ${progress.relationships || 0} relationships`)
|
||||
}
|
||||
|
||||
if (progress.throughput && progress.eta) {
|
||||
console.log(` Rate: ${progress.throughput.toFixed(1)}/sec, ETA: ${Math.round(progress.eta/1000)}s`)
|
||||
}
|
||||
}
|
||||
|
||||
// Use it for ANY format!
|
||||
await brain.import(csvBuffer, { onProgress: universalProgressHandler })
|
||||
await brain.import(pdfBuffer, { onProgress: universalProgressHandler })
|
||||
await brain.import(excelBuffer, { onProgress: universalProgressHandler })
|
||||
await brain.import(jsonBuffer, { onProgress: universalProgressHandler })
|
||||
await brain.import(markdownString, { onProgress: universalProgressHandler })
|
||||
await brain.import(yamlBuffer, { onProgress: universalProgressHandler })
|
||||
await brain.import(docxBuffer, { onProgress: universalProgressHandler })
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 What Different Formats Look Like (Same Handler!)
|
||||
|
||||
The examples below show **what messages look like** for different formats using the **same universal handler** above.
|
||||
|
||||
### CSV Import (Row-by-Row Progress)
|
||||
|
||||
```typescript
|
||||
await brain.import(csvBuffer, {
|
||||
format: 'csv',
|
||||
onProgress: (progress) => {
|
||||
if (progress.stage === 'extracting') {
|
||||
// CSV reports: "Parsing CSV (45%)", "Extracted 1000 rows", etc.
|
||||
console.log(progress.message)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**CSV Progress Messages:**
|
||||
- ✅ "Detecting CSV encoding and delimiter..."
|
||||
- ✅ "Parsing CSV rows (delimiter: ",")"
|
||||
- ✅ "Parsed 75%" (via bytes processed)
|
||||
- ✅ "Extracted 1000 rows"
|
||||
- ✅ "Converting types: 5000/10000 rows..."
|
||||
- ✅ "CSV processing complete: 10000 rows"
|
||||
|
||||
---
|
||||
|
||||
### PDF Import (Page-by-Page Progress)
|
||||
|
||||
```typescript
|
||||
await brain.import(pdfBuffer, {
|
||||
format: 'pdf',
|
||||
onProgress: (progress) => {
|
||||
// PDF reports exact page numbers
|
||||
console.log(progress.message)
|
||||
// Example: "Processing page 5 of 23"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**PDF Progress Messages:**
|
||||
- ✅ "Loading PDF document..."
|
||||
- ✅ "Processing 23 pages..."
|
||||
- ✅ "Processing page 5 of 23"
|
||||
- ✅ "Parsed 22%" (via bytes processed)
|
||||
- ✅ "Extracted 156 items from PDF"
|
||||
- ✅ "PDF complete: 23 pages, 156 items extracted"
|
||||
|
||||
---
|
||||
|
||||
### Excel Import (Sheet-by-Sheet Progress)
|
||||
|
||||
```typescript
|
||||
await brain.import(excelBuffer, {
|
||||
format: 'excel',
|
||||
onProgress: (progress) => {
|
||||
// Excel reports sheet names
|
||||
console.log(progress.message)
|
||||
// Example: "Reading sheet: Q2 Sales (2/5)"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Excel Progress Messages:**
|
||||
- ✅ "Loading Excel workbook..."
|
||||
- ✅ "Processing 3 sheets..."
|
||||
- ✅ "Reading sheet: Sales (1/3)"
|
||||
- ✅ "Parsing Excel (33%)" (via bytes processed)
|
||||
- ✅ "Extracted 5234 rows from Excel"
|
||||
- ✅ "Excel complete: 3 sheets, 5234 rows"
|
||||
|
||||
---
|
||||
|
||||
### JSON Import (Node Traversal)
|
||||
|
||||
```typescript
|
||||
await brain.import(jsonBuffer, {
|
||||
format: 'json',
|
||||
onProgress: (progress) => {
|
||||
// JSON reports every 10 nodes
|
||||
console.log(`Processed ${progress.processed} nodes, found ${progress.entities} entities`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Markdown Import (Section-by-Section)
|
||||
|
||||
```typescript
|
||||
await brain.import(markdownString, {
|
||||
format: 'markdown',
|
||||
onProgress: (progress) => {
|
||||
console.log(`Section ${progress.processed}/${progress.total}`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Building Progress UI Components
|
||||
|
||||
### React Progress Bar
|
||||
|
||||
```typescript
|
||||
function ImportProgress({ file }: { file: File }) {
|
||||
const [progress, setProgress] = useState({
|
||||
stage: 'idle',
|
||||
message: '',
|
||||
percent: 0,
|
||||
entities: 0,
|
||||
relationships: 0
|
||||
})
|
||||
|
||||
const handleImport = async () => {
|
||||
const buffer = await file.arrayBuffer()
|
||||
|
||||
await brain.import(Buffer.from(buffer), {
|
||||
onProgress: (p) => {
|
||||
setProgress({
|
||||
stage: p.stage,
|
||||
message: p.message,
|
||||
// Estimate percentage from stage
|
||||
percent: {
|
||||
detecting: 10,
|
||||
extracting: 50,
|
||||
'storing-vfs': 80,
|
||||
'storing-graph': 90,
|
||||
complete: 100
|
||||
}[p.stage] || 0,
|
||||
entities: p.entities || 0,
|
||||
relationships: p.relationships || 0
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ProgressBar value={progress.percent} />
|
||||
<p>{progress.message}</p>
|
||||
<p>Entities: {progress.entities} | Relationships: {progress.relationships}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CLI Progress Spinner
|
||||
|
||||
```typescript
|
||||
import ora from 'ora'
|
||||
|
||||
const spinner = ora('Starting import...').start()
|
||||
|
||||
await brain.import(buffer, {
|
||||
onProgress: (progress) => {
|
||||
spinner.text = progress.message
|
||||
|
||||
if (progress.stage === 'complete') {
|
||||
spinner.succeed(`Import complete: ${progress.entities} entities`)
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**CLI Output:**
|
||||
```
|
||||
⠋ Detecting format...
|
||||
⠙ Loading Excel workbook...
|
||||
⠹ Reading sheet: Sales (1/3)
|
||||
⠸ Parsing Excel (33%)
|
||||
⠼ Reading sheet: Products (2/3)
|
||||
...
|
||||
✔ Import complete: 1523 entities
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Progress Dashboard with ETA
|
||||
|
||||
```typescript
|
||||
let startTime = Date.now()
|
||||
let lastUpdate = startTime
|
||||
|
||||
await brain.import(buffer, {
|
||||
onProgress: (progress) => {
|
||||
const elapsed = Date.now() - startTime
|
||||
const rate = progress.entities / (elapsed / 1000) // entities/sec
|
||||
|
||||
console.clear()
|
||||
console.log('Import Progress Dashboard')
|
||||
console.log('========================')
|
||||
console.log(`Stage: ${progress.stage}`)
|
||||
console.log(`Status: ${progress.message}`)
|
||||
console.log(`Entities: ${progress.entities}`)
|
||||
console.log(`Relationships: ${progress.relationships}`)
|
||||
console.log(`Rate: ${rate.toFixed(1)} entities/sec`)
|
||||
console.log(`Elapsed: ${(elapsed / 1000).toFixed(1)}s`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Advanced: Format-Specific Optimization
|
||||
|
||||
### Detecting Format to Show Appropriate Progress
|
||||
|
||||
```typescript
|
||||
const formatMessages = {
|
||||
csv: (p) => `CSV: ${p.message}`,
|
||||
pdf: (p) => `PDF: ${p.message}`,
|
||||
excel: (p) => `Excel: ${p.message}`,
|
||||
json: (p) => `JSON: ${p.processed} nodes, ${p.entities} entities`,
|
||||
markdown: (p) => `Markdown: Section ${p.processed}/${p.total}`,
|
||||
yaml: (p) => `YAML: ${p.processed} nodes`,
|
||||
docx: (p) => `DOCX: ${p.processed} paragraphs`
|
||||
}
|
||||
|
||||
await brain.import(buffer, {
|
||||
onProgress: (progress) => {
|
||||
// Format is available in progress.stage metadata
|
||||
const message = formatMessages[detectedFormat]?.(progress) || progress.message
|
||||
console.log(message)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Performance Tips
|
||||
|
||||
### Throttle UI Updates
|
||||
|
||||
```typescript
|
||||
let lastUIUpdate = 0
|
||||
const THROTTLE_MS = 100 // Update UI max once per 100ms
|
||||
|
||||
await brain.import(buffer, {
|
||||
onProgress: (progress) => {
|
||||
const now = Date.now()
|
||||
if (now - lastUIUpdate < THROTTLE_MS && progress.stage !== 'complete') {
|
||||
return // Skip this update
|
||||
}
|
||||
|
||||
lastUIUpdate = now
|
||||
updateUI(progress) // Only update every 100ms
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Note:** Brainy already throttles progress callbacks internally, but additional UI throttling can help with heavy rendering.
|
||||
|
||||
---
|
||||
|
||||
## 📝 Summary
|
||||
|
||||
✅ **All 7 formats** have consistent progress reporting
|
||||
✅ **Real-time updates** during long imports (no more "0%" hangs)
|
||||
✅ **Contextual messages** show exactly what's happening
|
||||
✅ **Build reliable tools** with standardized progress callbacks
|
||||
✅ **Workshop team problem SOLVED** - users see progress throughout import
|
||||
|
||||
**Files Modified:**
|
||||
- 3 handlers: `csvHandler.ts`, `pdfHandler.ts`, `excelHandler.ts`
|
||||
- 7 importers: `SmartCSVImporter.ts`, `SmartPDFImporter.ts`, `SmartExcelImporter.ts`, `SmartJSONImporter.ts`, `SmartMarkdownImporter.ts`, `SmartYAMLImporter.ts`, `SmartDOCXImporter.ts`
|
||||
|
||||
**Result:** Comprehensive, consistent progress tracking across ALL import formats!
|
||||
734
docs/guides/import-progress-implementation.md
Normal file
734
docs/guides/import-progress-implementation.md
Normal file
|
|
@ -0,0 +1,734 @@
|
|||
# Import Progress Implementation Guide
|
||||
**For Developers: How to Add Progress Tracking to ANY File Handler**
|
||||
|
||||
> This guide shows the **standard pattern** for implementing rich progress tracking in Brainy import handlers. Follow this template for **all 7 supported formats** (CSV, PDF, Excel, JSON, Markdown, YAML, DOCX) or any future file format.
|
||||
|
||||
---
|
||||
|
||||
## 📊 Supported Formats & Consistent Progress Reporting
|
||||
|
||||
> **⚠️ IMPORTANT FOR DEVELOPERS:** The public API (`ImportProgress`) is 100% standardized across all formats. You can build ONE progress handler that works for CSV, PDF, Excel, JSON, Markdown, YAML, and DOCX with **zero format-specific code**. See [Standard Import Progress API](./standard-import-progress.md) for details.
|
||||
|
||||
**ALL 7 formats now have consistent, standardized progress reporting** for building reliable import tools:
|
||||
|
||||
| Format | Category | Progress Points | File Location | Status |
|
||||
|--------|----------|-----------------|---------------|--------|
|
||||
| **CSV** | Tabular | Parsing → Row extraction → Type conversion → Complete | `handlers/csvHandler.ts` + `SmartCSVImporter.ts` | ✅ Complete |
|
||||
| **PDF** | Document | Loading → Page-by-page → Item extraction → Complete | `handlers/pdfHandler.ts` + `SmartPDFImporter.ts` | ✅ Complete |
|
||||
| **Excel** | Tabular | Loading → Sheet-by-sheet → Row extraction → Type conversion → Complete | `handlers/excelHandler.ts` + `SmartExcelImporter.ts` | ✅ Complete |
|
||||
| **JSON** | Structured | Parsing → Node traversal (every 10 nodes) → Complete | `SmartJSONImporter.ts` | ✅ Complete |
|
||||
| **Markdown** | Document | Parsing → Section-by-section → Complete | `SmartMarkdownImporter.ts` | ✅ Complete |
|
||||
| **YAML** | Structured | Parsing → Node traversal (every 10 nodes) → Complete | `SmartYAMLImporter.ts` | ✅ Complete |
|
||||
| **DOCX** | Document | Parsing → Paragraph-by-paragraph (every 10) → Complete | `SmartDOCXImporter.ts` | ✅ Complete |
|
||||
|
||||
### The Standard Public API
|
||||
|
||||
**Developers calling `brain.import()` see ONE standardized interface** regardless of format:
|
||||
|
||||
```typescript
|
||||
// THE PUBLIC API - Same for ALL 7 formats!
|
||||
brain.import(buffer, {
|
||||
onProgress: (progress: ImportProgress) => {
|
||||
// These fields work for CSV, PDF, Excel, JSON, Markdown, YAML, DOCX
|
||||
progress.stage // 'detecting' | 'extracting' | 'storing-vfs' | 'storing-graph' | 'complete'
|
||||
progress.message // Human-readable status (varies by format, always readable)
|
||||
progress.processed // Items processed (optional)
|
||||
progress.total // Total items (optional)
|
||||
progress.entities // Entities extracted (optional)
|
||||
progress.relationships // Relationships inferred (optional)
|
||||
progress.throughput // Items/sec (optional, during extraction)
|
||||
progress.eta // Time remaining in ms (optional)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Internal Implementation** (for developers adding new format handlers):
|
||||
|
||||
The table below shows how formats implement progress *internally*. Normal developers don't need to know this - they just use the standard `ImportProgress` interface above!
|
||||
|
||||
```typescript
|
||||
// Internal: Binary formats use handler hooks (you added these!)
|
||||
interface FormatHandlerProgressHooks {
|
||||
onBytesProcessed?: (bytes: number) => void
|
||||
onCurrentItem?: (message: string) => void
|
||||
onDataExtracted?: (count: number, total?: number) => void
|
||||
}
|
||||
|
||||
// Internal: Text formats use importer callbacks
|
||||
interface ImporterProgressCallback {
|
||||
onProgress?: (stats: { processed, total, entities, relationships }) => void
|
||||
}
|
||||
|
||||
// Both are converted to ImportProgress by ImportCoordinator!
|
||||
```
|
||||
|
||||
### Developer Benefits
|
||||
|
||||
✅ **Consistent API** - Same pattern across all 7 formats
|
||||
✅ **Throttled Updates** - Progress reported every 10-1000 items (no spam)
|
||||
✅ **Contextual Messages** - "Processing page 5 of 23", "Reading sheet: Sales (2/5)"
|
||||
✅ **Real-time Estimates** - Users see progress during long imports
|
||||
✅ **Build Monitoring Tools** - Reliable progress data for UIs, dashboards, CLI tools
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Overview
|
||||
|
||||
As of v4.5.0, Brainy supports comprehensive, multi-dimensional progress tracking for imports:
|
||||
- **Bytes processed** (always available, most deterministic)
|
||||
- **Entities extracted** (AI extraction phase)
|
||||
- **Stage-specific metrics** (parsing: MB/s, extraction: entities/s)
|
||||
- **Time estimates** (remaining time, total time)
|
||||
- **Context information** ("Processing page 5 of 23")
|
||||
|
||||
All handlers follow a simple, consistent pattern using **progress hooks**.
|
||||
|
||||
---
|
||||
|
||||
## 📋 The Progress Hooks Pattern
|
||||
|
||||
### 1. Progress Hooks Interface
|
||||
|
||||
```typescript
|
||||
export interface FormatHandlerProgressHooks {
|
||||
/**
|
||||
* Report bytes processed
|
||||
* Call this as you read/parse the file
|
||||
*/
|
||||
onBytesProcessed?: (bytes: number) => void
|
||||
|
||||
/**
|
||||
* Set current processing context
|
||||
* Examples: "Processing page 5", "Reading sheet: Q2 Sales"
|
||||
*/
|
||||
onCurrentItem?: (item: string) => void
|
||||
|
||||
/**
|
||||
* Report structured data extraction progress
|
||||
* Examples: "Extracted 100 rows", "Parsed 50 paragraphs"
|
||||
*/
|
||||
onDataExtracted?: (count: number, total?: number) => void
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Handler Options (Automatic)
|
||||
|
||||
Progress hooks are automatically passed to your handler via `FormatHandlerOptions`:
|
||||
|
||||
```typescript
|
||||
export interface FormatHandlerOptions {
|
||||
// ... existing options ...
|
||||
|
||||
/**
|
||||
* Progress hooks (v4.5.0)
|
||||
* Handlers call these to report progress during processing
|
||||
*/
|
||||
progressHooks?: FormatHandlerProgressHooks
|
||||
|
||||
/**
|
||||
* Total file size in bytes (v4.5.0)
|
||||
* Used for progress percentage calculation
|
||||
*/
|
||||
totalBytes?: number
|
||||
}
|
||||
```
|
||||
|
||||
**You don't need to modify FormatHandlerOptions** - it's already done!
|
||||
|
||||
### 3. Standard Implementation Pattern
|
||||
|
||||
Every handler follows these 5 steps:
|
||||
|
||||
```typescript
|
||||
async process(data: Buffer | string, options: FormatHandlerOptions): Promise<ProcessedData> {
|
||||
const progressHooks = options.progressHooks // Step 1: Get hooks
|
||||
|
||||
// Step 2: Report initial progress
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem('Starting import...')
|
||||
}
|
||||
|
||||
// Step 3: Report bytes as you process
|
||||
const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data)
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(0) // Start
|
||||
}
|
||||
|
||||
// ... do parsing ...
|
||||
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(buffer.length) // Complete
|
||||
}
|
||||
|
||||
// Step 4: Report data extraction
|
||||
if (progressHooks?.onDataExtracted) {
|
||||
progressHooks.onDataExtracted(data.length, data.length)
|
||||
}
|
||||
|
||||
// Step 5: Report completion
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Complete: ${data.length} items processed`)
|
||||
}
|
||||
|
||||
return { format, data, metadata }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Complete Example: CSV Handler
|
||||
|
||||
Here's the **ACTUAL implementation** from CSV handler showing all the key progress points:
|
||||
|
||||
```typescript
|
||||
async process(data: Buffer | string, options: FormatHandlerOptions): Promise<ProcessedData> {
|
||||
const startTime = Date.now()
|
||||
const progressHooks = options.progressHooks // ✅ Step 1
|
||||
|
||||
// Convert to buffer if string
|
||||
const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8')
|
||||
const totalBytes = buffer.length
|
||||
|
||||
// ✅ Step 2: Report start
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(0)
|
||||
}
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem('Detecting CSV encoding and delimiter...')
|
||||
}
|
||||
|
||||
// Detect encoding
|
||||
const detectedEncoding = options.encoding || this.detectEncodingSafe(buffer)
|
||||
const text = buffer.toString(detectedEncoding as BufferEncoding)
|
||||
|
||||
// Detect delimiter
|
||||
const delimiter = options.csvDelimiter || this.detectDelimiter(text)
|
||||
|
||||
// ✅ Progress update: Parsing phase
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Parsing CSV rows (delimiter: "${delimiter}")...`)
|
||||
}
|
||||
|
||||
// Parse CSV
|
||||
const records = parse(text, { /* options */ })
|
||||
|
||||
// ✅ Step 3: Report bytes processed (entire file parsed)
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(totalBytes)
|
||||
}
|
||||
|
||||
const data = Array.isArray(records) ? records : [records]
|
||||
|
||||
// ✅ Step 4: Report data extraction
|
||||
if (progressHooks?.onDataExtracted) {
|
||||
progressHooks.onDataExtracted(data.length, data.length)
|
||||
}
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Extracted ${data.length} rows, inferring types...`)
|
||||
}
|
||||
|
||||
// Type inference and conversion
|
||||
const fields = data.length > 0 ? Object.keys(data[0]) : []
|
||||
const types = this.inferFieldTypes(data)
|
||||
|
||||
const convertedData = data.map((row, index) => {
|
||||
const converted = this.convertRow(row, types)
|
||||
|
||||
// ✅ Progress update every 1000 rows (avoid spam)
|
||||
if (progressHooks?.onCurrentItem && index > 0 && index % 1000 === 0) {
|
||||
progressHooks.onCurrentItem(`Converting types: ${index}/${data.length} rows...`)
|
||||
}
|
||||
|
||||
return converted
|
||||
})
|
||||
|
||||
// ✅ Step 5: Report completion
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`CSV processing complete: ${convertedData.length} rows`)
|
||||
}
|
||||
|
||||
return {
|
||||
format: this.format,
|
||||
data: convertedData,
|
||||
metadata: { /* ... */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Key Progress Points in CSV Handler
|
||||
|
||||
| Progress Point | Hook Used | Message Example |
|
||||
|----------------|-----------|-----------------|
|
||||
| **Start** | `onCurrentItem` | "Detecting CSV encoding and delimiter..." |
|
||||
| **Start bytes** | `onBytesProcessed(0)` | 0 bytes |
|
||||
| **Parsing** | `onCurrentItem` | "Parsing CSV rows (delimiter: \",\")..." |
|
||||
| **Bytes complete** | `onBytesProcessed(totalBytes)` | All bytes read |
|
||||
| **Data extracted** | `onDataExtracted(count, total)` | Number of rows extracted |
|
||||
| **Type conversion** | `onCurrentItem` (every 1000 rows) | "Converting types: 5000/10000 rows..." |
|
||||
| **Complete** | `onCurrentItem` | "CSV processing complete: 10000 rows" |
|
||||
|
||||
---
|
||||
|
||||
## 📖 Implementation Guide by File Type
|
||||
|
||||
### Supported Formats
|
||||
|
||||
Brainy supports **7 file formats** with full progress tracking:
|
||||
|
||||
**Binary Formats** (use handlers):
|
||||
1. **CSV** - Row-by-row parsing with type inference
|
||||
2. **PDF** - Page-by-page extraction with table detection
|
||||
3. **Excel** - Sheet-by-sheet processing with formula evaluation
|
||||
|
||||
**Text/Structured Formats** (parse inline):
|
||||
4. **JSON** - Recursive traversal of nested structures
|
||||
5. **Markdown** - Section-by-section with heading extraction
|
||||
6. **YAML** - Hierarchical traversal with relationship inference
|
||||
7. **DOCX** - Paragraph-by-paragraph with structure analysis
|
||||
|
||||
---
|
||||
|
||||
### PDF Handler (Multi-Page)
|
||||
|
||||
```typescript
|
||||
async process(data: Buffer, options: FormatHandlerOptions): Promise<ProcessedData> {
|
||||
const progressHooks = options.progressHooks
|
||||
const totalBytes = data.length
|
||||
|
||||
// Report start
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem('Loading PDF document...')
|
||||
}
|
||||
|
||||
const pdfDoc = await loadPDF(data)
|
||||
const totalPages = pdfDoc.numPages
|
||||
|
||||
const extractedData: any[] = []
|
||||
let bytesProcessed = 0
|
||||
|
||||
for (let pageNum = 1; pageNum <= totalPages; pageNum++) {
|
||||
// ✅ Report current page
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Processing page ${pageNum} of ${totalPages}`)
|
||||
}
|
||||
|
||||
const page = await pdfDoc.getPage(pageNum)
|
||||
const text = await page.getTextContent()
|
||||
extractedData.push(this.processPageText(text))
|
||||
|
||||
// ✅ Estimate bytes processed (pages are sequential)
|
||||
bytesProcessed = Math.floor((pageNum / totalPages) * totalBytes)
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(bytesProcessed)
|
||||
}
|
||||
|
||||
// ✅ Report extraction progress
|
||||
if (progressHooks?.onDataExtracted) {
|
||||
progressHooks.onDataExtracted(pageNum, totalPages)
|
||||
}
|
||||
}
|
||||
|
||||
// Final progress
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(totalBytes)
|
||||
}
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`PDF complete: ${totalPages} pages processed`)
|
||||
}
|
||||
|
||||
return { format: 'pdf', data: extractedData, metadata: { /* ... */ } }
|
||||
}
|
||||
```
|
||||
|
||||
### Excel Handler (Multi-Sheet)
|
||||
|
||||
```typescript
|
||||
async process(data: Buffer, options: FormatHandlerOptions): Promise<ProcessedData> {
|
||||
const progressHooks = options.progressHooks
|
||||
const totalBytes = data.length
|
||||
|
||||
// Load workbook
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem('Loading Excel workbook...')
|
||||
}
|
||||
|
||||
const workbook = XLSX.read(data)
|
||||
const sheetNames = options.excelSheets === 'all'
|
||||
? workbook.SheetNames
|
||||
: (options.excelSheets || [workbook.SheetNames[0]])
|
||||
|
||||
const allData: any[] = []
|
||||
let bytesProcessed = 0
|
||||
|
||||
for (let i = 0; i < sheetNames.length; i++) {
|
||||
const sheetName = sheetNames[i]
|
||||
|
||||
// ✅ Report current sheet
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Reading sheet: ${sheetName} (${i + 1}/${sheetNames.length})`)
|
||||
}
|
||||
|
||||
const sheet = workbook.Sheets[sheetName]
|
||||
const sheetData = XLSX.utils.sheet_to_json(sheet)
|
||||
allData.push(...sheetData)
|
||||
|
||||
// ✅ Estimate bytes processed (sheets processed sequentially)
|
||||
bytesProcessed = Math.floor(((i + 1) / sheetNames.length) * totalBytes)
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(bytesProcessed)
|
||||
}
|
||||
|
||||
// ✅ Report data extraction
|
||||
if (progressHooks?.onDataExtracted) {
|
||||
progressHooks.onDataExtracted(allData.length, undefined) // Total unknown until done
|
||||
}
|
||||
}
|
||||
|
||||
// Final progress
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(totalBytes)
|
||||
}
|
||||
if (progressHooks?.onCurrentItem) {
|
||||
progressHooks.onCurrentItem(`Excel complete: ${sheetNames.length} sheets, ${allData.length} rows`)
|
||||
}
|
||||
|
||||
return { format: 'xlsx', data: allData, metadata: { /* ... */ } }
|
||||
}
|
||||
```
|
||||
|
||||
### JSON Importer (Recursive Traversal)
|
||||
|
||||
```typescript
|
||||
async extract(data: any, options: SmartJSONOptions = {}): Promise<SmartJSONResult> {
|
||||
// ✅ Report parsing start
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Parse JSON if string
|
||||
let jsonData = typeof data === 'string' ? JSON.parse(data) : data
|
||||
|
||||
// ✅ Report parsing complete
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Traverse and extract (reports progress every 10 nodes)
|
||||
const entities: ExtractedJSONEntity[] = []
|
||||
const relationships: ExtractedJSONRelationship[] = []
|
||||
let nodesProcessed = 0
|
||||
|
||||
await this.traverseJSON(
|
||||
jsonData,
|
||||
entities,
|
||||
relationships,
|
||||
() => {
|
||||
nodesProcessed++
|
||||
if (nodesProcessed % 10 === 0) {
|
||||
options.onProgress?.({
|
||||
processed: nodesProcessed,
|
||||
entities: entities.length,
|
||||
relationships: relationships.length
|
||||
})
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// ✅ Report completion
|
||||
options.onProgress?.({
|
||||
processed: nodesProcessed,
|
||||
entities: entities.length,
|
||||
relationships: relationships.length
|
||||
})
|
||||
|
||||
return { nodesProcessed, entitiesExtracted: entities.length, ... }
|
||||
}
|
||||
```
|
||||
|
||||
### Markdown Importer (Section-Based)
|
||||
|
||||
```typescript
|
||||
async extract(markdown: string, options: SmartMarkdownOptions = {}): Promise<SmartMarkdownResult> {
|
||||
// ✅ Report parsing start
|
||||
options.onProgress?.({ processed: 0, total: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Parse markdown into sections
|
||||
const parsedSections = this.parseMarkdown(markdown, options)
|
||||
|
||||
// ✅ Report parsing complete
|
||||
options.onProgress?.({ processed: 0, total: parsedSections.length, entities: 0, relationships: 0 })
|
||||
|
||||
// Process each section (reports progress after each section)
|
||||
const sections: MarkdownSection[] = []
|
||||
for (let i = 0; i < parsedSections.length; i++) {
|
||||
const section = await this.processSection(parsedSections[i], options)
|
||||
sections.push(section)
|
||||
|
||||
options.onProgress?.({
|
||||
processed: i + 1,
|
||||
total: parsedSections.length,
|
||||
entities: sections.reduce((sum, s) => sum + s.entities.length, 0),
|
||||
relationships: sections.reduce((sum, s) => sum + s.relationships.length, 0)
|
||||
})
|
||||
}
|
||||
|
||||
// ✅ Report completion
|
||||
options.onProgress?.({
|
||||
processed: sections.length,
|
||||
total: sections.length,
|
||||
entities: sections.reduce((sum, s) => sum + s.entities.length, 0),
|
||||
relationships: sections.reduce((sum, s) => sum + s.relationships.length, 0)
|
||||
})
|
||||
|
||||
return { sectionsProcessed: sections.length, ... }
|
||||
}
|
||||
```
|
||||
|
||||
### YAML Importer (Hierarchical)
|
||||
|
||||
```typescript
|
||||
async extract(yamlContent: string | Buffer, options: SmartYAMLOptions = {}): Promise<SmartYAMLResult> {
|
||||
// ✅ Report parsing start
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Parse YAML
|
||||
const yamlString = typeof yamlContent === 'string' ? yamlContent : yamlContent.toString('utf-8')
|
||||
const data = yaml.load(yamlString)
|
||||
|
||||
// ✅ Report parsing complete
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Traverse YAML structure (reports progress every 10 nodes)
|
||||
// ... similar to JSON traversal ...
|
||||
|
||||
// ✅ Report completion (already implemented)
|
||||
options.onProgress?.({
|
||||
processed: nodesProcessed,
|
||||
entities: entities.length,
|
||||
relationships: relationships.length
|
||||
})
|
||||
|
||||
return { nodesProcessed, entitiesExtracted: entities.length, ... }
|
||||
}
|
||||
```
|
||||
|
||||
### DOCX Importer (Paragraph-Based)
|
||||
|
||||
```typescript
|
||||
async extract(buffer: Buffer, options: SmartDOCXOptions = {}): Promise<SmartDOCXResult> {
|
||||
// ✅ Report parsing start
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Extract text and HTML using Mammoth
|
||||
const textResult = await mammoth.extractRawText({ buffer })
|
||||
const htmlResult = await mammoth.convertToHtml({ buffer })
|
||||
|
||||
// ✅ Report parsing complete
|
||||
options.onProgress?.({ processed: 0, entities: 0, relationships: 0 })
|
||||
|
||||
// Process paragraphs (reports progress every 10 paragraphs)
|
||||
const paragraphs = textResult.value.split(/\n\n+/).filter(p => p.trim().length >= minLength)
|
||||
|
||||
for (let i = 0; i < paragraphs.length; i++) {
|
||||
await this.processParagraph(paragraphs[i])
|
||||
|
||||
if (i % 10 === 0) {
|
||||
options.onProgress?.({
|
||||
processed: i + 1,
|
||||
entities: entities.length,
|
||||
relationships: relationships.length
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ Report completion (already implemented)
|
||||
options.onProgress?.({
|
||||
processed: paragraphs.length,
|
||||
entities: entities.length,
|
||||
relationships: relationships.length
|
||||
})
|
||||
|
||||
return { paragraphsProcessed: paragraphs.length, ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Best Practices
|
||||
|
||||
### 1. Always Check if Hooks Exist
|
||||
|
||||
Progress hooks are **optional**. Always check before calling:
|
||||
|
||||
```typescript
|
||||
// ✅ Good - safe
|
||||
if (progressHooks?.onBytesProcessed) {
|
||||
progressHooks.onBytesProcessed(bytes)
|
||||
}
|
||||
|
||||
// ❌ Bad - will crash if hooks undefined
|
||||
progressHooks.onBytesProcessed(bytes) // TypeError!
|
||||
```
|
||||
|
||||
### 2. Report Bytes at Start and End
|
||||
|
||||
```typescript
|
||||
// ✅ Good - clear start and end
|
||||
progressHooks?.onBytesProcessed(0) // Start
|
||||
// ... processing ...
|
||||
progressHooks?.onBytesProcessed(totalBytes) // End
|
||||
|
||||
// ❌ Bad - no clear boundaries
|
||||
// ... just start processing without reporting start
|
||||
```
|
||||
|
||||
### 3. Throttle Frequent Updates
|
||||
|
||||
```typescript
|
||||
// ✅ Good - report every 1000 items
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
processItem(items[i])
|
||||
|
||||
if (i > 0 && i % 1000 === 0) {
|
||||
progressHooks?.onCurrentItem(`Processing: ${i}/${items.length}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ Bad - report EVERY item (spam!)
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
processItem(items[i])
|
||||
progressHooks?.onCurrentItem(`Processing: ${i}/${items.length}`) // 1M callbacks!
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Provide Contextual Messages
|
||||
|
||||
```typescript
|
||||
// ✅ Good - specific and helpful
|
||||
progressHooks?.onCurrentItem('Parsing CSV rows (delimiter: ",")')
|
||||
progressHooks?.onCurrentItem('Processing page 5 of 23')
|
||||
progressHooks?.onCurrentItem('Reading sheet: Q2 Sales Data')
|
||||
|
||||
// ❌ Bad - vague
|
||||
progressHooks?.onCurrentItem('Processing...')
|
||||
progressHooks?.onCurrentItem('Working...')
|
||||
```
|
||||
|
||||
### 5. Report Data Extraction with Totals (if known)
|
||||
|
||||
```typescript
|
||||
// ✅ Good - total known
|
||||
progressHooks?.onDataExtracted(100, 1000) // 100 of 1000 rows
|
||||
|
||||
// ✅ Also good - total unknown (streaming)
|
||||
progressHooks?.onDataExtracted(100, undefined) // 100 rows so far
|
||||
|
||||
// ✅ Also good - complete
|
||||
progressHooks?.onDataExtracted(1000, 1000) // All 1000 rows
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Testing Your Handler
|
||||
|
||||
### Manual Test
|
||||
|
||||
```typescript
|
||||
import { CSVHandler } from './csvHandler.js'
|
||||
import * as fs from 'fs'
|
||||
|
||||
const handler = new CSVHandler()
|
||||
const data = fs.readFileSync('./test.csv')
|
||||
|
||||
const result = await handler.process(data, {
|
||||
filename: 'test.csv',
|
||||
progressHooks: {
|
||||
onBytesProcessed: (bytes) => {
|
||||
console.log(`Bytes: ${bytes}`)
|
||||
},
|
||||
onCurrentItem: (item) => {
|
||||
console.log(`Status: ${item}`)
|
||||
},
|
||||
onDataExtracted: (count, total) => {
|
||||
console.log(`Extracted: ${count}${total ? `/${total}` : ''}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Complete: ${result.data.length} rows`)
|
||||
```
|
||||
|
||||
### Expected Output
|
||||
|
||||
```
|
||||
Status: Detecting CSV encoding and delimiter...
|
||||
Bytes: 0
|
||||
Status: Parsing CSV rows (delimiter: ",")...
|
||||
Bytes: 52438
|
||||
Extracted: 1000/1000
|
||||
Status: Extracted 1000 rows, inferring types...
|
||||
Status: CSV processing complete: 1000 rows
|
||||
Complete: 1000 rows
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Progress Flow Diagram
|
||||
|
||||
```
|
||||
User Imports File
|
||||
↓
|
||||
ImportManager
|
||||
↓
|
||||
Creates ProgressTracker
|
||||
↓
|
||||
Calls Handler.process() with progressHooks
|
||||
↓
|
||||
Handler Reports Progress:
|
||||
├─ onBytesProcessed(0) → ProgressTracker → overall_progress calculated
|
||||
├─ onCurrentItem("Parsing...") → ProgressTracker → stage_message updated
|
||||
├─ onBytesProcessed(bytes) → ProgressTracker → bytes_per_second calculated
|
||||
├─ onDataExtracted(count) → ProgressTracker → entities_extracted updated
|
||||
└─ onCurrentItem("Complete") → ProgressTracker → final progress
|
||||
↓
|
||||
ProgressTracker emits to callback (throttled 100ms)
|
||||
↓
|
||||
User sees:
|
||||
"Overall: 45% | PARSING | 12.5 MB/s | Parsing CSV rows..."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Checklist for New Handlers
|
||||
|
||||
When implementing a new file format handler:
|
||||
|
||||
- [ ] Get `progressHooks` from `options`
|
||||
- [ ] Get `totalBytes` (if available)
|
||||
- [ ] Report `onBytesProcessed(0)` at start
|
||||
- [ ] Report `onCurrentItem()` for key stages
|
||||
- [ ] Report `onBytesProcessed()` as you process
|
||||
- [ ] Report `onDataExtracted()` when you extract data
|
||||
- [ ] Throttle frequent updates (every 1000 items max)
|
||||
- [ ] Report `onBytesProcessed(totalBytes)` at end
|
||||
- [ ] Report final `onCurrentItem()` with summary
|
||||
- [ ] Test with progress callback to verify output
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Summary
|
||||
|
||||
**The Pattern (5 Steps)**:
|
||||
1. Get `progressHooks` from options
|
||||
2. Report start (`onBytesProcessed(0)`, `onCurrentItem("Starting...")`)
|
||||
3. Report progress as you process (`onBytesProcessed(bytes)`, `onCurrentItem("Page 5...")`)
|
||||
4. Report data extraction (`onDataExtracted(count, total)`)
|
||||
5. Report completion (`onBytesProcessed(totalBytes)`, `onCurrentItem("Complete")`)
|
||||
|
||||
**Always Check**: `progressHooks?.method()`
|
||||
|
||||
**Throttle**: Report every N items, not every single item
|
||||
|
||||
**Context**: Provide specific, helpful messages
|
||||
|
||||
**Testing**: Use manual test with console.log callbacks
|
||||
|
||||
---
|
||||
|
||||
**This pattern makes it trivial to add progress tracking to ANY file format. Copy this template and adapt for your handler!**
|
||||
453
docs/guides/standard-import-progress.md
Normal file
453
docs/guides/standard-import-progress.md
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
# Standard Import Progress API
|
||||
|
||||
## ✅ Build Once, Works for ALL Formats
|
||||
|
||||
**Brainy provides a 100% standardized progress API** - write your UI/tool once, and it works for all 7 supported formats (CSV, PDF, Excel, JSON, Markdown, YAML, DOCX) with **zero format-specific code**.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 The Standard Interface
|
||||
|
||||
### One Interface for Everything
|
||||
|
||||
```typescript
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
|
||||
const brain = await Brainy.create()
|
||||
|
||||
// THIS CODE WORKS FOR ALL 7 FORMATS - NO FORMAT-SPECIFIC LOGIC NEEDED!
|
||||
await brain.import(anyBuffer, {
|
||||
onProgress: (progress) => {
|
||||
// Standard fields - ALWAYS available regardless of format
|
||||
console.log(progress.stage) // Current stage
|
||||
console.log(progress.message) // Human-readable status
|
||||
|
||||
// Optional fields - available when relevant
|
||||
console.log(progress.processed) // Items processed so far
|
||||
console.log(progress.total) // Total items (if known)
|
||||
console.log(progress.entities) // Entities extracted
|
||||
console.log(progress.relationships) // Relationships inferred
|
||||
console.log(progress.throughput) // Items/sec (during extraction)
|
||||
console.log(progress.eta) // Time remaining in ms
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### The Complete Interface
|
||||
|
||||
```typescript
|
||||
interface ImportProgress {
|
||||
// === ALWAYS PRESENT ===
|
||||
|
||||
/** High-level stage (5 stages for all formats) */
|
||||
stage: 'detecting' | 'extracting' | 'storing-vfs' | 'storing-graph' | 'complete'
|
||||
|
||||
/** Human-readable status message */
|
||||
message: string
|
||||
|
||||
// === AVAILABLE WHEN RELEVANT ===
|
||||
|
||||
/** Items processed (rows, pages, nodes, etc.) */
|
||||
processed?: number
|
||||
|
||||
/** Total items to process (if known ahead of time) */
|
||||
total?: number
|
||||
|
||||
/** Entities extracted so far */
|
||||
entities?: number
|
||||
|
||||
/** Relationships inferred so far */
|
||||
relationships?: number
|
||||
|
||||
/** Processing rate (items per second) */
|
||||
throughput?: number
|
||||
|
||||
/** Estimated time remaining (milliseconds) */
|
||||
eta?: number
|
||||
|
||||
/** Whether data is queryable at this point (v4.2.0+) */
|
||||
queryable?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Generic UI Components
|
||||
|
||||
### React Progress Component (Works for ALL Formats)
|
||||
|
||||
```typescript
|
||||
import { useState } from 'react'
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
|
||||
function UniversalImportProgress({ file }: { file: File }) {
|
||||
const [progress, setProgress] = useState({
|
||||
stage: 'idle',
|
||||
message: 'Ready to import',
|
||||
percent: 0,
|
||||
entities: 0,
|
||||
relationships: 0
|
||||
})
|
||||
|
||||
const handleImport = async () => {
|
||||
const buffer = await file.arrayBuffer()
|
||||
const brain = await Brainy.create()
|
||||
|
||||
await brain.import(Buffer.from(buffer), {
|
||||
// THIS WORKS FOR CSV, PDF, EXCEL, JSON, MARKDOWN, YAML, DOCX!
|
||||
onProgress: (p) => {
|
||||
setProgress({
|
||||
stage: p.stage,
|
||||
message: p.message,
|
||||
|
||||
// Calculate percentage from stage + processed/total
|
||||
percent: calculatePercent(p),
|
||||
|
||||
entities: p.entities || 0,
|
||||
relationships: p.relationships || 0
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Helper: Calculate percentage from progress
|
||||
function calculatePercent(p: ImportProgress): number {
|
||||
// Use processed/total if available
|
||||
if (p.processed && p.total) {
|
||||
return Math.round((p.processed / p.total) * 100)
|
||||
}
|
||||
|
||||
// Otherwise estimate from stage
|
||||
const stagePercents = {
|
||||
detecting: 5,
|
||||
extracting: 50,
|
||||
'storing-vfs': 80,
|
||||
'storing-graph': 90,
|
||||
complete: 100
|
||||
}
|
||||
return stagePercents[p.stage] || 0
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="import-progress">
|
||||
{/* Stage Indicator */}
|
||||
<div className="stages">
|
||||
{['detecting', 'extracting', 'storing-vfs', 'storing-graph', 'complete'].map(s => (
|
||||
<span
|
||||
key={s}
|
||||
className={progress.stage === s ? 'active' : ''}
|
||||
>
|
||||
{s}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="progress-bar">
|
||||
<div style={{ width: `${progress.percent}%` }} />
|
||||
</div>
|
||||
|
||||
{/* Status Message (format-specific but always readable) */}
|
||||
<p className="message">{progress.message}</p>
|
||||
|
||||
{/* Counts */}
|
||||
<div className="counts">
|
||||
<span>Entities: {progress.entities}</span>
|
||||
<span>Relationships: {progress.relationships}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**This component works perfectly for:**
|
||||
- ✅ CSV files with 10,000 rows
|
||||
- ✅ PDF documents with 200 pages
|
||||
- ✅ Excel workbooks with 5 sheets
|
||||
- ✅ JSON files with nested structures
|
||||
- ✅ Markdown documents with sections
|
||||
- ✅ YAML configuration files
|
||||
- ✅ DOCX documents with paragraphs
|
||||
|
||||
**No format detection needed. No format-specific rendering. Just works.**
|
||||
|
||||
---
|
||||
|
||||
### CLI Progress Indicator (Works for ALL Formats)
|
||||
|
||||
```typescript
|
||||
import ora from 'ora'
|
||||
import { Brainy } from '@soulcraft/brainy'
|
||||
|
||||
async function importWithProgress(filePath: string) {
|
||||
const spinner = ora('Starting import...').start()
|
||||
const brain = await Brainy.create()
|
||||
|
||||
try {
|
||||
await brain.import(filePath, {
|
||||
// THIS WORKS FOR ALL 7 FORMATS!
|
||||
onProgress: (p) => {
|
||||
// Update spinner text with current message
|
||||
spinner.text = p.message
|
||||
|
||||
// Add counts if available
|
||||
if (p.entities || p.relationships) {
|
||||
spinner.text += ` (${p.entities || 0} entities, ${p.relationships || 0} relationships)`
|
||||
}
|
||||
|
||||
// Add throughput/ETA if available (during extraction)
|
||||
if (p.throughput && p.eta) {
|
||||
const etaSec = Math.round(p.eta / 1000)
|
||||
spinner.text += ` [${p.throughput.toFixed(1)}/sec, ETA: ${etaSec}s]`
|
||||
}
|
||||
|
||||
// Change spinner when complete
|
||||
if (p.stage === 'complete') {
|
||||
spinner.succeed(p.message)
|
||||
}
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
spinner.fail(`Import failed: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Works for ANY format!
|
||||
await importWithProgress('data.csv')
|
||||
await importWithProgress('document.pdf')
|
||||
await importWithProgress('workbook.xlsx')
|
||||
await importWithProgress('config.yaml')
|
||||
```
|
||||
|
||||
**CLI Output (same code, different formats):**
|
||||
|
||||
```bash
|
||||
# CSV Import
|
||||
⠋ Detecting format...
|
||||
⠙ Parsing CSV rows (delimiter: ",")
|
||||
⠹ Extracting entities from csv (45 rows/sec, ETA: 120s) (150 entities, 45 relationships)
|
||||
⠸ Extracting entities from csv (45 rows/sec, ETA: 60s) (750 entities, 223 relationships)
|
||||
✔ Import complete (1350 entities, 401 relationships)
|
||||
|
||||
# PDF Import
|
||||
⠋ Detecting format...
|
||||
⠙ Loading PDF document...
|
||||
⠹ Processing page 5 of 23
|
||||
⠸ Extracting entities from pdf (2.5 pages/sec, ETA: 30s) (45 entities, 12 relationships)
|
||||
✔ Import complete (156 entities, 89 relationships)
|
||||
|
||||
# Excel Import
|
||||
⠋ Detecting format...
|
||||
⠙ Loading Excel workbook...
|
||||
⠹ Reading sheet: Sales (2/5)
|
||||
⠸ Extracting entities from excel (120 rows/sec, ETA: 45s) (500 entities, 234 relationships)
|
||||
✔ Import complete (2340 entities, 892 relationships)
|
||||
```
|
||||
|
||||
**Same code. Different formats. Perfect progress for all.**
|
||||
|
||||
---
|
||||
|
||||
### Dashboard with Real-Time Stats (Works for ALL Formats)
|
||||
|
||||
```typescript
|
||||
function ImportDashboard() {
|
||||
const [stats, setStats] = useState({
|
||||
stage: '',
|
||||
message: '',
|
||||
elapsed: 0,
|
||||
entities: 0,
|
||||
relationships: 0,
|
||||
throughput: 0,
|
||||
eta: 0
|
||||
})
|
||||
|
||||
const startTime = Date.now()
|
||||
|
||||
const handleImport = async (file: File) => {
|
||||
await brain.import(await file.arrayBuffer(), {
|
||||
// UNIVERSAL PROGRESS HANDLER - WORKS FOR ALL FORMATS!
|
||||
onProgress: (p) => {
|
||||
setStats({
|
||||
stage: p.stage,
|
||||
message: p.message,
|
||||
elapsed: Date.now() - startTime,
|
||||
entities: p.entities || 0,
|
||||
relationships: p.relationships || 0,
|
||||
throughput: p.throughput || 0,
|
||||
eta: p.eta || 0
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="dashboard">
|
||||
<h2>Import Progress</h2>
|
||||
|
||||
<div className="metric">
|
||||
<label>Stage</label>
|
||||
<value>{stats.stage}</value>
|
||||
</div>
|
||||
|
||||
<div className="metric">
|
||||
<label>Status</label>
|
||||
<value>{stats.message}</value>
|
||||
</div>
|
||||
|
||||
<div className="metric">
|
||||
<label>Elapsed</label>
|
||||
<value>{(stats.elapsed / 1000).toFixed(1)}s</value>
|
||||
</div>
|
||||
|
||||
<div className="metric">
|
||||
<label>Entities</label>
|
||||
<value>{stats.entities.toLocaleString()}</value>
|
||||
</div>
|
||||
|
||||
<div className="metric">
|
||||
<label>Relationships</label>
|
||||
<value>{stats.relationships.toLocaleString()}</value>
|
||||
</div>
|
||||
|
||||
{stats.throughput > 0 && (
|
||||
<div className="metric">
|
||||
<label>Throughput</label>
|
||||
<value>{stats.throughput.toFixed(1)} items/sec</value>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{stats.eta > 0 && (
|
||||
<div className="metric">
|
||||
<label>ETA</label>
|
||||
<value>{(stats.eta / 1000).toFixed(0)}s</value>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**This dashboard shows live stats for ANY format** - CSV, PDF, Excel, JSON, Markdown, YAML, DOCX.
|
||||
|
||||
---
|
||||
|
||||
## 📊 What Messages Look Like (Format-Specific Text, Standard Fields)
|
||||
|
||||
While the **fields are standardized**, the **message text** varies by format to be most helpful:
|
||||
|
||||
```typescript
|
||||
// CSV Import Messages
|
||||
"Detecting format..."
|
||||
"Parsing CSV rows (delimiter: ",")"
|
||||
"Extracted 1000 rows, inferring types..."
|
||||
"Extracting entities from csv (45 rows/sec, ETA: 120s)..."
|
||||
"Creating VFS structure..."
|
||||
"Import complete"
|
||||
|
||||
// PDF Import Messages
|
||||
"Detecting format..."
|
||||
"Loading PDF document..."
|
||||
"Processing page 5 of 23"
|
||||
"Extracting entities from pdf (2.5 pages/sec, ETA: 30s)..."
|
||||
"Creating VFS structure..."
|
||||
"Import complete"
|
||||
|
||||
// Excel Import Messages
|
||||
"Detecting format..."
|
||||
"Loading Excel workbook..."
|
||||
"Reading sheet: Sales (2/5)"
|
||||
"Extracting entities from excel (120 rows/sec, ETA: 45s)..."
|
||||
"Creating VFS structure..."
|
||||
"Import complete"
|
||||
```
|
||||
|
||||
**Key Point:** You can display `progress.message` directly in your UI **without parsing it**. It's always human-readable and contextually appropriate.
|
||||
|
||||
---
|
||||
|
||||
## ✅ The 5 Standard Stages (Same for ALL Formats)
|
||||
|
||||
Every import goes through these 5 stages in order:
|
||||
|
||||
| Stage | Duration | Description | Fields Available |
|
||||
|-------|----------|-------------|------------------|
|
||||
| **detecting** | ~1% | Format detection | `stage`, `message` |
|
||||
| **extracting** | ~70% | Parse file + AI extraction | `stage`, `message`, `processed`, `total`, `entities`, `relationships`, `throughput`, `eta` |
|
||||
| **storing-vfs** | ~5% | Create file structure | `stage`, `message` |
|
||||
| **storing-graph** | ~20% | Create graph nodes | `stage`, `message`, `entities`, `relationships` |
|
||||
| **complete** | ~1% | Finalize | `stage`, `message`, `entities`, `relationships` |
|
||||
|
||||
**These 5 stages are the same whether you're importing:**
|
||||
- A 10MB CSV file with 50,000 rows
|
||||
- A 200-page PDF document
|
||||
- A 5-sheet Excel workbook
|
||||
- A nested JSON structure
|
||||
- A Markdown document
|
||||
- A YAML configuration
|
||||
- A DOCX document
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Why This Matters
|
||||
|
||||
### Build Tools That Work for Everything
|
||||
|
||||
```typescript
|
||||
// ONE progress handler for your entire application
|
||||
function universalProgressHandler(progress: ImportProgress) {
|
||||
// Update UI (works for all formats)
|
||||
updateProgressBar(progress)
|
||||
updateStatusText(progress.message)
|
||||
updateCounts(progress.entities, progress.relationships)
|
||||
|
||||
// Log to analytics (works for all formats)
|
||||
analytics.track('import_progress', {
|
||||
stage: progress.stage,
|
||||
processed: progress.processed,
|
||||
total: progress.total
|
||||
})
|
||||
|
||||
// Send to monitoring (works for all formats)
|
||||
monitoring.gauge('import.entities', progress.entities)
|
||||
monitoring.gauge('import.throughput', progress.throughput)
|
||||
}
|
||||
|
||||
// Use it everywhere
|
||||
await brain.import(csvFile, { onProgress: universalProgressHandler })
|
||||
await brain.import(pdfFile, { onProgress: universalProgressHandler })
|
||||
await brain.import(excelFile, { onProgress: universalProgressHandler })
|
||||
await brain.import(jsonFile, { onProgress: universalProgressHandler })
|
||||
```
|
||||
|
||||
### No Format Detection Needed
|
||||
|
||||
```typescript
|
||||
// ❌ DON'T DO THIS (format-specific handling)
|
||||
if (format === 'csv') {
|
||||
// CSV-specific progress code
|
||||
} else if (format === 'pdf') {
|
||||
// PDF-specific progress code
|
||||
} else if (format === 'excel') {
|
||||
// Excel-specific progress code
|
||||
}
|
||||
|
||||
// ✅ DO THIS (universal handling)
|
||||
onProgress: (p) => {
|
||||
// Works for ALL formats!
|
||||
updateUI(p.stage, p.message, p.entities, p.relationships)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 Summary
|
||||
|
||||
✅ **100% Standardized** - Same `ImportProgress` interface for all 7 formats
|
||||
✅ **Build Once** - Your progress UI works for CSV, PDF, Excel, JSON, Markdown, YAML, DOCX
|
||||
✅ **No Format Detection** - No need to check file type in your progress handler
|
||||
✅ **Human-Readable Messages** - Display `progress.message` directly, no parsing needed
|
||||
✅ **Standard Fields** - `stage`, `processed`, `total`, `entities`, `relationships` work everywhere
|
||||
✅ **Optional Enhancements** - `throughput`, `eta` available during extraction (all formats)
|
||||
|
||||
**The Workshop team (and any developer) can now build monitoring tools, dashboards, CLIs, and UIs that work perfectly for all import formats with zero format-specific code!**
|
||||
Loading…
Add table
Add a link
Reference in a new issue