Spaces:
Sleeping

File size: 9,050 Bytes
0b355ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const aiService = require('./aiService');
const logger = require('../utils/logger');

class DueDateExtractionService {
  async extractDueDates(documentText, documentType = 'syllabus') {
    try {
      const prompt = this.buildExtractionPrompt(documentText, documentType);
      
      const response = await aiService.generateResponse([
        {
          role: 'system',
          content: prompt
        }
      ], {});

      // Parse the AI response to extract structured due date information
      const dueDates = this.parseAIResponse(response.content);
      
      logger.info('Due dates extracted', { 
        documentType, 
        extractedCount: dueDates.length,
        textLength: documentText.length 
      });

      return dueDates;

    } catch (error) {
      logger.error('Due date extraction failed:', error);
      return [];
    }
  }

  buildExtractionPrompt(documentText, documentType) {
    const basePrompt = `You are an expert at extracting due dates and important deadlines from academic documents. 

Your task is to carefully analyze the following ${documentType} and extract ALL due dates, deadlines, exam dates, project submissions, assignment dates, and other time-sensitive academic information.

For each due date found, extract:
1. Title/Description of what is due
2. Due date (be very specific about the date and time if provided)
3. Type of assignment/task (assignment, exam, project, quiz, presentation, reading, other)
4. Course information if mentioned
5. Any additional relevant details
6. Your confidence level (0.0 to 1.0) in the accuracy of this extraction

IMPORTANT GUIDELINES:
- Extract dates in a consistent format (YYYY-MM-DD or MM/DD/YYYY)
- If only relative dates are given (e.g., "next week", "in two weeks"), try to calculate actual dates if a reference point exists
- Include recurring events if mentioned (weekly quizzes, etc.)
- Pay attention to different date formats and academic calendar references
- Look for words like: due, deadline, exam, test, quiz, project, assignment, submit, presentation, reading
- Include final exams, midterms, and any other important academic dates
- If a date is unclear or ambiguous, mark confidence as lower

Return your findings in the following JSON format:
[
  {
    "title": "Assignment 1: Research Paper",
    "dueDate": "2024-09-15",
    "type": "assignment",
    "description": "5-page research paper on machine learning applications",
    "course": "CS 4710",
    "confidence": 0.95,
    "extractedText": "Assignment 1 due September 15th"
  }
]

Document text to analyze:

${documentText}

Please extract all due dates and return ONLY the JSON array:`;

    return basePrompt;
  }

  parseAIResponse(responseText) {
    try {
      // Clean the response text to extract JSON
      let cleanedResponse = responseText.trim();
      
      // Remove any markdown code blocks
      cleanedResponse = cleanedResponse.replace(/```json\s*|\s*```/g, '');
      cleanedResponse = cleanedResponse.replace(/```\s*|\s*```/g, '');
      
      // Try to find JSON array in the response
      const jsonMatch = cleanedResponse.match(/\[[\s\S]*\]/);
      if (jsonMatch) {
        cleanedResponse = jsonMatch[0];
      }

      const dueDates = JSON.parse(cleanedResponse);
      
      if (!Array.isArray(dueDates)) {
        logger.warn('AI response is not an array:', dueDates);
        return [];
      }

      // Validate and clean the extracted due dates
      return dueDates
        .filter(item => item.title && item.dueDate)
        .map(item => ({
          title: String(item.title).trim(),
          dueDate: this.parseDateString(item.dueDate),
          type: this.validateType(item.type),
          description: item.description ? String(item.description).trim() : '',
          course: item.course ? String(item.course).trim() : '',
          extractedText: item.extractedText ? String(item.extractedText).trim() : '',
          confidence: this.validateConfidence(item.confidence)
        }))
        .filter(item => item.dueDate); // Remove items with invalid dates

    } catch (error) {
      logger.error('Failed to parse AI response for due dates:', error);
      logger.debug('Raw AI response:', responseText);
      
      // Fallback: try to extract dates using regex patterns
      return this.fallbackDateExtraction(responseText);
    }
  }

