-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocess_cv_revamp.php
More file actions
969 lines (823 loc) · 36.2 KB
/
process_cv_revamp.php
File metadata and controls
969 lines (823 loc) · 36.2 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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
<?php
// Start output buffering to prevent any accidental output
ob_start();
header('Content-Type: application/json');
// Enable error reporting for debugging but don't display errors
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
// Error handler to convert errors to JSON
set_error_handler(function($errno, $errstr, $errfile, $errline) {
ob_clean(); // Clear any output
echo json_encode([
'success' => false,
'error' => "PHP Error: $errstr in $errfile on line $errline"
]);
exit;
});
// Load Composer autoloader for dependencies (PDF parser, etc.)
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
}
// Load configuration if exists
if (file_exists(__DIR__ . '/config.php')) {
require_once __DIR__ . '/config.php';
} elseif (file_exists(__DIR__ . '/config.example.php')) {
require_once __DIR__ . '/config.example.php';
}
// Load PHPMailer
require_once __DIR__ . '/PHPMailer/src/Exception.php';
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load TCPDF if available (Composer or manual installation)
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/tcpdf/tcpdf.php')) {
require_once __DIR__ . '/tcpdf/tcpdf.php';
} elseif (file_exists(__DIR__ . '/vendor/tecnickcom/tcpdf/tcpdf.php')) {
require_once __DIR__ . '/vendor/tecnickcom/tcpdf/tcpdf.php';
}
function json_error($message) {
ob_clean(); // Clear any output buffer
echo json_encode(['success' => false, 'error' => $message]);
exit;
}
// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
json_error('Invalid request method');
}
// Validate required fields (either file upload OR pasted text)
if (empty($_POST['target_job']) || empty($_POST['email'])) {
json_error('Please fill in all required fields');
}
// Check if either file upload or pasted text is provided
if (empty($_FILES['current_cv']['tmp_name']) && empty($_POST['cv_text'])) {
json_error('Please either upload a CV file or paste your CV text');
}
// Validate email
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
if (!$email) {
json_error('Invalid email address');
}
// Create uploads directory if it doesn't exist
$upload_dir = defined('CV_UPLOAD_DIR') ? CV_UPLOAD_DIR : __DIR__ . '/data/cv_uploads';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
// Generate unique ID for this request
$unique_id = uniqid('cv_', true);
// Check if using pasted text or file upload
$cv_text = '';
if (!empty($_POST['cv_text'])) {
// User pasted CV text
$cv_text = trim($_POST['cv_text']);
if (strlen($cv_text) < 100) {
json_error('Please paste your complete CV text (at least 100 characters)');
}
} else {
// User uploaded a file
if (!isset($_FILES['current_cv']) || $_FILES['current_cv']['error'] !== UPLOAD_ERR_OK) {
json_error('Please either upload a CV file or paste your CV text');
}
$cv_file = $_FILES['current_cv'];
$allowed_extensions = ['pdf', 'doc', 'docx'];
$file_extension = strtolower(pathinfo($cv_file['name'], PATHINFO_EXTENSION));
if (!in_array($file_extension, $allowed_extensions)) {
json_error('Invalid file format. Please upload PDF, DOC, or DOCX');
}
if ($cv_file['size'] > 10 * 1024 * 1024) { // 10MB limit
json_error('File size exceeds 10MB limit');
}
// Generate filename
$cv_filename = $unique_id . '.' . $file_extension;
$cv_path = $upload_dir . '/' . $cv_filename;
// Move uploaded file
if (!move_uploaded_file($cv_file['tmp_name'], $cv_path)) {
json_error('Failed to upload file');
}
// Extract text from CV
$cv_text = extractTextFromCV($cv_path, $file_extension);
// Clean up uploaded file
@unlink($cv_path);
}
// Validate extracted/pasted text
$cv_text_cleaned = trim($cv_text);
if (empty($cv_text_cleaned) || strlen($cv_text_cleaned) < 50) {
// Only show file-specific error if they uploaded a file
if (!empty($_POST['cv_text'])) {
json_error('The pasted CV text is too short. Please paste your complete CV (at least 50 characters).');
}
// File extraction error
$error_msg = 'Could not extract readable text from your CV. ';
if (isset($file_extension)) {
if ($file_extension === 'pdf') {
$error_msg .= 'The PDF may be scanned/image-based or protected. Please try: ';
$error_msg .= '1) Click "Paste Text" tab above and copy-paste your CV content, or 2) Save as DOCX and try again.';
} elseif ($file_extension === 'doc') {
$error_msg .= 'Old DOC format may have compatibility issues. Please try: ';
$error_msg .= '1) Click "Paste Text" tab and paste your CV, or 2) Save as DOCX.';
} else {
$error_msg .= 'Click "Paste Text" tab above and paste your CV content instead.';
}
}
json_error($error_msg);
}
// Get job details
$target_job = htmlspecialchars(trim($_POST['target_job']));
$job_description = !empty($_POST['job_description']) ? htmlspecialchars(trim($_POST['job_description'])) : '';
// Generate revamped CV using AI
$revamped_cv = generateRevampedCV($cv_text_cleaned, $target_job, $job_description);
if (!$revamped_cv) {
json_error('Failed to generate revamped CV. Please try again.');
}
// Save revamped CV as PDF (or TXT if TCPDF unavailable)
$file_extension = class_exists('TCPDF') ? 'pdf' : 'txt';
$output_filename = 'revamped_cv_' . $unique_id . '.' . $file_extension;
$output_path = $upload_dir . '/' . $output_filename;
// Generate PDF using TCPDF
$pdf_created = createPDF($revamped_cv, $output_path, $target_job, $email);
if (!$pdf_created) {
json_error('Failed to create PDF. The revamped content has been generated but could not be saved.');
}
// Save metadata
$metadata = [
'id' => $unique_id,
'email' => $email,
'target_job' => $target_job,
'job_description' => $job_description,
'original_cv' => isset($cv_file['name']) ? $cv_file['name'] : 'pasted_text',
'timestamp' => date('Y-m-d H:i:s'),
'output_file' => $output_filename
];
file_put_contents($upload_dir . '/metadata_' . $unique_id . '.json', json_encode($metadata, JSON_PRETTY_PRINT));
// Send email with revamped CV
sendRevampedCVEmail($email, $output_path, $target_job);
// Return success response
$message = class_exists('TCPDF')
? 'Your CV has been revamped successfully! Check your email for the PDF download link.'
: 'Your CV has been revamped successfully! Download link ready (Note: Install TCPDF for PDF format).';
ob_clean(); // Clear any output buffer before sending JSON
echo json_encode([
'success' => true,
'message' => $message,
'download_url' => 'download_file.php?file=' . urlencode($output_filename) . '&type=cv',
'file_type' => $file_extension
]);
/**
* Extract text from CV file
*/
function extractTextFromCV($filepath, $extension) {
$text = '';
$extraction_method = '';
if ($extension === 'pdf') {
// Method 1: Try PDF parser library if available
if (class_exists('Smalot\PdfParser\Parser')) {
try {
$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile($filepath);
$text = $pdf->getText();
$extraction_method = 'PDF Parser Library';
if (!empty(trim($text))) {
error_log("CV extraction successful using: $extraction_method");
}
} catch (Exception $e) {
error_log('PDF parsing error: ' . $e->getMessage());
$text = '';
}
}
// Method 2: Try pdftotext command if library failed
if (empty(trim($text))) {
$output = @shell_exec("pdftotext " . escapeshellarg($filepath) . " - 2>&1");
if (!empty($output) &&
strpos($output, 'not recognized') === false &&
strpos($output, 'not found') === false &&
strpos($output, 'command not found') === false) {
$text = $output;
$extraction_method = 'pdftotext command';
error_log("CV extraction successful using: $extraction_method");
}
}
// Method 3: Manual extraction from raw PDF
if (empty(trim($text))) {
$raw = file_get_contents($filepath);
$text = extractReadableTextFromPDF($raw);
$extraction_method = 'Manual PDF extraction';
if (!empty(trim($text))) {
error_log("CV extraction successful using: $extraction_method");
}
}
} elseif ($extension === 'docx') {
// Extract from DOCX (ZIP archive with XML)
if (class_exists('ZipArchive')) {
$zip = new ZipArchive();
if ($zip->open($filepath) === true) {
$xml = $zip->getFromName('word/document.xml');
$zip->close();
if ($xml) {
$xml_obj = @simplexml_load_string($xml);
if ($xml_obj) {
$text = strip_tags($xml_obj->asXML());
$extraction_method = 'DOCX XML extraction';
error_log("CV extraction successful using: $extraction_method");
}
}
}
}
} elseif ($extension === 'doc') {
// For old DOC files, try antiword first
$output = @shell_exec("antiword " . escapeshellarg($filepath) . " 2>&1");
if (!empty($output) &&
strpos($output, 'not recognized') === false &&
strpos($output, 'not found') === false) {
$text = $output;
$extraction_method = 'antiword command';
error_log("CV extraction successful using: $extraction_method");
}
// Fallback: extract readable text from binary DOC
if (empty(trim($text))) {
$raw = file_get_contents($filepath);
$text = extractReadableText($raw);
$extraction_method = 'Manual DOC extraction';
if (!empty(trim($text))) {
error_log("CV extraction successful using: $extraction_method");
}
}
}
// Clean up the extracted text
if (!empty($text)) {
$text = cleanExtractedText($text);
$cleaned_length = strlen(trim($text));
error_log("Final cleaned text length: $cleaned_length characters");
if ($cleaned_length < 50) {
error_log("Warning: Extracted text is very short ($cleaned_length chars)");
}
} else {
error_log("Error: No text could be extracted from CV file: $filepath (extension: $extension)");
}
return trim($text);
}
/**
* Extract readable text from raw PDF content
*/
function extractReadableTextFromPDF($raw_content) {
$text = '';
// Method 1: Extract text between BT (Begin Text) and ET (End Text) markers
if (preg_match_all('/BT\s+(.*?)\s+ET/s', $raw_content, $matches)) {
foreach ($matches[1] as $text_block) {
// Extract text from Tj operators
if (preg_match_all('/\((.*?)\)\s*Tj/s', $text_block, $text_matches)) {
foreach ($text_matches[1] as $line) {
$text .= $line . "\n";
}
}
// Extract text from TJ operators (array)
if (preg_match_all('/\[(.*?)\]\s*TJ/s', $text_block, $array_matches)) {
foreach ($array_matches[1] as $array_content) {
if (preg_match_all('/\((.*?)\)/', $array_content, $array_text)) {
$text .= implode(' ', $array_text[1]) . "\n";
}
}
}
}
}
// Method 2: If no text found, extract all printable text
if (empty(trim($text))) {
// Remove binary chunks and keep readable text
$text = preg_replace('/stream[\r\n]+.*?endstream/s', '', $raw_content);
$text = preg_replace('/<<[^>]*>>/', '', $text);
$text = preg_replace('/\d+ \d+ obj/', '', $text);
$text = preg_replace('/endobj/', '', $text);
$text = preg_replace('/[^\x20-\x7E\n\r]/', ' ', $text);
}
return $text;
}
/**
* Extract readable text from any binary format
*/
function extractReadableText($content) {
// Remove common binary patterns
$content = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\xFF]/', ' ', $content);
// Keep only printable ASCII and newlines
$content = preg_replace('/[^\x20-\x7E\n\r]/', '', $content);
return $content;
}
/**
* Clean extracted text from PDF artifacts
*/
function cleanExtractedText($text) {
// Remove PDF object markers
$text = preg_replace('/\d+\s+\d+\s+obj\s*/', '', $text);
$text = preg_replace('/endobj\s*/', '', $text);
$text = preg_replace('/endstream\s*/', '', $text);
$text = preg_replace('/stream\s*/', '', $text);
// Remove PDF dictionary markers
$text = preg_replace('/<</s', '', $text);
$text = preg_replace('/>>/s', '', $text);
// Remove PDF operators and references
$text = preg_replace('/\/[A-Z][a-zA-Z0-9]*/', '', $text);
$text = preg_replace('/\d+\s+\d+\s+R/', '', $text);
// Remove encoding artifacts
$text = preg_replace('/\/Filter.*?Length\s+\d+/', '', $text);
$text = preg_replace('/\/FlateDecode/', '', $text);
// Clean up whitespace
$text = preg_replace('/[ \t]+/', ' ', $text);
$text = preg_replace('/\n\s*\n\s*\n+/', "\n\n", $text);
// Remove lines that are just numbers or single characters
$lines = explode("\n", $text);
$cleaned_lines = [];
foreach ($lines as $line) {
$line = trim($line);
if (strlen($line) > 2 && !preg_match('/^[\d\s]+$/', $line)) {
$cleaned_lines[] = $line;
}
}
return implode("\n", $cleaned_lines);
}
/**
* Generate revamped CV using AI with strict constraints
*/
function generateRevampedCV($cv_text, $target_job, $job_description) {
// AI API configuration
$api_key = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : getenv('OPENAI_API_KEY');
$use_ai = defined('ENABLE_AI_PROCESSING') ? ENABLE_AI_PROCESSING : true;
if (!$use_ai || empty($api_key) || $api_key === 'your-api-key-here') {
// Fallback to rule-based revamp if no API key
return ruleBasedRevamp($cv_text, $target_job, $job_description);
}
// Build strict prompt
$prompt = buildRevampPrompt($cv_text, $target_job, $job_description);
// Call AI API
$api_endpoint = defined('OPENAI_ENDPOINT') ? OPENAI_ENDPOINT : 'https://api.openai.com/v1/chat/completions';
$model = defined('OPENAI_MODEL') ? OPENAI_MODEL : 'gpt-4';
$temperature = defined('CV_TEMPERATURE') ? CV_TEMPERATURE : 0.3;
$max_tokens = defined('CV_MAX_TOKENS') ? CV_MAX_TOKENS : 2000;
$ch = curl_init($api_endpoint);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'messages' => [
[
'role' => 'system',
'content' => 'You are an HR Career Expert and Selection Panel Assessor. Rewrite resumes to align perfectly with the target job description. Use ONLY facts from the provided resume; never fabricate. Optimize for ATS with JD keywords, highlight measurable impact and leadership, and keep a human, natural tone that passes AI detection. Ensure clear ATS-friendly structure and formatting.'
],
[
'role' => 'user',
'content' => $prompt
]
],
'temperature' => $temperature,
'max_tokens' => $max_tokens
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code !== 200) {
return ruleBasedRevamp($cv_text, $target_job, $job_description);
}
$data = json_decode($response, true);
return $data['choices'][0]['message']['content'] ?? null;
}
/**
* Build AI prompt with strict no-hallucination constraints
*/
function buildRevampPrompt($cv_text, $target_job, $job_description) {
$jd_section = !empty($job_description)
? "\n\nTarget Job Description (use for keywords/criteria):\n$job_description\n"
: "";
return <<<PROMPT
Act as an HR Career Expert and Selection Panel Assessor. Rewrite the enclosed resume so it aligns perfectly with the $target_job role.
CORE RULES (NON-NEGOTIABLE):
1) Fact-Based Only: use ONLY information in the resume. No fabrication. If criteria are missing, surface transferable skills from real roles.
2) ATS Compliance: weave in keywords/phrases from the job description naturally; use ATS-friendly headings, bullets, and consistent formatting.
3) High-Impact Presentation: position candidate as high-achieving corporate asset; emphasize measurable outcomes (KPI %, cost/time savings, efficiency gains, revenue/quality improvements, leadership impact).
4) Alignment to Job Description: map experience and skills to essential/desirable criteria; emphasize relevant tech/skills/achievements; show adaptability via transferable skills where gaps exist.
5) Humanized & Professional Tone: natural, authentic voice that passes AI detection; avoid robotic phrasing or generic buzzwords; clear and concise.
6) Do NOT change dates/company names or add new roles.
LENGTH REQUIREMENTS:
- Target: 2 pages maximum for roles with 5-10 years experience
- Target: 1.5-2 pages for roles with 3-5 years experience
- If CV is currently too long: consolidate older/less relevant roles
- If CV is currently too short: expand recent roles with more detail on impact
- Professional summary: maximum 4 lines
KEYWORD INTEGRATION RULES:
- Extract specific skills/tools from job description
- Integrate keywords ONLY where genuinely applicable to their experience
- Never fabricate experience to include keywords
- Prioritize keywords that appear in BOTH job description and original CV
- Place critical keywords in: Professional Summary, Core Competencies, and relevant role descriptions
- Avoid: keyword stuffing, unnatural phrasing, claiming skills not demonstrated
HANDLING GAPS & MISSING INFO:
- If job description is missing/vague: optimize for general industry roles
- If CV lacks quantified achievements: infer reasonable impact from tasks described
Example: "Managed stakeholder meetings" → "Facilitated weekly stakeholder alignment sessions across 5 departments, improving project visibility and decision-making speed"
- If specific tools mentioned but no context: add brief context without fabricating
- If dates/companies unclear: flag this in output for user to clarify
ATS OPTIMIZATION STANDARDS:
- Use standard section headers: "Professional Experience" not "Where I've Worked"
- Avoid tables, text boxes, headers/footers, graphics
- Use simple bullet points (•) not custom symbols
- Spell out acronyms on first use, then use acronym: "Business Analysis (BA)"
- Include both spelled-out and acronym versions of key skills
- Date format: Month Year - Month Year (e.g., "Jan 2018 - Dec 2022")
- No pronouns (I, me, my) in bullet points
- Each role must have 6-8 achievement-focused bullet points
- Start each bullet with strong action verb (Led, Delivered, Implemented, Transformed, etc.)
- Include metrics in at least 70% of bullets
FINAL VERIFICATION CHECKLIST (AI must self-check before outputting):
☐ Every quantified metric from original CV is present (£, %, timeframes)
☐ All specific tool/technology names preserved
☐ No bullet point is more generic than original
☐ At least 70% of bullets include quantified results
☐ Each role shows progression/increasing responsibility
☐ Professional summary mentions target role and top 3 value propositions
☐ No fabricated achievements or exaggerated claims
☐ Tone is confident but credible
ERROR HANDLING GUIDELINES:
If CV quality is extremely poor (no achievements, all generic tasks):
1. Flag this to user: "This CV needs significant strengthening beyond formatting"
2. Still attempt revamp but note: "Recommend adding specific metrics and results"
3. Suggest what information is missing
If CV is not in English:
- Return error: "Please provide CV in English"
If job description contradicts CV experience level:
- Flag mismatch but optimize for job description requirements
OUTPUT FORMAT REQUIREMENTS:
- Return ONLY the revamped CV content, no explanations or commentary
- Use this exact structure: Professional Summary (3-4 lines), Core Competencies (bullet points), Professional Experience (reverse chronological), Education, Certifications (if applicable)
- Start each bullet with strong action verb (Led, Delivered, Implemented, etc.)
- Include metrics in at least 70% of bullets
- Do NOT add generic skills claims without proof
LENGTH REQUIREMENTS:
- Target: 2 pages maximum for 5-10 years experience; 1.5-2 pages for 3-5 years experience
- If CV is too long: consolidate older/less relevant roles
- If CV is too short: expand recent roles with more detail on impact
- Professional summary: maximum 4 lines
KEYWORD INTEGRATION:
- Extract specific skills/tools from job description
- Integrate keywords ONLY where genuinely applicable to their experience
- Never fabricate experience to include keywords
- Prioritize keywords that appear in BOTH job description and original CV
- Place critical keywords in: Professional Summary, Core Competencies, and relevant role descriptions
- Avoid: keyword stuffing, unnatural phrasing, claiming skills not demonstrated
HANDLING GAPS:
- If job description is missing/vague: optimize for general industry roles
- If CV lacks quantified achievements: infer reasonable impact from tasks described (e.g., "Managed stakeholder meetings" → "Facilitated weekly stakeholder alignment sessions across 5 departments, improving project visibility")
- If specific tools mentioned but no context: add brief context without fabricating
- If dates/companies unclear: flag this in output for user to clarify
ATS OPTIMIZATION:
- Use standard section headers: "Professional Experience" not "Where I've Worked"
- Avoid tables, text boxes, headers/footers, graphics
- Use simple bullet points (•) not custom symbols
- Spell out acronyms on first use, then use acronym: "Business Analysis (BA)"
- Date format: Month Year - Month Year (e.g., "Jan 2018 - Dec 2022")
- No pronouns (I, me, my) in bullet points
FINAL VERIFICATION CHECKLIST (AI must self-check before outputting):
☐ Every quantified metric from original CV is present (£, %, timeframes)
☐ All specific tool/technology names preserved
☐ No bullet point is more generic than original
☐ At least 70% of bullets include quantified results
☐ Each role shows progression/increasing responsibility
☐ Professional summary mentions target role and top 3 value propositions
☐ No fabricated achievements or exaggerated claims
☐ Tone is confident but credible
ERROR HANDLING:
- If CV quality is extremely poor: Flag "This CV needs significant strengthening beyond formatting" and still attempt revamp with note "Recommend adding specific metrics and results"
- If CV is not in English: Return error "Please provide CV in English"
- If job description contradicts CV experience level: Flag mismatch but optimize for job description requirements
Original Resume (source of truth):
$cv_text
$jd_section
Output: A polished, ATS-optimized resume that aligns with the job description, highlights measurable impact, sounds human and professional, and positions the candidate as a top-tier applicant. Return ONLY the CV content with no additional commentary.
PROMPT;
}
/**
* Rule-based revamp (fallback when AI is unavailable)
*/
function ruleBasedRevamp($cv_text, $target_job, $job_description) {
// Extract key sections
$sections = extractCVSections($cv_text);
// Build revamped content
$output = "RESUME - " . strtoupper($target_job) . "\n\n";
// Professional summary
$output .= "PROFESSIONAL SUMMARY\n";
$output .= "Experienced professional seeking a position as $target_job. ";
$output .= "Proven track record in delivering results through effective collaboration and problem-solving.\n\n";
// Experience
if (!empty($sections['experience'])) {
$output .= "PROFESSIONAL EXPERIENCE\n";
$output .= $sections['experience'] . "\n\n";
}
// Education
if (!empty($sections['education'])) {
$output .= "EDUCATION\n";
$output .= $sections['education'] . "\n\n";
}
// Skills
if (!empty($sections['skills'])) {
$output .= "CORE COMPETENCIES\n";
$output .= $sections['skills'] . "\n\n";
}
return $output;
}
/**
* Extract CV sections using basic pattern matching
*/
function extractCVSections($text) {
$sections = [
'experience' => '',
'education' => '',
'skills' => ''
];
// Basic section extraction (enhance with better parsing)
if (preg_match('/experience(.+?)(?=education|skills|$)/is', $text, $matches)) {
$sections['experience'] = trim($matches[1]);
}
if (preg_match('/education(.+?)(?=experience|skills|$)/is', $text, $matches)) {
$sections['education'] = trim($matches[1]);
}
if (preg_match('/skills(.+?)(?=experience|education|$)/is', $text, $matches)) {
$sections['skills'] = trim($matches[1]);
}
return $sections;
}
/**
* Create PDF from revamped CV using TCPDF
*/
function createPDF($content, $output_path, $title, $contact_email = '') {
// Check if TCPDF is available
if (!class_exists('TCPDF')) {
// Fallback to simple text file if TCPDF not installed
return file_put_contents($output_path, $content) !== false;
}
try {
// Create new PDF document
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
// Set document information
$pdf->SetCreator('Chronus Career Services');
$pdf->SetAuthor('Chronus Solutions');
$pdf->SetTitle('Revamped CV');
$pdf->SetSubject('Professional Resume');
// Remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// Set margins
$pdf->SetMargins(20, 20, 20);
$pdf->SetAutoPageBreak(true, 20);
// Add a page
$pdf->AddPage();
// Convert plain text CV to formatted HTML
$html = formatCVtoHTML($content, $contact_email);
// Write content
$pdf->writeHTML($html, true, false, true, false, '');
// Output PDF to file
$pdf->Output($output_path, 'F');
return file_exists($output_path);
} catch (Exception $e) {
error_log('PDF generation error: ' . $e->getMessage());
// Fallback to text file
return file_put_contents($output_path, $content) !== false;
}
}
/**
* Format CV text content into professional HTML for PDF
*/
function formatCVtoHTML($content, $contact_email = '') {
// Clean content one more time before formatting
$content = finalCleanContent($content);
// Parse the content into sections
$lines = explode("\n", $content);
$html = '<style>
body { font-family: helvetica, sans-serif; color: #333; }
h1 {
font-size: 22pt;
color: #1a1a1a;
font-weight: bold;
margin: 0 0 5px 0;
padding: 0;
text-transform: uppercase;
letter-spacing: 1px;
}
.contact {
font-size: 10pt;
color: #666;
margin: 0 0 20px 0;
padding: 0 0 10px 0;
border-bottom: 2px solid #2c3e50;
}
h2 {
font-size: 13pt;
color: #2c3e50;
font-weight: bold;
margin: 15px 0 8px 0;
padding: 5px 0 3px 0;
border-bottom: 2px solid #95cf4a;
text-transform: uppercase;
letter-spacing: 0.5px;
}
h3 {
font-size: 11pt;
color: #444;
font-weight: bold;
margin: 10px 0 5px 0;
}
p {
font-size: 10pt;
line-height: 1.5;
margin: 0 0 8px 0;
text-align: justify;
}
ul {
margin: 5px 0 10px 15px;
padding: 0;
list-style-type: disc;
}
li {
font-size: 10pt;
line-height: 1.4;
margin-bottom: 4px;
}
.section-content {
margin-bottom: 10px;
}
</style>';
$current_section = '';
$section_content = '';
$name_found = false;
foreach ($lines as $line) {
$line = trim($line);
// Skip empty lines and PDF artifacts
if (empty($line) || isPDFArtifact($line)) continue;
// Skip lines that look like PDF code
if (strlen($line) < 3 || preg_match('/^[\d\s]+$/', $line)) continue;
// Detect name (first meaningful line, usually all caps or title case)
if (!$name_found && strlen($line) > 3 && !preg_match('/^(RESUME|CV|CURRICULUM)/i', $line)) {
$html .= '<h1>' . htmlspecialchars($line) . '</h1>';
if (!empty($contact_email)) {
$html .= '<div class="contact">' . htmlspecialchars($contact_email) . '</div>';
}
$name_found = true;
continue;
}
// Detect section headers (all caps, common CV sections)
if (preg_match('/^(PROFESSIONAL SUMMARY|SUMMARY|EXPERIENCE|PROFESSIONAL EXPERIENCE|EDUCATION|SKILLS|CORE COMPETENCIES|CERTIFICATIONS|ACHIEVEMENTS|PROJECTS)$/i', $line)) {
// Close previous section
if (!empty($section_content)) {
$html .= '<div class="section-content">' . $section_content . '</div>';
$section_content = '';
}
// Start new section
$html .= '<h2>' . htmlspecialchars($line) . '</h2>';
$current_section = $line;
continue;
}
// Detect job titles or subsection headers (contains dates, or bold-worthy)
if (preg_match('/\d{4}|\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\b|Present/i', $line) &&
strlen($line) < 100) {
$section_content .= '<h3>' . htmlspecialchars($line) . '</h3>';
continue;
}
// Detect bullet points
if (preg_match('/^[-•*·]\s*/', $line)) {
$line = preg_replace('/^[-•*·]\s*/', '', $line);
$section_content .= '<ul><li>' . htmlspecialchars($line) . '</li></ul>';
continue;
}
// Regular paragraph
$section_content .= '<p>' . htmlspecialchars($line) . '</p>';
}
// Add last section
if (!empty($section_content)) {
$html .= '<div class="section-content">' . $section_content . '</div>';
}
return $html;
}
/**
* Check if a line is a PDF artifact that should be filtered out
*/
function isPDFArtifact($line) {
// Check for common PDF internal markers
$pdf_patterns = [
'/^endobj$/i',
'/^\d+\s+\d+\s+obj$/i',
'/^stream$/i',
'/^endstream$/i',
'/^<</',
'/>>$/',
'/^\/[A-Z]/i', // PDF operators like /Filter, /Type, etc.
'/^\d+\s+\d+\s+R$/', // References like "55 0 R"
'/Parent\s+\d+\s+\d+\s+R/i',
'/\/Dest\[/i',
'/\/Title\(/i',
'/\/Count\s+-?\d+/i',
'/\/First\s+\d+/i',
'/\/Last\s+\d+/i',
'/\/Next\s+\d+/i',
'/\/Prev\s+\d+/i',
'/\/XYZ\s+\d+/i',
'/FlateDecode/i',
'/Length\s+\d+/i'
];
foreach ($pdf_patterns as $pattern) {
if (preg_match($pattern, $line)) {
return true;
}
}
// Check if line is mostly non-alphanumeric (binary garbage)
$alphanumeric = preg_replace('/[^a-zA-Z0-9]/', '', $line);
if (strlen($line) > 10 && strlen($alphanumeric) < strlen($line) * 0.3) {
return true;
}
return false;
}
/**
* Final cleaning pass on content before PDF generation
*/
function finalCleanContent($content) {
$lines = explode("\n", $content);
$cleaned = [];
foreach ($lines as $line) {
$line = trim($line);
// Skip empty lines
if (empty($line)) continue;
// Skip PDF artifacts
if (isPDFArtifact($line)) continue;
// Skip lines that are just numbers or single chars
if (strlen($line) < 3) continue;
// Skip lines with suspicious patterns
if (preg_match('/^[\d\s]+$/', $line)) continue;
if (preg_match('/^[^a-zA-Z]+$/', $line) && strlen($line) < 20) continue;
$cleaned[] = $line;
}
return implode("\n", $cleaned);
}
/**
* Send email with revamped CV using PHPMailer
*/
function sendRevampedCVEmail($email, $cv_path, $target_job) {
// Check if email is enabled
$email_enabled = defined('EMAIL_ENABLED') ? EMAIL_ENABLED : false;
if (!$email_enabled) {
return true; // Skip email if not configured
}
try {
$mail = new PHPMailer(true);
// Server settings
$mail->isSMTP();
$mail->Host = defined('SMTP_HOST') ? SMTP_HOST : 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = defined('SMTP_USERNAME') ? SMTP_USERNAME : '';
$mail->Password = defined('SMTP_PASSWORD') ? SMTP_PASSWORD : '';
$mail->SMTPSecure = defined('SMTP_ENCRYPTION') ? SMTP_ENCRYPTION : 'tls';
$mail->Port = defined('SMTP_PORT') ? SMTP_PORT : 587;
// Recipients
$from_email = defined('FROM_EMAIL') ? FROM_EMAIL : 'noreply@chronus.com';
$from_name = defined('FROM_NAME') ? FROM_NAME : 'Chronus Career Services';
$mail->setFrom($from_email, $from_name);
$mail->addAddress($email);
// Attachment
if (file_exists($cv_path)) {
$mail->addAttachment($cv_path, 'Revamped_CV.pdf');
}
// Content
$mail->isHTML(true);
$mail->Subject = "Your Revamped CV for $target_job Position";
$mail->Body = "
<html>
<body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
<div style='max-width: 600px; margin: 0 auto; padding: 20px;'>
<h2 style='color: #9acd32;'>Your CV Has Been Revamped!</h2>
<p>Great news! Your CV has been professionally revamped and optimized for <strong>$target_job</strong> positions.</p>
<div style='background: #f9f9f9; padding: 15px; border-left: 4px solid #9acd32; margin: 20px 0;'>
<h3 style='margin-top: 0; color: #2c3e50;'>What We've Enhanced:</h3>
<ul>
<li>ATS-optimized formatting</li>
<li>Achievement-focused bullet points</li>
<li>Transferable skills highlighted</li>
<li>Industry-specific keywords</li>
</ul>
</div>
<p>Your revamped CV is attached to this email. Download it and start applying with confidence!</p>
<p style='margin-top: 30px;'>Best regards,<br><strong>Chronus Career Services</strong></p>
<hr style='border: none; border-top: 1px solid #ddd; margin: 20px 0;'>
<p style='font-size: 12px; color: #999;'>This is an automated message. Please do not reply directly to this email.</p>
</div>
</body>
</html>
";
$mail->AltBody = "Your CV has been revamped and optimized for $target_job positions. Please find your revamped CV attached.\n\nBest regards,\nChronus Career Services";
$mail->send();
return true;
} catch (Exception $e) {
error_log('Email sending failed: ' . $mail->ErrorInfo);
return false; // Don't fail the whole process if email fails
}
}