create-huenei-template 0.2.10 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Document-to-Markdown converter for the /analisis-docs command.
4
+
5
+ Scans a docs/ folder, converts every supported file to Markdown,
6
+ stores results in .cursor/cache/docs-md/ with hash-based caching,
7
+ and generates a consolidated _all_docs.md file.
8
+
9
+ Usage:
10
+ python .cursor/tools/doc-reader/convert_to_md.py ./docs
11
+ python .cursor/tools/doc-reader/convert_to_md.py ./docs --only file1.pdf file2.xlsx
12
+
13
+ Supported formats: .pdf, .xlsx, .xls, .csv, .docx, .md, .txt
14
+ Unsupported: .doc (convert to .docx or .md first)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ CACHE_DIR = Path(".cursor/cache/docs-md")
26
+ RESULT_FILE = CACHE_DIR / "_result.json"
27
+ SUPPORTED_EXTENSIONS = {".pdf", ".xlsx", ".xls", ".csv", ".docx", ".md", ".txt"}
28
+ UNSUPPORTED_EXTENSIONS = {".doc"}
29
+
30
+
31
+ def compute_hash(file_path: Path) -> str:
32
+ h = hashlib.sha256()
33
+ with open(file_path, "rb") as f:
34
+ for chunk in iter(lambda: f.read(8192), b""):
35
+ h.update(chunk)
36
+ return h.hexdigest()
37
+
38
+
39
+ def cache_is_fresh(stem: str, current_hash: str) -> bool:
40
+ hash_file = CACHE_DIR / f"{stem}.hash"
41
+ if not hash_file.exists():
42
+ return False
43
+ return hash_file.read_text(encoding="utf-8").strip() == current_hash
44
+
45
+
46
+ def save_to_cache(stem: str, markdown: str, file_hash: str) -> None:
47
+ (CACHE_DIR / f"{stem}.md").write_text(markdown, encoding="utf-8")
48
+ (CACHE_DIR / f"{stem}.hash").write_text(file_hash, encoding="utf-8")
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Converters
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def convert_pdf(file_path: Path) -> str:
56
+ import pdfplumber
57
+
58
+ parts: list[str] = [f"# {file_path.name}\n"]
59
+ with pdfplumber.open(file_path) as pdf:
60
+ for i, page in enumerate(pdf.pages, 1):
61
+ text = page.extract_text()
62
+ if text:
63
+ parts.append(f"## Page {i}\n\n{text}\n")
64
+
65
+ tables = page.extract_tables()
66
+ for t_idx, table in enumerate(tables, 1):
67
+ if not table:
68
+ continue
69
+ headers = [str(c or "") for c in table[0]]
70
+ parts.append(f"### Table {t_idx}\n")
71
+ parts.append("| " + " | ".join(headers) + " |")
72
+ parts.append("| " + " | ".join("---" for _ in headers) + " |")
73
+ for row in table[1:]:
74
+ parts.append("| " + " | ".join(str(c or "") for c in row) + " |")
75
+ parts.append("")
76
+
77
+ return "\n".join(parts)
78
+
79
+
80
+ def convert_excel(file_path: Path) -> str:
81
+ import pandas as pd
82
+
83
+ parts: list[str] = [f"# {file_path.name}\n"]
84
+ xls = pd.ExcelFile(file_path)
85
+ for sheet_name in xls.sheet_names:
86
+ df = pd.read_excel(xls, sheet_name=sheet_name)
87
+ parts.append(f"## Sheet: {sheet_name}\n")
88
+ if df.empty:
89
+ parts.append("*Empty sheet*\n")
90
+ else:
91
+ parts.append(df.to_markdown(index=False))
92
+ parts.append("")
93
+ return "\n".join(parts)
94
+
95
+
96
+ def convert_csv(file_path: Path) -> str:
97
+ import pandas as pd
98
+
99
+ parts: list[str] = [f"# {file_path.name}\n"]
100
+ df = pd.read_csv(file_path)
101
+ if df.empty:
102
+ parts.append("*Empty file*\n")
103
+ else:
104
+ parts.append(df.to_markdown(index=False))
105
+ parts.append("")
106
+ return "\n".join(parts)
107
+
108
+
109
+ def convert_docx(file_path: Path) -> str:
110
+ from docx import Document
111
+
112
+ doc = Document(str(file_path))
113
+ parts: list[str] = [f"# {file_path.name}\n"]
114
+ for para in doc.paragraphs:
115
+ text = para.text.strip()
116
+ if not text:
117
+ continue
118
+ style = (para.style.name or "").lower()
119
+ if "heading 1" in style:
120
+ parts.append(f"## {text}\n")
121
+ elif "heading 2" in style:
122
+ parts.append(f"### {text}\n")
123
+ elif "heading 3" in style:
124
+ parts.append(f"#### {text}\n")
125
+ elif "list" in style:
126
+ parts.append(f"- {text}")
127
+ else:
128
+ parts.append(f"{text}\n")
129
+
130
+ for table in doc.tables:
131
+ headers = [cell.text.strip() for cell in table.rows[0].cells]
132
+ parts.append("\n| " + " | ".join(headers) + " |")
133
+ parts.append("| " + " | ".join("---" for _ in headers) + " |")
134
+ for row in table.rows[1:]:
135
+ parts.append("| " + " | ".join(cell.text.strip() for cell in row.cells) + " |")
136
+ parts.append("")
137
+
138
+ return "\n".join(parts)
139
+
140
+
141
+ def copy_text(file_path: Path) -> str:
142
+ content = file_path.read_text(encoding="utf-8", errors="replace")
143
+ if file_path.suffix.lower() == ".txt":
144
+ return f"# {file_path.name}\n\n{content}"
145
+ return content
146
+
147
+
148
+ CONVERTERS = {
149
+ ".pdf": convert_pdf,
150
+ ".xlsx": convert_excel,
151
+ ".xls": convert_excel,
152
+ ".csv": convert_csv,
153
+ ".docx": convert_docx,
154
+ ".md": copy_text,
155
+ ".txt": copy_text,
156
+ }
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # Main
161
+ # ---------------------------------------------------------------------------
162
+
163
+ def safe_stem(file_path: Path, docs_root: Path) -> str:
164
+ """Produce a unique cache-friendly name preserving subdirectory info."""
165
+ rel = file_path.relative_to(docs_root)
166
+ return str(rel.with_suffix("")).replace(os.sep, "__")
167
+
168
+
169
+ def build_all_docs(cache_dir: Path) -> None:
170
+ parts: list[str] = []
171
+ for md_file in sorted(cache_dir.glob("*.md")):
172
+ if md_file.name.startswith("_"):
173
+ continue
174
+ parts.append(md_file.read_text(encoding="utf-8"))
175
+ parts.append("\n---\n")
176
+ (cache_dir / "_all_docs.md").write_text("\n".join(parts), encoding="utf-8")
177
+
178
+
179
+ def parse_args() -> tuple[Path, set[str] | None]:
180
+ """Parse CLI arguments. Returns (docs_root, only_files_or_None)."""
181
+ if len(sys.argv) < 2:
182
+ print(json.dumps({"error": "Usage: python convert_to_md.py <docs_folder> [--only file1 file2 ...]"}))
183
+ sys.exit(1)
184
+
185
+ docs_root = Path(sys.argv[1])
186
+ only_files: set[str] | None = None
187
+
188
+ if "--only" in sys.argv:
189
+ idx = sys.argv.index("--only")
190
+ only_files = set(sys.argv[idx + 1:])
191
+
192
+ return docs_root, only_files
193
+
194
+
195
+ def main() -> None:
196
+ docs_root, only_files = parse_args()
197
+
198
+ if not docs_root.is_dir():
199
+ print(json.dumps({"error": f"Directory not found: {docs_root}"}))
200
+ sys.exit(1)
201
+
202
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
203
+
204
+ results: list[dict] = []
205
+ has_failures = False
206
+
207
+ for file_path in sorted(docs_root.rglob("*")):
208
+ if not file_path.is_file():
209
+ continue
210
+ if file_path.parent.name.startswith("_"):
211
+ continue
212
+
213
+ if only_files and str(file_path) not in only_files:
214
+ continue
215
+
216
+ ext = file_path.suffix.lower()
217
+ stem = safe_stem(file_path, docs_root)
218
+
219
+ if ext in UNSUPPORTED_EXTENSIONS:
220
+ results.append({
221
+ "file": str(file_path),
222
+ "status": "unsupported",
223
+ "message": f"Format '{ext}' is not supported. Please convert to .docx or .md.",
224
+ })
225
+ has_failures = True
226
+ continue
227
+
228
+ if ext not in SUPPORTED_EXTENSIONS:
229
+ results.append({
230
+ "file": str(file_path),
231
+ "status": "unsupported",
232
+ "message": f"Extension '{ext}' is not supported. Convert to .md or .txt.",
233
+ })
234
+ has_failures = True
235
+ continue
236
+
237
+ file_hash = compute_hash(file_path)
238
+
239
+ if cache_is_fresh(stem, file_hash):
240
+ results.append({
241
+ "file": str(file_path),
242
+ "status": "skipped",
243
+ "message": "Cache is up to date.",
244
+ "cached_as": f"{stem}.md",
245
+ })
246
+ continue
247
+
248
+ converter = CONVERTERS[ext]
249
+ try:
250
+ markdown = converter(file_path)
251
+ save_to_cache(stem, markdown, file_hash)
252
+ results.append({
253
+ "file": str(file_path),
254
+ "status": "ok",
255
+ "message": "Converted successfully.",
256
+ "cached_as": f"{stem}.md",
257
+ })
258
+ except Exception as exc:
259
+ results.append({
260
+ "file": str(file_path),
261
+ "status": "fail",
262
+ "message": str(exc),
263
+ })
264
+ has_failures = True
265
+
266
+ build_all_docs(CACHE_DIR)
267
+
268
+ output = {
269
+ "cache_dir": str(CACHE_DIR),
270
+ "all_docs": str(CACHE_DIR / "_all_docs.md"),
271
+ "total": len(results),
272
+ "ok": sum(1 for r in results if r["status"] == "ok"),
273
+ "skipped": sum(1 for r in results if r["status"] == "skipped"),
274
+ "failed": sum(1 for r in results if r["status"] in ("fail", "unsupported")),
275
+ "has_failures": has_failures,
276
+ "files": results,
277
+ }
278
+
279
+ RESULT_FILE.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8")
280
+ print(json.dumps(output, indent=2, ensure_ascii=False))
281
+ sys.exit(1 if has_failures else 0)
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()
@@ -0,0 +1,325 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Document-to-Markdown converter — TypeScript fallback.
4
+ *
5
+ * Same cache directory, hash logic, and JSON output as the Python script.
6
+ * Used when Python dependencies fail to install.
7
+ *
8
+ * Run via npx (no package.json / node_modules needed):
9
+ * npx --package=tsx --package=xlsx --package=mammoth --package=pdf-parse tsx \
10
+ * .cursor/tools/doc-reader/convert_to_md.ts ./docs
11
+ *
12
+ * To process only files that Python failed to convert:
13
+ * npx --package=tsx --package=xlsx --package=mammoth --package=pdf-parse tsx \
14
+ * .cursor/tools/doc-reader/convert_to_md.ts ./docs \
15
+ * --only-failed .cursor/cache/docs-md/_result.json
16
+ *
17
+ * Supported: .pdf, .xlsx, .xls, .csv, .docx, .md, .txt
18
+ * Unsupported: .doc (convert to .docx or .md first)
19
+ */
20
+
21
+ import { createHash } from "crypto";
22
+ import {
23
+ readFileSync,
24
+ writeFileSync,
25
+ mkdirSync,
26
+ existsSync,
27
+ readdirSync,
28
+ statSync,
29
+ } from "fs";
30
+ import { join, extname, relative, sep } from "path";
31
+
32
+ const CACHE_DIR = join(".cursor", "cache", "docs-md");
33
+ const RESULT_FILE = join(CACHE_DIR, "_result.json");
34
+
35
+ const SUPPORTED = new Set([".pdf", ".xlsx", ".xls", ".csv", ".docx", ".md", ".txt"]);
36
+ const UNSUPPORTED = new Set([".doc"]);
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Helpers
40
+ // ---------------------------------------------------------------------------
41
+
42
+ function computeHash(filePath: string): string {
43
+ const data = readFileSync(filePath);
44
+ return createHash("sha256").update(data).digest("hex");
45
+ }
46
+
47
+ function safeStem(filePath: string, docsRoot: string): string {
48
+ const rel = relative(docsRoot, filePath);
49
+ const noExt = rel.replace(/\.[^.]+$/, "");
50
+ return noExt.split(sep).join("__");
51
+ }
52
+
53
+ function cacheIsFresh(stem: string, currentHash: string): boolean {
54
+ const hashFile = join(CACHE_DIR, `${stem}.hash`);
55
+ if (!existsSync(hashFile)) return false;
56
+ return readFileSync(hashFile, "utf-8").trim() === currentHash;
57
+ }
58
+
59
+ function saveToCache(stem: string, markdown: string, hash: string): void {
60
+ writeFileSync(join(CACHE_DIR, `${stem}.md`), markdown, "utf-8");
61
+ writeFileSync(join(CACHE_DIR, `${stem}.hash`), hash, "utf-8");
62
+ }
63
+
64
+ function walkDir(dir: string): string[] {
65
+ const results: string[] = [];
66
+ for (const entry of readdirSync(dir)) {
67
+ if (entry.startsWith("_")) continue;
68
+ const full = join(dir, entry);
69
+ const st = statSync(full);
70
+ if (st.isDirectory()) {
71
+ results.push(...walkDir(full));
72
+ } else if (st.isFile()) {
73
+ results.push(full);
74
+ }
75
+ }
76
+ return results.sort();
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // Converters
81
+ // ---------------------------------------------------------------------------
82
+
83
+ async function convertPdf(filePath: string): Promise<string> {
84
+ const pdfParse = require("pdf-parse");
85
+ const buffer = readFileSync(filePath);
86
+ const data = await pdfParse(buffer);
87
+ const name = filePath.split(sep).pop() || filePath;
88
+ return `# ${name}\n\n${data.text}\n`;
89
+ }
90
+
91
+ function convertExcel(filePath: string): string {
92
+ const XLSX = require("xlsx");
93
+ const workbook = XLSX.readFile(filePath);
94
+ const name = filePath.split(sep).pop() || filePath;
95
+ const parts: string[] = [`# ${name}\n`];
96
+
97
+ for (const sheetName of workbook.SheetNames) {
98
+ const sheet = workbook.Sheets[sheetName];
99
+ const rows: unknown[][] = XLSX.utils.sheet_to_json(sheet, { header: 1 });
100
+ parts.push(`## Sheet: ${sheetName}\n`);
101
+
102
+ if (rows.length === 0) {
103
+ parts.push("*Empty sheet*\n");
104
+ continue;
105
+ }
106
+
107
+ const headers = (rows[0] as unknown[]).map((h) => String(h ?? ""));
108
+ parts.push("| " + headers.join(" | ") + " |");
109
+ parts.push("| " + headers.map(() => "---").join(" | ") + " |");
110
+ for (let i = 1; i < rows.length; i++) {
111
+ const row = rows[i] as unknown[];
112
+ parts.push(
113
+ "| " + headers.map((_, j) => String(row[j] ?? "")).join(" | ") + " |"
114
+ );
115
+ }
116
+ parts.push("");
117
+ }
118
+ return parts.join("\n");
119
+ }
120
+
121
+ function convertCsv(filePath: string): string {
122
+ const XLSX = require("xlsx");
123
+ const workbook = XLSX.readFile(filePath);
124
+ const name = filePath.split(sep).pop() || filePath;
125
+ const parts: string[] = [`# ${name}\n`];
126
+
127
+ const sheetName = workbook.SheetNames[0];
128
+ if (!sheetName) return parts.join("\n") + "\n*Empty file*\n";
129
+
130
+ const sheet = workbook.Sheets[sheetName];
131
+ const rows: unknown[][] = XLSX.utils.sheet_to_json(sheet, { header: 1 });
132
+
133
+ if (rows.length === 0) {
134
+ parts.push("*Empty file*\n");
135
+ return parts.join("\n");
136
+ }
137
+
138
+ const headers = (rows[0] as unknown[]).map((h) => String(h ?? ""));
139
+ parts.push("| " + headers.join(" | ") + " |");
140
+ parts.push("| " + headers.map(() => "---").join(" | ") + " |");
141
+ for (let i = 1; i < rows.length; i++) {
142
+ const row = rows[i] as unknown[];
143
+ parts.push(
144
+ "| " + headers.map((_, j) => String(row[j] ?? "")).join(" | ") + " |"
145
+ );
146
+ }
147
+ parts.push("");
148
+ return parts.join("\n");
149
+ }
150
+
151
+ async function convertDocx(filePath: string): Promise<string> {
152
+ const mammoth = require("mammoth");
153
+ const result = await mammoth.convertToMarkdown({ path: filePath });
154
+ const name = filePath.split(sep).pop() || filePath;
155
+ return `# ${name}\n\n${result.value}`;
156
+ }
157
+
158
+ function copyText(filePath: string): string {
159
+ const content = readFileSync(filePath, "utf-8");
160
+ const name = filePath.split(sep).pop() || filePath;
161
+ if (extname(filePath).toLowerCase() === ".txt") {
162
+ return `# ${name}\n\n${content}`;
163
+ }
164
+ return content;
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // Main
169
+ // ---------------------------------------------------------------------------
170
+
171
+ function buildAllDocs(): void {
172
+ const files = readdirSync(CACHE_DIR)
173
+ .filter((f) => f.endsWith(".md") && !f.startsWith("_"))
174
+ .sort();
175
+ const parts: string[] = [];
176
+ for (const f of files) {
177
+ parts.push(readFileSync(join(CACHE_DIR, f), "utf-8"));
178
+ parts.push("\n---\n");
179
+ }
180
+ writeFileSync(join(CACHE_DIR, "_all_docs.md"), parts.join("\n"), "utf-8");
181
+ }
182
+
183
+ interface FileResult {
184
+ file: string;
185
+ status: "ok" | "skipped" | "fail" | "unsupported";
186
+ message: string;
187
+ cached_as?: string;
188
+ }
189
+
190
+ async function main(): Promise<void> {
191
+ const args = process.argv.slice(2);
192
+ if (args.length === 0) {
193
+ console.log(
194
+ JSON.stringify({
195
+ error:
196
+ "Usage: tsx convert_to_md.ts <docs_folder> [--only-failed <result.json>]",
197
+ })
198
+ );
199
+ process.exit(1);
200
+ }
201
+
202
+ const docsRoot = args[0];
203
+ if (!existsSync(docsRoot) || !statSync(docsRoot).isDirectory()) {
204
+ console.log(
205
+ JSON.stringify({ error: `Directory not found: ${docsRoot}` })
206
+ );
207
+ process.exit(1);
208
+ }
209
+
210
+ mkdirSync(CACHE_DIR, { recursive: true });
211
+
212
+ let onlyFiles: Set<string> | null = null;
213
+ const onlyIdx = args.indexOf("--only-failed");
214
+ if (onlyIdx !== -1 && args[onlyIdx + 1]) {
215
+ const resultPath = args[onlyIdx + 1];
216
+ if (existsSync(resultPath)) {
217
+ const prev = JSON.parse(readFileSync(resultPath, "utf-8"));
218
+ onlyFiles = new Set(
219
+ (prev.files as FileResult[])
220
+ .filter((f) => f.status === "fail")
221
+ .map((f) => f.file)
222
+ );
223
+ }
224
+ }
225
+
226
+ const allFiles = walkDir(docsRoot);
227
+ const results: FileResult[] = [];
228
+ let hasFailures = false;
229
+
230
+ for (const filePath of allFiles) {
231
+ if (onlyFiles && !onlyFiles.has(filePath)) continue;
232
+
233
+ const ext = extname(filePath).toLowerCase();
234
+ const stem = safeStem(filePath, docsRoot);
235
+
236
+ if (UNSUPPORTED.has(ext)) {
237
+ results.push({
238
+ file: filePath,
239
+ status: "unsupported",
240
+ message: `Format '${ext}' is not supported. Please convert to .docx or .md.`,
241
+ });
242
+ hasFailures = true;
243
+ continue;
244
+ }
245
+
246
+ if (!SUPPORTED.has(ext)) {
247
+ results.push({
248
+ file: filePath,
249
+ status: "unsupported",
250
+ message: `Extension '${ext}' is not supported. Convert to .md or .txt.`,
251
+ });
252
+ hasFailures = true;
253
+ continue;
254
+ }
255
+
256
+ const fileHash = computeHash(filePath);
257
+
258
+ if (cacheIsFresh(stem, fileHash)) {
259
+ results.push({
260
+ file: filePath,
261
+ status: "skipped",
262
+ message: "Cache is up to date.",
263
+ cached_as: `${stem}.md`,
264
+ });
265
+ continue;
266
+ }
267
+
268
+ try {
269
+ let markdown: string;
270
+ switch (ext) {
271
+ case ".pdf":
272
+ markdown = await convertPdf(filePath);
273
+ break;
274
+ case ".xlsx":
275
+ case ".xls":
276
+ markdown = convertExcel(filePath);
277
+ break;
278
+ case ".csv":
279
+ markdown = convertCsv(filePath);
280
+ break;
281
+ case ".docx":
282
+ markdown = await convertDocx(filePath);
283
+ break;
284
+ default:
285
+ markdown = copyText(filePath);
286
+ }
287
+
288
+ saveToCache(stem, markdown, fileHash);
289
+ results.push({
290
+ file: filePath,
291
+ status: "ok",
292
+ message: "Converted successfully.",
293
+ cached_as: `${stem}.md`,
294
+ });
295
+ } catch (err) {
296
+ results.push({
297
+ file: filePath,
298
+ status: "fail",
299
+ message: err instanceof Error ? err.message : String(err),
300
+ });
301
+ hasFailures = true;
302
+ }
303
+ }
304
+
305
+ buildAllDocs();
306
+
307
+ const output = {
308
+ cache_dir: CACHE_DIR,
309
+ all_docs: join(CACHE_DIR, "_all_docs.md"),
310
+ total: results.length,
311
+ ok: results.filter((r) => r.status === "ok").length,
312
+ skipped: results.filter((r) => r.status === "skipped").length,
313
+ failed: results.filter((r) =>
314
+ ["fail", "unsupported"].includes(r.status)
315
+ ).length,
316
+ has_failures: hasFailures,
317
+ files: results,
318
+ };
319
+
320
+ writeFileSync(RESULT_FILE, JSON.stringify(output, null, 2), "utf-8");
321
+ console.log(JSON.stringify(output, null, 2));
322
+ process.exit(hasFailures ? 1 : 0);
323
+ }
324
+
325
+ main();
@@ -0,0 +1,5 @@
1
+ pdfplumber>=0.10.0
2
+ pandas>=2.0.0
3
+ openpyxl>=3.1.0
4
+ python-docx>=1.0.0
5
+ tabulate>=0.9.0