-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-random-highlights-pl-spec.js
83 lines (68 loc) · 2.39 KB
/
get-random-highlights-pl-spec.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
// get random highlights of arg value number and put them in format { data , metadata }
import { fetchRandomHighlight } from "./get-random-highlight.js";
import fs from "fs";
const convertToDataMetadata = async (amount, embeddings = false) => {
const highlights = await fetchRandomHighlight(amount, true);
const data = highlights.map((highlight) => highlight.text);
const metadata = highlights.map((highlight) => {
return {
title: highlight.book.title,
author: highlight.book.author,
book_id: highlight.book.book_id,
cover_image_url: highlight.book.cover_image_url,
readwise_url: highlight.readwise_url,
question: highlight.question,
thoughts: highlight.thoughts,
};
});
if (embeddings) {
const embeddings = highlights.map((highlight) => highlight.embedding);
return data.map((data, index) => {
return { data: data, metadata: metadata[index], embedding: embeddings[index] };
});
}
// zip data and metadata into an object and return it as an array
const result = data.map((data, index) => {
return { data: data, metadata: metadata[index] };
});
return result;
};
// write to csv file with headers: data, metadata
const saveAsCSV = async (amount, embeddings = false) => {
const dataMetadata = await convertToDataMetadata(amount, embeddings);
if (embeddings) {
const csv = dataMetadata.map((row) => {
const cleanData = row.data.replace(/,/g, "");
const cleanMetadata = JSON.stringify(row.metadata).replace(/,/g, "");
return `${cleanData},${JSON.stringify(cleanMetadata)},${row.embedding}`;
});
// add headers
csv.unshift("data,metadata,embedding");
const csvString = csv.join("\n");
fs.writeFile("highlights.csv", csvString, (err) => {
if (err) {
console.error(err);
return;
}
console.log("File has been created");
});
return;
}
const csv = dataMetadata.map((row) => {
const cleanData = row.data.replace(/,/g, "");
const cleanMetadata = JSON.stringify(row.metadata).replace(/,/g, "");
return `${cleanData},${JSON.stringify(cleanMetadata)}`;
});
// add headers
csv.unshift("data,metadata");
const csvString = csv.join("\n");
fs.writeFile("highlights.csv", csvString, (err) => {
if (err) {
console.error(err);
return;
}
console.log("File has been created");
});
};
const amount = 10;
saveAsCSV(amount);