Improve video intake and graph refresh semantics

This commit is contained in:
Зарубин Филипп
2026-06-17 21:57:24 +03:00
parent 2d37393cdb
commit 2d2b1ee4b6
4 changed files with 142 additions and 7 deletions
+3 -1
View File
@@ -7,7 +7,9 @@ __pycache__/
.mnemazine/cache/ .mnemazine/cache/
.mnemazine/tmp/ .mnemazine/tmp/
.mnemazine/bin/ .mnemazine/bin/
.mnemazine/state/*.lock .mnemazine/archive/
.mnemazine/state/
.mnemazine/reprocess-video-inbox/
inbox/* inbox/*
!inbox/.gitkeep !inbox/.gitkeep
vault/* vault/*
+2 -2
View File
@@ -46,7 +46,7 @@ await fs.writeFile(path.join(vault, 'sample.js'), 'export const answer = 42\n',
await fs.writeFile(path.join(vault, 'sample.md'), '# Sample\n\n## What This Is\n\nSmoke note.\n\n## Source\n\n- local\n', 'utf8') await fs.writeFile(path.join(vault, 'sample.md'), '# Sample\n\n## What This Is\n\nSmoke note.\n\n## Source\n\n- local\n', 'utf8')
const codeRun = await runNode([HELPER, '--vault', vault, '--mode', 'code', '--json'], 180000) const codeRun = await runNode([HELPER, '--vault', vault, '--mode', 'code', '--json'], 180000)
assert(codeRun.code === 2, `expected code mode exit 2 for pending semantic refresh, got ${codeRun.code}`) assert(codeRun.code === 0, `expected code mode exit 0 with pending semantic marker, got ${codeRun.code}`)
const codeJson = JSON.parse(codeRun.stdout) const codeJson = JSON.parse(codeRun.stdout)
assert(codeJson.code_refresh?.ok === true, 'code refresh should be ok in code mode') assert(codeJson.code_refresh?.ok === true, 'code refresh should be ok in code mode')
assert(codeJson.semantic_pending_after === true, 'code mode should leave semantic pending on docs corpus') assert(codeJson.semantic_pending_after === true, 'code mode should leave semantic pending on docs corpus')
@@ -60,7 +60,7 @@ await fs.rm(tempRoot, { recursive: true, force: true })
console.log(JSON.stringify({ console.log(JSON.stringify({
ok: true, ok: true,
checks: [ checks: [
'code mode leaves semantic pending on docs corpus', 'code mode succeeds while leaving semantic pending on docs corpus',
'semantic mode rejects unsupported backend cleanly' 'semantic mode rejects unsupported backend cleanly'
] ]
}, null, 2)) }, null, 2))
+2 -2
View File
@@ -440,12 +440,12 @@ async function main() {
if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate() if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate()
result.after = await graphSummary(GRAPH_PATH) result.after = await graphSummary(GRAPH_PATH)
result.semantic_pending_after = existsSync(NEEDS_UPDATE_PATH) result.semantic_pending_after = existsSync(NEEDS_UPDATE_PATH)
result.ok = !result.semantic_pending_after result.ok = MODE === 'code' ? true : !result.semantic_pending_after
if (JSON_OUT) console.log(JSON.stringify(result, null, 2)) if (JSON_OUT) console.log(JSON.stringify(result, null, 2))
else console.log(result.semantic_pending_after else console.log(result.semantic_pending_after
? `Code graph refreshed. Semantic refresh still pending for ${rel(NEEDS_UPDATE_PATH)}.` ? `Code graph refreshed. Semantic refresh still pending for ${rel(NEEDS_UPDATE_PATH)}.`
: `Graph refreshed. Nodes=${result.after.nodes} edges=${result.after.edges} communities=${result.after.communities}.`) : `Graph refreshed. Nodes=${result.after.nodes} edges=${result.after.edges} communities=${result.after.communities}.`)
process.exit(result.semantic_pending_after ? 2 : 0) process.exit(MODE === 'code' || !result.semantic_pending_after ? 0 : 2)
} }
result.semantic_refresh = await semanticRefresh({ baseline: afterCode }) result.semantic_refresh = await semanticRefresh({ baseline: afterCode })
+135 -2
View File
@@ -8,8 +8,17 @@ import { spawnSync } from 'node:child_process'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox') const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault') const VAULT = process.env.MNEMAZINE_VAULT || path.join(ROOT, 'vault')
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
const CACHE = path.join(ROOT, '.mnemazine/cache/processed-hashes.json') const CACHE = path.join(ROOT, '.mnemazine/cache/processed-hashes.json')
const ARCHIVE = path.join(ROOT, '.mnemazine/archive') const ARCHIVE = path.join(ROOT, '.mnemazine/archive')
const TRANSCRIPTS = path.join(ROOT, '.mnemazine/cache/video-transcripts')
const VIDEO_AUDIO = path.join(ROOT, '.mnemazine/cache/video-audio')
const VIDEO_FRAMES = path.join(ROOT, '.mnemazine/cache/video-frames')
const VIDEO_QUEUE = path.join(ROOT, '.mnemazine/cache/video-queue.jsonl')
const WHISPER_MODEL = process.env.MNEMAZINE_WHISPER_MODEL || ''
const WHISPER_LANGUAGE = process.env.MNEMAZINE_WHISPER_LANGUAGE || 'ru'
const VIDEO_FRAME_LIMIT = Number(process.env.MNEMAZINE_VIDEO_FRAME_LIMIT || '8')
const VIDEO_INLINE_MAX_SECONDS = Number(process.env.MNEMAZINE_VIDEO_INLINE_MAX_SECONDS || '180')
async function ensureDir(dir) { async function ensureDir(dir) {
await fs.mkdir(dir, { recursive: true }) await fs.mkdir(dir, { recursive: true })
@@ -72,9 +81,131 @@ function bullets(text, max = 7) {
return out return out
} }
function isVideo(file) {
return ['.mp4', '.mov', '.m4v', '.webm', '.mkv'].includes(path.extname(file).toLowerCase())
}
function videoDurationSeconds(file) {
const probe = spawnSync('ffmpeg', ['-i', file], { encoding: 'utf8' })
const match = `${probe.stderr}\n${probe.stdout}`.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/)
if (!match) return null
return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3])
}
function whisperModelFor(durationSeconds) {
if (WHISPER_MODEL) return WHISPER_MODEL
if (durationSeconds !== null && durationSeconds <= 90) return 'base'
return 'tiny'
}
async function appendVideoQueue(item) {
await ensureDir(path.dirname(VIDEO_QUEUE))
await fs.appendFile(VIDEO_QUEUE, `${JSON.stringify(item)}\n`, 'utf8')
}
async function extractVideo(file, hash) {
await ensureDir(TRANSCRIPTS)
await ensureDir(VIDEO_AUDIO)
await ensureDir(VIDEO_FRAMES)
const durationSeconds = videoDurationSeconds(file)
const transcriptPath = path.join(TRANSCRIPTS, `${hash}.txt`)
if (existsSync(transcriptPath)) {
const transcript = await fs.readFile(transcriptPath, 'utf8')
const frames = await extractVideoFrames(file, hash)
return joinVideoParts(transcript, frames)
}
if (durationSeconds !== null && durationSeconds > VIDEO_INLINE_MAX_SECONDS) {
const frames = await extractVideoFrames(file, hash)
await appendVideoQueue({
hash,
source_ref: sourceRef(hash),
file,
duration_seconds: Math.round(durationSeconds),
status: 'deferred_transcription',
reason: `duration exceeds inline limit ${VIDEO_INLINE_MAX_SECONDS}s`,
suggested_command: `MNEMAZINE_WHISPER_MODEL=small MNEMAZINE_VIDEO_INLINE_MAX_SECONDS=999999 node scripts/mnemazine-run.mjs`
})
return joinVideoParts('', frames) || `Video queued for local Whisper transcription.\n\nDuration: ${Math.round(durationSeconds)} seconds.\nInline limit: ${VIDEO_INLINE_MAX_SECONDS} seconds.\nSource: ${sourceRef(hash)}`
}
const audioPath = path.join(VIDEO_AUDIO, `${hash}.wav`)
const ffmpeg = spawnSync('ffmpeg', [
'-y',
'-i', file,
'-vn',
'-ac', '1',
'-ar', '16000',
'-f', 'wav',
audioPath
], { encoding: 'utf8' })
if (ffmpeg.status !== 0 || !existsSync(audioPath)) return ''
const whisper = spawnSync('whisper', [
audioPath,
'--model', whisperModelFor(durationSeconds),
'--language', WHISPER_LANGUAGE,
'--output_dir', TRANSCRIPTS,
'--output_format', 'txt',
'--fp16', 'False',
'--verbose', 'False'
], { encoding: 'utf8' })
const whisperOut = path.join(TRANSCRIPTS, `${hash}.txt`)
let transcript = ''
if (whisper.status === 0 && existsSync(whisperOut)) {
transcript = await fs.readFile(whisperOut, 'utf8')
}
const frames = await extractVideoFrames(file, hash)
return joinVideoParts(transcript, frames)
}
async function extractVideoFrames(file, hash) {
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
if (!existsSync(ocr)) return ''
const frameDir = path.join(VIDEO_FRAMES, hash)
await ensureDir(frameDir)
const existing = (await fs.readdir(frameDir).catch(() => [])).filter(name => name.endsWith('.png'))
if (!existing.length) {
spawnSync('ffmpeg', [
'-y',
'-i', file,
'-vf', 'fps=1/3',
'-frames:v', String(VIDEO_FRAME_LIMIT),
path.join(frameDir, 'frame-%03d.png')
], { encoding: 'utf8' })
}
const chunks = []
const seen = new Set()
const frames = (await fs.readdir(frameDir).catch(() => []))
.filter(name => name.endsWith('.png'))
.sort()
.slice(0, VIDEO_FRAME_LIMIT)
for (const frame of frames) {
const out = spawnSync(ocr, [path.join(frameDir, frame)], { encoding: 'utf8' })
if (out.status !== 0) continue
for (const line of out.stdout.split(/\r?\n/)) {
const clean = compact(line, 220)
if (clean.length < 12) continue
const key = clean.toLowerCase()
if (seen.has(key)) continue
seen.add(key)
chunks.push(clean)
}
}
return chunks.join('\n')
}
function joinVideoParts(transcript, frameText) {
const parts = []
if (compact(transcript, 80)) parts.push(`Video transcript from local Whisper:\n\n${transcript.trim()}`)
if (compact(frameText, 80)) parts.push(`Video keyframe OCR:\n\n${frameText.trim()}`)
return parts.join('\n\n')
}
async function extract(file) { async function extract(file) {
const ext = path.extname(file).toLowerCase() const ext = path.extname(file).toLowerCase()
if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8') if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8')
if (isVideo(file)) return await extractVideo(file, await sha256(file))
const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8' }) const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8' })
if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr') const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
@@ -156,10 +287,12 @@ async function archiveFile(file, hash) {
async function main() { async function main() {
await ensureDir(INBOX) await ensureDir(INBOX)
await ensureDir(VAULT) await ensureDir(VAULT)
await ensureDir(REPORTS)
await ensureDir(path.dirname(CACHE)) await ensureDir(path.dirname(CACHE))
await ensureDir(ARCHIVE) await ensureDir(ARCHIVE)
const cache = await readJson(CACHE, {}) const cache = await readJson(CACHE, {})
const entries = (await fs.readdir(INBOX, { withFileTypes: true })).filter(d => d.isFile()) const entries = (await fs.readdir(INBOX, { withFileTypes: true }))
.filter(d => d.isFile() && !d.name.startsWith('.'))
let processed = 0 let processed = 0
const toArchive = [] const toArchive = []
for (const entry of entries) { for (const entry of entries) {
@@ -168,7 +301,7 @@ async function main() {
if (cache[hash]) continue if (cache[hash]) continue
const text = await extract(file) const text = await extract(file)
const title = inferTitle(text, 'Unextractable local source') const title = inferTitle(text, 'Unextractable local source')
const noteName = `${new Date().toISOString().slice(0, 10)}-${slugify(title)}.md` const noteName = `${new Date().toISOString().slice(0, 10)}-${slugify(title)}-${hash.slice(0, 12)}.md`
const notePath = path.join(VAULT, '01 Concepts', noteName) const notePath = path.join(VAULT, '01 Concepts', noteName)
await ensureDir(path.dirname(notePath)) await ensureDir(path.dirname(notePath))
await fs.writeFile(notePath, makeNote(file, hash, text), 'utf8') await fs.writeFile(notePath, makeNote(file, hash, text), 'utf8')