-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
567 lines (490 loc) · 19.9 KB
/
Copy pathscript.js
File metadata and controls
567 lines (490 loc) · 19.9 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// ========================================
// ECE Project Generator - JavaScript Logic
// ========================================
// DOM Elements
const projectForm = document.getElementById('projectForm');
const generateBtn = document.getElementById('generateBtn');
const loadingIndicator = document.getElementById('loadingIndicator');
const outputContent = document.getElementById('outputContent');
const reportOutput = document.getElementById('reportOutput');
const errorMessage = document.getElementById('errorMessage');
const initialState = document.getElementById('initialState');
const copyBtn = document.getElementById('copyBtn');
const downloadBtn = document.getElementById('downloadBtn');
const printBtn = document.getElementById('printBtn');
// Form inputs
const semesterInput = document.getElementById('semester');
const skillLevelInput = document.getElementById('skillLevel');
const interestAreaInput = document.getElementById('interestArea');
const budgetInput = document.getElementById('budget');
const projectTypeInput = document.getElementById('projectType');
const apiKeyInput = document.getElementById('apiKey');
// Master Prompt Template
const masterPromptTemplate = `You are an expert Electronics and Communication Engineering (ECE) professor and AI system architect. Your task is to generate a COMPLETE ECE MINI/MAJOR PROJECT REPORT based on student inputs.
STUDENT INPUTS:
- Semester: {SEMESTER}
- Skill Level: {SKILL_LEVEL}
- Interest Area: {INTEREST_AREA}
- Budget: INR {BUDGET}
- Project Type: {PROJECT_TYPE}
IMPORTANT CONSTRAINTS:
1. Every section mentioned below MUST be included in your output. No section can be skipped.
2. Use clear, exam-oriented engineering language suitable for college submission.
3. Make the project realistic with actual components available in Indian market.
4. Ensure the total estimated cost is within the specified budget.
5. Content must be original and suitable for viva presentation.
6. Prefer modern technologies: IoT, AI, Embedded Systems, Robotics, Signal Processing.
STRICT OUTPUT STRUCTURE:
=====================================
## 1. PROJECT TITLE
[Generate a compelling, specific project title based on interest area and semester]
## 2. PROBLEM DEFINITION
[2-3 clear paragraphs explaining:
- The real-world problem being solved
- Why this problem needs a solution
- Current limitations or existing approaches]
## 3. WORKING LOGIC
[Provide clear step-by-step numbered explanation (at least 8-10 steps) of how the project works]
## 4. COMPONENTS REQUIRED
### A. HARDWARE COMPONENTS
[List all hardware components in format:
- Component Name | Purpose/Use | Specification]
### B. SOFTWARE / TOOLS USED
[List all software, programming languages, libraries, frameworks]
## 5. ESTIMATED COST (in INR)
[Provide component-wise breakdown with realistic Indian market prices]
- Total Estimated Cost: INR ______
## 6. FUTURE SCOPE
[Provide at least 5 strong improvements, extensions, or scalability options with detailed explanation for each]
## 7. COMPLETE PROJECT REPORT
### 7.1 ABSTRACT
[150-200 words summarizing the entire project, objectives, and outcomes]
### 7.2 INTRODUCTION
[Comprehensive introduction to the domain, current state, and relevance. 250-300 words]
### 7.3 PROBLEM STATEMENT
[Detailed problem analysis, existing gaps, and project objectives]
### 7.4 PROPOSED SYSTEM
[Detailed explanation of the proposed solution with advantages over existing systems]
### 7.5 WORKING METHODOLOGY
[Step-by-step detailed explanation of how the system operates]
### 7.6 HARDWARE DESCRIPTION
[Detailed specifications and working of each hardware component used]
### 7.7 SOFTWARE DESCRIPTION
[Detailed explanation of software architecture, algorithms, code structure, or implementation approach]
### 7.8 BLOCK DIAGRAM EXPLANATION
[Text-based detailed explanation of the system architecture and signal flow between components.
Describe how data/signals flow from input → processing → output]
### 7.9 EXPECTED OUTPUT
[Describe what outputs the project will produce and how success will be measured]
### 7.10 ADVANTAGES
[List 5-7 key advantages of this system over existing approaches]
### 7.11 APPLICATIONS
[List 5-8 real-world applications where this project can be deployed]
### 7.12 LIMITATIONS
[Honest discussion of 4-5 limitations and potential constraints]
### 7.13 FUTURE ENHANCEMENTS
[Provide 5+ detailed enhancement ideas for future versions]
### 7.14 CONCLUSION
[Brief conclusion summarizing the project, achievements, and impact. 150-200 words]
=====================================
QUALITY REQUIREMENTS:
✓ Language: Clear, technical, exam-ready
✓ Cost: Realistic INR prices, within budget
✓ Feasibility: Achievable within given semester/skill level
✓ Originality: Unique approach to the problem
✓ Completeness: All 14 sections MUST be present
✓ Relevance: Aligned with interest area and modern ECE trends
Now generate the complete project report following the structure above. Ensure EVERY section is included with substantial, original content.`;
// Event Listeners
projectForm.addEventListener('submit', handleFormSubmit);
copyBtn.addEventListener('click', copyToClipboard);
downloadBtn.addEventListener('click', downloadReport);
printBtn.addEventListener('click', printReport);
/**
* Handle form submission
*/
async function handleFormSubmit(e) {
e.preventDefault();
e.preventDefault();
hideError();
// Collect and validate inputs
const inputs = collectFormInputs();
if (!inputs) return;
// Build prompt and call AI
const prompt = buildMasterPrompt(inputs);
showLoading(true);
try {
const generatedText = await callAI(prompt, inputs.apiKey);
// Try to parse into structured sections and render
const sections = parseSections(generatedText);
renderSections(sections, generatedText);
} catch (err) {
showError(err.message || String(err));
// fallback: show raw output if available
} finally {
showLoading(false);
}
}
/**
* Validate form inputs
*/
function validateForm() {
if (!semesterInput.value || !skillLevelInput.value || !interestAreaInput.value ||
!budgetInput.value || !projectTypeInput.value || !apiKeyInput.value) {
showError('Please fill all required fields');
return false;
}
if (!apiKeyInput.value.startsWith('sk-')) {
showError('Invalid API Key format. It should start with "sk-"');
return false;
}
return true;
}
/**
* Generate project report using OpenAI API
*/
async function generateProjectReport(prompt, apiKey) {
// This function is no longer used; logic moved to callAI and handleFormSubmit
}
/**
* Collect form inputs and return structured object or null on validation failure
*/
function collectFormInputs() {
const semester = semesterInput.value;
const skillLevel = skillLevelInput.value;
const interestArea = interestAreaInput.value;
const budget = budgetInput.value;
const projectType = projectTypeInput.value;
const apiKey = apiKeyInput.value;
if (!semester || !skillLevel || !interestArea || !budget || !projectType || !apiKey) {
showError('Please fill all required fields');
return null;
}
if (!apiKey.startsWith('sk-')) {
showError('Invalid API Key format. It should start with "sk-"');
return null;
}
return { semester, skillLevel, interestArea, budget, projectType, apiKey };
}
/**
* Build final prompt from template and inputs
*/
function buildMasterPrompt(inputs) {
return masterPromptTemplate
.replace('{SEMESTER}', inputs.semester + ' Semester')
.replace('{SKILL_LEVEL}', inputs.skillLevel)
.replace('{INTEREST_AREA}', inputs.interestArea)
.replace('{BUDGET}', inputs.budget)
.replace('{PROJECT_TYPE}', inputs.projectType);
}
/**
* Call OpenAI Chat Completions and return generated text
*/
async function callAI(prompt, apiKey) {
// Disable button and show intermediate state
generateBtn.disabled = true;
const originalText = generateBtn.querySelector('span').textContent;
generateBtn.querySelector('span').textContent = 'Generating...';
try {
const res = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'You are an expert ECE professor generating exam-ready project reports. Output must exactly follow the required headings and order.' },
{ role: 'user', content: prompt }
],
temperature: 0.2,
max_tokens: 5000,
top_p: 1,
presence_penalty: 0,
frequency_penalty: 0
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
if (err && err.error && err.error.message) throw new Error(err.error.message);
throw new Error(`API Error: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const text = data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content;
if (!text) throw new Error('No content returned from API');
return text;
} finally {
generateBtn.disabled = false;
generateBtn.querySelector('span').textContent = originalText;
}
}
/**
* Parse generated text into structured sections using exact heading matching (robust to header markers)
*/
function parseSections(text) {
const lines = text.split(/\r?\n/);
const sectionDefs = [
{ keys: ['1. PROJECT TITLE', 'PROJECT TITLE'], id: 'projectTitle' },
{ keys: ['2. PROBLEM DEFINITION', 'PROBLEM DEFINITION'], id: 'problemDefinition' },
{ keys: ['3. WORKING LOGIC', 'WORKING LOGIC'], id: 'workingLogic' },
{ keys: ['A. HARDWARE COMPONENTS', '4.A HARDWARE COMPONENTS', 'HARDWARE COMPONENTS'], id: 'componentsHardware' },
{ keys: ['B. SOFTWARE / TOOLS USED', '4.B SOFTWARE / TOOLS USED', 'SOFTWARE / TOOLS USED'], id: 'componentsSoftware' },
{ keys: ['5. ESTIMATED COST', 'ESTIMATED COST'], id: 'estimatedCost' },
{ keys: ['6. FUTURE SCOPE', 'FUTURE SCOPE'], id: 'futureScope' },
{ keys: ['7.1 ABSTRACT', 'ABSTRACT'], id: 'abstract' },
{ keys: ['7.2 INTRODUCTION', 'INTRODUCTION'], id: 'introduction' },
{ keys: ['7.3 PROBLEM STATEMENT', 'PROBLEM STATEMENT'], id: 'problemStatement' },
{ keys: ['7.4 PROPOSED SYSTEM', 'PROPOSED SYSTEM'], id: 'proposedSystem' },
{ keys: ['7.5 WORKING METHODOLOGY', 'WORKING METHODOLOGY'], id: 'workingMethodology' },
{ keys: ['7.6 HARDWARE DESCRIPTION', 'HARDWARE DESCRIPTION'], id: 'hardwareDescription' },
{ keys: ['7.7 SOFTWARE DESCRIPTION', 'SOFTWARE DESCRIPTION'], id: 'softwareDescription' },
{ keys: ['7.8 BLOCK DIAGRAM EXPLANATION', 'BLOCK DIAGRAM EXPLANATION'], id: 'blockDiagram' },
{ keys: ['7.9 EXPECTED OUTPUT', 'EXPECTED OUTPUT'], id: 'expectedOutput' },
{ keys: ['7.10 ADVANTAGES', 'ADVANTAGES'], id: 'advantages' },
{ keys: ['7.11 APPLICATIONS', 'APPLICATIONS'], id: 'applications' },
{ keys: ['7.12 LIMITATIONS', 'LIMITATIONS'], id: 'limitations' },
{ keys: ['7.13 FUTURE ENHANCEMENTS', 'FUTURE ENHANCEMENTS'], id: 'futureEnhancements' },
{ keys: ['7.14 CONCLUSION', 'CONCLUSION'], id: 'conclusion' }
];
// Find line indices for headings
const positions = [];
for (let i = 0; i < lines.length; i++) {
const norm = lines[i].replace(/[#\-\>\*]/g, '').replace(/\s+/g, ' ').trim().toUpperCase();
for (const def of sectionDefs) {
for (const key of def.keys) {
if (norm === key.toUpperCase()) {
positions.push({ id: def.id, index: i });
}
}
}
}
// If no positions found, return null to indicate fallback
if (positions.length === 0) return null;
// Sort positions by index
positions.sort((a, b) => a.index - b.index);
const sections = {};
for (let i = 0; i < positions.length; i++) {
const current = positions[i];
const next = positions[i + 1];
const start = current.index + 1;
const end = next ? next.index : lines.length;
const content = lines.slice(start, end).join('\n').trim();
sections[current.id] = content || '';
}
return sections;
}
/**
* Render parsed sections into dedicated DOM containers. If parsing failed, render raw text into fallback container.
*/
function renderSections(sections, rawText) {
const mapping = {
projectTitle: 'projectTitle',
problemDefinition: 'problemDefinition',
workingLogic: 'workingLogic',
componentsHardware: 'componentsHardware',
componentsSoftware: 'componentsSoftware',
estimatedCost: 'estimatedCost',
futureScope: 'futureScope',
abstract: 'abstract',
introduction: 'introduction',
problemStatement: 'problemStatement',
proposedSystem: 'proposedSystem',
workingMethodology: 'workingMethodology',
hardwareDescription: 'hardwareDescription',
softwareDescription: 'softwareDescription',
blockDiagram: 'blockDiagram',
expectedOutput: 'expectedOutput',
advantages: 'advantages',
applications: 'applications',
limitations: 'limitations',
futureEnhancements: 'futureEnhancements',
conclusion: 'conclusion'
};
// If parsing failed, show raw formatted output in reportOutput
if (!sections) {
reportOutput.innerHTML = formatReportContent(rawText);
initialState.style.display = 'none';
outputContent.style.display = 'block';
return;
}
// Clear all containers first
Object.values(mapping).forEach(id => {
const el = document.getElementById(id);
if (el) el.innerHTML = '';
});
// Fill containers with formatted content (keep heading title as visible label)
for (const [key, id] of Object.entries(mapping)) {
const el = document.getElementById(id);
if (!el) continue;
const content = sections[key] || '';
if (content.trim() === '') {
el.innerHTML = `<h3>${toReadableHeading(key)}</h3><p><em>Section missing in AI output.</em></p>`;
} else {
el.innerHTML = `<h3>${toReadableHeading(key)}</h3>` + formatReportContent(content);
}
}
// Show output panel
initialState.style.display = 'none';
outputContent.style.display = 'block';
}
function toReadableHeading(key) {
const map = {
projectTitle: '1. PROJECT TITLE',
problemDefinition: '2. PROBLEM DEFINITION',
workingLogic: '3. WORKING LOGIC',
componentsHardware: '4.A HARDWARE COMPONENTS',
componentsSoftware: '4.B SOFTWARE / TOOLS USED',
estimatedCost: '5. ESTIMATED COST',
futureScope: '6. FUTURE SCOPE',
abstract: '7.1 ABSTRACT',
introduction: '7.2 INTRODUCTION',
problemStatement: '7.3 PROBLEM STATEMENT',
proposedSystem: '7.4 PROPOSED SYSTEM',
workingMethodology: '7.5 WORKING METHODOLOGY',
hardwareDescription: '7.6 HARDWARE DESCRIPTION',
softwareDescription: '7.7 SOFTWARE DESCRIPTION',
blockDiagram: '7.8 BLOCK DIAGRAM EXPLANATION',
expectedOutput: '7.9 EXPECTED OUTPUT',
advantages: '7.10 ADVANTAGES',
applications: '7.11 APPLICATIONS',
limitations: '7.12 LIMITATIONS',
futureEnhancements: '7.13 FUTURE ENHANCEMENTS',
conclusion: '7.14 CONCLUSION'
};
return map[key] || key;
}
/**
* Display the generated report
*/
function displayReport(content) {
// Convert markdown to HTML-like format
const htmlContent = formatReportContent(content);
reportOutput.innerHTML = htmlContent;
// Hide initial state and show output
initialState.style.display = 'none';
outputContent.style.display = 'block';
}
/**
* Format report content for display
*/
function formatReportContent(content) {
let html = content;
// Basic markdown-like to HTML conversion (safe, minimal)
// Headers (lines that are all-caps section headings will remain as text in renderSections)
html = html
.replace(/\r/g, '')
.split('\n\n')
.map(para => {
// convert list items
if (/^\s*-\s+/.test(para)) {
const items = para.split(/\n/).map(l => l.replace(/^\s*-\s+/, '').trim()).filter(Boolean);
return '<ul>' + items.map(i => '<li>' + escapeHtml(i) + '</li>').join('') + '</ul>';
}
return '<p>' + escapeHtml(para).replace(/\n/g, '<br>') + '</p>';
})
.join('');
return html;
}
function escapeHtml(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
/**
* Show loading indicator
*/
function showLoading(show) {
if (show) {
loadingIndicator.style.display = 'flex';
outputContent.style.display = 'none';
initialState.style.display = 'none';
} else {
loadingIndicator.style.display = 'none';
}
}
/**
* Show error message
*/
function showError(message) {
errorMessage.textContent = message;
errorMessage.style.display = 'block';
}
/**
* Hide error message
*/
function hideError() {
errorMessage.style.display = 'none';
}
/**
* Copy report to clipboard
*/
function copyToClipboard() {
const text = reportOutput.innerText;
navigator.clipboard.writeText(text).then(() => {
// Show feedback
const originalText = copyBtn.textContent;
copyBtn.textContent = '✓ Copied!';
setTimeout(() => {
copyBtn.textContent = originalText;
}, 2000);
}).catch(err => {
showError('Failed to copy to clipboard');
});
}
/**
* Download report as text file
*/
function downloadReport() {
const text = reportOutput.innerText;
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', 'ECE_Project_Report.txt');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
/**
* Print report
*/
function printReport() {
const printWindow = window.open('', '', 'width=800,height=600');
const printContent = `
<html>
<head>
<title>ECE Project Report</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 20px; }
h1 { color: #667eea; border-bottom: 3px solid #667eea; padding-bottom: 10px; }
h2 { color: #764ba2; border-left: 4px solid #764ba2; padding-left: 10px; margin-top: 20px; }
h3 { color: #667eea; margin-top: 15px; }
p { text-align: justify; }
ul, ol { margin-left: 20px; }
li { margin-bottom: 8px; }
</style>
</head>
<body>
${reportOutput.innerHTML}
</body>
</html>
`;
printWindow.document.write(printContent);
printWindow.document.close();
printWindow.print();
}
/**
* Initialize on page load
*/
document.addEventListener('DOMContentLoaded', function() {
console.log('ECE Project Generator initialized');
// Check if API key is stored in localStorage (optional security enhancement)
const storedApiKey = localStorage.getItem('eceProjectGeneratorApiKey');
if (storedApiKey) {
apiKeyInput.value = storedApiKey;
}
});
// Optional: Save API key to localStorage (user can clear manually)
apiKeyInput.addEventListener('change', function() {
if (confirm('Save API key locally for future use? (You can clear it anytime)')) {
localStorage.setItem('eceProjectGeneratorApiKey', this.value);
}
});