Report / generate-academic-report.js
salekml's picture
Upload generate-academic-report.js
90870d2 verified
#!/usr/bin/env node
/**
* Smart Academic Report Generator - DOCX Backend
* Generates professional PhD-level academic reports
* Usage: node generate-academic-report.js --config config.json
*/
// ================= Import Modules =================
const {
Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
Header, Footer, AlignmentType, PageOrientation, LevelFormat,
PageNumber, PageBreak, BorderStyle, WidthType, ShadingType,
TableOfContents, HeadingLevel, UnderlineType, Tab, TabStopType,
TabStopPosition, Footer: FooterRef, PageNumberFormat
} = require('docx');
const fs = require('fs'); // <-- declare only once
const path = require('path'); // <-- declare only once
// ================= Default Configuration =================
const defaultConfig = {
studentName: 'Student Name',
studentId: 'ID-2023-001',
department: 'Computer Science & Engineering',
university: 'University Name',
courseTitle: 'Course Title',
courseCode: 'CSE 101',
teacherName: 'Professor Name',
teacherDesignation: 'Associate Professor',
submissionDate: new Date().toISOString().split('T')[0],
reportType: 'assignment',
reportTitle: 'Report Title',
topic: 'Topic Description',
includeAbstract: true,
includeTOC: true,
includeReferences: true,
pageNumbers: true,
fontFamily: 'Times New Roman',
fontSize: '12',
lineSpacing: '1.5'
};
// Sample content structure
const sampleContent = {
abstract: "This report presents a comprehensive analysis of the topic under investigation. The study employs a systematic approach to examine key aspects and their implications. Through rigorous methodology and careful analysis, this research contributes to the existing body of knowledge in the field. The findings demonstrate significant insights that have both theoretical and practical applications. This work establishes a foundation for future research directions and provides valuable recommendations for stakeholders.",
introduction: `The field has witnessed remarkable developments in recent years, necessitating a thorough examination of current practices and emerging trends. This report aims to provide a comprehensive analysis of the subject matter, exploring its various dimensions and implications.
The primary objective of this study is to investigate the fundamental aspects of the topic and their relevance to contemporary challenges. By examining existing literature and analyzing current data, this research seeks to contribute meaningful insights to the field.
This report is structured to provide a logical progression of ideas, beginning with a review of existing literature, followed by a detailed methodology, presentation of findings, discussion of implications, and concluding with recommendations for future research and practice.`,
literatureReview: `The existing body of literature provides a robust foundation for understanding the complexities of this subject. Previous researchers have explored various dimensions of the topic, establishing theoretical frameworks that inform current practice.
Smith and Johnson (2022) conducted a seminal study examining the fundamental principles underlying this phenomenon. Their work demonstrated that systematic approaches yield more reliable outcomes than traditional methods. This finding has been corroborated by subsequent research conducted by Williams et al. (2023).
Recent developments in the field have been marked by technological advancements and methodological innovations. Chen and Rodriguez (2024) introduced a novel framework that integrates multiple perspectives, providing a more holistic understanding of the subject matter.
Critical analysis of the literature reveals several gaps that this research aims to address. While previous studies have focused primarily on theoretical aspects, there remains a need for empirical investigation of practical applications. Furthermore, the intersection of various factors influencing outcomes has not been adequately explored.
The theoretical framework adopted in this study draws upon established models while incorporating contemporary insights. This synthesis of traditional and modern approaches enables a comprehensive examination of the research questions.`,
methodology: `This research employs a mixed-methods approach, combining quantitative and qualitative techniques to provide a comprehensive analysis. The methodology was designed to ensure rigor, reliability, and validity of findings.
Data Collection: Primary data was gathered through structured surveys and semi-structured interviews. The survey instrument was developed based on validated scales from previous research, with modifications to suit the specific context of this study. A total of 250 participants were recruited using stratified random sampling to ensure representativeness.
Qualitative data was collected through in-depth interviews with 25 key stakeholders. Interview protocols were designed to explore participants' experiences, perceptions, and insights regarding the phenomenon under investigation. All interviews were recorded with consent and transcribed verbatim for analysis.
Data Analysis: Quantitative data was analyzed using statistical software (SPSS version 28). Descriptive statistics, correlation analysis, and regression modeling were employed to identify patterns and relationships. The significance level was set at p < 0.05.
Qualitative data underwent thematic analysis following the six-phase framework proposed by Braun and Clarke (2006). This process involved familiarization with data, generating initial codes, searching for themes, reviewing themes, defining themes, and producing the final report.
Ethical Considerations: The research protocol received approval from the Institutional Review Board. Informed consent was obtained from all participants, and measures were implemented to ensure confidentiality and anonymity. Data was stored securely and will be retained according to institutional guidelines.`,
results: `The analysis revealed several significant findings that address the research objectives. This section presents the key results organized thematically.
Finding 1: Quantitative analysis demonstrated a strong positive correlation (r = 0.72, p < 0.001) between the primary variables under investigation. This relationship remained significant even after controlling for potential confounding factors through multiple regression analysis (Ξ² = 0.68, p < 0.001).
Finding 2: Qualitative analysis identified four major themes that emerged consistently across participant interviews. These themes represent distinct but interconnected aspects of the phenomenon: (a) contextual factors influencing outcomes, (b) individual variations in approach, (c) systemic barriers and facilitators, and (d) long-term sustainability concerns.
Finding 3: Comparative analysis across different demographic groups revealed interesting patterns. Participants with higher levels of experience demonstrated significantly different approaches compared to novices (t(248) = 4.82, p < 0.001). However, no significant differences were observed based on other demographic variables.
Finding 4: The data suggests that certain interventions are more effective than others in achieving desired outcomes. Specifically, integrated approaches that address multiple factors simultaneously yielded superior results compared to single-dimension interventions (F(3,246) = 12.45, p < 0.001).
These findings collectively provide strong evidence supporting the hypotheses proposed at the outset of this research. The convergence of quantitative and qualitative results strengthens the validity of these conclusions.`,
discussion: `The findings of this research have significant implications for both theory and practice. This section interprets the results in the context of existing literature and explores their broader significance.
The strong correlation identified in the quantitative analysis aligns with theoretical predictions but extends previous understanding by demonstrating the robustness of this relationship across diverse contexts. This finding challenges some assumptions in earlier work and suggests the need for theoretical refinement.
The qualitative themes provide nuanced insights that help explain the mechanisms underlying the quantitative patterns. Participants' narratives reveal complex interactions between individual agency and structural constraints, highlighting the importance of context in shaping outcomes.
The observed differences across experience levels have important practical implications. They suggest that interventions should be tailored to account for varying levels of expertise rather than employing one-size-fits-all approaches. This finding supports calls for more personalized and adaptive strategies.
Several limitations should be acknowledged. First, the cross-sectional design limits causal inference. While the results suggest relationships between variables, longitudinal research would be needed to establish causality definitively. Second, the sample was drawn from a specific geographic region, which may limit generalizability to other contexts.
Despite these limitations, the research makes several important contributions. It provides empirical evidence supporting theoretical propositions, introduces methodological innovations that can be applied in future studies, and offers practical recommendations grounded in rigorous analysis.`,
conclusion: `This research has provided comprehensive insights into the topic under investigation, addressing the objectives established at the outset. The findings contribute to theoretical understanding while offering practical implications for stakeholders.
The key conclusions can be summarized as follows: (1) There exists a strong, consistent relationship between the primary variables examined, (2) Multiple factors interact in complex ways to influence outcomes, (3) Experience and context play crucial roles in shaping approaches and results, and (4) Integrated interventions demonstrate superior effectiveness compared to single-dimension approaches.
These conclusions have several practical implications. For practitioners, the findings suggest the importance of adopting comprehensive, context-sensitive approaches rather than relying on standardized interventions. For policymakers, the results highlight the need to consider multiple factors when designing initiatives and allocating resources.
Future research should address the limitations identified in this study. Longitudinal investigations would provide stronger evidence for causal relationships. Cross-cultural studies would enhance understanding of how findings translate across different contexts. Additionally, experimental designs could test the effectiveness of specific interventions suggested by this research.
In conclusion, this study has advanced knowledge in the field by providing robust empirical evidence, offering theoretical insights, and generating practical recommendations. The findings establish a foundation for continued investigation and inform efforts to improve outcomes in practice.`,
references: [
"Anderson, M. K., & Thompson, R. L. (2024). Contemporary approaches in research methodology. Journal of Academic Studies, 45(3), 234-256. https://doi.org/10.1234/jas.2024.001",
"Braun, V., & Clarke, V. (2006). Using thematic analysis in psychology. Qualitative Research in Psychology, 3(2), 77-101. https://doi.org/10.1191/1478088706qp063oa",
"Chen, L., & Rodriguez, P. (2024). Integrated frameworks for comprehensive analysis. International Review of Research, 18(1), 45-67. https://doi.org/10.5678/irr.2024.003",
"Davis, S. J., Martinez, K. R., & White, D. L. (2023). Empirical investigations in modern contexts. Research Quarterly, 67(4), 412-435. https://doi.org/10.9012/rq.2023.042",
"Johnson, E. T. (2023). Theoretical foundations and practical applications. Academic Press.",
"Kim, H. S., & Park, J. Y. (2024). Cross-cultural perspectives on contemporary issues. Global Studies Review, 29(2), 156-178. https://doi.org/10.3456/gsr.2024.015",
"Miller, B. A., & Wilson, C. D. (2023). Methodological innovations in research design. Methods in Research, 12(3), 289-312. https://doi.org/10.7890/mir.2023.028",
"Smith, J. A., & Johnson, R. B. (2022). Systematic approaches to complex problems. Journal of Contemporary Research, 34(5), 567-589. https://doi.org/10.2345/jcr.2022.056",
"Williams, P. T., Garcia, M. E., & Brown, L. K. (2023). Advanced techniques in data analysis. Statistical Methods Journal, 41(6), 723-745. https://doi.org/10.6789/smj.2023.072",
"Zhang, Y., & Lee, S. M. (2024). Future directions in academic research. Trends in Education and Research, 15(1), 89-112. https://doi.org/10.4567/ter.2024.008"
]
};
/**
* Helper function to create paragraphs from text with multiple paragraphs
*/
function createParagraphs(text, fontSize = 24, lineSpacing = 360) {
if (!text) return [];
return text.split('\n\n')
.filter(p => p.trim())
.map(para => new Paragraph({
children: [new TextRun({
text: para.trim(),
size: fontSize
})],
spacing: {
before: 120,
after: 120,
line: lineSpacing
},
alignment: AlignmentType.JUSTIFIED
}));
}
/**
* Format date in academic style
*/
function formatDate(dateString) {
const date = new Date(dateString);
const options = { day: 'numeric', month: 'long', year: 'numeric' };
return date.toLocaleDateString('en-GB', options);
}
/**
* Generate the complete academic report
*/
function generateAcademicReport(config, content = sampleContent) {
const cfg = { ...defaultConfig, ...config };
const fontSize = parseInt(cfg.fontSize) * 2; // Convert to half-points
const lineSpacing = Math.round(parseFloat(cfg.lineSpacing) * 240); // Convert to twips
const doc = new Document({
styles: {
default: {
document: {
run: {
font: cfg.fontFamily,
size: fontSize
},
paragraph: {
spacing: {
line: lineSpacing
}
}
}
},
paragraphStyles: [
{
id: "Heading1",
name: "Heading 1",
basedOn: "Normal",
next: "Normal",
quickFormat: true,
run: {
size: 32,
bold: true,
font: cfg.fontFamily,
color: "1F4788"
},
paragraph: {
spacing: { before: 480, after: 240, line: lineSpacing },
outlineLevel: 0,
border: {
bottom: {
color: "1F4788",
space: 1,
style: BorderStyle.SINGLE,
size: 6
}
}
}
},
{
id: "Heading2",
name: "Heading 2",
basedOn: "Normal",
next: "Normal",
quickFormat: true,
run: {
size: 28,
bold: true,
font: cfg.fontFamily,
color: "2E5C8A"
},
paragraph: {
spacing: { before: 360, after: 180, line: lineSpacing },
outlineLevel: 1
}
},
{
id: "Heading3",
name: "Heading 3",
basedOn: "Normal",
next: "Normal",
quickFormat: true,
run: {
size: 26,
bold: true,
font: cfg.fontFamily,
color: "4472C4"
},
paragraph: {
spacing: { before: 240, after: 120, line: lineSpacing },
outlineLevel: 2
}
}
]
},
numbering: {
config: [
{
reference: "references-numbering",
levels: [
{
level: 0,
format: LevelFormat.DECIMAL,
text: "[%1]",
alignment: AlignmentType.LEFT,
style: {
paragraph: {
indent: { left: 720, hanging: 360 }
}
}
}
]
}
]
},
sections: [
// ====== COVER PAGE SECTION ======
{
properties: {
page: {
size: { width: 12240, height: 15840 }, // US Letter
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 }
}
},
children: [
// University Logo Space (optional)
new Paragraph({
spacing: { before: 480, after: 240 }
}),
// University Name
new Paragraph({
children: [
new TextRun({
text: cfg.university.toUpperCase(),
bold: true,
size: 36,
font: cfg.fontFamily,
color: "1F4788"
})
],
alignment: AlignmentType.CENTER,
spacing: { before: 960, after: 120 }
}),
// Department
new Paragraph({
children: [
new TextRun({
text: `Department of ${cfg.department}`,
bold: true,
size: 30,
font: cfg.fontFamily,
color: "2E5C8A"
})
],
alignment: AlignmentType.CENTER,
spacing: { after: 720 }
}),
// Decorative Top Border
new Paragraph({
border: {
top: {
color: "1F4788",
space: 1,
style: BorderStyle.DOUBLE,
size: 12
}
},
spacing: { before: 360, after: 360 }
}),
// Report Type Badge
new Paragraph({
children: [
new TextRun({
text: cfg.reportType.toUpperCase(),
bold: true,
size: 24,
font: cfg.fontFamily,
color: "FFFFFF"
})
],
alignment: AlignmentType.CENTER,
spacing: { before: 480, after: 240 },
shading: {
type: ShadingType.CLEAR,
fill: "4472C4"
},
border: {
top: { color: "4472C4", size: 6, style: BorderStyle.SINGLE },
bottom: { color: "4472C4", size: 6, style: BorderStyle.SINGLE },
left: { color: "4472C4", size: 6, style: BorderStyle.SINGLE },
right: { color: "4472C4", size: 6, style: BorderStyle.SINGLE }
}
}),
// Main Report Title
new Paragraph({
children: [
new TextRun({
text: cfg.reportTitle,
bold: true,
size: 40,
font: cfg.fontFamily,
color: "1F4788"
})
],
alignment: AlignmentType.CENTER,
spacing: { before: 480, after: 240 }
}),
// Topic/Subtitle (if different)
...(cfg.topic && cfg.topic !== cfg.reportTitle ? [
new Paragraph({
children: [
new TextRun({
text: cfg.topic,
size: 28,
font: cfg.fontFamily,
italics: true,
color: "2E5C8A"
})
],
alignment: AlignmentType.CENTER,
spacing: { after: 720 }
})
] : [
new Paragraph({
spacing: { after: 720 }
})
]),
// Decorative Middle Border
new Paragraph({
border: {
bottom: {
color: "1F4788",
space: 1,
style: BorderStyle.DOUBLE,
size: 12
}
},
spacing: { before: 360, after: 720 }
}),
// Course Information Section
new Paragraph({
children: [
new TextRun({
text: "Course Information",
bold: true,
size: 26,
font: cfg.fontFamily,
underline: { type: UnderlineType.SINGLE }
})
],
alignment: AlignmentType.CENTER,
spacing: { before: 240, after: 240 }
}),
new Paragraph({
children: [
new TextRun({
text: `${cfg.courseTitle} (${cfg.courseCode})`,
size: 24,
font: cfg.fontFamily,
bold: true
})
],
alignment: AlignmentType.CENTER,
spacing: { after: 480 }
}),
// Instructor Information
new Paragraph({
children: [
new TextRun({
text: "Submitted To:",
bold: true,
size: 24,
font: cfg.fontFamily
}),
new TextRun({
text: "\n" + cfg.teacherName,
size: 24,
font: cfg.fontFamily
}),
...(cfg.teacherDesignation ? [
new TextRun({
text: `\n${cfg.teacherDesignation}`,
size: 22,
font: cfg.fontFamily,
italics: true
})
] : [])
],
alignment: AlignmentType.CENTER,
spacing: { before: 360, after: 480 }
}),
// Student Information
new Paragraph({
children: [
new TextRun({
text: "Submitted By:",
bold: true,
size: 24,
font: cfg.fontFamily
}),
new TextRun({
text: "\n" + cfg.studentName,
size: 26,
font: cfg.fontFamily,
bold: true,
color: "1F4788"
}),
new TextRun({
text: `\nStudent ID: ${cfg.studentId}`,
size: 22,
font: cfg.fontFamily
}),
new TextRun({
text: `\n${cfg.department}`,
size: 22,
font: cfg.fontFamily,
italics: true
})
],
alignment: AlignmentType.CENTER,
spacing: { after: 480 }
}),
// Submission Date
new Paragraph({
children: [
new TextRun({
text: "Date of Submission:",
bold: true,
size: 22,
font: cfg.fontFamily
}),
new TextRun({
text: "\n" + formatDate(cfg.submissionDate),
size: 24,
font: cfg.fontFamily,
bold: true
})
],
alignment: AlignmentType.CENTER,
spacing: { before: 480 }
}),
// Decorative Bottom Border
new Paragraph({
border: {
bottom: {
color: "1F4788",
space: 1,
style: BorderStyle.TRIPLE,
size: 12
}
},
spacing: { before: 720 }
}),
// Page Break
new Paragraph({
children: [new PageBreak()]
})
]
},
// ====== MAIN CONTENT SECTION ======
{
properties: {
page: {
size: { width: 12240, height: 15840 },
margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 }
}
},
footers: cfg.pageNumbers ? {
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun({
text: "Page ",
size: fontSize
}),
new TextRun({
children: [PageNumber.CURRENT],
size: fontSize
}),
new TextRun({
text: " of ",
size: fontSize
}),
new TextRun({
children: [PageNumber.TOTAL_PAGES],
size: fontSize
})
]
})
]
})
} : undefined,
children: [
// ====== TABLE OF CONTENTS ======
...(cfg.includeTOC ? [
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("Table of Contents")],
pageBreakBefore: false
}),
new TableOfContents("Table of Contents", {
hyperlink: true,
headingStyleRange: "1-3",
stylesWithLevels: [
{ heading: HeadingLevel.HEADING_1, level: 0 },
{ heading: HeadingLevel.HEADING_2, level: 1 },
{ heading: HeadingLevel.HEADING_3, level: 2 }
]
}),
new Paragraph({
children: [new PageBreak()]
})
] : []),
// ====== ABSTRACT ======
...(cfg.includeAbstract && content.abstract ? [
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("Abstract")]
}),
new Paragraph({
children: [new TextRun({
text: content.abstract,
italics: true,
size: fontSize
})],
alignment: AlignmentType.JUSTIFIED,
spacing: { before: 240, after: 480, line: lineSpacing }
}),
new Paragraph({
children: [new PageBreak()]
})
] : []),
// ====== INTRODUCTION ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("1. Introduction")]
}),
...createParagraphs(content.introduction, fontSize, lineSpacing),
new Paragraph({ spacing: { after: 480 } }),
// ====== LITERATURE REVIEW ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("2. Literature Review")]
}),
...createParagraphs(content.literatureReview, fontSize, lineSpacing),
new Paragraph({ spacing: { after: 480 } }),
// ====== METHODOLOGY ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("3. Methodology")]
}),
...createParagraphs(content.methodology, fontSize, lineSpacing),
new Paragraph({
children: [new PageBreak()]
}),
// ====== RESULTS ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("4. Results and Findings")]
}),
...createParagraphs(content.results, fontSize, lineSpacing),
new Paragraph({ spacing: { after: 480 } }),
// ====== DISCUSSION ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("5. Discussion")]
}),
...createParagraphs(content.discussion, fontSize, lineSpacing),
new Paragraph({ spacing: { after: 480 } }),
// ====== CONCLUSION ======
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("6. Conclusion")]
}),
...createParagraphs(content.conclusion, fontSize, lineSpacing),
// ====== REFERENCES ======
...(cfg.includeReferences && content.references && content.references.length > 0 ? [
new Paragraph({
children: [new PageBreak()]
}),
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [new TextRun("References")]
}),
...content.references.map((ref, idx) =>
new Paragraph({
numbering: {
reference: "references-numbering",
level: 0
},
children: [new TextRun({
text: ref,
size: fontSize
})],
spacing: { before: 120, after: 120, line: lineSpacing },
alignment: AlignmentType.LEFT
})
)
] : [])
]
}
]
});
return doc;
}
/**
* Main execution
*/
async function main() {
try {
// Check for config file argument
let config = defaultConfig;
const configArgIndex = process.argv.indexOf('--config');
if (configArgIndex !== -1 && process.argv[configArgIndex + 1]) {
const configPath = process.argv[configArgIndex + 1];
const configData = fs.readFileSync(configPath, 'utf8');
config = { ...defaultConfig, ...JSON.parse(configData) };
}
console.log('πŸŽ“ Smart Academic Report Generator');
console.log('━'.repeat(50));
console.log(`πŸ“š Generating report for: ${config.studentName}`);
console.log(`πŸ“ Title: ${config.reportTitle}`);
console.log(`πŸ›οΈ University: ${config.university}`);
console.log('━'.repeat(50));
// Generate document
const doc = generateAcademicReport(config);
// Output path
const outputPath = path.join('/mnt/user-data/outputs', 'academic-report.docx');
// Ensure output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Generate buffer and save
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync(outputPath, buffer);
console.log('βœ… Document generated successfully!');
console.log(`πŸ“„ Saved to: ${outputPath}`);
console.log('━'.repeat(50));
console.log('✨ Features included:');
console.log(' β€’ Professional Cover Page');
if (config.includeTOC) console.log(' β€’ Table of Contents');
if (config.includeAbstract) console.log(' β€’ Abstract');
console.log(' β€’ Complete Report Structure');
if (config.includeReferences) console.log(' β€’ APA Style References');
if (config.pageNumbers) console.log(' β€’ Page Numbers');
console.log('━'.repeat(50));
} catch (error) {
console.error('❌ Error generating document:', error);
process.exit(1);
}
}
// ================= Output Path =================
const outputDir = '/mnt/user-data/outputs';
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true }); // folder create if not exists
}
const outputPath = path.join(outputDir, 'academic-report.docx'); // <-- path
// Run if called directly
if (require.main === module) {
main();
}
// Export for use as module
module.exports = { generateAcademicReport, defaultConfig, sampleContent };