-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoJobs.js
More file actions
306 lines (255 loc) · 10.3 KB
/
AutoJobs.js
File metadata and controls
306 lines (255 loc) · 10.3 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
require("dotenv").config();
const cron = require('node-cron');
const axios = require('axios');
const OpenAI = require("openai");
const db = require("./utils/firebaseConfig");
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const API_BASE_URL = 'http://127.0.0.1:5000/api/v1';
// Helper function to get last 24 hours journals for a user
async function getLast24HoursJournals(userId) {
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const snapshot = await db.ref("journal")
.orderByChild("user_id")
.equalTo(userId)
.once("value");
if (!snapshot.exists()) return [];
const journals = Object.values(snapshot.val())
.filter(journal => journal.created_at > yesterday);
return journals;
}
// Generate satisfaction score using GPT
async function analyzeMood(journals) {
if (journals.length === 0) return null;
const combinedContent = journals.map(j => j.content).join('\n');
const prompt = `Analyze these journal entries and provide a satisfaction score from 0 to 100 based on the overall mood and content. Return only the number, nothing else.`;
const response = await openai.chat.completions.create({
messages: [
{ role: "system", content: prompt },
{ role: "user", content: combinedContent }
],
model: "gpt-4",
});
const score = parseInt(response.choices[0].message.content.trim());
return {
satisfactionScore: score
};
}
// Generate insight using GPT
async function generateInsight(journals) {
if (journals.length === 0) return null;
const combinedContent = journals.map(j => j.content).join('\n');
const prompt = `Based on these journal entries, provide:
1. A one or two-word title that captures the main theme
2. A 10-line insight about the person's mental state, patterns, and suggestions
Format: TITLE|||INSIGHT`;
const response = await openai.chat.completions.create({
messages: [
{ role: "system", content: prompt },
{ role: "user", content: combinedContent }
],
model: "gpt-4",
});
const [title, insight] = response.choices[0].message.content.split('|||');
return { title: title.trim(), insight: insight.trim() };
}
async function updateMoodForDay(userId, satisfactionScore) {
try {
// Get current mood data
const response = await axios.get(`${API_BASE_URL}/mood/${userId}`);
const currentMood = response.data.mood.mood || Array(7).fill().map(() => ({ value: 0 }));
// Get current day of week (0 = Sunday, 1 = Monday, etc.)
const dayIndex = new Date().getDay();
const dayMap = ['S', 'M', 'T', 'W', 'TH', 'F', 'S'];
// Update the value for current day
currentMood[dayIndex] = {
day: dayMap[dayIndex],
value: satisfactionScore
};
// Update mood via API
await axios.post(`${API_BASE_URL}/mood/update`, {
userId,
mood: currentMood
});
return true;
} catch (error) {
console.error('Error updating mood:', error);
return false;
}
}
async function createMindInsight(userId, insight, title) {
try {
await axios.post(`${API_BASE_URL}/mind/create`, {
userId,
insight,
title
});
return true;
} catch (error) {
console.error('Error creating mind insight:', error);
return false;
}
}
// Add this new function to check last analysis time
async function checkLastAnalysis(userId) {
try {
const snapshot = await db.ref(`analysis_tracker/${userId}`).once("value");
if (!snapshot.exists()) return true; // Never analyzed before
const lastAnalysis = snapshot.val().lastAnalysis;
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
return lastAnalysis < twentyFourHoursAgo;
} catch (error) {
console.error(`Error checking last analysis for user ${userId}:`, error);
return false;
}
}
// Add this function to update last analysis timestamp
async function updateLastAnalysis(userId) {
try {
await db.ref(`analysis_tracker/${userId}`).set({
lastAnalysis: new Date().toISOString()
});
} catch (error) {
console.error(`Error updating last analysis for user ${userId}:`, error);
}
}
// Process single user
async function processUser(userId) {
try {
// Check if enough time has passed since last analysis
const shouldAnalyze = await checkLastAnalysis(userId);
if (!shouldAnalyze) {
console.log(`Skipping analysis for user ${userId}: Too soon since last analysis`);
return;
}
const journals = await getLast24HoursJournals(userId);
if (journals.length === 0) return;
// Analyze mood
const moodAnalysis = await analyzeMood(journals);
if (moodAnalysis) {
await updateMoodForDay(userId, moodAnalysis.satisfactionScore);
}
// Generate insight
const mindInsight = await generateInsight(journals);
if (mindInsight) {
await createMindInsight(userId, mindInsight.insight, mindInsight.title);
}
// Update the last analysis timestamp
await updateLastAnalysis(userId);
} catch (error) {
console.error(`Error processing user ${userId}:`, error);
}
}
// Main cron job function
function startDailyAnalysis() {
// Run every day at 00:00
cron.schedule('* * * * *', async () => {
try {
// Get all unique users with journals
const snapshot = await db.ref("journal")
.orderByChild("created_at")
.startAt(new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString())
.once("value");
if (!snapshot.exists()) return;
const journals = snapshot.val();
const userIds = [...new Set(Object.values(journals).map(j => j.user_id))];
// Process each user
for (const userId of userIds) {
await processUser(userId);
}
} catch (error) {
console.error('Daily analysis cron job error:', error);
}
});
}
// Helper function to find frequent words in journals
async function findFrequentWords(journals) {
// Combine all journal contents
const combinedContent = journals.map(j => j.content).join(' ');
// Convert to lowercase and remove punctuation
const cleanContent = combinedContent.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
// Split into words and filter out common words and short words
const commonWords = new Set(['the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i',
'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his',
'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all',
'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which',
'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take',
'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than',
'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after',
'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because',
'any', 'these', 'give', 'day', 'most', 'us', 'is', 'am', 'are', 'was', 'were', 'been']);
const words = cleanContent.split(/\s+/).filter(word =>
word.length > 3 && !commonWords.has(word)
);
// Count word frequencies
const wordFrequency = {};
words.forEach(word => {
wordFrequency[word] = (wordFrequency[word] || 0) + 1;
});
// Convert to array and sort by frequency
const sortedWords = Object.entries(wordFrequency)
.sort((a, b) => b[1] - a[1])
.slice(0, 3) // Get only top 3 words
.map(([word, count]) => [word, count.toString()]); // Convert count to string
return sortedWords;
}
// Function to update frequent words for a user
async function updateFrequentWords(userId, frequentWords) {
try {
// Ensure exactly 3 words
while (frequentWords.length < 3) {
frequentWords.push(["", ""]); // Pad with empty pairs if less than 3 words found
}
await axios.patch(`${API_BASE_URL}/frequent-words/update/${userId}`, {
frequentWords
});
return true;
} catch (error) {
console.error('Error updating frequent words:', error);
return false;
}
}
// Process frequent words for a single user
async function processFrequentWords(userId) {
try {
// Get all journals for the user
const snapshot = await db.ref("journal")
.orderByChild("user_id")
.equalTo(userId)
.once("value");
if (!snapshot.exists()) return;
const journals = Object.values(snapshot.val());
const frequentWords = await findFrequentWords(journals);
if (frequentWords.length > 0) {
await updateFrequentWords(userId, frequentWords);
}
} catch (error) {
console.error(`Error processing frequent words for user ${userId}:`, error);
}
}
// Add this new function to start the frequent words analysis
function startFrequentWordsAnalysis() {
// Run every day at 01:00 (different time than the mood analysis to spread the load)
cron.schedule('5 * * * *', async () => {
try {
// Get all unique users with journals
const snapshot = await db.ref("journal")
.once("value");
if (!snapshot.exists()) return;
const journals = snapshot.val();
const userIds = [...new Set(Object.values(journals).map(j => j.user_id))];
// Process each user
for (const userId of userIds) {
await processFrequentWords(userId);
}
} catch (error) {
console.error('Frequent words analysis cron job error:', error);
}
});
}
// Update the module exports to include the new function
module.exports = {
startDailyAnalysis,
startFrequentWordsAnalysis
};