  parseDateString(dateStr) {
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) {
        // Try different date formats
        const formats = [
          /(\d{1,2})\/(\d{1,2})\/(\d{4})/,  // MM/DD/YYYY
          /(\d{4})-(\d{1,2})-(\d{1,2})/,    // YYYY-MM-DD
          /(\d{1,2})-(\d{1,2})-(\d{4})/,    // MM-DD-YYYY
        ];

        for (const format of formats) {
          const match = dateStr.match(format);
          if (match) {
            let year, month, day;
            if (format === formats[0] || format === formats[2]) {
              [, month, day, year] = match;
            } else {
              [, year, month, day] = match;
            }
            const parsedDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
            if (!isNaN(parsedDate.getTime())) {
              return parsedDate;
            }
          }
        }
        return null;
      }
      return date;
    } catch (error) {
      logger.warn('Failed to parse date string:', dateStr);
      return null;
    }
  }

  validateType(type) {
    const validTypes = ['assignment', 'exam', 'project', 'quiz', 'presentation', 'reading', 'other'];
    if (validTypes.includes(type)) {
      return type;
    }
    
    // Try to infer type from keywords
    const lowerType = String(type || '').toLowerCase();
    if (lowerType.includes('exam') || lowerType.includes('test')) return 'exam';
    if (lowerType.includes('quiz')) return 'quiz';
    if (lowerType.includes('project')) return 'project';
    if (lowerType.includes('assignment') || lowerType.includes('homework')) return 'assignment';
    if (lowerType.includes('presentation')) return 'presentation';
    if (lowerType.includes('reading')) return 'reading';
    
    return 'other';
  }

  validateConfidence(confidence) {
    const conf = parseFloat(confidence);
    if (isNaN(conf)) return 0.5;
    return Math.max(0, Math.min(1, conf));
  }

  fallbackDateExtraction(text) {
    // Simple regex-based fallback for extracting dates
    const datePatterns = [
      /due\s+(?:on\s+)?(\w+\s+\d{1,2},?\s+\d{4})/gi,
      /deadline\s+(?:is\s+)?(\w+\s+\d{1,2},?\s+\d{4})/gi,
      /(\w+\s+\d{1,2},?\s+\d{4})\s*[-:]\s*(.+?)(?=\n|$)/gi,
    ];

    const fallbackDates = [];
    
    for (const pattern of datePatterns) {
      let match;
      while ((match = pattern.exec(text)) !== null) {
        const dateStr = match[1];
        const description = match[2] || 'Extracted due date';
        const parsedDate = this.parseDateString(dateStr);
        
        if (parsedDate) {
          fallbackDates.push({
            title: description.trim(),
            dueDate: parsedDate,
            type: 'other',
            description: '',
            course: '',
            extractedText: match[0],
            confidence: 0.3 // Lower confidence for regex extraction
          });
        }
      }
    }

    logger.info('Fallback extraction found dates:', fallbackDates.length);
    return fallbackDates;
  }

  // Helper method to extract dates for a specific course context
  async extractDueDatesWithCourseContext(documentText, courseInfo = {}) {
    const dueDates = await this.extractDueDates(documentText);
    
    // Enhance due dates with course context
    return dueDates.map(dueDate => ({
      ...dueDate,
      course: dueDate.course || courseInfo.courseCode || '',
      semester: courseInfo.semester || '',
      year: courseInfo.year || new Date().getFullYear()
    }));
  }

  // Method to validate and improve extracted dates
  validateExtractedDates(dueDates, documentContext = {}) {
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    
    return dueDates.map(dueDate => {
      let confidence = dueDate.confidence;
      
      // Reduce confidence for dates in the past (unless it's a historical document)
      if (dueDate.dueDate < currentDate && !documentContext.isHistorical) {
        confidence = Math.max(0.1, confidence - 0.3);
      }
      
      // Reduce confidence for dates too far in the future
      const yearsDiff = dueDate.dueDate.getFullYear() - currentYear;
      if (yearsDiff > 2) {
        confidence = Math.max(0.1, confidence - 0.2);
      }
      
      // Increase confidence for dates that match academic calendar patterns
      const month = dueDate.dueDate.getMonth();
      if ((month >= 8 && month <= 11) || (month >= 0 && month <= 4)) {
        // Fall or Spring semester - typical academic dates
        confidence = Math.min(1.0, confidence + 0.1);
      }
      
      return {
        ...dueDate,
        confidence
      };
    });
  }
}

module.exports = new DueDateExtractionService();