-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·206 lines (182 loc) · 6.45 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { program } from "commander";
import clipboardy from "clipboardy";
import { tokenize } from "./tokenizer.js";
import { processDirectoryOrPaths } from "./fileProcessor.js";
import { formatOutput } from "./outputFormatter.js";
import { filterFiles } from "./fileFilter.js";
const TOKENIZER_OPTIONS = Object.freeze({
"Xenova/gpt-4": "gpt-4 / gpt-3.5-turbo / text-embedding-ada-002",
"Xenova/text-davinci-003": "text-davinci-003 / text-davinci-002",
"Xenova/gpt-3": "gpt-3",
"Xenova/grok-1-tokenizer": "Grok-1",
"Xenova/claude-tokenizer": "Claude",
"Xenova/mistral-tokenizer-v3": "Mistral v3",
"Xenova/mistral-tokenizer-v1": "Mistral v1",
"Xenova/gemma-tokenizer": "Gemma",
"Xenova/llama-3-tokenizer": "Llama 3",
"Xenova/llama-tokenizer": "LLaMA / Llama 2",
"Xenova/c4ai-command-r-v01-tokenizer": "Cohere Command-R",
"Xenova/t5-small": "T5",
"Xenova/bert-base-cased": "bert-base-cased",
});
program
.version("0.1.0")
.arguments("[paths...]")
.option(
"-e, --extensions <extensions>",
"File extensions to include (comma-separated)",
)
.option(
"-i, --ignore <patterns>",
"Additional patterns to ignore (comma-separated)",
)
.option("-m, --max-tokens <number>", "Maximum number of tokens", parseInt)
.option(
"-f, --format <format>",
"Output format (xml, json, codeblocks)",
"xml",
)
.option("-t, --tokenizer <model>", "Tokenizer model to use", "Xenova/gpt-4")
.option(
"--disable-language-filter",
"Disable language-specific file filtering",
)
.option("--disable-config-filter", "Disable configuration file filtering")
.option("--disable-token-filter", "Disable token count anomaly filtering")
.option(
"--include-dot-files <patterns>",
"Dot files/directories to include (comma-separated)",
)
.parse(process.argv);
const options = program.opts();
const paths = program.args.length > 0 ? program.args : [process.cwd()];
function printFileStructure(files) {
const structure = {};
files.forEach((file) => {
const parts = file.path.split(path.sep);
let current = structure;
parts.forEach((part, index) => {
if (!current[part]) {
current[part] = index === parts.length - 1 ? null : {};
}
current = current[part];
});
});
function printStructure(obj, indent = "") {
Object.keys(obj).forEach((key, index, array) => {
const isLast = index === array.length - 1;
console.log(`${indent}${isLast ? "└── " : "├── "}${key}`);
if (obj[key]) {
printStructure(obj[key], `${indent}${isLast ? " " : "│ "}`);
}
});
}
console.log("File structure:");
printStructure(structure);
console.log();
}
async function main() {
try {
const files = await processDirectoryOrPaths(paths, {
extensions: options.extensions ? options.extensions.split(",") : null,
ignorePatterns: options.ignore ? options.ignore.split(",") : null,
includeDotFiles: options.includeDotFiles
? options.includeDotFiles.split(",")
: [],
});
console.log("File structure before filtering:");
printFileStructure(files);
let totalTokens = 0;
// Tokenize files
for (const file of files) {
try {
const result = await tokenize(file.content, options.tokenizer);
file.tokenCount = result.tokenCount;
totalTokens += result.tokenCount;
} catch (error) {
console.error(`Error tokenizing file ${file.path}: ${error.message}`);
file.tokenCount = 0;
}
}
console.log(`\nTotal tokens before filtering: ${totalTokens}`);
// Apply filtering
const { filteredFiles, removedFiles, detectedLanguage } = filterFiles(
files,
{
disableLanguageFilter: options.disableLanguageFilter,
disableConfigFilter: options.disableConfigFilter,
disableTokenFilter: options.disableTokenFilter,
},
);
console.log(`\nDetected language: ${detectedLanguage}`);
if (
!options.disableLanguageFilter &&
removedFiles.languageSpecific.length > 0
) {
console.log("\nFiles removed by language-specific filter:");
removedFiles.languageSpecific.forEach((file) => {
console.log(`- ${file.path} (${file.tokenCount} tokens)`);
});
}
if (
!options.disableConfigFilter &&
removedFiles.configurationFiles.length > 0
) {
console.log("\nConfiguration files removed:");
removedFiles.configurationFiles.forEach((file) => {
console.log(`- ${file.path} (${file.tokenCount} tokens)`);
});
}
if (!options.disableTokenFilter) {
if (removedFiles.tokenAnomaly.length > 0) {
console.log("\nFiles removed due to token count anomaly:");
removedFiles.tokenAnomaly.forEach((file) => {
console.log(`- ${file.path} (${file.tokenCount} tokens)`);
});
} else if (totalTokens > 50000) {
console.log(
"\nNo files were removed by token count anomaly filter, despite total tokens exceeding threshold.",
);
} else {
console.log(
"\nToken count anomaly filter was not applied due to low total token count.",
);
}
}
console.log("\nIncluded files after filtering:");
filteredFiles.forEach((file) => {
console.log(`- ${file.path} (${file.tokenCount} tokens)`);
});
const filteredTotalTokens = filteredFiles.reduce(
(sum, file) => sum + file.tokenCount,
0,
);
// Generate formatted output for all filtered files at once
const formattedOutput = formatOutput(filteredFiles, options.format);
// Calculate token overhead from formatting
let formattedTokenCount;
try {
const formattedTokenResult = await tokenize(
formattedOutput,
options.tokenizer,
);
formattedTokenCount = formattedTokenResult.tokenCount;
} catch (error) {
console.error(`Error tokenizing formatted output: ${error.message}`);
formattedTokenCount = filteredTotalTokens; // Fallback to avoid negative overhead
}
const tokenOverhead = formattedTokenCount - filteredTotalTokens;
console.log(
`\n${formattedTokenCount} tokens total, including ${tokenOverhead} from ${options.format} formatting.`,
);
// Copy formatted output to clipboard
clipboardy.writeSync(formattedOutput);
console.log("Formatted output has been copied to the clipboard.");
} catch (error) {
console.error("An error occurred:", error.message);
}
}
main();