Spaces:
Sleeping
Sleeping
Download backend/src/services/dueDateExtractionService.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 9.05 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/dueDateExtractionService.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/services/dueDateExtractionService.js
-
curl -L -o dueDateExtractionService.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/dueDateExtractionService.js
9.05 kB
| 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(); |