-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch_form_voice.js
More file actions
366 lines (316 loc) · 14.6 KB
/
Copy pathpatch_form_voice.js
File metadata and controls
366 lines (316 loc) · 14.6 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
/**
* SECTION-SPECIFIC VOICE INPUT - Replace old voice code with this
*
* Instructions:
* 1. In form_mode.html, find the line: setupVoiceInput();
* 2. Replace it with: setupSectionVoiceInput();
* 3. Delete all code from "let voiceRecorder = {" to "function fillFormWithCVData..." (entire old voice implementation)
* 4. Copy and paste this entire file content in that location
*/
// Voice Recording (section-specific)
let voiceRecorder = {
mediaRecorder: null,
audioChunks: [],
isRecording: false,
startTime: null,
timerInterval: null,
currentSection: null
};
function setupSectionVoiceInput() {
// Add event listeners to all voice section buttons
document.querySelectorAll('.voice-section-btn').forEach(btn => {
btn.addEventListener('click', () => {
const section = btn.getAttribute('data-section');
showVoiceRecordingModal(section);
});
});
// Keyboard shortcut for recording
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'z' && voiceRecorder.currentSection) {
e.preventDefault();
if (!voiceRecorder.isRecording) {
startSectionRecording();
}
}
});
document.addEventListener('keyup', (e) => {
if ((e.key === 'Control' || e.key === 'z') && voiceRecorder.isRecording) {
stopSectionRecording();
}
});
}
function showVoiceRecordingModal(section) {
voiceRecorder.currentSection = section;
// Create modal
const modal = document.createElement('div');
modal.id = 'voiceModal';
modal.className = 'fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50';
modal.innerHTML = `
<div class="glass-strong rounded-2xl p-8 max-w-lg w-full mx-4 shadow-2xl">
<div class="flex items-center justify-between mb-6">
<h3 class="text-2xl font-bold text-white">🎙️ Voice Input: ${capitalize(section)}</h3>
<button onclick="closeVoiceModal()" class="text-gray-400 hover:text-white text-2xl">×</button>
</div>
<div class="bg-white/5 rounded-lg p-4 mb-6">
<h5 class="font-semibold text-white mb-2 flex items-center gap-2">
<i class="fas fa-lightbulb text-yellow-400"></i>
What to say:
</h5>
<div class="text-sm text-gray-300 space-y-1 ml-6">
${getVoiceGuidelines(section)}
</div>
</div>
<div class="space-y-4">
<div id="voiceIdleState" class="text-center">
<button onclick="startSectionRecording()" class="bg-red-500 hover:bg-red-600 text-white px-8 py-4 rounded-xl font-semibold flex items-center space-x-3 mx-auto transition">
<i class="fas fa-circle text-xs animate-pulse"></i>
<span>Hold Ctrl+Z to Record</span>
</button>
<p class="text-xs text-gray-400 mt-3">Or click button to start</p>
</div>
<div id="voiceRecordingState" class="hidden bg-red-500/20 border border-red-500 rounded-lg p-4 text-center">
<div class="flex items-center justify-center space-x-3">
<div class="recording-pulse"></div>
<span class="text-white font-semibold">Recording... <span id="sectionRecordingTimer">00:00</span></span>
</div>
<p class="text-sm text-gray-300 mt-2">Release Ctrl+Z or click Stop</p>
<button onclick="stopSectionRecording()" class="mt-3 bg-gray-700 hover:bg-gray-600 text-white px-6 py-2 rounded-lg">Stop</button>
</div>
<div id="voiceProcessingState" class="hidden bg-blue-500/20 border border-blue-500 rounded-lg p-4 text-center">
<div class="flex items-center justify-center space-x-3">
<i class="fas fa-spinner fa-spin text-blue-400"></i>
<span class="text-white font-semibold">Processing...</span>
</div>
<p class="text-sm text-gray-300 mt-2">Extracting information from your voice</p>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
requestMicrophonePermission();
}
function getVoiceGuidelines(section) {
const guidelines = {
personal: `
<p>✓ Your full name and professional title</p>
<p>✓ Email, phone number, and location</p>
<p>✓ LinkedIn, GitHub, or portfolio links</p>
`,
summary: `
<p>✓ Your role and years of experience</p>
<p>✓ Key specializations and technologies</p>
<p>✓ Major achievements or impact</p>
`,
education: `
<p>✓ Degree name and major</p>
<p>✓ University or institution name</p>
<p>✓ Graduation year and GPA (if strong)</p>
`,
experience: `
<p>✓ Job title and company name</p>
<p>✓ Start and end dates</p>
<p>✓ Key responsibilities and achievements</p>
<p>✓ Metrics and quantifiable results</p>
`,
projects: `
<p>✓ Project name and description</p>
<p>✓ Technologies and tools used</p>
<p>✓ Your role and contributions</p>
<p>✓ Links to demo or source code</p>
`,
skills: `
<p>✓ Technical skills and tools</p>
<p>✓ Programming languages</p>
<p>✓ Frameworks and technologies</p>
`
};
return guidelines[section] || '<p>Describe your information clearly</p>';
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function closeVoiceModal() {
const modal = document.getElementById('voiceModal');
if (modal) modal.remove();
voiceRecorder.currentSection = null;
if (voiceRecorder.isRecording) {
stopSectionRecording();
}
}
async function requestMicrophonePermission() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach(track => track.stop());
} catch (err) {
showNotification('Microphone permission required. Please allow access.', 'error');
}
}
async function startSectionRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
voiceRecorder.mediaRecorder = new MediaRecorder(stream);
voiceRecorder.audioChunks = [];
voiceRecorder.isRecording = true;
voiceRecorder.startTime = Date.now();
voiceRecorder.mediaRecorder.ondataavailable = (event) => {
voiceRecorder.audioChunks.push(event.data);
};
voiceRecorder.mediaRecorder.onstop = async () => {
const audioBlob = new Blob(voiceRecorder.audioChunks, { type: 'audio/webm' });
await processSectionVoice(audioBlob);
};
voiceRecorder.mediaRecorder.start();
// Update UI
document.getElementById('voiceIdleState').classList.add('hidden');
document.getElementById('voiceRecordingState').classList.remove('hidden');
// Start timer
voiceRecorder.timerInterval = setInterval(updateSectionTimer, 100);
} catch (err) {
showNotification('Failed to start recording: ' + err.message, 'error');
}
}
function updateSectionTimer() {
if (!voiceRecorder.isRecording) return;
const elapsed = Date.now() - voiceRecorder.startTime;
const seconds = Math.floor(elapsed / 1000);
const minutes = Math.floor(seconds / 60);
const secs = seconds % 60;
const timerEl = document.getElementById('sectionRecordingTimer');
if (timerEl) {
timerEl.textContent = `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
// Auto-stop at 2 minutes
if (seconds >= 120) {
stopSectionRecording();
}
}
function stopSectionRecording() {
if (!voiceRecorder.isRecording) return;
voiceRecorder.isRecording = false;
clearInterval(voiceRecorder.timerInterval);
if (voiceRecorder.mediaRecorder && voiceRecorder.mediaRecorder.state !== 'inactive') {
voiceRecorder.mediaRecorder.stop();
voiceRecorder.mediaRecorder.stream.getTracks().forEach(track => track.stop());
}
}
async function processSectionVoice(audioBlob) {
// Show processing state
document.getElementById('voiceRecordingState').classList.add('hidden');
document.getElementById('voiceProcessingState').classList.remove('hidden');
try {
// Step 1: Transcribe
const formData = new FormData();
formData.append('audio', audioBlob, 'section_voice.webm');
const transcribeResponse = await fetch('/api/voice/transcribe-bulk', {
method: 'POST',
body: formData
});
if (!transcribeResponse.ok) {
throw new Error('Transcription failed');
}
const transcribeData = await transcribeResponse.json();
const transcript = transcribeData.text;
// Step 2: Extract section-specific data
const extractResponse = await fetch('/api/voice/extract-section-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transcript: transcript,
section: voiceRecorder.currentSection
})
});
if (!extractResponse.ok) {
throw new Error('Data extraction failed');
}
const sectionData = await extractResponse.json();
// Step 3: Fill section fields
fillSectionData(voiceRecorder.currentSection, sectionData);
// Success
closeVoiceModal();
showNotification(`✅ ${capitalize(voiceRecorder.currentSection)} section filled!`, 'success');
} catch (err) {
console.error('Voice processing error:', err);
document.getElementById('voiceProcessingState').classList.add('hidden');
document.getElementById('voiceIdleState').classList.remove('hidden');
showNotification('❌ ' + err.message, 'error');
}
}
function fillSectionData(section, data) {
if (section === 'personal' && data.personal_info) {
const fields = ['name', 'headline', 'email', 'phone', 'location', 'linkedin', 'github', 'website'];
fields.forEach(field => {
const value = data.personal_info[field] || data.personal_info[field === 'headline' ? 'title' : field];
if (value) setFieldValue(field, value);
});
}
if (section === 'summary' && data.summary) {
setFieldValue('summary', data.summary);
}
if (section === 'education' && data.education && data.education.length > 0) {
data.education.forEach(edu => {
addEducationEntry();
const entries = document.getElementById('education-entries').children;
const entry = entries[entries.length - 1];
const inputs = {
degree: entry.querySelector('input[placeholder*="Degree"]'),
institution: entry.querySelector('input[placeholder*="Institution"]'),
year: entry.querySelector('input[placeholder*="Year"]'),
gpa: entry.querySelector('input[placeholder*="GPA"]')
};
if (inputs.degree) inputs.degree.value = edu.degree || '';
if (inputs.institution) inputs.institution.value = edu.institution || '';
if (inputs.year) inputs.year.value = edu.graduation_year || '';
if (inputs.gpa) inputs.gpa.value = edu.gpa || '';
});
}
if (section === 'experience' && data.experiences && data.experiences.length > 0) {
data.experiences.forEach(exp => {
addExperienceEntry();
const entries = document.getElementById('experience-entries').children;
const entry = entries[entries.length - 1];
const inputs = {
title: entry.querySelector('input[placeholder*="Title"], input[placeholder*="Position"]'),
company: entry.querySelector('input[placeholder*="Company"]'),
start: entry.querySelector('input[placeholder*="Start"]'),
end: entry.querySelector('input[placeholder*="End"]'),
highlights: entry.querySelector('textarea')
};
if (inputs.title) inputs.title.value = exp.position || '';
if (inputs.company) inputs.company.value = exp.company || '';
if (inputs.start) inputs.start.value = exp.start_date || '';
if (inputs.end) inputs.end.value = exp.end_date || '';
if (inputs.highlights && exp.highlights) inputs.highlights.value = exp.highlights.join('\n');
});
}
if (section === 'projects' && data.projects && data.projects.length > 0) {
data.projects.forEach(proj => {
addProjectEntry();
const entries = document.getElementById('project-entries').children;
const entry = entries[entries.length - 1];
const inputs = {
name: entry.querySelector('input[placeholder*="Name"]'),
url: entry.querySelector('input[placeholder*="URL"]'),
description: entry.querySelector('textarea')
};
if (inputs.name) inputs.name.value = proj.name || '';
if (inputs.url) inputs.url.value = proj.url || '';
if (inputs.description) inputs.description.value = proj.description || '';
});
}
if (section === 'skills' && data.skills) {
['technical', 'soft', 'languages'].forEach(skillType => {
if (data.skills[skillType] && data.skills[skillType].length > 0) {
addSkillEntry();
const entries = document.getElementById('skill-entries').children;
const entry = entries[entries.length - 1];
const inputs = {
category: entry.querySelector('input[placeholder*="Category"]'),
skills: entry.querySelector('textarea')
};
if (inputs.category) inputs.category.value = capitalize(skillType) + ' Skills';
if (inputs.skills) inputs.skills.value = data.skills[skillType].join(', ');
}
});
}
updateProgress();
}