Compare commits

...
23 Commits
Author SHA1 Message Date
xiaolaiandClaude Code e03c4604fb fix: remove stray colon in --cluster-only dict literal (SyntaxError) (#603)
tokens dict at line 826 had output-colon-colon 0 causing a SyntaxError
when the Trae skill is invoked with --cluster-only. The extra colon
makes Python reject the dict literal entirely.

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-05-02 14:14:39 +01:00
SafiandClaude Sonnet 4.6 699e9960ce Remove Anthropic API call from transcribe.py - agent generates Whisper prompt itself
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:55:22 +01:00
SafiandClaude Sonnet 4.6 2c21bc0488 Fix CI: mock lazy anthropic import via sys.modules instead of module attribute
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:48:54 +01:00
SafiandClaude Sonnet 4.6 a2872cafac Add YouTube URL example to README usage, update repo about with pip install
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:44:44 +01:00
SafiandClaude Sonnet 4.6 f758911b10 Update README and descriptions to mention video/audio and YouTube support
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:42:35 +01:00
SafiandClaude Sonnet 4.6 79acb7e46a Add video/audio corpus support with yt-dlp download and Whisper transcription
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 15:40:18 +01:00
Safi 210243fa58 fix hook reinstall, CRLF labels, skill-windows missing commands (0.3.28) 2026-04-10 10:07:11 +01:00
Safi f7ee752eb1 switch downloads badge to pepy.tech to avoid shields.io rate limit 2026-04-10 09:49:50 +01:00
Safi af3a3d2157 update README Gemini CLI description to mention skill file copy 2026-04-10 01:29:05 +01:00
Safi 55964bc0b1 fix gemini install missing skill file copy (0.3.27) 2026-04-10 01:28:19 +01:00
Safi a0a196e1af update README to list all platforms including Aider, Copilot CLI, Cursor, Gemini in CLI section 2026-04-10 01:09:35 +01:00
Safi 863100cb06 fix MCP server path validation security issue (0.3.26) 2026-04-10 01:08:15 +01:00
SafiandClaude Sonnet 4.6 1cbcee539f release 0.3.25: Aider + Copilot CLI, directed graphs, frontmatter cache, graphifyignore parent discovery, MCP fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 00:56:22 +01:00
Safi cf39034744 Remove Trendshift badge (API not available) 2026-04-09 22:46:47 +01:00
Safi e440539305 Add Trendshift badge to README 2026-04-09 22:45:52 +01:00
Safi ee43236c16 Fix codex/opencode install idempotency — always run hook step (#153) 2026-04-09 17:59:16 +01:00
Safi 54c6d04b75 Switch star history to star-history.com for faster updates 2026-04-09 17:46:34 +01:00
Safi 687fbc810a Update README: add Cursor and Gemini CLI to all platform sections 2026-04-09 17:44:59 +01:00
SafiandClaude Sonnet 4.6 dcc402e140 Add Gemini CLI support and sponsor nudge at pipeline completion (#105)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:40:45 +01:00
Safi 0b8067c9d1 Add Cursor to description, README intro, and PyPI keywords 2026-04-09 17:25:36 +01:00
SafiandClaude Sonnet 4.6 f770712704 Add Cursor support, fix _rebuild_code KeyError and node_link_data crash (#137, #148, #149)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:19:40 +01:00
Safi a104a0d9fc Add monthly PyPI downloads badge to README 2026-04-09 14:46:13 +01:00
SafiandClaude Sonnet 4.6 6f9fc65af4 Fix Codex hook JSON schema (#138) and use #!/bin/sh for Windows git hooks (#140)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:12:36 +01:00
30 changed files with 3806 additions and 76 deletions

No files matched your search

+55
View File
@@ -2,6 +2,61 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
## 0.3.29 (2026-04-10)
- Add: video and audio corpus support — drop `.mp4`, `.mp3`, `.wav`, `.mov`, `.webm`, `.m4a`, `.ogg`, `.mkv`, `.avi`, `.m4v` files into any corpus and graphify transcribes them with faster-whisper before extraction
- Add: YouTube and URL video download — pass a YouTube link (or any video URL) to `/graphify add <url>` and yt-dlp downloads audio-only, which is then transcribed and added to the corpus automatically
- Add: domain-aware Whisper prompts — god nodes from non-video files are used to build a one-sentence domain hint for Whisper via a cheap Haiku call, improving transcript accuracy on technical content
- Add: `graphify-out/transcripts/` cache — transcripts are cached by filename so re-runs skip already-transcribed files; URLs cached by hash
- Requires: `pip install 'graphifyy[video]'` for faster-whisper + yt-dlp
## 0.3.28 (2026-04-10)
- Fix: hook installers (Claude Code, Codex, Gemini CLI) now always remove and reinstall the hook on re-run — users upgrading from old versions no longer get stuck with a broken hook format (#182)
- Fix: rationale node labels no longer contain bare `\r` characters on Windows/WSL CRLF files — breaks Obsidian export was silently producing invalid filenames (#176)
- Fix: `skill-windows.md` now includes `--wiki`, `--obsidian-dir`, and `--directed` which were missing vs the main skill (#177)
## 0.3.27 (2026-04-10)
- Fix: graphify install --platform gemini now also copies the skill file to ~/.gemini/skills/graphify/SKILL.md so the /graphify trigger works in Gemini CLI (#174)
## 0.3.26 (2026-04-10)
- Fix: MCP server no longer uses a circular path validation when loading a graph outside cwd — now validates the path exists and ends in `.json` instead of checking containment within its own parent directory (security fix)
## 0.3.25 (2026-04-09)
- Fix: `graphify install --platform gemini` now routes to `gemini_install()` instead of erroring — `gemini` was missing from `_PLATFORM_CONFIG` (#171)
- Fix: `graphify install --platform cursor` now routes to `_cursor_install()` the same way (#171)
- Fix: `serve.py` `validate_graph_path` now passes `base=Path(graph_path).resolve().parent` so MCP server works when graph is outside cwd (#170)
- Fix: MCP `call_tool()` handler now wraps dispatch in try/except — exceptions in tool handlers return graceful error strings instead of crashing the stdio loop (#163)
- Fix: `_load_graphifyignore` now walks parent directories up to the `.git` boundary, matching `.gitignore` discovery behavior — subdirectory scans now inherit root ignore patterns (#168)
- Add: Aider platform support — `graphify install --platform aider` copies skill to `~/.aider/graphify/SKILL.md`; `graphify aider install/uninstall` writes AGENTS.md rules (#74)
- Add: GitHub Copilot CLI platform support — `graphify install --platform copilot` copies skill to `~/.copilot/skills/graphify/SKILL.md`; `graphify copilot install/uninstall` for skill management (#134)
- Add: `--directed` flag — `build_from_json()` and `build()` now accept `directed=True` to produce a `DiGraph` preserving edge direction (source→target); `cluster()` converts to undirected internally for Leiden; `graph_diff` edge key handles directed graphs correctly (#125)
- Add: Frontmatter-aware cache for Markdown files — `.md` files hash only the body below YAML frontmatter, so metadata-only changes (reviewed, status, tags) no longer invalidate the cache (#131)
## 0.3.24 (2026-04-09)
- Fix: `graphify codex install` (and opencode) no longer exits early when `AGENTS.md` already has the graphify section — partial installs with a missing `.codex/hooks.json` can now recover on re-run (#153)
## 0.3.23 (2026-04-09)
- Add: Gemini CLI support — `graphify gemini install` writes a `GEMINI.md` section and a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls (#105)
- Add: sponsor nudge at pipeline completion — all skill files now print a one-line sponsor link after a fresh build, not on `--update` runs
## 0.3.22 (2026-04-09)
- Add: Cursor support — `graphify cursor install` writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` so the graph context is always included; `graphify cursor uninstall` removes it (#137)
- Fix: `_rebuild_code()` KeyError — `detected[FileType.CODE]` corrected to `detected['files']['code']` matching `detect()`'s actual return shape; was silently breaking git hooks on every commit (#148)
- Fix: `to_json()` crash on NetworkX 3.2.x — `node_link_data(G, edges="links")` now falls back to `node_link_data(G)` on older NetworkX, same shim already used for `node_link_graph` (#149)
- Fix: README clarifies `graphifyy` is the only official PyPI package — other `graphify*` packages are not affiliated (#129)
## 0.3.21 (2026-04-09)
- Fix: Codex PreToolUse hook now places `systemMessage` at the top level of the output JSON instead of inside `hookSpecificOutput` — matches the strict schema enforced by codex-cli 0.118.0+ which uses `additionalProperties: false` (#138)
- Fix: git hooks now use `#!/bin/sh` instead of `#!/bin/bash` — Git for Windows ships `sh.exe` not `bash`, so hooks were silently skipped on Windows (#140)
## 0.3.20 (2026-04-09)
- Fix: XSS in interactive HTML graph — node labels, file types, community names, source files, and edge relations now HTML-escaped before `innerHTML` injection; neighbor link `onclick` uses `JSON.stringify` instead of raw string interpolation
+36 -9
View File
@@ -4,11 +4,12 @@
[![CI](https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v3)](https://github.com/safishamsi/graphify/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/graphifyy)](https://pypi.org/project/graphifyy/)
[![Downloads](https://static.pepy.tech/badge/graphifyy/month)](https://pepy.tech/project/graphifyy)
[![Sponsor](https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors)](https://github.com/sponsors/safishamsi)
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, OpenClaw, Factory Droid, or Trae - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
**An AI coding assistant skill.** Type `/graphify` in Claude Code, Codex, OpenCode, Cursor, Gemini CLI, GitHub Copilot CLI, Aider, OpenClaw, Factory Droid, or Trae - it reads your files, builds a knowledge graph, and gives you back structure you didn't know was there. Understand a codebase faster. Find the "why" behind architectural decisions.
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, even images in other languages - graphify uses Claude vision to extract concepts and relationships from all of it and connects them into one graph. 20 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
Fully multimodal. Drop in code, PDFs, markdown, screenshots, diagrams, whiteboard photos, images in other languages, or video and audio files - graphify extracts concepts and relationships from all of it and connects them into one graph. Videos are transcribed with Whisper using a domain-aware prompt derived from your corpus. 20 languages supported via tree-sitter AST (Python, JS, TS, Go, Rust, Java, C, C++, Ruby, C#, Kotlin, Scala, PHP, Swift, Lua, Zig, PowerShell, Elixir, Objective-C, Julia).
> Andrej Karpathy keeps a `/raw` folder where he drops papers, tweets, screenshots, and notes. graphify is the answer to that problem - 71.5x fewer tokens per query vs reading the raw files, persistent across sessions, honest about what it found vs guessed.
@@ -38,7 +39,7 @@ Same syntax as `.gitignore`. Patterns match against file paths relative to the f
## How it works
graphify runs in two passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, Claude subagents run in parallel over docs, papers, and images to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
graphify runs in three passes. First, a deterministic AST pass extracts structure from code files (classes, functions, imports, call graphs, docstrings, rationale comments) with no LLM needed. Second, video and audio files are transcribed locally with faster-whisper using a domain-aware prompt derived from corpus god nodes — transcripts are cached so re-runs are instant. Third, Claude subagents run in parallel over docs, papers, images, and transcripts to extract concepts, relationships, and design rationale. The results are merged into a NetworkX graph, clustered with Leiden community detection, and exported as interactive HTML, queryable JSON, and a plain-language audit report.
**Clustering is graph-topology-based — no embeddings.** Leiden finds communities by edge density. The semantic similarity edges that Claude extracts (`semantically_similar_to`, marked INFERRED) are already in the graph, so they influence community detection directly. The graph structure is the similarity signal — no separate embedding step or vector database needed.
@@ -46,13 +47,13 @@ Every relationship is tagged `EXTRACTED` (found directly in source), `INFERRED`
## Install
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), or [Trae](https://trae.ai)
**Requires:** Python 3.10+ and one of: [Claude Code](https://claude.ai/code), [Codex](https://openai.com/codex), [OpenCode](https://opencode.ai), [Cursor](https://cursor.com), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [GitHub Copilot CLI](https://docs.github.com/en/copilot/how-tos/copilot-cli), [Aider](https://aider.chat), [OpenClaw](https://openclaw.ai), [Factory Droid](https://factory.ai), or [Trae](https://trae.ai)
```bash
pip install graphifyy && graphify install
```
> The PyPI package is temporarily named `graphifyy` while the `graphify` name is being reclaimed. The CLI and skill command are still `graphify`.
> **Official package:** The PyPI package is named `graphifyy` (install with `pip install graphifyy`). Other packages named `graphify*` on PyPI are not affiliated with this project. The only official repository is [safishamsi/graphify](https://github.com/safishamsi/graphify). The CLI and skill command are still `graphify`.
### Platform support
@@ -62,12 +63,16 @@ pip install graphifyy && graphify install
| Claude Code (Windows) | `graphify install` (auto-detected) or `graphify install --platform windows` |
| Codex | `graphify install --platform codex` |
| OpenCode | `graphify install --platform opencode` |
| GitHub Copilot CLI | `graphify install --platform copilot` |
| Aider | `graphify install --platform aider` |
| OpenClaw | `graphify install --platform claw` |
| Factory Droid | `graphify install --platform droid` |
| Trae | `graphify install --platform trae` |
| Trae CN | `graphify install --platform trae-cn` |
| Gemini CLI | `graphify install --platform gemini` |
| Cursor | `graphify cursor install` |
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw uses sequential extraction (parallel agent support is still early on that platform). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism.
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism.
Then open your AI coding assistant and type:
@@ -86,10 +91,14 @@ After building a graph, run this once in your project:
| Claude Code | `graphify claude install` |
| Codex | `graphify codex install` |
| OpenCode | `graphify opencode install` |
| GitHub Copilot CLI | `graphify copilot install` |
| Aider | `graphify aider install` |
| OpenClaw | `graphify claw install` |
| Factory Droid | `graphify droid install` |
| Trae | `graphify trae install` |
| Trae CN | `graphify trae-cn install` |
| Cursor | `graphify cursor install` |
| Gemini CLI | `graphify gemini install` |
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
@@ -97,7 +106,13 @@ After building a graph, run this once in your project:
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
**OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
**Cursor** writes `.cursor/rules/graphify.mdc` with `alwaysApply: true` — Cursor includes it in every conversation automatically, no hook needed.
**Gemini CLI** copies the skill to `~/.gemini/skills/graphify/SKILL.md`, writes a `GEMINI.md` section, and installs a `BeforeTool` hook in `.gemini/settings.json` that fires before file-read tool calls — same always-on mechanism as Claude Code.
**Aider and OpenClaw, Factory Droid, Trae** write the same rules to `AGENTS.md` in your project root. These platforms don't support tool hooks, so AGENTS.md is the always-on mechanism.
**GitHub Copilot CLI** copies the skill to `~/.copilot/skills/graphify/SKILL.md`. Run `graphify copilot install` to set it up.
Uninstall with the matching uninstall command (e.g. `graphify claude uninstall`).
@@ -170,6 +185,7 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/graphify ./raw # run on a specific folder
/graphify ./raw --mode deep # more aggressive INFERRED edge extraction
/graphify ./raw --update # re-extract only changed files, merge into existing graph
/graphify ./raw --directed # build directed graph (preserves edge direction: source→target)
/graphify ./raw --cluster-only # rerun clustering on existing graph, no re-extraction
/graphify ./raw --no-viz # skip HTML, just produce report + JSON
/graphify ./raw --obsidian # also generate Obsidian vault (opt-in)
@@ -177,6 +193,7 @@ When the user types `/graphify`, invoke the Skill tool with `skill: "graphify"`
/graphify add https://arxiv.org/abs/1706.03762 # fetch a paper, save, update graph
/graphify add https://x.com/karpathy/status/... # fetch a tweet
/graphify add https://www.youtube.com/watch?v=... # download audio, transcribe, add to graph
/graphify add https://... --author "Name" # tag the original author
/graphify add https://... --contributor "Name" # tag who added it to the corpus
@@ -204,6 +221,14 @@ graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
graphify claude uninstall
graphify codex install # AGENTS.md (Codex)
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
graphify cursor uninstall
graphify gemini install # GEMINI.md + BeforeTool hook (Gemini CLI)
graphify gemini uninstall
graphify copilot install # skill file (GitHub Copilot CLI)
graphify copilot uninstall
graphify aider install # AGENTS.md (Aider)
graphify aider uninstall
graphify claw install # AGENTS.md (OpenClaw)
graphify droid install # AGENTS.md (Factory Droid)
graphify trae install # AGENTS.md (Trae)
@@ -227,6 +252,8 @@ Works with any mix of file types:
| Office | `.docx .xlsx` | Converted to markdown then extracted via Claude (requires `pip install graphifyy[office]`) |
| Papers | `.pdf` | Citation mining + concept extraction |
| Images | `.png .jpg .webp .gif` | Claude vision - screenshots, diagrams, any language |
| Video / Audio | `.mp4 .mov .mkv .webm .avi .m4v .mp3 .wav .m4a .ogg` | Transcribed locally with faster-whisper, transcript fed into Claude extraction (requires `pip install graphifyy[video]`) |
| YouTube / URLs | any video URL | Audio downloaded via yt-dlp, then same Whisper pipeline (requires `pip install graphifyy[video]`) |
## What you get
@@ -264,7 +291,7 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
## Privacy
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
## Tech stack
@@ -276,7 +303,7 @@ graphify is the graph layer. We are building [Penpax](https://safishamsi.github.
## Star history
[![Star History Chart](https://starchart.cc/safishamsi/graphify.svg)](https://starchart.cc/safishamsi/graphify)
[![Star History Chart](https://api.star-history.com/svg?repos=safishamsi/graphify&type=Date)](https://star-history.com/#safishamsi/graphify&Date)
<details>
<summary>Contributing</summary>
+238 -21
View File
@@ -62,6 +62,16 @@ _PLATFORM_CONFIG: dict[str, dict] = {
"skill_dst": Path(".config") / "opencode" / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"aider": {
"skill_file": "skill-aider.md",
"skill_dst": Path(".aider") / "graphify" / "SKILL.md",
"claude_md": False,
},
"copilot": {
"skill_file": "skill-copilot.md",
"skill_dst": Path(".copilot") / "skills" / "graphify" / "SKILL.md",
"claude_md": False,
},
"claw": {
"skill_file": "skill-claw.md",
"skill_dst": Path(".claw") / "skills" / "graphify" / "SKILL.md",
@@ -91,9 +101,15 @@ _PLATFORM_CONFIG: dict[str, dict] = {
def install(platform: str = "claude") -> None:
if platform == "gemini":
gemini_install()
return
if platform == "cursor":
_cursor_install()
return
if platform not in _PLATFORM_CONFIG:
print(
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}",
f"error: unknown platform '{platform}'. Choose from: {', '.join(_PLATFORM_CONFIG)}, gemini, cursor",
file=sys.stderr,
)
sys.exit(1)
@@ -160,6 +176,167 @@ Rules:
_AGENTS_MD_MARKER = "## graphify"
_GEMINI_MD_SECTION = """\
## graphify
This project has a graphify knowledge graph at graphify-out/.
Rules:
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
"""
_GEMINI_MD_MARKER = "## graphify"
_GEMINI_HOOK = {
"matcher": "read_file|list_directory",
"hooks": [
{
"type": "command",
"command": (
"[ -f graphify-out/graph.json ] && "
r"""echo '{"decision":"allow","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}' """
r"""|| echo '{"decision":"allow"}'"""
),
}
],
}
def gemini_install(project_dir: Path | None = None) -> None:
"""Copy skill file to ~/.gemini/skills/graphify/, write GEMINI.md section, and install BeforeTool hook."""
# Copy skill file to ~/.gemini/skills/graphify/SKILL.md
skill_src = Path(__file__).parent / "skill.md"
skill_dst = Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
skill_dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(skill_src, skill_dst)
(skill_dst.parent / ".graphify_version").write_text(__version__, encoding="utf-8")
print(f" skill installed -> {skill_dst}")
target = (project_dir or Path(".")) / "GEMINI.md"
if target.exists():
content = target.read_text(encoding="utf-8")
if _GEMINI_MD_MARKER in content:
print("graphify already configured in GEMINI.md")
else:
target.write_text(content.rstrip() + "\n\n" + _GEMINI_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
else:
target.write_text(_GEMINI_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
_install_gemini_hook(project_dir or Path("."))
print()
print("Gemini CLI will now check the knowledge graph before answering")
print("codebase questions and rebuild it after code changes.")
def _install_gemini_hook(project_dir: Path) -> None:
settings_path = project_dir / ".gemini" / "settings.json"
settings_path.parent.mkdir(parents=True, exist_ok=True)
try:
settings = json.loads(settings_path.read_text(encoding="utf-8")) if settings_path.exists() else {}
except json.JSONDecodeError:
settings = {}
before_tool = settings.setdefault("hooks", {}).setdefault("BeforeTool", [])
settings["hooks"]["BeforeTool"] = [h for h in before_tool if "graphify" not in str(h)]
settings["hooks"]["BeforeTool"].append(_GEMINI_HOOK)
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(" .gemini/settings.json -> BeforeTool hook registered")
def _uninstall_gemini_hook(project_dir: Path) -> None:
settings_path = project_dir / ".gemini" / "settings.json"
if not settings_path.exists():
return
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return
before_tool = settings.get("hooks", {}).get("BeforeTool", [])
filtered = [h for h in before_tool if "graphify" not in str(h)]
if len(filtered) == len(before_tool):
return
settings["hooks"]["BeforeTool"] = filtered
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(" .gemini/settings.json -> BeforeTool hook removed")
def gemini_uninstall(project_dir: Path | None = None) -> None:
"""Remove the graphify section from GEMINI.md, uninstall hook, and remove skill file."""
# Remove skill file
skill_dst = Path.home() / ".gemini" / "skills" / "graphify" / "SKILL.md"
if skill_dst.exists():
skill_dst.unlink()
print(f" skill removed -> {skill_dst}")
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (skill_dst.parent, skill_dst.parent.parent):
try:
d.rmdir()
except OSError:
break
target = (project_dir or Path(".")) / "GEMINI.md"
if not target.exists():
print("No GEMINI.md found in current directory - nothing to do")
return
content = target.read_text(encoding="utf-8")
if _GEMINI_MD_MARKER not in content:
print("graphify section not found in GEMINI.md - nothing to do")
return
cleaned = re.sub(r"\n*## graphify\n.*?(?=\n## |\Z)", "", content, flags=re.DOTALL).rstrip()
if cleaned:
target.write_text(cleaned + "\n", encoding="utf-8")
print(f"graphify section removed from {target.resolve()}")
else:
target.unlink()
print(f"GEMINI.md was empty after removal - deleted {target.resolve()}")
_uninstall_gemini_hook(project_dir or Path("."))
_CURSOR_RULE_PATH = Path(".cursor") / "rules" / "graphify.mdc"
_CURSOR_RULE = """\
---
description: graphify knowledge graph context
alwaysApply: true
---
This project has a graphify knowledge graph at graphify-out/.
- Before answering architecture or codebase questions, read graphify-out/GRAPH_REPORT.md for god nodes and community structure
- If graphify-out/wiki/index.md exists, navigate it instead of reading raw files
- After modifying code files in this session, run `python3 -c "from graphify.watch import _rebuild_code; from pathlib import Path; _rebuild_code(Path('.'))"` to keep the graph current
"""
def _cursor_install(project_dir: Path) -> None:
"""Write .cursor/rules/graphify.mdc with alwaysApply: true."""
rule_path = (project_dir or Path(".")) / _CURSOR_RULE_PATH
rule_path.parent.mkdir(parents=True, exist_ok=True)
if rule_path.exists():
print(f"graphify rule already exists at {rule_path} (no change)")
return
rule_path.write_text(_CURSOR_RULE, encoding="utf-8")
print(f"graphify rule written to {rule_path.resolve()}")
print()
print("Cursor will now always include the knowledge graph context.")
print("Run /graphify . first to build the graph if you haven't already.")
def _cursor_uninstall(project_dir: Path) -> None:
"""Remove .cursor/rules/graphify.mdc."""
rule_path = (project_dir or Path(".")) / _CURSOR_RULE_PATH
if not rule_path.exists():
print("No graphify Cursor rule found - nothing to do")
return
rule_path.unlink()
print(f"graphify Cursor rule removed from {rule_path.resolve()}")
# OpenCode tool.execute.before plugin — fires before every tool call.
# Injects a graph reminder into bash command output when graph.json exists.
_OPENCODE_PLUGIN_JS = """\
@@ -251,7 +428,7 @@ _CODEX_HOOK = {
"type": "command",
"command": (
"[ -f graphify-out/graph.json ] && "
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","systemMessage":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"},"systemMessage":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}' """
"|| true"
),
}
@@ -276,11 +453,8 @@ def _install_codex_hook(project_dir: Path) -> None:
existing = {}
pre_tool = existing.setdefault("hooks", {}).setdefault("PreToolUse", [])
if any("graphify" in str(h) for h in pre_tool):
print(f" .codex/hooks.json -> hook already registered (no change)")
return
pre_tool.extend(_CODEX_HOOK["hooks"]["PreToolUse"])
existing["hooks"]["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
existing["hooks"]["PreToolUse"].extend(_CODEX_HOOK["hooks"]["PreToolUse"])
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
print(f" .codex/hooks.json -> PreToolUse hook registered")
@@ -309,13 +483,12 @@ def _agents_install(project_dir: Path, platform: str) -> None:
content = target.read_text(encoding="utf-8")
if _AGENTS_MD_MARKER in content:
print(f"graphify already configured in AGENTS.md")
return
new_content = content.rstrip() + "\n\n" + _AGENTS_MD_SECTION
else:
target.write_text(content.rstrip() + "\n\n" + _AGENTS_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
else:
new_content = _AGENTS_MD_SECTION
target.write_text(new_content, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
target.write_text(_AGENTS_MD_SECTION, encoding="utf-8")
print(f"graphify section written to {target.resolve()}")
if platform == "codex":
_install_codex_hook(project_dir or Path("."))
@@ -400,12 +573,8 @@ def _install_claude_hook(project_dir: Path) -> None:
hooks = settings.setdefault("hooks", {})
pre_tool = hooks.setdefault("PreToolUse", [])
# Check if already installed
if any(h.get("matcher") == "Glob|Grep" and "graphify" in str(h) for h in pre_tool):
print(f" .claude/settings.json -> hook already registered (no change)")
return
pre_tool.append(_SETTINGS_HOOK)
hooks["PreToolUse"] = [h for h in pre_tool if not (h.get("matcher") == "Glob|Grep" and "graphify" in str(h))]
hooks["PreToolUse"].append(_SETTINGS_HOOK)
settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8")
print(f" .claude/settings.json -> PreToolUse hook registered")
@@ -468,7 +637,7 @@ def main() -> None:
print("Usage: graphify <command>")
print()
print("Commands:")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|claw|droid|trae|trae-cn)")
print(" install [--platform P] copy skill to platform config dir (claude|windows|codex|opencode|aider|claw|droid|trae|trae-cn|gemini|cursor)")
print(" query \"<question>\" BFS traversal of graph.json for a question")
print(" --dfs use depth-first instead of breadth-first")
print(" --budget N cap output at N tokens (default 2000)")
@@ -483,12 +652,20 @@ def main() -> None:
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
print(" hook uninstall remove git hooks")
print(" hook status check if git hooks are installed")
print(" gemini install write GEMINI.md section + BeforeTool hook (Gemini CLI)")
print(" gemini uninstall remove GEMINI.md section + BeforeTool hook")
print(" cursor install write .cursor/rules/graphify.mdc (Cursor)")
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
print(" codex install write graphify section to AGENTS.md (Codex)")
print(" codex uninstall remove graphify section from AGENTS.md")
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
print(" aider install write graphify section to AGENTS.md (Aider)")
print(" aider uninstall remove graphify section from AGENTS.md")
print(" copilot install copy graphify skill to ~/.copilot/skills (GitHub Copilot CLI)")
print(" copilot uninstall remove graphify skill from ~/.copilot/skills")
print(" claw install write graphify section to AGENTS.md (OpenClaw)")
print(" claw uninstall remove graphify section from AGENTS.md")
print(" droid install write graphify section to AGENTS.md (Factory Droid)")
@@ -526,7 +703,47 @@ def main() -> None:
else:
print("Usage: graphify claude [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd in ("codex", "opencode", "claw", "droid", "trae", "trae-cn"):
elif cmd == "gemini":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
gemini_install()
elif subcmd == "uninstall":
gemini_uninstall()
else:
print("Usage: graphify gemini [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "cursor":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_cursor_install(Path("."))
elif subcmd == "uninstall":
_cursor_uninstall(Path("."))
else:
print("Usage: graphify cursor [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd == "copilot":
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
install(platform="copilot")
elif subcmd == "uninstall":
skill_dst = Path.home() / _PLATFORM_CONFIG["copilot"]["skill_dst"]
removed = []
if skill_dst.exists():
skill_dst.unlink()
removed.append(f"skill removed: {skill_dst}")
version_file = skill_dst.parent / ".graphify_version"
if version_file.exists():
version_file.unlink()
for d in (skill_dst.parent, skill_dst.parent.parent, skill_dst.parent.parent.parent):
try:
d.rmdir()
except OSError:
break
print("; ".join(removed) if removed else "nothing to remove")
else:
print("Usage: graphify copilot [install|uninstall]", file=sys.stderr)
sys.exit(1)
elif cmd in ("aider", "codex", "opencode", "claw", "droid", "trae", "trae-cn"):
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
if subcmd == "install":
_agents_install(Path("."), cmd)
+2
View File
@@ -469,6 +469,8 @@ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
]
def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
if G.is_directed():
return (u, v, data.get("relation", ""))
return (min(u, v), max(u, v), data.get("relation", ""))
old_edge_keys = {
+12 -4
View File
@@ -26,13 +26,18 @@ import networkx as nx
from .validate import validate_extraction
def build_from_json(extraction: dict) -> nx.Graph:
def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
"""Build a NetworkX graph from an extraction dict.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
"""
errors = validate_extraction(extraction)
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
real_errors = [e for e in errors if "does not match any node id" not in e]
if real_errors:
print(f"[graphify] Extraction warning ({len(real_errors)} issues): {real_errors[0]}", file=sys.stderr)
G = nx.Graph()
G: nx.Graph = nx.DiGraph() if directed else nx.Graph()
for node in extraction.get("nodes", []):
G.add_node(node["id"], **{k: v for k, v in node.items() if k != "id"})
node_set = set(G.nodes())
@@ -52,9 +57,12 @@ def build_from_json(extraction: dict) -> nx.Graph:
return G
def build(extractions: list[dict]) -> nx.Graph:
def build(extractions: list[dict], *, directed: bool = False) -> nx.Graph:
"""Merge multiple extraction results into one graph.
directed=True produces a DiGraph that preserves edge direction (source→target).
directed=False (default) produces an undirected Graph for backward compatibility.
Extractions are merged in order. For nodes with the same ID, the last
extraction's attributes win (NetworkX add_node overwrites). Pass AST
results before semantic results so semantic labels take precedence, or
@@ -67,4 +75,4 @@ def build(extractions: list[dict]) -> nx.Graph:
combined["hyperedges"].extend(ext.get("hyperedges", []))
combined["input_tokens"] += ext.get("input_tokens", 0)
combined["output_tokens"] += ext.get("output_tokens", 0)
return build_from_json(combined)
return build_from_json(combined, directed=directed)
+18 -2
View File
@@ -7,11 +7,27 @@ import os
from pathlib import Path
def _body_content(content: bytes) -> bytes:
"""Strip YAML frontmatter from Markdown content, returning only the body."""
text = content.decode(errors="replace")
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
return text[end + 4:].encode()
return content
def file_hash(path: Path) -> str:
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content."""
"""SHA256 of file contents + resolved path. Prevents cache collisions on identical content.
For Markdown files (.md), only the body below the YAML frontmatter is hashed,
so metadata-only changes (e.g. reviewed, status, tags) do not invalidate the cache.
"""
p = Path(path)
raw = p.read_bytes()
content = _body_content(raw) if p.suffix.lower() == ".md" else raw
h = hashlib.sha256()
h.update(p.read_bytes())
h.update(content)
h.update(b"\x00")
h.update(str(p.resolve()).encode())
return h.hexdigest()
+5
View File
@@ -62,9 +62,14 @@ def cluster(G: nx.Graph) -> dict[int, list[str]]:
Community IDs are stable across runs: 0 = largest community after splitting.
Oversized communities (> 25% of graph nodes, min 10) are split by running
a second Leiden pass on the subgraph.
Accepts directed or undirected graphs. DiGraphs are converted to undirected
internally since Louvain/Leiden require undirected input.
"""
if G.number_of_nodes() == 0:
return {}
if G.is_directed():
G = G.to_undirected()
if G.number_of_edges() == 0:
return {i: [n] for i, n in enumerate(sorted(G.nodes))}
+29 -10
View File
@@ -13,6 +13,7 @@ class FileType(str, Enum):
DOCUMENT = "document"
PAPER = "paper"
IMAGE = "image"
VIDEO = "video"
_MANIFEST_PATH = "graphify-out/manifest.json"
@@ -22,6 +23,7 @@ DOC_EXTENSIONS = {'.md', '.txt', '.rst'}
PAPER_EXTENSIONS = {'.pdf'}
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
OFFICE_EXTENSIONS = {'.docx', '.xlsx'}
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
CORPUS_WARN_THRESHOLD = 50_000 # words - below this, warn "you may not need a graph"
CORPUS_UPPER_THRESHOLD = 500_000 # words - above this, warn about token cost
@@ -95,6 +97,8 @@ def classify_file(path: Path) -> FileType | None:
return FileType.DOCUMENT
if ext in OFFICE_EXTENSIONS:
return FileType.DOCUMENT
if ext in VIDEO_EXTENSIONS:
return FileType.VIDEO
return None
@@ -250,21 +254,34 @@ def _is_noise_dir(part: str) -> bool:
def _load_graphifyignore(root: Path) -> list[str]:
"""Read .graphifyignore from root and return a list of patterns.
"""Read .graphifyignore from root **and ancestor directories**, returning patterns.
Walks upward from *root* towards the filesystem root, collecting patterns
from every ``.graphifyignore`` encountered (like ``.gitignore`` discovery).
The search stops at the filesystem root or at a ``.git`` directory boundary
so it doesn't leak outside the repository.
Lines starting with # are comments. Blank lines are ignored.
Patterns follow gitignore semantics: glob matched against the path
relative to root. A leading slash anchors to root. A trailing slash
matches directories only (we match both dir and file for simplicity).
"""
ignore_file = root / ".graphifyignore"
if not ignore_file.exists():
return []
patterns = []
for line in ignore_file.read_text(errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append(line)
patterns: list[str] = []
current = root.resolve()
while True:
ignore_file = current / ".graphifyignore"
if ignore_file.exists():
for line in ignore_file.read_text(errors="ignore").splitlines():
line = line.strip()
if line and not line.startswith("#"):
patterns.append(line)
# Stop climbing once we've processed the git repo root
if (current / ".git").exists():
break
parent = current.parent
if parent == current:
break # filesystem root
current = parent
return patterns
@@ -305,6 +322,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
FileType.DOCUMENT: [],
FileType.PAPER: [],
FileType.IMAGE: [],
FileType.VIDEO: [],
}
total_words = 0
@@ -375,7 +393,8 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
skipped_sensitive.append(str(p) + " [office conversion failed - pip install graphifyy[office]]")
continue
files[ftype].append(str(p))
total_words += count_words(p)
if ftype != FileType.VIDEO:
total_words += count_words(p)
total_files = sum(len(v) for v in files.values())
needs_graph = total_words >= CORPUS_WARN_THRESHOLD
+6 -3
View File
@@ -284,7 +284,10 @@ def attach_hyperedges(G: nx.Graph, hyperedges: list) -> None:
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str) -> None:
node_community = _node_community_map(communities)
data = json_graph.node_link_data(G, edges="links")
try:
data = json_graph.node_link_data(G, edges="links")
except TypeError:
data = json_graph.node_link_data(G)
for node in data["nodes"]:
node["community"] = node_community.get(node["id"])
for link in data["links"]:
@@ -460,7 +463,7 @@ def to_obsidian(
# Map node_id → safe filename so wikilinks stay consistent.
# Deduplicate: if two nodes produce the same filename, append a numeric suffix.
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip() or "unnamed"
node_filename: dict[str, str] = {}
seen_names: dict[str, int] = {}
@@ -696,7 +699,7 @@ def to_canvas(
CANVAS_COLORS = ["1", "2", "3", "4", "5", "6"] # red, orange, yellow, green, cyan, purple
def safe_name(label: str) -> str:
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label).strip() or "unnamed"
return re.sub(r'[\\/*?:"<>|#^[\]]', "", label.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")).strip() or "unnamed"
# Build node_filenames if not provided (same dedup logic as to_obsidian)
if node_filenames is None:
+1 -1
View File
@@ -1021,7 +1021,7 @@ def _extract_python_rationale(path: Path, result: dict) -> None:
return None
def _add_rationale(text: str, line: int, parent_nid: str) -> None:
label = text[:80].replace("\n", " ").strip()
label = text[:80].replace("\r\n", " ").replace("\r", " ").replace("\n", " ").strip()
rid = _make_id(stem, "rationale", str(line))
if rid not in seen_ids:
seen_ids.add(rid)
+2 -2
View File
@@ -124,7 +124,7 @@ def _install_hook(hooks_dir: Path, name: str, script: str, marker: str) -> str:
return f"already installed at {hook_path}"
hook_path.write_text(content.rstrip() + "\n\n" + script)
return f"appended to existing {name} hook at {hook_path}"
hook_path.write_text("#!/bin/bash\n" + script)
hook_path.write_text("#!/bin/sh\n" + script)
hook_path.chmod(0o755)
return f"installed at {hook_path}"
@@ -143,7 +143,7 @@ def _uninstall_hook(hooks_dir: Path, name: str, marker: str, marker_end: str) ->
content,
flags=re.DOTALL,
).strip()
if not new_content or new_content == "#!/bin/bash":
if not new_content or new_content in ("#!/bin/bash", "#!/bin/sh"):
hook_path.unlink()
return f"removed {name} hook at {hook_path}"
hook_path.write_text(new_content + "\n")
+6
View File
@@ -207,6 +207,12 @@ def ingest(url: str, target_dir: Path, author: str | None = None, contributor: s
print(f"Downloaded image: {out.name}")
return out
if url_type == "youtube":
from graphify.transcribe import download_audio
out = download_audio(url, target_dir)
print(f"Downloaded audio: {out.name}")
return out
if url_type == "tweet":
content, filename = _fetch_tweet(url, author, contributor)
elif url_type == "arxiv":
+11 -3
View File
@@ -5,12 +5,17 @@ import sys
from pathlib import Path
import networkx as nx
from networkx.readwrite import json_graph
from graphify.security import validate_graph_path, sanitize_label
from graphify.security import sanitize_label
def _load_graph(graph_path: str) -> nx.Graph:
try:
safe = validate_graph_path(graph_path)
resolved = Path(graph_path).resolve()
if resolved.suffix != ".json":
raise ValueError(f"Graph path must be a .json file, got: {graph_path!r}")
if not resolved.exists():
raise FileNotFoundError(f"Graph file not found: {resolved}")
safe = resolved
data = json.loads(safe.read_text())
try:
return json_graph.node_link_graph(data, edges="links")
@@ -309,7 +314,10 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
handler = _handlers.get(name)
if not handler:
return [types.TextContent(type="text", text=f"Unknown tool: {name}")]
return [types.TextContent(type="text", text=handler(arguments))]
try:
return [types.TextContent(type="text", text=handler(arguments))]
except Exception as exc:
return [types.TextContent(type="text", text=f"Error executing {name}: {exc}")]
import asyncio
File diff suppressed because it is too large. Load diff
+50 -1
View File
@@ -98,13 +98,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
**Step 2 - Transcribe:**
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -608,6 +655,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
+50 -1
View File
@@ -97,13 +97,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
**Step 2 - Transcribe:**
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -664,6 +711,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
File diff suppressed because it is too large. Load diff
+50 -1
View File
@@ -98,13 +98,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
**Step 2 - Transcribe:**
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -661,6 +708,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
+50 -1
View File
@@ -98,13 +98,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
**Step 2 - Transcribe:**
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -660,6 +707,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
+51 -2
View File
@@ -97,13 +97,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `GRAPHIFY_WHISPER_PROMPT` in the environment before running the transcription command.
**Step 2 - Transcribe:**
```bash
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -639,6 +686,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
@@ -774,7 +823,7 @@ G = json_graph.node_link_graph(data, edges='links')
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
'files': {'code': [], 'document': [], 'paper': []}}
tokens = {'input': 0, 'output':': 0}
tokens = {'input': 0, 'output': 0}
communities = cluster(G)
cohesion = score_all(G, communities)
+53 -1
View File
@@ -15,6 +15,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <path> # full pipeline on specific path
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
@@ -22,6 +23,8 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify add <url> # fetch URL, save to ./raw, update graph
@@ -87,13 +90,60 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from the detect output or analysis file. You are already a language model - write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` -> `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` -> `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `$env:GRAPHIFY_WHISPER_PROMPT` before running the transcription command.
**Step 2 - Transcribe (PowerShell):**
```powershell
& (Get-Content graphify-out\.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
```
After transcription:
- Read the transcript paths from `graphify-out\.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `$env:GRAPHIFY_WHISPER_MODEL = "<name>"` before running the command above.
### Step 3 - Extract entities and relationships
@@ -651,6 +701,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
+57 -2
View File
@@ -15,6 +15,8 @@ Turn any folder of files into a navigable knowledge graph with community detecti
/graphify <path> # full pipeline on specific path
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
@@ -100,13 +102,61 @@ Corpus: X files · ~Y words
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names.
- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 3 - no need to ask anything.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
Set it as `WHISPER_PROMPT` to use in the next command.
**Step 2 - Transcribe:**
```bash
GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed
$(cat graphify-out/.graphify_python) -c "
import json, os
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
print(json.dumps(transcript_paths))
" > graphify-out/.graphify_transcripts.json
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, set `GRAPHIFY_WHISPER_MODEL=<name>` in the environment before running the command above.
### Step 3 - Extract entities and relationships
@@ -340,6 +390,8 @@ print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(s
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`.
```bash
mkdir -p graphify-out
$(cat graphify-out/.graphify_python) -c "
@@ -664,6 +716,8 @@ Graph complete. Outputs in PATH_TO_DIR/graphify-out/
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
Then paste these sections from GRAPH_REPORT.md directly into the chat:
@@ -1147,8 +1201,9 @@ except RuntimeError as e:
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
+182
View File
@@ -0,0 +1,182 @@
# Video transcription using faster-whisper
# Converts video/audio files to text transcripts for graph extraction
from __future__ import annotations
import os
from pathlib import Path
VIDEO_EXTENSIONS = {'.mp4', '.mov', '.webm', '.mkv', '.avi', '.m4v', '.mp3', '.wav', '.m4a', '.ogg'}
URL_PREFIXES = ('http://', 'https://', 'www.')
_DEFAULT_MODEL = "base"
_TRANSCRIPTS_DIR = "graphify-out/transcripts"
_FALLBACK_PROMPT = "Use proper punctuation and paragraph breaks."
def _model_name() -> str:
return os.environ.get("GRAPHIFY_WHISPER_MODEL", _DEFAULT_MODEL)
def _get_whisper():
try:
from faster_whisper import WhisperModel
return WhisperModel
except ImportError as exc:
raise ImportError(
"Video transcription requires faster-whisper. "
"Run: pip install 'graphifyy[video]'"
) from exc
def _get_yt_dlp():
try:
import yt_dlp
return yt_dlp
except ImportError as exc:
raise ImportError(
"YouTube/URL download requires yt-dlp. "
"Run: pip install 'graphifyy[video]'"
) from exc
def is_url(path: str) -> bool:
"""Return True if the string looks like a URL rather than a file path."""
return any(path.startswith(p) for p in URL_PREFIXES)
def download_audio(url: str, output_dir: Path) -> Path:
"""Download audio-only stream from a URL using yt-dlp.
Returns the path to the downloaded audio file (.m4a or .opus).
Uses cached file if already downloaded.
"""
yt_dlp = _get_yt_dlp()
output_dir.mkdir(parents=True, exist_ok=True)
# yt-dlp uses %(title)s which can be long/weird — use a stable name based on URL hash
import hashlib
url_hash = hashlib.sha1(url.encode()).hexdigest()[:12]
out_template = str(output_dir / f"yt_{url_hash}.%(ext)s")
# Check for already-downloaded file
for ext in ('.m4a', '.opus', '.mp3', '.ogg', '.wav', '.webm'):
candidate = output_dir / f"yt_{url_hash}{ext}"
if candidate.exists():
print(f" cached audio: {candidate.name}")
return candidate
ydl_opts = {
'format': 'bestaudio[ext=m4a]/bestaudio/best',
'outtmpl': out_template,
'quiet': True,
'no_warnings': True,
'noplaylist': True,
'postprocessors': [], # no ffmpeg needed — use native audio
}
print(f" downloading audio: {url[:80]} ...", flush=True)
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
ext = info.get('ext', 'm4a')
downloaded = output_dir / f"yt_{url_hash}.{ext}"
if not downloaded.exists():
# yt-dlp may have picked a different extension
for p in output_dir.glob(f"yt_{url_hash}.*"):
downloaded = p
break
return downloaded
def build_whisper_prompt(god_nodes: list[dict]) -> str:
"""Build a domain hint for Whisper from god nodes extracted from the corpus.
Formats the top god node labels into a topic string for Whisper.
The coding agent (Claude Code, Codex, etc.) generates the actual one-sentence
domain hint from these labels and passes it via GRAPHIFY_WHISPER_PROMPT or
as initial_prompt — no separate API call needed here.
"""
if not god_nodes:
return _FALLBACK_PROMPT
override = os.environ.get("GRAPHIFY_WHISPER_PROMPT")
if override:
return override
labels = [n.get("label", "") for n in god_nodes[:10] if n.get("label")]
if not labels:
return _FALLBACK_PROMPT
topics = ", ".join(labels[:5])
return f"Technical discussion about {topics}. Use proper punctuation and paragraph breaks."
def transcribe(
video_path: Path | str,
output_dir: Path | None = None,
initial_prompt: str | None = None,
force: bool = False,
) -> Path:
"""Transcribe a video/audio file or URL to a .txt transcript.
If video_path is a URL, audio is downloaded first via yt-dlp.
Returns the path to the saved transcript file.
Uses cached transcript if it exists unless force=True.
initial_prompt: domain hint for Whisper (built from corpus god nodes).
force: re-transcribe even if transcript already exists.
"""
out_dir = Path(output_dir) if output_dir else Path(_TRANSCRIPTS_DIR)
out_dir.mkdir(parents=True, exist_ok=True)
if is_url(str(video_path)):
audio_path = download_audio(str(video_path), out_dir / "downloads")
else:
audio_path = Path(video_path)
transcript_path = out_dir / (audio_path.stem + ".txt")
if transcript_path.exists() and not force:
return transcript_path
WhisperModel = _get_whisper()
model_name = _model_name()
prompt = initial_prompt or _FALLBACK_PROMPT
print(f" transcribing {audio_path.name} (model={model_name}) ...", flush=True)
model = WhisperModel(model_name, device="cpu", compute_type="int8")
segments, info = model.transcribe(
str(audio_path),
beam_size=5,
initial_prompt=prompt,
)
lines = [segment.text.strip() for segment in segments if segment.text.strip()]
transcript = "\n".join(lines)
transcript_path.write_text(transcript, encoding="utf-8")
lang = info.language if hasattr(info, "language") else "unknown"
print(f" transcript saved -> {transcript_path} (lang={lang}, {len(lines)} segments)")
return transcript_path
def transcribe_all(
video_files: list[str],
output_dir: Path | None = None,
initial_prompt: str | None = None,
) -> list[str]:
"""Transcribe a list of video/audio files or URLs, return paths to transcript .txt files.
Already-transcribed files are returned from cache instantly.
initial_prompt is shared across all files — built once from corpus god nodes.
"""
if not video_files:
return []
transcript_paths = []
for vf in video_files:
try:
t = transcribe(vf, output_dir, initial_prompt=initial_prompt)
transcript_paths.append(str(t))
except Exception as exc:
print(f" warning: could not transcribe {vf}: {exc}")
return transcript_paths
+2 -2
View File
@@ -18,7 +18,7 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
"""
try:
from graphify.extract import extract
from graphify.detect import detect, FileType
from graphify.detect import detect
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
@@ -26,7 +26,7 @@ def _rebuild_code(watch_path: Path, *, follow_symlinks: bool = False) -> bool:
from graphify.export import to_json
detected = detect(watch_path, follow_symlinks=follow_symlinks)
code_files = [Path(f) for f in detected[FileType.CODE]]
code_files = [Path(f) for f in detected['files']['code']]
if not code_files:
print("[graphify watch] No code files found - nothing to rebuild.")
+6 -5
View File
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
[project]
name = "graphifyy"
version = "0.3.20"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, OpenClaw) - turn any folder of code, docs, papers, or images into a queryable knowledge graph"
version = "0.3.29"
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, OpenClaw, Factory Droid, Trae) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
readme = "README.md"
license = { file = "LICENSE" }
keywords = ["claude", "claude-code", "codex", "opencode", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
keywords = ["claude", "claude-code", "codex", "opencode", "cursor", "knowledge-graph", "rag", "graphrag", "obsidian", "community-detection", "tree-sitter", "leiden", "llm"]
requires-python = ">=3.10"
dependencies = [
"networkx",
@@ -47,7 +47,8 @@ pdf = ["pypdf", "html2text"]
watch = ["watchdog"]
leiden = ["graspologic"]
office = ["python-docx", "openpyxl"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic", "python-docx", "openpyxl"]
video = ["faster-whisper", "yt-dlp"]
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic", "python-docx", "openpyxl", "faster-whisper", "yt-dlp"]
[project.scripts]
graphify = "graphify.__main__:main"
@@ -57,4 +58,4 @@ where = ["."]
include = ["graphify*"]
[tool.setuptools.package-data]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"]
graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-aider.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md"]
+53 -1
View File
@@ -1,7 +1,7 @@
"""Tests for graphify/cache.py."""
import pytest
from pathlib import Path
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache
from graphify.cache import file_hash, cache_dir, load_cached, save_cached, cached_files, clear_cache, _body_content
@pytest.fixture
@@ -72,3 +72,55 @@ def test_clear_cache(tmp_file, cache_root):
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) > 0
clear_cache(cache_root)
assert len(list((cache_root / "graphify-out" / "cache").glob("*.json"))) == 0
def test_md_frontmatter_only_change_same_hash(tmp_path):
"""Changing only frontmatter fields in a .md file does not change the hash."""
f = tmp_path / "doc.md"
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nBody text.")
h1 = file_hash(f)
f.write_text("---\nreviewed: 2026-04-09\n---\n\n# Title\n\nBody text.")
h2 = file_hash(f)
assert h1 == h2
def test_md_body_change_different_hash(tmp_path):
"""Changing the body of a .md file produces a different hash."""
f = tmp_path / "doc.md"
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nOriginal body.")
h1 = file_hash(f)
f.write_text("---\nreviewed: 2026-01-01\n---\n\n# Title\n\nChanged body.")
h2 = file_hash(f)
assert h1 != h2
def test_md_no_frontmatter_hashed_normally(tmp_path):
"""A .md file with no frontmatter is hashed by its full content."""
f = tmp_path / "doc.md"
f.write_text("# Just a heading\n\nNo frontmatter here.")
h1 = file_hash(f)
f.write_text("# Just a heading\n\nDifferent content.")
h2 = file_hash(f)
assert h1 != h2
def test_non_md_file_hashed_fully(tmp_path):
"""Non-.md files are still hashed by their full content."""
f = tmp_path / "script.py"
f.write_text("# comment\nx = 1")
h1 = file_hash(f)
f.write_text("# changed comment\nx = 1")
h2 = file_hash(f)
assert h1 != h2
def test_body_content_strips_frontmatter():
"""_body_content correctly strips YAML frontmatter."""
content = b"---\ntitle: Test\n---\n\nActual body."
assert _body_content(content) == b"\n\nActual body."
def test_body_content_no_frontmatter():
"""_body_content returns content unchanged when no frontmatter present."""
content = b"No frontmatter here."
assert _body_content(content) == content
+90
View File
@@ -138,6 +138,59 @@ def test_detect_follows_symlinked_file(tmp_path):
assert any("link.py" in f for f in code)
def test_graphifyignore_discovered_from_parent(tmp_path):
"""A .graphifyignore in a parent directory applies to subdirectory scans."""
(tmp_path / ".graphifyignore").write_text("vendor/\n")
sub = tmp_path / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert not any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] >= 1
def test_graphifyignore_stops_at_git_boundary(tmp_path):
"""Upward search stops at the git repo root (.git directory)."""
(tmp_path / ".graphifyignore").write_text("main.py\n")
repo = tmp_path / "repo"
repo.mkdir()
(repo / ".git").mkdir()
sub = repo / "sub"
sub.mkdir()
(sub / "main.py").write_text("x = 1")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert result["graphifyignore_patterns"] == 0
def test_graphifyignore_at_git_root_is_included(tmp_path):
"""A .graphifyignore at the git repo root is included when scanning a subdir."""
repo = tmp_path / "repo"
repo.mkdir()
(repo / ".git").mkdir()
(repo / ".graphifyignore").write_text("vendor/\n")
sub = repo / "packages" / "mylib"
sub.mkdir(parents=True)
(sub / "main.py").write_text("x = 1")
vendor = sub / "vendor"
vendor.mkdir()
(vendor / "dep.py").write_text("y = 2")
result = detect(sub)
code_files = result["files"]["code"]
assert any("main.py" in f for f in code_files)
assert not any("vendor" in f for f in code_files)
assert result["graphifyignore_patterns"] == 1
def test_detect_handles_circular_symlinks(tmp_path):
sub = tmp_path / "a"
sub.mkdir()
@@ -146,3 +199,40 @@ def test_detect_handles_circular_symlinks(tmp_path):
result = detect(tmp_path, follow_symlinks=True)
assert any("main.py" in f for f in result["files"]["code"])
def test_classify_video_extensions():
"""Video and audio file extensions should classify as VIDEO."""
from graphify.detect import FileType
assert classify_file(Path("lecture.mp4")) == FileType.VIDEO
assert classify_file(Path("podcast.mp3")) == FileType.VIDEO
assert classify_file(Path("talk.mov")) == FileType.VIDEO
assert classify_file(Path("recording.wav")) == FileType.VIDEO
assert classify_file(Path("webinar.webm")) == FileType.VIDEO
assert classify_file(Path("audio.m4a")) == FileType.VIDEO
def test_detect_includes_video_key(tmp_path):
"""detect() result always includes a 'video' key even with no video files."""
(tmp_path / "main.py").write_text("x = 1")
result = detect(tmp_path)
assert "video" in result["files"]
def test_detect_finds_video_files(tmp_path):
"""detect() correctly counts video files and does not add them to word count."""
(tmp_path / "lecture.mp4").write_bytes(b"fake video data")
(tmp_path / "notes.md").write_text("# Notes\nSome content here.")
result = detect(tmp_path)
assert len(result["files"]["video"]) == 1
assert any("lecture.mp4" in f for f in result["files"]["video"])
# total_words should not include video files (they have no readable text)
assert result["total_words"] >= 0 # won't crash
def test_detect_video_not_in_words(tmp_path):
"""Video files do not contribute to total_words."""
(tmp_path / "clip.mp4").write_bytes(b"\x00" * 100)
result = detect(tmp_path)
# Only video file present — total_words should be 0
assert result["total_words"] == 0
+93
View File
@@ -225,3 +225,96 @@ def test_opencode_agents_uninstall_removes_plugin(tmp_path):
if config_file.exists():
config = _json.loads(config_file.read_text())
assert not any("graphify.js" in p for p in config.get("plugin", []))
# ── Cursor ────────────────────────────────────────────────────────────────────
def test_cursor_install_writes_rule(tmp_path):
"""cursor install writes .cursor/rules/graphify.mdc."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
assert rule.exists()
content = rule.read_text()
assert "alwaysApply: true" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_cursor_install_idempotent(tmp_path):
"""cursor install does not overwrite an existing rule file."""
from graphify.__main__ import _cursor_install
_cursor_install(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
original = rule.read_text()
_cursor_install(tmp_path)
assert rule.read_text() == original
def test_cursor_uninstall_removes_rule(tmp_path):
"""cursor uninstall removes the rule file."""
from graphify.__main__ import _cursor_install, _cursor_uninstall
_cursor_install(tmp_path)
_cursor_uninstall(tmp_path)
rule = tmp_path / ".cursor" / "rules" / "graphify.mdc"
assert not rule.exists()
def test_cursor_uninstall_noop_if_not_installed(tmp_path):
"""cursor uninstall does nothing if rule was never written."""
from graphify.__main__ import _cursor_uninstall
_cursor_uninstall(tmp_path) # should not raise
# ── Gemini CLI ────────────────────────────────────────────────────────────────
def test_gemini_install_writes_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.exists()
assert "graphify-out/GRAPH_REPORT.md" in md.read_text()
def test_gemini_install_writes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
settings = _json.loads((tmp_path / ".gemini" / "settings.json").read_text())
hooks = settings["hooks"]["BeforeTool"]
assert any("graphify" in str(h) for h in hooks)
def test_gemini_install_idempotent(tmp_path):
from graphify.__main__ import gemini_install
gemini_install(tmp_path)
gemini_install(tmp_path)
md = tmp_path / "GEMINI.md"
assert md.read_text().count("## graphify") == 1
def test_gemini_install_merges_existing_gemini_md(tmp_path):
from graphify.__main__ import gemini_install
(tmp_path / "GEMINI.md").write_text("# My project rules\n")
gemini_install(tmp_path)
content = (tmp_path / "GEMINI.md").read_text()
assert "# My project rules" in content
assert "graphify-out/GRAPH_REPORT.md" in content
def test_gemini_uninstall_removes_section(tmp_path):
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
md = tmp_path / "GEMINI.md"
assert not md.exists()
def test_gemini_uninstall_removes_hook(tmp_path):
import json as _json
from graphify.__main__ import gemini_install, gemini_uninstall
gemini_install(tmp_path)
gemini_uninstall(tmp_path)
settings_path = tmp_path / ".gemini" / "settings.json"
if settings_path.exists():
settings = _json.loads(settings_path.read_text())
hooks = settings.get("hooks", {}).get("BeforeTool", [])
assert not any("graphify" in str(h) for h in hooks)
def test_gemini_uninstall_noop_if_not_installed(tmp_path):
from graphify.__main__ import gemini_uninstall
gemini_uninstall(tmp_path) # should not raise
+1 -4
View File
@@ -138,14 +138,11 @@ def test_subgraph_to_text_edge_included():
# --- _load_graph ---
def test_load_graph_roundtrip(tmp_path):
from unittest.mock import patch
G = _make_graph()
data = json_graph.node_link_data(G, edges="links")
p = tmp_path / "graph.json"
p.write_text(json.dumps(data))
# validate_graph_path is tested separately; here we test parse correctness
with patch("graphify.serve.validate_graph_path", return_value=p):
G2 = _load_graph(str(p))
G2 = _load_graph(str(p))
assert G2.number_of_nodes() == G.number_of_nodes()
assert G2.number_of_edges() == G.number_of_edges()
+147
View File
@@ -0,0 +1,147 @@
"""Tests for graphify.transcribe — video/audio transcription support."""
from __future__ import annotations
import os
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from graphify.transcribe import (
VIDEO_EXTENSIONS,
build_whisper_prompt,
transcribe,
transcribe_all,
)
# ---------------------------------------------------------------------------
# VIDEO_EXTENSIONS
# ---------------------------------------------------------------------------
def test_video_extensions_set():
assert ".mp4" in VIDEO_EXTENSIONS
assert ".mp3" in VIDEO_EXTENSIONS
assert ".wav" in VIDEO_EXTENSIONS
assert ".mov" in VIDEO_EXTENSIONS
assert ".py" not in VIDEO_EXTENSIONS
# ---------------------------------------------------------------------------
# build_whisper_prompt
# ---------------------------------------------------------------------------
def test_build_whisper_prompt_no_nodes():
"""Empty god_nodes returns fallback prompt."""
prompt = build_whisper_prompt([])
assert "punctuation" in prompt.lower() or len(prompt) > 0
def test_build_whisper_prompt_env_override(monkeypatch):
"""GRAPHIFY_WHISPER_PROMPT env var short-circuits LLM call."""
monkeypatch.setenv("GRAPHIFY_WHISPER_PROMPT", "Custom domain hint.")
prompt = build_whisper_prompt([{"label": "Python"}, {"label": "FastAPI"}])
assert prompt == "Custom domain hint."
def test_build_whisper_prompt_returns_topic_string():
"""Returns a topic-based prompt from god node labels — no LLM call."""
god_nodes = [{"label": "neural networks"}, {"label": "transformers"}, {"label": "attention"}]
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("GRAPHIFY_WHISPER_PROMPT", None)
prompt = build_whisper_prompt(god_nodes)
assert "neural networks" in prompt.lower() or "transformers" in prompt.lower()
assert "punctuation" in prompt.lower()
def test_build_whisper_prompt_nodes_without_labels():
"""Nodes missing 'label' keys are safely skipped."""
god_nodes = [{"id": "1"}, {"id": "2", "label": ""}]
prompt = build_whisper_prompt(god_nodes)
assert len(prompt) > 0
# ---------------------------------------------------------------------------
# transcribe
# ---------------------------------------------------------------------------
def test_transcribe_uses_cache(tmp_path):
"""If transcript already exists, transcribe() returns cached path without running Whisper."""
video = tmp_path / "lecture.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
cached = out_dir / "lecture.txt"
cached.write_text("Cached transcript content.")
result = transcribe(video, output_dir=out_dir)
assert result == cached
def test_transcribe_force_reruns(tmp_path):
"""force=True re-transcribes even when cache exists."""
video = tmp_path / "talk.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
(out_dir / "talk.txt").write_text("Old transcript.")
fake_segment = MagicMock()
fake_segment.text = "New transcript segment."
fake_info = MagicMock()
fake_info.language = "en"
fake_model = MagicMock()
fake_model.transcribe.return_value = ([fake_segment], fake_info)
with patch("graphify.transcribe._get_whisper", return_value=lambda *a, **kw: fake_model):
result = transcribe(video, output_dir=out_dir, force=True)
assert result.read_text() == "New transcript segment."
def test_transcribe_missing_faster_whisper(tmp_path):
"""ImportError propagates when faster_whisper is not installed."""
video = tmp_path / "clip.mp4"
video.write_bytes(b"fake")
with patch("graphify.transcribe._get_whisper", side_effect=ImportError("faster-whisper not installed")):
with pytest.raises(ImportError):
transcribe(video, output_dir=tmp_path / "out")
# ---------------------------------------------------------------------------
# transcribe_all
# ---------------------------------------------------------------------------
def test_transcribe_all_empty():
"""Empty input returns empty list without error."""
assert transcribe_all([]) == []
def test_transcribe_all_uses_cache(tmp_path):
"""transcribe_all() returns cached paths for already-transcribed files."""
video = tmp_path / "lecture.mp4"
video.write_bytes(b"fake")
out_dir = tmp_path / "transcripts"
out_dir.mkdir()
cached = out_dir / "lecture.txt"
cached.write_text("Cached.")
results = transcribe_all([str(video)], output_dir=out_dir)
assert len(results) == 1
assert str(cached) in results[0]
def test_transcribe_all_skips_failed(tmp_path):
"""transcribe_all() warns and skips files that fail to transcribe."""
video = tmp_path / "broken.mp4"
video.write_bytes(b"fake")
def raise_import(*args, **kwargs):
raise ImportError("faster_whisper not installed")
with patch("graphify.transcribe.transcribe", side_effect=RuntimeError("boom")):
results = transcribe_all([str(video)], output_dir=tmp_path / "out")
assert results == []