amazon-business-cli-kdp 0.0.0-stage → 0.1.0
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.
- package/README.md +102 -2
- package/machine/extractor/extract.js +508 -0
- package/machine/extractor/parse.js +336 -0
- package/machine/pipeline/README.md +14 -0
- package/machine/pipeline/apply.ts +242 -0
- package/machine/pipeline/autocomplete.ts +157 -0
- package/machine/pipeline/bsr.ts +185 -0
- package/machine/pipeline/capture-bestsellers.ts +252 -0
- package/machine/pipeline/capture-search.ts +103 -0
- package/machine/pipeline/category-words.txt +6124 -0
- package/machine/pipeline/classify.ts +127 -0
- package/machine/pipeline/common-words.txt +64001 -0
- package/machine/pipeline/cross.ts +241 -0
- package/machine/pipeline/cruce.ts +174 -0
- package/machine/pipeline/dedupe.ts +73 -0
- package/machine/pipeline/gates.ts +147 -0
- package/machine/pipeline/homogeneity.ts +116 -0
- package/machine/pipeline/http.ts +126 -0
- package/machine/pipeline/ngram.ts +190 -0
- package/machine/pipeline/paths.ts +26 -0
- package/machine/pipeline/phrases.ts +164 -0
- package/machine/pipeline/prefilter.ts +90 -0
- package/machine/pipeline/render.ts +127 -0
- package/machine/pipeline/run.ts +458 -0
- package/machine/pipeline/sweep.ts +153 -0
- package/machine/pipeline/total.ts +25 -0
- package/machine/pipeline/types.ts +63 -0
- package/machine/pipeline/units.ts +27 -0
- package/machine/pipeline/verify.ts +153 -0
- package/machine/storage/schema.sql +90 -0
- package/package.json +30 -4
- package/src/cli.ts +220 -0
- package/src/workspace.ts +199 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parsers puros: no tocan el DOM. Se pueden probar desde Bun/Node.
|
|
3
|
+
* Todo lo que entra es texto tal como aparece en Amazon, en español o en inglés.
|
|
4
|
+
*/
|
|
5
|
+
(function (root, factory) {
|
|
6
|
+
const api = factory();
|
|
7
|
+
if (typeof module !== "undefined" && module.exports) module.exports = api;
|
|
8
|
+
root.KDPXParse = api;
|
|
9
|
+
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
|
|
10
|
+
function clean(s) {
|
|
11
|
+
if (s == null) return "";
|
|
12
|
+
return String(s)
|
|
13
|
+
.replace(/[\u200b-\u200f\u202a-\u202e]/g, "")
|
|
14
|
+
.replace(/\s+/g, " ")
|
|
15
|
+
.replace(/\u00a0/g, " ")
|
|
16
|
+
.trim();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const CURRENCY_SYMBOLS = [
|
|
20
|
+
["ARS", /ARS\s?/i],
|
|
21
|
+
["USD", /US\$\s?/i],
|
|
22
|
+
["CAD", /CDN\$\s?|CA\$\s?/i],
|
|
23
|
+
["GBP", /£\s?/],
|
|
24
|
+
["EUR", /€\s?/],
|
|
25
|
+
["JPY", /¥\s?/],
|
|
26
|
+
["BRL", /R\$\s?/],
|
|
27
|
+
["MXN", /MX\$\s?/],
|
|
28
|
+
["AUD", /AU\$\s?/],
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
function detectCurrency(text) {
|
|
32
|
+
const t = clean(text);
|
|
33
|
+
for (const [code, re] of CURRENCY_SYMBOLS) if (re.test(t)) return code;
|
|
34
|
+
if (/\$\s?\d/.test(t)) return "USD";
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Normaliza "1.234,56" / "1,234.56" / "1 234,56" a numero. */
|
|
39
|
+
function toNumber(raw) {
|
|
40
|
+
if (raw == null) return null;
|
|
41
|
+
let s = clean(String(raw)).replace(/[^\d.,-]/g, "");
|
|
42
|
+
if (!s) return null;
|
|
43
|
+
const lastDot = s.lastIndexOf(".");
|
|
44
|
+
const lastComma = s.lastIndexOf(",");
|
|
45
|
+
if (lastDot >= 0 && lastComma >= 0) {
|
|
46
|
+
// El separador que aparece ultimo es el decimal.
|
|
47
|
+
if (lastComma > lastDot) s = s.replace(/\./g, "").replace(",", ".");
|
|
48
|
+
else s = s.replace(/,/g, "");
|
|
49
|
+
} else if (lastComma >= 0) {
|
|
50
|
+
const after = s.length - lastComma - 1;
|
|
51
|
+
s = after === 3 && s.length > 4 ? s.replace(/,/g, "") : s.replace(",", ".");
|
|
52
|
+
} else if (lastDot >= 0) {
|
|
53
|
+
const after = s.length - lastDot - 1;
|
|
54
|
+
if (after === 3 && s.length > 4) s = s.replace(/\./g, "");
|
|
55
|
+
}
|
|
56
|
+
const n = Number(s);
|
|
57
|
+
return Number.isFinite(n) ? n : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Precio: soporta "US$16.99", "ARS 26.372,93", "16,99 €", rangos,
|
|
62
|
+
* y la trampa de Kindle: "Gratis con Kindle+ ... O US$0.99 para comprar".
|
|
63
|
+
*/
|
|
64
|
+
function parsePrice(raw, contextText) {
|
|
65
|
+
const rawText = clean(raw);
|
|
66
|
+
const ctx = clean(contextText || "");
|
|
67
|
+
const joined = clean(rawText + " " + ctx);
|
|
68
|
+
|
|
69
|
+
// Preferir el precio de compra explicito frente al "Gratis con suscripcion".
|
|
70
|
+
const buyMatch = joined.match(/(?:O|or)\s*((?:US\$|ARS|CDN\$|CA\$|MX\$|AU\$|R\$|£|€|¥|\$)\s?[\d.,]+)\s*(?:para comprar|to buy)/i);
|
|
71
|
+
if (/gratis con|free with|incluido con|included with/i.test(joined) && buyMatch) {
|
|
72
|
+
const value = toNumber(buyMatch[1]);
|
|
73
|
+
return {
|
|
74
|
+
value: value,
|
|
75
|
+
currency: detectCurrency(buyMatch[1]),
|
|
76
|
+
raw: buyMatch[1],
|
|
77
|
+
fromSubscription: true,
|
|
78
|
+
isRange: false,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const priceRe = /(?:US\$|ARS|CDN\$|CA\$|MX\$|AU\$|R\$|£|€|¥|\$)\s?[\d][\d.,]*|[\d][\d.,]*\s?(?:€|£|¥)/g;
|
|
83
|
+
const matches = joined.match(priceRe);
|
|
84
|
+
if (!matches || !matches.length) return { value: null, currency: detectCurrency(joined), raw: rawText || null, fromSubscription: false, isRange: false };
|
|
85
|
+
|
|
86
|
+
const first = matches[0];
|
|
87
|
+
const isRange = matches.length > 1 && /(?:-|–|to|a)\s*(?:US\$|ARS|CDN\$|CA\$|MX\$|AU\$|R\$|£|€|¥|\$)/.test(joined);
|
|
88
|
+
return {
|
|
89
|
+
value: toNumber(first),
|
|
90
|
+
currency: detectCurrency(first),
|
|
91
|
+
raw: first,
|
|
92
|
+
fromSubscription: false,
|
|
93
|
+
isRange: isRange,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function parseReviewCount(raw) {
|
|
98
|
+
const t = clean(raw);
|
|
99
|
+
if (!t) return null;
|
|
100
|
+
if (/s[eé] el primero|be the first|sin opiniones|no reviews|todav[ií]a no hay/i.test(t)) return 0;
|
|
101
|
+
// Preferir el grupo entre parentesis: "(1.2 K)" o "(118)".
|
|
102
|
+
const paren = t.match(/\(([^)]+)\)/);
|
|
103
|
+
const source = paren ? paren[1] : t;
|
|
104
|
+
const m = source.match(/([\d.,]+)\s*(mil|mill[oó]n|millon|k|m|b)?/i);
|
|
105
|
+
if (!m) return null;
|
|
106
|
+
let n = toNumber(m[1]);
|
|
107
|
+
if (n == null) return null;
|
|
108
|
+
const suffix = (m[2] || "").toLowerCase();
|
|
109
|
+
if (suffix === "k" || suffix === "mil") n *= 1000;
|
|
110
|
+
else if (suffix === "m" || suffix.startsWith("mill")) n *= 1000000;
|
|
111
|
+
return Math.round(n);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function parseRating(raw) {
|
|
115
|
+
const t = clean(raw);
|
|
116
|
+
if (!t) return null;
|
|
117
|
+
const m = t.match(/([0-5](?:[.,]\d)?)\s*(?:de\s*5|out of 5|\/\s*5|estrellas|stars)?/i);
|
|
118
|
+
if (!m) return null;
|
|
119
|
+
const n = toNumber(m[1].replace(",", "."));
|
|
120
|
+
return n != null && n >= 0 && n <= 5 ? n : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Lista de rankings: "#12,345 in Books" / "nº12.345 en Libros". */
|
|
124
|
+
function parseRankList(text) {
|
|
125
|
+
const t = clean(text);
|
|
126
|
+
const out = [];
|
|
127
|
+
const re = /(?:#|n[º°]\s?|rank\s?)([\d.,]+)\s*(?:en|in)\s+(.+?)(?=\s*(?:#|n[º°])\s?[\d.,]|$)/gi;
|
|
128
|
+
let m;
|
|
129
|
+
const seen = new Set();
|
|
130
|
+
while ((m = re.exec(t))) {
|
|
131
|
+
const rank = toNumber(m[1]);
|
|
132
|
+
let category = clean(m[2])
|
|
133
|
+
.split("|")[0]
|
|
134
|
+
.replace(/\s*\(ver el top[^)]*\)?.*$/i, "")
|
|
135
|
+
.replace(/\s*\(see top[^)]*\)?.*$/i, "")
|
|
136
|
+
.replace(/\s*(opiniones de clientes|customer reviews|rating|estrellas).*$/i, "")
|
|
137
|
+
.replace(/[.,;:|\s]+$/, "")
|
|
138
|
+
.replace(/\s+/g, " ")
|
|
139
|
+
.trim();
|
|
140
|
+
if (rank == null || !category || category.length < 2) continue;
|
|
141
|
+
if (category.length > 70) continue;
|
|
142
|
+
const key = `${Math.round(rank)}|${category.toLowerCase()}`;
|
|
143
|
+
if (seen.has(key)) continue;
|
|
144
|
+
seen.add(key);
|
|
145
|
+
out.push({ rank: Math.round(rank), category });
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function isOverallCategory(category) {
|
|
151
|
+
return /^(books?|libros?|kindle store|tienda kindle|all departments|todas las categor[ií]as)$/i.test(clean(category));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const MONTHS = {
|
|
155
|
+
enero: 1, febrero: 2, marzo: 3, abril: 4, mayo: 5, junio: 6, julio: 7, agosto: 8,
|
|
156
|
+
septiembre: 9, setiembre: 9, octubre: 10, noviembre: 11, diciembre: 12,
|
|
157
|
+
january: 1, february: 2, march: 3, april: 4, may: 5, june: 6, july: 7, august: 8,
|
|
158
|
+
september: 9, october: 10, november: 11, december: 12,
|
|
159
|
+
jan: 1, feb: 2, mar: 3, apr: 4, jun: 6, jul: 7, aug: 8, sep: 9, sept: 9, oct: 10, nov: 11, dec: 12,
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
function parseDate(raw) {
|
|
163
|
+
const t = clean(raw).toLowerCase();
|
|
164
|
+
if (!t) return null;
|
|
165
|
+
let m = t.match(/(\d{1,2})\s*(?:de\s*)?([a-záéíóúñ]+)\s*(?:de\s*|,\s*)?(\d{4})/);
|
|
166
|
+
if (m && MONTHS[m[2]]) {
|
|
167
|
+
return `${m[3]}-${String(MONTHS[m[2]]).padStart(2, "0")}-${String(Number(m[1])).padStart(2, "0")}`;
|
|
168
|
+
}
|
|
169
|
+
m = t.match(/([a-záéíóúñ]+)\s+(\d{1,2}),?\s+(\d{4})/);
|
|
170
|
+
if (m && MONTHS[m[1]]) {
|
|
171
|
+
return `${m[3]}-${String(MONTHS[m[1]]).padStart(2, "0")}-${String(Number(m[2])).padStart(2, "0")}`;
|
|
172
|
+
}
|
|
173
|
+
m = t.match(/(\d{4})-(\d{2})-(\d{2})/);
|
|
174
|
+
if (m) return m[0];
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function parseTotalResults(text) {
|
|
179
|
+
const t = clean(text);
|
|
180
|
+
if (!t) return { text: null, total: null, isOver: false };
|
|
181
|
+
const over = /m[aá]s de|over|more than/i.test(t);
|
|
182
|
+
const m = t.match(/(?:m[aá]s de|over|more than)?\s*([\d.,]{3,})/);
|
|
183
|
+
const total = m ? toNumber(m[1]) : null;
|
|
184
|
+
return { text: t, total: total == null ? null : Math.round(total), isOver: over };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function parsePages(raw) {
|
|
188
|
+
const m = clean(raw).match(/([\d.,]+)\s*(?:p[aá]ginas|pages)/i);
|
|
189
|
+
if (!m) return null;
|
|
190
|
+
const n = toNumber(m[1]);
|
|
191
|
+
return n == null ? null : Math.round(n);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function parseIsbn13(raw) {
|
|
195
|
+
const m = clean(raw).match(/(97[89][\d-]{10,17})/);
|
|
196
|
+
return m ? m[1].replace(/-/g, "") : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function isSponsored(text) {
|
|
200
|
+
return /(^|\s)(patrocinado|sponsored)(\s|$)/i.test(clean(text));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function isKindleUnlimited(text) {
|
|
204
|
+
return /kindle unlimited|kindle\+|gratis con la membres[ií]a|free with kindle|incluido con/i.test(clean(text));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function formatFromText(text) {
|
|
208
|
+
const t = clean(text);
|
|
209
|
+
const map = [
|
|
210
|
+
["Kindle", /edici[oó]n kindle|kindle edition|formato kindle|e-?book/i],
|
|
211
|
+
["Paperback", /tapa blanda|pasta blanda|paperback/i],
|
|
212
|
+
["Hardcover", /tapa dura|pasta dura|hardcover/i],
|
|
213
|
+
["Audiobook", /audiolibro|audiobook|audible/i],
|
|
214
|
+
["Spiral", /espiral|spiral/i],
|
|
215
|
+
];
|
|
216
|
+
for (const [name, re] of map) if (re.test(t)) return name;
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function parseBestsellerRank(raw) {
|
|
221
|
+
const m = clean(raw).match(/(?:#|n[º°])\s*([\d.,]+)/);
|
|
222
|
+
if (!m) return null;
|
|
223
|
+
const n = toNumber(m[1]);
|
|
224
|
+
return n == null ? null : Math.round(n);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function daysSince(iso, refISO) {
|
|
228
|
+
if (!iso) return null;
|
|
229
|
+
const a = Date.parse(iso);
|
|
230
|
+
const b = refISO ? Date.parse(refISO) : Date.now();
|
|
231
|
+
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
|
232
|
+
return Math.round((b - a) / 86400000);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Texto que PublishFlow dibuja sobre cada resultado, sin estilos:
|
|
237
|
+
* "Libros #10 Pasta blanda US$5.35 Libros para Colorear para Adultos#1 ... Extensión96 páginas
|
|
238
|
+
* Fecha de publicación2024-12-03 ASINB0DJ27336M"
|
|
239
|
+
*/
|
|
240
|
+
function parsePublishFlowText(rawText) {
|
|
241
|
+
const text = clean(rawText);
|
|
242
|
+
const ranks = [];
|
|
243
|
+
const re = /([A-Za-zÁÉÍÓÚÑÜáéíóúñü][A-Za-zÁÉÍÓÚÑÜáéíóúñü\s()\/&.,'’-]*?)\s*#([\d.,]+)/g;
|
|
244
|
+
let m;
|
|
245
|
+
while ((m = re.exec(text))) {
|
|
246
|
+
let category = m[1].split(/US\$\s?[\d.,]+/).pop() || "";
|
|
247
|
+
category = category
|
|
248
|
+
.replace(/^(pasta blanda|pasta dura|tapa blanda|tapa dura|paperback|hardcover|kindle|edici[oó]n kindle)\s*/i, "")
|
|
249
|
+
.replace(/[.,;:|\s]+$/, "")
|
|
250
|
+
.trim();
|
|
251
|
+
const rank = toNumber(m[2]);
|
|
252
|
+
if (rank == null || !category) continue;
|
|
253
|
+
if (category.length > 60) continue;
|
|
254
|
+
if (ranks.some((r) => r.rank === Math.round(rank) && r.category === category)) continue;
|
|
255
|
+
ranks.push({ rank: Math.round(rank), category });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const pagesMatch = text.match(/(?:Extensión|Print length)\s*([\d.,]+)\s*(?:páginas|pages)/i);
|
|
259
|
+
const pages = pagesMatch ? toNumber(pagesMatch[1]) : null;
|
|
260
|
+
const dateMatch = text.match(/(?:Fecha de publicación|Publication date)\s*([\d-]{8,10})/i);
|
|
261
|
+
const priceMatch = text.match(/(?:US\$|ARS|CDN\$|CA\$|MX\$|AU\$|R\$|£|€|¥)\s?[\d][\d.,]*/);
|
|
262
|
+
const price = priceMatch ? parsePrice(priceMatch[0]) : { value: null, currency: null };
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
ranks,
|
|
266
|
+
pages: pages == null ? null : Math.round(pages),
|
|
267
|
+
pubDate: dateMatch ? parseDate(dateMatch[1]) : null,
|
|
268
|
+
price: price.value,
|
|
269
|
+
currency: price.currency,
|
|
270
|
+
format: formatFromText(text),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** "1.0k" -> 1000, "2,351" -> 2351 */
|
|
275
|
+
function parseCompactNumber(raw) {
|
|
276
|
+
const t = clean(raw).toLowerCase();
|
|
277
|
+
const m = t.match(/([\d.,]+)\s*(k|m|mil|mill[oó]n)?/);
|
|
278
|
+
if (!m) return null;
|
|
279
|
+
let n = toNumber(m[1]);
|
|
280
|
+
if (n == null) return null;
|
|
281
|
+
const suf = m[2] || "";
|
|
282
|
+
if (suf === "k" || suf === "mil") n *= 1000;
|
|
283
|
+
else if (suf === "m" || suf.startsWith("mill")) n *= 1000000;
|
|
284
|
+
return Math.round(n);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** "767-1280 Sales/Day" o "$613-$1.0k Royalty/Day" -> {min,max} */
|
|
288
|
+
function parseRange(text, unit) {
|
|
289
|
+
const t = clean(text);
|
|
290
|
+
const re = new RegExp(`\\$?([\\d.,]+\\s*[km]?)\\s*[-–]\\s*\\$?([\\d.,]+\\s*[km]?)\\s*${unit}`, "i");
|
|
291
|
+
const m = t.match(re);
|
|
292
|
+
if (m) {
|
|
293
|
+
const min = parseCompactNumber(m[1]);
|
|
294
|
+
const max = parseCompactNumber(m[2]);
|
|
295
|
+
return min == null || max == null ? null : { min, max };
|
|
296
|
+
}
|
|
297
|
+
const single = new RegExp(`\\$?([\\d.,]+\\s*[km]?)\\s*${unit}`, "i").exec(t);
|
|
298
|
+
if (single) {
|
|
299
|
+
const v = parseCompactNumber(single[1]);
|
|
300
|
+
return v == null ? null : { min: v, max: v };
|
|
301
|
+
}
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** "Titulo: subtitulo largo" -> {title, subtitle} */
|
|
306
|
+
function splitTitleSubtitle(full) {
|
|
307
|
+
const t = clean(full);
|
|
308
|
+
const i = t.indexOf(": ");
|
|
309
|
+
if (i > 10 && i < t.length - 3) return { title: t.slice(0, i).trim(), subtitle: t.slice(i + 1).trim() };
|
|
310
|
+
return { title: t, subtitle: null };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
clean,
|
|
315
|
+
toNumber,
|
|
316
|
+
splitTitleSubtitle,
|
|
317
|
+
parseCompactNumber,
|
|
318
|
+
parseRange,
|
|
319
|
+
parsePublishFlowText,
|
|
320
|
+
detectCurrency,
|
|
321
|
+
parsePrice,
|
|
322
|
+
parseReviewCount,
|
|
323
|
+
parseRating,
|
|
324
|
+
parseRankList,
|
|
325
|
+
isOverallCategory,
|
|
326
|
+
parseDate,
|
|
327
|
+
parseTotalResults,
|
|
328
|
+
parsePages,
|
|
329
|
+
parseIsbn13,
|
|
330
|
+
isSponsored,
|
|
331
|
+
isKindleUnlimited,
|
|
332
|
+
formatFromText,
|
|
333
|
+
parseBestsellerRank,
|
|
334
|
+
daysSince,
|
|
335
|
+
};
|
|
336
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Motor de Amazon Business CLI
|
|
2
|
+
|
|
3
|
+
Este directorio contiene el motor que ejecuta `abck`. La guía de uso está en el
|
|
4
|
+
[`README.md`](../../README.md) de la CLI; no ejecutar estos scripts directamente salvo para
|
|
5
|
+
desarrollo y tests.
|
|
6
|
+
|
|
7
|
+
El pipeline y el extractor están copiados dentro de este proyecto para poder evolucionarlos
|
|
8
|
+
sin depender del código de la extensión. La CLI los ejecuta con la configuración creada por
|
|
9
|
+
`abck init`; todos los datos y la DB quedan dentro de `.amazon-business/data/`.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun test
|
|
13
|
+
abck doctor
|
|
14
|
+
```
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* E4 — aplica las cuatro compuertas a una captura real y escribe el brief.
|
|
4
|
+
*
|
|
5
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --keyword "rabbit care"
|
|
6
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --keyword "rabbit care" --json
|
|
7
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --keyword "rabbit care" --write
|
|
8
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --fixture test/fixtures/rabbit-care.json
|
|
9
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --list
|
|
10
|
+
* bun run Lab/Departamento-de-Investigacion/Machine/pipeline/apply.ts --all --out Lab/Departamento-de-Investigacion/corridas
|
|
11
|
+
*
|
|
12
|
+
* Lee de la base de kdp-extension-chromium. No toca Amazon y no gasta cupo.
|
|
13
|
+
* Por defecto NO escribe: el brief se escribe solo con --write.
|
|
14
|
+
*/
|
|
15
|
+
import { Database } from "bun:sqlite";
|
|
16
|
+
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
|
|
17
|
+
import { dirname, join, resolve } from "node:path";
|
|
18
|
+
import type { PhraseInput, Row } from "./types";
|
|
19
|
+
import { evaluate } from "./gates";
|
|
20
|
+
import { renderAnalysis } from "./render";
|
|
21
|
+
import { parseTotal } from "./total";
|
|
22
|
+
import { DB_PATH, CORRIDAS } from "./paths";
|
|
23
|
+
|
|
24
|
+
const HERE = dirname(new URL(import.meta.url).pathname);
|
|
25
|
+
const DEFAULT_DB = DB_PATH;
|
|
26
|
+
const DEFAULT_OUT = CORRIDAS;
|
|
27
|
+
|
|
28
|
+
function arg(name: string): string | undefined {
|
|
29
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
30
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
31
|
+
}
|
|
32
|
+
function has(name: string): boolean {
|
|
33
|
+
return process.argv.includes(`--${name}`);
|
|
34
|
+
}
|
|
35
|
+
function slug(s: string): string {
|
|
36
|
+
return s.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type DbRow = {
|
|
40
|
+
asin: string | null;
|
|
41
|
+
position: number | null;
|
|
42
|
+
title: string | null;
|
|
43
|
+
subtitle: string | null;
|
|
44
|
+
bsr_overall: number | null;
|
|
45
|
+
estimate_source: string | null;
|
|
46
|
+
pub_date: string | null;
|
|
47
|
+
reviews: number | null;
|
|
48
|
+
price: number | null;
|
|
49
|
+
pages: number | null;
|
|
50
|
+
sponsored: number | null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function fromDb(dbPath: string, keyword: string): PhraseInput | null {
|
|
54
|
+
if (!existsSync(dbPath)) throw new Error(`No existe la base: ${dbPath}`);
|
|
55
|
+
const db = new Database(dbPath, { readonly: true });
|
|
56
|
+
|
|
57
|
+
const dates = db
|
|
58
|
+
.query(`select substr(created_at,1,10) d, count(*) n from runs
|
|
59
|
+
where keyword = ? and kind = 'search' group by d order by d desc limit 1`)
|
|
60
|
+
.all(keyword) as { d: string; n: number }[];
|
|
61
|
+
if (!dates.length) return null;
|
|
62
|
+
const date = dates[0].d;
|
|
63
|
+
|
|
64
|
+
// Última corrida por página, dentro de la fecha elegida.
|
|
65
|
+
const pages = db
|
|
66
|
+
.query(
|
|
67
|
+
`select page, id, total_results, total_results_is_over, currency, created_at
|
|
68
|
+
from runs
|
|
69
|
+
where keyword = ? and kind = 'search' and substr(created_at,1,10) = ?
|
|
70
|
+
order by page asc, created_at asc`,
|
|
71
|
+
)
|
|
72
|
+
.all(keyword, date) as {
|
|
73
|
+
page: number | null;
|
|
74
|
+
id: number;
|
|
75
|
+
total_results: number | null;
|
|
76
|
+
total_results_is_over: number | null;
|
|
77
|
+
currency: string | null;
|
|
78
|
+
created_at: string;
|
|
79
|
+
}[];
|
|
80
|
+
if (!pages.length) return null;
|
|
81
|
+
|
|
82
|
+
const latestByPage = new Map<number, (typeof pages)[number]>();
|
|
83
|
+
for (const p of pages) latestByPage.set(p.page ?? 1, p);
|
|
84
|
+
|
|
85
|
+
const runIds = [...latestByPage.values()].map((p) => p.id);
|
|
86
|
+
const placeholders = runIds.map(() => "?").join(",");
|
|
87
|
+
const raw = db
|
|
88
|
+
.query(
|
|
89
|
+
`select asin, position, title, subtitle, bsr_overall, estimate_source, pub_date, reviews, price, pages, sponsored
|
|
90
|
+
from items where run_id in (${placeholders})`,
|
|
91
|
+
)
|
|
92
|
+
.all(...runIds) as DbRow[];
|
|
93
|
+
|
|
94
|
+
const seen = new Set<string>();
|
|
95
|
+
const rows: Row[] = [];
|
|
96
|
+
for (const [, p] of [...latestByPage.entries()].sort((a, b) => a[0] - b[0])) {
|
|
97
|
+
const items = raw
|
|
98
|
+
.filter((r) => r.position != null)
|
|
99
|
+
.sort((a, b) => (a.position as number) - (b.position as number));
|
|
100
|
+
for (const r of items) {
|
|
101
|
+
const key = r.asin ?? `${p.page}-${r.position}`;
|
|
102
|
+
if (seen.has(key)) continue;
|
|
103
|
+
seen.add(key);
|
|
104
|
+
rows.push({
|
|
105
|
+
asin: r.asin,
|
|
106
|
+
position: ((p.page ?? 1) - 1) * 16 + (r.position as number),
|
|
107
|
+
title: r.title,
|
|
108
|
+
subtitle: r.subtitle,
|
|
109
|
+
// Un libro marcado 'sin-bsr' no tiene ranking porque no vendió: se le asigna
|
|
110
|
+
// la peor banda en vez de contarlo como dato faltante.
|
|
111
|
+
bsr: r.bsr_overall ?? (r.estimate_source === "sin-bsr" ? 5_000_000 : null),
|
|
112
|
+
pubDate: r.pub_date,
|
|
113
|
+
reviews: r.reviews,
|
|
114
|
+
price: r.price,
|
|
115
|
+
pages: r.pages,
|
|
116
|
+
sponsored: !!r.sponsored,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const first = latestByPage.get(1) ?? pages[0];
|
|
122
|
+
const withTotal = [...latestByPage.values()]
|
|
123
|
+
.sort((a, b) => (a.page ?? 1) - (b.page ?? 1))
|
|
124
|
+
.find((p) => p.total_results != null);
|
|
125
|
+
const textRow = db
|
|
126
|
+
.query(
|
|
127
|
+
`select total_results_text t from runs
|
|
128
|
+
where keyword = ? and kind = 'search' and substr(created_at,1,10) = ? and total_results_text is not null
|
|
129
|
+
order by page asc, created_at desc limit 1`,
|
|
130
|
+
)
|
|
131
|
+
.get(keyword, date) as { t: string } | null;
|
|
132
|
+
const parsed = parseTotal(textRow?.t ?? null);
|
|
133
|
+
|
|
134
|
+
db.close();
|
|
135
|
+
return {
|
|
136
|
+
keyword,
|
|
137
|
+
totalResults: withTotal?.total_results ?? parsed.total,
|
|
138
|
+
totalIsOver: !!(withTotal?.total_results_is_over) || parsed.isOver,
|
|
139
|
+
currency: first.currency,
|
|
140
|
+
capturedAt: `${date}T00:00:00.000Z`,
|
|
141
|
+
rows,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function listKeywords(dbPath: string): string[] {
|
|
146
|
+
if (!existsSync(dbPath)) throw new Error(`No existe la base: ${dbPath}`);
|
|
147
|
+
const db = new Database(dbPath, { readonly: true });
|
|
148
|
+
const out = db
|
|
149
|
+
.query(`select r.keyword, count(*) n from items i join runs r on r.id = i.run_id
|
|
150
|
+
where r.keyword is not null and r.kind = 'search' group by r.keyword order by n desc`)
|
|
151
|
+
.all() as { keyword: string; n: number }[];
|
|
152
|
+
db.close();
|
|
153
|
+
return out.map((r) => `${r.keyword} (${r.n})`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function runOne(input: PhraseInput, outRoot: string | null): ReturnType<typeof evaluate> {
|
|
157
|
+
const ev = evaluate(input);
|
|
158
|
+
if (outRoot) {
|
|
159
|
+
const day = input.capturedAt.slice(0, 10);
|
|
160
|
+
const dir = join(outRoot, `${day}-${slug(input.keyword)}`);
|
|
161
|
+
mkdirSync(dir, { recursive: true });
|
|
162
|
+
writeFileSync(join(dir, "analisis.md"), renderAnalysis(ev, input.rows));
|
|
163
|
+
writeFileSync(join(dir, "crudo.json"), JSON.stringify(input, null, 2));
|
|
164
|
+
}
|
|
165
|
+
return ev;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function printLine(ev: ReturnType<typeof evaluate>) {
|
|
169
|
+
const fails = ev.gates.filter((g) => !g.pass).map((g) => g.id);
|
|
170
|
+
console.log(
|
|
171
|
+
`${ev.keyword.padEnd(38)} ${ev.verdict.padEnd(17)} cob ${String(ev.coverage).padEnd(4)} masa ${String(ev.mass.mid).padEnd(6)} ${fails.length ? "falla " + fails.join(",") : "pasa"}`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function printMd(ev: ReturnType<typeof evaluate>) {
|
|
176
|
+
const fails = ev.gates.filter((g) => !g.pass).map((g) => g.id).join(", ") || "—";
|
|
177
|
+
console.log(
|
|
178
|
+
`| ${ev.keyword} | ${ev.verdict} | ${ev.totalResults ?? "—"} | ${ev.mass.min}–${ev.mass.max} | ${ev.coverage} | ${fails} |`,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (import.meta.main) {
|
|
183
|
+
const dbPath = arg("db") ?? DEFAULT_DB;
|
|
184
|
+
const outArg = arg("out");
|
|
185
|
+
// Solo escribe con --write explícito. --json, --json-only y --md son de lectura.
|
|
186
|
+
// --no-write gana si se pasan los dos, para que el modo seguro no dependa del orden.
|
|
187
|
+
const write = has("write") && !has("no-write");
|
|
188
|
+
const outRoot = write ? (outArg ? resolve(outArg) : DEFAULT_OUT) : null;
|
|
189
|
+
|
|
190
|
+
if (has("list")) {
|
|
191
|
+
for (const k of listKeywords(dbPath)) console.log(k);
|
|
192
|
+
process.exit(0);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const fixture = arg("fixture");
|
|
196
|
+
if (fixture) {
|
|
197
|
+
const input = JSON.parse(readFileSync(fixture, "utf8")) as PhraseInput;
|
|
198
|
+
const ev = runOne(input, outRoot);
|
|
199
|
+
console.log(has("json") ? JSON.stringify(ev, null, 2) : "");
|
|
200
|
+
printLine(ev);
|
|
201
|
+
process.exit(0);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const keyword = arg("keyword");
|
|
205
|
+
if (has("all")) {
|
|
206
|
+
const kw = listKeywords(dbPath).map((s) => s.replace(/ \(\d+\)$/, ""));
|
|
207
|
+
const results = [];
|
|
208
|
+
for (const k of kw) {
|
|
209
|
+
const input = fromDb(dbPath, k);
|
|
210
|
+
if (!input) continue;
|
|
211
|
+
results.push(runOne(input, outRoot));
|
|
212
|
+
}
|
|
213
|
+
results.sort((a, b) => b.mass.mid - a.mass.mid);
|
|
214
|
+
if (has("md")) {
|
|
215
|
+
console.log("| Frase | Veredicto | Resultados | Masa u/día | Cob. | Compuertas que fallan |");
|
|
216
|
+
console.log("|---|---|---|---|---|---|");
|
|
217
|
+
for (const ev of results) printMd(ev);
|
|
218
|
+
} else {
|
|
219
|
+
for (const ev of results) printLine(ev);
|
|
220
|
+
}
|
|
221
|
+
process.exit(0);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (!keyword) {
|
|
225
|
+
console.error('Uso: bun run apply.ts --keyword "frase" [--json] [--json-only] [--md] [--write] | --list | --all');
|
|
226
|
+
process.exit(1);
|
|
227
|
+
}
|
|
228
|
+
const input = fromDb(dbPath, keyword);
|
|
229
|
+
if (!input) {
|
|
230
|
+
console.error(`Sin captura para "${keyword}" en ${dbPath}`);
|
|
231
|
+
process.exit(2);
|
|
232
|
+
}
|
|
233
|
+
const ev = runOne(input, outRoot);
|
|
234
|
+
if (has("json-only")) console.log(JSON.stringify(ev));
|
|
235
|
+
else if (has("json")) console.log(JSON.stringify(ev, null, 2));
|
|
236
|
+
else if (has("md")) {
|
|
237
|
+
console.log("| Frase | Veredicto | Resultados | Masa u/día | Cob. | Compuertas que fallan |");
|
|
238
|
+
console.log("|---|---|---|---|---|---|");
|
|
239
|
+
printMd(ev);
|
|
240
|
+
} else printLine(ev);
|
|
241
|
+
if (outRoot) console.log(`brief: ${join(outRoot, `${input.capturedAt.slice(0, 10)}-${slug(keyword)}`, "analisis.md")}`);
|
|
242
|
+
}
|