-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex-files.js
236 lines (192 loc) · 7.61 KB
/
index-files.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
require('dotenv').config();
const fs = require('fs');
const { title } = require('process');
const recursive = require('recursive-readdir');
const path = require('path');
// Function to send data to Clarifai
async function sendToClarifai (id, filepath, text, title) {
const raw = JSON.stringify({
"user_app_id": {
"user_id": process.env.CLARIFAI_USER_ID,
"app_id": process.env.CLARIFAI_APP_ID
},
"inputs": [
{
id,
"data": {
text: {
raw: text
},
metadata: {
filepath,
url: generateURL(filepath),
title
}
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + process.env.CLARIFAI_PAT
},
body: raw
};
fetch("https://api.clarifai.com/v2/inputs", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
// sleep 100ms to not overwhelm the API
await new Promise(r => setTimeout(r, 100));
};
function generateURL(filepath) {
url = filepath.replace(".md", "");
// split url into parts
parts = url.split("/");
// if last part is index, remove it
if (parts[parts.length - 1] === "index") {
parts.pop();
}
// if last path is same as second to last, remove it
if (parts[parts.length - 1] === parts[parts.length - 2]) {
parts.pop();
}
// join parts back together
url = parts.join("/");
return url;
}
function getTitleFromMarkdown(text, filepath) {
// First try to get title from frontmatter
const titleRegex = /^title:\s+(.*)/gm;
const match = titleRegex.exec(text);
let title = match ? match[1] : null;
// If no title in frontmatter, try to get title from first heading
if (!title) {
const titleRegex = /^#\s+(.*)/gm;
const match = titleRegex.exec(text);
title = match ? match[1] : null;
}
// If no title in frontmatter or first heading, use filename
if (!title) {
filepath = filepath.replace(".md", "");
title = filepath.split("/").pop().replace(/-/g, " ");
title = title.charAt(0).toUpperCase() + title.slice(1);
}
return title;
}
// Function to read and process .md files
const processMarkdownFiles = async (dirPath) => {
try {
const files = await recursive(dirPath, ['!*.md', 'node_modules']);
for (const file of files) {
const text = fs.readFileSync(file, 'utf-8');
let relFilePath = file.replace(dirPath, '');
// Keep the relevant directory structure
const markdownAbsFilePath = path.resolve(dirPath, file);
// id is tied to file contents in case file is moved or changed and we re-run indexing
const id = require('crypto').createHash('md5')
.update(text)
.digest('hex');
let title = getTitleFromMarkdown(text, markdownAbsFilePath)
// send text - file too
// you may consider to split text into paragraphs if file is too big, but it could be slower to process
await sendToClarifai(id, relFilePath, text, title);
// send images
let docToImagesMap = await detectImageLinksInMarkdown(id, text, dirPath, markdownAbsFilePath);
await readImagesContentsAndPostToClarifai(docToImagesMap, markdownAbsFilePath, relFilePath, title);
}
} catch (err) {
console.error("Error reading files:", err);
}
};
async function detectImageLinksInMarkdown(id, text, dirPath, markdownFilePath) {
const imageRegex = /!\[.*?\]\((.*?)\)/gm;
let match;
let docToImagesMap = {};
docToImagesMap[id] = []; // Initialize an array for the given id
// Convert dirPath to an absolute path
const absoluteDirPath = path.resolve(dirPath);
while ((match = imageRegex.exec(text)) !== null) {
const relativeUrl = match[1];
if (relativeUrl.startsWith("http")){
docToImagesMap[id].push(relativeUrl);
}
else {
const decodedUrl = decodeURIComponent(relativeUrl); // Decode URL-encoded parts
// Correct the path resolution logic
const absolutePath = path.resolve(absoluteDirPath, path.dirname(markdownFilePath), decodedUrl);
// Check if the file exists before adding it to the map
if (fs.existsSync(absolutePath)) {
docToImagesMap[id].push(absolutePath);
} else {
console.error(`Image not found: ${absolutePath}`);
}
}
}
return docToImagesMap;
}
async function readImagesContentsAndPostToClarifai(docToImagesMap, markdownAbsFilePath, relFilePath, title) {
for (const [docId, imagePaths] of Object.entries(docToImagesMap)) {
for (const imagePath of imagePaths) {
try {
const raw = {
"inputs": [
{
"data": {
metadata: {
"filepath": markdownAbsFilePath,
"url": generateURL(relFilePath),
"title": title
}
},
}
],
};
if(imagePath.startsWith("http")) {
// Generate MD5 hash of the URL instead of file contents
const imageId = require('crypto').createHash('md5')
.update(imagePath)
.digest('hex');
raw.inputs[0].id = imageId; // Use imageId instead of docId
raw.inputs[0].data.image = {
url: imagePath
}
} else {
const imageData = fs.readFileSync(imagePath, { encoding: 'base64' });
// Generate MD5 hash of the image contents
const imageId = require('crypto').createHash('md5')
.update(fs.readFileSync(imagePath))
.digest('hex');
raw.inputs[0].id = imageId; // Use imageId instead of docId
raw.inputs[0].data.image = {
base64: imageData
}
}
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + process.env.CLARIFAI_PAT
},
body: JSON.stringify(raw)
};
const response = await fetch("https://api.clarifai.com/v2/inputs", requestOptions);
const result = await response.text();
console.log(result);
// sleep 100ms to not overwhelm the API
await new Promise(r => setTimeout(r, 1000));
} catch (error) {
console.error(`Error processing ${markdownAbsFilePath} : image ${imagePath}`, error);
}
}
}
}
// Run the script
const directoryToProcess = process.argv[2];
if (!directoryToProcess) {
console.error("Please provide a directory path to scan for .md files.");
process.exit(1);
}
processMarkdownFiles(directoryToProcess);