-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpost-carousel-module.js
More file actions
533 lines (460 loc) Β· 17 KB
/
Copy pathwebpost-carousel-module.js
File metadata and controls
533 lines (460 loc) Β· 17 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// WEBPOST CAROUSEL + VIDEO MODULE v1
// /webpost-carousel <topic> β Web search β Extract best content β Generate carousel + Runway video
// Token usage: ~150 tokens OpenRouter (minimal DeepSeek), 0 Grok
const cheerio = require('cheerio');
class WebPostCarouselGenerator {
constructor(options = {}) {
this.openrouterKey = options.openrouterKey;
this.anthropicKey = options.anthropicKey;
this.grokKey = options.grokKey;
this.runwayKey = options.runwayKey;
this.telegramToken = options.telegramToken;
this.r2Worker = options.r2Worker;
this.currentTextModel = 'deepseek/deepseek-chat';
this.searchProvider = options.searchProvider || 'duckduckgo'; // 'duckduckgo' | 'anthropic'
this.imageGenerator = options.imageGenerator || 'grok'; // 'grok' | 'anthropic' | 'webimages'
this.skipGrokFallback = false; // Set to true to disable Grok fallback
}
// ========== WEB SEARCH ==========
// Option 1: Grokpedia (X.AI search API)
async webSearchDuckDuckGo(query) {
try {
// Usar Grokpedia para bΓΊsqueda web confiable
if (!process.env.GROK_KEY) {
throw new Error('GROK_KEY not configured');
}
const response = await fetch('https://api.x.ai/v1/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.GROK_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: query,
max_results: 15,
search_depth: 'basic'
})
});
if (!response.ok) {
const error = await response.text();
console.error('Grokpedia error:', error);
throw new Error('Grokpedia search failed');
}
const data = await response.json();
let results = [];
if (data.results && Array.isArray(data.results)) {
results = data.results.map((item, idx) => ({
title: item.title || 'Untitled',
url: item.url || '#',
snippet: item.content || item.snippet || '',
index: idx + 1
}));
}
if (results.length === 0) {
throw new Error('No results from Grokpedia');
}
return results.slice(0, 15);
} catch (e) {
console.error('Grokpedia search error:', e.message);
// Fallback a Wikipedia
try {
const wikiUrl = `https://en.wikipedia.org/w/api.php?action=query&format=json&srsearch=${encodeURIComponent(query)}&list=search`;
const wikiResponse = await fetch(wikiUrl);
const wikiData = await wikiResponse.json();
if (wikiData.query?.search && wikiData.query.search.length > 0) {
return wikiData.query.search.slice(0, 15).map((item, idx) => ({
title: item.title,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(item.title)}`,
snippet: item.snippet.replace(/<[^>]*>/g, '').slice(0, 150),
index: idx + 1
}));
}
} catch (wikiError) {
console.log('Wikipedia fallback also failed');
}
// Last resort
return [
{
title: `${query} - Google Search`,
url: `https://www.google.com/search?q=${encodeURIComponent(query)}`,
index: 1
}
];
}
}
// Option 2: Anthropic/Claude (uses tokens but more structured)
async webSearchAnthropic(query) {
if (!this.anthropicKey) return [];
try {
const prompt = `Search the web for: "${query}"
Return top 10 results as JSON:
[
{ "title": "...", "url": "...", "snippet": "..." },
...
]
ONLY JSON, no other text.`;
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': this.anthropicKey,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 2048,
messages: [{ role: 'user', content: prompt }]
})
});
const data = await response.json();
const text = data.content?.[0]?.text || '';
try {
return JSON.parse(text);
} catch {
return [];
}
} catch (e) {
console.error('Anthropic search error:', e.message);
return [];
}
}
async webSearch(query) {
return this.searchProvider === 'anthropic'
? this.webSearchAnthropic(query)
: this.webSearchDuckDuckGo(query);
}
// ========== CONTENT EXTRACTION ==========
// Extraer imΓ‘genes + videos de una URL
async extractMediaFromUrl(url) {
try {
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
};
const response = await fetch(url, { headers, signal: AbortSignal.timeout(10000) });
if (!response.ok) return { images: [], videos: [] };
const html = await response.text();
const $ = cheerio.load(html);
let images = [];
let videos = [];
// Extract images
$('img').each((i, el) => {
if (images.length >= 20) return false;
const src = $(el).attr('src') || $(el).attr('data-src');
const alt = $(el).attr('alt') || '';
if (src && !src.includes('ad') && !src.includes('icon') && !src.includes('logo')) {
images.push({
url: src.startsWith('http') ? src : new URL(src, url).href,
alt: alt.slice(0, 100),
source: url
});
}
});
// Extract video sources
$('video source, iframe[src*="youtube"], iframe[src*="vimeo"]').each((i, el) => {
if (videos.length >= 5) return false;
const src = $(el).attr('src');
if (src) {
videos.push({
url: src,
type: $(el).attr('type') || 'video/mp4',
source: url
});
}
});
return {
images: images.slice(0, 15),
videos: videos.slice(0, 5)
};
} catch (e) {
console.error(`Media extraction error for ${url}:`, e.message);
return { images: [], videos: [] };
}
}
// ========== CONTENT SCORING & SELECTION ==========
scoreImages(images, topic) {
return images
.map((img, idx) => ({
...img,
score: (100 - idx * 5) + (img.alt.toLowerCase().includes(topic.toLowerCase()) ? 50 : 0)
}))
.sort((a, b) => b.score - a.score);
}
// ========== CAROUSEL GENERATION ==========
async generateCarouselSlides(topic, searchResults, media) {
if (!this.openrouterKey) return null;
// Extraer top 5 resultados como contexto
const context = searchResults
.slice(0, 5)
.map(r => `- ${r.title}`)
.join('\n');
const prompt = `Create 5 carousel slides for Instagram about: "${topic}"
Based on these sources:
${context}
Generate 5 slide texts (concise, impactful):
Slide 1: Hook/intro (max 80 chars)
Slide 2: Key insight #1 (max 120 chars)
Slide 3: Key insight #2 (max 120 chars)
Slide 4: Trend/analysis (max 120 chars)
Slide 5: CTA + hashtags (max 100 chars)
Format as JSON array:
[
{ "slide": 1, "text": "...", "emoji": "π―" },
...
]
ONLY JSON, no other text.`;
try {
const r = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.openrouterKey}`,
'HTTP-Referer': 'https://maarmapa.eth.limo'
},
body: JSON.stringify({
model: this.currentTextModel,
max_tokens: 800,
messages: [{ role: 'user', content: prompt }]
})
});
const data = await r.json();
const text = data.choices?.[0]?.message?.content || '';
try {
// Strip markdown code blocks if present
const clean = text.replace(/```json\s*/gi, '').replace(/```\s*/g, '').trim();
return JSON.parse(clean);
} catch {
// Fallback: build generic slides from topic
return [
{ slide: 1, text: topic, emoji: 'π―' },
{ slide: 2, text: `Key insights on ${topic}`, emoji: 'π‘' },
{ slide: 3, text: `Why ${topic} matters`, emoji: 'π' },
{ slide: 4, text: `The future of ${topic}`, emoji: 'π' },
{ slide: 5, text: `Follow for more β @maarmapa.eth`, emoji: 'β
' }
];
}
} catch (e) {
console.error('Carousel generation error:', e.message);
return [
{ slide: 1, text: topic, emoji: 'π―' },
{ slide: 2, text: `Key insights on ${topic}`, emoji: 'π‘' },
{ slide: 3, text: `Why ${topic} matters`, emoji: 'π' },
{ slide: 4, text: `The future of ${topic}`, emoji: 'π' },
{ slide: 5, text: `Follow for more β @maarmapa.eth`, emoji: 'β
' }
];
}
}
// ========== VIDEO GENERATION (Multiple Options) ==========
// Option 1: Grok (Generate carousel images)
async generateCarouselImagesWithGrok(topic, slides) {
if (!this.grokKey) return [];
const images = [];
for (let i = 0; i < Math.min(5, slides.length); i++) {
const slide = slides[i];
const prompt = `Create a visually stunning carousel slide image for: "${slide.text}"
Topic: ${topic}
Style: Modern, professional, Instagram-ready (1080x1350 portrait)
Include the slide text as overlay: "${slide.text.slice(0, 50)}..."`;
try {
const r = await fetch('https://api.x.ai/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.grokKey}`
},
body: JSON.stringify({
model: 'grok-imagine-image',
prompt,
n: 1,
response_format: 'url'
})
});
const data = await r.json();
if (data.data?.[0]?.url) {
images.push({ slide: i + 1, url: data.data[0].url });
}
} catch (e) {
console.log(`Grok image ${i + 1} failed:`, e.message);
}
}
return images;
}
// Option 2: Anthropic (Generate carousel images)
async generateCarouselImagesWithAnthropic(topic, slides) {
if (!this.anthropicKey) return [];
const images = [];
// Anthropic doesn't have image generation, so we'd use their vision API
// This is more of a text description generator
// For image generation, use Grok instead
return images;
}
// Option 3: Runway (Generate video from image)
async generateRunwayVideo(imageUrl, prompt) {
if (!this.runwayKey) return null;
try {
const r = await fetch('https://api.dev.runwayml.com/v1/image_to_video', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.runwayKey}`,
'X-Runway-Version': '2024-11-06'
},
body: JSON.stringify({
model: 'gen4_turbo',
promptImage: imageUrl,
promptText: prompt,
ratio: '720:1280',
duration: 5
})
});
const d = await r.json();
if (!d.id) return null;
// Poll for completion
for (let i = 0; i < 30; i++) {
await new Promise(res => setTimeout(res, 10000));
const t = await (await fetch(`https://api.dev.runwayml.com/v1/tasks/${d.id}`, {
headers: {
'Authorization': `Bearer ${this.runwayKey}`,
'X-Runway-Version': '2024-11-06'
}
})).json();
if (t.status === 'SUCCEEDED') return t.output?.[0] || null;
if (t.status === 'FAILED') return null;
}
return null;
} catch (e) {
console.error('Runway video error:', e.message);
return null;
}
}
// ========== UPLOAD TO R2 ==========
async uploadMediaToR2(buffer, filename, contentType = 'image/jpeg') {
try {
const r2Url = `${this.r2Worker}/${filename}`;
const res = await fetch(r2Url, {
method: 'PUT',
headers: {
'Content-Type': contentType,
'Authorization': `Bearer ${process.env.R2_UPLOAD_TOKEN || ''}`
},
body: buffer,
signal: AbortSignal.timeout(20000)
});
if (res.ok) {
const data = await res.json();
return data.url || r2Url;
}
return null;
} catch (e) {
console.error('R2 upload error:', e.message);
return null;
}
}
// ========== MAIN FLOW ==========
async generateWebPostCarousel(topic, monitor = null) {
const result = {
topic,
status: 'pending',
searchResults: [],
media: { images: [], videos: [] },
selectedImages: [],
slides: [],
videoUrl: null,
r2Urls: [],
tokensUsed: {}
};
try {
// STEP 1: Web search
console.log('π Web search...');
result.searchResults = await this.webSearch(topic);
if (!result.searchResults.length) {
result.status = 'error: no search results';
return result;
}
// STEP 2: Extract media from top 5 results
console.log('πΈ Extracting media...');
const mediaPromises = result.searchResults.slice(0, 5).map(r =>
this.extractMediaFromUrl(r.url)
);
const allMedia = await Promise.all(mediaPromises);
result.media.images = allMedia.flatMap(m => m.images);
result.media.videos = allMedia.flatMap(m => m.videos);
// STEP 3: Generate carousel slides (uses ~200 tokens OpenRouter)
console.log('π Generating carousel...');
result.slides = await this.generateCarouselSlides(topic, result.searchResults, result.media);
// STEP 4: Select images (Grok-generated OR web-extracted)
console.log('πΌοΈ Selecting carousel images...');
// If no web images found, generate with Grok (fallback logic)
if (!result.media.images.length) {
if (this.skipGrokFallback) {
// Lite mode: no Grok fallback
result.status = 'error: no images found (lite mode - no Grok fallback)';
return result;
}
console.log('π¨ No web images found, generating with Grok...');
if (this.grokKey) {
const slidesToUse = result.slides || [{ slide: 1, text: topic, emoji: 'π―' }];
const grokImages = await this.generateCarouselImagesWithGrok(topic, slidesToUse);
if (grokImages.length > 0) {
result.selectedImages = grokImages.map(img => ({ url: img.url, alt: `Slide ${img.slide}` }));
result.tokensUsed.grok = 50 * grokImages.length;
} else {
result.status = 'error: no images found and Grok generation failed';
return result;
}
} else {
result.status = 'error: no images found (no Grok key)';
return result;
}
} else if (this.imageGenerator === 'grok' && this.grokKey && result.slides) {
// User explicitly requested Grok images
console.log('π¨ Generating carousel images with Grok (explicit mode)...');
const grokImages = await this.generateCarouselImagesWithGrok(topic, result.slides);
result.selectedImages = grokImages.map(img => ({ url: img.url, alt: `Slide ${img.slide}` }));
result.tokensUsed.grok = 50 * Math.min(5, result.slides.length);
} else {
// Use web-extracted images (already scored)
const scored = this.scoreImages(result.media.images, topic);
result.selectedImages = scored.slice(0, 5);
result.tokensUsed.grok = 0;
}
// STEP 5: Generate video from best image (uses ~100 tokens Runway)
if (result.selectedImages.length > 0) {
console.log('π¬ Generating video with Runway...');
const bestImage = result.selectedImages[0];
const videoPrompt = `Create a dynamic, engaging video intro for: "${topic}".
Professional, modern, with subtle animations. Perfect for Instagram Reels.`;
result.videoUrl = await this.generateRunwayVideo(bestImage.url, videoPrompt);
}
// STEP 6: Upload images to R2
console.log('π€ Uploading to R2...');
for (let i = 0; i < result.selectedImages.length; i++) {
const img = result.selectedImages[i];
try {
const imgResponse = await fetch(img.url, { signal: AbortSignal.timeout(15000) });
if (imgResponse.ok) {
const buffer = await imgResponse.arrayBuffer();
const filename = `carousel_${topic.replace(/\s+/g, '-').toLowerCase()}-${i + 1}-${Date.now()}.jpg`;
const r2Url = await this.uploadMediaToR2(buffer, filename);
if (r2Url) result.r2Urls.push(r2Url);
}
} catch (e) {
console.log(`Image ${i + 1} upload failed:`, e.message);
}
}
// STEP 7: Track tokens
result.tokensUsed.openrouter = 200; // carousel text generation
if (monitor) {
await monitor.trackUsage('openrouter', 200, `/webpost-carousel ${topic}`);
if (result.tokensUsed.grok > 0) {
await monitor.trackUsage('grok', result.tokensUsed.grok, `/webpost-carousel ${topic}`);
}
}
result.status = 'success';
return result;
} catch (e) {
result.status = `error: ${e.message}`;
return result;
}
}
}
module.exports = WebPostCarouselGenerator;